/**
  * @param $action
  * @param \Doctrine\ORM\Mapping\ClassMetadata $meta
  * @param $entity
  */
 private function logEntityChange($action, \Doctrine\ORM\Mapping\ClassMetadata $meta, $entity)
 {
     $userToken = $this->container->get('security.context')->getToken();
     if (null !== $userToken) {
         $this->logger->info('Entity "' . $meta->getTableName() . '" with id: ' . $meta->getFieldValue($entity, $meta->getSingleIdentifierFieldName()) . ' ' . $action . ' by: ' . $this->container->get('security.context')->getToken()->getUsername());
     }
 }
 /**
  * Loads an entity by a list of field criteria.
  *
  * @param array $criteria The criteria by which to load the entity.
  * @param object $entity The entity to load the data into. If not specified,
  *                       a new entity is created.
  */
 public function load(array $criteria, $entity = null)
 {
     $stmt = $this->_conn->prepare($this->_getSelectSingleEntitySql($criteria));
     $stmt->execute(array_values($criteria));
     $data = array();
     foreach ($stmt->fetch(\PDO::FETCH_ASSOC) as $column => $value) {
         $fieldName = $this->_class->fieldNames[$column];
         $data[$fieldName] = Type::getType($this->_class->getTypeOfField($fieldName))->convertToPHPValue($value);
     }
     $stmt->closeCursor();
     if ($entity === null) {
         $entity = $this->_em->getUnitOfWork()->createEntity($this->_entityName, $data);
     } else {
         foreach ($data as $field => $value) {
             $this->_class->reflFields[$field]->setValue($entity, $value);
         }
         $id = array();
         if ($this->_class->isIdentifierComposite) {
             foreach ($this->_class->identifier as $fieldName) {
                 $id[] = $data[$fieldName];
             }
         } else {
             $id = array($data[$this->_class->getSingleIdentifierFieldName()]);
         }
         $this->_em->getUnitOfWork()->registerManaged($entity, $id, $data);
     }
     if (!$this->_em->getConfiguration()->getAllowPartialObjects()) {
         foreach ($this->_class->associationMappings as $field => $assoc) {
             if ($assoc->isOneToOne()) {
                 if ($assoc->isLazilyFetched()) {
                     // Inject proxy
                     $proxy = $this->_em->getProxyGenerator()->getAssociationProxy($entity, $assoc);
                     $this->_class->reflFields[$field]->setValue($entity, $proxy);
                 } else {
                     //TODO: Eager fetch?
                 }
             } else {
                 // Inject collection
                 $this->_class->reflFields[$field]->setValue($entity, new PersistentCollection($this->_em, $this->_em->getClassMetadata($assoc->targetEntityName)));
             }
         }
     }
     return $entity;
 }
 public function testGetSingleIdentifierFieldName_MultipleIdentifierEntity_ThrowsException()
 {
     $cm = new ClassMetadata('Doctrine\\Tests\\Models\\CMS\\CmsUser');
     $cm->isIdentifierComposite = true;
     $this->setExpectedException('Doctrine\\ORM\\Mapping\\MappingException');
     $cm->getSingleIdentifierFieldName();
 }
 /**
  * Kept for BC-compatibility purposes : people expect this lib to map ids for
  * translations.
  *
  * @deprecated It should be removed because it probably does not work with
  *             every doctrine version.
  *
  * @see https://github.com/doctrine/doctrine2/blob/0bff6aadbc9f3fd8167a320d9f4f6cf269382da0/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php#L508
  */
 private function mapId(ClassMetadata $class, EntityManager $em)
 {
     $platform = $em->getConnection()->getDatabasePlatform();
     if (!$class->hasField('id')) {
         $builder = new ClassMetadataBuilder($class);
         $builder->createField('id', 'integer')->isPrimaryKey()->generatedValue()->build();
         /// START DOCTRINE CODE
         $idGenType = $class->generatorType;
         if ($idGenType == ClassMetadata::GENERATOR_TYPE_AUTO) {
             if ($platform->prefersSequences()) {
                 $class->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_SEQUENCE);
             } else {
                 if ($platform->prefersIdentityColumns()) {
                     $class->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY);
                 } else {
                     $class->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_TABLE);
                 }
             }
         }
         // Create & assign an appropriate ID generator instance
         switch ($class->generatorType) {
             case ClassMetadata::GENERATOR_TYPE_IDENTITY:
                 // For PostgreSQL IDENTITY (SERIAL) we need a sequence name. It defaults to
                 // <table>_<column>_seq in PostgreSQL for SERIAL columns.
                 // Not pretty but necessary and the simplest solution that currently works.
                 $sequenceName = null;
                 $fieldName = $class->identifier ? $class->getSingleIdentifierFieldName() : null;
                 if ($platform instanceof Platforms\PostgreSQLPlatform) {
                     $columnName = $class->getSingleIdentifierColumnName();
                     $quoted = isset($class->fieldMappings[$fieldName]['quoted']) || isset($class->table['quoted']);
                     $sequenceName = $class->getTableName() . '_' . $columnName . '_seq';
                     $definition = array('sequenceName' => $platform->fixSchemaElementName($sequenceName));
                     if ($quoted) {
                         $definition['quoted'] = true;
                     }
                     $sequenceName = $em->getConfiguration()->getQuoteStrategy()->getSequenceName($definition, $class, $platform);
                 }
                 $generator = $fieldName && $class->fieldMappings[$fieldName]['type'] === 'bigint' ? new BigIntegerIdentityGenerator($sequenceName) : new IdentityGenerator($sequenceName);
                 $class->setIdGenerator($generator);
                 break;
             case ClassMetadata::GENERATOR_TYPE_SEQUENCE:
                 // If there is no sequence definition yet, create a default definition
                 $definition = $class->sequenceGeneratorDefinition;
                 if (!$definition) {
                     $fieldName = $class->getSingleIdentifierFieldName();
                     $columnName = $class->getSingleIdentifierColumnName();
                     $quoted = isset($class->fieldMappings[$fieldName]['quoted']) || isset($class->table['quoted']);
                     $sequenceName = $class->getTableName() . '_' . $columnName . '_seq';
                     $definition = array('sequenceName' => $platform->fixSchemaElementName($sequenceName), 'allocationSize' => 1, 'initialValue' => 1);
                     if ($quoted) {
                         $definition['quoted'] = true;
                     }
                     $class->setSequenceGeneratorDefinition($definition);
                 }
                 $sequenceGenerator = new \Doctrine\ORM\Id\SequenceGenerator($em->getConfiguration()->getQuoteStrategy()->getSequenceName($definition, $class, $platform), $definition['allocationSize']);
                 $class->setIdGenerator($sequenceGenerator);
                 break;
             case ClassMetadata::GENERATOR_TYPE_NONE:
                 $class->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator());
                 break;
             case ClassMetadata::GENERATOR_TYPE_UUID:
                 $class->setIdGenerator(new \Doctrine\ORM\Id\UuidGenerator());
                 break;
             case ClassMetadata::GENERATOR_TYPE_TABLE:
                 throw new ORMException("TableGenerator not yet implemented.");
                 break;
             case ClassMetadata::GENERATOR_TYPE_CUSTOM:
                 $definition = $class->customGeneratorDefinition;
                 if (!class_exists($definition['class'])) {
                     throw new ORMException("Can't instantiate custom generator : " . $definition['class']);
                 }
                 $class->setIdGenerator(new $definition['class']());
                 break;
             default:
                 throw new ORMException("Unknown generator type: " . $class->generatorType);
         }
         /// END DOCTRINE COPY / PASTED code
     }
 }
 public function testGetSingleIdentifierFieldName_MultipleIdentifierEntity_ThrowsException()
 {
     $cm = new ClassMetadata('Doctrine\\Tests\\Models\\CMS\\CmsUser');
     $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService());
     $cm->isIdentifierComposite = true;
     $this->setExpectedException('Doctrine\\ORM\\Mapping\\MappingException');
     $cm->getSingleIdentifierFieldName();
 }
