public function postPersist(LifecycleEventArgs $event)
 {
     /** @var OroEntityManager $em */
     $em = $event->getEntityManager();
     $entity = $event->getEntity();
     $configProvider = $em->getExtendManager()->getConfigProvider();
     $className = get_class($entity);
     if ($configProvider->hasConfig($className)) {
         $config = $configProvider->getConfig($className);
         $schema = $config->get('schema');
         if (isset($schema['relation'])) {
             foreach ($schema['relation'] as $fieldName) {
                 /** @var Config $fieldConfig */
                 $fieldConfig = $configProvider->getConfig($className, $fieldName);
                 if ($fieldConfig->getId()->getFieldType() == 'optionSet' && ($setData = $entity->{Inflector::camelize('get_' . $fieldName)}())) {
                     $model = $configProvider->getConfigManager()->getConfigFieldModel($fieldConfig->getId()->getClassName(), $fieldConfig->getId()->getFieldName());
                     /**
                      * in case of single select field type, should wrap value in array
                      */
                     if ($setData && !is_array($setData)) {
                         $setData = [$setData];
                     }
                     foreach ($setData as $option) {
                         $optionSetRelation = new OptionSetRelation();
                         $optionSetRelation->setData(null, $entity->getId(), $model, $em->getRepository(OptionSet::ENTITY_NAME)->find($option));
                         $em->persist($optionSetRelation);
                         $this->needFlush = true;
                     }
                 }
             }
         }
     }
 }
 /**
  * @Given the following :entityName entities exist:
  */
 public function theFollowingEntitiesExist($entityName, TableNode $table)
 {
     /** @var EntityManager $doctrine */
     $doctrine = $this->get('doctrine')->getManager();
     $meta = $doctrine->getClassMetadata($entityName);
     $rows = [];
     $hash = $table->getHash();
     foreach ($hash as $row) {
         $id = $row['id'];
         unset($row['id']);
         foreach ($row as $property => &$value) {
             $propertyName = Inflector::camelize($property);
             $fieldType = $meta->getTypeOfField($propertyName);
             switch ($fieldType) {
                 case 'array':
                 case 'json_array':
                     $value = json_decode($value, true);
                     break;
                 case 'datetime':
                     $value = new \DateTime($value);
                     break;
             }
         }
         $rows[$id] = $row;
     }
     $this->persistEntities($entityName, $rows);
 }
Esempio n. 3
0
 /**
  * @param array $data
  */
 public function fromArray(array $data)
 {
     foreach ($data as $key => $value) {
         $property = Inflector::camelize($key);
         $this->{$property} = $value;
     }
 }
