/**
  * Returns entity
  *
  * @param string $entityName Entity name. Can be full class name or short form: Bundle:Entity.
  * @return array contains entity details:
  *                           .    'name'          - entity full class name
  *                           .    'label'         - entity label
  *                           .    'plural_label'  - entity plural label
  *                           .    'icon'          - an icon associated with an entity
  */
 public function getEntity($entityName)
 {
     $className = $this->entityClassResolver->getEntityClass($entityName);
     $config = $this->entityConfigProvider->getConfig($className);
     $result = array();
     $this->addEntity($result, $config->getId()->getClassName(), $config->get('label'), $config->get('plural_label'), $config->get('icon'));
     return reset($result);
 }
 /**
  * Constructor
  *
  * @param array $owningEntityNames
  * @param ConfigProvider $configProvider
  * @param EntityClassResolver $entityClassResolver
  * @param CacheProvider|null $cache
  *
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function __construct(array $owningEntityNames, ConfigProvider $configProvider, EntityClassResolver $entityClassResolver = null, CacheProvider $cache = null)
 {
     $this->organizationClass = $entityClassResolver === null ? $owningEntityNames['organization'] : $entityClassResolver->getEntityClass($owningEntityNames['organization']);
     $this->businessUnitClass = $entityClassResolver === null ? $owningEntityNames['business_unit'] : $entityClassResolver->getEntityClass($owningEntityNames['business_unit']);
     $this->userClass = $entityClassResolver === null ? $owningEntityNames['user'] : $entityClassResolver->getEntityClass($owningEntityNames['user']);
     $this->configProvider = $configProvider;
     $this->cache = $cache;
     $this->noOwnershipMetadata = new OwnershipMetadata();
 }
 /**
  * @param array $config
  */
 public function resolve(&$config)
 {
     array_walk_recursive($config, function (&$val, $key) {
         if ($key === 'entity' || $key === 'parent_entity') {
             $val = $this->entityClassResolver->getEntityClass($val);
         } elseif (is_string($val)) {
             $this->resolveSystemCall($val);
         }
     });
 }
 public function testIsKnownEntityClassNamespace()
 {
     $config = $this->getMockBuilder('\\Doctrine\\ORM\\Configuration')->disableOriginalConstructor()->getMock();
     $config->expects($this->exactly(2))->method('getEntityNamespaces')->will($this->returnValue(array('AcmeSomeBundle' => 'Acme\\Bundle\\SomeBundle\\Entity')));
     $em = $this->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->getMock();
     $em->expects($this->exactly(2))->method('getConfiguration')->will($this->returnValue($config));
     $this->doctrine->expects($this->exactly(2))->method('getManagers')->will($this->returnValue(array('default' => $em)));
     $this->doctrine->expects($this->exactly(2))->method('getManager')->with($this->equalTo('default'))->will($this->returnValue($em));
     $this->assertTrue($this->resolver->isKnownEntityClassNamespace('Acme\\Bundle\\SomeBundle\\Entity'));
     $this->assertFalse($this->resolver->isKnownEntityClassNamespace('Acme\\Bundle\\AnotherBundle\\Entity'));
 }
 /**
  * @param DatagridConfiguration $config
  *
  * @return string|null
  */
 public function getEntity(DatagridConfiguration $config)
 {
     $entityClassName = $config->offsetGetByPath('[extended_entity_name]');
     if ($entityClassName) {
         return $entityClassName;
     }
     $from = $config->offsetGetByPath('[source][query][from]');
     if (!$from) {
         return null;
     }
     return $this->entityClassResolver->getEntityClass($from[0]['table']);
 }