Exemple #6
0
 /**
  * Returns the name of entity identifier field if an entity has a single-field identifier
  *
  * @return string
  */
 public function getSingleIdentifierFieldName()
 {
     return $this->metadata->getSingleIdentifierFieldName();
 }
Exemple #7
0
 public function __construct(\Symforce\AdminBundle\Compiler\Generator\AnnotationCache $cache, $bundle_name, ClassMetadata $meta, Generator $gen)
 {
     $this->cache = $cache;
     $this->bundle_name = $bundle_name;
     $this->class_name = $cache->class_name;
     $this->reflection = $meta->getReflectionClass();
     $this->generator = $gen;
     $this->orm_metadata = $meta;
     if ($meta->isIdentifierComposite) {
         // @TODO add Composite route handle
     } else {
         $this->property_id_name = $meta->getSingleIdentifierFieldName();
     }
     $this->setMyPropertie($cache->class_annotations['Symforce\\AdminBundle\\Compiler\\Annotation\\Entity']);
     if (!$this->name) {
         $this->name = strtolower(preg_replace('/\\W/', '_', $this->class_name));
     }
     $this->template = $this->name . '.admin.html.twig';
     $this->_template_path = $this->generator->getParameter('kernel.root_dir') . '/Resources/views/' . $this->template;
     if (null === $this->_final_template) {
         $tempalte = $this->bundle_name . ':' . basename(str_replace('\\', '\\/', $this->class_name)) . ':admin.macro.html.twig';
         try {
             $this->generator->loadTwigTemplatePath($tempalte);
             $this->_final_template = $tempalte;
         } catch (\InvalidArgumentException $e) {
         }
     }
     $compile_class_name = ucfirst($this->camelize($this->name));
     $this->_compile_class_name = 'Symforce\\AdminCache\\' . $compile_class_name . '\\Admin' . $compile_class_name;
     if (null === $this->tr_domain) {
         $this->tr_domain = $this->bundle_name;
     }
     $this->sf_domain = $gen->getSymforceDomain();
     if (isset($cache->class_annotations[self::ANNOT_TREE_CLASS])) {
         // not work for yml/xml,  because the private stof_doctrine_extensions.listener.tree service
         $tree_annot_len = strlen(self::ANNOT_TREE_CLASS);
         $this->tree = array();
         foreach ($cache->propertie_annotations as $property_name => $as) {
             foreach ($as as $annot_class => &$value) {
                 if (0 === strpos($annot_class, self::ANNOT_TREE_CLASS)) {
                     $tree_config_key = strtolower(substr($annot_class, $tree_annot_len));
                     $this->tree[$tree_config_key] = $property_name;
                 }
             }
         }
         if (!isset($this->tree['parent'])) {
             $this->throwError("missing @%sParent", self::ANNOT_TREE_CLASS);
         }
         if (!isset($this->tree['root'])) {
             $this->throwError("missing @%sRoot", self::ANNOT_TREE_CLASS);
         }
     }
     if (isset($cache->class_annotations[self::ANNOT_TOSTR_CLASS])) {
         \Dev::dump($cache->class_annotations[self::ANNOT_TOSTR_CLASS]);
         exit;
     }
     if (isset($cache->class_annotations[self::ANNOT_TREE_LEAF_CLASS])) {
         \Dev::dump($cache->class_annotations[self::ANNOT_TREE_LEAF_CLASS]);
         exit;
     }
     foreach ($cache->propertie_annotations as $property_name => $as) {
         if (isset($as[self::ANNOT_SLUG_CLASS])) {
             if ($this->property_slug_name) {
                 $this->throwError("slug property duplicate(%s, %s)", $this->property_slug_name, $property_name);
             }
             $this->property_slug_name = $property_name;
             $this->property_slug_unique = $meta->isUniqueField($property_name);
             $this->property_slug_nullable = $meta->isNullable($property_name);
         }
         if (isset($as[self::ANNOT_TOSTR_CLASS])) {
             if ($this->property_value_name) {
                 $this->throwError("@ToString(%s) is conflict with @ToString(%s)", $property_name, $this->property_value_name);
             }
             $this->property_value_name = $property_name;
         }
         if (isset($as[self::ANNOT_TREE_LEAF_CLASS])) {
             if (!$this->tree) {
                 $this->throwError("use @%s(%s) without @%s", self::ANNOT_TREE_LEAF_CLASS, $property_name, self::ANNOT_TREE_CLASS);
             }
             if (isset($this->tree['leaf'])) {
                 $this->throwError("@ToString(%s) is conflict with %s", self::ANNOT_TREE_LEAF_CLASS, $property_name, $this->tree['leaf']);
             }
             $this->tree['leaf'] = $property_name;
         }
         if (isset($as[Page::PAGE_ANNOT_CLASS])) {
             if ($this->page) {
                 $this->throwError("page property duplicate(%s, %s)", $this->page->pege_property, $property_name);
             }
             $this->page = new Page($this, $property_name, $as[Page::PAGE_ANNOT_CLASS]);
         }
         if (isset($as[Owner::OWNER_ANNOT_CLASS])) {
             if ($this->owner) {
                 $this->throwError("owner property duplicate(%s, %s)", $this->owner->owner_property, $property_name);
             }
             $this->owner = new Owner($this, $property_name, $as[Owner::OWNER_ANNOT_CLASS]);
         }
     }
     if (isset($cache->class_annotations[self::ANNOT_WORKFLOW_CLASS])) {
         $this->workflow = new Workflow($this, $cache->class_annotations[self::ANNOT_WORKFLOW_CLASS]);
     }
     if (!$this->form) {
         $this->form = new Form($this);
     }
     $this->form->bootstrap();
     $this->action_collection = new ActionCollection($this);
     $this->_route_assoc = new RouteAssoc($this);
     if (null !== $this->position) {
         if ($this->dashboard && null === $this->dashboard->position) {
             $this->dashboard->position = $this->position;
         }
         if ($this->menu && null === $this->menu->position) {
             $this->menu->position = $this->position;
         }
     }
 }
 /**
  * @param ClassMetadata $meta
  * @param array $criteria
  * @param array $orderBy
  * @param string|callable $nameKey
  * @return array
  */
 private function findPairs(ClassMetadata $meta, $criteria, $orderBy, $nameKey)
 {
     $repository = $this->em->getRepository($meta->getName());
     if ($repository instanceof Kdyby\Doctrine\EntityDao && !is_callable($nameKey)) {
         return $repository->findPairs($criteria, $nameKey, $orderBy);
     }
     $items = array();
     $idKey = $meta->getSingleIdentifierFieldName();
     foreach ($repository->findBy($criteria, $orderBy) as $entity) {
         $items[$this->accessor->getValue($entity, $idKey)] = is_callable($nameKey) ? Nette\Utils\Callback::invoke($nameKey, $entity) : $this->accessor->getValue($entity, $nameKey);
     }
     return $items;
 }
