/** * 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(); }
/** * {@inheritdoc} */ public function resolve(Route $route, RouteCollectionAccessor $routes) { if (!in_array('OPTIONS', $route->getMethods(), true)) { return; } $entryPath = $this->getEntryPath($route); if (!$entryPath) { return; } $nameFromController = $this->getNameFromController($route); if (!$nameFromController) { return; } $nameFromPath = str_replace('/', '', $entryPath); if ($nameFromPath === $nameFromController) { return; } if (false !== ($pos = strrpos($entryPath, '/'))) { $pluralName = substr($entryPath, $pos + 1); $singleName = substr($nameFromController, $pos - substr_count($entryPath, '/') + 1); } else { $pluralName = $entryPath; $singleName = $nameFromController; } if ($pluralName === $singleName || $pluralName !== Inflector::pluralize($singleName)) { return; } $singlePath = str_replace('/' . $pluralName, '/' . $singleName, $route->getPath()); $singleRoute = $routes->cloneRoute($route); $singleRoute->setPath($singlePath); $singleRoute->setOption('old_options', true); $pluralRouteName = $routes->getName($route); $routes->insert($routes->generateRouteName($pluralRouteName), $singleRoute, $pluralRouteName); }
/** * 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; }
/** * @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)); } } } } } } }
/** * 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>'); }
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; } } }
/** * 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); }
/** * 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 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)); } } } } }
/** * Get the plural form of an English word. * * @param string $value * @param int $count * @return string */ public static function plural($value, $count = 2) { if ((int) $count === 1 || static::uncountable($value)) { return $value; } $plural = Inflector::pluralize($value); return static::matchCase($plural, $value); }
/** * Resolves a table's name, following the plural naming scheme. * * @param $class string|object An instance of p810\Model\Model or a string. * @return string */ public static function getTableName($class) { if (is_object($class)) { $reflection = new \ReflectionClass($class); $class = $reflection->getShortName(); } return lcfirst(Inflector::pluralize($class)); }
private function getDefaultConfiguration() { $item = ucwords(str_replace('-', ' ', $this->getTaxonomyName())); $plural = Inflector::pluralize($item); $labels = ['name' => sprintf('%s', $plural), 'singular_name' => sprintf('%s', $item), 'menu_name' => __(sprintf('%s', $item)), 'all_items' => __(sprintf('All %s', $plural)), 'parent_item' => __(sprintf('Parent %s', $item)), 'parent_item_colon' => __(sprintf('Parent %s:', $item)), 'new_item_name' => __(sprintf('New %s', $item)), 'add_new_item' => __(sprintf('Add %s', $item)), 'edit_item' => __(sprintf('Edit %s', $item)), 'update_item' => __(sprintf('Update %s', $item)), 'view_item' => __(sprintf('View %s', $item)), 'separate_items_with_commas' => __(sprintf('Separate %s with commas', strtolower($plural))), 'add_or_remove_items' => __(sprintf('Add or remove %s', strtolower($plural))), 'choose_from_most_used' => __('Choose from the most used'), 'popular_items' => __(sprintf('Popular %s', $plural)), 'search_items' => __(sprintf('Search %s', $plural)), 'not_found' => __('Not Found')]; $args = ['labels' => $labels, 'hierarchical' => true, 'public' => true, 'show_ui' => true, 'show_admin_column' => true, 'show_in_nav_menus' => true, 'show_tagcloud' => false]; return $args; }
protected function getSkeleton($name) { $skeleton = new Skeleton($this->getSkeletonPath('entity')); $name = S::upperCamelize($name); $skeleton->entity_name = $name; $skeleton->table = Inflector::pluralize(S::replace(S::dasherize($name), '-', '_')); return $skeleton; }
public function getCollectionRoute($class) { $route = 'get_' . Inflector::pluralize($this->getRouteResourceName($class)); if ($this->router->getRouteCollection()->get($route) === null) { throw new \InvalidArgumentException('That entity does not have a corresponding collection route'); } return $route; }
/** * Constructor. * * @param array $config An optional associative array of configuration settings. * Recognized key values include 'name', 'default_task', 'model_path', and * 'view_path' (this list is not meant to be comprehensive). */ public function __construct($config = array()) { parent::__construct($config); // Set the view list as Joomla pluralize is buggy $this->view_list = \Doctrine\Common\Inflector\Inflector::pluralize($this->view_item); if (!property_exists($this, 'input') || empty($this->input)) { $this->input = JFactory::getApplication()->input; } }
/** * {@inheritdoc} */ public function resolveOperationPath(string $resourceShortName, array $operation, bool $collection) : string { $path = '/' . Inflector::pluralize(strtolower(preg_replace('~(?<=\\w)([A-Z])~', '-$1', $resourceShortName))); if (!$collection) { $path .= '/{id}'; } $path .= '.{_format}'; return $path; }
/** * @param string $className * @param bool $plural * @return string Partial method name to get / set object(s) */ public function methodNameFromClass($className, $plural = false) { $method = substr($className, strrpos($className, '\\') + 1); if ($plural) { return DoctrineInflector::pluralize($method); } else { return $method; } }
/** * Pluralize a word, obeying any stored exceptions. * * @param string $word the word to pluralize */ public static function pluralize($word) { foreach (self::$_exceptions as $exception) { if ($exception['singular'] == $word) { return $exception['plural']; } } return \Doctrine\Common\Inflector\Inflector::pluralize($word); }
/** * {@inheritdoc} */ public function classToTableName($className, $includePrefix = true) { $table_name = parent::classToTableName($className); $parts = explode('_', $table_name); $last = array_pop($parts); $last = Inflector::pluralize($last); $parts[] = $last; return implode('_', $parts); }
/** * {@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; }
public function write(WriterInterface $writer) { if ($this->referencedTable == null) { $writer->write('# There is another foreign key declaration.'); } else { $writer->write('%s:', 0 === strpos($this->parameters->get('name'), 'd:') ? substr($this->parameters->get('name'), 2) : $this->referencedTable->getModelName())->indent()->write('class: ' . $this->referencedTable->getModelName())->write('local: ' . $this->foreign->getColumnName())->write('foreign: ' . $this->local->getColumnName())->write('foreignAlias: ' . (($alias = $this->getForeignAlias()) ? $alias : ($this->isManyToOne() ? Inflector::pluralize($this->referencedTable->getModelName()) : $this->referencedTable->getModelName())))->write('onDelete: ' . strtolower($this->parameters->get('deleteRule')))->write('onUpdate: ' . strtolower($this->parameters->get('updateRule')))->outdent(); } return $this; }
public function pluralize($word, $num = 0) { $num = (int) $num; if ($num == 1) { return $word; } else { return \Doctrine\Common\Inflector\Inflector::pluralize($word); } }
/** * 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'; }
/** * @param ViewEvent $event */ public function onView(ViewEvent $event) { if ($this->getParameterResolver()->resolveApi()) { return; } $view = $event->getView(); if ($view->getData() instanceof Pagerfanta) { $view->setTemplateVar(Inflector::pluralize($event->getResource()->getName())); } }
/** * Pluralize the $singular word if count !== 1. If $plural is passed, it * will be used instead of trying to use doctrine\inflector * * @param string $singular - chicken * @param int $count - e.g. 4 * @param string $plural - (optional) chickens * @return string */ public static function pluralize($singular, $count = 2, $plural = null) { $count = intval($count); if ($count == 1) { return $singular; } if (null == $plural) { $plural = \Doctrine\Common\Inflector\Inflector::pluralize($singular); } return $plural; }
/** * Make sure that a number is accompanied with the appropriate grammatical * number * * @param number $number * @param string $singular The noun in its singular form */ public function __invoke($singular, $number = null) { if ($number == 1) { return "1 {$singular}"; } $plural = Inflector::pluralize($singular); if ($number === null) { return $plural; } return "{$number} {$plural}"; }
/** * 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; }
/** * $name is in singular. If $target_type_name is empty, it will be set to pluralized value of association name:. * * new BelongsToAssociation('author') * * will result in $target_type_name pointing at 'authors' type * * @param string $name * @param null $target_type_name */ public function __construct($name, $target_type_name = null) { if (empty($name)) { throw new InvalidArgumentException("Value '{$name}' is not a valid association name"); } if (empty($target_type_name)) { $target_type_name = Inflector::pluralize($name); } $this->name = $name; $this->target_type_name = $target_type_name; }
/** * Relation constructor. * @param Model $source * @param $attribute */ public function __construct(Model $source, $attribute) { list($this->model, $this->type) = $source->getRelations()[$attribute]; if ($this->isRel()) { $this->classPath = 'Afosto\\ApiClient\\Models\\' . Inflector::pluralize($this->_getModelForRel()) . '\\' . $this->model; } else { if ($this->isReference()) { $this->classPath = 'Afosto\\ApiClient\\Models\\' . Inflector::pluralize($this->_getModelForReference()) . '\\' . $this->_getModelForReference(); } else { $this->classPath = $source->getNameSpace() . '\\' . $this->model; } } }