getEventManager() public method

Gets the EventManager used by the EntityManager.
public getEventManager ( ) : Doctrine\Common\EventManager
return Doctrine\Common\EventManager
 protected function setUp()
 {
     AnnotationRegistry::registerLoader('class_exists');
     $conn = DriverManager::getConnection(array('driver' => 'pdo_sqlite', 'memory' => true));
     $this->em = $this->_getTestEntityManager($conn);
     $reader = new SimpleAnnotationReader();
     $reader->addNamespace('Bazinga\\Bundle\\GeocoderBundle\\Mapping\\Annotations');
     $reader->addNamespace('Doctrine\\ORM\\Mapping');
     $driver = new AnnotationDriver($reader);
     $geocoder = new GoogleMaps(new CurlHttpAdapter());
     $this->listener = new GeocoderListener($geocoder, $driver);
     $this->em->getEventManager()->addEventSubscriber($this->listener);
     $sm = new SchemaTool($this->em);
     $sm->createSchema(array($this->em->getClassMetadata('Bazinga\\Bundle\\GeocoderBundle\\Tests\\Doctrine\\ORM\\Dummy')));
 }
Exemplo n.º 2
1
 public function __construct(EntityManager $enm, Writer $logger)
 {
     $this->evm = $enm->getEventManager();
     //Unused, for now
     $this->enm = $enm;
     $this->logger = $logger;
     $this->connection = $enm->getConnection();
     $enm->getConnection()->getConfiguration()->setSQLLogger($this);
 }
 /**
  * Constructs a new dispatcher instance
  *
  * @param EntityManager $em
  * @param array $hints
  */
 public function __construct(EntityManager $em, array $hints = array())
 {
     $this->entityManager = $em;
     $this->metadataFactory = $em->getMetadataFactory();
     $this->eventManager = $this->entityManager->getEventManager();
     $this->hints = $hints;
 }
 /**
  * {@inheritDoc}.
  */
 protected function initialize()
 {
     $this->driver = $this->em->getConfiguration()->getMetadataDriverImpl();
     $this->targetPlatform = $this->em->getConnection()->getDatabasePlatform();
     $this->evm = $this->em->getEventManager();
     $this->initialized = true;
 }
Exemplo n.º 5
0
 /**
  *
  * @param Environment $environment
  * @param EventManager $eventManager
  * @param string $driver
  * @param string $username
  * @param string $password
  * @param string $dbname
  * @param string $host
  * @param int $port
  */
 public function __construct(Environment $environment, EventManager $eventManager, $driver, $username, $password, $dbname, $host, $port)
 {
     $paths = array();
     $eventHandler = new EventHandler($eventManager);
     $dbParams = array('driver' => $driver, 'user' => $username, 'password' => $password, 'dbname' => $dbname, 'host' => $host, 'charset' => 'utf8');
     $config = Setup::createAnnotationMetadataConfiguration($paths, $environment->isDebug(), $environment->getCachePath());
     $this->entityManager = EntityManager::create($dbParams, $config);
     $this->entityManager->getEventManager()->addEventListener(array('onFlush'), $eventHandler);
     $this->entityManager->getEventManager()->addEventListener(array('postFlush'), $eventHandler);
 }
 public function setUp()
 {
     $this->listener = new AttachEntityListenersListener();
     $driver = $this->createAnnotationDriver();
     $this->em = $this->_getTestEntityManager();
     $evm = $this->em->getEventManager();
     $this->factory = new ClassMetadataFactory();
     $evm->addEventListener(Events::loadClassMetadata, $this->listener);
     $this->em->getConfiguration()->setMetadataDriverImpl($driver);
     $this->factory->setEntityManager($this->em);
 }
