/** * Generate Fixture from bundle name, entity name, fixture name and ids * * @param BundleInterface $bundle * @param string $entity * @param string $name * @param array $ids * @param string|null $connectionName */ public function generate(BundleInterface $bundle, $entity, $name, array $ids, $order, $connectionName = null) { // configure the bundle (needed if the bundle does not contain any Entities yet) $config = $this->registry->getManager($connectionName)->getConfiguration(); $config->setEntityNamespaces(array_merge(array($bundle->getName() => $bundle->getNamespace() . '\\Entity'), $config->getEntityNamespaces())); $fixtureFileName = $this->getFixtureFileName($entity, $name, $ids); $entityClass = $this->registry->getAliasNamespace($bundle->getName()) . '\\' . $entity; $fixturePath = $bundle->getPath() . '/DataFixtures/ORM/' . $fixtureFileName . '.php'; $bundleNameSpace = $bundle->getNamespace(); if (file_exists($fixturePath)) { throw new \RuntimeException(sprintf('Fixture "%s" already exists.', $fixtureFileName)); } $class = new ClassMetadataInfo($entityClass); $fixtureGenerator = $this->getFixtureGenerator(); $fixtureGenerator->setFixtureName($fixtureFileName); $fixtureGenerator->setBundleNameSpace($bundleNameSpace); $fixtureGenerator->setMetadata($class); $fixtureGenerator->setFixtureOrder($order); /** @var EntityManager $em */ $em = $this->registry->getManager($connectionName); $repo = $em->getRepository($class->rootEntityName); if (empty($ids)) { $items = $repo->findAll(); } else { $items = $repo->findById($ids); } $fixtureGenerator->setItems($items); $fixtureCode = $fixtureGenerator->generateFixtureClass($class); $this->filesystem->mkdir(dirname($fixturePath)); file_put_contents($fixturePath, $fixtureCode); }
public function generateRestRouting(BundleInterface $bundle, $controller) { $file = $bundle->getPath() . '/Resources/config/routing.rest.yml'; if (file_exists($file)) { $content = file_get_contents($file); } elseif (!is_dir($dir = $bundle->getPath() . '/Resources/config')) { mkdir($dir); } $resource = $bundle->getNamespace() . "\\Controller\\" . $controller . 'Controller'; $name = strtolower(preg_replace('/([A-Z])/', '_\\1', $bundle->getName() . $controller . '_rest')); $name_prefix = strtolower(preg_replace('/([A-Z])/', '_\\1', $bundle->getName() . '_api_')); if (!isset($content)) { $content = ''; } else { $yml = new Yaml(); $route = $yml->parse($content); if (isset($route[$name])) { return false; } } $content .= sprintf("\n%s:\n type: rest\n resource: %s\n name_prefix: %s\n", $name, $resource, $name_prefix); $flink = fopen($file, 'w'); if ($flink) { $write = fwrite($flink, $content); if ($write) { fclose($flink); } else { throw new \RunTimeException(sprintf('We cannot write into file "%s", has that file the correct access level?', $file)); } } else { throw new \RunTimeException(sprintf('Problems with generating file "%s", did you gave write access to that directory?', $file)); } }
/** * @param BundleInterface $bundle The bundle * @param string $entity The entity name * @param string $format The format * @param array $fields The fields * @param boolean $withRepository With repository * @param string $prefix A prefix * * @throws \RuntimeException */ public function generate(BundleInterface $bundle, $entity, $format, array $fields, $withRepository, $prefix) { // configure the bundle (needed if the bundle does not contain any Entities yet) $config = $this->registry->getManager(null)->getConfiguration(); $config->setEntityNamespaces(array_merge(array($bundle->getName() => $bundle->getNamespace() . '\\Entity'), $config->getEntityNamespaces())); $entityClass = $this->registry->getAliasNamespace($bundle->getName()) . '\\' . $entity; $entityPath = $bundle->getPath() . '/Entity/' . str_replace('\\', '/', $entity) . '.php'; if (file_exists($entityPath)) { throw new \RuntimeException(sprintf('Entity "%s" already exists.', $entityClass)); } $class = new ClassMetadataInfo($entityClass); if ($withRepository) { $entityClass = preg_replace('/\\\\Entity\\\\/', '\\Repository\\', $entityClass, 1); $class->customRepositoryClassName = $entityClass . 'Repository'; } foreach ($fields as $field) { $class->mapField($field); } $class->setPrimaryTable(array('name' => $prefix . $this->getTableNameFromEntityName($entity))); $entityGenerator = $this->getEntityGenerator(); $entityCode = $entityGenerator->generateEntityClass($class); $mappingPath = $mappingCode = false; $this->filesystem->mkdir(dirname($entityPath)); file_put_contents($entityPath, $entityCode); if ($mappingPath) { $this->filesystem->mkdir(dirname($mappingPath)); file_put_contents($mappingPath, $mappingCode); } if ($withRepository) { $path = $bundle->getPath() . str_repeat('/..', substr_count(get_class($bundle), '\\')); $this->getRepositoryGenerator()->writeEntityRepositoryClass($class->customRepositoryClassName, $path); } $this->addGeneratedEntityClassLoader($entityClass, $entityPath); }
/** * @param \Symfony\Component\HttpKernel\Bundle\BundleInterface $bundle * @param string $document * @param array $fields * @param Boolean $withRepository * @throws \RuntimeException */ public function generate(BundleInterface $bundle, $document, array $fields, $withRepository) { $config = $this->documentManager->getConfiguration(); $config->addDocumentNamespace($bundle->getName(), $bundle->getNamespace() . '\\Document'); $documentClass = $config->getDocumentNamespace($bundle->getName()) . '\\' . $document; $documentPath = $bundle->getPath() . '/Document/' . str_replace('\\', '/', $document) . '.php'; if (file_exists($documentPath)) { throw new \RuntimeException(sprintf('Document "%s" already exists.', $documentClass)); } $class = new ClassMetadataInfo($documentClass); if ($withRepository) { $class->setCustomRepositoryClass($documentClass . 'Repository'); } $class->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true)); $class->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); foreach ($fields as $field) { $class->mapField($field); } $documentGenerator = $this->getDocumentGenerator(); $documentCode = $documentGenerator->generateDocumentClass($class); $this->filesystem->mkdir(dirname($documentPath)); file_put_contents($documentPath, rtrim($documentCode) . PHP_EOL, LOCK_EX); if ($withRepository) { $path = $bundle->getPath() . str_repeat('/..', substr_count(get_class($bundle), '\\')); $this->getRepositoryGenerator()->writeDocumentRepositoryClass($class->customRepositoryClassName, $path); } }
/** * Gets the prefix of the asset with the given bundle * * @param BundleInterface $bundle Bundle to fetch in * * @throws \InvalidArgumentException * @return string Prefix */ public function getPrefix(BundleInterface $bundle) { if (!is_dir($bundle->getPath() . '/Resources/public')) { throw new \InvalidArgumentException(sprintf('Bundle %s does not have Resources/public folder', $bundle->getName())); } return sprintf('/bundles/%s', preg_replace('/bundle$/', '', strtolower($bundle->getName()))); }
public function generate(BundleInterface $bundle, $controller, $routeFormat, $templateFormat, array $actions = array()) { $dir = $bundle->getPath(); $controllerFile = $dir . '/Controller/' . $controller . 'Controller.php'; if (file_exists($controllerFile)) { throw new \RuntimeException(sprintf('Controller "%s" already exists', $controller)); } // seeRoute $bundleShortName = substr($bundle->getName(), strlen('Webobs'), strlen($bundle->getName()) - (strlen('Bundle') + strlen('Webobs'))); $seeRoute = 'webobs_' . strtolower($bundleShortName) . '_' . strtolower($controller) . '_see'; $parameters = array('namespace' => $bundle->getNamespace(), 'bundle' => $bundle->getName(), 'format' => array('routing' => $routeFormat, 'templating' => $templateFormat), 'entity' => $controller, 'seeRoute' => $seeRoute); foreach ($actions as $i => $action) { // get the actioname without the sufix Action (for the template logical name) $actions[$i]['basename'] = $action['name']; $params = $parameters; $params['action'] = $actions[$i]; // create a template $template = $actions[$i]['template']; if ('default' == $template) { $template = $bundle->getName() . ':' . $controller . ':' . $action['name'] . '.html.' . $templateFormat; } $this->generateRouting($bundle, $controller, $actions[$i], $routeFormat); } $parameters['actions'] = $actions; $this->renderFile('controller/Controller.php.twig', $controllerFile, $parameters); $this->renderFile('controller/ControllerTest.php.twig', $dir . '/Tests/Controller/' . $controller . 'ControllerTest.php', $parameters); }
/** * Gets the metadata of all classes of a bundle. * * @param BundleInterface $bundle A BundleInterface instance * * @return ClassMetadataCollection A ClassMetadataCollection instance */ public function getBundleMetadata(BundleInterface $bundle) { $namespace = $bundle->getNamespace(); if (!($metadata = $this->getMetadataForNamespace($namespace))) { throw new \RuntimeException(sprintf('Bundle "%s" does not contain any mapped entities.', $bundle->getName())); } $path = $this->getBasePathForClass($bundle->getName(), $bundle->getNamespace(), $bundle->getPath()); $metadata->setPath($path); $metadata->setNamespace($bundle->getNamespace()); return $metadata; }
/** * Generate the pagepart entity. * * @throws \RuntimeException */ private function generatePagePartEntity() { list($entityCode, $entityPath) = $this->generateEntity($this->bundle, $this->entity, $this->fields, 'PageParts', $this->prefix, 'Kunstmaan\\PagePartBundle\\Entity\\AbstractPagePart'); // Add some extra functions in the generated entity :s $params = array('bundle' => $this->bundle->getName(), 'pagepart' => $this->entity, 'adminType' => '\\' . $this->bundle->getNamespace() . '\\Form\\PageParts\\' . $this->entity . 'AdminType'); $extraCode = $this->render('/Entity/PageParts/ExtraFunctions.php', $params); $pos = strrpos($entityCode, "}"); $trimmed = substr($entityCode, 0, $pos); $entityCode = $trimmed . "\n" . $extraCode . "\n}"; // Write class to filesystem $this->filesystem->mkdir(dirname($entityPath)); file_put_contents($entityPath, $entityCode); $this->assistant->writeLine('Generating entity : <info>OK</info>'); }
public function generate(BundleInterface $bundle, $entity, $format, array $fields, $withRepository) { // configure the bundle (needed if the bundle does not contain any Entities yet) $config = $this->registry->getManager(null)->getConfiguration(); $config->setEntityNamespaces(array_merge(array($bundle->getName() => $bundle->getNamespace() . '\\Entity'), $config->getEntityNamespaces())); $entityClass = $this->registry->getAliasNamespace($bundle->getName()) . '\\' . $entity; $entityPath = $bundle->getPath() . '/Entity/' . str_replace('\\', '/', $entity) . '.php'; if (file_exists($entityPath)) { throw new \RuntimeException(sprintf('Entity "%s" already exists.', $entityClass)); } $class = new ClassMetadataInfo($entityClass); $namingArray = Helper\NamingHelper::getNamingArray($bundle); $class->table['name'] = $namingArray['vendor'] . '__' . $namingArray['bundle'] . '__' . strtolower($entity); if ($withRepository) { $class->customRepositoryClassName = $entityClass . 'Repository'; } $class->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true)); $class->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); foreach ($fields as $field) { $class->mapField($field); } $entityGenerator = $this->getEntityGenerator(); if ('annotation' === $format) { $entityGenerator->setGenerateAnnotations(true); $entityCode = $entityGenerator->generateEntityClass($class); $mappingPath = $mappingCode = false; } else { $cme = new ClassMetadataExporter(); $exporter = $cme->getExporter('yml' == $format ? 'yaml' : $format); $mappingPath = $bundle->getPath() . '/Resources/config/doctrine/' . str_replace('\\', '.', $entity) . '.orm.' . $format; if (file_exists($mappingPath)) { throw new \RuntimeException(sprintf('Cannot generate entity when mapping "%s" already exists.', $mappingPath)); } $mappingCode = $exporter->exportClassMetadata($class); $entityGenerator->setGenerateAnnotations(false); $entityCode = $entityGenerator->generateEntityClass($class); } $this->filesystem->mkdir(dirname($entityPath)); file_put_contents($entityPath, $entityCode); if ($mappingPath) { $this->filesystem->mkdir(dirname($mappingPath)); file_put_contents($mappingPath, $mappingCode); } if ($withRepository) { $path = $bundle->getPath() . str_repeat('/..', substr_count(get_class($bundle), '\\')); $this->getRepositoryGenerator()->writeEntityRepositoryClass($class->customRepositoryClassName, $path); } }
/** * @param BundleInterface $bundle * @param string $module * @param string $entity */ public function generate(BundleInterface $bundle, $module, $entity) { $parameters = array('namespace' => $bundle->getNamespace(), 'bundle' => $bundle->getName(), 'module' => $module, 'entity' => $entity, 'identifier' => Container::underscore($module), 'bundle_alias' => Container::underscore($bundle->getName())); $dir = $bundle->getPath(); $moduleFile = $dir . '/Module/' . $module . 'Module.php'; if (file_exists($moduleFile)) { throw new \RuntimeException(sprintf('Module "%s" already exists', $module)); } $formExtensionFile = $dir . '/Form/Module/' . $module . 'FormExtension.php'; if (file_exists($formExtensionFile)) { throw new \RuntimeException(sprintf('FormExtension "%s" already exists', $module)); } $this->renderFile('module/Module.php.twig', $moduleFile, $parameters); $this->renderFile('module/FormExtension.php.twig', $formExtensionFile, $parameters); $this->updateDependencyInjection($bundle, $parameters); }
/** * Export the translations from a given path * * @param BundleInterface $bundle * @param string $locale * @param string $outputDir * @param bool $excel * @return array */ private function exportTranslations(BundleInterface $bundle, $locale, $outputDir, $excel = false) { // if the bundle does not have a translation dir, continue to the next one $translationPath = sprintf('%s%s', $bundle->getPath(), '/Resources/translations'); if (!is_dir($translationPath)) { return array(); } // create a catalogue, and load the messages $catalogue = new MessageCatalogue($locale); /** @var \Symfony\Bundle\FrameworkBundle\Translation\TranslationLoader $loader */ $loader = $this->getContainer()->get('translation.loader'); $loader->loadMessages($translationPath, $catalogue); // export in desired format if ($excel) { // check if the PHPExcel library is installed if (!class_exists('PHPExcel')) { throw new \RuntimeException('PHPExcel library is not installed. Please do so if you want to export translations as Excel file.'); } $dumper = new ExcelFileDumper(); } else { $dumper = new CsvFileDumper(); } /** @var DumperInterface $dumper */ return $dumper->dump($catalogue, array('path' => $outputDir, 'bundleName' => $bundle->getName())); }
function it_locates_resource(PathCheckerInterface $pathChecker, KernelInterface $kernel, BundleInterface $bundle) { $bundle->getName()->willReturn("Bundle"); $bundle->getPath()->willReturn("/app/bundle"); $kernel->getBundle("Bundle", false)->willReturn([$bundle]); $pathChecker->processPaths(Argument::type('array'), Argument::type('array'), [])->shouldBeCalled()->willReturn("/app/bundle/resource"); $this->locateResource("@Bundle/Resources/resource", [])->shouldReturn("/app/bundle/resource"); }
/** * @todo Move into trait or dependency. * @param BundleInterface $bundle * @param string $entity */ protected function declareService(BundleInterface $bundle, $entity) { $dir = $bundle->getPath(); $parts = explode('\\', $entity); $entityClass = array_pop($parts); $entityNamespace = implode('\\', $parts); $namespace = $bundle->getNamespace(); $bundleName = strtolower($bundle->getName()); $entityName = strtolower($entity); $handlersFile = sprintf("%s/Resources/config/handlers.xml", $dir); $handlerClass = sprintf("%s\\Handler\\%sHandler", $namespace, $entityClass); $paramKey = sprintf("%s.%s.handler.class", str_replace("bundle", "", $bundleName), $entityName); $newId = sprintf("%s.%s.handler", str_replace("bundle", "", $bundleName), $entityName); $fileName = sprintf("%s/DependencyInjection/%s.php", $dir, str_replace("Bundle", "Extension", $bundle->getName())); if (!is_file($handlersFile)) { $this->renderFile("config/services.xml.twig", $handlersFile, []); } $newXML = simplexml_load_file($handlersFile); if (!($parametersTag = $newXML->parameters)) { $parametersTag = $newXML->addChild('parameters'); } if (!($servicesTag = $newXML->services)) { $servicesTag = $newXML->addChild("services"); } $paramSearch = $newXML->xpath("//*[@key='{$paramKey}']"); $serviceSearch = $newXML->xpath("//*[@id='{$newId}']"); if (!$paramSearch) { $newParamTag = $parametersTag->addChild("parameter"); $newParamTag->addAttribute("key", $paramKey); $newParamTag[0] = $handlerClass; } if (!$serviceSearch) { $newServiceTag = $servicesTag->addChild("service"); $newServiceTag->addAttribute("id", $newId); $newServiceTag->addAttribute("class", "%" . $paramKey . "%"); $entityManagerTag = $newServiceTag->addChild("argument"); $entityManagerTag->addAttribute("type", "service"); $entityManagerTag->addAttribute("id", "doctrine.orm.entity_manager"); $newServiceTag->addChild("argument", sprintf("%s\\Entity\\%s%s", $namespace, $entityNamespace, $entityClass)); $formFactoryTag = $newServiceTag->addChild("argument"); $formFactoryTag->addAttribute("type", "service"); $formFactoryTag->addAttribute("id", "form.factory"); } $newXML->saveXML($handlersFile); $this->updateDIFile($fileName); }
/** * @param BundleInterface $bundle * @param string $entity * @param string $format * @param array $fields * * @return EntityGeneratorResult * * @throws \Doctrine\ORM\Tools\Export\ExportException */ public function generate(BundleInterface $bundle, $entity, $format, array $fields) { // configure the bundle (needed if the bundle does not contain any Entities yet) $config = $this->registry->getManager(null)->getConfiguration(); $config->setEntityNamespaces(array_merge(array($bundle->getName() => $bundle->getNamespace() . '\\Entity'), $config->getEntityNamespaces())); $entityClass = $this->registry->getAliasNamespace($bundle->getName()) . '\\' . $entity; $entityPath = $bundle->getPath() . '/Entity/' . str_replace('\\', '/', $entity) . '.php'; if (file_exists($entityPath)) { throw new \RuntimeException(sprintf('Entity "%s" already exists.', $entityClass)); } $class = new ClassMetadataInfo($entityClass); $class->customRepositoryClassName = str_replace('\\Entity\\', '\\Repository\\', $entityClass) . 'Repository'; $class->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true)); $class->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); foreach ($fields as $field) { $class->mapField($field); } $entityGenerator = $this->getEntityGenerator(); if ('annotation' === $format) { $entityGenerator->setGenerateAnnotations(true); $class->setPrimaryTable(array('name' => Inflector::tableize($entity))); $entityCode = $entityGenerator->generateEntityClass($class); $mappingPath = $mappingCode = false; } else { $cme = new ClassMetadataExporter(); $exporter = $cme->getExporter('yml' == $format ? 'yaml' : $format); $mappingPath = $bundle->getPath() . '/Resources/config/doctrine/' . str_replace('\\', '.', $entity) . '.orm.' . $format; if (file_exists($mappingPath)) { throw new \RuntimeException(sprintf('Cannot generate entity when mapping "%s" already exists.', $mappingPath)); } $mappingCode = $exporter->exportClassMetadata($class); $entityGenerator->setGenerateAnnotations(false); $entityCode = $entityGenerator->generateEntityClass($class); } $entityCode = str_replace(array("@var integer\n", "@var boolean\n", "@param integer\n", "@param boolean\n", "@return integer\n", "@return boolean\n"), array("@var int\n", "@var bool\n", "@param int\n", "@param bool\n", "@return int\n", "@return bool\n"), $entityCode); $this->filesystem->mkdir(dirname($entityPath)); file_put_contents($entityPath, $entityCode); if ($mappingPath) { $this->filesystem->mkdir(dirname($mappingPath)); file_put_contents($mappingPath, $mappingCode); } $path = $bundle->getPath() . str_repeat('/..', substr_count(get_class($bundle), '\\')); $this->getRepositoryGenerator()->writeEntityRepositoryClass($class->customRepositoryClassName, $path); $repositoryPath = $path . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $class->customRepositoryClassName) . '.php'; return new EntityGeneratorResult($entityPath, $repositoryPath, $mappingPath); }
/** * Generate the fixtures class. * * @param BundleInterface $bundle A bundle object * @param BundleInterface $destBundle The destination bundle object * @param string $entity The entity relative class name * @param ClassMetadataInfo $metadata The entity class metadata * @parma integer $num The number of fixtures to generate * * @throws \RuntimeException */ public function generate(BundleInterface $bundle, BundleInterface $destBundle, $entity, ClassMetadataInfo $metadata, $num = 1) { $parts = explode('\\', $entity); $entityClass = array_pop($parts); $dir = $destBundle->getPath() . '/DataFixtures/ORM/'; $this->filesystem->mkdir($dir); $this->renderFile('fixtures/DataFixtures.php.twig', $dir . $entityClass . 'Data.php', array('namespace' => $destBundle->getNamespace(), 'bundle' => $bundle->getName(), 'entity' => $entity, 'entity_class' => $entityClass, 'fields' => $this->getFieldsFromMetadata($metadata), 'num' => $num)); }
/** * Generates the functional test class only. * */ protected function generateTestClass() { $parts = explode('\\', $this->entity); $entityClass = array_pop($parts); $entityNamespace = implode('\\', $parts); $dir = $this->bundle->getPath() . '/Tests/Controller'; $target = $dir . '/' . str_replace('\\', '/', $entityNamespace) . '/' . $entityClass . 'RESTControllerTest.php'; $this->renderFile('rest/tests/test.php.twig', $target, array('route_prefix' => $this->routePrefix, 'route_name_prefix' => $this->routeNamePrefix, 'entity' => $this->entity, 'bundle' => $this->bundle->getName(), 'entity_class' => $entityClass, 'namespace' => $this->bundle->getNamespace(), 'entity_namespace' => $entityNamespace, 'actions' => $this->actions, 'form_type_name' => strtolower(str_replace('\\', '_', $this->bundle->getNamespace()) . ($parts ? '_' : '') . implode('_', $parts) . '_' . $entityClass . 'Type'))); }
function let(KernelWrapper $kernel, BundleInterface $bundle1, BundleInterface $bundle2, ServiceNameGenerator $generator) { $kernel->getBundles()->willReturn([$bundle1, $bundle2]); $this->beConstructedWith($kernel, $generator); $bundle1->getNamespace()->willReturn('Company\\MyBundle'); $bundle1->getName()->willReturn('bundle1'); $bundle2->getNamespace()->willReturn('Company\\MyOther\\Bundle'); $bundle2->getName()->willReturn('Bundle2'); }
/** * @param BundleInterface $bundle * @param SwaggerDocument $document * @param string $relativeNamespace */ public function generate(BundleInterface $bundle, SwaggerDocument $document, $relativeNamespace = 'Model\\Resources') { $dir = $bundle->getPath(); $parameters = ['namespace' => $bundle->getNamespace(), 'bundle' => $bundle->getName(), 'resource_namespace' => $relativeNamespace]; foreach ($document->getResourceSchemas() as $typeName => $spec) { $resourceFile = "{$dir}/" . str_replace('\\', '/', $relativeNamespace) . "/{$typeName}.php"; $this->renderFile('resource.php.twig', $resourceFile, array_merge($parameters, $spec, ['resource' => $typeName, 'resource_class' => $typeName])); } }
/** * Generate the page entity. * * @throws \RuntimeException */ private function generatePageEntity() { list($entityCode, $entityPath) = $this->generateEntity($this->bundle, $this->entity, $this->fields, 'Pages', $this->prefix, 'Kunstmaan\\NodeBundle\\Entity\\AbstractPage'); // Add implements HasPageTemplateInterface $search = 'extends \\Kunstmaan\\NodeBundle\\Entity\\AbstractPage'; $entityCode = str_replace($search, $search . ' implements \\Kunstmaan\\PagePartBundle\\Helper\\HasPageTemplateInterface', $entityCode); // Add some extra functions in the generated entity :s $params = array('bundle' => $this->bundle->getName(), 'page' => $this->entity, 'template' => substr($this->template, 0, strlen($this->template) - 4), 'sections' => array_map(function ($val) { return substr($val, 0, strlen($val) - 4); }, $this->sections), 'adminType' => '\\' . $this->bundle->getNamespace() . '\\Form\\Pages\\' . $this->entity . 'AdminType', 'namespace' => $this->registry->getAliasNamespace($this->bundle->getName()) . '\\Pages\\' . $this->entity); $extraCode = $this->render('/Entity/Pages/ExtraFunctions.php', $params); $pos = strrpos($entityCode, '}'); $trimmed = substr($entityCode, 0, $pos); $entityCode = $trimmed . $extraCode . "\n}"; // Write class to filesystem $this->filesystem->mkdir(dirname($entityPath)); file_put_contents($entityPath, $entityCode); $this->assistant->writeLine('Generating entity : <info>OK</info>'); }
/** * Copy and modify default config files for the pagetemplate and pageparts. */ private function copyTemplateConfig() { $dirPath = $this->bundle->getPath(); $pagepartFile = $dirPath . '/Resources/config/pageparts/' . $this->template . '.yml'; $this->filesystem->copy($this->skeletonDir . '/Resources/config/pageparts/formpage.yml', $pagepartFile, false); GeneratorUtils::replace("~~~ENTITY~~~", $this->entity, $pagepartFile); $pagetemplateFile = $dirPath . '/Resources/config/pagetemplates/' . $this->template . '.yml'; $this->filesystem->copy($this->skeletonDir . '/Resources/config/pagetemplates/formpage.yml', $pagetemplateFile, false); GeneratorUtils::replace("~~~BUNDLE~~~", $this->bundle->getName(), $pagetemplateFile); GeneratorUtils::replace("~~~ENTITY~~~", $this->entity, $pagetemplateFile); }
function it_throws_an_exception_if_resource_can_not_be_located(Filesystem $filesystem, KernelInterface $kernel, ThemeInterface $theme, BundleInterface $childBundle, BundleInterface $parentBundle) { $kernel->getBundle('ParentBundle', false)->willReturn([$childBundle, $parentBundle]); $childBundle->getName()->willReturn('ChildBundle'); $parentBundle->getName()->willReturn('ParentBundle'); $theme->getName()->willReturn('theme/name'); $theme->getPath()->willReturn('/theme/path'); $filesystem->exists('/theme/path/ChildBundle/views/index.html.twig')->shouldBeCalled()->willReturn(false); $filesystem->exists('/theme/path/ParentBundle/views/index.html.twig')->shouldBeCalled()->willReturn(false); $this->shouldThrow(ResourceNotFoundException::class)->during('locateResource', ['@ParentBundle/Resources/views/index.html.twig', $theme]); }
/** * Generate the basic layout. * * @param BundleInterface $bundle The bundle * @param string $rootDir The root directory of the application */ public function generate(BundleInterface $bundle, $rootDir, $demosite) { $this->bundle = $bundle; $this->rootDir = $rootDir; $this->demosite = $demosite; $this->shortBundleName = '@' . str_replace('Bundle', '', $bundle->getName()); $this->generateBowerFiles(); $this->generateGulpFiles(); $this->generateGemsFile(); $this->generateAssets(); $this->generateTemplate(); }
/** * Generates the controller class only. * */ private function generateControllerClass() { $dir = $this->bundle->getPath(); $parts = explode('\\', $this->document); $class = array_pop($parts); $namespace = implode('\\', $parts); $target = sprintf('%s/Controller/%s/%sController.php', $dir, str_replace('\\', '/', $namespace), $class); if (file_exists($target)) { throw new \RuntimeException('Unable to generate the controller as it already exists.'); } $this->renderFile('controller.php.twig', $target, array('actions' => $this->actions, 'route_prefix' => $this->routePrefix, 'route_name_prefix' => $this->routeNamePrefix, 'dir' => $this->skeletonDir, 'bundle' => $this->bundle->getName(), 'document' => $this->document, 'document_class' => $class, 'namespace' => $this->bundle->getNamespace(), 'controller_namespace' => $namespace, 'format' => $this->format)); }
/** * Generates the entity form class if it does not exist. * * @param BundleInterface $bundle The bundle in which to create the class * @param string $entity The entity relative class name * @param ClassMetadataInfo $metadata The entity metadata class */ public function generate(BundleInterface $bundle, $entity, ClassMetadataInfo $metadata, $forceOverwrite = false) { $parts = explode('\\', $entity); $entityClass = array_pop($parts); $this->className = $entityClass . 'FormType'; $dirPath = $bundle->getPath() . '/Form'; $this->classPath = $dirPath . '/Type/' . str_replace('\\', '/', $entity) . 'FormType.php'; $handlerClassName = $entityClass . 'FormHandler'; $classFormHandlerPath = $dirPath . '/Handler/' . str_replace('\\', '/', $entity) . 'FormHandler.php'; if (!$forceOverwrite && file_exists($this->classPath)) { throw new \RuntimeException(sprintf('Unable to generate the %s form class as it already exists under the %s file', $this->className, $this->classPath)); } if (count($metadata->identifier) > 1) { throw new \RuntimeException('The form generator does not support entity classes with multiple primary keys.'); } $parts = explode('\\', $entity); array_pop($parts); // Form Handler Generator $this->renderFile('form/FormHandler.php.twig', $classFormHandlerPath, array('namespace' => $bundle->getNamespace(), 'entity_namespace' => implode('\\', $parts), 'entity_class' => $entityClass, 'bundle' => $bundle->getName(), 'form_class' => $handlerClassName)); $this->renderFile('form/FormType.php.twig', $this->classPath, array('fields' => $this->getFieldsFromMetadata($metadata), 'namespace' => $bundle->getNamespace(), 'entity_namespace' => implode('\\', $parts), 'entity_class' => $entityClass, 'bundle' => $bundle->getName(), 'form_class' => $this->className, 'form_type_name' => strtolower(str_replace('\\', '_', $bundle->getNamespace()) . ($parts ? '_' : '') . implode('_', $parts) . '_' . substr($this->className, 0, -4)))); }
public function generateTranslationEntity(BundleInterface $bundle, $translatableEntity, $translationEntity, $format, array $fields) { // configure the bundle (needed if the bundle does not contain any Entities yet) $config = $this->registry->getManager(null)->getConfiguration(); $config->setEntityNamespaces(array_merge(array($bundle->getName() => $bundle->getNamespace() . '\\Entity'), $config->getEntityNamespaces())); $translationEntityClass = $this->registry->getAliasNamespace($bundle->getName()) . '\\' . $translationEntity; $translatableEntityClass = $this->registry->getAliasNamespace($bundle->getName()) . '\\' . $translatableEntity; $translationEntityPath = $bundle->getPath() . '/Entity/' . str_replace('\\', '/', $translationEntity) . '.php'; if (file_exists($translationEntityPath)) { throw new \RuntimeException(sprintf('Entity "%s" already exists.', $translationEntityClass)); } $translationClass = new ClassMetadataInfo($translationEntityClass); $translatableClass = new ClassMetadataInfo($translatableEntityClass); foreach ($fields as $field) { $translationClass->mapField($field); } $entityGenerator = $this->getEntityGenerator(); $entityGenerator->setClassToExtend('Prezent\\Doctrine\\Translatable\\Entity\\AbstractTranslation'); if ('annotation' === $format) { $entityGenerator->setGenerateAnnotations(true); $entityCode = $entityGenerator->generateTranslationEntityClass($translationClass, $translatableClass); $mappingPath = $mappingCode = false; } else { $cme = new ClassMetadataExporter(); $exporter = $cme->getExporter('yml' == $format ? 'yaml' : $format); $mappingPath = $bundle->getPath() . '/Resources/config/doctrine/' . str_replace('\\', '.', $translationEntity) . '.orm.' . $format; if (file_exists($mappingPath)) { throw new \RuntimeException(sprintf('Cannot generate entity when mapping "%s" already exists.', $mappingPath)); } $mappingCode = $exporter->exportClassMetadata($translationClass); $entityGenerator->setGenerateAnnotations(false); $entityCode = $entityGenerator->generateTranslationEntityClass($translationClass, $translatableClass); } $this->filesystem->mkdir(dirname($translationEntityPath)); file_put_contents($translationEntityPath, $entityCode); if ($mappingPath) { $this->filesystem->mkdir(dirname($mappingPath)); file_put_contents($mappingPath, $mappingCode); } }
/** * Adds a Manager service within the managers config file. * * @param BundleInterface $bundle * @param string $entity * * @return Boolean true if it worked, false otherwise * * @throws \RuntimeException If bundle is already imported */ public function addResource(BundleInterface $bundle, $entity) { $managerService = sprintf('%s.manager.%s', Container::underscore(substr($bundle->getName(), 0, -6)), strtolower($entity)); $managerClass = sprintf('%s\\Manager\\%sManager', $bundle->getNamespace(), ucfirst($entity)); $entityClass = sprintf('%s\\Entity\\%s', $bundle->getNamespace(), ucfirst($entity)); $content = Yaml::parse(file_get_contents($this->file)); $content['parameters'][$managerService . '.class'] = $managerClass; $content['services'][$managerService] = array('class' => "%{$managerService}.class%", 'tags' => array(array('name' => 'voryx.manager')), 'arguments' => array($entityClass)); $yaml = Yaml::dump($content, 4); if (false === file_put_contents($this->file, $yaml)) { return false; } return true; }
/** * @param BundleInterface $bundle * @param string $entity * @param BundleInterface $entityBundle * @param OutputInterface $output */ public function generateCrud(BundleInterface $bundle, $entity, BundleInterface $entityBundle, OutputInterface $output) { $parameters = array('namespace' => $bundle->getNamespace(), 'bundle' => $bundle->getName(), 'entity' => $entity, 'entity_pluralized' => lcfirst(Inflector::pluralize($entity)), 'entity_namespace' => $entityBundle->getNamespace() . '\\Entity', 'entity_bundle' => $entityBundle->getName(), 'route_prefix' => Container::underscore(substr($bundle->getName(), 0, -6)) . '_' . Container::underscore($entity)); // Render php files $output->writeln($this->renderTwigFile('crud/Controller.php.twig', $bundle->getPath() . '/Controller/' . $entity . 'Controller.php', $parameters)); $output->writeln($this->renderTwigFile('crud/FormType.php.twig', $bundle->getPath() . '/Form/' . $entity . 'Type.php', $parameters)); $output->writeln($this->renderTwigFile('crud/FilterFormType.php.twig', $bundle->getPath() . '/Form/' . $entity . 'FilterType.php', $parameters)); // Render twig files $output->writeln($this->renderTwigFile('crud/views/index.html.twig.twig', $bundle->getPath() . '/Resources/views/' . lcfirst($entity) . '/index.html.twig', $parameters)); $output->writeln($this->renderTwigFile('crud/views/create.html.twig.twig', $bundle->getPath() . '/Resources/views/' . lcfirst($entity) . '/create.html.twig', $parameters)); $output->writeln($this->renderTwigFile('crud/views/update.html.twig.twig', $bundle->getPath() . '/Resources/views/' . lcfirst($entity) . '/update.html.twig', $parameters)); $output->writeln($this->renderTwigFile('crud/views/delete.html.twig.twig', $bundle->getPath() . '/Resources/views/' . lcfirst($entity) . '/delete.html.twig', $parameters)); $output->writeln($this->renderTwigFile('crud/views/parts/item.html.twig.twig', $bundle->getPath() . '/Resources/views/' . lcfirst($entity) . '/parts/item.html.twig', $parameters)); }
/** * Adds an Admin service within the admin config file. * * @param BundleInterface $bundle * @param string $entity * @param string $group * @param string $label * @param string $translationDomain * * @return Boolean true if it worked, false otherwise * * @throws \RuntimeException If bundle is already imported */ public function addResource(BundleInterface $bundle, $entity, $group, $label, $translationDomain = 'Sonata') { $adminService = sprintf('%s.admin.%s', Container::underscore(substr($bundle->getName(), 0, -6)), strtolower($entity)); $adminClass = sprintf('%s\\Admin\\%sAdmin', $bundle->getNamespace(), ucfirst($entity)); $entityClass = sprintf('%s\\Entity\\%s', $bundle->getNamespace(), ucfirst($entity)); $content = Yaml::parse(file_get_contents($this->file)); $content['parameters'][$adminService . '.class'] = $adminClass; $content['services'][$adminService] = array('class' => "%{$adminService}.class%", 'tags' => array(array('name' => 'sonata.admin', 'manager_type' => 'orm', 'group' => $group, 'label' => $label)), 'arguments' => array(null, $entityClass, null), 'calls' => array(array('setTranslationDomain', array($translationDomain)))); $yaml = Yaml::dump($content, 4); if (false === file_put_contents($this->file, $yaml)) { return false; } return true; }
/** * Generates the entity form class if it does not exist. * * @param BundleInterface $bundle The bundle in which to create the class * @param string $entity The entity relative class name * @param ClassMetadataInfo $metadata The entity metadata class * @param array $options [restSupport => (bool)] */ public function generate(BundleInterface $bundle, $entity, ClassMetadataInfo $metadata, array $options = null) { $dir = $bundle->getPath(); $parts = explode('\\', $entity); $entityClass = array_pop($parts); $entityNamespace = implode('\\', $parts); $target = sprintf('%s/Admin/%sAdmin.php', $dir, str_replace('\\', '/', $entityNamespace), $entityClass); if (!$options['overwrite'] && file_exists($target)) { throw new \RuntimeException('Unable to generate the sonata admin ' . $target . ' class as it already exists.'); } if (!is_dir("{$dir}/Admin")) { mkdir("{$dir}/Admin"); } $this->renderFile('sonata/admin.php.twig', $target, array('fields' => $this->getFieldsFromMetadata($metadata), 'bundle' => $bundle->getName(), 'entity' => $entity, 'entity_class' => $entityClass, 'namespace' => $bundle->getNamespace(), 'entity_namespace' => $entityNamespace)); }
/** * Generates the entity form class. * * @param BundleInterface $bundle The bundle in which to create the class * @param string $entity The entity relative class name * @param ClassMetadataInfo $metadata The entity metadata class * @param bool $forceOverwrite If true, remove any existing form class before generating it again */ public function generate(BundleInterface $bundle, $entity, ClassMetadataInfo $metadata, $forceOverwrite = false) { $parts = explode('\\', $entity); $entityClass = array_pop($parts); $this->className = $entityClass . 'Type'; $dirPath = $bundle->getPath() . '/Form'; $this->classPath = $dirPath . '/' . str_replace('\\', '/', $entity) . 'Type.php'; if (!$forceOverwrite && file_exists($this->classPath)) { throw new \RuntimeException(sprintf('Unable to generate the %s form class as it already exists under the %s file', $this->className, $this->classPath)); } if (count($metadata->identifier) > 1) { throw new \RuntimeException('The form generator does not support entity classes with multiple primary keys.'); } $parts = explode('\\', $entity); array_pop($parts); $this->renderFile('form/FormType.php.twig', $this->classPath, array('fields' => $this->getFieldsFromMetadata($metadata), 'fields_mapping' => $metadata->fieldMappings, 'namespace' => $bundle->getNamespace(), 'entity_namespace' => implode('\\', $parts), 'entity_class' => $entityClass, 'bundle' => $bundle->getName(), 'form_class' => $this->className, 'form_type_name' => strtolower(str_replace('\\', '_', $bundle->getNamespace()) . ($parts ? '_' : '') . implode('_', $parts) . '_' . substr($this->className, 0, -4)), 'configure_options_available' => method_exists('Symfony\\Component\\Form\\AbstractType', 'configureOptions'), 'get_name_required' => !method_exists('Symfony\\Component\\Form\\AbstractType', 'getBlockPrefix'))); }