Exemple #1
0
 /**
  * Returns translation key (placeholder) by entity class name, field name and property code
  * examples (for default scope which is 'entity'):
  *      [vendor].[bundle].[entity].[field].[config property]
  *      oro.user.group.name.label
  *
  *      if [entity] == [bundle] -> skip it
  *      oro.user.first_name.label
  *
  *      if NO fieldName -> add prefix 'entity_'
  *      oro.user.entity_label
  *      oro.user.group.entity_label
  * examples (for other scopes, for instance 'test'):
  *      [vendor].[bundle].[entity].[field].[scope]_[config property]
  *      oro.user.group.name.test_label
  *
  *      if [entity] == [bundle] -> skip it
  *      oro.user.first_name.test_label
  *
  *      if NO fieldName -> add prefix 'entity_'
  *      oro.user.entity_test_label
  *      oro.user.group.entity_test_label
  *
  * @param string $scope
  * @param string $propertyName property key: label, description, plural_label, etc.
  * @param string $className
  * @param string $fieldName
  *
  * @return string
  *
  * @throws \InvalidArgumentException
  */
 public static function getTranslationKey($scope, $propertyName, $className, $fieldName = null)
 {
     if (empty($scope)) {
         throw new \InvalidArgumentException('$scope must not be empty');
     }
     if (empty($propertyName)) {
         throw new \InvalidArgumentException('$propertyName must not be empty');
     }
     if (empty($className)) {
         throw new \InvalidArgumentException('$className must not be empty');
     }
     // handle 'entity' scope separately
     if ($scope === 'entity') {
         return EntityLabelBuilder::getTranslationKey($propertyName, $className, $fieldName);
     }
     $parts = EntityLabelBuilder::explodeClassName($className);
     $propertyName = Inflector::tableize($scope) . '_' . $propertyName;
     if ($fieldName) {
         $parts[] = Inflector::tableize($fieldName);
         $parts[] = $propertyName;
     } else {
         $parts[] = 'entity_' . $propertyName;
     }
     return implode('.', $parts);
 }
Exemple #2
0
 /**
  * @inheritdoc
  */
 public static function tableize($word)
 {
     if (!isset(static::$cache['tableize'][$word])) {
         static::$cache['tableize'][$word] = parent::tableize($word);
     }
     return static::$cache['tableize'][$word];
 }
 /**
  * Return name
  *
  * @return string
  */
 public function getName()
 {
     $classname = get_class($this);
     if (preg_match('@\\\\([\\w]+)$@', $classname, $matches)) {
         $classname = $matches[1];
     }
     return Inflector::tableize($classname);
 }
 /**
  * Magic method to execute curl_xxx calls
  *
  * @param string $name      Method name (should be camelized)
  * @param array  $arguments Method arguments
  *
  * @return mixed
  * @throws \Exception
  */
 public function __call($name, $arguments)
 {
     $name = Inflector::tableize($name);
     if (function_exists("curl_{$name}")) {
         array_unshift($arguments, $this->handle);
         return call_user_func_array("curl_{$name}", $arguments);
     }
     throw new \Exception("Function 'curl_{$name}' do not exist, see PHP manual.");
 }
 public static function configureMigrationsForBundle(Application $application, $bundle, Configuration $configuration)
 {
     $bundle = $application->getKernel()->getBundle($bundle);
     $dir = $bundle->getPath() . '/DoctrineMigrations';
     $configuration->setMigrationsNamespace($bundle->getNamespace() . '\\DoctrineMigrations');
     $configuration->setMigrationsDirectory($dir);
     $configuration->registerMigrationsFromDirectory($dir);
     $configuration->setName($bundle->getName() . ' Migrations');
     $configuration->setMigrationsTableName(Inflector::tableize($bundle->getName()) . '_migration_versions');
 }
 /**
  * Creates a name for a command that can be used throughout configuration files
  *
  * @return string
  */
 public function getName()
 {
     $class = get_class($this);
     $class = explode('\\', $class);
     $class = $class[count($class) - 1];
     $class = str_replace(array('Supra', 'Package'), '', $class);
     $inflector = new Inflector();
     $name = $inflector->tableize($class);
     return $name;
 }
 /**
  * Returns the translation key for the given entity property
  *
  * The result format for entity: [vendor].[bundle].[entity].entity_[property]
  * Examples:
  *  label for Acme\Bundle\TestBundle\Entity\Product          -> acme.test.product.entity_label
  *  description for Acme\Bundle\ProductBundle\Entity\Product -> acme.product.entity_label
  *
  * The result format for field: [vendor].[bundle].[entity].[field].[property]
  * Examples:
  *  label for Acme\Bundle\TestBundle\Entity\Product::sellPrice    -> acme.test.product.sell_price.label
  *  label for Acme\Bundle\ProductBundle\Entity\Product::sellPrice -> acme.product.sell_price.label
  *
  * @param string      $propertyName
  * @param string      $className
  * @param string|null $fieldName
  *
  * @return string
  */
 public static function getTranslationKey($propertyName, $className, $fieldName = null)
 {
     $parts = self::explodeClassName($className);
     if ($fieldName) {
         $parts[] = Inflector::tableize($fieldName);
         $parts[] = $propertyName;
     } else {
         $parts[] = 'entity_' . $propertyName;
     }
     return implode('.', $parts);
 }
 public static function configureMigrationsForBundle(Application $application, $bundle, Configuration $configuration)
 {
     $configuration->setMigrationsNamespace($bundle . '\\DoctrineMigrations');
     $dirs = $application->getKernel()->getBundleDirs();
     $tmp = str_replace('\\', '/', $bundle);
     $namespace = str_replace('/', '\\', dirname($tmp));
     $bundle = basename($tmp);
     $dir = $dirs[$namespace] . '/' . $bundle . '/DoctrineMigrations';
     $configuration->setMigrationsDirectory($dir);
     $configuration->registerMigrationsFromDirectory($dir);
     $configuration->setName($bundle . ' Migrations');
     $configuration->setMigrationsTableName(Inflector::tableize($bundle) . '_migration_versions');
 }
