Exemplo n.º 1
0
 public function hydrateEntity($entity, array $values)
 {
     $classMetadata = $this->em->getClassMetadata(get_class($entity));
     foreach ($values as $fieldName => $value) {
         if ($classMetadata->hasField($fieldName)) {
             $fieldMappping = $classMetadata->getFieldMapping($fieldName);
             if (null === $fieldMappping) {
                 throw new HydrationException($fieldName);
             }
             $type = Type::getType($classMetadata->fieldMappings[$fieldName]['type']);
             $value = $type->convertToPHPValue($value, $this->em->getConnection()->getDatabasePlatform());
             $classMetadata->setFieldValue($entity, $fieldName, $value);
         } elseif (isset($classMetadata->associationMappings[$fieldName])) {
             $fieldMapping = $classMetadata->associationMappings[$fieldName];
             if (ClassMetadataInfo::MANY_TO_MANY === $fieldMapping['type']) {
                 // expecting an array of ids in $value
                 if (1 === count($fieldMapping['relationToTargetKeyColumns'])) {
                     $columnName = array_pop($fieldMapping['relationToTargetKeyColumns']);
                     $otherSideMapping = $this->em->getClassMetadata($fieldMapping['targetEntity']);
                     $value = $this->em->getRepository($fieldMapping['targetEntity'])->findBy(array($otherSideMapping->fieldNames[$columnName] => $value));
                 }
                 $classMetadata->setFieldValue($entity, $fieldName, $value);
             } elseif (ClassMetadataInfo::MANY_TO_ONE === $fieldMapping['type']) {
                 // expecting an array of ids in $value
                 $value = $this->em->getRepository($fieldMapping['targetEntity'])->find($value);
                 $classMetadata->setFieldValue($entity, $fieldName, $value);
             }
         } else {
             throw new HydrationException($fieldName);
         }
     }
 }
Exemplo n.º 2
0
 private function getFieldByTagVaule($tag_value)
 {
     $value_and_params = $this->parseTagValueAndParameters($tag_value);
     $type = trim($value_and_params['value']);
     $params = $value_and_params['parameters'];
     return new \Hitar\FieldType($params, \Doctrine\DBAL\Types\Type::getType($type));
 }
 /**
  * @test
  */
 public function table_should_contain_binary_uuid_column()
 {
     $uuidColumn = $this->table->getColumn('uuid');
     $this->assertEquals(16, $uuidColumn->getLength());
     $this->assertEquals(Type::getType(Type::BINARY), $uuidColumn->getType());
     $this->assertTrue($uuidColumn->getFixed());
 }
Exemplo n.º 4
0
 protected function convertResultsInternal($results, AbstractPlatform $platform, CaseSensor $sensor)
 {
     if (is_array($results)) {
         $results = current($results);
     }
     return Type::getType($this->type)->convertToPHPValue($results, $platform);
 }
Exemplo n.º 5
0
 /**
  * Walks down a SelectStatement AST node, modifying it to retrieve DISTINCT ids
  * of the root Entity
  *
  * @param SelectStatement $AST
  * @return void
  */
 public function walkSelectStatement(SelectStatement $AST)
 {
     $parent = null;
     $parentName = null;
     $selectExpressions = array();
     foreach ($this->_getQueryComponents() as $dqlAlias => $qComp) {
         // preserve mixed data in query for ordering
         if (isset($qComp['resultVariable'])) {
             $selectExpressions[] = new SelectExpression($qComp['resultVariable'], $dqlAlias);
             continue;
         }
         if ($qComp['parent'] === null && $qComp['nestingLevel'] == 0) {
             $parent = $qComp;
             $parentName = $dqlAlias;
             continue;
         }
     }
     $identifier = $parent['metadata']->getSingleIdentifierFieldName();
     $this->_getQuery()->setHint(self::IDENTIFIER_TYPE, Type::getType($parent['metadata']->getTypeOfField($identifier)));
     $pathExpression = new PathExpression(PathExpression::TYPE_STATE_FIELD | PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, $parentName, $identifier);
     $pathExpression->type = PathExpression::TYPE_STATE_FIELD;
     array_unshift($selectExpressions, new SelectExpression($pathExpression, '_dctrn_id'));
     $AST->selectClause->selectExpressions = $selectExpressions;
     if (isset($AST->orderByClause)) {
         foreach ($AST->orderByClause->orderByItems as $item) {
             if ($item->expression instanceof PathExpression) {
                 $pathExpression = new PathExpression(PathExpression::TYPE_STATE_FIELD | PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, $item->expression->identificationVariable, $item->expression->field);
                 $pathExpression->type = PathExpression::TYPE_STATE_FIELD;
                 $AST->selectClause->selectExpressions[] = new SelectExpression($pathExpression, '_dctrn_ord' . $this->_aliasCounter++);
             }
         }
     }
     $AST->selectClause->isDistinct = true;
 }