Exemplo n.º 7
0
 private function initializeEntityManager()
 {
     if ($this->configuration->get('cache')) {
         $memcached = $this->container->get('memcached');
         $cache = new MemcachedCache();
         $cache->setMemcached($memcached);
     } else {
         $cache = null;
     }
     $config = Setup::createAnnotationMetadataConfiguration([ROOT_DIR . "/src"], true, ROOT_DIR . '/cache/doctrine/proxy', $cache);
     $connection = ['driver' => $this->configuration->get('driver'), 'user' => $this->configuration->get('user'), 'password' => $this->configuration->get('password'), 'dbname' => $this->configuration->get('dbname'), 'host' => $this->configuration->get('host')];
     $this->entityManager = EntityManager::create($connection, $config);
     $eventManager = $this->entityManager->getEventManager();
     $eventManager->addEventSubscriber(new DoctrineSubscriber());
 }
 /**
  * Get update queries.
  *
  * @return string[]
  */
 protected function getUpdateQueries()
 {
     $schema = new SchemaTool($this->em);
     $metadatas = $this->em->getMetadataFactory()->getAllMetadata();
     // Insure the name of altered tables are quoted according to the platform
     $this->em->getEventManager()->addEventListener(Events::onSchemaAlterTable, $this);
     $sqls = $schema->getUpdateSchemaSql($metadatas, true);
     return $sqls;
 }
 protected function disableLoggableExtension()
 {
     $instance = null;
     foreach ($this->em->getEventManager()->getListeners() as $event => $listeners) {
         foreach ($listeners as $hash => $listener) {
             if ($listener instanceof LoggableListener) {
                 $instance = $listener;
                 break 2;
             }
         }
     }
     if ($instance) {
         $evm = $this->em->getEventManager();
         $evm->removeEventListener(['onFlush'], $instance);
         $evm->removeEventListener(['postPersist'], $instance);
         $evm->removeEventListener(['loadClassMetadata'], $instance);
     }
 }
 public function setUp()
 {
     $config = new \Doctrine\ORM\Configuration();
     $config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache());
     $config->setQueryCacheImpl(new \Doctrine\Common\Cache\ArrayCache());
     $config->setProxyDir(__DIR__ . '/Proxy');
     $config->setProxyNamespace('DoctrineExtensions\\Taggable\\Proxies');
     $driverImpl = new \Doctrine\ORM\Mapping\Driver\DriverChain();
     $driverImpl->addDriver(new \Doctrine\ORM\Mapping\Driver\XmlDriver(__DIR__ . '/../../../../metadata'), 'DoctrineExtensions\\Taggable\\Entity');
     $driverImpl->addDriver($config->newDefaultAnnotationDriver(), 'Tests\\DoctrineExtensions\\Taggable\\Fixtures');
     $config->setMetadataDriverImpl($driverImpl);
     $this->em = \Doctrine\ORM\EntityManager::create(array('driver' => 'pdo_sqlite', 'memory' => true), $config);
     $schemaTool = new \Doctrine\ORM\Tools\SchemaTool($this->em);
     $schemaTool->dropSchema(array());
     $schemaTool->createSchema(array($this->em->getClassMetadata('DoctrineExtensions\\Taggable\\Entity\\Tag'), $this->em->getClassMetadata('DoctrineExtensions\\Taggable\\Entity\\Tagging'), $this->em->getClassMetadata('Tests\\DoctrineExtensions\\Taggable\\Fixtures\\Article')));
     $this->manager = new TagManager($this->em);
     $this->em->getEventManager()->addEventSubscriber(new TagListener($this->manager));
 }
Exemplo n.º 11
0
 public function setUp()
 {
     $this->checkEnviroment();
     $this->manager = DoctrineTestHelper::createTestEntityManager();
     $this->manager->getEventManager()->addEventSubscriber(new TreeListener());
     $this->managerRegistry = $this->createRegistryMock('default', $this->manager);
     $this->formFactory = $this->createFormFactoryBuilder()->getFormFactory();
     $schemaTool = new SchemaTool($this->manager);
     $classes = array($this->manager->getClassMetadata(self::POST_CLASS), $this->manager->getClassMetadata(self::CATEGORY_CLASS), $this->manager->getClassMetadata(self::SECTION_CLASS));
     try {
         $schemaTool->dropSchema($classes);
     } catch (\Exception $e) {
     }
     try {
         $schemaTool->createSchema($classes);
     } catch (\Exception $e) {
     }
 }
Exemplo n.º 12
0
 /**
  * Initiates a row-by-row hydration.
  *
  * @param object $stmt
  * @param object $resultSetMapping
  * @param array  $hints
  *
  * @return IterableResult
  */
 public function iterate($stmt, $resultSetMapping, array $hints = array())
 {
     $this->_stmt = $stmt;
     $this->_rsm = $resultSetMapping;
     $this->_hints = $hints;
     $evm = $this->_em->getEventManager();
     $evm->addEventListener(array(Events::onClear), $this);
     $this->prepare();
     return new IterableResult($this);
 }
 function let(UserContext $userContext, EntityManager $em, ClassMetadata $classMetadata, EventManager $eventManager, TreeListener $treeListener, Nested $strategy)
 {
     $classMetadata->name = 'category';
     $userContext->getCurrentLocaleCode()->willReturn('en_US');
     $em->getEventManager()->willReturn($eventManager);
     $eventManager->getListeners()->willReturn([[$treeListener]]);
     $treeListener->getStrategy(Argument::cetera())->willReturn($strategy);
     $treeListener->getConfiguration(Argument::cetera())->willReturn(['parent' => 'parent', 'left' => 'left']);
     $this->beConstructedWith($userContext, $em, $classMetadata);
 }
