public function getName() { $name = $this->reflection->getName(); $inflector = new Inflector(); $name = $inflector->tableize($name); return $name; }
public function validate(Request $request, array $rules) { $valid = true; foreach ($rules as $field => $rule) { if (is_null($rule) || !is_string($rule) || strlen($rule) == 0) { throw new ValidationException("Rule must be a string"); } // get field value $value = $request->input($field); // split validation rule into required / sometimes (no validation if not set or empty) // contract and contract parameters $parts = explode("|", $rule); if (is_null($parts) || !is_array($parts) || count($parts) < 3) { throw new ValidationException("Invalid rule"); } $required = strtolower($parts[0]) == "required" ? true : false; if ($required && is_null($value)) { $valid = false; continue; } $args = explode(":", $parts[1]); $clazz = Inflector::classify($args[0]) . "Contract"; if (!class_exists($clazz)) { throw new ValidationException("Invalid rule: invalid validation class '{$clazz}'"); } $instance = new $clazz($value, isset($args[1]) ? $args[1] : array()); if (!$instance instanceof Contract) { throw new ValidationException("Invalid rule: invalid validation class '{$clazz}'. Class must extend Simplified\\Validator\\Contract"); } if (!$instance->isValid()) { $valid = false; } } return $valid; }
/** * @param LifecycleEventArgs $event */ public function prePersist(LifecycleEventArgs $event) { $document = $event->getDocument(); $className = get_class($document); $generateAnnotations = $this->annotationReader->getClassAnnotation(new \ReflectionClass($className), 'OpenOrchestra\\Mapping\\Annotations\\Document'); if (!is_null($generateAnnotations)) { $repository = $this->container->get($generateAnnotations->getServiceName()); $getSource = $generateAnnotations->getSource($document); $getGenerated = $generateAnnotations->getGenerated($document); $setGenerated = $generateAnnotations->setGenerated($document); $testMethod = $generateAnnotations->getTestMethod(); if ($testMethod === null && $repository instanceof FieldAutoGenerableRepositoryInterface) { $testMethod = 'testUniquenessInContext'; } if (is_null($document->{$getGenerated}())) { $source = $document->{$getSource}(); $source = Inflector::tableize($source); $sourceField = $this->suppressSpecialCharacterHelper->transform($source); $generatedField = $sourceField; $count = 1; while ($repository->{$testMethod}($generatedField)) { $generatedField = $sourceField . '-' . $count; $count++; } $document->{$setGenerated}($generatedField); } } }
/** * {@inheritdoc} */ public function getDirection($activity, $target) { //check if target is entity created from admin part if (!$target instanceof EmailHolderInterface) { $metadata = $this->doctrineHelper->getEntityMetadata($target); $columns = $metadata->getColumnNames(); $className = get_class($target); foreach ($columns as $column) { //check only columns with 'contact_information' if ($this->isEmailType($className, $column)) { $getMethodName = "get" . Inflector::classify($column); /** @var $activity Email */ if ($activity->getFromEmailAddress()->getEmail() === $target->{$getMethodName}()) { return DirectionProviderInterface::DIRECTION_OUTGOING; } else { foreach ($activity->getTo() as $recipient) { if ($recipient->getEmailAddress()->getEmail() === $target->{$getMethodName}()) { return DirectionProviderInterface::DIRECTION_INCOMING; } } } } } return DirectionProviderInterface::DIRECTION_UNKNOWN; } /** @var $activity Email */ /** @var $target EmailHolderInterface */ if ($activity->getFromEmailAddress()->getEmail() === $target->getEmail()) { return DirectionProviderInterface::DIRECTION_OUTGOING; } return DirectionProviderInterface::DIRECTION_INCOMING; }
/** * @param ContainerBuilder $container */ public function process(ContainerBuilder $container) { $bundles = $container->getParameter('kernel.bundles'); $reader = $container->get('annotation_reader'); $registry = $container->getDefinition('lemon_rest.object_registry'); foreach ($bundles as $name => $bundle) { $reflection = new \ReflectionClass($bundle); $baseNamespace = $reflection->getNamespaceName() . '\\Entity\\'; $dir = dirname($reflection->getFileName()) . '/Entity'; if (is_dir($dir)) { $finder = new Finder(); $iterator = $finder->files()->name('*.php')->in($dir); /** @var SplFileInfo $file */ foreach ($iterator as $file) { // Translate the directory path from our starting namespace forward $expandedNamespace = substr($file->getPath(), strlen($dir) + 1); // If we are in a sub namespace add a trailing separation $expandedNamespace = $expandedNamespace === false ? '' : $expandedNamespace . '\\'; $className = $baseNamespace . $expandedNamespace . $file->getBasename('.php'); if (class_exists($className)) { $reflectionClass = new \ReflectionClass($className); foreach ($reader->getClassAnnotations($reflectionClass) as $annotation) { if ($annotation instanceof Resource) { $name = $annotation->name ?: Inflector::pluralize(lcfirst($reflectionClass->getShortName())); $definition = new Definition('Lemon\\RestBundle\\Object\\Definition', array($name, $className, $annotation->search, $annotation->create, $annotation->update, $annotation->delete, $annotation->partialUpdate)); $container->setDefinition('lemon_rest.object_resources.' . $name, $definition); $registry->addMethodCall('add', array($definition)); } } } } } } }
private function toIdentifier($object) { $className = get_class($object); $className = substr($className, strrpos($className, '\\') + 1); $className = str_replace('SystemInfo', '', $className); return Inflector::tableize($className); }
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); }
/** * @param $keys * @param $object * @return array */ protected function getParametersFromObject($keys, $object) { $parameters = []; foreach ($keys as $key) { $relation = $object; $method = 'get' . Inflector::classify($key); if (method_exists($relation, $method)) { $relation = $relation->{$method}(); } else { $segments = explode('_', $key); if (count($segments) > 1) { foreach ($segments as $segment) { $method = 'get' . Inflector::classify($segment); if (method_exists($relation, $method)) { $relation = $relation->{$method}(); } else { $relation = $object; break; } } } } if ($object !== $relation) { $parameters[$key] = $relation; } } return $parameters; }
/** * @param array $data */ public function fromArray(array $data) { foreach ($data as $key => $value) { $property = Inflector::camelize($key); $this->{$property} = $value; } }
public function transform($entities) { foreach ($entities as &$entity) { $entity['icon'] = $this->getIcon(Inflector::singularize($entity['name'])); } return $entities; }
/** * @param Request $request * @param string $id * @param string $type * @param string $event * @param string $eventClass * * @return Response */ protected function reverseTransform(Request $request, $id, $type, $event, $eventClass) { $facadeName = Inflector::classify($type) . 'Facade'; $typeName = Inflector::tableize($type); $format = $request->get('_format', 'json'); $facade = $this->get('jms_serializer')->deserialize($request->getContent(), 'OpenOrchestra\\ApiBundle\\Facade\\' . $facadeName, $format); $mixed = $this->get('open_orchestra_model.repository.' . $typeName)->find($id); $oldStatus = null; if ($mixed instanceof StatusableInterface) { $oldStatus = $mixed->getStatus(); } $mixed = $this->get('open_orchestra_api.transformer_manager')->get($typeName)->reverseTransform($facade, $mixed); if ($this->isValid($mixed)) { $em = $this->get('object_manager'); $em->persist($mixed); $em->flush(); if (in_array('OpenOrchestra\\ModelInterface\\Event\\EventTrait\\EventStatusableInterface', class_implements($eventClass))) { $this->dispatchEvent($event, new $eventClass($mixed, $oldStatus)); return array(); } $this->dispatchEvent($event, new $eventClass($mixed)); return array(); } return $this->getViolations(); }
/** * @param FactoryArguments $arguments * @param $method * @param array $parameters * @return mixed * @throws \LukaszMordawski\CampaignMonitorBundle\Exception\Exception * @throws \LogicException * * This method invokes proper API method and stores result in cache. */ public function invoke(FactoryArguments $arguments, $method, $parameters = []) { if (!$arguments->clientId) { $arguments->clientId = $this->clientId; } $method = Inflector::tableize($method); $cacheKey = $this->getCacheKey($arguments, $method, $parameters); if ($this->cache->contains($cacheKey)) { return unserialize($this->cache->fetch($cacheKey)); } $csClient = $this->factory->factory($arguments); if (method_exists($csClient, $method)) { if (is_array($parameters)) { $data = call_user_func_array([$csClient, $method], $parameters); } else { $data = call_user_func([$csClient, $method], $parameters); } } else { throw new \LogicException(sprintf('Method %s does not exist for class %s', $method, get_class($csClient))); } if ($data->http_status_code != 200 && $data->http_status_code != 201) { throw new Exception($data->response->Message, $data->response->Code); } $this->cache->save($cacheKey, serialize($data->response), $this->cacheLifetime); return $data->response; }
public static function arrayToXml(array $data, \SimpleXMLElement $xml, $parentKey = null, $keyFilterCallback = null) { foreach ($data as $k => $v) { if (!is_numeric($k) && is_callable($keyFilterCallback)) { $k = call_user_func($keyFilterCallback, $k); } if (is_array($v)) { if (!is_numeric($k)) { self::arrayToXml($v, $xml->addChild($k), $k, $keyFilterCallback); } else { self::arrayToXml($v, $xml->addChild(Inflector::singularize($parentKey)), null, $keyFilterCallback); } } else { if (!is_numeric($k)) { $xml->addChildWithCDATA($k, $v); } else { if (!is_null($parentKey)) { $xml->addChildWithCDATA(Inflector::singularize($parentKey), $v); } else { throw new \Exception("Array To xml forma error: invalid element name {$k}"); } } } } return $xml; }
/** * {@inheritDoc} */ public function process(ContainerBuilder $container) { if (!$container->hasDefinition(self::SERVICE_KEY)) { return; } // find providers $providers = []; $taggedServices = $container->findTaggedServiceIds(self::TAG); foreach ($taggedServices as $id => $attributes) { if (empty($attributes[0]['scope'])) { throw new InvalidConfigurationException(sprintf('Tag attribute "scope" is required for "%s" service', $id)); } $priority = isset($attributes[0]['priority']) ? $attributes[0]['priority'] : 0; $scope = $attributes[0]['scope']; $providers[$scope][$priority][] = new Reference($id); } if (empty($providers)) { return; } // add to chain $serviceDef = $container->getDefinition(self::SERVICE_KEY); foreach ($providers as $scope => $items) { // sort by priority and flatten krsort($items); $items = call_user_func_array('array_merge', $items); // register foreach ($items as $provider) { $serviceDef->addMethodCall(sprintf('add%sVariablesProvider', Inflector::classify($scope)), [$provider]); } } }
/** * Execute after types are built. */ public function postBuild() { $types_build_path = $this->getBuildPath() ? "{$this->getBuildPath()}/types.php" : null; if ($types_build_path) { $result = []; $result[] = '<?php'; $result[] = ''; if ($this->getStructure()->getConfig('header_comment')) { $result = array_merge($result, explode("\n", $this->getStructure()->getConfig('header_comment'))); $result[] = ''; } $namespace = $this->getStructure()->getNamespace(); if ($namespace) { $namespace = ltrim($namespace, '\\'); } if ($this->getStructure()->getNamespace()) { $result[] = '/**'; $result[] = ' * @package ' . $this->getStructure()->getNamespace(); $result[] = ' */'; } $result[] = 'return ['; foreach ($this->getStructure()->getTypes() as $current_type) { $result[] = ' ' . var_export($namespace . '\\' . Inflector::classify(Inflector::singularize($current_type->getName())), true) . ','; } $result[] = '];'; $result[] = ''; $result = implode("\n", $result); if (is_file($types_build_path) && file_get_contents($types_build_path) === $result) { return; } else { file_put_contents($types_build_path, $result); $this->triggerEvent('on_types_built', [$types_build_path]); } } }
/** * @param TypeInterface $type */ public function buildType(TypeInterface $type) { $class_name = Inflector::classify(Inflector::singularize($type->getName())); $base_class_name = 'Base\\' . $class_name; $class_build_path = $this->getBuildPath() ? "{$this->getBuildPath()}/{$class_name}.php" : null; if ($class_build_path && is_file($class_build_path)) { $this->triggerEvent('on_class_build_skipped', [$class_name, $class_build_path]); return; } $result = []; $result[] = '<?php'; $result[] = ''; if ($this->getStructure()->getConfig('header_comment')) { $result = array_merge($result, explode("\n", $this->getStructure()->getConfig('header_comment'))); $result[] = ''; } if ($this->getStructure()->getNamespace()) { $result[] = 'namespace ' . $this->getStructure()->getNamespace() . ';'; $result[] = ''; $result[] = '/**'; $result[] = ' * @package ' . $this->getStructure()->getNamespace(); $result[] = ' */'; } $result[] = 'class ' . $class_name . ' extends ' . $base_class_name; $result[] = '{'; $result[] = '}'; $result[] = ''; $result = implode("\n", $result); if ($this->getBuildPath()) { file_put_contents($class_build_path, $result); } else { eval(ltrim($result, '<?php')); } $this->triggerEvent('on_class_built', [$class_name, $class_build_path]); }
/** * Return singular or plural parameter, based on the given count * * @param integer $count * @param string $singular * @param string $plural * @return string */ public static function pluralize($count = 1, $singular, $plural = null) { if ($count == 1) { return $singular; } return is_null($plural) ? Inflector::pluralize($singular) : $plural; }
/** * Creates operation. * * @param ResourceInterface $resource * @param bool $collection * @param string|array $methods * @param string|null $path * @param string|null $controller * @param string|null $routeName * @param array $context * * @return Operation */ private function createOperation(ResourceInterface $resource, $collection, $methods, $path = null, $controller = null, $routeName = null, array $context = []) { $shortName = $resource->getShortName(); if (!isset(self::$inflectorCache[$shortName])) { self::$inflectorCache[$shortName] = Inflector::pluralize(Inflector::tableize($shortName)); } // Populate path if (null === $path) { $path = '/' . self::$inflectorCache[$shortName]; if (!$collection) { $path .= '/{id}'; } } // Guess default method if (is_array($methods)) { $defaultMethod = $methods[0]; } else { $defaultMethod = $methods; } // Populate controller if (null === $controller) { $defaultAction = strtolower($defaultMethod); if ($collection) { $defaultAction = 'c' . $defaultAction; } $controller = self::DEFAULT_CONTROLLER . ':' . $defaultAction; // Populate route name if (null === $routeName) { $routeName = self::ROUTE_NAME_PREFIX . self::$inflectorCache[$shortName] . '_' . $defaultAction; } } return new Operation(new Route($path, ['_controller' => $controller, '_resource' => $shortName], [], [], '', [], $methods), $routeName, $context); }
/** * {@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); } } }); } }
public function load($resource, $type = null) { $routes = new RouteCollection(); list($prefix, $resource) = explode('.', $resource); $pluralResource = Inflector::pluralize($resource); $rootPath = '/' . $pluralResource . '/'; $requirements = array(); // GET collection request. $routeName = sprintf('%s_api_%s_index', $prefix, $resource); $defaults = array('_controller' => sprintf('%s.controller.%s:indexAction', $prefix, $resource)); $route = new Route($rootPath, $defaults, $requirements, array(), '', array(), array('GET')); $routes->add($routeName, $route); // GET request. $routeName = sprintf('%s_api_%s_show', $prefix, $resource); $defaults = array('_controller' => sprintf('%s.controller.%s:showAction', $prefix, $resource)); $route = new Route($rootPath . '{id}', $defaults, $requirements, array(), '', array(), array('GET')); $routes->add($routeName, $route); // POST request. $routeName = sprintf('%s_api_%s_create', $prefix, $resource); $defaults = array('_controller' => sprintf('%s.controller.%s:createAction', $prefix, $resource)); $route = new Route($rootPath, $defaults, $requirements, array(), '', array(), array('POST')); $routes->add($routeName, $route); // PUT request. $routeName = sprintf('%s_api_%s_update', $prefix, $resource); $defaults = array('_controller' => sprintf('%s.controller.%s:updateAction', $prefix, $resource)); $route = new Route($rootPath . '{id}', $defaults, $requirements, array(), '', array(), array('PUT', 'PATCH')); $routes->add($routeName, $route); // DELETE request. $routeName = sprintf('%s_api_%s_delete', $prefix, $resource); $defaults = array('_controller' => sprintf('%s.controller.%s:deleteAction', $prefix, $resource)); $route = new Route($rootPath . '{id}', $defaults, $requirements, array(), '', array(), array('DELETE')); $routes->add($routeName, $route); return $routes; }
protected function mapDirectory(ContainerBuilder $container, $dir, $prefix) { if (!is_dir($dir)) { throw new \RuntimeException(sprintf("Invalid directory %s", $dir)); } $reader = $container->get('annotation_reader'); $registry = $container->getDefinition('lemon_rest.object_registry'); $finder = new Finder(); $iterator = $finder->files()->name('*.php')->in($dir); if (substr($prefix, -1, 1) !== "\\") { $prefix .= "\\"; } /** @var \SplFileInfo $file */ foreach ($iterator as $file) { // Translate the directory path from our starting namespace forward $expandedNamespace = substr($file->getPath(), strlen($dir) + 1); // If we are in a sub namespace add a trailing separation $expandedNamespace = $expandedNamespace === false ? '' : $expandedNamespace . '\\'; $className = $prefix . $expandedNamespace . $file->getBasename('.php'); if (class_exists($className)) { $reflectionClass = new \ReflectionClass($className); foreach ($reader->getClassAnnotations($reflectionClass) as $annotation) { if ($annotation instanceof Resource) { $name = $annotation->name ?: Inflector::pluralize(lcfirst($reflectionClass->getShortName())); $definition = new Definition('Lemon\\RestBundle\\Object\\Definition', array($name, $className, $annotation->search, $annotation->create, $annotation->update, $annotation->delete, $annotation->partialUpdate)); $container->setDefinition('lemon_rest.object_resources.' . $name, $definition); $registry->addMethodCall('add', array($definition)); } } } } }
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; }
protected function execute(InputInterface $input, OutputInterface $output) { $selectedSections = $input->getArgument('sections'); $sections = []; foreach (static::$availableSections as $section) { if (in_array($section, $selectedSections) || in_array(Inflector::pluralize($section), $selectedSections)) { $sections[] = $section; } } if (empty($sections)) { $sections = static::$defaultSections; } foreach ($sections as $section) { switch ($section) { case 'locale': $this->displayLocale($input, $output); break; case 'format': $this->displayFormat($input, $output); break; case 'converter': $this->displayConverter($input, $output); break; case 'provider': $this->displayProvider($input, $output); break; case 'method': $this->displayMethod($input, $output); break; } } }
public function testChoiceNormalizer() { // source data $workflowAwareClass = 'WorkflowAwareClass'; $extendedClass = 'ExtendedClass'; $notExtendedClass = 'NotExtendedClass'; $notConfigurableClass = 'NotConfigurableClass'; // asserts $this->entityConnector->expects($this->any())->method('isWorkflowAware')->will($this->returnCallback(function ($class) use($workflowAwareClass) { return $class === $workflowAwareClass; })); $extendedEntityConfig = $this->getMock('Oro\\Bundle\\EntityConfigBundle\\Config\\ConfigInterface'); $extendedEntityConfig->expects($this->any())->method('is')->with('is_extend')->will($this->returnValue(true)); $notExtendedEntityConfig = $this->getMock('Oro\\Bundle\\EntityConfigBundle\\Config\\ConfigInterface'); $notExtendedEntityConfig->expects($this->any())->method('is')->with('is_extend')->will($this->returnValue(false)); $extendConfigProvider = $this->getMockBuilder('Oro\\Bundle\\EntityConfigBundle\\Provider\\ConfigProvider')->disableOriginalConstructor()->getMock(); $hasConfigMap = array(array($workflowAwareClass, null, false), array($extendedClass, null, true), array($notExtendedClass, null, true), array($notConfigurableClass, null, false)); $extendConfigProvider->expects($this->any())->method('hasConfig')->with($this->isType('string'), null)->will($this->returnValueMap($hasConfigMap)); $getConfigMap = array(array($extendedClass, null, $extendedEntityConfig), array($notExtendedClass, null, $notExtendedEntityConfig)); $extendConfigProvider->expects($this->any())->method('getConfig')->with($this->isType('string'), null)->will($this->returnValueMap($getConfigMap)); $this->configManager->expects($this->once())->method('getProvider')->with('extend')->will($this->returnValue($extendConfigProvider)); // test $inputChoices = array($workflowAwareClass => Inflector::tableize($workflowAwareClass), $extendedClass => Inflector::tableize($extendedClass), $notExtendedClass => Inflector::tableize($notExtendedClass), $notConfigurableClass => Inflector::tableize($notConfigurableClass)); $expectedChoices = array($workflowAwareClass => Inflector::tableize($workflowAwareClass), $extendedClass => Inflector::tableize($extendedClass)); $resolver = new OptionsResolver(); $resolver->setDefaults(array('choices' => $inputChoices)); $this->formType->setDefaultOptions($resolver); $result = $resolver->resolve(array()); $this->assertEquals($expectedChoices, $result['choices']); }
/** * Creates operation. * * @param ResourceInterface $resource * @param bool $collection * @param string|array $methods * @param string|null $path * @param string|null $controller * @param string|null $routeName * @param array $context * * @return Operation */ private function createOperation(ResourceInterface $resource, $collection, $methods, $path = null, $controller = null, $routeName = null, array $context = []) { $shortName = $resource->getShortName(); if (!isset(self::$inflectorCache[$shortName])) { self::$inflectorCache[$shortName] = Inflector::pluralize(Inflector::tableize($shortName)); } // Populate path if (null === $path) { $path = '/' . self::$inflectorCache[$shortName]; if (!$collection) { $path .= '/{id}'; } } // Guess default method if (is_array($methods)) { $defaultMethod = $methods[0]; } else { $defaultMethod = $methods; } // Populate controller if (null === $controller) { $actionName = sprintf('%s_%s', strtolower($defaultMethod), $collection ? 'collection' : 'item'); $controller = self::DEFAULT_ACTION_PATTERN . $actionName; // Populate route name if (null === $routeName) { $routeName = sprintf('%s%s_%s', self::ROUTE_NAME_PREFIX, self::$inflectorCache[$shortName], $actionName); } } return new Operation(new Route($path, ['_controller' => $controller, '_resource' => $shortName], [], [], '', [], $methods), $routeName, $context); }
/** * {@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; }
public function handle($className, Property $property) { try { if ($type = $this->guesser->guessType($className, $property->getName())) { $property->addType($this->getPropertyType($type)); $property->setFormat($this->getPropertyFormat($type)); if (in_array($type->getType(), array('document', 'entity'))) { $options = $type->getOptions(); if (isset($options['class']) && $this->registry->hasNamespace($options['class'])) { $alias = $this->registry->getAlias($options['class']); if ($alias) { $property->setObject($alias); if (isset($options['multiple']) && $options['multiple'] == true) { $property->setMultiple(true); } } } } } if ($required = $this->guesser->guessRequired($className, $property->getName())) { $property->setRequired($required->getValue()); } if ($pattern = $this->guesser->guessPattern($className, $property->getName())) { $property->setPattern($pattern->getValue()); } if ($maximum = $this->guesser->guessMaxLength($className, $property->getName())) { $property->setMaximum($maximum->getValue()); } if ($property->getTitle() == null) { $title = ucwords(str_replace('_', ' ', Inflector::tableize($property->getName()))); $property->setTitle($title); } } catch (MappingException $e) { } }
/** * Generate the CRUD controller. * * @param BundleInterface $bundle A bundle object * @param string $entity The entity relative class name * @param ClassMetadataInfo $metadata The entity class metadata * @param string $format The configuration format (xml, yaml, annotation) * @param string $routePrefix The route name prefix * @param array $needWriteActions Wether or not to generate write actions * * @throws \RuntimeException */ public function generate(BundleInterface $bundle, $entity, ClassMetadataInfo $metadata, $format, $routePrefix, $needWriteActions, $forceOverwrite) { $this->routePrefix = $routePrefix; $this->routeNamePrefix = self::getRouteNamePrefix($routePrefix); $this->actions = $needWriteActions ? array('index', 'show', 'new', 'edit', 'delete') : array('index', 'show'); if (count($metadata->identifier) != 1) { throw new \RuntimeException('The CRUD generator does not support entity classes with multiple or no primary keys.'); } $this->entity = $entity; $this->entitySingularized = lcfirst(Inflector::singularize($entity)); $this->entityPluralized = lcfirst(Inflector::pluralize($entity)); $this->bundle = $bundle; $this->metadata = $metadata; $this->setFormat($format); $this->generateControllerClass($forceOverwrite); $dir = sprintf('%s/Resources/views/%s', $this->rootDir, str_replace('\\', '/', strtolower($this->entity))); if (!file_exists($dir)) { $this->filesystem->mkdir($dir, 0777); } $this->generateIndexView($dir); if (in_array('show', $this->actions)) { $this->generateShowView($dir); } if (in_array('new', $this->actions)) { $this->generateNewView($dir); } if (in_array('edit', $this->actions)) { $this->generateEditView($dir); } $this->generateTestClass(); $this->generateConfiguration(); }
/** * Executes the command. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return object|\Symfony\Component\Console\Output\OutputInterface */ protected function execute(InputInterface $input, OutputInterface $output) { $config = Configuration::get(); $templates = str_replace('Commands', 'Templates', __DIR__); $contents = []; $generator = new ViewGenerator($this->describe); $data = ['{name}' => $input->getArgument('name'), '{pluralTitle}' => Inflector::ucwords(str_replace('_', ' ', Inflector::pluralize($input->getArgument('name')))), '{plural}' => Inflector::pluralize($input->getArgument('name')), '{singular}' => Inflector::singularize($input->getArgument('name'))]; $contents['create'] = $generator->generate($data, $templates, 'create'); $contents['edit'] = $generator->generate($data, $templates, 'edit'); $contents['index'] = $generator->generate($data, $templates, 'index'); $contents['show'] = $generator->generate($data, $templates, 'show'); $fileName = $config->folders->views . '/' . $data['{plural}'] . '/'; $layout = $config->folders->views . '/layouts/master.twig'; if (!$this->filesystem->has($layout)) { $template = file_get_contents($templates . '/Views/layout.twig'); $keywords = ['{application}' => $config->application->name]; $template = str_replace(array_keys($keywords), array_values($keywords), $template); $this->filesystem->write($layout, $template); } foreach ($contents as $type => $content) { $view = $fileName . $type . '.twig'; if ($this->filesystem->has($view)) { if (!$input->getOption('overwrite')) { return $output->writeln('<error>View already exists.</error>'); } else { $this->filesystem->delete($view); } } $this->filesystem->write($view, $content); } return $output->writeln('<info>View created successfully.</info>'); }