generate RESTful controllers ans service configs

@param array  $parameters twig parameters
@param string $dir        base bundle dir
@param string $document   document name

@return void
559819
protected function generateController(array $parameters, $dir, $document)
    {
        $this->renderFile(
            'controller/DocumentController.php.twig',
            $dir . '/Controller/' . $document . 'Controller.php',
            $parameters
        );

        $bundleParts = explode('\\', $parameters['base']);
        $shortName = strtolower($bundleParts[0]);
        $shortBundle = strtolower(substr($bundleParts[1], 0, -6));
        $paramName = implode('.', array($shortName, $shortBundle, 'controller', strtolower($parameters['document'])));

        $this->addParameter(
            $parameters['base'] . 'Controller\\' . $parameters['document'] . 'Controller',
            $paramName . '.class'
        );

        $this->addService(
            $paramName,
            $parameters['parent'],
            array(
                array(
                    'method' => 'setModel',
                    'service' => implode(
                        '.',
                        array($shortName, $shortBundle, 'model', strtolower($parameters['document']))
                    )
                )
            ),
            'graviton.rest'
        );
    }
80010
protected function render($template, $parameters)
    {
        $twig = $this->templating;
        $twig->setLoader(new \Twig_Loader_Filesystem($this->skeletonDirs));

        return $twig->render($template, $parameters);
    }
1185689
private function generateIndexView($dir)
    {
        $this->renderFile('views/index.html.twig', $dir.'/index.html.twig', array(
            'dir' => $this->skeletonDir,
            'document' => $this->document,
            'fields' => $this->metadata->fieldMappings,
            'actions' => $this->actions,
            'record_actions' => $this->getRecordActions(),
            'route_prefix' => $this->routePrefix,
            'route_name_prefix' => $this->routeNamePrefix,
        ));
    }
1290690
private function createOrUpdatePageRoute(RoutablePageBehavior $document, $locale)
    {
        $route = $this->reallocateExistingRoute($document, $locale);
        if ($route) {
            return $route;
        }

        $route = $document->getRoute();
        if (!$route) {
            $route = $this->routeRepository->findByEntity($document->getClass(), $document->getUuid(), $locale);
        }

        if ($route && $route->getEntityId() !== $document->getId()) {
            // Mismatch of entity-id's happens because doctrine don't check entities which has been changed in the
            // current session.

            $document->removeRoute();
            $route = null;
        }

        if ($route) {
            $document->setRoute($route);

            return $this->routeManager->update($document, null, false);
        }

        return $this->routeManager->create($document);
    }
1299384
protected function mapParameters($node, array $parameters, ContainerBuilder $container)
    {
        foreach ($parameters as $key => $value) {
            $container->setParameter(sprintf('wall_poster.%s.%s',$node,$key), $value);
        }
    }
1157044
public function generate($namespace, $bundle, $dir, $format)
    {
        $dir .= '/' . strtr($namespace, '\\', '/');

        // make sure we have no trailing \ in namespace
        if (substr($namespace, -1) == '\\') {
            $namespace = substr($namespace, 0, -1);
        }

        $basename = $this->getBundleBaseName($bundle);
        $parameters = array(
            'namespace' => $namespace,
            'bundle' => $bundle,
            'format' => $format,
            'bundle_basename' => $basename,
            'extension_alias' => Container::underscore($basename),
        );

        $this->renderFile('bundle/Bundle.php.twig', $dir . '/' . $bundle . '.php', $parameters);
        $this->renderFile(
            'bundle/Extension.php.twig',
            $dir . '/DependencyInjection/' . $basename . 'Extension.php',
            $parameters
        );

        $this->renderFile('bundle/config.xml.twig', $dir . '/Resources/config/config.xml', $parameters);

        if ('xml' === $format || 'annotation' === $format) {
            $this->renderFile('bundle/services.xml.twig', $dir . '/Resources/config/services.xml', $parameters);
        } else {
            $this->renderFile(
                'bundle/services.' . $format . '.twig',
                $dir . '/Resources/config/services.' . $format,
                $parameters
            );
        }

        if ('annotation' != $format) {
            $this->renderFile(
                'bundle/routing.' . $format . '.twig',
                $dir . '/Resources/config/routing.' . $format,
                $parameters
            );
        }
    }
