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) { } }
/** * @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(); }
/** * 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); }
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']); }
/** * @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 function getName() { $name = $this->reflection->getName(); $inflector = new Inflector(); $name = $inflector->tableize($name); return $name; }
private function toIdentifier($object) { $className = get_class($object); $className = substr($className, strrpos($className, '\\') + 1); $className = str_replace('SystemInfo', '', $className); return Inflector::tableize($className); }
/** * 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); }
/** * @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 deduce($class, $event) { $parts = explode('\\', $class); $parts = array_map(function ($e) { return Inflector::tableize($e); }, $parts); return sprintf('%s.%s', implode('.', $parts), Inflector::tableize($event)); }
/** * {@inheritdoc} */ public function resolveOperationPath(string $resourceShortName, array $operation, bool $collection) : string { $path = '/' . Inflector::pluralize(Inflector::tableize($resourceShortName)); if (!$collection) { $path .= '/{id}'; } $path .= '.{_format}'; return $path; }
/** * Hydrate a collection from an array * * @param array $data * * @return Object */ public function fromArray(array $data) { foreach ($data as $key => $value) { if (property_exists($this, $key)) { $this->{'set' . Inflector::tableize($key)}($value); } } return $this; }
/** * Returns the url for the webhook * @param $action Can be create, update or delete * @return string */ public function getWebhookUrl($action) { $params = ['model' => Inflector::tableize($this->getName()), 'action' => $action]; if (defined('WEBHOOK_KEY')) { $params = array_merge(['key' => WEBHOOK_KEY], $params); } $query = http_build_query($params); return WEBHOOK_BASE . '/?' . $query; }
/** * Get the URI for this collection (with placeholders) * * @return string */ protected static function getUri() { if (isset(static::$uri)) { return static::$uri; } // Guess URI $class = preg_replace('/^.+\\\\/', '', static::getResourceClass()); $plural = Inflector::pluralize($class); return '/' . strtr(Inflector::tableize($plural), '_', '-') . '/:id'; }
/** * @return string Model name */ public function getModelName() { if (is_null($this->model_name)) { $model_name = get_class($this); $model_name = explode('\\', $model_name); $model_name = end($model_name); $model_name = substr($model_name, 0, -strlen('Controller')); $this->model_name = Inflector::tableize($model_name); } return $this->model_name; }
/** * Get the Mongo collection name. * Uses the static `$collection` property if available, otherwise guesses based on class name. * * @return string */ protected static function getCollectionName() { if (isset(static::$collection)) { $name = static::$collection; } else { $class = preg_replace('/^.+\\\\/', '', static::getDocumentClass()); $plural = Inflector::pluralize($class); $name = Inflector::tableize($plural); } return $name; }
/** * @param callable|null $callback A callable function compatible with array_map * @param string|null $namespaceSeparator Choose which character should replace namespaces separation. * Example: With Foo\BarMagic enum class with '.' separator, * it will be converted to foo.bar_magic.YOUR_KEY * * @return string[] */ public static final function getClassPrefixedKeys($callback = null, $namespaceSeparator = null) { $namespaceSeparator = $namespaceSeparator ?: static::$defaultNamespaceSeparator; $classKey = str_replace('\\', $namespaceSeparator, Inflector::tableize(static::class)); $keys = static::getKeys(function ($key) use($namespaceSeparator, $classKey) { return $classKey . $namespaceSeparator . $key; }); if (is_callable($callback)) { return array_map($callback, $keys); } return $keys; }
/** * Returns a database table name. * * The name that is returned is based on the classname or on the TABLE_NAME * constant in that class if that constant exists. * * @param string $class_name * @return string Database table name. */ public final function tableName($class_name = null) { if (!$class_name) { $class_name = get_class($this); } if (defined($class_name . '::TABLE_NAME')) { return constant($class_name . '::TABLE_NAME'); } $reflection = new \ReflectionClass($class_name); $class_name = $reflection->getShortName(); return Inflector::tableize($class_name); }
/** * @param string $class * * @return string */ private function buildAlias($class) { $parts = explode('\\', $class); $shortName = end($parts); if (false === strpos($shortName, 'Validator')) { return Inflector::tableize($shortName); } if ('Validator' !== substr($shortName, -9)) { return Inflector::tableize($shortName); } return Inflector::tableize(substr($shortName, 0, -9)); }
/** * Figure out parts of the action path * * @param string $className Name of the action class * @return array Parts of the action path */ public static function getPathParts($className) { $classParts = explode('\\', $className); $path = array_pop($classParts); $path = preg_replace('/Action$/', '', $path); $path = Inflector::tableize($path); $pathParts = explode('_', $path); if ($pathParts[count($pathParts) - 1] === 'index') { array_pop($pathParts); } return $pathParts; }
public function generateFilename($taskName, $time = null) { $date = date('Y-m-d'); if (is_integer($time)) { $date = date('Ymd', $time); } else { if (is_string($time)) { $date = $time; } } $name = Inflector::tableize($taskName); return sprintf('%s_%s.php', $date, $taskName); }
/** * Model constructor. * @param \Enjoin\Model\Definition $Definition * @param string $modelName */ public function __construct(Definition $Definition, $modelName) { if (!property_exists($Definition, 'table') || !$Definition->table) { # Define table name from model name # if not performed manually: $arr = explode('\\', get_class($Definition)); $Definition->table = Inflector::tableize(end($arr)); } $this->Definition = $Definition; $this->modelName = $modelName; $this->unique = get_class($Definition); $this->CacheJar = new CacheJar($this); }
/** * @param AttributeMetadataInterface $attributeMetadata * * @return mixed */ public function guess(AttributeMetadataInterface $attributeMetadata) { $value = null; $type = null; if (true === ($isDoctrine = isset($attributeMetadata->getTypes()[0]))) { $type = $attributeMetadata->getTypes()[0]; } // Guess associations if ($isDoctrine && 'object' === $type->getType() && 'DateTime' !== $type->getClass()) { $class = $type->isCollection() ? $type->getCollectionType()->getClass() : $type->getClass(); $resource = $this->resourceCollection->getResourceForEntity($class); $classMetadata = $this->classMetadataFactory->getMetadataFor($resource->getEntityClass(), $resource->getNormalizationGroups(), $resource->getDenormalizationGroups(), $resource->getValidationGroups()); $id = $this->guess($classMetadata->getIdentifier()); $value = $this->iriConverter->getIriFromResource($resource) . '/' . $id; if ($type->isCollection()) { $value = [$value]; } } // Guess by faker if (null === $value) { try { $value = call_user_func([$this->generator, $attributeMetadata->getName()]); } catch (\InvalidArgumentException $e) { } } // Guess by field name if (null === $value) { $value = $this->guessFormat(Inflector::tableize($attributeMetadata->getName())); } // Guess by Doctrine type if (null === $value && $isDoctrine) { switch ($type->getType()) { case 'string': $value = $this->generator->sentence; break; case 'int': $value = $this->generator->numberBetween; break; case 'bool': $value = $this->generator->boolean; break; case 'object': if ('DateTime' !== $type->getClass()) { throw new \InvalidArgumentException(sprintf('Unknown Doctrine object type %s in field %s', $type->getClass(), $attributeMetadata->getName())); } $value = $this->generator->dateTime; break; } } return $this->clean($value); }
/** * Returns the required data for model. * * @return void */ public function concat(array &$data) { $columns = $this->describe->getTable($data['name']); $counter = 0; $data['columns'] = ''; $data['methods'] = ''; foreach ($columns as $column) { $template = $this->columnTemplate; if (!$column->isPrimaryKey()) { $search = " * @Id @GeneratedValue\n"; $replace = ''; $template = str_replace($search, $replace, $template); if (!$column->isForeignKey()) { $data['methods'] .= $this->mutatorMethodTemplate . "\n "; } else { $data['foreignClasses'] = "\nuse Doctrine\\ORM\\Mapping\\ManyToOne;\n" . "use Doctrine\\ORM\\Mapping\\JoinColumn;"; } if (strpos($column->getDataType(), 'date') !== false) { $template = str_replace(', length={length}', '', $template); } } if ($column->isNull()) { $data['methods'] = str_replace('{class}${variable}', '{class}${variable} = null', $data['methods']); } $data['methods'] .= $this->accessorMethodTemplate; $keywords = ['{name}' => $column->getField(), '{datatype}' => strpos($column->getDataType(), 'blob') !== false ? 'blob' : $column->getDataType(), '{length}' => $column->getLength(), '{variable}' => Inflector::camelize($column->getField()), '{description}' => str_replace('_', ' ', Inflector::tableize($column->getField())), '{accessorName}' => Inflector::camelize('get_' . $column->getField()), '{mutatorName}' => Inflector::camelize('set_' . $column->getField()), '{class}' => '']; if (strpos($column->getDataType(), 'date') !== false) { if (strpos($data['foreignClasses'], "\nuse DateTime;") === false) { $data['foreignClasses'] .= "\nuse DateTime;"; } $data['methods'] = str_replace('@param {datatype}', '@param \\DateTime', $data['methods']); $data['methods'] = str_replace('@return {datatype}', '@return \\DateTime', $data['methods']); $data['methods'] = str_replace('= ${variable};', '= new DateTime(${variable});', $data['methods']); } else { if (strpos($column->getDataType(), 'blob') !== false) { $accesor = '' . 'if (! $this->{variable}) {' . "\n " . 'return null;' . "\n " . '}' . "\n\n " . 'return base64_encode(stream_get_contents($this->{variable}));'; $data['methods'] = str_replace('return $this->{variable};', $accesor, $data['methods']); } } $template = str_replace(array_keys($keywords), array_values($keywords), $template); $data['methods'] = str_replace(array_keys($keywords), array_values($keywords), $data['methods']); $data['columns'] .= $template; $this->setForeignKey($column, $data, $keywords); if ($counter < count($columns) - 1) { $data['columns'] .= "\n\n" . ' '; $data['methods'] .= "\n" . ' '; } $counter++; } $data['methods'] = trim($data['methods']); }
/** * Retrieve the table name for this DAO * * @return string */ public function getTableName() { if ($this->_tableName === null) { $class = get_called_class(); $ns = Objects::getNamespace($class); $dirs = $this->getTableNameExcludeDirs(); foreach ($dirs as $dir) { $ns = ltrim(Strings::offset($ns, $dir), '\\'); } $this->_tableName = trim(Inflector::tableize(implode('_', [Strings::stringToUnderScore($ns), Inflector::pluralize(Objects::classShortname($class))])), '_ '); $this->_tableName = str_replace('__', '_', $this->_tableName); } return $this->_tableName; }
/** * @param ApiResource $apiResource */ protected function addActions(ApiResource $apiResource) { $options = $this->getOptionsForApiResource($apiResource); $def = $this->getDefinitionForApiResource($apiResource); foreach ($this->getActionsForApiResource($apiResource) as $actionName) { $class = Inflector::classify($actionName); $actionClass = "BiteCodes\\RestApiGeneratorBundle\\Api\\Actions\\{$class}"; $action = new Definition($actionClass); $action->addArgument(new Reference('router')); $action->addMethodCall('setSecurityExpression', [$options['routes'][$actionName]['security']]); $action->addMethodCall('setSerializationGroups', [$options['routes'][$actionName]['serialization_groups']]); $this->container->set('bite_codes.rest_api_generator.action.' . $apiResource->getName() . '.' . Inflector::tableize($actionName), $action); $def->addMethodCall('addAction', [$action]); } }
public function asArray() { $data = []; $class = get_class($this); $reflection = new \ReflectionClass($class); $properties = $reflection->getProperties(); foreach ($properties as $property) { $reader = new Reader($class, $property->getName(), 'property'); $isQueryParameter = $reader->getParameter('isQueryParameter'); $propertyName = Inflector::tableize($property->getName()); if ($isQueryParameter === true && $this->{$property->getName()} !== null) { $data[$propertyName] = $this->{$property->getName()}; } } return $data; }
/** * @param $jsonResources * * @return array */ public function classifyResources($jsonResources) { $classifiedResources = []; if (count($jsonResources) > 0) { $columnNames = $this->getEntityColumnNames($jsonResources[0]); $mapper = function ($jsonResource) use($columnNames) { foreach ($columnNames as $columnName) { $classifiedColumnName = Inflector::classify($columnName); $getter = 'get' . $classifiedColumnName; $properties[Inflector::tableize($columnName)] = $jsonResource->{$getter}(); } return $properties; }; $classifiedResources = array_map($mapper, $jsonResources); } return $classifiedResources; }
/** * @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'); } }
/** * @return array */ public function toArray() { $result = array(); foreach (get_class_methods($this) as $methodName) { if (substr($methodName, 0, 3) === 'get') { $value = $this->{$methodName}(); $value = $this->processEnumValue($value); $indexName = Inflector::tableize(substr($methodName, 3)); $result[$indexName] = $value; } } foreach (get_object_vars($this) as $property => $value) { $value = $this->processEnumValue($value); $result[$property] = $value; } return $result; }