Esempio n. 4
0
 public static function create(DeclareSchema $schema, $baseClass)
 {
     $cTemplate = new ClassFile($schema->getBaseModelClass());
     $cTemplate->addConsts(array('schema_proxy_class' => $schema->getSchemaProxyClass(), 'collection_class' => $schema->getCollectionClass(), 'model_class' => $schema->getModelClass(), 'table' => $schema->getTable(), 'read_source_id' => $schema->getReadSourceId(), 'write_source_id' => $schema->getWriteSourceId(), 'primary_key' => $schema->primaryKey));
     $cTemplate->addMethod('public', 'getSchema', [], ['if ($this->_schema) {', '   return $this->_schema;', '}', 'return $this->_schema = \\LazyRecord\\Schema\\SchemaLoader::load(' . var_export($schema->getSchemaProxyClass(), true) . ');']);
     $cTemplate->addStaticVar('column_names', $schema->getColumnNames());
     $cTemplate->addStaticVar('column_hash', array_fill_keys($schema->getColumnNames(), 1));
     $cTemplate->addStaticVar('mixin_classes', array_reverse($schema->getMixinSchemaClasses()));
     if ($traitClasses = $schema->getModelTraitClasses()) {
         foreach ($traitClasses as $traitClass) {
             $cTemplate->useTrait($traitClass);
         }
     }
     $cTemplate->extendClass('\\' . $baseClass);
     // interfaces
     if ($ifs = $schema->getModelInterfaces()) {
         foreach ($ifs as $iface) {
             $cTemplate->implementClass($iface);
         }
     }
     // Create column accessor
     if ($schema->enableColumnAccessors) {
         foreach ($schema->getColumnNames() as $columnName) {
             $accessorMethodName = 'get' . ucfirst(Inflector::camelize($columnName));
             $cTemplate->addMethod('public', $accessorMethodName, [], ['if (isset($this->_data[' . var_export($columnName, true) . '])) {', '    return $this->_data[' . var_export($columnName, true) . '];', '}']);
         }
     }
     return $cTemplate;
 }
 /**
  * {@inheritDoc}
  */
 public function getStructureMetadata($type, $structureType = null)
 {
     $cacheKey = $type . $structureType;
     if (isset($this->cache[$cacheKey])) {
         return $this->cache[$cacheKey];
     }
     $this->assertExists($type);
     if (!$structureType) {
         $structureType = $this->getDefaultStructureType($type);
     }
     if (!is_string($structureType)) {
         throw new \InvalidArgumentException(sprintf('Expected string for structureType, got: %s', is_object($structureType) ? get_class($structureType) : gettype($structureType)));
     }
     $cachePath = sprintf('%s/%s%s', $this->cachePath, Inflector::camelize($type), Inflector::camelize($structureType));
     $cache = new ConfigCache($cachePath, $this->debug);
     if ($this->debug || !$cache->isFresh()) {
         $paths = $this->getPaths($type);
         // reverse paths, so that the last path overrides previous ones
         $fileLocator = new FileLocator(array_reverse($paths));
         try {
             $filePath = $fileLocator->locate(sprintf('%s.xml', $structureType));
         } catch (\InvalidArgumentException $e) {
             throw new Exception\StructureTypeNotFoundException(sprintf('Could not load structure type "%s" for document type "%s", looked in "%s"', $structureType, $type, implode('", "', $paths)), null, $e);
         }
         $metadata = $this->loader->load($filePath, $type);
         $resources = [new FileResource($filePath)];
         $cache->write(sprintf('<?php $metadata = \'%s\';', serialize($metadata)), $resources);
     }
     require $cachePath;
     $structure = unserialize($metadata);
     $this->cache[$cacheKey] = $structure;
     return $structure;
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $builder->add('added', 'oro_entity_identifier', array('class' => $options['class'], 'multiple' => true))->add('removed', 'oro_entity_identifier', array('class' => $options['class'], 'multiple' => true));
     if ($options['extend']) {
         $em = $this->entityManager;
         $class = $options['class'];
         $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use($em, $class) {
             $data = $event->getData();
             $repository = $em->getRepository($class);
             $targetData = $event->getForm()->getParent()->getData();
             $fieldName = $event->getForm()->getName();
             foreach (explode(',', $data['added']) as $id) {
                 $entity = $repository->find($id);
                 if ($entity) {
                     $targetData->{Inflector::camelize('add_' . $fieldName)}($entity);
                 }
             }
             foreach (explode(',', $data['removed']) as $id) {
                 $entity = $repository->find($id);
                 if ($entity) {
                     $targetData->{Inflector::camelize('remove_' . $fieldName)}($entity);
                 }
             }
         });
     }
 }
 /**
  * {@inheritDoc}
  *
  * @param $parameter BodyParameter
  */
 public function generateDocParameter($parameter, Context $context)
 {
     list($class, $array) = $this->getClass($parameter, $context);
     if (null === $class) {
         return sprintf('%s $%s %s', 'mixed', Inflector::camelize($parameter->getName()), $parameter->getDescription() ?: '');
     }
     return sprintf('%s $%s %s', $class, Inflector::camelize($parameter->getName()), $parameter->getDescription() ?: '');
 }
Esempio n. 8
0
 /**
  * @dataProvider providerCreateDialect
  */
 public function testCreateDialect($method, $expected)
 {
     $dialect = call_user_func(array('\\CSanquer\\ColibriCsv\\Dialect', $method));
     $this->assertInstanceOf('\\CSanquer\\ColibriCsv\\Dialect', $dialect);
     foreach ($expected as $key => $value) {
         $this->assertEquals($value, call_user_func(array($dialect, Inflector::camelize('get_' . $key))), 'the value is not the expected for the option ' . $key);
     }
 }
