Render paste top button. Returns null if no button should be rendered.

@param EnvironmentInterface                    $environment The environment.
@param GroupAndSortingDefinitionInterface|null $sorting     The sorting mode.

@return string
979411
protected function renderPasteTopButton(EnvironmentInterface $environment, $sorting)
    {
        $definition     = $environment->getDataDefinition();
        $dispatcher     = $environment->getEventDispatcher();
        $languageDomain = 'contao_' . $definition->getName();

        $filter = new Filter();
        $filter->andModelIsFromProvider($definition->getBasicDefinition()->getDataProvider());

        if (!$sorting || $environment->getClipboard()->isEmpty($filter)) {
            return null;
        }
        if (!ViewHelpers::getManualSortingProperty($environment)) {
            return null;
        }

        /** @var AddToUrlEvent $urlEvent */
        $urlEvent = $dispatcher->dispatch(
            ContaoEvents::BACKEND_ADD_TO_URL,
            new AddToUrlEvent(
                'act=paste&after=' . ModelId::fromValues($definition->getName(), '0')->getSerialized()
            )
        );

        /** @var GenerateHtmlEvent $imageEvent */
        $imageEvent = $dispatcher->dispatch(
            ContaoEvents::IMAGE_GET_HTML,
            new GenerateHtmlEvent(
                'pasteafter.svg',
                $this->translate('pasteafter.0', $languageDomain),
                'class="blink"'
            )
        );

        return \sprintf(
            '<a href="%s" title="%s" onclick="Backend.getScrollOffset()">%s</a>',
            $urlEvent->getUrl(),
            StringUtil::specialchars($this->translate('pasteafter.0', $languageDomain)),
            $imageEvent->getHtml()
        );
    }
1329593
public function getCommand($commandNamespace, Factory $environment = null)
    {
        $commandName = $this->testCommandRegistration($commandNamespace);

        /**
         * @var IBladedCommand $command
         */
        $command = $this->application->make($commandName);

        if (($environment !== null) && (!in_array($commandNamespace, $this->environmental, true))) {
            $this->environmental[] = $commandNamespace;
            $command->setEnvironment($environment);
        }

        return $command;
    }
487200
protected function handleSubmit(Action $action, EnvironmentInterface $environment)
    {
        $inputProvider   = $environment->getInputProvider();
        $sessionStorage  = $environment->getSessionStorage();
        $eventDispatcher = $environment->getEventDispatcher();

        if (('auto' === $inputProvider->getValue('SUBMIT_TYPE'))
            || !$inputProvider->hasValue($this->getMode($action) . '_saveNback')) {
            return;
        }

        $sessionStorage->remove($environment->getDataDefinition()->getName() . '.' . $this->getMode($action));

        $urlEvent = new GetReferrerEvent(false, $environment->getDataDefinition()->getName());

        $eventDispatcher->dispatch(ContaoEvents::SYSTEM_GET_REFERRER, $urlEvent);
        $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_REDIRECT, new RedirectEvent($urlEvent->getReferrerUrl()));
    }
1119180
protected function process(EnvironmentInterface $environment)
    {
        $modelId = ModelId::fromSerialized($environment->getInputProvider()->getParameter('source'));

        $dataDefinition = $environment->getDataDefinition();
        $this->guardValidEnvironment($dataDefinition, $modelId);
        // We want a redirect here if not creatable.
        $this->guardIsCreatable($environment, $modelId, true);

        if ($dataDefinition->getBasicDefinition()->isEditOnlyMode()) {
            return $this->callAction($environment, 'edit');
        }

        // Manual sorting mode. The ClipboardController should pick it up.
        $manualSortingProperty = ViewHelpers::getManualSortingProperty($environment);
        if ($manualSortingProperty && $environment->getDataProvider()->fieldExists($manualSortingProperty)) {
            return false;
        }

        $copiedModel = $this->copy($environment, $modelId);

        // If edit several don´t redirect do home.
        if ('select' === $environment->getInputProvider()->getParameter('act')) {
            return false;
        }

        $this->redirect($environment, ModelId::fromModel($copiedModel));

        return null;
    }
518081
protected function renderTemplate(ContaoBackendViewTemplate $template, EnvironmentInterface $environment)
    {
        $definition = $environment->getDataDefinition();
        $showColumn = $this->getViewSection($definition)->getListingConfig()->getShowColumns();

        $template
            ->set('subHeadline', $this->translate('MSC.select_models', 'contao_default'))
            ->set('tableName', ($definition->getName() ?? 'none'))
            ->set('select', 'select' === $environment->getInputProvider()->getParameter('act'))
            ->set('action', \ampersand(Environment::get('request')))
            ->set('selectButtons', $this->getSelectButtons($environment))
            ->set('sortable', $this->isSortable($environment))
            ->set('showColumns', $showColumn)
            ->set('tableHead', $showColumn ? $this->getTableHead($environment) : '')
            // Add breadcrumb, if we have one.
            ->set('breadcrumb', $this->breadcrumb($environment))
            ->set('floatRightSelectButtons', true)
            ->set('selectCheckBoxName', 'models[]')
            ->set('selectCheckBoxIdPrefix', 'models_')
            ->set('selectContainer', $this->getSelectContainer($environment));

        if ((null !== $template->get('action'))
            && (false !== \strpos($template->get('action'), 'select=models'))
        ) {
            $template->set('action', \str_replace('select=models', 'select=properties', $template->get('action')));
        }
    }