Exemplo n.º 6
0
 /**
  * @inheritdoc
  */
 public function up(Schema $schema, QueryBag $queries)
 {
     $table = $schema->getTable('orocrm_sales_opportunity');
     $table->getColumn('probability')->setType(Type::getType('percent'));
     $table->getColumn('budget_amount')->setType(Type::getType('money'));
     $table->getColumn('close_revenue')->setType(Type::getType('money'));
 }
Exemplo n.º 7
0
 /**
  * {@inheritdoc}
  */
 public function up(Schema $schema, QueryBag $queries)
 {
     $table = $schema->getTable('orocrm_magento_cart');
     $table->getColumn('items_qty')->setType(Type::getType('float'));
     $table = $schema->getTable('orocrm_magento_order_items');
     $table->getColumn('qty')->setType(Type::getType('float'));
 }
Exemplo n.º 8
0
 /**
  * Create service
  *
  * @param  ServiceLocatorInterface $validators
  * @return mixed
  */
 public function createService(ServiceLocatorInterface $validators)
 {
     if (isset($this->options['enum'])) {
         $this->options['enum'] = DoctrineType::getType($this->options['enum']);
     }
     return new EnumValidator($this->options);
 }
Exemplo n.º 9
0
 public function testAlterTableSql()
 {
     $changes = array('name' => 'userlist', 'add' => array('quota' => array('type' => Type::getType('integer'))));
     $sql = $this->_platform->getAlterTableSql('mytable', $changes);
     $this->assertEquals('ALTER TABLE mytable ADD quota INT DEFAULT NULL', $sql[0]);
     $this->assertEquals('ALTER TABLE mytable RENAME TO userlist', $sql[1]);
 }
 /**
  * @test
  */
 public function I_can_register_all_codes_at_once()
 {
     $typeName = $this->getExpectedTypeName();
     self::assertFalse(Type::hasType($typeName), "Type of name '{$typeName}' should not be registered yet");
     /** @var ScalarEnumType $typeClass */
     $typeClass = $this->getTypeClass();
     foreach ($this->getRelatedCodeClasses() as $relatedCodeClass) {
         self::assertFalse($typeClass::hasSubTypeEnum($relatedCodeClass), "Sub-type enum of a class '{$relatedCodeClass}' should not be registered yet");
     }
     $typeClass::registerSelf();
     self::assertTrue(Type::hasType($typeName), "Type of name '{$typeName}' is not registered");
     $testedType = Type::getType($typeName);
     $platform = $this->createPlatform();
     foreach ($this->getRelatedCodeClasses() as $relatedCodeClass) {
         self::assertTrue($typeClass::hasSubTypeEnum($relatedCodeClass), "Sub-type enum of a class '{$relatedCodeClass}' is not registered");
         foreach ($relatedCodeClass::getPossibleValues() as $possibleValue) {
             $asPhp = $testedType->convertToPHPValue($relatedCodeClass . '::' . $possibleValue, $platform);
             self::assertInstanceOf($relatedCodeClass, $asPhp);
             /** @var AbstractCode $asPhp */
             self::assertSame($possibleValue, $asPhp->getValue());
         }
     }
     $typeClass::registerSelf();
     // test if can call registering repeatedly
 }
 /**
  * Walks down a SelectStatement AST node, modifying it to retrieve DISTINCT ids
  * of the root Entity.
  *
  * @param SelectStatement $AST
  *
  * @return void
  *
  * @throws \RuntimeException
  */
 public function walkSelectStatement(SelectStatement $AST)
 {
     $queryComponents = $this->_getQueryComponents();
     // Get the root entity and alias from the AST fromClause
     $from = $AST->fromClause->identificationVariableDeclarations;
     $fromRoot = reset($from);
     $rootAlias = $fromRoot->rangeVariableDeclaration->aliasIdentificationVariable;
     $rootClass = $queryComponents[$rootAlias]['metadata'];
     $selectExpressions = array();
     foreach ($queryComponents as $dqlAlias => $qComp) {
         // Preserve mixed data in query for ordering.
         if (isset($qComp['resultVariable'])) {
             $selectExpressions[] = new SelectExpression($qComp['resultVariable'], $dqlAlias);
             continue;
         }
     }
     $identifier = $rootClass->getSingleIdentifierFieldName();
     if (isset($rootClass->associationMappings[$identifier])) {
         throw new \RuntimeException("Paginating an entity with foreign key as identifier only works when using the Output Walkers. Call Paginator#setUseOutputWalkers(true) before iterating the paginator.");
     }
     $this->_getQuery()->setHint(self::IDENTIFIER_TYPE, Type::getType($rootClass->getTypeOfField($identifier)));
     $pathExpression = new PathExpression(PathExpression::TYPE_STATE_FIELD | PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, $rootAlias, $identifier);
     $pathExpression->type = PathExpression::TYPE_STATE_FIELD;
     array_unshift($selectExpressions, new SelectExpression($pathExpression, '_dctrn_id'));
     $AST->selectClause->selectExpressions = $selectExpressions;
     if (isset($AST->orderByClause)) {
         foreach ($AST->orderByClause->orderByItems as $item) {
             if (!$item->expression instanceof PathExpression) {
                 continue;
             }
             $AST->selectClause->selectExpressions[] = new SelectExpression($this->createSelectExpressionItem($item->expression), '_dctrn_ord' . $this->_aliasCounter++);
         }
     }
     $AST->selectClause->isDistinct = true;
 }
 /**
  * {@inheritdoc}
  */
 public function convertValue($value, array $options, ConversionHints $hints)
 {
     if (2 === $hints->conversionStrategy || 3 === $hints->conversionStrategy) {
         return DBALType::getType('date')->convertToDatabaseValue($value, $hints->connection->getDatabasePlatform());
     }
     return (int) $value;
 }