Beispiel #6
0
 /**
  * @param DatagridConfiguration $config
  *
  * @return null|string
  */
 protected function getEntity(DatagridConfiguration $config)
 {
     $entityClassName = $config->offsetGetByPath(self::GRID_EXTEND_ENTITY_PATH);
     if (!$entityClassName) {
         $from = $config->offsetGetByPath(self::GRID_FROM_PATH);
         if (!$from) {
             return null;
         }
         $entityClassName = $this->entityClassResolver->getEntityClass($from[0]['table']);
     }
     return $entityClassName;
 }
 /**
  * Constructor
  *
  * @param array $owningEntityNames
  * @param ConfigProvider $configProvider
  * @param EntityClassResolver $entityClassResolver
  * @param CacheProvider|null $cache
  *
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function __construct(array $owningEntityNames, ConfigProvider $configProvider, EntityClassResolver $entityClassResolver = null, CacheProvider $cache = null)
 {
     $this->organizationClass = $entityClassResolver === null ? $owningEntityNames['organization'] : $entityClassResolver->getEntityClass($owningEntityNames['organization']);
     $this->businessUnitClass = $entityClassResolver === null ? $owningEntityNames['business_unit'] : $entityClassResolver->getEntityClass($owningEntityNames['business_unit']);
     $this->userClass = $entityClassResolver === null ? $owningEntityNames['user'] : $entityClassResolver->getEntityClass($owningEntityNames['user']);
     $this->configProvider = $configProvider;
     $this->cache = $cache;
     if ($this->cache !== null && $this->cache->getNamespace() === '') {
         $this->cache->setNamespace(self::CACHE_NAMESPACE);
     }
     $this->noOwnershipMetadata = new OwnershipMetadata();
 }
 /**
  * Returns fields for the given entity
  *
  * @param string $entityName             Entity name. Can be full class name or short form: Bundle:Entity.
  * @param bool   $withRelations          Indicates whether fields of related entities should be returned as well.
  * @param bool   $withEntityDetails      Indicates whether details of related entity should be returned as well.
  * @param int    $deepLevel              The maximum deep level of related entities.
  * @param bool   $lastDeepLevelRelations The maximum deep level of related entities.
  * @return array of fields sorted by field label (relations follows fields)
  *                                       .       'name'          - field name
  *                                       .       'type'          - field type
  *                                       .       'label'         - field label
  *                                       If a field is an identifier (primary key in terms of a database)
  *                                       .       'identifier'    - true for an identifier field
  *                                       If a field represents a relation and $withRelations = true
  *                                       the following attributes are added:
  *                                       .       'relation_type'       - relation type
  *                                       .       'related_entity_name' - entity full class name
  *                                       If a field represents a relation and $withEntityDetails = true
  *                                       the following attributes are added:
  *                                       .       'related_entity_label'        - entity label
  *                                       .       'related_entity_plural_label' - entity plural label
  *                                       .       'related_entity_icon'         - an icon associated with an entity
  *                                       If a field represents a relation and $deepLevel > 0
  *                                       the related entity fields are added:
  *                                       .       'related_entity_fields'       - array of fields
  * @throws InvalidEntityException
  */
 public function getFields($entityName, $withRelations = false, $withEntityDetails = false, $deepLevel = 0, $lastDeepLevelRelations = false)
 {
     $result = array();
     $className = $this->entityClassResolver->getEntityClass($entityName);
     $em = $this->getManagerForClass($className);
     $this->addFields($result, $className, $em);
     if ($withRelations) {
         $this->addRelations($result, $className, $em, $withEntityDetails, $deepLevel - 1, $lastDeepLevelRelations);
     }
     $this->sortFields($result);
     return $result;
 }
 /**
  * {@inheritdoc}
  */
 public function supports($data)
 {
     if ($data instanceof FormInterface) {
         $data = $data->getData();
         return $this->supports($data);
     }
     $class = false;
     if (is_object($data) || is_string($data)) {
         $class = ClassUtils::getRealClass($data);
     }
     return $class && $this->resolver->isEntity($class);
 }
 /**
  * {@inheritdoc}
  */
 public function visitDatasource(DatagridConfiguration $config, DatasourceInterface $datasource)
 {
     $fields = $this->getFields($config);
     if (empty($fields)) {
         return;
     }
     $entityClassName = $this->entityClassResolver->getEntityClass($this->getEntityName($config));
     /** @var QueryBuilder $qb */
     $qb = $datasource->getQueryBuilder();
     $fromParts = $qb->getDQLPart('from');
     $alias = false;
     /** @var From $fromPart */
     foreach ($fromParts as $fromPart) {
         if ($this->entityClassResolver->getEntityClass($fromPart->getFrom()) == $entityClassName) {
             $alias = $fromPart->getAlias();
         }
     }
     if ($alias === false) {
         // add entity if it not exists in from clause
         $alias = 'o';
         $qb->from($entityClassName, $alias);
     }
     $relationIndex = 0;
     $relationTemplate = 'auto_rel_%d';
     foreach ($fields as $field) {
         $fieldName = $field->getFieldName();
         switch ($field->getFieldType()) {
             case 'enum':
                 $extendFieldConfig = $this->getFieldConfig('extend', $field);
                 $joinAlias = sprintf($relationTemplate, ++$relationIndex);
                 $qb->leftJoin(sprintf('%s.%s', $alias, $fieldName), $joinAlias);
                 $columnDataName = $fieldName;
                 $sorterDataName = sprintf('%s.%s', $joinAlias, $extendFieldConfig->get('target_field'));
                 $selectExpr = sprintf('%s as %s', $sorterDataName, $fieldName);
                 break;
             case 'multiEnum':
                 $columnDataName = ExtendHelper::getMultiEnumSnapshotFieldName($fieldName);
                 $sorterDataName = sprintf('%s.%s', $alias, $columnDataName);
                 $selectExpr = $sorterDataName;
                 break;
             default:
                 $columnDataName = $fieldName;
                 $sorterDataName = sprintf('%s.%s', $alias, $fieldName);
                 $selectExpr = $sorterDataName;
                 break;
         }
         $qb->addSelect($selectExpr);
         // set real "data name" for filters and sorters
         $config->offsetSetByPath(sprintf('[%s][%s][data_name]', FormatterConfiguration::COLUMNS_KEY, $fieldName), $columnDataName);
         $config->offsetSetByPath(sprintf('%s[%s][data_name]', SorterConfiguration::COLUMNS_PATH, $fieldName), $sorterDataName);
         $config->offsetSetByPath(sprintf('%s[%s][data_name]', FilterConfiguration::COLUMNS_PATH, $fieldName), sprintf('%s.%s', $alias, $fieldName));
     }
 }
 public function testOwnerClassesConfig()
 {
     $this->entityClassResolver->expects($this->exactly(3))->method('getEntityClass')->will($this->returnValueMap([['AcmeBundle:Organization', 'AcmeBundle\\Entity\\Organization'], ['AcmeBundle:BusinessUnit', 'AcmeBundle\\Entity\\BusinessUnit'], ['AcmeBundle:User', 'AcmeBundle\\Entity\\User']]));
     $provider = new OwnershipMetadataProvider(['organization' => 'AcmeBundle:Organization', 'business_unit' => 'AcmeBundle:BusinessUnit', 'user' => 'AcmeBundle:User']);
     $provider->setContainer($this->container);
     $this->assertEquals('AcmeBundle\\Entity\\Organization', $provider->getGlobalLevelClass());
     $this->assertEquals('AcmeBundle\\Entity\\Organization', $provider->getOrganizationClass());
     $this->assertEquals('AcmeBundle\\Entity\\BusinessUnit', $provider->getLocalLevelClass());
     $this->assertEquals('AcmeBundle\\Entity\\BusinessUnit', $provider->getBusinessUnitClass());
     $this->assertEquals('AcmeBundle\\Entity\\User', $provider->getBasicLevelClass());
     $this->assertEquals('AcmeBundle\\Entity\\User', $provider->getUserClass());
 }
 protected function setUp()
 {
     $this->em = $this->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->getMock();
     $this->uow = $this->getMockBuilder('Doctrine\\ORM\\UnitOfWork')->disableOriginalConstructor()->getMock();
     $this->resolver = $this->getMockBuilder('Oro\\Bundle\\EntityBundle\\ORM\\EntityClassResolver')->disableOriginalConstructor()->getMock();
     $this->em->expects($this->any())->method('getUnitOfWork')->will($this->returnValue($this->uow));
     $entityClass = self::TEST_ENTITY_NAME;
     $this->resolver->expects($this->any())->method('isEntity')->will($this->returnCallback(function ($class) use($entityClass) {
         return $class === $entityClass;
     }));
     $this->generator = new DoctrineTagGenerator($this->em, $this->resolver);
 }
 protected function setUp()
 {
     $this->configProvider = $this->getMockBuilder('Oro\\Bundle\\EntityConfigBundle\\Provider\\ConfigProvider')->disableOriginalConstructor()->getMock();
     $this->securityFacade = $this->getMockBuilder('Oro\\Bundle\\SecurityBundle\\SecurityFacade')->disableOriginalConstructor()->getMock();
     $this->securityConfigProvider = $this->getMock('Oro\\Bundle\\EntityConfigBundle\\Provider\\ConfigProviderInterface');
     $this->entityClassResolver = $this->getMockBuilder('Oro\\Bundle\\EntityBundle\\ORM\\EntityClassResolver')->disableOriginalConstructor()->getMock();
     $this->entityClassResolver->expects($this->any())->method('getEntityClass')->willReturnMap([['OroB2BAccountBundle:Account', self::LOCAL_LEVEL], ['OroB2BAccountBundle:AccountUser', self::BASIC_LEVEL], [self::LOCAL_LEVEL, self::LOCAL_LEVEL], [self::BASIC_LEVEL, self::BASIC_LEVEL]]);
     $this->cache = $this->getMockBuilder('Doctrine\\Common\\Cache\\CacheProvider')->setMethods(['fetch', 'save'])->getMockForAbstractClass();
     $this->container = $this->getMock('Symfony\\Component\\DependencyInjection\\ContainerInterface');
     $this->container->expects($this->any())->method('get')->will($this->returnValueMap([['oro_entity_config.provider.ownership', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $this->configProvider], ['orob2b_account.owner.frontend_ownership_metadata_provider.cache', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $this->cache], ['oro_entity.orm.entity_class_resolver', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $this->entityClassResolver], ['oro_security.security_facade', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $this->securityFacade], ['oro_entity_config.provider.security', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $this->securityConfigProvider]]));
     $this->provider = new FrontendOwnershipMetadataProvider(['local_level' => self::LOCAL_LEVEL, 'basic_level' => self::BASIC_LEVEL]);
     $this->provider->setContainer($this->container);
 }
 /**
  * @param BuildBefore $event
  * @param string      $entityName
  *
  * @return bool
  */
 protected function isApplicable(BuildBefore $event, $entityName)
 {
     if (empty($entityName)) {
         return false;
     }
     try {
         $isEntity = $this->entityClassResolver->isEntity($entityName);
     } catch (\Exception $e) {
         $isEntity = false;
     }
     $existingConfig = $event->getConfig()->offsetGetByPath(sprintf(self::ACTION_CONFIGURATION_KEY, MassUpdateActionHandler::ACTION_NAME), false);
     return empty($existingConfig) && $isEntity && $this->actionHandler->isMassActionEnabled($entityName);
 }
 /**
  * Checks if the given entity is an owning side of association
  *
  * @param string $className
  * @param string $associationClass Represents the owning side entity, can be:
  *                                 - full class name or entity name for single association
  *                                 - a group name for multiple association
  *                                 it is supposed that the group name should not contain \ and : characters
  *
  * @return bool
  */
 public function isAssociationOwningSideEntity($className, $associationClass)
 {
     if (strpos($associationClass, ':') !== false || strpos($associationClass, '\\') !== false) {
         // the association class is full class name or entity name
         if ($className === $this->entityClassResolver->getEntityClass($associationClass)) {
             return true;
         }
     } else {
         // the association class is a group name
         if (!empty($className) && in_array($className, $this->getOwningSideEntities($associationClass))) {
             return true;
         }
     }
     return false;
 }
 /**
  * Adds filter by $entity DQL to the given query builder
  *
  * @param QueryBuilder $qb                  The query builder that is used to get the list of activities
  * @param string       $entityClass         The target entity class
  * @param mixed        $entityId            The target entity id
  * @param string|null  $activityEntityClass This parameter should be specified
  *                                          if the query has more than one root entity
  *
  * @throws \RuntimeException
  */
 public function addFilterByTargetEntity(QueryBuilder $qb, $entityClass, $entityId, $activityEntityClass = null)
 {
     $activityEntityAlias = null;
     $rootEntities = $qb->getRootEntities();
     if (empty($rootEntities)) {
         throw new \RuntimeException('The query must have at least one root entity.');
     }
     if (empty($activityEntityClass)) {
         if (count($rootEntities) > 1) {
             throw new \RuntimeException('The $activityEntityClass must be specified if the query has several root entities.');
         }
         $activityEntityClass = $rootEntities[0];
         $activityEntityAlias = $qb->getRootAliases()[0];
     } else {
         $normalizedActivityEntityClass = ClassUtils::getRealClass($this->entityClassResolver->getEntityClass($activityEntityClass));
         foreach ($rootEntities as $i => $className) {
             $className = $this->entityClassResolver->getEntityClass($className);
             if ($className === $normalizedActivityEntityClass) {
                 $activityEntityAlias = $qb->getRootAliases()[$i];
                 break;
             }
         }
         if (empty($activityEntityAlias)) {
             throw new \RuntimeException(sprintf('The "%s" must be the root entity.', $activityEntityClass));
         }
     }
     $activityIdentifierFieldName = $this->doctrineHelper->getSingleEntityIdentifierFieldName($activityEntityClass);
     $targetIdentifierFieldName = $this->doctrineHelper->getSingleEntityIdentifierFieldName($entityClass);
     $filterQuery = $qb->getEntityManager()->createQueryBuilder()->select(sprintf('filterActivityEntity.%s', $activityIdentifierFieldName))->from($activityEntityClass, 'filterActivityEntity')->innerJoin(sprintf('filterActivityEntity.%s', ExtendHelper::buildAssociationName($entityClass, ActivityScope::ASSOCIATION_KIND)), 'filterTargetEntity')->where(sprintf('filterTargetEntity.%s = :targetEntityId', $targetIdentifierFieldName))->getQuery();
     $qb->andWhere($qb->expr()->in(sprintf('%s.%s', $activityEntityAlias, $activityIdentifierFieldName), $filterQuery->getDQL()))->setParameter('targetEntityId', $entityId);
 }
 /**
  * Constructs an ObjectIdentity for the given domain object
  *
  * @param string $descriptor
  *
  * @return ObjectIdentity
  * @throws \InvalidArgumentException
  */
 protected function fromDescriptor($descriptor)
 {
     $type = $id = null;
     $this->parseDescriptor($descriptor, $type, $id);
     if ($id === $this->getExtensionKey()) {
         return new ObjectIdentity($id, $this->entityClassResolver->getEntityClass(ClassUtils::getRealClass($type)));
     }
     throw new \InvalidArgumentException(sprintf('Unsupported object identity descriptor: %s.', $descriptor));
 }
 /**
  * @param string     $entityName
  * @param bool       $isEntity
  * @param bool       $isException
  * @param bool       $isAlreadyConfigured
  * @param bool       $isActionEnabled
  * @param array|null $expected
  *
  * @dataProvider onBuildBeforeProvider
  */
 public function testOnBuildBefore($entityName, $isEntity, $isException, $isAlreadyConfigured, $isActionEnabled, $expected = null)
 {
     $datagrid = $this->getDatagrid($entityName, $isAlreadyConfigured);
     // prepare mocks
     if ($isException) {
         $this->classResolverMock->expects($this->once())->method('isEntity')->with($entityName)->will($this->throwException(new \ReflectionException("Not valid class")));
     } else {
         $this->classResolverMock->expects($this->once())->method('isEntity')->with($entityName)->will($this->returnValue($isEntity));
         if ($isEntity && !$isAlreadyConfigured && $isActionEnabled) {
             $this->doctrineHelperMock->expects($this->once())->method('getSingleEntityIdentifierFieldName')->will($this->returnValue('id'));
         }
         $isEmptyAndEnabled = !$isAlreadyConfigured && $isEntity;
         $this->handlerMock->expects($isEmptyAndEnabled ? $this->once() : $this->never())->method('isMassActionEnabled')->with($entityName)->will($this->returnValue($isActionEnabled));
     }
     $event = new BuildBefore($datagrid, $datagrid->getConfig());
     $this->listener->onBuildBefore($event);
     $this->assertEquals($expected, $event->getConfig()->offsetGetByPath(sprintf(GridListener::ACTION_CONFIGURATION_KEY, MassUpdateActionHandler::ACTION_NAME)), 'Failed asserting that mass action config added by listener');
 }
 protected function setUp()
 {
     $this->entityConfigProvider = $this->getMockBuilder('Oro\\Bundle\\EntityConfigBundle\\Provider\\ConfigProvider')->disableOriginalConstructor()->getMock();
     $this->extendConfigProvider = $this->getMockBuilder('Oro\\Bundle\\EntityConfigBundle\\Provider\\ConfigProvider')->disableOriginalConstructor()->getMock();
     $this->entityClassResolver = $this->getMockBuilder('Oro\\Bundle\\EntityBundle\\ORM\\EntityClassResolver')->disableOriginalConstructor()->getMock();
     $this->entityClassResolver->expects($this->any())->method('getEntityClass')->will($this->returnCallback(function ($entityName) {
         return str_replace(':', '\\Entity\\', $entityName);
     }));
     $this->translator = $this->getMockBuilder('Symfony\\Component\\Translation\\Translator')->disableOriginalConstructor()->getMock();
     $this->translator->expects($this->any())->method('trans')->will($this->returnArgument(0));
     $this->exclusionProvider = $this->getMock('Oro\\Bundle\\EntityBundle\\Provider\\ExclusionProviderInterface');
     $this->entityProvider = new EntityProvider($this->entityConfigProvider, $this->extendConfigProvider, $this->entityClassResolver, $this->translator);
     $this->entityProvider->setExclusionProvider($this->exclusionProvider);
     $this->doctrine = $this->getMockBuilder('Symfony\\Bridge\\Doctrine\\ManagerRegistry')->disableOriginalConstructor()->getMock();
     $this->virtualFieldProvider = $this->getMock('Oro\\Bundle\\EntityBundle\\Provider\\VirtualFieldProviderInterface');
     $this->virtualRelationProvider = $this->getMock('Oro\\Bundle\\EntityBundle\\Provider\\VirtualRelationProviderInterface');
     $this->provider = new EntityFieldProvider($this->entityConfigProvider, $this->extendConfigProvider, $this->entityClassResolver, new FieldTypeHelper([]), $this->doctrine, $this->translator, []);
     $this->provider->setEntityProvider($this->entityProvider);
     $this->provider->setVirtualFieldProvider($this->virtualFieldProvider);
     $this->provider->setVirtualRelationProvider($this->virtualRelationProvider);
     $this->provider->setExclusionProvider($this->exclusionProvider);
 }