Exemple #9
0
 public function getDirname($model)
 {
     $className = get_class($model);
     if (isset($this->basedirs[$className])) {
         $basedir = $this->basedirs[$className];
     } else {
         $reflection = new \ReflectionClass($className);
         $basedir = $this->basedirs[$className] = Inflector::tableize($reflection->getShortName());
     }
     $id = sprintf('%012s', $model->id);
     // Format
     //      $basedir / id[0..4] / id[5..8] / id[9..12]
     //      $basedir / 0000 / 0000 / 0001
     return sprintf('%s/%04s/%04s/%04s', $basedir, substr($id, 0, 4), substr($id, 5, 4), substr($id, 9, 4));
 }
Exemple #10
0
 /**
  * Map domain model to DTO.
  *
  * @param \Staffim\DTOBundle\Model\ModelInterface $model
  * @return object $dto
  */
 public function map(ModelInterface $model, $parentPropertyName = null)
 {
     $dto = $this->factory->create($model);
     $properties = get_object_vars($dto);
     // @todo trigger pre event
     foreach ($properties as $propertyName => $property) {
         $this->updateProperty($model, $dto, $propertyName, $parentPropertyName);
     }
     if ($this->eventDispatcher) {
         $event = new PostMapEvent($model, $dto);
         $modelClassParts = explode('\\', get_class($model));
         $modelName = \Doctrine\Common\Util\Inflector::tableize(end($modelClassParts));
         $this->eventDispatcher->dispatch('dto.' . $modelName . '.post_map', $event);
     }
     return $dto;
 }
 /**
  * @param BundleInterface $bundle
  * @param string          $entity
  * @param string          $format
  * @param array           $fields
  *
  * @return EntityGeneratorResult
  *
  * @throws \Doctrine\ORM\Tools\Export\ExportException
  */
 public function generate(BundleInterface $bundle, $entity, $format, array $fields)
 {
     // configure the bundle (needed if the bundle does not contain any Entities yet)
     $config = $this->registry->getManager(null)->getConfiguration();
     $config->setEntityNamespaces(array_merge(array($bundle->getName() => $bundle->getNamespace() . '\\Entity'), $config->getEntityNamespaces()));
     $entityClass = $this->registry->getAliasNamespace($bundle->getName()) . '\\' . $entity;
     $entityPath = $bundle->getPath() . '/Entity/' . str_replace('\\', '/', $entity) . '.php';
     if (file_exists($entityPath)) {
         throw new \RuntimeException(sprintf('Entity "%s" already exists.', $entityClass));
     }
     $class = new ClassMetadataInfo($entityClass);
     $class->customRepositoryClassName = str_replace('\\Entity\\', '\\Repository\\', $entityClass) . 'Repository';
     $class->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true));
     $class->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO);
     foreach ($fields as $field) {
         $class->mapField($field);
     }
     $entityGenerator = $this->getEntityGenerator();
     if ('annotation' === $format) {
         $entityGenerator->setGenerateAnnotations(true);
         $class->setPrimaryTable(array('name' => Inflector::tableize($entity)));
         $entityCode = $entityGenerator->generateEntityClass($class);
         $mappingPath = $mappingCode = false;
     } else {
         $cme = new ClassMetadataExporter();
         $exporter = $cme->getExporter('yml' == $format ? 'yaml' : $format);
         $mappingPath = $bundle->getPath() . '/Resources/config/doctrine/' . str_replace('\\', '.', $entity) . '.orm.' . $format;
         if (file_exists($mappingPath)) {
             throw new \RuntimeException(sprintf('Cannot generate entity when mapping "%s" already exists.', $mappingPath));
         }
         $mappingCode = $exporter->exportClassMetadata($class);
         $entityGenerator->setGenerateAnnotations(false);
         $entityCode = $entityGenerator->generateEntityClass($class);
     }
     $entityCode = str_replace(array("@var integer\n", "@var boolean\n", "@param integer\n", "@param boolean\n", "@return integer\n", "@return boolean\n"), array("@var int\n", "@var bool\n", "@param int\n", "@param bool\n", "@return int\n", "@return bool\n"), $entityCode);
     $this->filesystem->mkdir(dirname($entityPath));
     file_put_contents($entityPath, $entityCode);
     if ($mappingPath) {
         $this->filesystem->mkdir(dirname($mappingPath));
         file_put_contents($mappingPath, $mappingCode);
     }
     $path = $bundle->getPath() . str_repeat('/..', substr_count(get_class($bundle), '\\'));
     $this->getRepositoryGenerator()->writeEntityRepositoryClass($class->customRepositoryClassName, $path);
     $repositoryPath = $path . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $class->customRepositoryClassName) . '.php';
     return new EntityGeneratorResult($entityPath, $repositoryPath, $mappingPath);
 }
 protected function setUp()
 {
     $this->importProcessor = $this->getMockBuilder('Oro\\Bundle\\IntegrationBundle\\ImportExport\\Processor\\StepExecutionAwareImportProcessor')->disableOriginalConstructor()->getMock();
     $this->exportProcessor = $this->getMockBuilder('Oro\\Bundle\\IntegrationBundle\\ImportExport\\Processor\\StepExecutionAwareExportProcessor')->disableOriginalConstructor()->getMock();
     $this->importProcessor->expects($this->any())->method('process')->will($this->returnCallback(function ($item) {
         $keys = array_map(function ($key) {
             return Inflector::camelize($key);
         }, array_keys($item));
         return (object) array_combine($keys, array_values($item));
     }));
     $this->exportProcessor->expects($this->any())->method('process')->will($this->returnCallback(function ($item) {
         $item = (array) $item;
         $keys = array_map(function ($key) {
             return Inflector::tableize($key);
         }, array_keys($item));
         return array_combine($keys, array_values($item));
     }));
     $this->strategy = new TwoWaySyncStrategy($this->importProcessor, $this->exportProcessor);
 }
 /**
  * @param object $entity
  * @return array|null
  */
 protected function _serializeEntity($entity)
 {
     $className = get_class($entity);
     $metadata = $this->_em->getClassMetadata($className);
     $data = array();
     foreach ($metadata->fieldMappings as $field => $mapping) {
         $value = $metadata->reflFields[$field]->getValue($entity);
         $field = Inflector::tableize($field);
         if ($value instanceof \DateTime) {
             // We cast DateTime to array to keep consistency with array result
             $data[$field] = (array) $value;
         } elseif (is_object($value)) {
             $data[$field] = (string) $value;
         } else {
             $data[$field] = $value;
         }
     }
     foreach ($metadata->associationMappings as $field => $mapping) {
         $key = Inflector::tableize($field);
         if ($mapping['isCascadeDetach']) {
             $data[$key] = $metadata->reflFields[$field]->getValue($entity);
             if (null !== $data[$key]) {
                 $data[$key] = $this->_serializeEntity($data[$key]);
             }
         } elseif ($mapping['isOwningSide'] && $mapping['type'] & ClassMetadata::TO_ONE) {
             if (null !== $metadata->reflFields[$field]->getValue($entity)) {
                 if ($this->_recursionDepth < $this->_maxRecursionDepth) {
                     $this->_recursionDepth++;
                     $data[$key] = $this->_serializeEntity($metadata->reflFields[$field]->getValue($entity));
                     $this->_recursionDepth--;
                 } else {
                     $data[$key] = $this->getEntityManager()->getUnitOfWork()->getEntityIdentifier($metadata->reflFields[$field]->getValue($entity));
                 }
             } else {
                 // In some case the relationship may not exist, but we want
                 // to know about it
                 $data[$key] = null;
             }
         }
     }
     return $data;
 }