Exemplo n.º 14
0
 public function carregar()
 {
     $dados = \controlador\Facil::$dadosIni['doctrine'];
     $this->obterLoaders($dados);
     $this->obterConfiguracao($dados);
     $this->obterConexao();
     // Create EntityManager
     $this->em = EntityManager::create($this->connection, $this->config);
     if (\controlador\Facil::$dadosIni['l10n']['charset'] == 'UTF-8') {
         $this->em->getEventManager()->addEventSubscriber(new \Doctrine\DBAL\Event\Listeners\MysqlSessionInit('utf8', 'utf8_unicode_ci'));
     }
 }
Exemplo n.º 15
0
 public function setUpEntityManager(EntityManager $entityManager, callable $aclLocator)
 {
     if ($this->securityIdentityClass === null) {
         throw new \RuntimeException('The security identity class must be configured: call ->setSecurityIdentityClass("...")');
     }
     $evm = $entityManager->getEventManager();
     // Configure which entity implements the SecurityIdentityInterface
     $rtel = new ResolveTargetEntityListener();
     $rtel->addResolveTargetEntity('MyCLabs\\ACL\\Model\\SecurityIdentityInterface', $this->securityIdentityClass, []);
     $evm->addEventListener(Events::loadClassMetadata, $rtel);
     // Register the metadata loader
     $evm->addEventListener(Events::loadClassMetadata, $this->metadataLoader);
     // Register the listener that looks for new resources
     $evm->addEventSubscriber(new EntityResourcesListener($aclLocator));
 }
Exemplo n.º 16
0
 /**
  * Start Doctrine entity manager
  *
  * @return void
  */
 public function startEntityManager()
 {
     // Initialize DB connection and entity manager
     static::$em = \Doctrine\ORM\EntityManager::create($this->getDSN(), $this->configuration);
     static::registerCustomTypes(static::$em);
     // Bind events
     $events = array(\Doctrine\ORM\Events::loadClassMetadata);
     if (static::$cacheDriver) {
         // Bind cache checkers
         $events[] = \Doctrine\ORM\Events::postPersist;
         $events[] = \Doctrine\ORM\Events::postUpdate;
         $events[] = \Doctrine\ORM\Events::postRemove;
     }
     static::$em->getEventManager()->addEventListener($events, $this);
 }
 function let(EntityManager $em, Connection $connection, Statement $statement, ClassMetadata $classMetadata, EventManager $eventManager, TreeListener $treeListener, Nested $strategy, \ReflectionProperty $property)
 {
     $connection->prepare(Argument::any())->willReturn($statement);
     $em->getClassMetadata(Argument::any())->willReturn($classMetadata);
     $classMetadata->name = 'channel';
     $classMetadata->getReflectionProperty(Argument::any())->willReturn($property);
     $em->getConnection()->willReturn($connection);
     $em->getEventManager()->willReturn($eventManager);
     $em->getClassMetadata()->willReturn($classMetadata);
     $strategy->getName()->willReturn(Strategy::NESTED);
     $strategy->setNodePosition(Argument::cetera())->willReturn(null);
     $treeListener->getStrategy(Argument::cetera())->willReturn($strategy);
     $configuration = ['parent' => 'parent', 'left' => 'left'];
     $treeListener->getConfiguration(Argument::cetera())->willReturn($configuration);
     $eventManager->getListeners()->willReturn([[$treeListener]]);
     $this->beConstructedWith($em, $classMetadata);
 }
