pax_global_header00006660000000000000000000000064127702051750014520gustar00rootroot0000000000000052 comment=17fa5bfe6ff52e35cb3d9ec37c934a2f4bd1fa2e data-fixtures-1.2.2/000077500000000000000000000000001277020517500143025ustar00rootroot00000000000000data-fixtures-1.2.2/.gitignore000066400000000000000000000000421277020517500162660ustar00rootroot00000000000000phpunit.xml vendor/ composer.lock data-fixtures-1.2.2/.travis.yml000066400000000000000000000011621277020517500164130ustar00rootroot00000000000000language: php sudo: false cache: directories: - $HOME/.composer/cache php: - 5.6 - 7.0 - nightly - hhvm matrix: allow_failures: - php: nightly services: mongodb before_install: - "if [[ $TRAVIS_PHP_VERSION != 'hhvm' && $TRAVIS_PHP_VERSION != '7.0' ]]; then echo 'extension = mongo.so' >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini; fi" before_script: - composer self-update - composer install --prefer-source - "if [[ $TRAVIS_PHP_VERSION != 'hhvm' && $TRAVIS_PHP_VERSION != '7.0' ]]; then composer require 'doctrine/mongodb-odm' '*@beta'; fi" script: - ./vendor/bin/phpunit -v data-fixtures-1.2.2/LICENSE000066400000000000000000000020521277020517500153060ustar00rootroot00000000000000Copyright (c) 2006-2015 Doctrine Project Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. data-fixtures-1.2.2/README.md000066400000000000000000000120221277020517500155560ustar00rootroot00000000000000# Doctrine Data Fixtures Extension [![Build Status](https://travis-ci.org/doctrine/data-fixtures.png)](https://travis-ci.org/doctrine/data-fixtures) This extension aims to provide a simple way to manage and execute the loading of data fixtures for the [Doctrine ORM or ODM](http://www.doctrine-project.org/). You can write fixture classes by implementing the [`Doctrine\Common\DataFixtures\FixtureInterface`](lib/Doctrine/Common/DataFixtures/FixtureInterface.php) interface: ```php namespace MyDataFixtures; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\FixtureInterface; class UserFixtureLoader implements FixtureInterface { public function load(ObjectManager $manager) { $user = new User(); $user->setUsername('jwage'); $user->setPassword('test'); $manager->persist($user); $manager->flush(); } } ``` Now you can begin adding the fixtures to a loader instance: ```php use Doctrine\Common\DataFixtures\Loader; use MyDataFixtures\LoadUserData; $loader = new Loader(); $loader->addFixture(new LoadUserData()); ``` You can load a set of fixtures from a directory as well: ```php $loader->loadFromDirectory('/path/to/MyDataFixtures'); ``` Or you can load a set of fixtures from a file: $loader->loadFromFile('/path/to/MyDataFixtures/MyFixture1.php'); You can get the added fixtures using the getFixtures() method: ```php $fixtures = $loader->getFixtures(); ``` Now you can easily execute the fixtures: ```php use Doctrine\Common\DataFixtures\Executor\ORMExecutor; use Doctrine\Common\DataFixtures\Purger\ORMPurger; $purger = new ORMPurger(); $executor = new ORMExecutor($em, $purger); $executor->execute($loader->getFixtures()); ``` If you want to append the fixtures instead of purging before loading then pass true to the 2nd argument of execute: ```php $executor->execute($loader->getFixtures(), true); ``` ## Sharing objects between fixtures In case if fixture objects have relations to other fixtures, it is now possible to easily add a reference to that object by name and later reference it to form a relation. Here is an example fixtures for **Role** and **User** relation ```php namespace MyDataFixtures; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\Persistence\ObjectManager; class LoadUserRoleData extends AbstractFixture { public function load(ObjectManager $manager) { $adminRole = new Role(); $adminRole->setName('admin'); $anonymousRole = new Role(); $anonymousRole->setName('anonymous'); $manager->persist($adminRole); $manager->persist($anonymousRole); $manager->flush(); // store reference to admin role for User relation to Role $this->addReference('admin-role', $adminRole); } } ``` And the **User** data loading fixture: ```php namespace MyDataFixtures; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\Persistence\ObjectManager; class LoadUserData extends AbstractFixture { public function load(ObjectManager $manager) { $user = new User(); $user->setUsername('jwage'); $user->setPassword('test'); $user->setRole( $this->getReference('admin-role') // load the stored reference ); $manager->persist($user); $manager->flush(); // store reference of admin-user for other Fixtures $this->addReference('admin-user', $user); } } ``` ## Fixture ordering **Notice** that the fixture loading order is important! To handle it manually implement one of the following interfaces: ### OrderedFixtureInterface Set the order manually: ```php namespace MyDataFixtures; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\Persistence\ObjectManager; class MyFixture extends AbstractFixture implements OrderedFixtureInterface { public function load(ObjectManager $manager) {} public function getOrder() { return 10; // number in which order to load fixtures } } ``` ### DependentFixtureInterface Provide an array of fixture class names: ```php namespace MyDataFixtures; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Doctrine\Common\Persistence\ObjectManager; class MyFixture extends AbstractFixture implements DependentFixtureInterface { public function load(ObjectManager $manager) {} public function getDependencies() { return array('MyDataFixtures\MyOtherFixture'); // fixture classes fixture is dependent on } } class MyOtherFixture extends AbstractFixture { public function load(ObjectManager $manager) {} } ``` **Notice** the ordering is relevant to Loader class. ## Running the tests: PHPUnit 3.5 or newer together with Mock_Object package is required. To setup and run tests follow these steps: - go to the root directory of data-fixtures - run: **composer install --dev** - copy the phpunit config **cp phpunit.xml.dist phpunit.xml** - run: **phpunit** data-fixtures-1.2.2/UPGRADE000066400000000000000000000004371277020517500153200ustar00rootroot00000000000000# Between v1.0.0-ALPHA1 and v1.0.0-ALPHA2 The FixtureInterface was changed from interface FixtureInterface { load($manager); } to use Doctrine\Common\Persistence\ObjectManager; interface FixtureInterface { load(ObjectManager $manager); } data-fixtures-1.2.2/composer.json000066400000000000000000000020571277020517500170300ustar00rootroot00000000000000{ "name": "doctrine/data-fixtures", "type": "library", "description": "Data Fixtures for all Doctrine Object Managers", "keywords": ["database"], "homepage": "http://www.doctrine-project.org", "license": "MIT", "authors": [ {"name": "Jonathan Wage", "email": "jonwage@gmail.com"} ], "require": { "php": "^5.6 || ^7.0", "doctrine/common": "~2.2" }, "require-dev": { "doctrine/orm": "^2.5.4", "doctrine/dbal": "^2.5.4", "phpunit/phpunit": "^5.4.6" }, "conflict": { "doctrine/orm": "< 2.4" }, "suggest": { "doctrine/orm": "For loading ORM fixtures", "doctrine/mongodb-odm": "For loading MongoDB ODM fixtures", "doctrine/phpcr-odm": "For loading PHPCR ODM fixtures" }, "autoload": { "psr-0": { "Doctrine\\Common\\DataFixtures": "lib/" } }, "autoload-dev": { "psr-0": { "Doctrine\\Tests": "tests/" } }, "extra": { "branch-alias": { "dev-master": "1.3.x-dev" } } } data-fixtures-1.2.2/lib/000077500000000000000000000000001277020517500150505ustar00rootroot00000000000000data-fixtures-1.2.2/lib/Doctrine/000077500000000000000000000000001277020517500166175ustar00rootroot00000000000000data-fixtures-1.2.2/lib/Doctrine/Common/000077500000000000000000000000001277020517500200475ustar00rootroot00000000000000data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/000077500000000000000000000000001277020517500224525ustar00rootroot00000000000000data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/AbstractFixture.php000066400000000000000000000065541277020517500263070ustar00rootroot00000000000000. */ namespace Doctrine\Common\DataFixtures; use Doctrine\Common\DataFixtures\ReferenceRepository; /** * Abstract Fixture class helps to manage references * between fixture classes in order to set relations * among other fixtures * * @author Gediminas Morkevicius */ abstract class AbstractFixture implements SharedFixtureInterface { /** * Fixture reference repository * * @var ReferenceRepository */ protected $referenceRepository; /** * {@inheritdoc} */ public function setReferenceRepository(ReferenceRepository $referenceRepository) { $this->referenceRepository = $referenceRepository; } /** * Set the reference entry identified by $name * and referenced to managed $object. If $name * already is set, it overrides it * * @param string $name * @param object $object - managed object * @see Doctrine\Common\DataFixtures\ReferenceRepository::setReference * @return void */ public function setReference($name, $object) { $this->referenceRepository->setReference($name, $object); } /** * Set the reference entry identified by $name * and referenced to managed $object. If $name * already is set, it throws a * BadMethodCallException exception * * @param string $name * @param object $object - managed object * @see Doctrine\Common\DataFixtures\ReferenceRepository::addReference * @throws BadMethodCallException - if repository already has * a reference by $name * @return void */ public function addReference($name, $object) { $this->referenceRepository->addReference($name, $object); } /** * Loads an object using stored reference * named by $name * * @param string $name * @see Doctrine\Common\DataFixtures\ReferenceRepository::getReference * @return object */ public function getReference($name) { return $this->referenceRepository->getReference($name); } /** * Check if an object is stored using reference * named by $name * * @param string $name * @see Doctrine\Common\DataFixtures\ReferenceRepository::hasReference * @return boolean */ public function hasReference($name) { return $this->referenceRepository->hasReference($name); } } data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/DependentFixtureInterface.php000066400000000000000000000026651277020517500302720ustar00rootroot00000000000000. */ namespace Doctrine\Common\DataFixtures; /** * DependentFixtureInterface needs to be implemented * by fixtures which depend on other fixtures * * @author Gustavo Adrian */ interface DependentFixtureInterface { /** * This method must return an array of fixtures classes * on which the implementing class depends on * * @return array */ function getDependencies(); } data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/Event/000077500000000000000000000000001277020517500235335ustar00rootroot00000000000000data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/Event/Listener/000077500000000000000000000000001277020517500253205ustar00rootroot00000000000000data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/Event/Listener/MongoDBReferenceListener.php000066400000000000000000000047031277020517500326470ustar00rootroot00000000000000. */ namespace Doctrine\Common\DataFixtures\Event\Listener; use Doctrine\Common\EventSubscriber; use Doctrine\Common\DataFixtures\ReferenceRepository; use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs; /** * Reference Listener populates identities for * stored references * * @author Gediminas Morkevicius */ final class MongoDBReferenceListener implements EventSubscriber { /** * @var ReferenceRepository */ private $referenceRepository; /** * Initialize listener * * @param ReferenceRepository $referenceRepository */ public function __construct(ReferenceRepository $referenceRepository) { $this->referenceRepository = $referenceRepository; } /** * {@inheritdoc} */ public function getSubscribedEvents() { return array( 'postPersist' ); } /** * Populates identities for stored references * * @param LifecycleEventArgs $args */ public function postPersist(LifecycleEventArgs $args) { $object = $args->getDocument(); if (($names = $this->referenceRepository->getReferenceNames($object)) !== false) { foreach ($names as $name) { $identity = $args->getDocumentManager() ->getUnitOfWork() ->getDocumentIdentifier($object); $this->referenceRepository->setReferenceIdentity($name, $identity); } } } } data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/Event/Listener/ORMReferenceListener.php000066400000000000000000000047641277020517500320260ustar00rootroot00000000000000. */ namespace Doctrine\Common\DataFixtures\Event\Listener; use Doctrine\Common\EventSubscriber; use Doctrine\Common\DataFixtures\ReferenceRepository; use Doctrine\ORM\Event\LifecycleEventArgs; /** * Reference Listener populates identities for * stored references * * @author Gediminas Morkevicius */ final class ORMReferenceListener implements EventSubscriber { /** * @var ReferenceRepository */ private $referenceRepository; /** * Initialize listener * * @param ReferenceRepository $referenceRepository */ public function __construct(ReferenceRepository $referenceRepository) { $this->referenceRepository = $referenceRepository; } /** * {@inheritdoc} */ public function getSubscribedEvents() { return array( 'postPersist' // would be better to use onClear, but it is supported only in 2.1 ); } /** * Populates identities for stored references * * @param LifecycleEventArgs $args */ public function postPersist(LifecycleEventArgs $args) { $object = $args->getEntity(); if (($names = $this->referenceRepository->getReferenceNames($object)) !== false) { foreach ($names as $name) { $identity = $args->getEntityManager() ->getUnitOfWork() ->getEntityIdentifier($object); $this->referenceRepository->setReferenceIdentity($name, $identity); } } } } data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/Exception/000077500000000000000000000000001277020517500244105ustar00rootroot00000000000000data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/Exception/CircularReferenceException.php000066400000000000000000000002461277020517500323650ustar00rootroot00000000000000 */ abstract class AbstractExecutor { /** Purger instance for purging database before loading data fixtures */ protected $purger; /** Logger callback for logging messages when loading data fixtures */ protected $logger; /** * Fixture reference repository * @var ReferenceRepository */ protected $referenceRepository; /** * Loads an instance of reference repository * * @param Doctrine\Common\Persistence\ObjectManager $manager */ public function __construct(ObjectManager $manager) { $this->referenceRepository = new ReferenceRepository($manager); } /** * Get reference repository * * @return ReferenceRepository */ public function getReferenceRepository() { return $this->referenceRepository; } /** * Set the reference repository * * @param ReferenceRepository $referenceRepository Reference repository */ public function setReferenceRepository(ReferenceRepository $referenceRepository) { $this->referenceRepository = $referenceRepository; } /** * Sets the Purger instance to use for this executor instance. * * @param PurgerInterface $purger */ public function setPurger(PurgerInterface $purger) { $this->purger = $purger; } /** * Get purger * * @return Purger */ public function getPurger() { return $this->purger; } /** * Set the logger callable to execute with the log() method. * * @param $logger */ public function setLogger($logger) { $this->logger = $logger; } /** * Logs a message using the logger. * * @param string $message */ public function log($message) { $logger = $this->logger; $logger($message); } /** * Load a fixture with the given persistence manager. * * @param Doctrine\Common\Persistence\ObjectManager $manager * @param FixtureInterface $fixture */ public function load(ObjectManager $manager, FixtureInterface $fixture) { if ($this->logger) { $prefix = ''; if ($fixture instanceof OrderedFixtureInterface) { $prefix = sprintf('[%d] ',$fixture->getOrder()); } $this->log('loading ' . $prefix . get_class($fixture)); } // additionally pass the instance of reference repository to shared fixtures if ($fixture instanceof SharedFixtureInterface) { $fixture->setReferenceRepository($this->referenceRepository); } $fixture->load($manager); $manager->clear(); } /** * Purges the database before loading. */ public function purge() { if ($this->purger === null) { throw new \Exception('Doctrine\Common\DataFixtures\Purger\PurgerInterface instance is required if you want to purge the database before loading your data fixtures.'); } if ($this->logger) { $this->log('purging database'); } $this->purger->purge(); } /** * Executes the given array of data fixtures. * * @param array $fixtures Array of fixtures to execute. * @param boolean $append Whether to append the data fixtures or purge the database before loading. */ abstract public function execute(array $fixtures, $append = false); } data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/Executor/MongoDBExecutor.php000066400000000000000000000056731277020517500300000ustar00rootroot00000000000000. */ namespace Doctrine\Common\DataFixtures\Executor; use Doctrine\ODM\MongoDB\DocumentManager; use Doctrine\Common\DataFixtures\Purger\MongoDBPurger; use Doctrine\Common\DataFixtures\Event\Listener\MongoDBReferenceListener; use Doctrine\Common\DataFixtures\ReferenceRepository; /** * Class responsible for executing data fixtures. * * @author Jonathan H. Wage */ class MongoDBExecutor extends AbstractExecutor { /** * Construct new fixtures loader instance. * * @param DocumentManager $dm DocumentManager instance used for persistence. */ public function __construct(DocumentManager $dm, MongoDBPurger $purger = null) { $this->dm = $dm; if ($purger !== null) { $this->purger = $purger; $this->purger->setDocumentManager($dm); } parent::__construct($dm); $this->listener = new MongoDBReferenceListener($this->referenceRepository); $dm->getEventManager()->addEventSubscriber($this->listener); } /** * Retrieve the DocumentManager instance this executor instance is using. * * @return \Doctrine\ODM\MongoDB\DocumentManager */ public function getObjectManager() { return $this->dm; } /** @inheritDoc */ public function setReferenceRepository(ReferenceRepository $referenceRepository) { $this->dm->getEventManager()->removeEventListener( $this->listener->getSubscribedEvents(), $this->listener ); $this->referenceRepository = $referenceRepository; $this->listener = new MongoDBReferenceListener($this->referenceRepository); $this->dm->getEventManager()->addEventSubscriber($this->listener); } /** @inheritDoc */ public function execute(array $fixtures, $append = false) { if ($append === false) { $this->purge(); } foreach ($fixtures as $fixture) { $this->load($this->dm, $fixture); } } } data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/Executor/ORMExecutor.php000066400000000000000000000062611277020517500271420ustar00rootroot00000000000000. */ namespace Doctrine\Common\DataFixtures\Executor; use Doctrine\ORM\EntityManagerInterface; use Doctrine\Common\DataFixtures\Purger\ORMPurger; use Doctrine\Common\DataFixtures\Event\Listener\ORMReferenceListener; use Doctrine\Common\DataFixtures\ReferenceRepository; /** * Class responsible for executing data fixtures. * * @author Jonathan H. Wage */ class ORMExecutor extends AbstractExecutor { /** * @var EntityManagerInterface */ private $em; /** * Construct new fixtures loader instance. * * @param EntityManagerInterface $em EntityManagerInterface instance used for persistence. */ public function __construct(EntityManagerInterface $em, ORMPurger $purger = null) { $this->em = $em; if ($purger !== null) { $this->purger = $purger; $this->purger->setEntityManager($em); } parent::__construct($em); $this->listener = new ORMReferenceListener($this->referenceRepository); $em->getEventManager()->addEventSubscriber($this->listener); } /** * Retrieve the EntityManagerInterface instance this executor instance is using. * * @return \Doctrine\ORM\EntityManagerInterface */ public function getObjectManager() { return $this->em; } /** @inheritDoc */ public function setReferenceRepository(ReferenceRepository $referenceRepository) { $this->em->getEventManager()->removeEventListener( $this->listener->getSubscribedEvents(), $this->listener ); $this->referenceRepository = $referenceRepository; $this->listener = new ORMReferenceListener($this->referenceRepository); $this->em->getEventManager()->addEventSubscriber($this->listener); } /** @inheritDoc */ public function execute(array $fixtures, $append = false) { $executor = $this; $this->em->transactional(function(EntityManagerInterface $em) use ($executor, $fixtures, $append) { if ($append === false) { $executor->purge(); } foreach ($fixtures as $fixture) { $executor->load($em, $fixture); } }); } } data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/Executor/PHPCRExecutor.php000066400000000000000000000050071277020517500273560ustar00rootroot00000000000000. */ namespace Doctrine\Common\DataFixtures\Executor; use Doctrine\ODM\PHPCR\DocumentManager; use Doctrine\Common\DataFixtures\Purger\PHPCRPurger; /** * Class responsible for executing data fixtures. * * @author Jonathan H. Wage * @author Daniel Barsotti */ class PHPCRExecutor extends AbstractExecutor { /** * Construct new fixtures loader instance. * * @param DocumentManager $dm DocumentManager instance used for persistence. */ public function __construct(DocumentManager $dm, PHPCRPurger $purger = null) { $this->dm = $dm; if ($purger !== null) { $this->purger = $purger; $this->purger->setDocumentManager($dm); } parent::__construct($dm); } /** * Retrieve the DocumentManager instance this executor instance is using. * * @return \Doctrine\ODM\PHPCR\DocumentManager */ public function getObjectManager() { return $this->dm; } /** @inheritDoc */ public function execute(array $fixtures, $append = false) { $that = $this; $function = function ($dm) use ($append, $that, $fixtures) { if ($append === false) { $that->purge(); } foreach ($fixtures as $fixture) { $that->load($dm, $fixture); } }; if (method_exists($this->dm, 'transactional')) { $this->dm->transactional($function); } else { $function($this->dm); } } } data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/FixtureInterface.php000066400000000000000000000025561277020517500264420ustar00rootroot00000000000000. */ namespace Doctrine\Common\DataFixtures; use Doctrine\Common\Persistence\ObjectManager; /** * Interface contract for fixture classes to implement. * * @author Jonathan H. Wage */ interface FixtureInterface { /** * Load data fixtures with the passed EntityManager * * @param ObjectManager $manager */ public function load(ObjectManager $manager); } data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/Loader.php000066400000000000000000000315251277020517500243770ustar00rootroot00000000000000. */ namespace Doctrine\Common\DataFixtures; use Doctrine\Common\DataFixtures\Exception\CircularReferenceException; /** * Class responsible for loading data fixture classes. * * @author Jonathan H. Wage */ class Loader { /** * Array of fixture object instances to execute. * * @var array */ private $fixtures = array(); /** * Array of ordered fixture object instances. * * @var array */ private $orderedFixtures = array(); /** * Determines if we must order fixtures by number * * @var boolean */ private $orderFixturesByNumber = false; /** * Determines if we must order fixtures by its dependencies * * @var boolean */ private $orderFixturesByDependencies = false; /** * The file extension of fixture files. * * @var string */ private $fileExtension = '.php'; /** * Find fixtures classes in a given directory and load them. * * @param string $dir Directory to find fixture classes in. * @return array $fixtures Array of loaded fixture object instances. */ public function loadFromDirectory($dir) { if (!is_dir($dir)) { throw new \InvalidArgumentException(sprintf('"%s" does not exist', $dir)); } $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($dir), \RecursiveIteratorIterator::LEAVES_ONLY ); return $this->loadFromIterator($iterator); } /** * Find fixtures classes in a given file and load them. * * @param string $fileName File to find fixture classes in. * @return array $fixtures Array of loaded fixture object instances. */ public function loadFromFile($fileName) { if (!is_readable($fileName)) { throw new \InvalidArgumentException(sprintf('"%s" does not exist or is not readable', $fileName)); } $iterator = new \ArrayIterator(array(new \SplFileInfo($fileName))); return $this->loadFromIterator($iterator); } /** * Has fixture? * * @param FixtureInterface $fixture * * @return boolean */ public function hasFixture($fixture) { return isset($this->fixtures[get_class($fixture)]); } /** * Get a specific fixture instance * * @param string $className * @return FixtureInterface */ public function getFixture($className) { if (!isset($this->fixtures[$className])) { throw new \InvalidArgumentException(sprintf( '"%s" is not a registered fixture', $className )); } return $this->fixtures[$className]; } /** * Add a fixture object instance to the loader. * * @param FixtureInterface $fixture */ public function addFixture(FixtureInterface $fixture) { $fixtureClass = get_class($fixture); if (!isset($this->fixtures[$fixtureClass])) { if ($fixture instanceof OrderedFixtureInterface && $fixture instanceof DependentFixtureInterface) { throw new \InvalidArgumentException(sprintf('Class "%s" can\'t implement "%s" and "%s" at the same time.', get_class($fixture), 'OrderedFixtureInterface', 'DependentFixtureInterface')); } $this->fixtures[$fixtureClass] = $fixture; if ($fixture instanceof OrderedFixtureInterface) { $this->orderFixturesByNumber = true; } elseif ($fixture instanceof DependentFixtureInterface) { $this->orderFixturesByDependencies = true; foreach($fixture->getDependencies() as $class) { if (class_exists($class)) { $this->addFixture(new $class); } } } } } /** * Returns the array of data fixtures to execute. * * @return array $fixtures */ public function getFixtures() { $this->orderedFixtures = array(); if ($this->orderFixturesByNumber) { $this->orderFixturesByNumber(); } if ($this->orderFixturesByDependencies) { $this->orderFixturesByDependencies(); } if (!$this->orderFixturesByNumber && !$this->orderFixturesByDependencies) { $this->orderedFixtures = $this->fixtures; } return $this->orderedFixtures; } /** * Check if a given fixture is transient and should not be considered a data fixtures * class. * * @return boolean */ public function isTransient($className) { $rc = new \ReflectionClass($className); if ($rc->isAbstract()) return true; $interfaces = class_implements($className); return in_array('Doctrine\Common\DataFixtures\FixtureInterface', $interfaces) ? false : true; } /** * Orders fixtures by number * * @todo maybe there is a better way to handle reordering * @return void */ private function orderFixturesByNumber() { $this->orderedFixtures = $this->fixtures; usort($this->orderedFixtures, function($a, $b) { if ($a instanceof OrderedFixtureInterface && $b instanceof OrderedFixtureInterface) { if ($a->getOrder() === $b->getOrder()) { return 0; } return $a->getOrder() < $b->getOrder() ? -1 : 1; } elseif ($a instanceof OrderedFixtureInterface) { return $a->getOrder() === 0 ? 0 : 1; } elseif ($b instanceof OrderedFixtureInterface) { return $b->getOrder() === 0 ? 0 : -1; } return 0; }); } /** * Orders fixtures by dependencies * * @return void */ private function orderFixturesByDependencies() { $sequenceForClasses = array(); // If fixtures were already ordered by number then we need // to remove classes which are not instances of OrderedFixtureInterface // in case fixtures implementing DependentFixtureInterface exist. // This is because, in that case, the method orderFixturesByDependencies // will handle all fixtures which are not instances of // OrderedFixtureInterface if ($this->orderFixturesByNumber) { $count = count($this->orderedFixtures); for ($i = 0 ; $i < $count ; ++$i) { if (!($this->orderedFixtures[$i] instanceof OrderedFixtureInterface)) { unset($this->orderedFixtures[$i]); } } } // First we determine which classes has dependencies and which don't foreach ($this->fixtures as $fixture) { $fixtureClass = get_class($fixture); if ($fixture instanceof OrderedFixtureInterface) { continue; } elseif ($fixture instanceof DependentFixtureInterface) { $dependenciesClasses = $fixture->getDependencies(); $this->validateDependencies($dependenciesClasses); if (!is_array($dependenciesClasses) || empty($dependenciesClasses)) { 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)); } if (in_array($fixtureClass, $dependenciesClasses)) { throw new \InvalidArgumentException(sprintf('Class "%s" can\'t have itself as a dependency', $fixtureClass)); } // We mark this class as unsequenced $sequenceForClasses[$fixtureClass] = -1; } else { // This class has no dependencies, so we assign 0 $sequenceForClasses[$fixtureClass] = 0; } } // Now we order fixtures by sequence $sequence = 1; $lastCount = -1; while (($count = count($unsequencedClasses = $this->getUnsequencedClasses($sequenceForClasses))) > 0 && $count !== $lastCount) { foreach ($unsequencedClasses as $key => $class) { $fixture = $this->fixtures[$class]; $dependencies = $fixture->getDependencies(); $unsequencedDependencies = $this->getUnsequencedClasses($sequenceForClasses, $dependencies); if (count($unsequencedDependencies) === 0) { $sequenceForClasses[$class] = $sequence++; } } $lastCount = $count; } $orderedFixtures = array(); // If there're fixtures unsequenced left and they couldn't be sequenced, // it means we have a circular reference if ($count > 0) { $msg = 'Classes "%s" have produced a CircularReferenceException. '; $msg .= 'An example of this problem would be the following: Class C has class B as its dependency. '; $msg .= 'Then, class B has class A has its dependency. Finally, class A has class C as its dependency. '; $msg .= 'This case would produce a CircularReferenceException.'; throw new CircularReferenceException(sprintf($msg, implode(',', $unsequencedClasses))); } else { // We order the classes by sequence asort($sequenceForClasses); foreach ($sequenceForClasses as $class => $sequence) { // If fixtures were ordered $orderedFixtures[] = $this->fixtures[$class]; } } $this->orderedFixtures = array_merge($this->orderedFixtures, $orderedFixtures); } private function validateDependencies($dependenciesClasses) { $loadedFixtureClasses = array_keys($this->fixtures); foreach ($dependenciesClasses as $class) { if (!in_array($class, $loadedFixtureClasses)) { throw new \RuntimeException(sprintf('Fixture "%s" was declared as a dependency, but it should be added in fixture loader first.', $class)); } } return true; } private function getUnsequencedClasses($sequences, $classes = null) { $unsequencedClasses = array(); if (is_null($classes)) { $classes = array_keys($sequences); } foreach ($classes as $class) { if ($sequences[$class] === -1) { $unsequencedClasses[] = $class; } } return $unsequencedClasses; } /** * Load fixtures from files contained in iterator. * * @param \Iterator $iterator Iterator over files from which fixtures should be loaded. * @return array $fixtures Array of loaded fixture object instances. */ private function loadFromIterator(\Iterator $iterator) { $includedFiles = array(); foreach ($iterator as $file) { if (($fileName = $file->getBasename($this->fileExtension)) == $file->getBasename()) { continue; } $sourceFile = realpath($file->getPathName()); require_once $sourceFile; $includedFiles[] = $sourceFile; } $fixtures = array(); $declared = get_declared_classes(); // Make the declared classes order deterministic sort($declared); foreach ($declared as $className) { $reflClass = new \ReflectionClass($className); $sourceFile = $reflClass->getFileName(); if (in_array($sourceFile, $includedFiles) && ! $this->isTransient($className)) { $fixture = new $className; $fixtures[] = $fixture; $this->addFixture($fixture); } } return $fixtures; } } data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/OrderedFixtureInterface.php000066400000000000000000000027011277020517500277370ustar00rootroot00000000000000. */ namespace Doctrine\Common\DataFixtures; /** * Ordered Fixture interface needs to be implemented * by fixtures, which needs to have a specific order * when being loaded by directory scan for example * * @author Gediminas Morkevicius * @author Jonathan H. Wage */ interface OrderedFixtureInterface { /** * Get the order of this fixture * * @return integer */ public function getOrder(); } data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/ProxyReferenceRepository.php000066400000000000000000000101571277020517500302270ustar00rootroot00000000000000. */ namespace Doctrine\Common\DataFixtures; use Doctrine\Common\Version; use Doctrine\Common\Util\ClassUtils; /** * Proxy reference repository * * Allow data fixture references and identities to be persisted when cached data fixtures * are pre-loaded, for example, by LiipFunctionalTestBundle\Test\WebTestCase loadFixtures(). * * @author Guilherme Blanco * @author Anthon Pang */ class ProxyReferenceRepository extends ReferenceRepository { /** * Get real class name of a reference that could be a proxy * * @param string $className Class name of reference object * * @return string */ protected function getRealClass($className) { if (Version::compare('2.2.0') <= 0) { return ClassUtils::getRealClass($className); } if (substr($className, -5) === 'Proxy') { return substr($className, 0, -5); } return $className; } /** * Serialize reference repository * * @return string */ public function serialize() { $unitOfWork = $this->getManager()->getUnitOfWork(); $simpleReferences = array(); foreach ($this->getReferences() as $name => $reference) { $className = $this->getRealClass(get_class($reference)); $simpleReferences[$name] = array($className, $this->getIdentifier($reference, $unitOfWork)); } $serializedData = json_encode(array( 'references' => $simpleReferences, 'identities' => $this->getIdentities(), )); return $serializedData; } /** * Unserialize reference repository * * @param string $serializedData Serialized data */ public function unserialize($serializedData) { $repositoryData = json_decode($serializedData, true); $references = $repositoryData['references']; foreach ($references as $name => $proxyReference) { $this->setReference( $name, $this->getManager()->getReference( $proxyReference[0], // entity class name $proxyReference[1] // identifiers ) ); } $identities = $repositoryData['identities']; foreach ($identities as $name => $identity) { $this->setReferenceIdentity($name, $identity); } } /** * Load data fixture reference repository * * @param string $baseCacheName Base cache name * * @return boolean */ public function load($baseCacheName) { $filename = $baseCacheName . '.ser'; if ( ! file_exists($filename) || ($serializedData = file_get_contents($filename)) === false) { return false; } $this->unserialize($serializedData); return true; } /** * Save data fixture reference repository * * @param string $baseCacheName Base cache name */ public function save($baseCacheName) { $serializedData = $this->serialize(); file_put_contents($baseCacheName . '.ser', $serializedData); } } data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/Purger/000077500000000000000000000000001277020517500237165ustar00rootroot00000000000000data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/Purger/MongoDBPurger.php000066400000000000000000000046011277020517500271020ustar00rootroot00000000000000. */ namespace Doctrine\Common\DataFixtures\Purger; use Doctrine\ODM\MongoDB\DocumentManager; /** * Class responsible for purging databases of data before reloading data fixtures. * * @author Jonathan H. Wage */ class MongoDBPurger implements PurgerInterface { /** DocumentManager instance used for persistence. */ private $dm; /** * Construct new purger instance. * * @param DocumentManager $dm DocumentManager instance used for persistence. */ public function __construct(DocumentManager $dm = null) { $this->dm = $dm; } /** * Set the DocumentManager instance this purger instance should use. * * @param DocumentManager $dm */ public function setDocumentManager(DocumentManager $dm) { $this->dm = $dm; } /** * Retrieve the DocumentManager instance this purger instance is using. * * @return \Doctrine\ODM\MongoDB\DocumentManager */ public function getObjectManager() { return $this->dm; } /** @inheritDoc */ public function purge() { $metadatas = $this->dm->getMetadataFactory()->getAllMetadata(); foreach ($metadatas as $metadata) { if ( ! $metadata->isMappedSuperclass) { $this->dm->getDocumentCollection($metadata->name)->drop(); } } $this->dm->getSchemaManager()->ensureIndexes(); } } data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/Purger/ORMPurger.php000066400000000000000000000213461277020517500262570ustar00rootroot00000000000000. */ namespace Doctrine\Common\DataFixtures\Purger; use Doctrine\ORM\EntityManagerInterface; use Doctrine\Common\DataFixtures\Sorter\TopologicalSorter; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\ORM\Mapping\ClassMetadataInfo; /** * Class responsible for purging databases of data before reloading data fixtures. * * @author Jonathan H. Wage * @author Benjamin Eberlei */ class ORMPurger implements PurgerInterface { const PURGE_MODE_DELETE = 1; const PURGE_MODE_TRUNCATE = 2; /** EntityManagerInterface instance used for persistence. */ private $em; /** * If the purge should be done through DELETE or TRUNCATE statements * * @var int */ private $purgeMode = self::PURGE_MODE_DELETE; /** * Table/view names to be excleded from purge * * @var string[] */ private $excluded; /** * Construct new purger instance. * * @param EntityManagerInterface $em EntityManagerInterface instance used for persistence. * @param string[] $excluded array of table/view names to be excleded from purge */ public function __construct(EntityManagerInterface $em = null, array $excluded = array()) { $this->em = $em; $this->excluded = $excluded; } /** * Set the purge mode * * @param $mode * @return void */ public function setPurgeMode($mode) { $this->purgeMode = $mode; } /** * Get the purge mode * * @return int */ public function getPurgeMode() { return $this->purgeMode; } /** * Set the EntityManagerInterface instance this purger instance should use. * * @param EntityManagerInterface $em */ public function setEntityManager(EntityManagerInterface $em) { $this->em = $em; } /** * Retrieve the EntityManagerInterface instance this purger instance is using. * * @return \Doctrine\ORM\EntityManagerInterface */ public function getObjectManager() { return $this->em; } /** @inheritDoc */ public function purge() { $classes = array(); foreach ($this->em->getMetadataFactory()->getAllMetadata() as $metadata) { if (! $metadata->isMappedSuperclass && ! (isset($metadata->isEmbeddedClass) && $metadata->isEmbeddedClass)) { $classes[] = $metadata; } } $commitOrder = $this->getCommitOrder($this->em, $classes); // Get platform parameters $platform = $this->em->getConnection()->getDatabasePlatform(); // Drop association tables first $orderedTables = $this->getAssociationTables($commitOrder, $platform); // Drop tables in reverse commit order for ($i = count($commitOrder) - 1; $i >= 0; --$i) { $class = $commitOrder[$i]; if ( (isset($class->isEmbeddedClass) && $class->isEmbeddedClass) || $class->isMappedSuperclass || ($class->isInheritanceTypeSingleTable() && $class->name !== $class->rootEntityName) ) { continue; } $orderedTables[] = $this->getTableName($class, $platform); } $connection = $this->em->getConnection(); $filterExpr = $connection->getConfiguration()->getFilterSchemaAssetsExpression(); $emptyFilterExpression = empty($filterExpr); foreach($orderedTables as $tbl) { if(($emptyFilterExpression||preg_match($filterExpr, $tbl)) && array_search($tbl, $this->excluded) === false){ if ($this->purgeMode === self::PURGE_MODE_DELETE) { $connection->executeUpdate("DELETE FROM " . $tbl); } else { $connection->executeUpdate($platform->getTruncateTableSQL($tbl, true)); } } } } /** * @param EntityManagerInterface $em * @param ClassMetadata[] $classes * * @return ClassMetadata[] */ private function getCommitOrder(EntityManagerInterface $em, array $classes) { $sorter = new TopologicalSorter(); foreach ($classes as $class) { if ( ! $sorter->hasNode($class->name)) { $sorter->addNode($class->name, $class); } // $class before its parents foreach ($class->parentClasses as $parentClass) { $parentClass = $em->getClassMetadata($parentClass); $parentClassName = $parentClass->getName(); if ( ! $sorter->hasNode($parentClassName)) { $sorter->addNode($parentClassName, $parentClass); } $sorter->addDependency($class->name, $parentClassName); } foreach ($class->associationMappings as $assoc) { if ($assoc['isOwningSide']) { /* @var $targetClass ClassMetadata */ $targetClass = $em->getClassMetadata($assoc['targetEntity']); $targetClassName = $targetClass->getName(); if ( ! $sorter->hasNode($targetClassName)) { $sorter->addNode($targetClassName, $targetClass); } // add dependency ($targetClass before $class) $sorter->addDependency($targetClassName, $class->name); // parents of $targetClass before $class, too foreach ($targetClass->parentClasses as $parentClass) { $parentClass = $em->getClassMetadata($parentClass); $parentClassName = $parentClass->getName(); if ( ! $sorter->hasNode($parentClassName)) { $sorter->addNode($parentClassName, $parentClass); } $sorter->addDependency($parentClassName, $class->name); } } } } return array_reverse($sorter->sort()); } /** * @param array $classes * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform * @return array */ private function getAssociationTables(array $classes, AbstractPlatform $platform) { $associationTables = array(); foreach ($classes as $class) { foreach ($class->associationMappings as $assoc) { if ($assoc['isOwningSide'] && $assoc['type'] == ClassMetadata::MANY_TO_MANY) { $associationTables[] = $this->getJoinTableName($assoc, $class, $platform); } } } return $associationTables; } /** * * @param \Doctrine\ORM\Mapping\ClassMetadata $class * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform * @return string */ private function getTableName($class, $platform) { if (isset($class->table['schema']) && !method_exists($class, 'getSchemaName')) { return $class->table['schema'].'.'.$this->em->getConfiguration()->getQuoteStrategy()->getTableName($class, $platform); } return $this->em->getConfiguration()->getQuoteStrategy()->getTableName($class, $platform); } /** * * @param array $association * @param \Doctrine\ORM\Mapping\ClassMetadata $class * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform * @return string */ private function getJoinTableName($assoc, $class, $platform) { if (isset($assoc['joinTable']['schema']) && !method_exists($class, 'getSchemaName')) { return $assoc['joinTable']['schema'].'.'.$this->em->getConfiguration()->getQuoteStrategy()->getJoinTableName($assoc, $class, $platform); } return $this->em->getConfiguration()->getQuoteStrategy()->getJoinTableName($assoc, $class, $platform); } }data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/Purger/PHPCRPurger.php000066400000000000000000000044061277020517500264740ustar00rootroot00000000000000. */ namespace Doctrine\Common\DataFixtures\Purger; use PHPCR\Util\NodeHelper; use Doctrine\ODM\PHPCR\DocumentManager; /** * Class responsible for purging databases of data before reloading data fixtures. * * @author Daniel Barsotti */ class PHPCRPurger implements PurgerInterface { /** * DocumentManager instance used for persistence. * @var DocumentManager */ private $dm; /** * Construct new purger instance. * * @param DocumentManager $dm DocumentManager instance used for persistence. */ public function __construct(DocumentManager $dm = null) { $this->dm = $dm; } /** * Set the DocumentManager instance this purger instance should use. * * @param DocumentManager $dm */ public function setDocumentManager(DocumentManager $dm) { $this->dm = $dm; } /** * Retrieve the DocumentManager instance this purger instance is using. * * @return \Doctrine\ODM\PHPCR\DocumentManager */ public function getObjectManager() { return $this->dm; } /** * @inheritDoc */ public function purge() { $session = $this->dm->getPhpcrSession(); NodeHelper::purgeWorkspace($session); $session->save(); } } data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/Purger/PurgerInterface.php000066400000000000000000000023771277020517500275250ustar00rootroot00000000000000. */ namespace Doctrine\Common\DataFixtures\Purger; /** * PurgerInterface * * @author Jonathan H. Wage */ interface PurgerInterface { /** * Purge the data from the database for the given EntityManager. * * @return void */ function purge(); } data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/ReferenceRepository.php000066400000000000000000000157611277020517500271730ustar00rootroot00000000000000. */ namespace Doctrine\Common\DataFixtures; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\ODM\PHPCR\DocumentManager as PhpcrDocumentManager; /** * ReferenceRepository class manages references for * fixtures in order to easily support the relations * between fixtures * * @author Gediminas Morkevicius */ class ReferenceRepository { /** * List of named references to the fixture objects * gathered during loads of fixtures * * @var array */ private $references = array(); /** * List of identifiers stored for references * in case if reference gets unmanaged, it will * use a proxy referenced by this identity * * @var array */ private $identities = array(); /** * Currently used object manager * * @var Doctrine\Common\Persistence\ObjectManager */ private $manager; /** * Initialize the ReferenceRepository * * @param Doctrine\Common\Persistence\ObjectManager $manager */ public function __construct(ObjectManager $manager) { $this->manager = $manager; } /** * Get identifier for a unit of work * * @param object $reference Reference object * @param object $uow Unit of work * * @return array */ protected function getIdentifier($reference, $uow) { // In case Reference is not yet managed in UnitOfWork if ( ! $this->hasIdentifier($reference)) { $class = $this->manager->getClassMetadata(get_class($reference)); return $class->getIdentifierValues($reference); } // Dealing with ORM UnitOfWork if (method_exists($uow, 'getEntityIdentifier')) { return $uow->getEntityIdentifier($reference); } // ODM UnitOfWork return $uow->getDocumentIdentifier($reference); } /** * Set the reference entry identified by $name * and referenced to $reference. If $name * already is set, it overrides it * * @param string $name * @param object $reference */ public function setReference($name, $reference) { $this->references[$name] = $reference; if ($this->hasIdentifier($reference)) { // in case if reference is set after flush, store its identity $uow = $this->manager->getUnitOfWork(); $this->identities[$name] = $this->getIdentifier($reference, $uow); } } /** * Store the identifier of a reference * * @param string $name * @param mixed $identity */ public function setReferenceIdentity($name, $identity) { $this->identities[$name] = $identity; } /** * Set the reference entry identified by $name * and referenced to managed $object. $name must * not be set yet * * Notice: in case if identifier is generated after * the record is inserted, be sure tu use this method * after $object is flushed * * @param string $name * @param object $object - managed object * @throws BadMethodCallException - if repository already has * a reference by $name * @return void */ public function addReference($name, $object) { if (isset($this->references[$name])) { throw new \BadMethodCallException("Reference to: ({$name}) already exists, use method setReference in order to override it"); } $this->setReference($name, $object); } /** * Loads an object using stored reference * named by $name * * @param string $name * @throws OutOfBoundsException - if repository does not exist * @return object */ public function getReference($name) { if (!$this->hasReference($name)) { throw new \OutOfBoundsException("Reference to: ({$name}) does not exist"); } $reference = $this->references[$name]; $meta = $this->manager->getClassMetadata(get_class($reference)); if (!$this->manager->contains($reference) && isset($this->identities[$name])) { $reference = $this->manager->getReference( $meta->name, $this->identities[$name] ); $this->references[$name] = $reference; // already in identity map } return $reference; } /** * Check if an object is stored using reference * named by $name * * @param string $name * @return boolean */ public function hasReference($name) { return isset($this->references[$name]); } /** * Searches for reference names in the * list of stored references * * @param object $reference * @return array */ public function getReferenceNames($reference) { return array_keys($this->references, $reference, true); } /** * Checks if reference has identity stored * * @param string $name */ public function hasIdentity($name) { return array_key_exists($name, $this->identities); } /** * Get all stored identities * * @return array */ public function getIdentities() { return $this->identities; } /** * Get all stored references * * @return array */ public function getReferences() { return $this->references; } /** * Get object manager * * @return Doctrine\Common\Persistence\ObjectManager */ public function getManager() { return $this->manager; } /** * Checks if object has identifier already in unit of work. * * @param $reference * * @return bool */ private function hasIdentifier($reference) { // in case if reference is set after flush, store its identity $uow = $this->manager->getUnitOfWork(); if ($this->manager instanceof PhpcrDocumentManager) { return $uow->contains($reference); } else { return $uow->isInIdentityMap($reference); } } } data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/SharedFixtureInterface.php000066400000000000000000000031051277020517500275600ustar00rootroot00000000000000. */ namespace Doctrine\Common\DataFixtures; use Doctrine\Common\DataFixtures\ReferenceRepository; /** * Shared Fixture interface needs to be implemented * by fixtures, which needs some references to be shared * among other fixture classes in order to maintain * relation mapping * * @author Gediminas Morkevicius */ interface SharedFixtureInterface extends FixtureInterface { /** * Set the reference repository * * @param ReferenceRepository $referenceRepository */ function setReferenceRepository(ReferenceRepository $referenceRepository); } data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/Sorter/000077500000000000000000000000001277020517500237305ustar00rootroot00000000000000data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/Sorter/TopologicalSorter.php000066400000000000000000000141021277020517500301120ustar00rootroot00000000000000. */ namespace Doctrine\Common\DataFixtures\Sorter; use Doctrine\Common\DataFixtures\Exception\CircularReferenceException; use Doctrine\ORM\Mapping\ClassMetadata; /** * TopologicalSorter is an ordering algorithm for directed graphs (DG) and/or * directed acyclic graphs (DAG) by using a depth-first searching (DFS) to * traverse the graph built in memory. * This algorithm have a linear running time based on nodes (V) and dependency * between the nodes (E), resulting in a computational complexity of O(V + E). * * @author Guilherme Blanco * @author Roman Borschel * * @internal this class is to be used only by data-fixtures internals: do not * rely on it in your own libraries/applications. */ class TopologicalSorter { /** * Matrix of nodes (aka. vertex). * Keys are provided hashes and values are the node definition objects. * * @var Vertex[] */ private $nodeList = []; /** * Volatile variable holding calculated nodes during sorting process. * * @var array */ private $sortedNodeList = []; /** * Allow or not cyclic dependencies * * @var boolean */ private $allowCyclicDependencies; /** * Construct TopologicalSorter object * * @param boolean $allowCyclicDependencies */ public function __construct($allowCyclicDependencies = true) { $this->allowCyclicDependencies = $allowCyclicDependencies; } /** * Adds a new node (vertex) to the graph, assigning its hash and value. * * @param string $hash * @param ClassMetadata $node * * @return void */ public function addNode($hash, ClassMetadata $node) { $this->nodeList[$hash] = new Vertex($node); } /** * Checks the existence of a node in the graph. * * @param string $hash * * @return bool */ public function hasNode($hash) { return isset($this->nodeList[$hash]); } /** * Adds a new dependency (edge) to the graph using their hashes. * * @param string $fromHash * @param string $toHash * * @return void */ public function addDependency($fromHash, $toHash) { $definition = $this->nodeList[$fromHash]; $definition->dependencyList[] = $toHash; } /** * Return a valid order list of all current nodes. * The desired topological sorting is the postorder of these searches. * * Note: Highly performance-sensitive method. * * @throws \RuntimeException * @throws CircularReferenceException * * @return array */ public function sort() { foreach ($this->nodeList as $definition) { if ($definition->state !== Vertex::NOT_VISITED) { continue; } $this->visit($definition); } $sortedList = $this->sortedNodeList; $this->nodeList = []; $this->sortedNodeList = []; return $sortedList; } /** * Visit a given node definition for reordering. * * Note: Highly performance-sensitive method. * * @throws \RuntimeException * @throws CircularReferenceException * * @param Vertex $definition */ private function visit(Vertex $definition) { $definition->state = Vertex::IN_PROGRESS; foreach ($definition->dependencyList as $dependency) { if ( ! isset($this->nodeList[$dependency])) { throw new \RuntimeException(sprintf( 'Fixture "%s" has a dependency of fixture "%s", but it not listed to be loaded.', get_class($definition->value), $dependency )); } $childDefinition = $this->nodeList[$dependency]; // allow self referencing classes if ($definition === $childDefinition) { continue; } switch ($childDefinition->state) { case Vertex::VISITED: break; case Vertex::IN_PROGRESS: if ( ! $this->allowCyclicDependencies) { throw new CircularReferenceException( sprintf( 'Graph contains cyclic dependency between the classes "%s" and' .' "%s". An example of this problem would be the following: ' .'Class C has class B as its dependency. Then, class B has class A has its dependency. ' .'Finally, class A has class C as its dependency.', $definition->value->getName(), $childDefinition->value->getName() ) ); } break; case Vertex::NOT_VISITED: $this->visit($childDefinition); } } $definition->state = Vertex::VISITED; $this->sortedNodeList[] = $definition->value; } } data-fixtures-1.2.2/lib/Doctrine/Common/DataFixtures/Sorter/Vertex.php000066400000000000000000000037271277020517500257270ustar00rootroot00000000000000. */ namespace Doctrine\Common\DataFixtures\Sorter; use Doctrine\ORM\Mapping\ClassMetadata; /** * @author Marco Pivetta * * @internal this class is to be used only by data-fixtures internals: do not * rely on it in your own libraries/applications. This class is * designed to work with {@see \Doctrine\Common\DataFixtures\Sorter\TopologicalSorter} * only. */ class Vertex { const NOT_VISITED = 0; const IN_PROGRESS = 1; const VISITED = 2; /** * @var int one of either {@see self::NOT_VISITED}, {@see self::IN_PROGRESS} or {@see self::VISITED}. */ public $state = self::NOT_VISITED; /** * @var ClassMetadata Actual node value */ public $value; /** * @var string[] Map of node dependencies defined as hashes. */ public $dependencyList = []; /** * @param ClassMetadata $value */ public function __construct(ClassMetadata $value) { $this->value = $value; } } data-fixtures-1.2.2/phpunit.xml.dist000066400000000000000000000012201277020517500174500ustar00rootroot00000000000000 ./tests/Doctrine/ lib data-fixtures-1.2.2/tests/000077500000000000000000000000001277020517500154445ustar00rootroot00000000000000data-fixtures-1.2.2/tests/Doctrine/000077500000000000000000000000001277020517500172135ustar00rootroot00000000000000data-fixtures-1.2.2/tests/Doctrine/Tests/000077500000000000000000000000001277020517500203155ustar00rootroot00000000000000data-fixtures-1.2.2/tests/Doctrine/Tests/Common/000077500000000000000000000000001277020517500215455ustar00rootroot00000000000000data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/000077500000000000000000000000001277020517500241505ustar00rootroot00000000000000data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/BaseTest.php000066400000000000000000000042301277020517500263720ustar00rootroot00000000000000. */ namespace Doctrine\Tests\Common\DataFixtures; use Doctrine\DBAL\Driver; use Doctrine\ORM\EntityManager; use Doctrine\ORM\Tools\Setup; use PHPUnit_Framework_TestCase; /** * Base test class * * @author Jonathan H. Wage */ abstract class BaseTest extends PHPUnit_Framework_TestCase { /** * EntityManager mock object together with * annotation mapping driver * * @return EntityManager */ protected function getMockAnnotationReaderEntityManager() { $dbParams = array('driver' => 'pdo_sqlite', 'memory' => true); $config = Setup::createAnnotationMetadataConfiguration(array(__DIR__.'/TestEntity'), true); return EntityManager::create($dbParams, $config); } /** * EntityManager mock object together with * annotation mapping driver and pdo_sqlite * database in memory * * @return EntityManager */ protected function getMockSqliteEntityManager() { $dbParams = array('driver' => 'pdo_sqlite', 'memory' => true); $config = Setup::createAnnotationMetadataConfiguration(array(__DIR__.'/TestEntity'), true); return EntityManager::create($dbParams, $config); } } data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/DependentFixtureTest.php000066400000000000000000000307151277020517500310040ustar00rootroot00000000000000. */ namespace Doctrine\Tests\Common\DataFixtures; use Doctrine\Common\DataFixtures\Exception\CircularReferenceException; use Doctrine\Common\DataFixtures\Loader; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use InvalidArgumentException; use RuntimeException; /** * Test Fixture ordering by dependencies. * * @author Gustavo Adrian */ class DependentFixtureTest extends BaseTest { public function test_orderFixturesByDependencies_orderClassesWithASingleParent() { $loader = new Loader(); $loader->addFixture(new DependentFixture3); $loader->addFixture(new DependentFixture1); $loader->addFixture(new DependentFixture2); $loader->addFixture(new BaseParentFixture1); $orderedFixtures = $loader->getFixtures(); $this->assertCount(4, $orderedFixtures); $this->assertInstanceOf(__NAMESPACE__ . '\BaseParentFixture1', array_shift($orderedFixtures)); $this->assertInstanceOf(__NAMESPACE__ . '\DependentFixture1', array_shift($orderedFixtures)); $this->assertInstanceOf(__NAMESPACE__ . '\DependentFixture2', array_shift($orderedFixtures)); $this->assertInstanceOf(__NAMESPACE__ . '\DependentFixture3', array_shift($orderedFixtures)); } public function test_orderFixturesByDependencies_orderClassesWithAMultipleParents() { $loader = new Loader(); $addressFixture = new AddressFixture(); $contactMethodFixture = new ContactMethodFixture(); $contactFixture = new ContactFixture(); $baseParentFixture = new BaseParentFixture1(); $countryFixture = new CountryFixture(); $stateFixture = new StateFixture(); $loader->addFixture($addressFixture); $loader->addFixture($contactMethodFixture); $loader->addFixture($contactFixture); $loader->addFixture($baseParentFixture); $loader->addFixture($countryFixture); $loader->addFixture($stateFixture); $orderedFixtures = $loader->getFixtures(); $this->assertCount(6, $orderedFixtures); $contactFixtureOrder = array_search($contactFixture, $orderedFixtures); $contactMethodFixtureOrder = array_search($contactMethodFixture, $orderedFixtures); $addressFixtureOrder = array_search($addressFixture, $orderedFixtures); $countryFixtureOrder = array_search($countryFixture, $orderedFixtures); $stateFixtureOrder = array_search($stateFixture, $orderedFixtures); $baseParentFixtureOrder = array_search($baseParentFixture, $orderedFixtures); // Order of fixtures is not exact. We need to test, however, that dependencies are // indeed satisfied // BaseParentFixture1 has no dependencies, so it will always be first in this case $this->assertEquals($baseParentFixtureOrder, 0); $this->assertTrue($contactFixtureOrder > $contactMethodFixtureOrder); $this->assertTrue($contactFixtureOrder > $addressFixtureOrder); $this->assertTrue($contactFixtureOrder > $countryFixtureOrder); $this->assertTrue($contactFixtureOrder > $stateFixtureOrder); $this->assertTrue($contactFixtureOrder > $contactMethodFixtureOrder); $this->assertTrue($addressFixtureOrder > $stateFixtureOrder); $this->assertTrue($addressFixtureOrder > $countryFixtureOrder); } public function test_orderFixturesByDependencies_circularReferencesMakeMethodThrowCircularReferenceException() { $loader = new Loader(); $loader->addFixture(new CircularReferenceFixture3); $loader->addFixture(new CircularReferenceFixture); $loader->addFixture(new CircularReferenceFixture2); $this->expectException(CircularReferenceException::class); $loader->getFixtures(); } public function test_orderFixturesByDependencies_fixturesCantHaveItselfAsParent() { $loader = new Loader(); $loader->addFixture(new FixtureWithItselfAsParent); $this->expectException(InvalidArgumentException::class); $loader->getFixtures(); } public function test_inCaseThereAreFixturesOrderedByNumberAndByDependenciesBothOrdersAreExecuted() { $loader = new Loader(); $loader->addFixture(new OrderedByNumberFixture1); $loader->addFixture(new OrderedByNumberFixture3); $loader->addFixture(new OrderedByNumberFixture2); $loader->addFixture(new DependentFixture3); $loader->addFixture(new DependentFixture1); $loader->addFixture(new DependentFixture2); $loader->addFixture(new BaseParentFixture1); $orderedFixtures = $loader->getFixtures(); $this->assertCount(7, $orderedFixtures); $this->assertInstanceOf(__NAMESPACE__ . '\OrderedByNumberFixture1', array_shift($orderedFixtures)); $this->assertInstanceOf(__NAMESPACE__ . '\OrderedByNumberFixture2', array_shift($orderedFixtures)); $this->assertInstanceOf(__NAMESPACE__ . '\OrderedByNumberFixture3', array_shift($orderedFixtures)); $this->assertInstanceOf(__NAMESPACE__ . '\BaseParentFixture1', array_shift($orderedFixtures)); $this->assertInstanceOf(__NAMESPACE__ . '\DependentFixture1', array_shift($orderedFixtures)); $this->assertInstanceOf(__NAMESPACE__ . '\DependentFixture2', array_shift($orderedFixtures)); $this->assertInstanceOf(__NAMESPACE__ . '\DependentFixture3', array_shift($orderedFixtures)); } public function test_inCaseAFixtureHasAnUnexistentDependencyOrIfItWasntLoaded_throwsException() { $loader = new Loader(); $loader->addFixture(new FixtureWithUnexistentDependency); $this->expectException(RuntimeException::class); $loader->getFixtures(); } public function test_inCaseGetFixturesReturnsDifferentResultsEachTime() { $loader = new Loader(); $loader->addFixture(new DependentFixture1); $loader->addFixture(new BaseParentFixture1); // Intentionally calling getFixtures() twice $loader->getFixtures(); $orderedFixtures = $loader->getFixtures(); $this->assertCount(2, $orderedFixtures); $this->assertInstanceOf(__NAMESPACE__ . '\BaseParentFixture1', array_shift($orderedFixtures)); $this->assertInstanceOf(__NAMESPACE__ . '\DependentFixture1', array_shift($orderedFixtures)); } } class DependentFixture1 implements FixtureInterface, DependentFixtureInterface { public function load(ObjectManager $manager) {} public function getDependencies() { return array( 'Doctrine\Tests\Common\DataFixtures\BaseParentFixture1' ); } } class DependentFixture2 implements FixtureInterface, DependentFixtureInterface { public function load(ObjectManager $manager) {} public function getDependencies() { return array( 'Doctrine\Tests\Common\DataFixtures\DependentFixture1' ); } } class DependentFixture3 implements FixtureInterface, DependentFixtureInterface { public function load(ObjectManager $manager) {} public function getDependencies() { return array( 'Doctrine\Tests\Common\DataFixtures\DependentFixture2' ); } } class BaseParentFixture1 implements FixtureInterface { public function load(ObjectManager $manager) {} } class CountryFixture implements FixtureInterface, DependentFixtureInterface { public function load(ObjectManager $manager) {} public function getDependencies() { return array( 'Doctrine\Tests\Common\DataFixtures\BaseParentFixture1' ); } } class StateFixture implements FixtureInterface, DependentFixtureInterface { public function load(ObjectManager $manager) {} public function getDependencies() { return array( 'Doctrine\Tests\Common\DataFixtures\BaseParentFixture1', 'Doctrine\Tests\Common\DataFixtures\CountryFixture' ); } } class AddressFixture implements FixtureInterface, DependentFixtureInterface { public function load(ObjectManager $manager) {} public function getDependencies() { return array( 'Doctrine\Tests\Common\DataFixtures\BaseParentFixture1', 'Doctrine\Tests\Common\DataFixtures\CountryFixture', 'Doctrine\Tests\Common\DataFixtures\StateFixture' ); } } class ContactMethodFixture implements FixtureInterface, DependentFixtureInterface { public function load(ObjectManager $manager) {} public function getDependencies() { return array( 'Doctrine\Tests\Common\DataFixtures\BaseParentFixture1' ); } } class ContactFixture implements FixtureInterface, DependentFixtureInterface { public function load(ObjectManager $manager) {} public function getDependencies() { return array( 'Doctrine\Tests\Common\DataFixtures\AddressFixture', 'Doctrine\Tests\Common\DataFixtures\ContactMethodFixture' ); } } class CircularReferenceFixture implements FixtureInterface, DependentFixtureInterface { public function load(ObjectManager $manager) {} public function getDependencies() { return array( 'Doctrine\Tests\Common\DataFixtures\CircularReferenceFixture3' ); } } class CircularReferenceFixture2 implements FixtureInterface, DependentFixtureInterface { public function load(ObjectManager $manager) {} public function getDependencies() { return array( 'Doctrine\Tests\Common\DataFixtures\CircularReferenceFixture' ); } } class CircularReferenceFixture3 implements FixtureInterface, DependentFixtureInterface { public function load(ObjectManager $manager) {} public function getDependencies() { return array( 'Doctrine\Tests\Common\DataFixtures\CircularReferenceFixture2' ); } } class FixtureWithItselfAsParent implements FixtureInterface, DependentFixtureInterface { public function load(ObjectManager $manager) {} public function getDependencies() { return array( 'Doctrine\Tests\Common\DataFixtures\FixtureWithItselfAsParent' ); } } class FixtureWithUnexistentDependency implements FixtureInterface, DependentFixtureInterface { public function load(ObjectManager $manager) {} public function getDependencies() { return array( 'UnexistentDependency' ); } } class FixtureImplementingBothOrderingInterfaces implements FixtureInterface, OrderedFixtureInterface, DependentFixtureInterface { public function load(ObjectManager $manager) {} public function getOrder() { return 1; } public function getDependencies() { return array( 'Doctrine\Tests\Common\DataFixtures\FixtureWithItselfAsParent' ); } } class OrderedByNumberFixture1 implements FixtureInterface, OrderedFixtureInterface { public function load(ObjectManager $manager) {} public function getOrder() { return 1; } } class OrderedByNumberFixture2 implements FixtureInterface, OrderedFixtureInterface { public function load(ObjectManager $manager) {} public function getOrder() { return 5; } } class OrderedByNumberFixture3 implements FixtureInterface, OrderedFixtureInterface { public function load(ObjectManager $manager) {} public function getOrder() { return 10; } } data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/Executor/000077500000000000000000000000001277020517500257465ustar00rootroot00000000000000ORMExecutorSharedFixtureTest.php000066400000000000000000000072261277020517500341210ustar00rootroot00000000000000data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/Executor. */ namespace Doctrine\Tests\Common\DataFixtures; use Doctrine\Common\DataFixtures\Executor\ORMExecutor; use Doctrine\Common\DataFixtures\Purger\ORMPurger; use Doctrine\Common\DataFixtures\SharedFixtureInterface; use Doctrine\ORM\Tools\SchemaTool; use Doctrine\Tests\Common\DataFixtures\TestEntity\Role; use Doctrine\Tests\Common\DataFixtures\TestEntity\User; /** * Test referenced fixture execution * * @author Gediminas Morkevicius */ class ORMExecutorSharedFixtureTest extends BaseTest { const TEST_ENTITY_ROLE = 'Doctrine\Tests\Common\DataFixtures\TestEntity\Role'; const TEST_ENTITY_USER = 'Doctrine\Tests\Common\DataFixtures\TestEntity\User'; public function testFixtureExecution() { $em = $this->getMockAnnotationReaderEntityManager(); $purger = new ORMPurger(); $executor = new ORMExecutor($em, $purger); $referenceRepository = $executor->getReferenceRepository(); $fixture = $this->getMockFixture(); $fixture->expects($this->once()) ->method('load') ->with($em); $fixture->expects($this->once()) ->method('setReferenceRepository') ->with($referenceRepository); $executor->execute(array($fixture), true); } public function testSharedFixtures() { if (!extension_loaded('pdo_sqlite')) { $this->markTestSkipped('Missing pdo_sqlite extension.'); } $em = $this->getMockSqliteEntityManager(); $schemaTool = new SchemaTool($em); $schemaTool->dropSchema(array()); $schemaTool->createSchema(array( $em->getClassMetadata(self::TEST_ENTITY_ROLE), $em->getClassMetadata(self::TEST_ENTITY_USER) )); $purger = new ORMPurger(); $executor = new ORMExecutor($em, $purger); $userFixture = new TestFixtures\UserFixture; $roleFixture = new TestFixtures\RoleFixture; $executor->execute(array($roleFixture, $userFixture), true); $referenceRepository = $executor->getReferenceRepository(); $references = $referenceRepository->getReferences(); $this->assertEquals(2, count($references)); $roleReference = $referenceRepository->getReference('admin-role'); $this->assertTrue($roleReference instanceof Role); $this->assertEquals('admin', $roleReference->getName()); $userReference = $referenceRepository->getReference('admin'); $this->assertTrue($userReference instanceof User); $this->assertEquals('admin@example.com', $userReference->getEmail()); } private function getMockFixture() { return $this->createMock(SharedFixtureInterface::class); } } data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/Executor/ORMExecutorTest.php000066400000000000000000000054321277020517500314770ustar00rootroot00000000000000. */ namespace Doctrine\Tests\Common\DataFixtures\Executor; use Doctrine\Common\DataFixtures\Executor\ORMExecutor; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\DataFixtures\Purger\ORMPurger; use Doctrine\Tests\Common\DataFixtures\BaseTest; /** * Test Fixture executor. * * @author Jonathan H. Wage */ class ORMExecutorTest extends BaseTest { public function testExecuteWithNoPurge() { $em = $this->getMockSqliteEntityManager(); $purger = $this->getMockPurger(); $purger->expects($this->once()) ->method('setEntityManager') ->with($em); $executor = new ORMExecutor($em, $purger); $fixture = $this->getMockFixture(); $fixture->expects($this->once()) ->method('load') ->with($em); $executor->execute(array($fixture), true); } public function testExecuteWithPurge() { $em = $this->getMockSqliteEntityManager(); $purger = $this->getMockPurger(); $purger->expects($this->once()) ->method('purge') ->will($this->returnValue(null)); $executor = new ORMExecutor($em, $purger); $fixture = $this->getMockFixture(); $fixture->expects($this->once()) ->method('load') ->with($em); $executor->execute(array($fixture), false); } public function testExecuteTransaction() { $em = $this->getMockSqliteEntityManager(); $executor = new ORMExecutor($em); $fixture = $this->getMockFixture(); $executor->execute(array($fixture), true); } private function getMockFixture() { return $this->createMock(FixtureInterface::class); } private function getMockPurger() { return $this->createMock(ORMPurger::class); } } data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/Executor/PHPCRExecutorTest.php000066400000000000000000000152531277020517500317200ustar00rootroot00000000000000. */ namespace Doctrine\Tests\Common\DataFixtures\Executor; use Doctrine\Common\DataFixtures\Executor\PHPCRExecutor; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\DataFixtures\Purger\PHPCRPurger; use Doctrine\ODM\PHPCR\DocumentManager; use Exception; use PHPUnit_Framework_TestCase; /** * Tests for {@see \Doctrine\Common\DataFixtures\Executor\PHPCRExecutor} * * @author Marco Pivetta * * @covers \Doctrine\Common\DataFixtures\Executor\PHPCRExecutor */ class PHPCRExecutorTest extends PHPUnit_Framework_TestCase { public function testExecuteSingleFixtureWithNoPurge() { $dm = $this->getDocumentManager(); $executor = new PHPCRExecutor($dm); $fixture = $this->getMockFixture(); $fixture->expects($this->once())->method('load')->with($dm); $dm ->expects($this->once()) ->method('transactional') ->with($this->isType('callable')) ->will($this->returnCallback(function ($callback) use ($dm) { return $callback($dm); })); $executor->execute(array($fixture), true); } public function testExecuteMultipleFixturesWithNoPurge() { $dm = $this->getDocumentManager(); $executor = new PHPCRExecutor($dm); $fixture1 = $this->getMockFixture(); $fixture2 = $this->getMockFixture(); $fixture1->expects($this->once())->method('load')->with($dm); $fixture2->expects($this->once())->method('load')->with($dm); $dm ->expects($this->once()) ->method('transactional') ->with($this->isType('callable')) ->will($this->returnCallback(function ($callback) use ($dm) { return $callback($dm); })); $executor->execute(array($fixture1, $fixture2), true); } public function testExecuteFixtureWithPurge() { $dm = $this->getDocumentManager(); $purger = $this->getPurger(); $executor = new PHPCRExecutor($dm, $purger); $fixture = $this->getMockFixture(); $fixture->expects($this->once())->method('load')->with($dm); $dm ->expects($this->once()) ->method('transactional') ->with($this->isType('callable')) ->will($this->returnCallback(function ($callback) use ($dm) { return $callback($dm); })); $purger->expects($this->once())->method('purge'); $executor->execute(array($fixture), false); } public function testExecuteFixtureWithoutPurge() { $dm = $this->getDocumentManager(); $purger = $this->getPurger(); $executor = new PHPCRExecutor($dm, $purger); $fixture = $this->getMockFixture(); $fixture->expects($this->once())->method('load')->with($dm); $dm ->expects($this->once()) ->method('transactional') ->with($this->isType('callable')) ->will($this->returnCallback(function ($callback) use ($dm) { return $callback($dm); })); $purger->expects($this->never())->method('purge'); $executor->execute(array($fixture), true); } public function testFailedTransactionalStopsPurgingAndFixtureLoading() { $dm = $this->getDocumentManager(); $purger = $this->getPurger(); $executor = new PHPCRExecutor($dm, $purger); $fixture = $this->getMockFixture(); $exception = new Exception(); $fixture->expects($this->never())->method('load'); $dm->expects($this->once())->method('transactional')->will($this->throwException($exception)); $purger->expects($this->never())->method('purge'); try { $executor->execute(array($fixture), true); } catch (\Exception $caughtException) { $this->assertSame($exception, $caughtException); } } /** * @return PHPCRPurger|\PHPUnit_Framework_MockObject_MockObject */ private function getPurger() { return $this->createMock(PHPCRPurger::class); } /** * @return DocumentManager|\PHPUnit_Framework_MockObject_MockObject */ private function getDocumentManager() { $this->loadDocumentManagerClass(); return $this ->getMockBuilder(DocumentManager::class) ->setMethods([ 'transactional', 'flush', 'clear', ]) ->disableOriginalConstructor() ->getMock(); } /** * @return FixtureInterface|\PHPUnit_Framework_MockObject_MockObject */ private function getMockFixture() { return $this->createMock(FixtureInterface::class); } /** * Ensures that the {@see \Doctrine\ODM\PHPCR\DocumentManager} class exists */ private function loadDocumentManagerClass() { if (class_exists(DocumentManager::class)) { return; } // hold my beer while I do some mocking eval( <<<'PHP' namespace Doctrine\ODM\PHPCR; class DocumentManager implements \Doctrine\Common\Persistence\ObjectManager { public function find($className, $id) {} public function persist($object) {} public function remove($object) {} public function merge($object) {} public function clear($objectName = null) {} public function detach($object) {} public function refresh($object) {} public function flush() {} public function getRepository($className) {} public function getClassMetadata($className) {} public function getMetadataFactory() {} public function initializeObject($obj) {} public function contains($object) {} } PHP ); } } data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/FixtureTest.php000066400000000000000000000031631277020517500271520ustar00rootroot00000000000000. */ namespace Doctrine\Tests\Common\DataFixtures; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; /** * Test Fixture interface. * * @author Jonathan H. Wage */ class FixtureTest extends BaseTest { public function testFixtureInterface() { $em = $this->createMock(ObjectManager::class); $fixture = new MyFixture2(); $fixture->load($em); self::assertTrue($fixture->loaded); } } class MyFixture2 implements FixtureInterface { public $loaded = false; public function load(ObjectManager $manager) { $this->loaded = true; } } data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/LoaderTest.php000066400000000000000000000065141277020517500267350ustar00rootroot00000000000000. */ namespace Doctrine\Tests\Common\DataFixtures; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\DataFixtures\Loader; use Doctrine\Common\DataFixtures\SharedFixtureInterface; use TestFixtures\MyFixture1; /** * Test fixtures loader. * * @author Jonathan H. Wage */ class LoaderTest extends BaseTest { public function testLoadFromDirectory() { $loader = new Loader(); $loader->addFixture($this->getMockBuilder(FixtureInterface::class)->setMockClassName('Mock1')->getMock()); $loader->addFixture($this->getMockBuilder(FixtureInterface::class)->setMockClassName('Mock2')->getMock()); $loader->addFixture($this->getMockBuilder(SharedFixtureInterface::class)->setMockClassName('Mock3')->getMock()); $this->assertCount(3, $loader->getFixtures()); $loader->loadFromDirectory(__DIR__.'/TestFixtures'); $this->assertCount(7, $loader->getFixtures()); $this->assertTrue($loader->isTransient('TestFixtures\NotAFixture')); $this->assertFalse($loader->isTransient('TestFixtures\MyFixture1')); } public function testLoadFromFile() { $loader = new Loader(); $loader->addFixture($this->getMockBuilder(FixtureInterface::class)->setMockClassName('Mock1')->getMock()); $loader->addFixture($this->getMockBuilder(FixtureInterface::class)->setMockClassName('Mock2')->getMock()); $loader->addFixture($this->getMockBuilder(SharedFixtureInterface::class)->setMockClassName('Mock3')->getMock()); $this->assertCount(3, $loader->getFixtures()); $loader->loadFromFile(__DIR__.'/TestFixtures/MyFixture1.php'); $this->assertCount(4, $loader->getFixtures()); $loader->loadFromFile(__DIR__.'/TestFixtures/NotAFixture.php'); $this->assertCount(4, $loader->getFixtures()); $loader->loadFromFile(__DIR__.'/TestFixtures/MyFixture2.php'); $this->assertCount(5, $loader->getFixtures()); $this->assertTrue($loader->isTransient('TestFixtures\NotAFixture')); $this->assertFalse($loader->isTransient('TestFixtures\MyFixture1')); } public function testGetFixture() { $loader = new Loader(); $loader->loadFromFile(__DIR__.'/TestFixtures/MyFixture1.php'); $fixture = $loader->getFixture(MyFixture1::class); $this->assertInstanceOf(MyFixture1::class, $fixture); } } data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/OrderedFixtureTest.php000066400000000000000000000054111277020517500304550ustar00rootroot00000000000000. */ namespace Doctrine\Tests\Common\DataFixtures; use Doctrine\Common\DataFixtures\Loader; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; /** * Test Fixture ordering. * * @author Gediminas Morkevicius */ class OrderedFixtureTest extends BaseTest { public function testFixtureOrder() { $loader = new Loader(); $loader->addFixture(new OrderedFixture1); $loader->addFixture(new OrderedFixture2); $loader->addFixture(new OrderedFixture3); $loader->addFixture(new BaseFixture1); $orderedFixtures = $loader->getFixtures(); $this->assertCount(4, $orderedFixtures); $this->assertInstanceOf(__NAMESPACE__ . '\BaseFixture1', $orderedFixtures[0]); $this->assertInstanceOf(__NAMESPACE__ . '\OrderedFixture2', $orderedFixtures[1]); $this->assertInstanceOf(__NAMESPACE__ . '\OrderedFixture1', $orderedFixtures[2]); $this->assertInstanceOf(__NAMESPACE__ . '\OrderedFixture3', $orderedFixtures[3]); } } class OrderedFixture1 implements FixtureInterface, OrderedFixtureInterface { public function load(ObjectManager $manager) {} public function getOrder() { return 5; } } class OrderedFixture2 implements FixtureInterface, OrderedFixtureInterface { public function load(ObjectManager $manager) {} public function getOrder() { return 2; } } class OrderedFixture3 implements FixtureInterface, OrderedFixtureInterface { public function load(ObjectManager $manager) {} public function getOrder() { return 8; } } class BaseFixture1 implements FixtureInterface { public function load(ObjectManager $manager) {} } data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/ProxyReferenceRepositoryTest.php000066400000000000000000000143041277020517500325630ustar00rootroot00000000000000. */ namespace Doctrine\Tests\Common\DataFixtures; use Doctrine\Common\DataFixtures\ProxyReferenceRepository; use Doctrine\Common\DataFixtures\Event\Listener\ORMReferenceListener; use Doctrine\ORM\Tools\SchemaTool; use Doctrine\ORM\Proxy\Proxy; /** * Test ProxyReferenceRepository. * * @author Gediminas Morkevicius * @author Anthon Pang */ class ProxyReferenceRepositoryTest extends BaseTest { const TEST_ENTITY_ROLE = 'Doctrine\Tests\Common\DataFixtures\TestEntity\Role'; public function testReferenceEntry() { $em = $this->getMockAnnotationReaderEntityManager(); $role = new TestEntity\Role; $role->setName('admin'); $meta = $em->getClassMetadata(self::TEST_ENTITY_ROLE); $meta->getReflectionProperty('id')->setValue($role, 1); $referenceRepo = new ProxyReferenceRepository($em); $referenceRepo->addReference('test', $role); $references = $referenceRepo->getReferences(); $this->assertCount(1, $references); $this->assertArrayHasKey('test', $references); $this->assertInstanceOf(self::TEST_ENTITY_ROLE, $references['test']); } public function testReferenceIdentityPopulation() { $em = $this->getMockSqliteEntityManager(); $referenceRepository = $this->getMockBuilder('Doctrine\Common\DataFixtures\ProxyReferenceRepository') ->setConstructorArgs(array($em)) ->getMock(); $em->getEventManager()->addEventSubscriber( new ORMReferenceListener($referenceRepository) ); $schemaTool = new SchemaTool($em); $schemaTool->dropSchema(array()); $schemaTool->createSchema(array( $em->getClassMetadata(self::TEST_ENTITY_ROLE) )); $referenceRepository->expects($this->once()) ->method('addReference') ->with('admin-role'); $referenceRepository->expects($this->once()) ->method('getReferenceNames') ->will($this->returnValue(array('admin-role'))); $referenceRepository->expects($this->once()) ->method('setReferenceIdentity') ->with('admin-role', array('id' => 1)); $roleFixture = new TestFixtures\RoleFixture; $roleFixture->setReferenceRepository($referenceRepository); $roleFixture->load($em); } public function testReferenceReconstruction() { $em = $this->getMockSqliteEntityManager(); $referenceRepository = new ProxyReferenceRepository($em); $listener = new ORMReferenceListener($referenceRepository); $em->getEventManager()->addEventSubscriber($listener); $schemaTool = new SchemaTool($em); $schemaTool->dropSchema(array()); $schemaTool->createSchema(array( $em->getClassMetadata(self::TEST_ENTITY_ROLE) )); $roleFixture = new TestFixtures\RoleFixture; $roleFixture->setReferenceRepository($referenceRepository); $roleFixture->load($em); // first test against managed state $ref = $referenceRepository->getReference('admin-role'); $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $ref); // test reference reconstruction from serialized data (was managed) $serializedData = $referenceRepository->serialize(); $proxyReferenceRepository = new ProxyReferenceRepository($em); $proxyReferenceRepository->unserialize($serializedData); $ref = $proxyReferenceRepository->getReference('admin-role'); // before clearing, the reference is not yet a proxy $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $ref); $this->assertInstanceOf('Doctrine\Tests\Common\DataFixtures\TestEntity\Role', $ref); // now test reference reconstruction from identity $em->clear(); $ref = $referenceRepository->getReference('admin-role'); $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $ref); // test reference reconstruction from serialized data (was identity) $serializedData = $referenceRepository->serialize(); $proxyReferenceRepository = new ProxyReferenceRepository($em); $proxyReferenceRepository->unserialize($serializedData); $ref = $proxyReferenceRepository->getReference('admin-role'); $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $ref); } public function testReferenceMultipleEntries() { $em = $this->getMockSqliteEntityManager(); $referenceRepository = new ProxyReferenceRepository($em); $em->getEventManager()->addEventSubscriber(new ORMReferenceListener($referenceRepository)); $schemaTool = new SchemaTool($em); $schemaTool->createSchema(array($em->getClassMetadata(self::TEST_ENTITY_ROLE))); $role = new TestEntity\Role; $role->setName('admin'); $em->persist($role); $referenceRepository->addReference('admin', $role); $referenceRepository->addReference('duplicate', $role); $em->flush(); $em->clear(); $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $referenceRepository->getReference('admin')); $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $referenceRepository->getReference('duplicate')); } } data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/Purger/000077500000000000000000000000001277020517500254145ustar00rootroot00000000000000data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/Purger/MongoDBPurgerTest.php000066400000000000000000000041531277020517500314420ustar00rootroot00000000000000markTestSkipped('Missing doctrine/mongodb-odm'); } $root = dirname(dirname(dirname(dirname(dirname(__DIR__))))); $config = new Configuration(); $config->setProxyDir($root . '/generate/proxies'); $config->setProxyNamespace('Proxies'); $config->setHydratorDir($root . '/generate/hydrators'); $config->setHydratorNamespace('Hydrators'); $config->setMetadataDriverImpl(AnnotationDriver::create(dirname(__DIR__) . '/TestDocument')); AnnotationDriver::registerAnnotationClasses(); $dm = DocumentManager::create(null, $config); if (!$dm->getConnection()->connect()) { $this->markTestSkipped('Unable to connect to MongoDB'); } return $dm; } private function getPurger() { return new MongoDBPurger($this->getDocumentManager()); } public function testPurgeKeepsIndices() { $purger = $this->getPurger(); $dm = $purger->getObjectManager(); $collection = $dm->getDocumentCollection(self::TEST_DOCUMENT_ROLE); $collection->drop(); $this->assertCount(0, $collection->getIndexInfo()); $role = new Role; $role->setName('role'); $dm->persist($role); $dm->flush(); $schema = $dm->getSchemaManager()->ensureDocumentIndexes(self::TEST_DOCUMENT_ROLE); $this->assertCount(2, $collection->getIndexInfo()); $purger->purge(); $this->assertCount(2, $collection->getIndexInfo()); } } data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/Purger/ORMPurgerExcludeTest.php000066400000000000000000000062271277020517500321300ustar00rootroot00000000000000markTestSkipped('Missing pdo_sqlite extension.'); } $dbParams = array('driver' => 'pdo_sqlite', 'memory' => true); $config = Setup::createAnnotationMetadataConfiguration(array(__DIR__.'/../TestPurgeEntity'), true); $em = EntityManager::create($dbParams, $config); $connection = $em->getConnection(); $configuration = $connection->getConfiguration(); $configuration->setFilterSchemaAssetsExpression(null); $schemaTool = new \Doctrine\ORM\Tools\SchemaTool($em); $schemaTool->dropDatabase(); $schemaTool->createSchema(array( $em->getClassMetadata(self::TEST_ENTITY_INCLUDED), $em->getClassMetadata(self::TEST_ENTITY_EXCLUDED) )); $entity = new ExcludedEntity(); $entity->setId(1); $em->persist($entity); $entity = new IncludedEntity(); $entity->setId(1); $em->persist($entity); $em->flush(); return $em; } /** * Execute test purge * * @param string|null $expression * @param array $list */ public function executeTestPurge($expression, array $list){ $em = $this->loadTestData(); $excludedRepository = $em->getRepository(self::TEST_ENTITY_EXCLUDED); $includedRepository = $em->getRepository(self::TEST_ENTITY_INCLUDED); $excluded = $excludedRepository->findAll(); $included = $includedRepository->findAll(); $this->assertGreaterThan(0, count($included)); $this->assertGreaterThan(0, count($excluded)); $connection = $em->getConnection(); $configuration = $connection->getConfiguration(); $configuration->setFilterSchemaAssetsExpression($expression); $purger = new ORMPurger($em,$list); $purger->purge(); $excluded = $excludedRepository->findAll(); $included = $includedRepository->findAll(); $this->assertEquals(0, count($included)); $this->assertGreaterThan(0, count($excluded)); } /** * Test for purge exclusion usig dbal filter expression regexp. * */ public function testPurgeExcludeUsingFilterExpression(){ $this->executeTestPurge('~^(?!ExcludedEntity)~', array()); } /** * Test for purge exclusion usig explicit exclution list. * */ public function testPurgeExcludeUsingList(){ $this->executeTestPurge(null,array('ExcludedEntity')); } }data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/Purger/ORMPurgerTest.php000066400000000000000000000053451277020517500306160ustar00rootroot00000000000000 */ class ORMPurgerTest extends BaseTest { const TEST_ENTITY_USER = 'Doctrine\Tests\Common\DataFixtures\TestEntity\User'; const TEST_ENTITY_USER_WITH_SCHEMA = 'Doctrine\Tests\Common\DataFixtures\TestEntity\UserWithSchema'; const TEST_ENTITY_QUOTED = 'Doctrine\Tests\Common\DataFixtures\TestEntity\Quoted'; public function testGetAssociationTables() { $em = $this->getMockAnnotationReaderEntityManager(); $metadata = $em->getClassMetadata(self::TEST_ENTITY_USER); $platform = $em->getConnection()->getDatabasePlatform(); $purger = new ORMPurger($em); $class = new ReflectionClass('Doctrine\Common\DataFixtures\Purger\ORMPurger'); $method = $class->getMethod('getAssociationTables'); $method->setAccessible(true); $associationTables = $method->invokeArgs($purger, array(array($metadata), $platform)); $this->assertEquals($associationTables[0], 'readers.author_reader'); } public function testGetAssociationTablesQuoted() { $em = $this->getMockAnnotationReaderEntityManager(); $metadata = $em->getClassMetadata(self::TEST_ENTITY_QUOTED); $platform = $em->getConnection()->getDatabasePlatform(); $purger = new ORMPurger($em); $class = new ReflectionClass('Doctrine\Common\DataFixtures\Purger\ORMPurger'); $method = $class->getMethod('getAssociationTables'); $method->setAccessible(true); $associationTables = $method->invokeArgs($purger, array(array($metadata), $platform)); $this->assertEquals($associationTables[0], '"INSERT"'); } public function testTableNameWithSchema() { $isDoctrine25 = (ORMVersion::compare('2.5.0') <= 0); if (!$isDoctrine25) { $this->markTestSkipped('@Table schema attribute is not supported in Doctrine < 2.5.0'); } $em = $this->getMockAnnotationReaderEntityManager(); $metadata = $em->getClassMetadata(self::TEST_ENTITY_USER_WITH_SCHEMA); $platform = $em->getConnection()->getDatabasePlatform(); $purger = new ORMPurger($em); $class = new ReflectionClass('Doctrine\Common\DataFixtures\Purger\ORMPurger'); $method = $class->getMethod('getTableName'); $method->setAccessible(true); $tableName = $method->invokeArgs($purger, array($metadata, $platform)); $this->assertStringStartsWith('test_schema',$tableName); } } data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/ReferenceRepositoryTest.php000066400000000000000000000214141277020517500315210ustar00rootroot00000000000000. */ namespace Doctrine\Tests\Common\DataFixtures; use Doctrine\Common\DataFixtures\ReferenceRepository; use Doctrine\Common\DataFixtures\Event\Listener\ORMReferenceListener; use Doctrine\Common\Persistence\Mapping\ClassMetadata; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Proxy\Proxy; use Doctrine\ORM\Tools\SchemaTool; use Doctrine\ORM\UnitOfWork; use Doctrine\Tests\Common\DataFixtures\TestEntity\Role; use Prophecy\Prophecy\ProphecyInterface; /** * @author Gediminas Morkevicius * @author Manuel Gonalez */ class ReferenceRepositoryTest extends BaseTest { public function testReferenceEntry() { $em = $this->getMockAnnotationReaderEntityManager(); $role = new TestEntity\Role; $role->setName('admin'); $meta = $em->getClassMetadata(Role::class); $meta->getReflectionProperty('id')->setValue($role, 1); $referenceRepo = new ReferenceRepository($em); $this->assertSame($em, $referenceRepo->getManager()); $referenceRepo->addReference('test', $role); $references = $referenceRepo->getReferences(); $this->assertCount(1, $references); $this->assertArrayHasKey('test', $references); $this->assertInstanceOf(Role::class, $references['test']); } public function testReferenceIdentityPopulation() { $em = $this->getMockSqliteEntityManager(); $referenceRepository = $this->getMockBuilder(ReferenceRepository::class) ->setConstructorArgs(array($em)) ->getMock(); $em->getEventManager()->addEventSubscriber( new ORMReferenceListener($referenceRepository) ); $schemaTool = new SchemaTool($em); $schemaTool->dropSchema(array()); $schemaTool->createSchema(array( $em->getClassMetadata(Role::class) )); $referenceRepository->expects($this->once()) ->method('addReference') ->with('admin-role'); $referenceRepository->expects($this->once()) ->method('getReferenceNames') ->will($this->returnValue(array('admin-role'))); $referenceRepository->expects($this->once()) ->method('setReferenceIdentity') ->with('admin-role', array('id' => 1)); $roleFixture = new TestFixtures\RoleFixture; $roleFixture->setReferenceRepository($referenceRepository); $roleFixture->load($em); } public function testReferenceReconstruction() { $em = $this->getMockSqliteEntityManager(); $referenceRepository = new ReferenceRepository($em); $em->getEventManager()->addEventSubscriber( new ORMReferenceListener($referenceRepository) ); $schemaTool = new SchemaTool($em); $schemaTool->dropSchema(array()); $schemaTool->createSchema(array( $em->getClassMetadata(Role::class) )); $roleFixture = new TestFixtures\RoleFixture; $roleFixture->setReferenceRepository($referenceRepository); $roleFixture->load($em); // first test against managed state $ref = $referenceRepository->getReference('admin-role'); $this->assertNotInstanceOf(Proxy::class, $ref); // now test reference reconstruction from identity $em->clear(); $ref = $referenceRepository->getReference('admin-role'); $this->assertInstanceOf(Proxy::class, $ref); } public function testReferenceMultipleEntries() { $em = $this->getMockSqliteEntityManager(); $referenceRepository = new ReferenceRepository($em); $em->getEventManager()->addEventSubscriber(new ORMReferenceListener($referenceRepository)); $schemaTool = new SchemaTool($em); $schemaTool->createSchema(array($em->getClassMetadata(Role::class))); $role = new TestEntity\Role; $role->setName('admin'); $em->persist($role); $referenceRepository->addReference('admin', $role); $referenceRepository->addReference('duplicate', $role); $em->flush(); $em->clear(); $this->assertInstanceOf(Proxy::class, $referenceRepository->getReference('admin')); $this->assertInstanceOf(Proxy::class, $referenceRepository->getReference('duplicate')); } public function testUndefinedReference() { $referenceRepository = new ReferenceRepository($this->getMockSqliteEntityManager()); $this->expectException(\OutOfBoundsException::class); $this->expectExceptionMessage('Reference to: (foo) does not exist'); $referenceRepository->getReference('foo'); } public function testThrowsExceptionAddingDuplicatedReference() { $referenceRepository = new ReferenceRepository($this->getMockSqliteEntityManager()); $referenceRepository->addReference('duplicated_reference', new \stdClass()); $this->expectException(\BadMethodCallException::class); $this->expectExceptionMessage('Reference to: (duplicated_reference) already exists, use method setReference in order to override it'); $referenceRepository->addReference('duplicated_reference', new \stdClass()); } public function testThrowsExceptionTryingToGetWrongReference() { $referenceRepository = new ReferenceRepository($this->getMockSqliteEntityManager()); $this->expectException(\OutOfBoundsException::class); $this->expectExceptionMessage('Reference to: (missing_reference) does not exist'); $referenceRepository->getReference('missing_reference'); } public function testHasIdentityCheck() { $role = new Role(); $referenceRepository = new ReferenceRepository($this->getMockSqliteEntityManager()); $referenceRepository->setReferenceIdentity('entity', $role); $this->assertTrue($referenceRepository->hasIdentity('entity')); $this->assertFalse($referenceRepository->hasIdentity('invalid_entity')); $this->assertEquals(['entity' => $role], $referenceRepository->getIdentities()); } public function testSetReferenceHavingIdentifier() { $em = $this->getMockSqliteEntityManager(); $referenceRepository = new ReferenceRepository($em); $schemaTool = new SchemaTool($em); $schemaTool->dropSchema(array()); $schemaTool->createSchema(array( $em->getClassMetadata(Role::class) )); $role = new Role(); $role->setName('role_name'); $em->persist($role); $em->flush(); $referenceRepository->setReference('entity', $role); $identities = $referenceRepository->getIdentities(); $this->assertCount(1, $identities); $this->assertArrayHasKey('entity', $identities); } public function testGetIdentifierWhenHasNotBeenManagedYetByUnitOfWork() { $role = new Role(); $identitiesExpected = ['id' => 1]; /** @var UnitOfWork | ProphecyInterface $uow */ $uow = $this->prophesize(UnitOfWork::class); $uow->isInIdentityMap($role)->shouldBeCalledTimes(2)->willReturn(true, false); /** @var ClassMetadata $classMetadata */ $classMetadata = $this->prophesize(ClassMetadata::class); $classMetadata->getIdentifierValues($role)->shouldBeCalled()->willReturn($identitiesExpected); /** @var EntityManagerInterface | ProphecyInterface $em */ $em = $this->prophesize(EntityManagerInterface::class); $em->getUnitOfWork()->shouldBeCalled()->willReturn($uow); $em->getClassMetadata(Role::class)->shouldBeCalled()->willReturn($classMetadata); $referenceRepository = new ReferenceRepository($em->reveal()); $referenceRepository->setReference('entity', $role); $identities = $referenceRepository->getIdentities(); $this->assertEquals($identitiesExpected, $identities['entity']); } } data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/Sorter/000077500000000000000000000000001277020517500254265ustar00rootroot00000000000000data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/Sorter/TopologicalSorterTest.php000066400000000000000000000132311277020517500324520ustar00rootroot00000000000000. */ namespace Doctrine\Test\DataFixtures\Sorter; use Doctrine\Common\DataFixtures\Exception\CircularReferenceException; use Doctrine\Common\DataFixtures\Sorter\TopologicalSorter; use Doctrine\ORM\Mapping\ClassMetadata; /** * TopologicalSorter tests. * * Note: When writing tests here consider that a lot of graph * constellations can have many valid orderings, so you may want to * build a graph that has only 1 valid order to simplify your tests * * @author Guilherme Blanco * * @covers \Doctrine\Common\DataFixtures\Sorter\TopologicalSorter */ class TopologicalSorterTest extends \PHPUnit_Framework_TestCase { public function testSuccessSortLinearDependency() { $sorter = new TopologicalSorter(); $node1 = new ClassMetadata(1); $node2 = new ClassMetadata(2); $node3 = new ClassMetadata(3); $node4 = new ClassMetadata(4); $node5 = new ClassMetadata(5); $sorter->addNode('1', $node1); $sorter->addNode('2', $node2); $sorter->addNode('3', $node3); $sorter->addNode('4', $node4); $sorter->addNode('5', $node5); $sorter->addDependency('1', '2'); $sorter->addDependency('2', '3'); $sorter->addDependency('3', '4'); $sorter->addDependency('5', '1'); $sortedList = $sorter->sort(); $correctList = array($node4, $node3, $node2, $node1, $node5); self::assertSame($correctList, $sortedList); } public function testSuccessSortMultiDependency() { $sorter = new TopologicalSorter(); $node1 = new ClassMetadata(1); $node2 = new ClassMetadata(2); $node3 = new ClassMetadata(3); $node4 = new ClassMetadata(4); $node5 = new ClassMetadata(5); $sorter->addNode('1', $node1); $sorter->addNode('2', $node2); $sorter->addNode('3', $node3); $sorter->addNode('4', $node4); $sorter->addNode('5', $node5); $sorter->addDependency('3', '2'); $sorter->addDependency('3', '4'); $sorter->addDependency('3', '5'); $sorter->addDependency('4', '1'); $sorter->addDependency('5', '1'); $sortedList = $sorter->sort(); $correctList = array($node1, $node2, $node4, $node5, $node3); self::assertSame($correctList, $sortedList); } public function testSortCyclicDependency() { $sorter = new TopologicalSorter(); $node1 = new ClassMetadata(1); $node2 = new ClassMetadata(2); $node3 = new ClassMetadata(3); $sorter->addNode('1', $node1); $sorter->addNode('2', $node2); $sorter->addNode('3', $node3); $sorter->addDependency('1', '2'); $sorter->addDependency('2', '3'); $sorter->addDependency('3', '1'); $sortedList = $sorter->sort(); $correctList = array($node3, $node2, $node1); self::assertSame($correctList, $sortedList); $sorter->sort(); } public function testFailureSortCyclicDependency() { $sorter = new TopologicalSorter(false); $node1 = new ClassMetadata(1); $node2 = new ClassMetadata(2); $node3 = new ClassMetadata(3); $sorter->addNode('1', $node1); $sorter->addNode('2', $node2); $sorter->addNode('3', $node3); $sorter->addDependency('1', '2'); $sorter->addDependency('2', '3'); $sorter->addDependency('3', '1'); $this->expectException(CircularReferenceException::class); $sorter->sort(); } public function testNoFailureOnSelfReferencingDependency() { $sorter = new TopologicalSorter(); $node1 = new ClassMetadata(1); $node2 = new ClassMetadata(2); $node3 = new ClassMetadata(3); $node4 = new ClassMetadata(4); $node5 = new ClassMetadata(5); $sorter->addNode('1', $node1); $sorter->addNode('2', $node2); $sorter->addNode('3', $node3); $sorter->addNode('4', $node4); $sorter->addNode('5', $node5); $sorter->addDependency('1', '2'); $sorter->addDependency('1', '1'); $sorter->addDependency('2', '3'); $sorter->addDependency('3', '4'); $sorter->addDependency('5', '1'); $sortedList = $sorter->sort(); $correctList = array($node4, $node3, $node2, $node1, $node5); self::assertSame($correctList, $sortedList); } public function testFailureSortMissingDependency() { $sorter = new TopologicalSorter(); $node1 = new ClassMetadata(1); $sorter->addNode('1', $node1); $sorter->addDependency('1', '2'); $this->expectException(\RuntimeException::class); $sorter->sort(); } } data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/Sorter/VertexTest.php000066400000000000000000000030671277020517500302620ustar00rootroot00000000000000. */ namespace Doctrine\Test\DataFixtures\Sorter; use Doctrine\Common\DataFixtures\Sorter\Vertex; use Doctrine\ORM\Mapping\ClassMetadata; /** * @author Marco Pivetta * * @covers \Doctrine\Common\DataFixtures\Sorter\Vertex */ class VertexTest extends \PHPUnit_Framework_TestCase { public function testNode() { $value = new ClassMetadata('\Sample\Entity'); $node = new Vertex($value); self::assertSame($value, $node->value); self::assertSame(Vertex::NOT_VISITED, $node->state); self::assertSame([], $node->dependencyList); } } data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/TestDocument/000077500000000000000000000000001277020517500265665ustar00rootroot00000000000000data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/TestDocument/Role.php000066400000000000000000000007611277020517500302040ustar00rootroot00000000000000id; } public function setName($name) { $this->name = $name; } public function getName() { return $this->name; } } data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/TestEntity/000077500000000000000000000000001277020517500262645ustar00rootroot00000000000000data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/TestEntity/Quoted.php000066400000000000000000000011521277020517500302350ustar00rootroot00000000000000id; } public function setName($name) { $this->name = $name; } public function getName() { return $this->name; } }data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/TestEntity/User.php000066400000000000000000000043561277020517500277230ustar00rootroot00000000000000id = $id; } public function setCode($code) { $this->code = $code; } public function setPassword($password) { $this->password = md5($password); } public function getPassword() { return $this->password; } public function setEmail($email) { $this->email = $email; } public function getEmail() { return $this->email; } public function setRole(Role $role) { $this->role = $role; } public function getRole() { return $this->role; } /** * @return User[] */ public function getReaders() { return $this->readers; } /** * @param User[] $readers * @return User */ public function setReaders($readers) { $this->readers = $readers; return $this; } /** * @return User[] */ public function getAuthors() { return $this->authors; } /** * @param User[] $authors * @return User */ public function setAuthors($authors) { $this->authors = $authors; return $this; } } data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/TestEntity/UserWithSchema.php000066400000000000000000000044701277020517500316750ustar00rootroot00000000000000id = $id; } public function setCode($code) { $this->code = $code; } public function setPassword($password) { $this->password = md5($password); } public function getPassword() { return $this->password; } public function setEmail($email) { $this->email = $email; } public function getEmail() { return $this->email; } public function setRole(Role $role) { $this->role = $role; } public function getRole() { return $this->role; } /** * @return User[] */ public function getReaders() { return $this->readers; } /** * @param User[] $readers * @return User */ public function setReaders($readers) { $this->readers = $readers; return $this; } /** * @return User[] */ public function getAuthors() { return $this->authors; } /** * @param User[] $authors * @return User */ public function setAuthors($authors) { $this->authors = $authors; return $this; } } data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/TestFixtures/000077500000000000000000000000001277020517500266215ustar00rootroot00000000000000data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/TestFixtures/MyFixture1.php000066400000000000000000000003611277020517500313470ustar00rootroot00000000000000referenceRepository = $referenceRepository; } public function load(ObjectManager $manager) { $adminRole = new Role(); $adminRole->setName('admin'); $manager->persist($adminRole); $this->referenceRepository->addReference('admin-role', $adminRole); $manager->flush(); } } data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/TestFixtures/UserFixture.php000066400000000000000000000012631277020517500316210ustar00rootroot00000000000000setId(4); $admin->setCode('007'); $admin->setEmail('admin@example.com'); $admin->setPassword('secret'); $role = $this->getReference('admin-role'); $admin->setRole($role); $manager->persist($admin); $manager->flush(); $this->addReference('admin', $admin); } } data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/TestPurgeEntity/000077500000000000000000000000001277020517500272675ustar00rootroot00000000000000data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/TestPurgeEntity/ExcludedEntity.php000066400000000000000000000005461277020517500327370ustar00rootroot00000000000000id = $id; } public function getId() { return $this->id; } } data-fixtures-1.2.2/tests/Doctrine/Tests/Common/DataFixtures/TestPurgeEntity/IncludedEntity.php000066400000000000000000000005451277020517500327300ustar00rootroot00000000000000id = $id; } public function getId() { return $this->id; } }data-fixtures-1.2.2/tests/Doctrine/Tests/Mock/000077500000000000000000000000001277020517500212065ustar00rootroot00000000000000data-fixtures-1.2.2/tests/Doctrine/Tests/Mock/Node.php000066400000000000000000000024521277020517500226070ustar00rootroot00000000000000. */ namespace Doctrine\Tests\Mock; /** * Node. * * @author Guilherme Blanco */ class Node { /** * @var mixed */ public $value; /** * Constructor. * * @param mixed $value */ public function __construct($value) { $this->value = $value; } }