Exemple #14
0
 /**
  * Convenient method that intercepts the find*By*() calls.
  *
  * @param string $method
  * @param array $arguments
  * @return method
  * @throws RuntimeException
  */
 public function __call($method, $arguments)
 {
     if (strpos($method, 'findOneBy') === 0) {
         $property = substr($method, 9);
         $method = 'findOneBy';
     } elseif (strpos($method, 'findBy') === 0) {
         $property = substr($method, 6);
         $method = 'findBy';
     } else {
         throw new RuntimeException(sprintf("The %s repository class does not have a method %s", get_called_class(), $method));
     }
     $property = Inflector::tableize($property);
     foreach ($arguments as $position => $argument) {
         if (is_object($argument)) {
             if (!method_exists($argument, 'getRid')) {
                 throw new RuntimeException("When calling \$repository->find*By*(), you can only pass, as arguments, objects that have the getRid() method (shortly, entitites)");
             }
             $arguments[$position] = $argument->getRid();
         }
     }
     return $this->{$method}(array($property => $arguments[0]));
 }
 public function toDOMDocument()
 {
     $arrToXml = function ($node, $data) use(&$arrToXml) {
         foreach ($data as $k => $v) {
             $child = $node->ownerDocument->createElement($k);
             $node->appendChild($child);
             if (is_array($v)) {
                 $arrToXml($child, $v);
             } else {
                 $child->appendChild($node->ownerDocument->createTextNode($v));
             }
         }
     };
     $className = get_class($this);
     $em = ActiveEntityRegistry::getClassManager($className);
     $class = $em->getClassMetadata($className);
     $dom = new \DOMDocument('1.0', 'UTF-8');
     $root = $dom->createElement(Inflector::tableize($class->reflClass->getShortName()));
     $dom->appendChild($root);
     $arrToXml($root, $this->toArray());
     return $dom;
 }