Exemplo n.º 18
0
 /**
  * Start Doctrine entity manager
  *
  * @return void
  */
 public function startEntityManager()
 {
     // Initialize DB connection and entity manager
     static::$em = \Doctrine\ORM\EntityManager::create($this->getDSN(), $this->configuration);
     if (\XLite\Core\Profiler::getInstance()->enabled) {
         static::$em->getConnection()->getConfiguration()->setSQLLogger(\XLite\Core\Profiler::getInstance());
     }
     static::registerCustomTypes(static::$em);
     // Set charset for DB connection
     $this->setCharset();
     // Bind events
     $events = array(\Doctrine\ORM\Events::loadClassMetadata);
     if (static::$cacheDriver) {
         // Bind cache chekers
         $events[] = \Doctrine\ORM\Events::postPersist;
         $events[] = \Doctrine\ORM\Events::postUpdate;
         $events[] = \Doctrine\ORM\Events::postRemove;
     }
     static::$em->getEventManager()->addEventListener($events, $this);
 }
 /**
  * Get the currently used TranslatableListener
  *
  * @throws \Gedmo\Exception\RuntimeException - if listener is not found
  * @return \Gedmo\Translatable\TranslatableListener
  */
 private function getTranslatableListener()
 {
     if (!$this->listener) {
         foreach ($this->em->getEventManager()->getListeners() as $event => $listeners) {
             foreach ($listeners as $hash => $listener) {
                 if ($listener instanceof TranslatableListener) {
                     $this->listener = $listener;
                     break;
                 }
             }
             if ($this->listener) {
                 break;
             }
         }
         if (is_null($this->listener)) {
             throw new \Gedmo\Exception\RuntimeException('The translation listener could not be found');
         }
     }
     return $this->listener;
 }
 /**
  * Executes update.
  * 
  * @param \Doctrine\ORM\Event\LifecycleEventArgs $eventArgs
  * @param    object    $entity
  * @param     array $identifier The update criteria. An associative array containing column-value pairs.
  * @return integer The number of affected rows.
  * @access private
  *
  * @author Etienne de Longeaux <*****@*****.**>
  */
 public function executeUpdate($eventArgs, $entity, $Identifier)
 {
     $this->_em = $eventArgs->getEntityManager();
     $this->_evm = $this->_em->getEventManager();
     $this->_conn = $this->_em->getConnection();
     $this->_platform = $this->_conn->getDatabasePlatform();
     $this->_class = $this->_em->getClassMetadata(get_class($entity));
     $this->_entityName = $this->_class->name;
     $this->_reflFields = $this->_class->reflFields;
     //$data = $this->_prepareData($entity, true);
     //foreach($Identifier as $key=>$value)
     //    unset($data[$key]);
     $data = $this->_prepareUpdateData($entity);
     $id = $this->_em->getUnitOfWork()->getEntityIdentifier($entity);
     $tableName = $this->getOwningTable();
     if (isset($data[$tableName]) && $data[$tableName]) {
         return $this->_conn->update($this->getOwningTable(), $data, $Identifier);
     } else {
         return false;
     }
 }
 /**
  * This method should be called in your repository __construct().
  * Example:
  *
  * class MyTreeRepository extends EntityRepository
  * {
  *     use NestedTreeRepository; // or ClosureTreeRepository, or MaterializedPathRepository.
  *
  *     public function __construct(EntityManager $em, ClassMetadata $class)
  *     {
  *         parent::__construct($em, $class);
  *
  *         $this->initializeTreeRepository($em, $class);
  *     }
  *
  *     // ...
  * }
  *
  */
 public function initializeTreeRepository(EntityManager $em, ClassMetadata $class)
 {
     $treeListener = null;
     foreach ($em->getEventManager()->getListeners() as $listeners) {
         foreach ($listeners as $listener) {
             if ($listener instanceof TreeListener) {
                 $treeListener = $listener;
                 break;
             }
         }
         if ($treeListener) {
             break;
         }
     }
     if (null === $treeListener) {
         throw new \Gedmo\Exception\InvalidMappingException('Tree listener was not found on your entity manager, it must be hooked into the event manager');
     }
     $this->listener = $treeListener;
     if (!$this->validate()) {
         throw new \Gedmo\Exception\InvalidMappingException('This repository cannot be used for tree type: ' . $treeListener->getStrategy($em, $class->name)->getName());
     }
     $this->repoUtils = new RepositoryUtils($this->getEntityManager(), $this->getClassMetadata(), $this->listener, $this);
 }
Exemplo n.º 22
0
 /**
  * @param FormEvent $event
  */
 public function postSubmit(FormEvent $event)
 {
     if (null === ($config = $this->getPropertyConfig($event))) {
         return;
     }
     /** @var ResourceObjectInterface $resource */
     $resource = $event->getData();
     if ($resource instanceof ResourceObjectInterface) {
         if ($resource && ($file = $resource->getFile()) instanceof UploadedFile) {
             /** @var UploadedFile $file */
             if (!is_file($file->getRealPath())) {
                 $event->getForm()->addError(new FormError(sprintf('Error uploading file the file %s.', $file->getClientOriginalName())));
                 return;
             }
             $context = $event->getForm()->getParent()->getData();
             $property = $event->getForm()->getName();
             $updater = new ResourceLoaderListener($this->loader, $context, $property, $resource->getFile());
             $resource->setUpdated(new \DateTime());
             //force update
             //save initial info, the loader update this information later (postPersist),
             //is required to avoid save empty record
             if (!$resource->getId()) {
                 $resource->setName($file->getClientOriginalName());
                 $resource->setMapping($config->getMapping());
                 if (!$resource->getMapping()) {
                     throw new \RuntimeException('The mapping information is required to upload a resource.');
                 }
                 if (isset($this->config['mappings'][$config->getMapping()]['location'])) {
                     $resource->setLocation($this->config['mappings'][$config->getMapping()]['location']);
                 } else {
                     $resource->setLocation($this->config['default_location']);
                 }
             }
             $this->em->getEventManager()->addEventListener([Events::postPersist, Events::preUpdate], $updater);
         }
     }
 }