Beispiel #20
0
 /**
  * Get ACL annotation object for current controller action which was taken from request object
  *
  * @param Request $request
  * @param bool    $convertClassName
  * @return null|Acl
  */
 public function getRequestAcl(Request $request, $convertClassName = false)
 {
     $controller = $request->attributes->get('_controller');
     if (strpos($controller, '::') !== false) {
         $controllerData = explode('::', $controller);
         $acl = $this->getClassMethodAnnotation($controllerData[0], $controllerData[1]);
         if ($convertClassName && $acl) {
             $entityClass = $acl->getClass();
             if (!empty($entityClass) && $this->entityClassResolver->isEntity($entityClass)) {
                 $acl->setClass($this->entityClassResolver->getEntityClass($entityClass));
             }
         }
         return $acl;
     }
     return null;
 }
 /**
  * Adds entity virtual fields to $result
  *
  * @param array  $result
  * @param string $className
  * @param bool $withEntityDetails
  * @param bool $applyExclusions
  * @param bool $translate
  */
 protected function addVirtualRelations(array &$result, $className, $withEntityDetails, $applyExclusions, $translate)
 {
     if (!$this->virtualRelationProvider) {
         return;
     }
     $metadata = $this->getMetadataFor($className);
     $virtualRelations = $this->virtualRelationProvider->getVirtualRelations($className);
     foreach ($virtualRelations as $associationName => $virtualRelation) {
         if ($applyExclusions && $this->exclusionProvider->isIgnoredField($metadata, $associationName)) {
             continue;
         }
         $fieldType = $virtualRelation['relation_type'];
         $targetClassName = $this->entityClassResolver->getEntityClass($virtualRelation['related_entity_name']);
         $label = !empty($virtualRelation['label']) ? $virtualRelation['label'] : $this->getFieldLabel($metadata, $associationName);
         $this->addRelation($result, $associationName, $fieldType, $label, $this->getRelationType($fieldType), $targetClassName, $withEntityDetails, $translate);
     }
 }