Exemplo n.º 13
0
 /**
  * @group DDC-1337
  * @return void
  */
 public function testCreateTemporaryTableNotAutoCommitTransaction()
 {
     if ($this->_conn->getDatabasePlatform()->getName() == 'sqlanywhere' || $this->_conn->getDatabasePlatform()->getName() == 'oracle') {
         $this->markTestSkipped("Test does not work on Oracle and SQL Anywhere.");
     }
     $platform = $this->_conn->getDatabasePlatform();
     $columnDefinitions = array("id" => array("type" => Type::getType("integer"), "notnull" => true));
     $tempTable = $platform->getTemporaryTableName("my_temporary");
     $createTempTableSQL = $platform->getCreateTemporaryTableSnippetSQL() . ' ' . $tempTable . ' (' . $platform->getColumnDeclarationListSQL($columnDefinitions) . ')';
     $table = new Table("nontemporary");
     $table->addColumn("id", "integer");
     $table->setPrimaryKey(array('id'));
     foreach ($platform->getCreateTableSQL($table) as $sql) {
         $this->_conn->executeQuery($sql);
     }
     $this->_conn->beginTransaction();
     $this->_conn->insert("nontemporary", array("id" => 1));
     $this->_conn->exec($createTempTableSQL);
     $this->_conn->insert("nontemporary", array("id" => 2));
     $this->_conn->rollback();
     try {
         $this->_conn->exec($platform->getDropTemporaryTableSQL($tempTable));
     } catch (\Exception $e) {
     }
     $rows = $this->_conn->fetchAll('SELECT * FROM nontemporary');
     $this->assertEquals(array(), $rows, "In an event of an error this result has one row, because of an implicit commit.");
 }