Exemple #16
0
 /**
  * Reverse engineering of the model from the database structure.
  * Write result to the entity folder
  * 
  * WARNING THIS WILL OVERWRITE EXISTING MODEL.
  * 
  * @return boolean 
  */
 public function generate_model()
 {
     if (!$this->is_dev()) {
         return false;
     }
     $root = $this->get_entity_path();
     $connection_parameters = $this->get_connection_parameters();
     $connection = Doctrine\DBAL\DriverManager::getConnection($connection_parameters);
     $platform = $connection->getDatabasePlatform();
     $platform->registerDoctrineTypeMapping('enum', 'string');
     $platform->registerDoctrineTypeMapping('set', 'string');
     $config = Setup::createConfiguration($this->is_dev());
     $config->setMetadataDriverImpl(new Doctrine\ORM\Mapping\Driver\DatabaseDriver(new Doctrine\DBAL\Schema\MySqlSchemaManager($connection)));
     $em = EntityManager::create($connection, $config);
     $cmf = new Doctrine\ORM\Tools\DisconnectedClassMetadataFactory();
     $cmf->setEntityManager($em);
     $metadatas = $cmf->getAllMetadata();
     $repo_factory = new EntityRepositoryGenerator();
     $course = null;
     foreach ($metadatas as $metadata) {
         $n = strtolower($metadata->name);
         if ($n == 'course') {
             $course = $metadata;
             break;
         }
     }
     foreach ($metadatas as $metadata) {
         echo sprintf('Processing entity "<info>%s</info>"', $metadata->name) . '<br/>';
         foreach ($metadata->identifier as $key => $value) {
             //$mapping = $metadata->fieldMappings[$value];
             $metadata->identifier[$key] = Inflector::tableize($value);
         }
         $fields = array();
         foreach ($metadata->fieldMappings as $fieldMapping) {
             $name = Inflector::tableize($fieldMapping['fieldName']);
             $fieldMapping['fieldName'] = $name;
             $fields[$name] = $fieldMapping;
         }
         $metadata->fieldMappings = $fields;
         $n = $metadata->name;
         if ($n == 'CDocument') {
             $i = 1;
         }
         $name = $metadata->name;
         $name = Inflector::tableize($name);
         $is_course_table = strpos($name, 'c_') === 0;
         if ($is_course_table) {
             $name = substr($name, 2, strlen($name) - 2);
         }
         //$metadata->namespace = 'Entity';
         $metadata->customRepositoryClassName = 'Entity\\Repository\\' . Inflector::classify($name) . 'Repository';
         //if(is_course_table){
         $metadata->name = 'Entity\\' . Inflector::classify($name);
         $metadata->lifecycleCallbacks['prePersist'] = array('before_save');
         //}
         //$metadata->rootEntityName = Inflector::classify($name);
         if ($is_course_table) {
             foreach ($metadata->fieldMappings as $mapping) {
                 $name = $mapping['columnName'];
                 $is_id = isset($mapping['id']) ? $mapping['id'] : false;
                 if ($name != 'c_id' && $is_id) {
                 }
             }
         }
         if ($is_course_table) {
             $metadata->is_course_table = true;
             //                $mapping = array();
             //                $mapping['cascade'] = array();
             //                $mapping['joinColumns'][0] = array('name' => 'c_id', 'referencedColumnName' => 'id');
             //                $mapping['sourceToTargetKeyColumns']['c_id'] = 'id';
             //                $mapping['joinColumnFieldNames']['c_id'] = 'c_id';
             //                $mapping['targetToSourceKeyColumns']['id'] = 'c_id';
             //                $mapping['id'] = 1;
             //                $mapping['isOwningSide'] = 0;
             //                $mapping['isCascadeRemove'] = 0;
             //                $mapping['isCascadePersist'] = 0;
             //                $mapping['isCascadeRefresh'] = 0;
             //                $mapping['isCascadeMerge'] = 0;
             //                $mapping['isCascadeDetach'] = 0;
             //                $mapping['orphanRemoval'] = 0;
             //                $mapping['type'] = ClassMetadataInfo::MANY_TO_ONE;
             //                $mapping['fetch'] = ClassMetadataInfo::FETCH_LAZY;
             //                $mapping['fieldName'] = 'course';
             //                $mapping['targetEntity'] = 'Entity\\Course';
             //                $mapping['sourceEntity'] = $metadata->name;
             //
             //                $metadata->associationMappings['course'] = $mapping;
             //                $metadata->identifier['course'];
             //                unset($metadata->identifier['c_id']);
             //                unset($metadata->fieldMappings['c_id']);
             //                $mapping = array();
             //                $mapping['cascade'] = array();
             //                $mapping['joinColumns'][0] = array('name' => 'id', 'referencedColumnName' => 'c_id');
             //                $mapping['sourceToTargetKeyColumns']['id'] = 'c_id';
             //                $mapping['joinColumnFieldNames']['id'] = 'id';
             //                $mapping['targetToSourceKeyColumns']['c_id'] = 'id';
             //                $mapping['id'] = 1;
             //                $mapping['isOwningSide'] = 1;
             //                $mapping['isCascadeRemove'] = 0;
             //                $mapping['isCascadePersist'] = 0;
             //                $mapping['isCascadeRefresh'] = 0;
             //                $mapping['isCascadeMerge'] = 0;
             //                $mapping['isCascadeDetach'] = 0;
             //                $mapping['orphanRemoval'] = 0;
             //                $mapping['type'] = ClassMetadataInfo::ONE_TO_MANY;
             //                $mapping['fetch'] = ClassMetadataInfo::FETCH_LAZY;
             //                $name = explode('\\' ,$metadata->name);
             //                $name = end($name);
             //                $name = Inflector::tableize($name);
             //                $mapping['fieldName'] = $name;
             //                $mapping['targetEntity'] = $metadata->name;
             //                $mapping['sourceEntity'] = 'Entity\\Course';
             //                $course->associationMappings[$name] = $mapping;
         }
         $metadata->class_to_extend = $is_course_table ? 'CourseEntity' : 'Entity';
         $repo_factory->writeEntityRepositoryClass($metadata->name, $root . '\\repository\\');
     }
     $generator = new EntityGenerator();
     $generator->setClassToExtend('Entity');
     $generator->setGenerateAnnotations(false);
     $generator->setGenerateStubMethods(true);
     $generator->setRegenerateEntityIfExists(false);
     $generator->setUpdateEntityIfExists(false);
     $generator->setBackupExisting(false);
     $generator->setExtension('.class.php');
     $generator->setNumSpaces(4);
     // Generating Entities
     $generator->generate($metadatas, $root);
     $exporter = new \Doctrine\ORM\Tools\Export\Driver\YamlExporter();
     $exporter->setOutputDir($root . '/mapping');
     foreach ($metadatas as $metadata) {
         echo $metadata->name . '<br/>';
         try {
             $exporter->setMetadata(array($metadata));
             $exporter->export();
         } catch (Exception $e) {
             echo $e->getMessage();
         }
     }
 }
 protected function getColumn($class, $property)
 {
     if (isset($this->cache[$class . '::' . $property])) {
         return $this->cache[$class . '::' . $property];
     }
     $table = $this->getTable($class);
     if ($table && $table->hasColumn($property)) {
         return $this->cache[$class . '::' . $property] = $table->getColumn($property);
     } else {
         foreach ($table->getColumns() as $column) {
             if (Inflector::tableize($column->getPhpName()) === $property) {
                 return $this->cache[$class . '::' . $property] = $column;
             }
         }
     }
 }
 /**
  * @return string
  */
 protected function getAlias()
 {
     $name = basename(str_replace('\\', '/', $this->getClassName()));
     return Inflector::tableize($name);
 }
    private function _generateEntityStubMethod(ClassMetadataInfo $metadata, $type, $fieldName, $typeHint = null, $defaultValue = null)
    {

        $fieldName = Inflector::tableize($fieldName);
        if ($type == "add") {
            $addMethod = explode("\\", $typeHint);
            $addMethod = end($addMethod);
            $methodName = $type . $addMethod;
        } else {
            //change
            $methodName = $type . '_' . Inflector::tableize($fieldName);
            //
        }

        if ($this->_hasMethod($methodName, $metadata)) {
            return;
        }
        $this->_staticReflection[$metadata->name]['methods'][] = $methodName;

        $var = sprintf('_%sMethodTemplate', $type);
        $template = self::$$var;

        $variableType = $typeHint ? $typeHint . ' ' : null;

        $types = \Doctrine\DBAL\Types\Type::getTypesMap();
        $methodTypeHint = $typeHint && !isset($types[$typeHint]) ? '\\' . $typeHint . ' ' : null;

        $replacements = array(
            '<description>' => ucfirst($type) . ' ' . $fieldName,
            '<methodTypeHint>' => $methodTypeHint,
            '<variableType>' => $variableType,
            '<variableName>' => 'value',
            '<methodName>' => $methodName,
            '<fieldName>' => $fieldName,
            '<variableDefault>' => ($defaultValue !== null ) ? (' = ' . $defaultValue) : '',
            '<entity>' => $this->_getClassName($metadata)
        );

        $method = str_replace(
            array_keys($replacements), array_values($replacements), $template
        );

        return $this->_prefixCodeWithSpaces($method);
    }