994534
private function handleGlobalCommands(EnvironmentInterface $environment)
    {
        $dataDefinition = $environment->getDataDefinition();
        $backendView    = $dataDefinition->getDefinition(Contao2BackendViewDefinitionInterface::NAME);

        $backButton = null;
        if ($backendView->getGlobalCommands()->hasCommandNamed('back_button')) {
            $backButton = $backendView->getGlobalCommands()->getCommandNamed('back_button');
        }

        if (!$backButton) {
            return;
        }

        $parametersBackButton = $backButton->getParameters();

        if (\in_array($this->getSelectAction($environment), ['properties', 'edit'])) {
            $parametersBackButton->offsetSet('act', 'select');
            $parametersBackButton->offsetSet(
                'select',
                ('edit' === $this->getSelectAction($environment)) ? 'properties' : 'models'
            );
            $parametersBackButton->offsetSet('mode', $this->getSubmitAction($environment, true));
        }

        $closeCommand = new Command();
        $backendView->getGlobalCommands()->addCommand($closeCommand);

        $closeExtra = [
            'href'       => $this->getReferrerUrl($environment),
            'class'      => 'header_icon header_stop',
            'accessKey'  => 'x',
            'attributes' => 'onclick="Backend.getScrollOffset();"'
        ];

        $closeCommand
            ->setName('close_all_button')
            ->setLabel('MSC.closeAll.0')
            ->setDescription('MSC.closeAll.1')
            ->setParameters(new \ArrayObject())
            ->setExtra(new \ArrayObject($closeExtra))
            ->setDisabled(false);
    }
278466
public function pasteAfter(ModelInterface $previousModel, CollectionInterface $models, $sortedBy)
    {
        if (0 === $models->length()) {
            throw new \RuntimeException('No models passed to pasteAfter().');
        }
        $environment = $this->getEnvironment();

        if (\in_array(
            $environment
                ->getDataDefinition()
                ->getBasicDefinition()
                ->getMode(),
            [
                BasicDefinitionInterface::MODE_HIERARCHICAL,
                BasicDefinitionInterface::MODE_PARENTEDLIST
            ]
        )) {
            if (!$this->relationshipManager->isRoot($previousModel)) {
                $parentModel = $this->modelCollector->searchParentOf($previousModel);
                $parentName  = $parentModel->getProviderName();
                $this->relationshipManager->setSameParentForAll($models, $previousModel, $parentName);
            } else {
                $this->relationshipManager->setAllRoot($models);
            }
        }

        // Enforce proper sorting now.
        $siblings = $this->modelCollector->collectSiblingsOf($previousModel, $sortedBy);
        $newList  = (new SortingManager($models, $siblings, $sortedBy, $previousModel))->getResults();

        $environment->getDataProvider($previousModel->getProviderName())->saveEach($newList);
    }
168785
public static function renderIcon(Environment $twigEnvironment, $name, $style = null) {

        $handler = explode(":", $name);
        if (2 !== count($handler)) {
            return "";
        }

        $output = "";

        switch ($handler[0]) {

            case "fa": // Font Awesome
                $output = (new FontAwesomeTwigExtension($twigEnvironment))->renderIcon($handler[1], $style);
                break;

            case "mc": // Meteocons
                $output = (new MeteoconsTwigExtension($twigEnvironment))->renderIcon($handler[1], $style);
                break;

            case "zmdi": // Material Design Iconic Font
                $output = (new MaterialDesignIconicFontTwigExtension($twigEnvironment))->renderIcon($handler[1], $style);
                break;
        }

        return $output;
    }
941840
public function renderTwig(\Twig_Environment $environment, $template, array $parameters = array())
    {
        $template = $this->loadStringTemplate($environment, $template);

        return $template->render($parameters);
    }
1094054
private function getSelectCollection(EnvironmentInterface $environment)
    {
        $sessionStorage = $environment->getSessionStorage();
        $dataDefinition = $environment->getDataDefinition();
        $dataProvider   = $environment->getDataProvider();
        $session        =
            $sessionStorage->get($dataDefinition->getName() . '.' . $this->getSubmitAction($environment, true));

        $modelIds = [];
        foreach ($session['models'] as $modelId) {
            $modelIds[] = ModelId::fromSerialized($modelId)->getId();
        }

        $idProperty = \method_exists($dataProvider, 'getIdProperty') ? $dataProvider->getIdProperty() : 'id';
        return $dataProvider->fetchAll(
            $dataProvider->getEmptyConfig()->setFilter(
                [
                    [
                        'operation' => 'IN',
                        'property'  => $idProperty,
                        'values'    => $modelIds
                    ]
                ]
            )
        );
    }