Beispiel #22
0
 /**
  * @param string      $path          The path for which the join should be applied.
  * @param string      $joinType      The condition type constant. Either Join::INNER_JOIN or Join::LEFT_JOIN.
  * @param string      $join          The relationship to join.
  * @param string|null $conditionType The condition type constant. Either Join::ON or Join::WITH.
  * @param string|null $condition     The condition for the join.
  * @param string|null $indexBy       The index for the join.
  *
  * @return Join
  *
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 protected function addJoin($path, $joinType, $join, $conditionType = null, $condition = null, $indexBy = null)
 {
     if (!$path) {
         throw new \InvalidArgumentException('$path must be specified.');
     }
     if (!$join) {
         throw new \InvalidArgumentException(sprintf('$join must be specified. Join path: "%s".', $path));
     }
     if ($condition && !$conditionType) {
         throw new \InvalidArgumentException(sprintf('$conditionType must be specified if $condition exists. Join path: "%s".', $path));
     }
     if (null !== $conditionType && !$conditionType) {
         $conditionType = null;
     }
     if (null !== $condition && !$condition) {
         $condition = null;
     }
     if (null !== $indexBy && !$indexBy) {
         $indexBy = null;
     }
     if (null !== $conditionType && null === $condition) {
         $conditionType = null;
     }
     try {
         $join = $this->entityClassResolver->getEntityClass($join);
     } catch (ORMException $e) {
         throw new \InvalidArgumentException(sprintf('"%s" is not valid entity name. Join path: "%s".', $join, $path), 0, $e);
     }
     if (!isset($this->joins[$path])) {
         $newJoin = new Join($joinType, $join, $conditionType, $condition, $indexBy);
         $this->joins[$path] = $newJoin;
         return $newJoin;
     }
     $existingJoin = $this->joins[$path];
     if ($existingJoin->getJoin() !== $join || $existingJoin->getConditionType() !== $conditionType || $existingJoin->getCondition() !== $condition || $existingJoin->getIndexBy() !== $indexBy) {
         throw new \LogicException(sprintf('The join definition for "%s" conflicts with already added join. ' . 'Existing join: "%s". New join: "%s".', $path, (string) $existingJoin, (string) new Join($joinType, $join, $conditionType, $condition, $indexBy)));
     }
     $existingJoinType = $existingJoin->getJoinType();
     if ($existingJoinType !== $joinType && $existingJoinType === Join::LEFT_JOIN) {
         $existingJoin->setJoinType($joinType);
     }
     return $existingJoin;
 }
 /**
  * Returns fields for the given entity
  *
  * @param string $entityName         Entity name. Can be full class name or short form: Bundle:Entity.
  * @param bool   $withRelations      Indicates whether association fields should be returned as well.
  * @param bool   $withVirtualFields  Indicates whether virtual fields should be returned as well.
  * @param bool   $withEntityDetails  Indicates whether details of related entity should be returned as well.
  * @param bool   $withUnidirectional Indicates whether Unidirectional association fields should be returned.
  * @param bool   $applyExclusions    Indicates whether exclusion logic should be applied.
  * @param bool   $translate          Flag means that label, plural label should be translated
  *
  * @return array of fields sorted by field label (relations follows fields)
  *                                   .       'name'          - field name
  *                                   .       'type'          - field type
  *                                   .       'label'         - field label
  *                                   If a field is an identifier (primary key in terms of a database)
  *                                   .       'identifier'    - true for an identifier field
  *                                   If a field represents a relation and $withRelations = true or
  *                                   a virtual field has 'filter_by_id' = true following attribute is added:
  *                                   .       'related_entity_name' - entity full class name
  *                                   If a field represents a relation and $withRelations = true
  *                                   the following attributes are added:
  *                                   .       'relation_type'       - relation type
  *                                   If a field represents a relation and $withEntityDetails = true
  *                                   the following attributes are added:
  *                                   .       'related_entity_label'        - entity label
  *                                   .       'related_entity_plural_label' - entity plural label
  *                                   .       'related_entity_icon'         - an icon associated with an entity
  */
 public function getFields($entityName, $withRelations = false, $withVirtualFields = false, $withEntityDetails = false, $withUnidirectional = false, $applyExclusions = true, $translate = true)
 {
     $className = $this->entityClassResolver->getEntityClass($entityName);
     if (!$this->entityConfigProvider->hasConfig($className)) {
         // only configurable entities are supported
         return [];
     }
     $result = [];
     $em = $this->getManagerForClass($className);
     $this->addFields($result, $className, $em, $withVirtualFields, $applyExclusions, $translate);
     if ($withRelations) {
         $this->addRelations($result, $className, $em, $withEntityDetails, $applyExclusions, $translate);
         if ($withUnidirectional) {
             $this->addUnidirectionalRelations($result, $className, $em, $withEntityDetails, $applyExclusions, $translate);
         }
     }
     $this->sortFields($result);
     return $result;
 }
 public function testIsEntityForNotManageableEntity()
 {
     $className = 'Test\\Entity';
     $this->doctrine->expects($this->once())->method('getManagerForClass')->with($className)->will($this->returnValue(null));
     $this->assertFalse($this->resolver->isEntity($className));
 }