Exemple #20
0
 /**
  * Serialize an entity to an array
  *
  * @author      Boris Guéry <*****@*****.**>
  * @license     http://sam.zoy.org/wtfpl/COPYING
  * @link        http://borisguery.github.com/bgylibrary
  * @see         https://gist.github.com/1034079#file_serializable_entity.php
  * @param       $entity
  * @return      array
  */
 protected function serializeEntity($entity)
 {
     if ($entity instanceof \Doctrine\ORM\Proxy\Proxy) {
         /** @var $entity \Doctrine\ORM\Proxy\Proxy */
         $entity->__load();
         $className = get_parent_class($entity);
     } else {
         $className = get_class($entity);
     }
     $metadata = $this->getClassMetadata($className);
     $data = array();
     foreach ($metadata->fieldMappings as $field => $mapping) {
         $data[$field] = $metadata->reflFields[$field]->getValue($entity);
     }
     foreach ($metadata->associationMappings as $field => $mapping) {
         $key = Inflector::tableize($field);
         if ($mapping['isCascadeDetach']) {
             $data[$key] = $metadata->reflFields[$field]->getValue($entity);
             if (null !== $data[$key]) {
                 $data[$key] = $this->serializeEntity($data[$key]);
             }
         } elseif ($mapping['isOwningSide'] && $mapping['type'] & ClassMetadata::TO_ONE) {
             if (null !== $metadata->reflFields[$field]->getValue($entity)) {
                 $data[$key] = $this->getUnitOfWork()->getEntityIdentifier($metadata->reflFields[$field]->getValue($entity));
             } else {
                 // In some case the relationship may not exist, but we want
                 // to know about it
                 $data[$key] = null;
             }
         }
     }
     return $data;
 }