Exemplo n.º 23
0
 /**
  * From a given set of metadata classes this method creates a Schema instance.
  *
  * @param array $classes
  * @return Schema
  */
 public function getSchemaFromMetadata(array $classes)
 {
     // Reminder for processed classes, used for hierarchies
     $processedClasses = array();
     $eventManager = $this->em->getEventManager();
     $schemaManager = $this->em->getConnection()->getSchemaManager();
     $metadataSchemaConfig = $schemaManager->createSchemaConfig();
     $metadataSchemaConfig->setExplicitForeignKeyIndexes(false);
     $schema = new Schema(array(), array(), $metadataSchemaConfig);
     foreach ($classes as $class) {
         if ($this->processingNotRequired($class, $processedClasses)) {
             continue;
         }
         $table = $schema->createTable($this->quoteStrategy->getTableName($class, $this->platform));
         $columns = array();
         // table columns
         if ($class->isInheritanceTypeSingleTable()) {
             $columns = $this->_gatherColumns($class, $table);
             $this->_gatherRelationsSql($class, $table, $schema);
             // Add the discriminator column
             $this->addDiscriminatorColumnDefinition($class, $table);
             // Aggregate all the information from all classes in the hierarchy
             foreach ($class->parentClasses as $parentClassName) {
                 // Parent class information is already contained in this class
                 $processedClasses[$parentClassName] = true;
             }
             foreach ($class->subClasses as $subClassName) {
                 $subClass = $this->em->getClassMetadata($subClassName);
                 $this->_gatherColumns($subClass, $table);
                 $this->_gatherRelationsSql($subClass, $table, $schema);
                 $processedClasses[$subClassName] = true;
             }
         } else {
             if ($class->isInheritanceTypeJoined()) {
                 // Add all non-inherited fields as columns
                 $pkColumns = array();
                 foreach ($class->fieldMappings as $fieldName => $mapping) {
                     if (!isset($mapping['inherited'])) {
                         $columnName = $this->quoteStrategy->getColumnName($mapping['fieldName'], $class, $this->platform);
                         $this->_gatherColumn($class, $mapping, $table);
                         if ($class->isIdentifier($fieldName)) {
                             $pkColumns[] = $columnName;
                         }
                     }
                 }
                 $this->_gatherRelationsSql($class, $table, $schema);
                 // Add the discriminator column only to the root table
                 if ($class->name == $class->rootEntityName) {
                     $this->addDiscriminatorColumnDefinition($class, $table);
                 } else {
                     // Add an ID FK column to child tables
                     /* @var \Doctrine\ORM\Mapping\ClassMetadata $class */
                     $idMapping = $class->fieldMappings[$class->identifier[0]];
                     $this->_gatherColumn($class, $idMapping, $table);
                     $columnName = $this->quoteStrategy->getColumnName($class->identifier[0], $class, $this->platform);
                     // TODO: This seems rather hackish, can we optimize it?
                     $table->getColumn($columnName)->setAutoincrement(false);
                     $pkColumns[] = $columnName;
                     // Add a FK constraint on the ID column
                     $table->addUnnamedForeignKeyConstraint($this->quoteStrategy->getTableName($this->em->getClassMetadata($class->rootEntityName), $this->platform), array($columnName), array($columnName), array('onDelete' => 'CASCADE'));
                 }
                 $table->setPrimaryKey($pkColumns);
             } else {
                 if ($class->isInheritanceTypeTablePerClass()) {
                     throw ORMException::notSupported();
                 } else {
                     $this->_gatherColumns($class, $table);
                     $this->_gatherRelationsSql($class, $table, $schema);
                 }
             }
         }
         $pkColumns = array();
         foreach ($class->identifier as $identifierField) {
             if (isset($class->fieldMappings[$identifierField])) {
                 $pkColumns[] = $this->quoteStrategy->getColumnName($identifierField, $class, $this->platform);
             } else {
                 if (isset($class->associationMappings[$identifierField])) {
                     /* @var $assoc \Doctrine\ORM\Mapping\OneToOne */
                     $assoc = $class->associationMappings[$identifierField];
                     foreach ($assoc['joinColumns'] as $joinColumn) {
                         $pkColumns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform);
                     }
                 }
             }
         }
         if (!$table->hasIndex('primary')) {
             $table->setPrimaryKey($pkColumns);
         }
         if (isset($class->table['indexes'])) {
             foreach ($class->table['indexes'] as $indexName => $indexData) {
                 $table->addIndex($indexData['columns'], is_numeric($indexName) ? null : $indexName);
             }
         }
         if (isset($class->table['uniqueConstraints'])) {
             foreach ($class->table['uniqueConstraints'] as $indexName => $indexData) {
                 $table->addUniqueIndex($indexData['columns'], is_numeric($indexName) ? null : $indexName);
             }
         }
         if (isset($class->table['options'])) {
             foreach ($class->table['options'] as $key => $val) {
                 $table->addOption($key, $val);
             }
         }
         $processedClasses[$class->name] = true;
         if ($class->isIdGeneratorSequence() && $class->name == $class->rootEntityName) {
             $seqDef = $class->sequenceGeneratorDefinition;
             $quotedName = $this->quoteStrategy->getSequenceName($seqDef, $class, $this->platform);
             if (!$schema->hasSequence($quotedName)) {
                 $schema->createSequence($quotedName, $seqDef['allocationSize'], $seqDef['initialValue']);
             }
         }
         if ($eventManager->hasListeners(ToolEvents::postGenerateSchemaTable)) {
             $eventManager->dispatchEvent(ToolEvents::postGenerateSchemaTable, new GenerateSchemaTableEventArgs($class, $schema, $table));
         }
     }
     if (!$this->platform->supportsSchemas() && !$this->platform->canEmulateSchemas()) {
         $schema->visit(new RemoveNamespacedAssets());
     }
     if ($eventManager->hasListeners(ToolEvents::postGenerateSchema)) {
         $eventManager->dispatchEvent(ToolEvents::postGenerateSchema, new GenerateSchemaEventArgs($this->em, $schema));
     }
     return $schema;
 }