Exemplo n.º 14
0
 public function test_importSchemaArray()
 {
     $instance = new Xoops\Core\Database\Schema\ExportVisitor();
     $table = new Doctrine\DBAL\Schema\Table('system_group');
     $type = Type::getType(Type::INTEGER);
     $col_name = 'groupid';
     $column = new Doctrine\DBAL\Schema\Column($col_name, $type);
     $instance->acceptColumn($table, $column);
     $columns = array('groupid');
     $fk_table = 'system_permission';
     $fk_name = 'fk_name';
     $fk_options = array('o' => 'o1');
     $fk_columns = array('system_permission');
     $fk_constraint = new Doctrine\DBAL\Schema\ForeignKeyConstraint($columns, $fk_table, $fk_columns, $fk_name, $fk_options);
     $instance->acceptForeignKey($table, $fk_constraint);
     $name = 'index_name';
     $columns = array('name', 'description');
     $unique = true;
     $primary = true;
     $index = new Doctrine\DBAL\Schema\Index($name, $columns, $unique, $primary);
     $instance->acceptIndex($table, $index);
     $name = 'sequence_name';
     $alloc_size = 10;
     $initial_value = 11;
     $sequence = new Doctrine\DBAL\Schema\Sequence($name, $alloc_size, $initial_value);
     $instance->acceptSequence($sequence);
     $schema = $instance->getSchemaArray();
     $import = new $this->myClass();
     $value = $import->importSchemaArray($schema);
     $this->assertInstanceOf('Doctrine\\DBAL\\Schema\\Schema', $value);
 }
Exemplo n.º 15
0
 /**
  * @param Schema   $schema
  * @param QueryBag $queries
  * @param string   $tableName
  * @param string   $columnName
  * @param string   $type
  *
  * @throws \Exception
  */
 public function changePrimaryKeyType(Schema $schema, QueryBag $queries, $tableName, $columnName, $type)
 {
     $targetColumn = $schema->getTable($tableName)->getColumn($columnName);
     $type = Type::getType($type);
     if ($targetColumn->getType() === $type) {
         return;
     }
     /** @var ForeignKeyConstraint[] $foreignKeys */
     $foreignKeys = [];
     foreach ($schema->getTables() as $table) {
         /** @var ForeignKeyConstraint[] $tableForeignKeys */
         $tableForeignKeys = array_filter($table->getForeignKeys(), function (ForeignKeyConstraint $tableForeignKey) use($tableName, $columnName) {
             if ($tableForeignKey->getForeignTableName() !== $tableName) {
                 return false;
             }
             return $tableForeignKey->getForeignColumns() === [$columnName];
         });
         foreach ($tableForeignKeys as $tableForeignKey) {
             $foreignKeys[$tableForeignKey->getName()] = $tableForeignKey;
             $foreignKeyTableName = $tableForeignKey->getLocalTable()->getName();
             $foreignKeyColumnNames = $tableForeignKey->getLocalColumns();
             $queries->addPreQuery($this->platform->getDropForeignKeySQL($tableForeignKey, $foreignKeyTableName));
             $column = $schema->getTable($foreignKeyTableName)->getColumn(reset($foreignKeyColumnNames));
             if ($column instanceof ExtendColumn) {
                 $column->disableExtendOptions()->setType($type)->enableExtendOptions();
             } else {
                 $column->setType($type);
             }
         }
     }
     $targetColumn->setType($type);
     foreach ($foreignKeys as $foreignKey) {
         $queries->addPostQuery($this->platform->getCreateForeignKeySQL($foreignKey, $foreignKey->getLocalTable()));
     }
 }
 protected function setUp()
 {
     $this->platform = $this->getMockBuilder('Doctrine\\DBAL\\Platforms\\AbstractPlatform')->setMethods(array('getVarcharTypeDeclarationSQL'))->getMockForAbstractClass();
     $this->platform->expects($this->any())->method('getVarcharTypeDeclarationSQL')->will($this->returnValue('DUMMYVARCHAR()'));
     $this->type = Type::getType('phone_number');
     $this->phoneNumberUtil = PhoneNumberUtil::getInstance();
 }