425972
public function render($template, array $parameters = null, Response $response = null)
    {
        return parent::render($this->bundle->getBaseDirectory().DIRECTORY_SEPARATOR.'Templates'.DIRECTORY_SEPARATOR.'scripts'.DIRECTORY_SEPARATOR.$template, $parameters, $response);
    }
988218
public function generatePagepartConfigs(array $parameters)
    {
        $basePath = $this->isSymfony4() ? $this->container->getParameter('kernel.project_dir') : $this->bundle->getPath();
        $relPath = $this->isSymfony4() ? '/config/kunstmaancms/pageparts' : '/Resources/config/pageparts/';
        $sourceDir = $this->skeletonDir.'/Resources/config/pageparts/';
        $targetDir = $basePath.$relPath;

        $this->renderSingleFile($sourceDir, $targetDir, 'main.yml', $parameters);

        if ($this->demosite) {
            $this->renderSingleFile($sourceDir, $targetDir, 'header.yml', $parameters);
            $this->renderSingleFile($sourceDir, $targetDir, 'section1.yml', $parameters);
            $this->renderSingleFile($sourceDir, $targetDir, 'section2.yml', $parameters);
            $this->renderSingleFile($sourceDir, $targetDir, 'section3.yml', $parameters);
            $this->renderSingleFile($sourceDir, $targetDir, 'section4.yml', $parameters);
            $this->renderSingleFile($sourceDir, $targetDir, 'section5.yml', $parameters);
            $this->renderSingleFile($sourceDir, $targetDir, 'form.yml', $parameters);
        }

        $this->assistant->writeLine('Generating pagepart configuration : <info>OK</info>');
    }
1104201
protected function generateDeleteView($dir)
    {
        $this->renderFile('crud/views/delete.html.twig.twig', $dir.'/delete.html.twig', [
            'route_prefix'      => $this->routePrefix,
            'route_name_prefix' => $this->routeNamePrefix,
            'entity'            => $this->entity,
            'bundle'            => $this->bundle->getName(),
            'actions'           => $this->actions,
        ]);
    }
56099
private function setPageData(ArticleDocument $document, NodeInterface $node, $locale)
    {
        $pages = [
            [
                'uuid' => $document->getUuid(),
                'title' => $document->getPageTitle() ?: $document->getTitle(),
                'routePath' => $document->getRoutePath(),
                'pageNumber' => $document->getPageNumber(),
            ],
        ];

        foreach ($document->getChildren() as $child) {
            if ($child instanceof ArticlePageDocument
                && LocalizationState::GHOST !== $this->documentInspector->getLocalizationState($child)
            ) {
                $pages[] = [
                    'uuid' => $child->getUuid(),
                    'title' => $child->getPageTitle(),
                    'routePath' => $child->getRoutePath(),
                    'pageNumber' => $child->getPageNumber(),
                ];
            }
        }

        $pages = SortUtils::multisort($pages, '[pageNumber]');

        $document->setPages($pages);
        $node->setProperty(
            $this->propertyEncoder->localizedSystemName(self::PAGES_PROPERTY, $locale),
            json_encode($pages)
        );
    }