Exemplo n.º 24
0
 /**
  * Refreshes a managed entity.
  *
  * @param array $id The identifier of the entity as an associative array from
  *                  column or field names to values.
  * @param object $entity The entity to refresh.
  */
 public function refresh(array $id, $entity)
 {
     $sql = $this->_getSelectEntitiesSQL($id);
     list($params, $types) = $this->expandParameters($id);
     $stmt = $this->_conn->executeQuery($sql, $params, $types);
     $hydrator = $this->_em->newHydrator(Query::HYDRATE_OBJECT);
     $hydrator->hydrateAll($stmt, $this->_rsm, array(Query::HINT_REFRESH => true));
     if (isset($this->_class->lifecycleCallbacks[Events::postLoad])) {
         $this->_class->invokeLifecycleCallbacks(Events::postLoad, $entity);
     }
     $evm = $this->_em->getEventManager();
     if ($evm->hasListeners(Events::postLoad)) {
         $evm->dispatchEvent(Events::postLoad, new LifecycleEventArgs($entity, $this->_em));
     }
 }
Exemplo n.º 25
0
 /**
  * Initializes a new UnitOfWork instance, bound to the given EntityManager.
  *
  * @param \Doctrine\ORM\EntityManager $em
  */
 public function __construct(EntityManager $em)
 {
     $this->em = $em;
     $this->evm = $em->getEventManager();
     $this->listenersInvoker = new ListenersInvoker($em);
     $this->hasCache = $em->getConfiguration()->isSecondLevelCacheEnabled();
 }
Exemplo n.º 26
0
 /**
  * Initializes a new UnitOfWork instance, bound to the given EntityManager.
  *
  * @param Doctrine\ORM\EntityManager $em
  */
 public function __construct(EntityManager $em)
 {
     $this->em = $em;
     $this->evm = $em->getEventManager();
 }
Exemplo n.º 27
0
 private function insertOneRegistration(\Pimple $DI, EntityManager $em, User $user, \collection $collection, $when, $name)
 {
     $em->getEventManager()->removeEventSubscriber(new TimestampableListener());
     $registration = new Registration();
     $registration->setCollection($collection);
     $registration->setUser($user);
     $registration->setUpdated(new \DateTime($when));
     $registration->setCreated(new \DateTime($when));
     $em->persist($registration);
     $em->flush();
     $em->getEventManager()->addEventSubscriber(new TimestampableListener());
     $DI[$name] = $registration;
 }