Exemplo n.º 17
0
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $schemaManager = $this->container['db']->getSchemaManager();
     foreach ($schemaManager->listTableColumns($this->table) as $column) {
         // here we try to display nicely database relations w/ foreign keys
         if (false !== strpos($column->getName(), '_id')) {
             $table = str_replace('_id', '', $column->getName());
             $dataMap = new DataMap($this->container['db'], $schemaManager);
             $choices = $dataMap->mapForeignKeys($table, $column);
             if (is_array($choices)) {
                 $column->setType(Type::getType('array'));
             }
         }
         switch ($column->getType()) {
             case 'Integer':
                 $builder->add($column->getName(), 'integer', array('read_only' => $column->getName() === 'id' ? true : false, 'required' => $column->getNotNull()));
                 break;
             case 'Array':
                 $builder->add($column->getName(), 'choice', array('choices' => $choices, 'required' => $column->getNotNull()));
                 break;
             case 'Boolean':
                 $builder->add($column->getName(), 'checkbox', array('required' => false));
                 break;
             case 'String':
                 $builder->add($column->getName(), 'text', array('required' => $column->getNotNull()));
                 break;
             case 'Text':
                 $builder->add($column->getName(), 'textarea', array('required' => $column->getNotNull()));
                 break;
         }
     }
 }
 /**
  * @param array $column
  *
  * @return Column
  */
 protected function _getPortableTableColumnDefinition($column)
 {
     $type = $this->orient2Doctrine[$column['type']];
     $type = $this->_platform->getDoctrineTypeMapping($type);
     $options = array('default' => isset($column['defaultValue']) ? $column['defaultValue'] : null, 'notnull' => isset($column['notNull']) ? $column['notNull'] : null, 'collate' => isset($column['collate']) ? $column['collate'] : null, 'length' => null, 'unsigned' => false, 'fixed' => false, 'scale' => null, 'precision' => null, 'autoincrement' => false, 'comment' => null);
     return new Column($column['name'], Type::getType($type), $options);
 }
Exemplo n.º 19
0
 /**
  * {@inheritdoc}
  */
 protected function _getPortableTableColumnDefinition($tableColumn)
 {
     $tableColumn = array_change_key_case($tableColumn, \CASE_LOWER);
     $length = null;
     $fixed = null;
     $unsigned = false;
     $scale = false;
     $precision = false;
     $type = $this->_platform->getDoctrineTypeMapping($tableColumn['typename']);
     switch (strtolower($tableColumn['typename'])) {
         case 'varchar':
             $length = $tableColumn['length'];
             $fixed = false;
             break;
         case 'character':
             $length = $tableColumn['length'];
             $fixed = true;
             break;
         case 'clob':
             $length = $tableColumn['length'];
             break;
         case 'decimal':
         case 'double':
         case 'real':
             $scale = $tableColumn['scale'];
             $precision = $tableColumn['length'];
             break;
     }
     $options = array('length' => $length, 'unsigned' => (bool) $unsigned, 'fixed' => (bool) $fixed, 'default' => $tableColumn['default'] == "NULL" ? null : $tableColumn['default'], 'notnull' => (bool) ($tableColumn['nulls'] == 'N'), 'scale' => null, 'precision' => null, 'platformOptions' => array());
     if ($scale !== null && $precision !== null) {
         $options['scale'] = $scale;
         $options['precision'] = $precision;
     }
     return new Column($tableColumn['colname'], \Doctrine\DBAL\Types\Type::getType($type), $options);
 }
 public function __construct(Connection $con)
 {
     $this->con = $con;
     $this->platform = $con->getDatabasePlatform();
     $this->phpType = Type::getType(PhpTypeType::NAME);
     $this->insertStmt = $con->prepare(self::INSERT_SQL);
 }
 /**
  * {@inheritdoc}
  */
 protected function _processSQLResult(array $sqlResult)
 {
     $data = array();
     $discrColumnName = $this->_platform->getSQLResultCasing($this->_class->discriminatorColumn['name']);
     $entityName = $this->_class->discriminatorMap[$sqlResult[$discrColumnName]];
     unset($sqlResult[$discrColumnName]);
     foreach ($sqlResult as $column => $value) {
         $realColumnName = $this->_resultColumnNames[$column];
         if (isset($this->declaringClassMap[$column])) {
             $class = $this->declaringClassMap[$column];
             if ($class->name == $entityName || is_subclass_of($entityName, $class->name)) {
                 $field = $class->fieldNames[$realColumnName];
                 if (isset($data[$field])) {
                     $data[$realColumnName] = $value;
                 } else {
                     $data[$field] = Type::getType($class->fieldMappings[$field]['type'])->convertToPHPValue($value, $this->_platform);
                 }
             }
         } else {
             if (isset($this->declaringJoinColumnMap[$column])) {
                 if ($this->declaringJoinColumnMap[$column] == $entityName || is_subclass_of($entityName, $this->declaringJoinColumnMap[$column])) {
                     $data[$realColumnName] = $value;
                 }
             } else {
                 $data[$realColumnName] = $value;
             }
         }
     }
     return array($entityName, $data);
 }
 protected function setUp()
 {
     if (!Type::hasType(PercentType::TYPE)) {
         Type::addType(PercentType::TYPE, 'Oro\\DBAL\\Types\\PercentType');
     }
     $this->percentType = Type::getType(PercentType::TYPE);
 }