193854
protected function build(array $parameters)
    {
        $route    = preg_split('`([/.-])`', $this->route, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
        $regex    = array();
        $position = 0;

        foreach ($route as $index => $element) {
            switch ($element) {
                case '.':
                    $regex[$element . '-' . $index] = '\\' . $element;
                    break;
                case '/':
                case '-':
                    $regex[$element . '-' . $index] = $element;
                    break;

                default:

                    if (':' === substr($element, 0, 1)) {
                        $elementName = substr($element, 1);
                        $position++;

                        if (!isset($parameters[$elementName])) {
                            $parameters[$elementName] = new Parameter($elementName);
                        }

                        $regex[$elementName] = '(' . $parameters[$elementName]->getType() . ')';

                        $this->parameterCollection->add($parameters[$elementName]);
                    } else {
                        $regex[$element] = $element;
                    }
            }
        }

        $this->pattern = '`^' . implode('', $regex) . '$`i';
    }
1208567
private function executeMoves($documents)
    {
        foreach ($documents as $oid => $value) {
            if (!$this->contains($oid)) {
                continue;
            }

            list($document, $targetPath) = $value;

            $sourcePath = $this->getDocumentId($document);
            if ($sourcePath === $targetPath) {
                continue;
            }

            $class = $this->dm->getClassMetadata(get_class($document));
            if ($invoke = $this->eventListenersInvoker->getSubscribedSystems($class, Event::preMove)) {
                $this->eventListenersInvoker->invoke(
                    $class,
                    Event::preMove,
                    $document,
                    new MoveEventArgs($document, $this->dm, $sourcePath, $targetPath),
                    $invoke
                );
            }

            $parentNode = $this->session->getNode(PathHelper::getParentPath($targetPath));
            $this->validateChildClass($parentNode, $class);

            $this->session->move($sourcePath, $targetPath);

            // update fields nodename, parentMapping and depth if they exist in this type
            $node = $this->session->getNode($targetPath); // get node from session, document class might not map it
            if ($class->nodename) {
                $class->setFieldValue($document, $class->nodename, $node->getName());
            }

            if ($class->parentMapping) {
                $class->setFieldValue($document, $class->parentMapping, $this->getOrCreateProxyFromNode($node->getParent(), $this->getCurrentLocale($document, $class)));
            }

            if ($class->depthMapping) {
                $class->setFieldValue($document, $class->depthMapping, $node->getDepth());
            }

            // update all cached children of the document to reflect the move (path id changes)
            foreach ($this->documentIds as $childOid => $id) {
                if (0 !== strpos($id, $sourcePath)) {
                    continue;
                }

                $newId = $targetPath.substr($id, strlen($sourcePath));
                $this->documentIds[$childOid] = $newId;

                $child = $this->getDocumentById($id);
                if (!$child) {
                    continue;
                }

                unset($this->identityMap[$id]);
                $this->identityMap[$newId] = $child;

                $childClass = $this->dm->getClassMetadata(get_class($child));
                if ($childClass->identifier) {
                    $childClass->setIdentifierValue($child, $newId);
                    if (!$child instanceof Proxy || $child->__isInitialized()) {
                        $this->originalData[$childOid][$childClass->identifier] = $newId;
                    }
                }
            }

            if ($invoke = $this->eventListenersInvoker->getSubscribedSystems($class, Event::postMove)) {
                $this->eventListenersInvoker->invoke(
                    $class,
                    Event::postMove,
                    $document,
                    new MoveEventArgs($document, $this->dm, $sourcePath, $targetPath),
                    $invoke
                );
            }
        }
    }
1212837
public function doGenerate($location, array $parameters)
    {
        $urlAliasService = $this->repository->getURLAliasService();

        $siteaccess = null;
        if (isset($parameters['siteaccess'])) {
            $siteaccess = $parameters['siteaccess'];
            unset($parameters['siteaccess']);
        }

        if ($siteaccess) {
            // We generate for a different SiteAccess, so potentially in a different language.
            $languages = $this->configResolver->getParameter('languages', null, $siteaccess);
            $urlAliases = $urlAliasService->listLocationAliases($location, false, null, null, $languages);
            // Use the target SiteAccess root location
            $rootLocationId = $this->configResolver->getParameter('content.tree_root.location_id', null, $siteaccess);
        } else {
            $languages = null;
            $urlAliases = $urlAliasService->listLocationAliases($location, false);
            $rootLocationId = $this->rootLocationId;
        }

        $queryString = '';
        unset($parameters['language'], $parameters['contentId']);
        if (!empty($parameters)) {
            $queryString = '?' . http_build_query($parameters, '', '&');
        }

        if (!empty($urlAliases)) {
            $path = $urlAliases[0]->path;
            // Remove rootLocation's prefix if needed.
            if ($rootLocationId !== null) {
                $pathPrefix = $this->getPathPrefixByRootLocationId($rootLocationId, $languages, $siteaccess);
                // "/" cannot be considered as a path prefix since it's root, so we ignore it.
                if ($pathPrefix !== '/' && ($path === $pathPrefix || mb_stripos($path, $pathPrefix . '/') === 0)) {
                    $path = mb_substr($path, mb_strlen($pathPrefix));
                } elseif ($pathPrefix !== '/' && !$this->isUriPrefixExcluded($path) && $this->logger !== null) {
                    // Location path is outside configured content tree and doesn't have an excluded prefix.
                    // This is most likely an error (from content edition or link generation logic).
                    $this->logger->warning("Generating a link to a location outside root content tree: '$path' is outside tree starting to location #$rootLocationId");
                }
            }
        } else {
            $path = $this->defaultRouter->generate(
                self::INTERNAL_CONTENT_VIEW_ROUTE,
                array('contentId' => $location->contentId, 'locationId' => $location->id)
            );
        }

        $path = $path ?: '/';

        // replace potentially unsafe characters with url-encoded counterpart
        return strtr($path . $queryString, $this->unsafeCharMap);
    }
558600
private function generateConfiguration()
    {
        if (!in_array($this->format, array('yml', 'xml', 'php'))) {
            return;
        }

        $target = sprintf(
            '%s/Resources/config/routing/%s.%s',
            $this->bundle->getPath(),
            strtolower(str_replace('\\', '_', $this->document)),
            $this->format
        );

        $this->renderFile('config/routing.'.$this->format.'.twig', $target, array(
            'actions' => $this->actions,
            'route_prefix' => $this->routePrefix,
            'route_name_prefix' => $this->routeNamePrefix,
            'bundle' => $this->bundle->getName(),
            'document' => $this->document,
        ));
    }
462349
protected function generateIndexView($dir)
    {
        $this->renderFile('crud/views/index.html.twig.twig', $dir . '/index.html.twig', array(
            'bundle' => $this->bundle->getName(),
            'entity' => $this->entity,
            'entity_pluralized' => $this->entityPluralized,
            'entity_singularized' => $this->entitySingularized,
            'identifier' => $this->metadata->identifier[0],
            'fields' => $this->metadata->fieldMappings,
            'actions' => $this->actions,
            'record_actions' => $this->getRecordActions(),
            'route_prefix' => $this->config->getRoutePrefix(),
            'route_name_prefix' => $this->routeNamePrefix,
            'base_template' => $this->config->getBaseTemplate(),
            'without_bulk_action' => $this->config->getWithoutBulk(),
            'without_sorting' => $this->config->getWithoutSorting(),
            'without_page_size' => $this->config->getWithoutPageSize(),
            'filter_type' => $this->config->getFilterType(),
        ));
    }
398340
private function updateRoute($document, $generateRoutes)
    {
        $locales = $this->documentInspector->getLocales($document);
        $webspaceKey = $this->documentInspector->getWebspace($document);
        $uuid = $this->documentInspector->getUuid($document);
        $path = $this->documentInspector->getPath($document);
        $parentUuid = $this->documentInspector->getUuid($this->documentInspector->getParent($document));

        $defaultNode = $this->defaultSession->getNode($path);
        $liveNode = $this->liveSession->getNode($path);

        $resourceLocatorStrategy = $this->resourceLocatorStrategyPool->getStrategyByWebspaceKey($webspaceKey);

        foreach ($locales as $locale) {
            $localizedDocument = $this->documentManager->find($uuid, $locale);

            if (RedirectType::NONE !== $localizedDocument->getRedirectType()) {
                continue;
            }

            $resourceSegmentPropertyName = $this->encoder->localizedSystemName(
                $this->getResourceSegmentProperty($localizedDocument)->getName(),
                $locale
            );

            $this->updateResourceSegmentProperty(
                $defaultNode,
                $resourceSegmentPropertyName,
                $parentUuid,
                $webspaceKey,
                $locale
            );

            if ($liveNode->hasProperty($resourceSegmentPropertyName)) {
                $this->updateResourceSegmentProperty(
                    $liveNode,
                    $resourceSegmentPropertyName,
                    $parentUuid,
                    $webspaceKey,
                    $locale
                );

                // if the method is called with the generateRoutes flag it will create a new route
                // this happens on a move, but not on copy, because copy results in a draft page without url
                if ($generateRoutes) {
                    $localizedDocument->setResourceSegment($liveNode->getPropertyValue($resourceSegmentPropertyName));
                    $resourceLocatorStrategy->save($localizedDocument, null);
                    $localizedDocument->setResourceSegment($defaultNode->getPropertyValue($resourceSegmentPropertyName));
                }
            }
        }
    }
542483
public function createFileManager(array $parameters, $driver, $dir_path = null)
    {
        $file_manager = new FileManager($parameters, $driver, $this->container);
        $this->file_manager = $file_manager;
        $file_manager->setDirPaths($dir_path);
        $this->setDisplayType();
        return $file_manager;
    }