Exemplo n.º 28
0
 /**
  * Move the node to the new position and change level by {$levelDiff}
  * @param Node\DoctrineNode $node
  * @param int $pos
  * @param int $levelDiff
  */
 public function move(Node\NodeInterface $node, $pos, $levelDiff, $undoMove = false)
 {
     if (!$this->locked) {
         //\Log::info('Should lock before changes');
     }
     $tableName = $this->tableName;
     $arrayHelper = $this->arrayHelper;
     $self = $this;
     // Calculate the old position to rollback to in case of some issue
     $oldPosition = $node->getLeftValue();
     if ($pos < $oldPosition) {
         $oldPosition = $node->getRightValue() + 1;
     }
     if (!$node instanceof Node\DoctrineNode) {
         throw new Exception\WrongInstance($node, 'Node\\DoctrineNode');
     }
     // Transactional because need to rollback in case of trigger failure
     $this->entityManager->transactional(function (EntityManager $entityManager) use($node, $pos, $levelDiff, $tableName, $arrayHelper, $self) {
         $left = $node->getLeftValue();
         $right = $node->getRightValue();
         $spaceUsed = $right - $left + 1;
         $moveA = null;
         $moveB = null;
         $a = null;
         $b = null;
         $min = null;
         $max = null;
         if ($pos > $left) {
             $a = $right + 1;
             $b = $pos - 1;
             $moveA = $pos - $left - $spaceUsed;
             $moveB = -$spaceUsed;
             $min = $left;
             $max = $pos - 1;
         } else {
             $a = $pos;
             $b = $left - 1;
             $moveA = $pos - $left;
             $moveB = $spaceUsed;
             $min = $pos;
             $max = $right;
         }
         //			// NB! It's important to set "level" before "left" for MySQL!
         //			$dql = "UPDATE {$className} e
         //					SET e.level = e.level + IF(e.left BETWEEN {$left} AND {$right}, {$levelDiff}, 0),
         //						e.left = e.left + IF(e.left BETWEEN {$left} AND {$right}, {$moveA}, IF(e.left BETWEEN {$a} AND {$b}, {$moveB}, 0)),
         //						e.right = e.right + IF(e.right BETWEEN {$left} AND {$right}, {$moveA}, IF(e.right BETWEEN {$a} AND {$b}, {$moveB}, 0))
         //					WHERE (e.left BETWEEN {$min} AND {$max}
         //						OR e.right BETWEEN {$min} AND {$max})";
         //
         //			$dql .= $self->getAdditionalCondition('AND');
         //
         //			$query = $entityManager->createQuery($dql);
         //			$query->execute();
         $sql = "UPDATE {$tableName}\n\t\t\t\t\tSET lvl = lvl + IF(lft BETWEEN {$left} AND {$right}, {$levelDiff}, 0),\n\t\t\t\t\t\tlft = lft + IF(lft BETWEEN {$left} AND {$right}, {$moveA}, IF(lft BETWEEN {$a} AND {$b}, {$moveB}, 0)),\n\t\t\t\t\t\trgt = rgt + IF(rgt BETWEEN {$left} AND {$right}, {$moveA}, IF(rgt BETWEEN {$a} AND {$b}, {$moveB}, 0))\n\t\t\t\t\tWHERE (lft BETWEEN {$min} AND {$max}\n\t\t\t\t\t\tOR rgt BETWEEN {$min} AND {$max})";
         $sql .= $self->getAdditionalConditionSql('AND');
         $entityManager->getConnection()->exec($sql);
         // Change node parameters locally as well
         // TODO: how to rollback these changes if nested set post move trigger fails?
         $arrayHelper->move($node, $pos, $levelDiff);
     });
     // Trigger post move event. Only after transaction is commited because
     // public schema must update it's stuff as well
     try {
         $masterNode = $node->getMasterNode();
         $eventArgs = new Event\NestedSetEventArgs($masterNode, $this->entityManager);
         $this->entityManager->getEventManager()->dispatchEvent(Event\NestedSetEvents::nestedSetPostMove, $eventArgs);
     } catch (\Exception $e) {
         //TODO: new pages should be removed
         // Should not happen
         if ($undoMove) {
             throw $e;
         }
         // Undo move
         $this->move($node, $oldPosition, -$levelDiff, true);
         throw $e;
     }
 }