Esempio n. 9
0
 public function getRowValue($row, $key)
 {
     if (is_array($row)) {
         return $row[$key];
     }
     $method = 'get' . Inflector::camelize($key);
     $value = $row->{$method}();
     return $value;
 }
 /**
  * @ORM\PrePersist
  */
 public function updateParentFields()
 {
     if ($this->object->getLocale() == $this->locale) {
         $method = Inflector::camelize('set' . ucfirst($this->field));
         if (method_exists($this->object, $method)) {
             $this->object->{$method}($this->getContent());
         }
     }
 }
 /**
  * @param string $line
  *
  * @return mixed
  *
  * @throws \Exception
  */
 public static function fromLine($line, array $lineOptions)
 {
     $line = json_decode($line, true);
     $method = Inflector::camelize($line['type']) . 'FromLine';
     if (method_exists(get_class(new static()), $method) && $method !== 'FromLine') {
         return static::$method($line, $lineOptions);
     }
     throw new \Exception('Unknown message type: ' . $line['type']);
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->commandParserChain->execute($input, $output);
     $filename = sprintf('%s.json', Inflector::camelize(strtolower($this->collectionName)));
     $filepath = $this->rootDir . '/../' . $filename;
     file_put_contents($filepath, json_encode($this->normalizer->normalize($this->collectionGenerator->generate(), 'json')));
     $text = sprintf('Postman collection has been successfully built in file %s.', $filename);
     $output->writeln(['', $this->getHelperSet()->get('formatter')->formatBlock($text, 'bg=blue;fg=white', true), '']);
 }