Exemple #21
0
 /**
  * return string@
  */
 public function getTableName()
 {
     if (!isset($this->tableName)) {
         return \Doctrine\Common\Util\Inflector::tableize($this->getEntityName()) . 's';
     }
     return $this->tableName;
 }
Exemple #22
0
 /**
  * Tries to guess block template name.
  * @return string
  */
 private function guessTemplateName()
 {
     if ($this->package === null) {
         throw new \RuntimeException(sprintf('Block package is unknown, thus it is impossible to guess template name for block [%s].', $this->getTitle()));
     }
     $name = (new \ReflectionClass($this))->getShortName();
     if (($pos = strpos($name, 'Config')) !== false && $pos === strlen($name) - 6) {
         $name = substr($name, 0, -6);
     }
     return $this->package->getName() . ':blocks' . DIRECTORY_SEPARATOR . Inflector::tableize($name) . '.html.twig';
 }
 /**
  * {@inheritdoc}
  */
 public function loadMetadataForClass($className, ClassMetadataInfo $metadata)
 {
     $this->reverseEngineerMappingFromDatabase();
     if (!isset($this->classes[$className])) {
         throw new \InvalidArgumentException("Unknown class " . $className);
     }
     $tableName = Inflector::tableize($className);
     $metadata->name = $className;
     $metadata->table['name'] = $tableName;
     $columns = $this->tables[$tableName]->getColumns();
     $indexes = $this->tables[$tableName]->getIndexes();
     if ($this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) {
         $foreignKeys = $this->tables[$tableName]->getForeignKeys();
     } else {
         $foreignKeys = array();
     }
     $allForeignKeyColumns = array();
     foreach ($foreignKeys as $foreignKey) {
         $allForeignKeyColumns = array_merge($allForeignKeyColumns, $foreignKey->getLocalColumns());
     }
     $ids = array();
     $fieldMappings = array();
     foreach ($columns as $column) {
         $fieldMapping = array();
         if (isset($indexes['primary']) && in_array($column->getName(), $indexes['primary']->getColumns())) {
             $fieldMapping['id'] = true;
         } else {
             if (in_array($column->getName(), $allForeignKeyColumns)) {
                 continue;
             }
         }
         $fieldMapping['fieldName'] = Inflector::camelize(strtolower($column->getName()));
         $fieldMapping['columnName'] = $column->getName();
         $fieldMapping['type'] = strtolower((string) $column->getType());
         if ($column->getType() instanceof \Doctrine\DBAL\Types\StringType) {
             $fieldMapping['length'] = $column->getLength();
             $fieldMapping['fixed'] = $column->getFixed();
         } else {
             if ($column->getType() instanceof \Doctrine\DBAL\Types\IntegerType) {
                 $fieldMapping['unsigned'] = $column->getUnsigned();
             }
         }
         $fieldMapping['nullable'] = $column->getNotNull() ? false : true;
         if (isset($fieldMapping['id'])) {
             $ids[] = $fieldMapping;
         } else {
             $fieldMappings[] = $fieldMapping;
         }
     }
     if ($ids) {
         if (count($ids) == 1) {
             $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO);
         }
         foreach ($ids as $id) {
             $metadata->mapField($id);
         }
     }
     foreach ($fieldMappings as $fieldMapping) {
         $metadata->mapField($fieldMapping);
     }
     foreach ($this->manyToManyTables as $manyTable) {
         foreach ($manyTable->getForeignKeys() as $foreignKey) {
             if ($tableName == strtolower($foreignKey->getForeignTableName())) {
                 $myFk = $foreignKey;
                 foreach ($manyTable->getForeignKeys() as $foreignKey) {
                     if ($foreignKey != $myFk) {
                         $otherFk = $foreignKey;
                         break;
                     }
                 }
                 $localColumn = current($myFk->getColumns());
                 $associationMapping = array();
                 $associationMapping['fieldName'] = Inflector::camelize(str_replace('_id', '', strtolower(current($otherFk->getColumns()))));
                 $associationMapping['targetEntity'] = Inflector::classify(strtolower($otherFk->getForeignTableName()));
                 if (current($manyTable->getColumns())->getName() == $localColumn) {
                     $associationMapping['inversedBy'] = Inflector::camelize(str_replace('_id', '', strtolower(current($myFk->getColumns()))));
                     $associationMapping['joinTable'] = array('name' => strtolower($manyTable->getName()), 'joinColumns' => array(), 'inverseJoinColumns' => array());
                     $fkCols = $myFk->getForeignColumns();
                     $cols = $myFk->getColumns();
                     for ($i = 0; $i < count($cols); $i++) {
                         $associationMapping['joinTable']['joinColumns'][] = array('name' => $cols[$i], 'referencedColumnName' => $fkCols[$i]);
                     }
                     $fkCols = $otherFk->getForeignColumns();
                     $cols = $otherFk->getColumns();
                     for ($i = 0; $i < count($cols); $i++) {
                         $associationMapping['joinTable']['inverseJoinColumns'][] = array('name' => $cols[$i], 'referencedColumnName' => $fkCols[$i]);
                     }
                 } else {
                     $associationMapping['mappedBy'] = Inflector::camelize(str_replace('_id', '', strtolower(current($myFk->getColumns()))));
                 }
                 $metadata->mapManyToMany($associationMapping);
                 break;
             }
         }
     }
     foreach ($foreignKeys as $foreignKey) {
         $foreignTable = $foreignKey->getForeignTableName();
         $cols = $foreignKey->getColumns();
         $fkCols = $foreignKey->getForeignColumns();
         $localColumn = current($cols);
         $associationMapping = array();
         $associationMapping['fieldName'] = Inflector::camelize(str_replace('_id', '', strtolower($localColumn)));
         $associationMapping['targetEntity'] = Inflector::classify($foreignTable);
         for ($i = 0; $i < count($cols); $i++) {
             $associationMapping['joinColumns'][] = array('name' => $cols[$i], 'referencedColumnName' => $fkCols[$i]);
         }
         $metadata->mapManyToOne($associationMapping);
     }
 }
 /**
  * @test
  * @dataProvider routes
  *
  * @param $actionClass
  */
 public function it_returns_the_correct_route_names($actionClass)
 {
     $refl = new \ReflectionClass($actionClass);
     $name = Inflector::tableize($refl->getShortName());
     $this->assertEquals($this->bundlePrefix . '.posts.' . $name, $this->config->getActions()->get($actionClass)->getRouteName());
 }
 /**
  * @param string            $className
  * @param array             $model
  * @param ClassMetadataInfo $metadata
  *
  * @return void
  */
 private function convertRelations($className, array $model, ClassMetadataInfo $metadata)
 {
     if (empty($model['relations'])) {
         return;
     }
     foreach ($model['relations'] as $name => $relation) {
         if (!isset($relation['alias'])) {
             $relation['alias'] = $name;
         }
         if (!isset($relation['class'])) {
             $relation['class'] = $name;
         }
         if (!isset($relation['local'])) {
             $relation['local'] = Inflector::tableize($relation['class']);
         }
         if (!isset($relation['foreign'])) {
             $relation['foreign'] = 'id';
         }
         if (!isset($relation['foreignAlias'])) {
             $relation['foreignAlias'] = $className;
         }
         if (isset($relation['refClass'])) {
             $type = 'many';
             $foreignType = 'many';
             $joinColumns = array();
         } else {
             $type = isset($relation['type']) ? $relation['type'] : 'one';
             $foreignType = isset($relation['foreignType']) ? $relation['foreignType'] : 'many';
             $joinColumns = array(array('name' => $relation['local'], 'referencedColumnName' => $relation['foreign'], 'onDelete' => isset($relation['onDelete']) ? $relation['onDelete'] : null));
         }
         if ($type == 'one' && $foreignType == 'one') {
             $method = 'mapOneToOne';
         } elseif ($type == 'many' && $foreignType == 'many') {
             $method = 'mapManyToMany';
         } else {
             $method = 'mapOneToMany';
         }
         $associationMapping = array();
         $associationMapping['fieldName'] = $relation['alias'];
         $associationMapping['targetEntity'] = $relation['class'];
         $associationMapping['mappedBy'] = $relation['foreignAlias'];
         $associationMapping['joinColumns'] = $joinColumns;
         $metadata->{$method}($associationMapping);
     }
 }
    /**
     *
     * @param type $name
     * @param type $outputDirectory 
     */
    public function writeEntityRepositoryClass($name, $outputDirectory)
    {
        $name = explode('\\', $name);
        $name = end($name);
        $name = Inflector::tableize($name);
        $is_course_table = (strpos($name, 'c_') === 0);
        if ($is_course_table) {
            $name = substr($name, 2, strlen($name) - 2);
        }
        $name = Inflector::classify($name) . 'Repository';
        $fullClassName = $name;
        
        $file_name = Inflector::tableize($name);

        $code = $this->generateEntityRepositoryClass($fullClassName);

        $path = $outputDirectory . DIRECTORY_SEPARATOR
            . str_replace('\\', \DIRECTORY_SEPARATOR, $file_name) . '.class.php';
        $dir = dirname($path);

        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }

        if (!file_exists($path)) {
            file_put_contents($path, $code);
        }
    }
 public function __isset($field)
 {
     if ($this->_valueExists($field)) {
         return true;
     }
     $_field = Inflector::tableize($field);
     if ($_field != $field && $this->_valueExists($_field)) {
         return true;
     }
     $_field = Inflector::camelize($field);
     if ($_field != $field && $this->_valueExists($_field)) {
         return true;
     }
     return false;
 }
Exemple #28
0
 private function tableize($className)
 {
     return Inflector::tableize(str_replace('\\', '', $className));
 }
 /**
  * @param Text $text
  *
  * @return Slug
  */
 public function slugify(Text $text)
 {
     return new Slug(Inflector::tableize((string) $text));
 }
 public function fieldsAsArray()
 {
     $fields = array();
     $refclass = new \ReflectionClass($this);
     foreach ($refclass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
         $name = $methodName = $method->getName();
         if (preg_match('/^get/', $name)) {
             $name = substr($name, 3);
             $name = \Doctrine\Common\Util\Inflector::tableize($name);
             $name = str_replace(array('t_v_a', 'h_t', 't_t_c'), array('TVA', 'HT', 'TTC'), $name);
             $fields[$name] = $this->{$methodName}();
         }
     }
     return $fields;
 }