Loader.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. <?php
  2. namespace Doctrine\Common\DataFixtures;
  3. use Doctrine\Common\DataFixtures\Exception\CircularReferenceException;
  4. /**
  5. * Class responsible for loading data fixture classes.
  6. *
  7. * @author Jonathan H. Wage <jonwage@gmail.com>
  8. */
  9. class Loader
  10. {
  11. /**
  12. * Array of fixture object instances to execute.
  13. *
  14. * @var array
  15. */
  16. private $fixtures = [];
  17. /**
  18. * Array of ordered fixture object instances.
  19. *
  20. * @var array
  21. */
  22. private $orderedFixtures = [];
  23. /**
  24. * Determines if we must order fixtures by number
  25. *
  26. * @var boolean
  27. */
  28. private $orderFixturesByNumber = false;
  29. /**
  30. * Determines if we must order fixtures by its dependencies
  31. *
  32. * @var boolean
  33. */
  34. private $orderFixturesByDependencies = false;
  35. /**
  36. * The file extension of fixture files.
  37. *
  38. * @var string
  39. */
  40. private $fileExtension = '.php';
  41. /**
  42. * Find fixtures classes in a given directory and load them.
  43. *
  44. * @param string $dir Directory to find fixture classes in.
  45. * @return array $fixtures Array of loaded fixture object instances.
  46. */
  47. public function loadFromDirectory($dir)
  48. {
  49. if (!is_dir($dir)) {
  50. throw new \InvalidArgumentException(sprintf('"%s" does not exist', $dir));
  51. }
  52. $iterator = new \RecursiveIteratorIterator(
  53. new \RecursiveDirectoryIterator($dir),
  54. \RecursiveIteratorIterator::LEAVES_ONLY
  55. );
  56. return $this->loadFromIterator($iterator);
  57. }
  58. /**
  59. * Find fixtures classes in a given file and load them.
  60. *
  61. * @param string $fileName File to find fixture classes in.
  62. * @return array $fixtures Array of loaded fixture object instances.
  63. */
  64. public function loadFromFile($fileName)
  65. {
  66. if (!is_readable($fileName)) {
  67. throw new \InvalidArgumentException(sprintf('"%s" does not exist or is not readable', $fileName));
  68. }
  69. $iterator = new \ArrayIterator([new \SplFileInfo($fileName)]);
  70. return $this->loadFromIterator($iterator);
  71. }
  72. /**
  73. * Has fixture?
  74. *
  75. * @param FixtureInterface $fixture
  76. *
  77. * @return boolean
  78. */
  79. public function hasFixture($fixture)
  80. {
  81. return isset($this->fixtures[get_class($fixture)]);
  82. }
  83. /**
  84. * Get a specific fixture instance
  85. *
  86. * @param string $className
  87. * @return FixtureInterface
  88. */
  89. public function getFixture($className)
  90. {
  91. if (!isset($this->fixtures[$className])) {
  92. throw new \InvalidArgumentException(sprintf(
  93. '"%s" is not a registered fixture',
  94. $className
  95. ));
  96. }
  97. return $this->fixtures[$className];
  98. }
  99. /**
  100. * Add a fixture object instance to the loader.
  101. *
  102. * @param FixtureInterface $fixture
  103. */
  104. public function addFixture(FixtureInterface $fixture)
  105. {
  106. $fixtureClass = get_class($fixture);
  107. if (!isset($this->fixtures[$fixtureClass])) {
  108. if ($fixture instanceof OrderedFixtureInterface && $fixture instanceof DependentFixtureInterface) {
  109. throw new \InvalidArgumentException(sprintf('Class "%s" can\'t implement "%s" and "%s" at the same time.',
  110. get_class($fixture),
  111. 'OrderedFixtureInterface',
  112. 'DependentFixtureInterface'));
  113. }
  114. $this->fixtures[$fixtureClass] = $fixture;
  115. if ($fixture instanceof OrderedFixtureInterface) {
  116. $this->orderFixturesByNumber = true;
  117. } elseif ($fixture instanceof DependentFixtureInterface) {
  118. $this->orderFixturesByDependencies = true;
  119. foreach($fixture->getDependencies() as $class) {
  120. if (class_exists($class)) {
  121. $this->addFixture($this->createFixture($class));
  122. }
  123. }
  124. }
  125. }
  126. }
  127. /**
  128. * Returns the array of data fixtures to execute.
  129. *
  130. * @return array $fixtures
  131. */
  132. public function getFixtures()
  133. {
  134. $this->orderedFixtures = [];
  135. if ($this->orderFixturesByNumber) {
  136. $this->orderFixturesByNumber();
  137. }
  138. if ($this->orderFixturesByDependencies) {
  139. $this->orderFixturesByDependencies();
  140. }
  141. if (!$this->orderFixturesByNumber && !$this->orderFixturesByDependencies) {
  142. $this->orderedFixtures = $this->fixtures;
  143. }
  144. return $this->orderedFixtures;
  145. }
  146. /**
  147. * Check if a given fixture is transient and should not be considered a data fixtures
  148. * class.
  149. *
  150. * @return boolean
  151. */
  152. public function isTransient($className)
  153. {
  154. $rc = new \ReflectionClass($className);
  155. if ($rc->isAbstract()) return true;
  156. $interfaces = class_implements($className);
  157. return in_array(FixtureInterface::class, $interfaces) ? false : true;
  158. }
  159. /**
  160. * Creates the fixture object from the class.
  161. *
  162. * @param string $class
  163. * @return FixtureInterface
  164. */
  165. protected function createFixture($class)
  166. {
  167. return new $class();
  168. }
  169. /**
  170. * Orders fixtures by number
  171. *
  172. * @todo maybe there is a better way to handle reordering
  173. * @return void
  174. */
  175. private function orderFixturesByNumber()
  176. {
  177. $this->orderedFixtures = $this->fixtures;
  178. usort($this->orderedFixtures, function($a, $b) {
  179. if ($a instanceof OrderedFixtureInterface && $b instanceof OrderedFixtureInterface) {
  180. if ($a->getOrder() === $b->getOrder()) {
  181. return 0;
  182. }
  183. return $a->getOrder() < $b->getOrder() ? -1 : 1;
  184. } elseif ($a instanceof OrderedFixtureInterface) {
  185. return $a->getOrder() === 0 ? 0 : 1;
  186. } elseif ($b instanceof OrderedFixtureInterface) {
  187. return $b->getOrder() === 0 ? 0 : -1;
  188. }
  189. return 0;
  190. });
  191. }
  192. /**
  193. * Orders fixtures by dependencies
  194. *
  195. * @return void
  196. */
  197. private function orderFixturesByDependencies()
  198. {
  199. $sequenceForClasses = [];
  200. // If fixtures were already ordered by number then we need
  201. // to remove classes which are not instances of OrderedFixtureInterface
  202. // in case fixtures implementing DependentFixtureInterface exist.
  203. // This is because, in that case, the method orderFixturesByDependencies
  204. // will handle all fixtures which are not instances of
  205. // OrderedFixtureInterface
  206. if ($this->orderFixturesByNumber) {
  207. $count = count($this->orderedFixtures);
  208. for ($i = 0 ; $i < $count ; ++$i) {
  209. if (!($this->orderedFixtures[$i] instanceof OrderedFixtureInterface)) {
  210. unset($this->orderedFixtures[$i]);
  211. }
  212. }
  213. }
  214. // First we determine which classes has dependencies and which don't
  215. foreach ($this->fixtures as $fixture) {
  216. $fixtureClass = get_class($fixture);
  217. if ($fixture instanceof OrderedFixtureInterface) {
  218. continue;
  219. } elseif ($fixture instanceof DependentFixtureInterface) {
  220. $dependenciesClasses = $fixture->getDependencies();
  221. $this->validateDependencies($dependenciesClasses);
  222. if (!is_array($dependenciesClasses) || empty($dependenciesClasses)) {
  223. throw new \InvalidArgumentException(sprintf('Method "%s" in class "%s" must return an array of classes which are dependencies for the fixture, and it must be NOT empty.', 'getDependencies', $fixtureClass));
  224. }
  225. if (in_array($fixtureClass, $dependenciesClasses)) {
  226. throw new \InvalidArgumentException(sprintf('Class "%s" can\'t have itself as a dependency', $fixtureClass));
  227. }
  228. // We mark this class as unsequenced
  229. $sequenceForClasses[$fixtureClass] = -1;
  230. } else {
  231. // This class has no dependencies, so we assign 0
  232. $sequenceForClasses[$fixtureClass] = 0;
  233. }
  234. }
  235. // Now we order fixtures by sequence
  236. $sequence = 1;
  237. $lastCount = -1;
  238. while (($count = count($unsequencedClasses = $this->getUnsequencedClasses($sequenceForClasses))) > 0 && $count !== $lastCount) {
  239. foreach ($unsequencedClasses as $key => $class) {
  240. $fixture = $this->fixtures[$class];
  241. $dependencies = $fixture->getDependencies();
  242. $unsequencedDependencies = $this->getUnsequencedClasses($sequenceForClasses, $dependencies);
  243. if (count($unsequencedDependencies) === 0) {
  244. $sequenceForClasses[$class] = $sequence++;
  245. }
  246. }
  247. $lastCount = $count;
  248. }
  249. $orderedFixtures = [];
  250. // If there're fixtures unsequenced left and they couldn't be sequenced,
  251. // it means we have a circular reference
  252. if ($count > 0) {
  253. $msg = 'Classes "%s" have produced a CircularReferenceException. ';
  254. $msg .= 'An example of this problem would be the following: Class C has class B as its dependency. ';
  255. $msg .= 'Then, class B has class A has its dependency. Finally, class A has class C as its dependency. ';
  256. $msg .= 'This case would produce a CircularReferenceException.';
  257. throw new CircularReferenceException(sprintf($msg, implode(',', $unsequencedClasses)));
  258. } else {
  259. // We order the classes by sequence
  260. asort($sequenceForClasses);
  261. foreach ($sequenceForClasses as $class => $sequence) {
  262. // If fixtures were ordered
  263. $orderedFixtures[] = $this->fixtures[$class];
  264. }
  265. }
  266. $this->orderedFixtures = array_merge($this->orderedFixtures, $orderedFixtures);
  267. }
  268. private function validateDependencies($dependenciesClasses)
  269. {
  270. $loadedFixtureClasses = array_keys($this->fixtures);
  271. foreach ($dependenciesClasses as $class) {
  272. if (!in_array($class, $loadedFixtureClasses)) {
  273. throw new \RuntimeException(sprintf('Fixture "%s" was declared as a dependency, but it should be added in fixture loader first.', $class));
  274. }
  275. }
  276. return true;
  277. }
  278. private function getUnsequencedClasses($sequences, $classes = null)
  279. {
  280. $unsequencedClasses = [];
  281. if (is_null($classes)) {
  282. $classes = array_keys($sequences);
  283. }
  284. foreach ($classes as $class) {
  285. if ($sequences[$class] === -1) {
  286. $unsequencedClasses[] = $class;
  287. }
  288. }
  289. return $unsequencedClasses;
  290. }
  291. /**
  292. * Load fixtures from files contained in iterator.
  293. *
  294. * @param \Iterator $iterator Iterator over files from which fixtures should be loaded.
  295. * @return array $fixtures Array of loaded fixture object instances.
  296. */
  297. private function loadFromIterator(\Iterator $iterator)
  298. {
  299. $includedFiles = [];
  300. foreach ($iterator as $file) {
  301. if (($fileName = $file->getBasename($this->fileExtension)) == $file->getBasename()) {
  302. continue;
  303. }
  304. $sourceFile = realpath($file->getPathName());
  305. require_once $sourceFile;
  306. $includedFiles[] = $sourceFile;
  307. }
  308. $fixtures = [];
  309. $declared = get_declared_classes();
  310. // Make the declared classes order deterministic
  311. sort($declared);
  312. foreach ($declared as $className) {
  313. $reflClass = new \ReflectionClass($className);
  314. $sourceFile = $reflClass->getFileName();
  315. if (in_array($sourceFile, $includedFiles) && ! $this->isTransient($className)) {
  316. $fixture = $this->createFixture($className);
  317. $fixtures[] = $fixture;
  318. $this->addFixture($fixture);
  319. }
  320. }
  321. return $fixtures;
  322. }
  323. }