Exemple #9
0
 /**
  * @param ClassMetadata $class
  * @param mixed         $identifierValue
  *
  * @return mixed the identifier after type conversion
  *
  * @throws \Doctrine\ORM\Mapping\MappingException if the entity has more than a single identifier
  */
 private function convertSingleFieldIdentifierToPHPValue(ClassMetadata $class, $identifierValue)
 {
     return $this->em->getConnection()->convertToPHPValue($identifierValue, $class->getTypeOfField($class->getSingleIdentifierFieldName()));
 }
 /**
  * @return string
  */
 protected function getPKFieldName()
 {
     return $this->classMetadata->getSingleIdentifierFieldName();
 }
 /**
  * Save the tree hierarchy for the specified node.
  *
  * @param EntityManager $entityManager
  * @param object $entity The node to save the tree for.
  * @param ClassMetadata $nodeMetadata
  * @param object|null $parent The parent entity (or null to get it from the entity itself).
  */
 protected function saveNodeTree(EntityManager $entityManager, $entity, ClassMetadata $nodeMetadata, $parent = null)
 {
     $nodeClass = get_class($entity);
     $treeClass = $nodeMetadata->closureTree['treeEntity'];
     // Get metadata
     $treeMetadata = $entityManager->getClassMetadata($treeClass);
     // Get the table name
     $tableName = $treeMetadata->getTableName();
     $idColumn = $nodeMetadata->getSingleIdentifierFieldName();
     $ancestorColumn = $treeMetadata->closureTree['ancestor']['fieldName'];
     $descendantColumn = $treeMetadata->closureTree['descendant']['fieldName'];
     if ($treeMetadata->closureTree['depth']) {
         $depthColumn = $treeMetadata->closureTree['depth']['fieldName'];
     } else {
         $depthColumn = null;
     }
     $nodeId = $nodeMetadata->getReflectionProperty($idColumn)->getValue($entity);
     $parent = $parent ?: $entity->getParent();
     // Check if the entity has a parent
     if ($parent) {
         // Get the parent ID
         $parentId = $parent->getId();
         // Format the query to insert the tree hierarchy
         $query = 'INSERT INTO ' . $tableName . ' (' . $ancestorColumn . ', ' . $descendantColumn;
         if ($depthColumn) {
             $query .= ', ' . $depthColumn;
         }
         $query .= ') SELECT ' . $ancestorColumn . ', ' . $nodeId . ' ';
         if ($depthColumn) {
             $query .= ', (' . $depthColumn . ' + 1) ';
         }
         $query .= 'FROM ' . $tableName . ' ';
         $query .= 'WHERE ' . $descendantColumn . ' = ? ';
         $query .= 'UNION ALL SELECT ' . $nodeId . ', ' . $nodeId;
         if ($depthColumn) {
             $query .= ', 0';
         }
         // Set the query parameters
         $queryParams = array($parentId);
     } else {
         // Format the query to insert the tree hierarchy
         $query = 'INSERT INTO ' . $tableName . ' ';
         $query .= '(' . $ancestorColumn . ', ' . $descendantColumn;
         if ($depthColumn) {
             $query .= ', ' . $depthColumn;
         }
         $query .= ') VALUES (?, ?';
         if ($depthColumn) {
             $query .= ', 0';
         }
         $query .= ')';
         // Set the query parameters
         $queryParams = array($nodeId, $nodeId);
     }
     // Execute the query and close the cursor
     $entityManager->getConnection()->executeQuery($query, $queryParams)->closeCursor();
 }