Exemplo n.º 23
0
 private function getType($value)
 {
     try {
         return Type::getType(gettype($value))->getName();
     } catch (\Exception $e) {
         return 'text';
     }
 }
Exemplo n.º 24
0
 protected function setUp()
 {
     $this->_platform = new MockPlatform();
     if (!Type::hasType('vardatetime')) {
         Type::addType('vardatetime', 'Doctrine\\DBAL\\Types\\VarDateTimeType');
     }
     $this->_type = Type::getType('vardatetime');
 }
Exemplo n.º 25
0
 protected function setUp()
 {
     if (!Type::hasType($this->typeName)) {
         Type::addType($this->typeName, $this->typeClass);
     }
     $this->type = Type::getType($this->typeName);
     $this->platform = new PostgreSqlPlatform();
 }
 public function setUp()
 {
     if (!Type::hasType('url')) {
         Type::addType('url', '\\LonelyPullRequests\\Infrastructure\\Symfony\\LonelyPullRequestsBundle\\Type\\UrlType');
     }
     $this->type = Type::getType('url');
     $this->platform = Mockery::mock('\\Doctrine\\DBAL\\Platforms\\AbstractPlatform');
 }
Exemplo n.º 27
0
 /**
  * @test
  */
 public function I_can_convert_it_to_name()
 {
     NameType::registerSelf();
     $nameType = Type::getType($this->getExpectedTypeName());
     $phpValue = $nameType->convertToPHPValue($value = 'some string', $this->getPlatform());
     self::assertInstanceOf(Name::class, $phpValue);
     self::assertEquals($value, "{$phpValue}");
 }
Exemplo n.º 28
0
 protected function setUp()
 {
     $this->skipIfNoDoctrineDbal();
     $this->skip64BitTest();
     $this->platform = $this->getPlatformMock();
     $this->platform->expects($this->any())->method('getGuidTypeDeclarationSQL')->will($this->returnValue('DUMMYVARCHAR()'));
     $this->type = Type::getType('uuid');
 }
Exemplo n.º 29
0
 public function testSchemaConstructor()
 {
     $table1 = new Table('table1', [new Column('column1', Type::getType('string'), ['comment' => 'test'])]);
     $schema = new ExtendSchema($this->extendOptionsManager, $this->nameGenerator, [$table1]);
     $this->assertSchemaTypes($schema);
     $this->assertSchemaSql($schema, ['CREATE TABLE table1 (column1 VARCHAR(255) NOT NULL COMMENT \'test\')']);
     $this->assertExtendOptions($schema, []);
 }
Exemplo n.º 30
0
 protected function setUp()
 {
     $this->platform = m::mock(AbstractPlatform::class);
     if (!Type::hasType('json')) {
         Type::addType('json', Json::class);
     }
     $this->type = Type::getType('json');
 }