Exemplo n.º 1
0
 public function testItAddsTypeThatIsNotYetInStorage()
 {
     $this->generator->shouldReceive('getTypeClassName')->with(FooBar::class)->andReturn('__Enum__\\' . FooBarType::class);
     $this->storage->shouldReceive('exists')->with('__Enum__\\' . FooBarType::class)->andReturn(false);
     $this->generator->shouldNotReceive('generate')->with('foobar', FooBar::class)->andReturn(new GenerationResult('__Enum__\\' . FooBarType::class, 'type_class_content'));
     $this->storage->shouldReceive('save')->with('__Enum__\\' . FooBarType::class, 'type_class_content');
     $this->assertFalse(Type::hasType('foobar'));
     $this->sut->addType('foobar', FooBar::class);
     $map = Type::getTypesMap();
     $this->assertEquals('__Enum__\\' . FooBarType::class, $map['foobar']);
 }
Exemplo n.º 2
0
 public function compile()
 {
     $gClass = new \Psc\Code\Generate\GClass(\Psc\Code\Code::getClass($this));
     $gClass->elevateClass();
     $this->log('compiling ProjectEntities:');
     foreach ($gClass->getMethods() as $method) {
         if (\Psc\Preg::match($method->getName(), '/^compile[a-z0-9A-Z_]+$/') && $method->isPublic()) {
             $this->modelCompiler = NULL;
             // neuen erzeugen damit flags resetted werden, etc
             $m = $method->getName();
             $this->log('  ' . $m . ':');
             try {
                 $out = $this->{$m}($this->getModelCompiler());
             } catch (\Doctrine\DBAL\DBALException $e) {
                 if (mb_strpos($e->getMessage(), 'Unknown column type') !== FALSE) {
                     $types = A::implode(\Doctrine\DBAL\Types\Type::getTypesMap(), "\n", function ($fqn, $type) {
                         return $type . "\t\t" . ': ' . $fqn;
                     });
                     throw new \Psc\Exception('Database Error: Unknown Column Type: types are: ' . "\n" . $types, $e->getCode(), $e);
                 }
                 throw $e;
             } catch (\Exception $e) {
                 $this->log('    Fehler beim Aufruf von ' . $m);
                 throw $e;
             }
             if ($out instanceof \Webforge\Common\System\File) {
                 $this->log('    ' . $out . ' geschrieben');
             } elseif (is_array($out)) {
                 foreach ($out as $file) {
                     $this->log('    ' . $file . ' geschrieben');
                 }
             } elseif ($out instanceof \Psc\Doctrine\EntityBuilder) {
                 $this->log('    ' . $out->getWrittenFile() . ' geschrieben');
             }
         }
     }
     $this->log('finished.');
     return $this;
 }
Exemplo n.º 3
0
 /**
  * Initializes the Doctrine Type comments instance variable for in_array() checks.
  *
  * @return void
  */
 protected function initializeCommentedDoctrineTypes()
 {
     $this->doctrineTypeComments = array();
     foreach (Type::getTypesMap() as $typeName => $className) {
         $type = Type::getType($typeName);
         if ($type->requiresSQLCommentHint($this)) {
             $this->doctrineTypeComments[] = $typeName;
         }
     }
 }
Exemplo n.º 4
0
<?php

/**
 * This file is part of Mismatch.
 *
 * @author   ♥ <*****@*****.**>
 * @license  MIT
 */
namespace Mismatch\ORM;

