/** * Convert an Array to XML * @param string $root_node - name of the root node to be converted * @param array $data - array to be converted * @throws \Exception * @return \DOMNode */ protected function convertArrayToXml($root_node, $data = array()) { if (!$this->isValidTagName($root_node)) { throw new \Exception('Array to XML Conversion - Illegal character in element name: ' . $root_node); } $node = $this->xml->createElement($root_node); if (is_scalar($data)) { $node->appendChild($this->xml->createTextNode($this->bool2str($data))); } if (is_array($data)) { foreach ($data as $key => $value) { $this->current_node_name = $root_node; $key = is_numeric($key) ? Inflector::singularize($this->current_node_name) : $key; $node->appendChild($this->convertArrayToXml($key, $value)); unset($data[$key]); } } if (is_object($data)) { // Catch toString objects, and datetime. Note Closure's will fall into here if (method_exists($data, '__toString')) { $node->appendChild($this->xml->createTextNode($data->__toString())); } elseif ($data instanceof \DateTime) { $node->appendChild($this->xml->createTextNode($data->format(\DateTime::ISO8601))); } else { throw new \Exception('Invalid data type used in Array to XML conversion. Must be object of \\DateTime or implement __toString()'); } } return $node; }
/** * 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]); } } }
public function transform($entities) { foreach ($entities as &$entity) { $entity['icon'] = $this->getIcon(Inflector::singularize($entity['name'])); } return $entities; }
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; }
/** * @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]); }
/** * 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>'); }
/** * Get a list linking an item name with the property it refers to and what kind of collection it is. * Ex: [ * "byItemName" => "user" => ["property" => "users", "behavior" => "list", "methods" => ["add", "remove"]], * "byProperty" => "users" => ["itemName" => "user", "behavior" => "list", "methods" => ["add", "remove"]] * ] * * @param array $properties The properties of the object to read. * @param \Doctrine\Common\Annotations\Reader $annotationReader The annotation reader to use. * * @return array The described list. */ public static function getCollectionsItemNames($properties, $annotationReader) { $objectCollectionsItemNames = array("byProperty" => array(), "byItemName" => array()); foreach ($properties as $propertyName => $property) { $annotation = null; $behavior = null; foreach (self::$collectionAnnotationClasses as $annotationBehavior => $annotationClass) { $annotation = $annotationReader->getPropertyAnnotation($property, $annotationClass); if ($annotation !== null) { $behavior = $annotationBehavior; break; } } if ($annotation !== null) { // get the item name, or deduce it (singularize the property name) $itemName = $annotation->getItemName(); if ($itemName === null) { $itemName = Inflector::singularize($propertyName); } $objectCollectionsItemNames["byItemName"][$itemName] = array("property" => $propertyName, "behavior" => $behavior, "methods" => $annotation->getMethods()); $objectCollectionsItemNames["byProperty"][$propertyName] = array("itemName" => $itemName, "behavior" => $behavior, "methods" => $annotation->getMethods()); } } return $objectCollectionsItemNames; }
/** * @param string $id * * @return InstanceResource */ public function get($id) { $instanceClassName = Inflector::singularize(static::class); $uri = sprintf('%s/%s', $this->uri, $id); /** @var InstanceResource $resource */ $resource = new $instanceClassName($this->transport, $uri); return $resource; }
/** * Singularifies a given value. * * @param string $value * * @return string */ protected function singularize($value) { $singularified = Inflector::singularize($value); if (is_array($singularified)) { $singularified = end($singularified); } return $singularified; }
/** * Parse a response body into a collection * * @param string $data * * @return ResultCollection */ public static function parseResultCollection($data) { $responseBody = json_decode($data, true); $rootKey = self::getRootKey($responseBody); $data = self::getResultForRootKey($responseBody, $rootKey); $className = Inflector::singularize(Inflector::classify($rootKey)); $resultCollection = new ResultCollection(); return $resultCollection->fromArrayWithObjects($data, $className); }
/** * @param string $name * * @throws InvalidArgumentException * * @return ApiInterface */ public function api($name) { $name = Inflector::singularize($name); $apis = ['author', 'billing', 'bundle', 'category', 'expertise', 'language', 'locale', 'project', 'template', 'user']; if (!in_array($name, $apis, true)) { throw new InvalidArgumentException(sprintf('Undefined api instance called: "%s"', $name)); } $class = sprintf('Textmaster\\Api\\%s', ucfirst($name)); return new $class($this); }
public function __construct(FormatterManager $formatterManager, $dataProviderName, $dataSingularName = null, ProxySourceCollection $collection = null, FilterInterface $filter, MapInterface $map, ProxySourceItemFactoryInterface $factory = null) { $this->formatterManager = $formatterManager; $this->dataProviderName = $dataProviderName; $this->dataSingularName = $dataSingularName ?: Inflector::singularize($dataProviderName); $this->collection = $collection ?: new ProxySourceCollection(); $this->filter = $filter ?: new NullFilter(); $this->map = $map ?: new NullMap(); $this->factory = $factory ?: new SimpleProxySourceItemFactory(); }
/** * @param TypeInterface $type */ public function buildType(TypeInterface $type) { $base_manager_class_name = Inflector::classify($type->getName()); $type_class_name = Inflector::classify(Inflector::singularize($type->getName())); $base_class_build_path = $this->getBuildPath() ? "{$this->getBuildPath()}/Manager/Base/{$base_manager_class_name}.php" : null; $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()) { $base_class_namespace = $this->getStructure()->getNamespace() . '\\Manager\\Base'; $type_class_name = '\\' . ltrim($this->getStructure()->getNamespace(), '\\') . '\\' . $type_class_name; } else { $base_class_namespace = 'Manager\\Base'; } $result[] = 'namespace ' . $base_class_namespace . ';'; $result[] = ''; $result[] = '/**'; $result[] = ' * @package ' . $base_class_namespace; $result[] = ' */'; $interfaces = $traits = []; foreach ($type->getTraits() as $interface => $implementations) { if ($interface != '--just-paste-trait--') { $interfaces[] = '\\' . ltrim($interface, '\\'); } if (count($implementations)) { foreach ($implementations as $implementation) { $traits[] = '\\' . ltrim($implementation, '\\'); } } } $result[] = 'abstract class ' . $base_manager_class_name . ' extends \\ActiveCollab\\DatabaseObject\\Entity\\Manager'; $result[] = '{'; $result[] = ' /**'; $result[] = ' * Return type that this manager works with.'; $result[] = ' *'; $result[] = ' * @return string'; $result[] = ' */'; $result[] = ' public function getType()'; $result[] = ' {'; $result[] = ' return ' . var_export($type_class_name, true) . ';'; $result[] = ' }'; $result[] = '}'; $result[] = ''; $result = implode("\n", $result); if ($this->getBuildPath()) { file_put_contents($base_class_build_path, $result); } else { eval(ltrim($result, '<?php')); } $this->triggerEvent('on_class_built', [$base_manager_class_name, $base_class_build_path]); }
/** * Singularize the $plural word if count == 1. If $singular is passed, it * will be used instead of trying to use doctrine\inflector * * @param string $plural - chicken * @param int $count - e.g. 4 * @param string $singular - (optional) chickens * @return string */ public static function singularize($plural, $count = 1, $singular = null) { $count = intval($count); if ($count != 1) { return $plural; } if (null == $singular) { $singular = \Doctrine\Common\Inflector\Inflector::singularize($plural); } return $singular; }
/** * @param Request $request * @param $id * @param $embed * * @return ResourceInterface */ public function initFilterEmbed(Request $request, $id, $embed) { $embedShortname = ucwords(Inflector::singularize($embed)); /** @var $resourceEmbed ResourceInterface */ $resourceEmbed = $this->resourceResolver->getResourceForShortName($embedShortname, $this->router->getContext()->getApiVersion()); $filter = new EmbedFilter($this->managerRegistry, $this->propertyAccessor); $params = !$request->request->has('embedParams') ? ['embed' => $embed, 'id' => $id] : $request->request->get('embedParams'); $filter->setParameters($params); $filter->setRouteName($request->get('_route')); $resourceEmbed->addFilter($filter); return $resourceEmbed; }
/** * Method to get a model object, loading it if required. * * @param string $name The model name. Optional. * @param string $prefix The class prefix. Optional. * @param array $config Configuration array for model. Optional. * * @return object The model. */ public function getModel($name = '', $prefix = '', $config = array('ignore_request' => true)) { $class = get_class($this); if (empty($name)) { $name = strstr($class, 'Controller'); $name = str_replace('Controller', '', $name); $name = \Doctrine\Common\Inflector\Inflector::singularize($name); } if (empty($prefix)) { $prefix = strstr($class, 'Controller', true) . 'Model'; } return parent::getModel($name, $prefix, $config); }
public function hydrate($datasToHydrate) { foreach ($datasToHydrate as $keyToHydrate => $valueToHydrate) { if (is_array($valueToHydrate)) { foreach ($valueToHydrate as $subValue) { $class = "\\Litmus\\Sdk\\Model\\" . Inflector::singularize($keyToHydrate); $subObject = new $class(); $subObject->hydrate($subValue); $this->{"get" . $keyToHydrate}()->add($subObject); } } else { $this->{"set" . $keyToHydrate}($valueToHydrate); } } }
/** * Get relation query * * @return \Blast\Orm\Query */ public function getQuery() { if (null !== $this->query) { return $this->query; } $provider = $this->createProvider($this->getEntity()); $foreignProvider = $this->createProvider($this->getForeignEntity()); $localKey = $this->getLocalKey(); if ($localKey === null) { $localKey = Inflector::singularize($foreignProvider->getDefinition()->getTableName()) . '_' . $foreignProvider->getDefinition()->getPrimaryKeyName(); } $data = $provider->extract(); //find primary key $primaryKey = $data[$localKey]; $mapper = $foreignProvider->getDefinition()->getMapper()->setConnection($this->getConnection()); //if no primary key is available, return a select $this->query = $primaryKey === null ? $mapper->select() : $mapper->find($primaryKey); return $this->query; }
/** * Get a list linking a property with association between the property's class and the current class. * Ex: ["products" => ["property" => "cart", "association" => "inverted"]] * * @param array $properties The properties of the object to read. * @param \Doctrine\Common\Annotations\Reader $annotationReader The annotation reader to use. * * @return array The described list. */ public static function getAssociations($properties, $annotationReader) { $objectAssociations = array(); foreach ($properties as $propertyName => $property) { $annotation = null; $associationType = null; foreach (self::$associationAnnotationClasses as $annotationAssociationType => $annotationClass) { $annotation = $annotationReader->getPropertyAnnotation($property, $annotationClass); if ($annotation !== null) { $associationType = $annotationAssociationType; break; } } if ($annotation !== null) { // get the item name $associatedPropertyName = $annotation->getAssociatedProperty(); $objectAssociations[$propertyName] = array("property" => $associatedPropertyName, "association" => $associationType); // if this is a mapped association, get the item name of the current class if ($associationType === "mapped") { $associatedClass = new \ReflectionClass($annotation->getClassName()); $associatedPropertyReflection = $associatedClass->getProperty($associatedPropertyName); $itemName = null; foreach (self::$collectionAnnotationClasses as $annotationBehavior => $annotationClass) { $collectionAnnotation = $annotationReader->getPropertyAnnotation($associatedPropertyReflection, $annotationClass); if ($collectionAnnotation !== null) { $itemName = $collectionAnnotation->getItemName(); break; } } if ($itemName === null) { $itemName = Inflector::singularize($associatedPropertyName); } $objectAssociations[$propertyName]["itemName"] = $itemName; } } else { $objectAssociations[$propertyName] = null; } } return $objectAssociations; }
/** * Returns the required data for model. * * @return void */ public function concat(array &$data) { $config = Configuration::get(); $columns = $this->describe->getTable($data['name']); $data['repository'] = (object) ['compacts' => (object) ['create' => [], 'edit' => ''], 'dropdowns' => '', 'name' => 'repository']; $data['parameters'] = ''; foreach ($columns as $column) { if (strpos($column->getDataType(), 'blob') !== false) { $data['parameters'] = "\n\n " . '$files = request()->getUploadedFiles();'; } } foreach ($columns as $column) { if ($column->isForeignKey()) { $referencedTable = $this->stripTableSchema($column->getReferencedTable()); $keywords = ['{application}' => $config->application->name, '{namespace}' => $config->namespaces->repositories, '{plural}' => Inflector::pluralize($referencedTable), '{singularTitle}' => ucfirst(Inflector::singularize($referencedTable)), '{singular}' => lcfirst(Inflector::classify(Inflector::singularize($referencedTable)))]; $data['repository']->name = lcfirst(Inflector::classify($data['singular'])) . 'Repository'; $compact = ', \'{plural}\''; $dropdown = '${plural} = repository(\'{application}\\{namespace}\\{singularTitle}Repository\')->findAll();' . "\n "; $compact = str_replace(array_keys($keywords), array_values($keywords), $compact); $dropdown = str_replace(array_keys($keywords), array_values($keywords), $dropdown); $data['repository']->compacts->edit .= $compact; $data['repository']->dropdowns .= $dropdown; array_push($data['repository']->compacts->create, "'" . $keywords['{plural}'] . "'"); } if (strpos($column->getDataType(), 'blob') !== false) { $data['parameters'] .= "\n " . '$parameters[\'' . $column->getField() . '\'] = $files[\'' . $column->getField() . '\'];'; } } if (!empty($data['repository']->compacts->create)) { $data['repository']->compacts->create = ', compact(' . implode(', ', $data['repository']->compacts->create) . ')'; } else { $data['repository']->compacts->create = ''; } if (!empty($data['repository']->dropdowns)) { $data['repository']->dropdowns = substr($data['repository']->dropdowns, 0, count($data['repository']->dropdowns) - 9); $data['repository']->dropdowns .= "\n "; } }
/** * Get relation query * * @return \Blast\Orm\Query */ public function getQuery() { if (null !== $this->query) { return $this->query; } $provider = $this->createProvider($this->getEntity()); $foreignProvider = $this->createProvider($this->getForeignEntity()); $foreignKey = $this->getForeignKey(); $data = $provider->extract(); //find primary key if ($foreignKey === null) { $foreignKey = Inflector::singularize($provider->getDefinition()->getTableName()) . '_' . $provider->getDefinition()->getPrimaryKeyName(); } $mapper = $foreignProvider->getDefinition()->getMapper()->setConnection($this->getConnection()); $foreignKeyValue = isset($data[$provider->getDefinition()->getPrimaryKeyName()]) ? $data[$provider->getDefinition()->getPrimaryKeyName()] : false; //if no primary key is available, return a select $query = $mapper->select(); if ($foreignKeyValue !== false) { $query->where((new Query($this->getConnection()))->expr()->eq($foreignKey, $foreignKeyValue)); } $this->query = $query; return $this->query; }
/** * 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(); $data = ['application' => $config->application, 'author' => $config->author, 'model' => $input->getOption('model'), 'namespaces' => $config->namespaces, 'password' => $input->getOption('password'), 'plural' => lcfirst(Inflector::classify(Inflector::pluralize($input->getOption('model')))), 'singular' => lcfirst(Inflector::classify(Inflector::singularize($input->getOption('model')))), 'username' => $input->getOption('username')]; $controller = $this->renderer->render('Authentication/AuthenticationController.php', $data); $middleware = $this->renderer->render('Authentication/AuthenticateMiddleware.php', $data); $middlewares = $this->generateFile($config, 'middleware'); $routes = $this->generateFile($config, 'route'); $controllerFile = $config->folders->controllers . '/AuthenticationController.php'; $middlewareFile = $config->folders->middlewares . '/AuthenticateMiddleware.php'; if ($this->filesystem->has($controllerFile)) { if ($input->getOption('overwrite')) { $this->filesystem->delete($controllerFile); } else { $text = 'AuthenticationController.php already exists.'; return $output->writeln('<error>' . $text . '</error>'); } } if ($this->filesystem->has($middlewareFile)) { if ($input->getOption('overwrite')) { $this->filesystem->delete($middlewareFile); } else { $text = 'AuthenticateMiddleware.php already exists.'; return $output->writeln('<error>' . $text . '</error>'); } } $this->filesystem->write($controllerFile, $controller); $this->filesystem->write($middlewareFile, $middleware); if ($this->filesystem->has($config->files->routes)) { $this->filesystem->update($config->files->routes, $routes); } if ($this->filesystem->has($config->files->middlewares)) { $this->filesystem->update($config->files->middlewares, $middlewares); } $text = 'Basic authentication created successfully.'; return $output->writeln('<info>' . $text . '</info>'); }
public function generateFunctionName(Operation $operation) { $prefix = strtolower($operation->getMethod()); $shouldSingularize = true; $responses = $operation->getOperation()->getResponses(); if ($responses instanceof \ArrayObject && isset($responses[200])) { $response = $responses[200]; if ($response instanceof Response && $response->getSchema() instanceof Schema && $response->getSchema()->getType() === 'array') { $shouldSingularize = false; } } preg_match_all('/(?P<separator>[^a-zA-Z0-9_{}])+(?P<part>[a-zA-Z0-9_{}]*)/', $operation->getPath(), $matches); $methodNameParts = []; $lastNonParameterPartIndex = 0; foreach ($matches[0] as $index => $match) { if ($matches['separator'][$index] === '.') { continue; } $part = $matches['part'][$index]; if (preg_match_all('/{(?P<parameter>[^{}]+)}/', $part, $parameterMatches)) { foreach ($parameterMatches[0] as $parameterIndex => $parameterMatch) { $withoutSnakes = preg_replace_callback('/(^|_|\\.)+(.)/', function ($match) { return ('.' === $match[1] ? '_' : '') . strtoupper($match[2]); }, $parameterMatches['parameter'][$parameterIndex]); $methodNameParts[] = 'By' . ucfirst($withoutSnakes); } } else { $methodNameParts[] = ucfirst($part); $lastNonParameterPartIndex = count($methodNameParts) - 1; } } if ($shouldSingularize && count($methodNameParts) > 0) { $methodNameParts[$lastNonParameterPartIndex] = Inflector::singularize($methodNameParts[$lastNonParameterPartIndex]); } return $prefix . ucfirst(implode('', $methodNameParts)); }
/** * @param string $resourceClassName Fully classified class name * * @return string */ protected function getChildResourceName($resourceClassName = null) { $resourceName = $this->getResourceName($resourceClassName); $singular = Inflector::singularize($resourceName); return $singular; }
public function exportJson() { $metadata = $this->cmf->getAllMetadata(); $metadata = MetadataFilter::filter($metadata, $this->filter); if ($metadata) { $filename = $this->path . '/' . $this->extensionKey . '/' . self::PROJECT_FILE_NAME; if (!is_dir($dir = dirname($filename))) { mkdir($dir, 0777, true); } $configuration = new ExtensionBuilderConfiguration(); if (is_readable($filename)) { if ($this->overwriteExistingFiles && $this->roundTripExistingFiles) { $this->logs[] = sprintf('File "<info>%s</info>" already exists, you selected both override (force) and round-trip - please choose one.', $filename); return 1; } if (!$this->overwriteExistingFiles && !$this->roundTripExistingFiles) { $this->logs[] = sprintf('File "<info>%s</info>" already exists, use --force to override or --round-trip it.', $filename); return 1; } if ($this->roundTripExistingFiles) { $roundtripContents = json_decode(file_get_contents($filename), true); $configuration->setProperties($this->mapArrayToClass($roundtripContents['properties'], new Properties())); $configuration->setLog($this->mapArrayToClass($roundtripContents['log'], new Log())); } } $configuration->getProperties()->setExtensionKey($this->extensionKey); $configuration->getLog()->setLastModified(date('Y-m-d H:i')); //in this array we store the target entites for all relations to create wires later on $relationTargetsByModuleByRelation = array(); $moduleIndex = 0; $posX = 50; $posY = 50; foreach ($metadata as $metadata) { if ($moduleIndex) { if (0 == $moduleIndex % 5) { $posX = 50; $posY += 200; } else { $posX += 300; } } $className = $metadata->name; //remove namespaces, e.g. when importing entities if (class_exists($className)) { $reflection = new \ReflectionClass($className); $className = $reflection->getShortName(); } $this->logs[] = sprintf('Processing table "<info>%s</info>"', $className); $module = new Module(); $module->getValue()->setName($className); $module->getConfig()->setPosition(array($posX, $posY)); $module->getValue()->getObjectsettings()->setUid($this->getRandomUid()); $module->getValue()->getObjectsettings()->setType(ObjectSettings::OBJECT_TYPE_ENTITY); //export properties foreach ($metadata->fieldMappings as $fieldMapping) { $property = new Property(); $property->setPropertyName($fieldMapping['fieldName']); $property->setPropertyType($this->getPropertyType($fieldMapping['type'])); $property->setUid($this->getRandomUid()); $module->getValue()->getPropertyGroup()->addProperty($property); } //export relations $relationIndex = 0; foreach ($metadata->associationMappings as $associationMapping) { $relationNameSingular = $associationMapping['fieldName']; $relationNamePlural = Inflector::pluralize(Inflector::singularize($associationMapping['fieldName'])); $relation = new Relation(); $relationType = null; $relationName = ''; switch ($associationMapping['type']) { case ClassMetadataInfo::ONE_TO_MANY: $relationType = Relation::ONE_TO_MANY; $relationName = $relationNamePlural; break; case ClassMetadataInfo::MANY_TO_ONE: $relationType = Relation::MANY_TO_ONE; $relationName = $relationNameSingular; break; case ClassMetadataInfo::ONE_TO_ONE: $relationType = Relation::ONE_TO_ONE; $relationName = $relationNameSingular; break; case ClassMetadataInfo::MANY_TO_MANY: $relationType = Relation::MANY_TO_MANY; $relationName = $relationNamePlural; break; } $relation->setRelationName($relationName); $relation->setRelationType($relationType); $relationName = $relationNameSingular; $module->getValue()->getRelationGroup()->addRelation($relation); $targetClassName = $associationMapping['targetEntity']; //remove namespaces, e.g. when importing entities if (class_exists($targetClassName)) { $reflection = new \ReflectionClass($targetClassName); $targetClassName = $reflection->getShortName(); } $relationTargetsByModuleByRelation[$moduleIndex][$relationIndex] = $targetClassName; $relationIndex++; $this->logs[] = sprintf('Added relation "<comment>%s</comment>": "<info>%s</info>" -> "<info>%s</info>"', $relationName, $className, $targetClassName); } $configuration->addModule($module); $moduleIndex++; } // now we have all the modules, we can create wires $moduleIndex = 0; foreach ($configuration->getModules() as $key => $module) { $relationIndex = 0; if (!empty($module->getValue()->getRelationGroup()->getRelations())) { foreach ($module->getValue()->getRelationGroup()->getRelations() as $relation) { /* @var $relation Relation */ // now add the corresponding wire for the relation $wire = new Wire(); $targetEntity = $relationTargetsByModuleByRelation[$moduleIndex][$relationIndex]; $targetModule = $configuration->getModuleByName($targetEntity); if ($targetModule) { $targetModuleId = array_search($targetModule, $configuration->getModules()); $src = new Node(); $src->setModuleId($key); $src->setTerminal(Node::TERMINAL_SRC . $relationIndex); $src->setUid($relation->getUid()); $tgt = new Node(); $tgt->setModuleId($targetModuleId); $tgt->setTerminal(Node::TERMINAL_TGT); $tgt->setUid($targetModule->getValue()->getObjectsettings()->getUid()); $wire->setSrc($src); $wire->setTgt($tgt); $configuration->addWire($wire); $this->logs[] = sprintf('Added wire "<comment>%s</comment>": "<info>%s</info>" -> "<info>%s</info>"', $relation->getRelationName(), $module->getValue()->getName(), $targetEntity); } $relationIndex++; } } $moduleIndex++; } file_put_contents($filename, json_encode($configuration, JSON_PRETTY_PRINT)); $this->logs[] = 'Exported database schema to ' . $filename; return true; } else { $this->logs[] = 'Database does not have any mapping information.'; return false; } }
/** * Add a new instance to the related FieldDescriptionInterface value. * * @param object $object * @param \Sonata\AdminBundle\Admin\FieldDescriptionInterface $fieldDescription * * @throws \RuntimeException */ public function addNewInstance($object, FieldDescriptionInterface $fieldDescription) { $instance = $fieldDescription->getAssociationAdmin()->getNewInstance(); $mapping = $fieldDescription->getAssociationMapping(); $method = sprintf('add%s', $this->camelize($mapping['fieldName'])); if (!method_exists($object, $method)) { $method = rtrim($method, 's'); if (!method_exists($object, $method)) { $method = sprintf('add%s', $this->camelize(Inflector::singularize($mapping['fieldName']))); if (!method_exists($object, $method)) { throw new \RuntimeException(sprintf('Please add a method %s in the %s class!', $method, ClassUtils::getClass($object))); } } } $object->{$method}($instance); }
/** * Get the text name that represents a single element. eg: user * @return string $element_name */ public function getElementName() { // attempt to pull an entity name from the class $classNameParts = explode('\\', $this->className); if (is_array($classNameParts)) { return strtolower(Inflector::singularize(array_pop($classNameParts))); } return $this->className; }
/** * Test resetting inflection rules. * * @return void */ public function testCustomRuleWithReset() { Inflector::reset(); $uninflected = array('atlas', 'lapis', 'onibus', 'pires', 'virus', '.*x'); $pluralIrregular = array('as' => 'ases'); Inflector::rules('singular', array('rules' => array('/^(.*)(a|e|o|u)is$/i' => '\\1\\2l'), 'uninflected' => $uninflected), true); Inflector::rules('plural', array('rules' => array('/^(.*)(a|e|o|u)l$/i' => '\\1\\2is'), 'uninflected' => $uninflected, 'irregular' => $pluralIrregular), true); $this->assertEquals(Inflector::pluralize('Alcool'), 'Alcoois'); $this->assertEquals(Inflector::pluralize('Atlas'), 'Atlas'); $this->assertEquals(Inflector::singularize('Alcoois'), 'Alcool'); $this->assertEquals(Inflector::singularize('Atlas'), 'Atlas'); }
private function generateDocumentStubMethod(ClassMetadataInfo $metadata, $type, $fieldName, $typeHint = null, $defaultValue = null) { // Add/remove methods should use the singular form of the field name $formattedFieldName = in_array($type, array('add', 'remove')) ? Inflector::singularize($fieldName) : $fieldName; $methodName = $type . Inflector::classify($formattedFieldName); $variableName = Inflector::camelize($formattedFieldName); if ($this->hasMethod($methodName, $metadata)) { return; } $description = ucfirst($type) . ' ' . $variableName; $types = Type::getTypesMap(); $methodTypeHint = $typeHint && !isset($types[$typeHint]) ? '\\' . $typeHint . ' ' : null; $variableType = $typeHint ? $typeHint . ' ' : null; $replacements = array('<description>' => $description, '<methodTypeHint>' => $methodTypeHint, '<variableType>' => $variableType, '<variableName>' => $variableName, '<methodName>' => $methodName, '<fieldName>' => $fieldName, '<variableDefault>' => $defaultValue !== null ? ' = ' . $defaultValue : ''); $templateVar = sprintf('%sMethodTemplate', $type); $method = str_replace(array_keys($replacements), array_values($replacements), self::${$templateVar}); return $this->prefixCodeWithSpaces($method); }