717516
private function getParentModelButtons($parentModel, EnvironmentInterface $environment)
    {
        if ('select' === $environment->getInputProvider()->getParameter('act')) {
            return '';
        }

        $config = $environment->getBaseConfigRegistry()->getBaseConfig();
        $environment->getView()->getPanel()->initialize($config);
        if (!$config->getSorting()) {
            return '';
        }

        return \implode(
            ' ',
            [
                'editHeader' => $this->getHeaderEditButton($parentModel, $environment),
                'pasteNew' => $this->getHeaderPasteNewButton($parentModel, $environment),
                'pasteAfter' => $this->getHeaderPasteTopButton($parentModel, $environment)
            ]
        );
    }
361989
public static function getCurrentSorting(EnvironmentInterface $environment)
    {
        /** @var BackendViewInterface $view */
        $view = $environment->getView();

        foreach ($view->getPanel() as $panel) {
            /** @var PanelInterface $panel */
            $sort = $panel->getElement('sort');
            if ($sort) {
                /** @var SortElementInterface $sort */
                return $sort->getSelectedDefinition();
            }
        }

        /** @var Contao2BackendViewDefinitionInterface $viewSection */
        $viewSection = $environment->getDataDefinition()->getDefinition(Contao2BackendViewDefinitionInterface::NAME);
        $definition  = $viewSection->getListingConfig()->getGroupAndSortingDefinition();
        if ($definition->hasDefault()) {
            return $definition->getDefault();
        }

        return null;
    }
379555
public function getCategoryChildTree(
        \Twig_Environment $environment,
        $template = 'ONGRCategoryBundle:Category:inc/categorytree.html.twig',
        $maxLevel = 0,
        $selectedCategory = null,
        $fromCategory = null
    ) {
        $this->categoryService->setCurrentCategoryId($selectedCategory);

        $tree = $this->categoryService->getPartialTree($maxLevel, $fromCategory);
        $currentCategory = $this->categoryService->getCurrentCategoryDocument();

        return $this->renderCategoryTree($environment, $tree, $selectedCategory, $currentCategory, $template);
    }
792734
public function evaluate(EnvironmentInterface $env)
    {
        $qb = $env->queryBuilder;

        $paramName = $env->newParamName();
        $paramValue = $env->newParamName();

        $paramContent = $env->newParamName();
        $paramVs = $env->newParamName();
        $paramValues = $env->newParamName();
        $paramAttribute = $env->newParamName();

        $subQuery = $env->cloneQueryBuilder();

        $rootAliases = $subQuery->getRootAliases();
        $subQuery
            ->innerJoin($rootAliases[0].'.valueSet', $paramVs)
            ->innerJoin($paramVs.'.values', $paramValues)
            ->innerJoin($paramValues.'.attribute', $paramAttribute)
            ->andWhere($paramAttribute.'.name = :'.$paramName);

        switch ($this->operator) {
            case 'equals':
                $subQuery->andWhere($paramValues.'.value = :'.$paramValue);
                $qb->setParameter($paramValue, $this->getRight()->getValue());
                break;
            case 'notequals':
                $subQuery->andWhere($paramValues.'.value <> :'.$paramValue);
                $qb->setParameter($paramValue, $this->getRight()->getValue());
                break;
            case 'contains':
                $subQuery->andWhere($paramValues.'.value LIKE :'.$paramValue);
                $qb->setParameter($paramValue, '%'. $this->getRight()->getValue().'%');
                break;
        }

        $qb
            ->andWhere($qb->expr()->in('a', $subQuery->getDQL()))
            ->setParameter($paramName, $this->getAttribute())
        ;
    }
24030
protected function _sortResult(array &$result, $sort = 'asort')
    {
        // Sorting
        switch ($sort) {
            case 'asort':
                asort($result);
                break;

            case 'ksort':
                ksort($result);
                break;

            case 'natsort':
                natsort($result);
                break;

            default:
                $sort($result);
        }
    }
1211733
protected function handleGlobalCommands(EnvironmentInterface $environment)
    {
        $dataDefinition = $environment->getDataDefinition();
        $backendView    = $dataDefinition->getDefinition(Contao2BackendViewDefinitionInterface::NAME);
        $globalCommands = $backendView->getGlobalCommands();

        $globalCommands->clearCommands();

        $backCommand = new BackCommand();
        $backCommand->setDisabled(false);
        $globalCommands->addCommand($backCommand);
    }
1320390
protected function isAddingAllowed(EnvironmentInterface $environment)
    {
        $inputProvider = $environment->getInputProvider();

        // No manual sorting property defined, no need to add it to the clipboard.
        // Or we already have an after or into attribute, a handler can pick it up.
        return (!ViewHelpers::getManualSortingProperty($environment)
                || $inputProvider->hasParameter('after')
                || $inputProvider->hasParameter('into')
        );
    }