Exemplo n.º 29
0
 /**
  * Refreshes a managed entity.
  * 
  * @param array $id The identifier of the entity as an associative array from
  *                  column or field names to values.
  * @param object $entity The entity to refresh.
  */
 public function refresh(array $id, $entity)
 {
     $sql = $this->_getSelectEntitiesSQL($id);
     list($params, $types) = $this->expandParameters($id);
     $stmt = $this->_conn->executeQuery($sql, $params, $types);
     $result = $stmt->fetch(PDO::FETCH_ASSOC);
     $stmt->closeCursor();
     $metaColumns = array();
     $newData = array();
     // Refresh simple state
     foreach ($result as $column => $value) {
         $column = $this->_resultColumnNames[$column];
         if (isset($this->_class->fieldNames[$column])) {
             $fieldName = $this->_class->fieldNames[$column];
             $newValue = $this->_conn->convertToPHPValue($value, $this->_class->fieldMappings[$fieldName]['type']);
             $this->_class->reflFields[$fieldName]->setValue($entity, $newValue);
             $newData[$fieldName] = $newValue;
         } else {
             $metaColumns[$column] = $value;
         }
     }
     // Refresh associations
     foreach ($this->_class->associationMappings as $field => $assoc) {
         $value = $this->_class->reflFields[$field]->getValue($entity);
         if ($assoc['type'] & ClassMetadata::TO_ONE) {
             if ($value instanceof Proxy && !$value->__isInitialized__) {
                 continue;
                 // skip uninitialized proxies
             }
             if ($assoc['isOwningSide']) {
                 $joinColumnValues = array();
                 foreach ($assoc['targetToSourceKeyColumns'] as $targetColumn => $srcColumn) {
                     if ($metaColumns[$srcColumn] !== null) {
                         $joinColumnValues[$targetColumn] = $metaColumns[$srcColumn];
                     }
                 }
                 if (!$joinColumnValues && $value !== null) {
                     $this->_class->reflFields[$field]->setValue($entity, null);
                     $newData[$field] = null;
                 } else {
                     if ($value !== null) {
                         // Check identity map first, if the entity is not there,
                         // place a proxy in there instead.
                         $targetClass = $this->_em->getClassMetadata($assoc['targetEntity']);
                         if ($found = $this->_em->getUnitOfWork()->tryGetById($joinColumnValues, $targetClass->rootEntityName)) {
                             $this->_class->reflFields[$field]->setValue($entity, $found);
                             // Complete inverse side, if necessary.
                             if ($assoc['inversedBy'] && $assoc['type'] & ClassMetadata::ONE_TO_ONE) {
                                 $inverseAssoc = $targetClass->associationMappings[$assoc['inversedBy']];
                                 $targetClass->reflFields[$inverseAssoc['fieldName']]->setValue($found, $entity);
                             }
                             $newData[$field] = $found;
                         } else {
                             // FIXME: What is happening with subClassees here?
                             $proxy = $this->_em->getProxyFactory()->getProxy($assoc['targetEntity'], $joinColumnValues);
                             $this->_class->reflFields[$field]->setValue($entity, $proxy);
                             $newData[$field] = $proxy;
                             $this->_em->getUnitOfWork()->registerManaged($proxy, $joinColumnValues, array());
                         }
                     }
                 }
             } else {
                 // Inverse side of 1-1/1-x can never be lazy.
                 //$newData[$field] = $assoc->load($entity, null, $this->_em);
                 $newData[$field] = $this->_em->getUnitOfWork()->getEntityPersister($assoc['targetEntity'])->loadOneToOneEntity($assoc, $entity, null);
             }
         } else {
             if ($value instanceof PersistentCollection && $value->isInitialized()) {
                 $value->setInitialized(false);
                 // no matter if dirty or non-dirty entities are already loaded, smoke them out!
                 // the beauty of it being, they are still in the identity map
                 $value->unwrap()->clear();
                 $newData[$field] = $value;
             }
         }
     }
     $this->_em->getUnitOfWork()->setOriginalEntityData($entity, $newData);
     if (isset($this->_class->lifecycleCallbacks[Events::postLoad])) {
         $this->_class->invokeLifecycleCallbacks(Events::postLoad, $entity);
     }
     $evm = $this->_em->getEventManager();
     if ($evm->hasListeners(Events::postLoad)) {
         $evm->dispatchEvent(Events::postLoad, new LifecycleEventArgs($entity, $this->_em));
     }
 }
Exemplo n.º 30
0
 /**
  * Initializes a new UnitOfWork instance, bound to the given EntityManager.
  *
  * @param Doctrine\ORM\EntityManager $em
  */
 public function __construct(EntityManager $em)
 {
     $this->_em = $em;
     $this->_evm = $em->getEventManager();
     $this->_useCExtension = $this->_em->getConfiguration()->getUseCExtension();
 }