use Mismatch\Model\Attrs;
// Install native ORM types.
foreach (['belongs-to' => 'Mismatch\\ORM\\Attr\\BelongsTo', 'has-many' => 'Mismatch\\ORM\\Attr\\HasMany', 'has-one' => 'Mismatch\\ORM\\Attr\\HasOne'] as $name => $type) {
    Attrs::registerType($name, $type);
}
// Install doctrine-specific types
use Doctrine\DBAL\Types\Type;
use Mismatch\ORM\Attr\Native;
$types = Type::getTypesMap();
foreach ($types as $type => $class) {
    Attrs::registerType($type, function ($name, $opts) use($type) {
        $opts['type'] = Type::getType($type);
        return new Native($name, $opts);
    });
}
 private function generateEntityStubMethod(ClassMetadataInfo $metadata, $type, $fieldName, $typeHint = null, $defaultValue = null)
 {
     $methodName = $type . Inflector::classify($fieldName);
     if (in_array($type, array("add", "remove")) && substr($methodName, -1) == "s") {
         $methodName = substr($methodName, 0, -1);
     }
     if ($this->hasMethod($methodName, $metadata)) {
         return;
     }
     $this->staticReflection[$metadata->name]['methods'][] = $methodName;
     $var = sprintf('%sMethodTemplate', $type);
     $template = self::${$var};
     $methodTypeHint = null;
     $types = Type::getTypesMap();
     $variableType = $typeHint ? $this->getType($typeHint) . ' ' : null;
     if ($typeHint && !isset($types[$typeHint])) {
         $variableType = '\\' . ltrim($variableType, '\\');
         $methodTypeHint = '\\' . $typeHint . ' ';
     }
     $replacements = array('<description>' => ucfirst($type) . ' ' . $fieldName, '<methodTypeHint>' => $methodTypeHint, '<variableType>' => $variableType, '<variableName>' => Inflector::camelize($fieldName), '<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);
 }
Exemplo n.º 6
0
 public function __construct(\Espo\Core\Utils\File\Manager $fileManager)
 {
     $this->fileManager = $fileManager;
     $this->typeList = array_keys(\Doctrine\DBAL\Types\Type::getTypesMap());
 }
Exemplo n.º 7
0
 /**
  * @param string $query
  * @param array $params
  * @param array $types
  * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform
  * @throws \Doctrine\DBAL\DBALException
  * @throws \Nette\Utils\RegexpException
  * @return string
  */
 public static function formatQuery($query, $params, array $types = [], AbstractPlatform $platform = NULL)
 {
     if (!$platform) {
         $platform = new Doctrine\DBAL\Platforms\MySqlPlatform();
     }
     if (!$types) {
         foreach ($params as $key => $param) {
             if (is_array($param)) {
                 $types[$key] = Doctrine\DBAL\Connection::PARAM_STR_ARRAY;
             } else {
                 $types[$key] = 'string';
             }
         }
     }
     try {
         list($query, $params, $types) = \Doctrine\DBAL\SQLParserUtils::expandListParameters($query, $params, $types);
     } catch (Doctrine\DBAL\SQLParserUtilsException $e) {
     }
     $formattedParams = [];
     foreach ($params as $key => $param) {
         if (isset($types[$key])) {
             if (is_scalar($types[$key]) && array_key_exists($types[$key], Type::getTypesMap())) {
                 $types[$key] = Type::getType($types[$key]);
             }
             /** @var Type[] $types */
             if ($types[$key] instanceof Type) {
                 $param = $types[$key]->convertToDatabaseValue($param, $platform);
             }
         }
         $formattedParams[] = SimpleParameterFormatter::format($param);
     }
     $params = $formattedParams;
     if (Nette\Utils\Validators::isList($params)) {
         $parts = explode('?', $query);
         if (count($params) > $parts) {
             throw new Kdyby\Doctrine\InvalidStateException("Too mny parameters passed to query.");
         }
         return implode('', Kdyby\Doctrine\Helpers::zipper($parts, $params));
     }
     return Strings::replace($query, '~(\\:[a-z][a-z0-9]*|\\?[0-9]*)~i', function ($m) use(&$params) {
         if (substr($m[0], 0, 1) === '?') {
             if (strlen($m[0]) > 1) {
                 if (isset($params[$k = substr($m[0], 1)])) {
                     return $params[$k];
                 }
             } else {
                 return array_shift($params);
             }
         } else {
             if (isset($params[$k = substr($m[0], 1)])) {
                 return $params[$k];
             }
         }
         return $m[0];
     });
 }
 /**
  * @test
  */
 public function I_can_register_all_enums_at_once()
 {
     $registered = Type::getTypesMap();
     SkillsEnumsRegistrar::registerAll();
     self::assertGreaterThan(count($registered), Type::getTypesMap());
 }
Exemplo n.º 9
0
 /**
  * Interactively ask user to add field to his new Entity.
  *
  * @param InputInterface  $input
  * @param OutputInterface $output
  * @param QuestionHelper  $questionHelper
  *
  * @return $fields
  */
 private function addFields(InputInterface $input, OutputInterface $output, QuestionHelper $questionHelper)
 {
     $fields = $this->parseFields($input->getOption('fields'));
     $output->writeln(['', 'Instead of starting with a blank entity, you can add some fields now.', 'Note that the primary key will be added automatically (named <comment>id</comment>).', '']);
     $output->write('<info>Available types:</info> ');
     $types = array_keys(Type::getTypesMap());
     $count = 20;
     foreach ($types as $i => $type) {
         if ($count > 50) {
             $count = 0;
             $output->writeln('');
         }
         $count += strlen($type);
         $output->write(sprintf('<comment>%s</comment>', $type));
         if (count($types) != $i + 1) {
             $output->write(', ');
         } else {
             $output->write('.');
         }
     }
     $output->writeln('');
     $fieldValidator = function ($type) use($types) {
         if (!in_array($type, $types)) {
             throw new \InvalidArgumentException(sprintf('Invalid type "%s".', $type));
         }
         return $type;
     };
     $lengthValidator = function ($length) {
         if (!$length) {
             return $length;
         }
         $result = filter_var($length, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
         if (false === $result) {
             throw new \InvalidArgumentException(sprintf('Invalid length "%s".', $length));
         }
         return $length;
     };
     while (true) {
         $output->writeln('');
         $generator = $this->getEntityGenerator();
         $question = new Question($questionHelper->getQuestion('New field name (press <return> to stop adding fields)', null));
         $question->setValidator(function ($name) use($fields, $generator) {
             if (isset($fields[$name]) || 'id' == $name) {
                 throw new \InvalidArgumentException(sprintf('Field "%s" is already defined.', $name));
             }
             // check reserved words by database
             if ($generator->isReservedKeyword($name)) {
                 throw new \InvalidArgumentException(sprintf('Name "%s" is a reserved word.', $name));
             }
             // check reserved words by victoire
             if ($this->isReservedKeyword($name)) {
                 throw new \InvalidArgumentException(sprintf('Name "%s" is a Victoire reserved word.', $name));
             }
             return $name;
         });
         $columnName = $questionHelper->ask($input, $output, $question);
         if (!$columnName) {
             break;
         }
         $defaultType = 'string';
         // try to guess the type by the column name prefix/suffix
         if (substr($columnName, -3) == '_at') {
             $defaultType = 'datetime';
         } elseif (substr($columnName, -3) == '_id') {
             $defaultType = 'integer';
         } elseif (substr($columnName, 0, 3) == 'is_') {
             $defaultType = 'boolean';
         } elseif (substr($columnName, 0, 4) == 'has_') {
             $defaultType = 'boolean';
         }
         $question = new Question($questionHelper->getQuestion('Field type', $defaultType), $defaultType);
         $question->setValidator($fieldValidator);
         $question->setAutocompleterValues($types);
         $type = $questionHelper->ask($input, $output, $question);
         $data = ['columnName' => $columnName, 'fieldName' => lcfirst(Container::camelize($columnName)), 'type' => $type];
         if ($type == 'string') {
             $question = new Question($questionHelper->getQuestion('Field length', 255), 255);
             $question->setValidator($lengthValidator);
             $data['length'] = $questionHelper->ask($input, $output, $question);
         }
         $fields[$columnName] = $data;
     }
     return $fields;
 }
 /**
  * Add the entity fields
  *
  * @param InputInterface $input
  * @param OutputInterface $output
  * @param DialogHelper $dialog
  *
  * @return array
  */
 private function addFields(InputInterface $input, OutputInterface $output, DialogHelper $dialog)
 {
     $fields = $this->parseFields($input->getOption('fields'));
     $output->writeln(array('', 'Instead of starting with a blank entity, you can add some fields now.', 'Note that the primary key will be added automatically (named <comment>id</comment>) as well as the <comment>active</comment> field.', ''));
     $output->write('<info>Available types:</info> ');
     $types = array_keys(Type::getTypesMap());
     $count = 20;
     foreach ($types as $i => $type) {
         if ($count > 50) {
             $count = 0;
             $output->writeln('');
         }
         $count += strlen($type);
         $output->write(sprintf('<comment>%s</comment>', $type));
         if (count($types) != $i + 1) {
             $output->write(', ');
         } else {
             $output->write('.');
         }
     }
     $output->writeln('');
     $fieldValidator = function ($type) use($types) {
         // FIXME: take into account user-defined field types
         if (!in_array($type, $types)) {
             throw new \InvalidArgumentException(sprintf('Invalid type "%s".', $type));
         }
         return $type;
     };
     $lengthValidator = function ($length) {
         if (!$length) {
             return $length;
         }
         $result = filter_var($length, FILTER_VALIDATE_INT, array('options' => array('min_range' => 1)));
         if (false === $result) {
             throw new \InvalidArgumentException(sprintf('Invalid length "%s".', $length));
         }
         return $length;
     };
     $i18nValidator = function ($isI18n) {
         if (!in_array($isI18n, array('Yes', 'No', 'yes', 'no', 'Y', 'N', 'y', 'n'))) {
             throw new \InvalidArgumentException(sprintf('Invalid answer (Yes/No) "%s".', $isI18n));
         }
         return $isI18n;
     };
     $isNullableValidator = function ($isNullable) {
         if (!in_array($isNullable, array('Yes', 'No', 'yes', 'no', 'Y', 'N', 'y', 'n'))) {
             throw new \InvalidArgumentException(sprintf('Invalid answer (Yes/No) "%s".', $isNullable));
         }
         return substr(strtolower($isNullable), 0, 1) == 'y' ? true : false;
     };
     while (true) {
         $output->writeln('');
         $generator = $this->getGenerator();
         $columnName = $dialog->askAndValidate($output, $dialog->getQuestion('New field name (press <return> to stop adding fields)', null), function ($name) use($fields, $generator) {
             if (isset($fields[$name]) || 'id' == $name) {
                 throw new \InvalidArgumentException(sprintf('Field "%s" is already defined.', $name));
             }
             // check reserved words
             if ($generator->isReservedKeyword($name)) {
                 throw new \InvalidArgumentException(sprintf('Name "%s" is a reserved word.', $name));
             }
             return $name;
         });
         if (!$columnName) {
             break;
         }
         $defaultType = 'string';
         // try to guess the type by the column name prefix/suffix
         if (substr($columnName, -3) == '_at') {
             $defaultType = 'datetime';
         } elseif (substr($columnName, -3) == '_id') {
             $defaultType = 'integer';
         } elseif (substr($columnName, 0, 3) == 'is_') {
             $defaultType = 'boolean';
         } elseif (substr($columnName, 0, 4) == 'has_') {
             $defaultType = 'boolean';
         }
         $type = $dialog->askAndValidate($output, $dialog->getQuestion('Field type', $defaultType), $fieldValidator, false, $defaultType, $types);
         $data = array('columnName' => $columnName, 'fieldName' => lcfirst(Container::camelize($columnName)), 'type' => $type);
         if ($type == 'string') {
             $data['length'] = $dialog->askAndValidate($output, $dialog->getQuestion('Field length', 255), $lengthValidator, false, 255);
         }
         $data['i18n'] = $dialog->askAndValidate($output, $dialog->getQuestion('Field is i18n', 'no'), $i18nValidator, false, 'no');
         if ($columnName != 'slug') {
             $data['nullable'] = $dialog->askAndValidate($output, $dialog->getQuestion('Field is nullable', 'no'), $isNullableValidator, false, 'no');
         }
         $fields[$columnName] = $data;
     }
     return $fields;
 }
Exemplo n.º 11
0
 /**
  * @param ClassMetadataInfo $metadata
  * @param string            $type
  * @param string            $fieldName
  * @param string|null       $typeHint
  * @param string|null       $defaultValue
  *
  * @return string
  */
 protected function generateEntityStubMethod(ClassMetadataInfo $metadata, $type, $fieldName, $typeHint = null, $defaultValue = null)
 {
     $methodName = $type . Inflector::classify($fieldName);
     $variableName = Inflector::camelize($fieldName);
     if (in_array($type, ["add", "remove"])) {
         $methodName = Inflector::singularize($methodName);
         $variableName = Inflector::singularize($variableName);
     }
     if ($this->hasMethod($methodName, $metadata)) {
         return '';
     }
     $this->staticReflection[$metadata->name]['methods'][] = strtolower($methodName);
     $var = sprintf('%sMethodTemplate', $type);
     $template = static::${$var};
     $methodTypeHint = null;
     $types = Type::getTypesMap();
     $variableType = $typeHint ? $this->getType($typeHint) : null;
     if ($typeHint && !isset($types[$typeHint])) {
         $variableType = '\\' . ltrim($variableType, '\\');
         $methodTypeHint = '\\' . $typeHint . ' ';
     }
     $replacements = ['<description>' => ucfirst($type) . ' ' . $variableName . '.', '<methodTypeHint>' => $methodTypeHint, '<variableType>' => $variableType . (null !== $defaultValue ? '|' . $defaultValue : ''), '<variableName>' => $variableName, '<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);
 }
Exemplo n.º 12
0
 /**
  * {@inheritdoc}
  */
 protected function generateEntityStubMethod(ClassMetadataInfo $metadata, $type, $fieldName, $typeHint = null, $defaultValue = null)
 {
     $methodName = $type . Inflector::classify($fieldName);
     if (in_array($type, array("add", "remove"))) {
         $methodName = Inflector::singularize($methodName);
     }
     if ($this->hasMethod($methodName, $metadata)) {
         return '';
     }
     $this->staticReflection[$metadata->name]['methods'][] = $methodName;
     $var = sprintf('%sMethodTemplate', $type);
     $template = self::${$var};
     $methodTypeHint = null;
     $types = Type::getTypesMap();
     $variableType = $typeHint ? $this->getType($typeHint) . ' ' : null;
     if ($typeHint && !isset($types[$typeHint])) {
         $variableType = '\\' . ltrim($variableType, '\\');
         $methodTypeHint = '\\' . $typeHint . ' ';
     } elseif ($variableType[0] == '\\') {
         $variableType = '\\' . ltrim($variableType, '\\');
         $methodTypeHint = '\\' . ltrim($variableType, '\\');
     }
     switch (trim($variableType)) {
         case 'bool':
         case 'boolean':
             $variableCast = '(bool) ';
             break;
         case 'int':
         case 'integer':
             $variableCast = '(int) ';
             break;
         case 'float':
         case 'double':
             $variableCast = '(float) ';
             break;
         case 'string':
             $variableCast = '(string) ';
             break;
         default:
             $variableCast = '';
     }
     $variableName = Inflector::camelize($fieldName);
     if ($metadata->hasField($fieldName) && $metadata->isNullable($fieldName)) {
         $nullable = true;
     } else {
         $nullable = false;
     }
     if ($nullable && $variableCast) {
         $variableCast = sprintf('$%s === null ? null : %s', $variableName, $variableCast);
     }
     $replacements = array('<description>' => ucfirst($type) . ' ' . $fieldName, '<methodTypeHint>' => $methodTypeHint, '<variableType>' => $variableType, '<variableCast>' => $variableCast, '<variableName>' => $variableName, '<methodName>' => $methodName, '<fieldName>' => $fieldName, '<variableDefault>' => $defaultValue !== null ? ' = ' . $defaultValue : ($nullable ? ' = null' : ''), '<entity>' => $this->getClassName($metadata));
     $method = str_replace(array_keys($replacements), array_values($replacements), $template);
     return $this->prefixCodeWithSpaces($method);
 }
 /**
  * Map by Doctrine DBAL types map
  * @param $types
  * @param $key
  * @return null|string
  */
 protected function mapByTypesMap($types, $key)
 {
     $typesMap = Type::getTypesMap();
     if (array_key_exists($key, $types) && array_key_exists($types[$key], $typesMap)) {
         $name = $types[$key];
     } else {
         $name = null;
     }
     return $name;
 }
Exemplo n.º 14
0
 private function _generateEntityStubMethod(ClassMetadataInfo $metadata, $type, $fieldName, $typeHint = null)
 {
     $methodName = $type . Inflector::classify($fieldName);
     if ($this->_hasMethod($methodName, $metadata)) {
         return;
     }
     $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>' => Inflector::camelize($fieldName), '<methodName>' => $methodName, '<fieldName>' => $fieldName);
     $method = str_replace(array_keys($replacements), array_values($replacements), $template);
     return $this->_prefixCodeWithSpaces($method);
 }
 private function addFields(InputInterface $input, OutputInterface $output, DialogHelper $dialog)
 {
     $fields = $this->parseFields($input->getOption('fields'));
     $output->writeln(array('', 'Instead of starting with a blank entity, you can add some fields now.', 'Note that the primary key will be added automatically (named <comment>id</comment>).', ''));
     $output->write('<info>Available types:</info> ');
     $types = array_keys(Type::getTypesMap());
     $count = 20;
     foreach ($types as $i => $type) {
         if ($count > 50) {
             $count = 0;
             $output->writeln('');
         }
         $count += strlen($type);
         $output->write(sprintf('<comment>%s</comment>', $type));
         if (count($types) != $i + 1) {
             $output->write(', ');
         } else {
             $output->write('.');
         }
     }
     $output->writeln('');
     $fieldValidator = function ($type) use($types) {
         // FIXME: take into account user-defined field types
         if (!in_array($type, $types)) {
             throw new \InvalidArgumentException(sprintf('Invalid type "%s".', $type));
         }
         return $type;
     };
     $lengthValidator = function ($length) {
         if (!$length) {
             return $length;
         }
         $result = filter_var($length, FILTER_VALIDATE_INT, array('options' => array('min_range' => 1)));
         if (false === $result) {
             throw new \InvalidArgumentException(sprintf('Invalid length "%s".', $length));
         }
         return $length;
     };
     while (true) {
         $output->writeln('');
         $self = $this;
         $name = $dialog->askAndValidate($output, $dialog->getQuestion('New field name (press <return> to stop adding fields)', null), function ($name) use($fields, $self) {
             if (isset($fields[$name]) || 'id' == $name) {
                 throw new \InvalidArgumentException(sprintf('Field "%s" is already defined.', $name));
             }
             // check reserved words
             if ($self->getGenerator()->isReservedKeyword($name)) {
                 throw new \InvalidArgumentException(sprintf('Name "%s" is a reserved word.', $name));
             }
             return $name;
         });
         if (!$name) {
             break;
         }
         $defaultType = 'string';
         if (substr($name, -3) == '_at') {
             $defaultType = 'datetime';
         } elseif (substr($name, -3) == '_id') {
             $defaultType = 'integer';
         }
         $type = $dialog->askAndValidate($output, $dialog->getQuestion('Field type', $defaultType), $fieldValidator, false, $defaultType);
         $data = array('fieldName' => $name, 'type' => $type);
         if ($type == 'string') {
             $data['length'] = $dialog->askAndValidate($output, $dialog->getQuestion('Field length', 255), $lengthValidator, false, 255);
         }
         $fields[$name] = $data;
     }
     return $fields;
 }
Exemplo n.º 16
0
 private function _generateEntityStubMethod(ClassMetadataInfo $metadata, $type, $fieldName, $typeHint = null, $defaultValue = null)
 {
     if ($type == "add") {
         $addMethod = explode("\\", $typeHint);
         $addMethod = end($addMethod);
         $methodName = $type . $addMethod;
     } else {
         $methodName = $type . Inflector::classify($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>' => Inflector::camelize($fieldName), '<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);
 }
Exemplo n.º 17
0
 /**
  * Field Generator
  * Prompt user to add more fields
  *
  * @param string $entity    The entity name
  * @param array  $oldFields The entities existing fields
  *
  * @return array $fields
  */
 protected function fieldGenerator($entity, $oldFields)
 {
     $fields = array();
     $this->dialog->writeSection($this->output, 'Add some fields to your ' . $entity . ' entity');
     $this->output->write('<info>Available types:</info> ');
     $types = array_keys(Type::getTypesMap());
     $types[] = "manyToOne";
     $types[] = "manyToMany";
     $types[] = "oneToMany";
     $types[] = "oneToOne";
     $count = 20;
     foreach ($types as $i => $type) {
         if ($count > 50) {
             $count = 0;
             $this->output->writeln('');
         }
         $count += strlen($type);
         $this->output->write(sprintf('<comment>%s</comment>', $type));
         if (count($types) != $i + 1) {
             $this->output->write(', ');
         } else {
             $this->output->write('.');
         }
     }
     $this->output->writeln('');
     $fieldValidator = function ($type) use($types) {
         if (!in_array($type, $types)) {
             throw new \InvalidArgumentException(sprintf('Invalid type "%s".', $type));
         }
         return $type;
     };
     $lengthValidator = function ($length) {
         if (!$length) {
             return $length;
         }
         $result = filter_var($length, FILTER_VALIDATE_INT, array('options' => array('min_range' => 1)));
         if (false === $result) {
             throw new \InvalidArgumentException(sprintf('Invalid length "%s".', $length));
         }
         return $length;
     };
     while (true) {
         $this->output->writeln('');
         $data['fieldName'] = $this->dialog->askAndValidate($this->output, $this->dialog->getQuestion('New field name (press <return> to stop adding fields)', null), function ($name) use($fields) {
             if (isset($fields[$name]) || 'id' == $name) {
                 throw new \InvalidArgumentException(sprintf('Field "%s" is already defined.', $name));
             }
             return $name;
         });
         if (empty($data['fieldName'])) {
             break;
         }
         $type = $this->dialog->askAndValidate($this->output, $this->dialog->getQuestion('Field type', 'string'), $fieldValidator, false, 'string');
         $data['type'] = $type;
         if ($type == "decimal") {
             $data['precision'] = $this->dialog->askAndValidate($this->output, $this->dialog->getQuestion('Field precision', 10), $lengthValidator, false, 10);
             $data['scale'] = $this->dialog->askAndValidate($this->output, $this->dialog->getQuestion('Field scale', 2), $lengthValidator, false, 2);
         }
         if ($type == "oneToOne") {
             $data['targetEntity'] = $entity;
         }
         if ($type == "manyToOne" || $type == "oneToMany" || $type == "manyToMany") {
             $data['targetEntity'] = $this->dialog->ask($this->output, 'Enter the target entity (ie. Acme\\TestBundle\\Entity\\Post): ');
             $data['orphanRemoval'] = $this->dialog->askConfirmation($this->output, $this->dialog->getQuestion('Orphan removal?', 'no', '?'), false);
             if ($type == 'oneToMany' || $type == 'manyToMany') {
                 $bidirectional = $this->dialog->askConfirmation($this->output, $this->dialog->getQuestion('Is this a bi-directional mapping?', 'no', '?'), false);
                 $cascade = $this->dialog->askConfirmation($this->output, $this->dialog->getQuestion('Cascade all for this mapping?', 'no', '?'), false);
                 if ($cascade) {
                     $data['cascade'][] = 'all';
                 } else {
                     $data['cascade'] = array();
                 }
                 if ($bidirectional) {
                     $data['isOwningSide'] = $this->dialog->askConfirmation($this->output, $this->dialog->getQuestion('Is this the owning side?', 'yes', '?'), true);
                     if ($data['isOwningSide']) {
                         $data['mappedBy'] = $this->dialog->ask($this->output, 'Enter mappedBy: (ie. post): ');
                         $data['inversedBy'] = false;
                     } else {
                         $data['inversedBy'] = $this->dialog->ask($this->output, 'Enter inversedBy: (ie. tags): ');
                         $data['mappedBy'] = false;
                     }
                 } else {
                     $data['isOwningSide'] = false;
                     $data['mappedBy'] = false;
                     $data['inversedBy'] = false;
                 }
             }
         }
         if ($type == 'string') {
             $data['length'] = $this->dialog->askAndValidate($this->output, $this->dialog->getQuestion('Field length', 255), $lengthValidator, false, 255);
         }
         if ($type == 'oneToOne' || $type == 'manyToOne' || $type == 'manyToMany') {
             $data['nullable'] = false;
         } else {
             $data['nullable'] = $this->dialog->askConfirmation($this->output, $this->dialog->getQuestion('nullable?: ', 'yes', '?'), true);
         }
         $fields[$data['fieldName']] = $data;
     }
     if (false !== $oldFields) {
         if (!empty($fields)) {
             $fields = array_merge_recursive($oldFields, $fields);
         } else {
             $fields = $oldFields;
         }
     }
     if (!is_array($fields)) {
         $this->output->writeln('<error>No fields were provided</error>');
         return 1;
     }
     return $fields;
 }
 private function addFields(InputInterface $input, OutputInterface $output, QuestionHelper $questionHelper)
 {
     $fields = $this->parseFields($input->getOption('fields'));
     $output->writeln(array('', 'Instead of starting with a blank entity, you can add some fields now.', 'Note that the primary key will be added automatically (named <comment>id</comment>).', ''));
     $output->write('<info>Available types:</info> ');
     $types = array_keys(Type::getTypesMap());
     $count = 20;
     foreach ($types as $i => $type) {
         if ($count > 50) {
             $count = 0;
             $output->writeln('');
         }
         $count += strlen($type);
         $output->write(sprintf('<comment>%s</comment>', $type));
         if (count($types) != $i + 1) {
             $output->write(', ');
         } else {
             $output->write('.');
         }
     }
     $output->writeln('');
     $fieldValidator = function ($type) use($types) {
         if (!in_array($type, $types)) {
             throw new \InvalidArgumentException(sprintf('Invalid type "%s".', $type));
         }
         return $type;
     };
     $lengthValidator = function ($length) {
         if (!$length) {
             return $length;
         }
         $result = filter_var($length, FILTER_VALIDATE_INT, array('options' => array('min_range' => 1)));
         if (false === $result) {
             throw new \InvalidArgumentException(sprintf('Invalid length "%s".', $length));
         }
         return $length;
     };
     $boolValidator = function ($value) {
         if (null === ($valueAsBool = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE))) {
             throw new \InvalidArgumentException(sprintf('Invalid bool value "%s".', $value));
         }
         return $valueAsBool;
     };
     $precisionValidator = function ($precision) {
         if (!$precision) {
             return $precision;
         }
         $result = filter_var($precision, FILTER_VALIDATE_INT, array('options' => array('min_range' => 1, 'max_range' => 65)));
         if (false === $result) {
             throw new \InvalidArgumentException(sprintf('Invalid precision "%s".', $precision));
         }
         return $precision;
     };
     $scaleValidator = function ($scale) {
         if (!$scale) {
             return $scale;
         }
         $result = filter_var($scale, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0, 'max_range' => 30)));
         if (false === $result) {
             throw new \InvalidArgumentException(sprintf('Invalid scale "%s".', $scale));
         }
         return $scale;
     };
     while (true) {
         $output->writeln('');
         $generator = $this->getGenerator();
         $question = new Question($questionHelper->getQuestion('New field name (press <return> to stop adding fields)', null), null);
         $question->setValidator(function ($name) use($fields, $generator) {
             if (isset($fields[$name]) || 'id' == $name) {
                 throw new \InvalidArgumentException(sprintf('Field "%s" is already defined.', $name));
             }
             // check reserved words
             if ($generator->isReservedKeyword($name)) {
                 throw new \InvalidArgumentException(sprintf('Name "%s" is a reserved word.', $name));
             }
             // check for valid PHP variable name
             if (!is_null($name) && !$generator->isValidPhpVariableName($name)) {
                 throw new \InvalidArgumentException(sprintf('"%s" is not a valid PHP variable name.', $name));
             }
             return $name;
         });
         $columnName = $questionHelper->ask($input, $output, $question);
         if (!$columnName) {
             break;
         }
         $defaultType = 'string';
         // try to guess the type by the column name prefix/suffix
         if (substr($columnName, -3) == '_at') {
             $defaultType = 'datetime';
         } elseif (substr($columnName, -3) == '_id') {
             $defaultType = 'integer';
         } elseif (substr($columnName, 0, 3) == 'is_') {
             $defaultType = 'boolean';
         } elseif (substr($columnName, 0, 4) == 'has_') {
             $defaultType = 'boolean';
         }
         $question = new Question($questionHelper->getQuestion('Field type', $defaultType), $defaultType);
         $question->setValidator($fieldValidator);
         $question->setAutocompleterValues($types);
         $type = $questionHelper->ask($input, $output, $question);
         $data = array('columnName' => $columnName, 'fieldName' => lcfirst(Container::camelize($columnName)), 'type' => $type);
         if ($type == 'string') {
             $question = new Question($questionHelper->getQuestion('Field length', 255), 255);
             $question->setValidator($lengthValidator);
             $data['length'] = $questionHelper->ask($input, $output, $question);
         } elseif ('decimal' === $type) {
             // 10 is the default value given in \Doctrine\DBAL\Schema\Column::$_precision
             $question = new Question($questionHelper->getQuestion('Precision', 10), 10);
             $question->setValidator($precisionValidator);
             $data['precision'] = $questionHelper->ask($input, $output, $question);
             // 0 is the default value given in \Doctrine\DBAL\Schema\Column::$_scale
             $question = new Question($questionHelper->getQuestion('Scale', 0), 0);
             $question->setValidator($scaleValidator);
             $data['scale'] = $questionHelper->ask($input, $output, $question);
         }
         $question = new Question($questionHelper->getQuestion('Is nullable', 'false'), false);
         $question->setValidator($boolValidator);
         $question->setAutocompleterValues(array('true', 'false'));
         if ($nullable = $questionHelper->ask($input, $output, $question)) {
             $data['nullable'] = $nullable;
         }
         $question = new Question($questionHelper->getQuestion('Unique', 'false'), false);
         $question->setValidator($boolValidator);
         $question->setAutocompleterValues(array('true', 'false'));
         if ($unique = $questionHelper->ask($input, $output, $question)) {
             $data['unique'] = $unique;
         }
         $fields[$columnName] = $data;
     }
     return $fields;
 }
Exemplo n.º 19
0
 public function testDoctrineTypes()
 {
     $doctrineTypes = array_keys(Type::getTypesMap());
     $mismatchTypes = Attrs::availableTypes();
     $this->assertSame($doctrineTypes, array_intersect($doctrineTypes, $mismatchTypes));
 }