Esempio n. 13
0
 public function instantiate(string $class, array $data)
 {
     $object = new $class();
     foreach ($data as $key => $value) {
         $property = Inflector::camelize($key);
         $object->{$property} = $value;
     }
     return $object;
 }
 public function initializeAction(string $token)
 {
     $payment = $this->getManager()->findPaymentByToken($token);
     $order = $payment->getOrder();
     $processor = $this->getPaymentProcessor($order->getPaymentMethod()->getProcessor());
     $processorName = ucfirst(Inflector::camelize($processor->getConfigurator()->getName()));
     $content = $this->renderView(sprintf('WellCommercePaymentBundle:Front/%s:initialize.html.twig', $processorName), ['payment' => $payment]);
     return new Response($content);
 }
    public function relation_maker($model_name, $relation_type)
    {
        return '
    public function ' . ($relation_type == 'belongsTo' ? strtolower($model_name) : Inflector::pluralize(strtolower($model_name))) . '()
    {
        return $this->' . Inflector::camelize($relation_type) . '(\'App\\' . $model_name . '\');
    }
';
    }
Esempio n. 16
0
 /**
  * Magic getter.
  *
  * @param mixed $name
  *
  * @return mixed
  */
 public function __set($propertyName, $propertyValue)
 {
     $propertyName = Inflector::tableize($propertyName);
     if (!property_exists($this, $propertyName)) {
         throw new BadMethodCallException(sprintf('Entity %s does not have a property named %s', get_class($this), $propertyName));
     }
     $propertyName = Inflector::camelize($propertyName);
     $setter = sprintf('set%s', ucfirst($propertyName));
     return $this->{$setter}($propertyValue);
 }
Esempio n. 17
0
 /**
  * @param array $data
  */
 public function fromArray(array $values)
 {
     foreach ($values as $key => $value) {
         $methodName = 'set' . Inflector::camelize($key);
         if (method_exists($this, $methodName)) {
             $this->{$methodName}($value);
         } else {
             $this->{$key} = $value;
         }
     }
 }
 /**
  * Try to call a state lifecycle callback
  *
  * @param \KPhoen\DoctrineStateMachineBehavior\Entity\Stateful $object
  * @param string $callbackPrefix
  * @param string $transitionName
  * @return mixed
  */
 protected function callCallback($object, $callbackPrefix, $transitionName)
 {
     $camelCasedName = Inflector::camelize($transitionName);
     $methodName = $callbackPrefix . $camelCasedName;
     if (!method_exists($this, $methodName)) {
         return;
     }
     if (!$this->supportsObject($object)) {
         return;
     }
     return call_user_func(array($this, $methodName), $object);
 }
Esempio n. 19
0
 /**
  * @param \ReflectionClass $reflection
  * @param FactoryArguments $args
  * @return String|Integer
  * @author Lukasz Mordawski <*****@*****.**>
  *
  * This method gets additional parameter that must be passed to wrapper constructor from FactoryArguments object.
  */
 private function getAdditionalParameter(\ReflectionClass $reflection, FactoryArguments $args)
 {
     $constructor = $reflection->getConstructor();
     $constructorParameters = $constructor->getParameters();
     $constructorParameter = $constructorParameters[0];
     $name = $constructorParameter->getName();
     $name = Inflector::camelize($name);
     if ($args->{$name} === null) {
         throw new \LogicException($name . ' should not be null');
     }
     return $args->{$name};
 }
 protected function getOperatorMock($type, $name, $field = null, $value = null)
 {
     $operatorClass = Inflector::camelize($name);
     $namespace = 'ABK\\QueryBundle\\Filter\\Operators\\' . ucfirst($type);
     $operatorMock = $this->getMockBuilder($namespace . '\\' . ($type === Types::LOGICAL ? ucfirst($type) : '') . ucfirst($operatorClass))->disableOriginalConstructor()->getMock();
     if ($type === Types::COMPARISON) {
         $operatorMock->expects($this->any())->method('getField')->will($this->returnValue($field));
         $operatorMock->expects($this->any())->method('getValue')->will($this->returnValue($value));
     }
     $operatorMock->expects($this->any())->method('getName')->will($this->returnValue($name));
     $operatorMock->expects($this->any())->method('getType')->will($this->returnValue($type));
     return $operatorMock;
 }
Esempio n. 21
0
 public function instantiate(string $class, array $data)
 {
     $object = new $class();
     $reflection = new \ReflectionClass($object);
     foreach ($data as $key => $value) {
         $property = $reflection->getProperty(Inflector::camelize($key));
         if (!$property->isPublic()) {
             $property->setAccessible(true);
         }
         $property->setValue($object, $value);
     }
     return $object;
 }
Esempio n. 22
0
 /**
  * Get value of property by name
  *
  * @param  string $name
  *
  * @return mixed
  */
 public function getValue($name)
 {
     $propertyAccessor = PropertyAccess::createPropertyAccessor();
     foreach ($this->valueContainers as $data) {
         if (is_array($data) && array_key_exists($name, $data)) {
             return $data[$name];
         }
         if (is_object($data)) {
             return $propertyAccessor->getValue($data, Inflector::camelize($name));
         }
     }
     return null;
 }
Esempio n. 23
0
 /**
  * Get value of property by name
  *
  * @param  string $name
  *
  * @return mixed
  */
 public function getValue($name)
 {
     foreach ($this->valueContainers as $data) {
         if (is_array($data)) {
             if (strpos($name, '[') === 0) {
                 return $this->getPropertyAccessor()->getValue($data, $name);
             } elseif (array_key_exists($name, $data)) {
                 return $data[$name];
             }
         } elseif (is_object($data)) {
             return $this->getPropertyAccessor()->getValue($data, Inflector::camelize($name));
         }
     }
     return null;
 }
 protected function resolveController($parameters)
 {
     if ($parameters['_route'] === 'magic') {
         // Controller is not defined, magically resolve.
         $controller = sprintf('Eng\\%s\\Controller\\%sController::%sAction', $this->bundle, Inflector::classify(strtolower($parameters['controller'])), Inflector::camelize(strtolower($parameters['action'])));
     } else {
         // Controller to use defined explicitly in route parameters
         $controller = $parameters['_controller'];
     }
     list($controller, $action) = $this->createController($controller);
     if (!method_exists($controller, $action)) {
         throw new \InvalidArgumentException(sprintf('Method "%s::%s" does not exist.', get_class($controller), $action));
     }
     return array($controller, $action);
 }
Esempio n. 25
0
 /**
  * Collection name associated with document model. Can automatically generate collection name
  * based on model class.
  *
  * @return mixed
  */
 public function getCollection()
 {
     if ($this->isEmbeddable()) {
         return null;
     }
     $collection = $this->property('collection');
     if (empty($collection)) {
         if ($this->parentSchema()) {
             //Using parent collection
             return $this->parentSchema()->getCollection();
         }
         $collection = Inflector::camelize($this->getShortName());
         $collection = Inflector::pluralize($collection);
     }
     return $collection;
 }
Esempio n. 26
0
 /**
  * @param  object $object
  * @param  string $format : lower|tableize|classify|camelize
  *
  * @return string
  *
  * @throws \RuntimeException
  */
 public static function getModelName($object, $format = 'tableize')
 {
     $reflection = new \ReflectionClass(get_class($object));
     $className = $reflection->getShortName();
     switch ($format) {
         case 'lower':
             return strtolower($className);
         case 'tableize':
             return Inflector::tableize($className);
         case 'classify':
             return Inflector::classify($className);
         case 'camelize':
             return Inflector::camelize($className);
         default:
             throw new \RuntimeException('Invalid format');
     }
 }
Esempio n. 27
0
 /**
  * Populate from array
  * @param array $fromArray Create from array
  * @return static
  */
 public function fromArray(array $fromArray)
 {
     foreach ($fromArray as $key => $value) {
         $lowerCamelCaseKey = Inflector::camelize($key);
         if (property_exists($this, $lowerCamelCaseKey)) {
             switch ($key) {
                 case 'mtime':
                     $this->{$lowerCamelCaseKey} = DateTime::createFromFormat("U", $value);
                     break;
                 default:
                     $this->{$lowerCamelCaseKey} = $value;
                     break;
             }
         }
     }
     return $this;
 }
Esempio n. 28
0
 public static function get($obj, $prop)
 {
     $reflectionClass = new \ReflectionClass($obj);
     $getter = Inflector::camelize('get_' . $prop);
     if (method_exists($obj, $getter)) {
         return $obj->{$getter}();
     }
     $reflectionProperty = $reflectionClass->getProperty($prop);
     if ($reflectionProperty->isPrivate() || $reflectionProperty->isProtected()) {
         $reflectionProperty->setAccessible(true);
         $value = $reflectionProperty->getValue($obj);
         $reflectionProperty->setAccessible(false);
     } else {
         $value = $reflectionProperty->getValue($obj);
     }
     return $value;
 }
Esempio n. 29
0
 /**
  * Returns the required data for model.
  * 
  * @return void
  */
 public function concat(array &$data)
 {
     $columns = $this->describe->getTable($data['name']);
     $counter = 0;
     $data['labels'] = '';
     $data['rules'] = '';
     foreach ($columns as $column) {
         $isBoolean = $column->getDataType() == 'integer' && $column->getLength() == 1;
         if ($column->isPrimaryKey() || $column->isNull() || $isBoolean || strpos($column->getDataType(), 'blob') !== false) {
             continue;
         }
         $template = '$this->validator->rule(\'required\', \'{name}\');' . "\n";
         $keywords = ['{name}' => $column->getField(), '{mutatorName}' => Inflector::camelize('set_' . $column->getField())];
         $label = ucfirst(str_replace('_', ' ', Inflector::tableize($column->getField())));
         $template = str_replace(array_keys($keywords), array_values($keywords), $template);
         if ($column->isForeignKey()) {
             $referencedTable = $this->stripTableSchema($column->getReferencedTable());
             $label = ucfirst(str_replace('_', ' ', Inflector::tableize($referencedTable)));
         }
         if ($column->getField() != 'datetime_created' && $column->getField() != 'datetime_updated' && $column->getField() != 'password') {
             $data['labels'] .= '\'' . $column->getField() . '\' => \'' . $label . '\',';
             $data['rules'] .= $template;
         }
         if ($column->getField() == 'password') {
             $data['labels'] .= '\'' . $column->getField() . '\' => \'' . $label . '\',';
             $data['labels'] .= "\n            " . '\'password_confirmation\' => \'Password confirmation\',';
         }
         if ($counter < count($columns) - 1) {
             if ($column->getField() != 'datetime_created' && $column->getField() != 'datetime_updated') {
                 if ($column->getField() != 'password') {
                     $data['rules'] .= '        ';
                 }
                 $data['labels'] .= "\n" . '            ';
             }
         }
         $counter++;
     }
     $data['labels'] = trim($data['labels']);
     $data['rules'] = trim($data['rules']);
     foreach ($columns as $column) {
         if ($column->getField() == 'password') {
             $data['rules'] .= "\n\n        " . 'if (isset($data[\'password\']) && $data[\'password\'] != null || ! isset($data[\'_method\'])) { ' . "\n            " . '$this->validator->rule(\'required\', \'password\');' . "\n            " . '$this->validator->rule(\'equals\', \'password\', \'password_confirmation\');' . "\n        " . '}';
         }
     }
 }
Esempio n. 30
0
 /**
  * @param string[] $resourceClassNames
  *
  * @throws \InvalidArgumentException when class name is not a Resource
  */
 protected function setSubResources(array $resourceClassNames)
 {
     foreach ($resourceClassNames as $key => $value) {
         $resourceClassName = is_int($key) ? $value : $key;
         if (false === is_subclass_of($resourceClassName, Resource::class)) {
             //@codeCoverageIgnoreStart
             throw new \InvalidArgumentException(sprintf('Class %s is not an instance of %s', $resourceClassName, Resource::class));
             //@codeCoverageIgnoreEnd
         }
         $resourceName = $this->getResourceName($resourceClassName);
         $uri = ltrim(sprintf('%s/%s', $this->uri, $resourceName), '/');
         if (false === is_int($key)) {
             $uri = $value;
         }
         $class = new $resourceClassName($this->transport, $uri);
         $this->subResources[lcfirst(Inflector::camelize($resourceName))] = $class;
     }
 }