<commit_before><?php

namespace Oro\Bundle\WorkflowBundle\Datagrid;

use Symfony\Component\Translation\TranslatorInterface;

use Oro\Bundle\DataGridBundle\Datagrid\Common\DatagridConfiguration;
use Oro\Bundle\DataGridBundle\Event\BuildBefore;
use Oro\Bundle\WorkflowBundle\Entity\WorkflowStep;
use Oro\Bundle\WorkflowBundle\Helper\WorkflowTranslationHelper;

/**
 * Replaces translation keys (Workflow Step Label) with their translated values
 */
class WorkflowDatagridLabelListener
{
    /**
     * @var TranslatorInterface
     */
    protected $translator;

    /**
     * @param TranslatorInterface $translator
     */
    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    /**
     * @param BuildBefore $event
     */
    public function onBuildBefore(BuildBefore $event)
    {
        $configuration = $event->getConfig();
        $columns = $this->getWorkflowLabelColumns($configuration);
        if (count($columns)) {
            foreach ($columns as $columnName) {
                $this->fixColumnDefinition($columnName, $configuration);
                $this->fixColumnFilter($columnName, $configuration);
                $this->fixColumnSorter($columnName, $configuration);
            }
        }
    }

    /**
     * Used only internally, please use WorkflowTranslationHelper or '@translator.default'
     *
     * @param $id
     *
     * @return string
     */
    public function trans($id)
    {
        return $this->translator->trans($id, [], WorkflowTranslationHelper::TRANSLATION_DOMAIN);
    }

    /**
     * @param DatagridConfiguration $configuration
     *
     * @return array
     */
    private function getWorkflowLabelColumns(DatagridConfiguration $configuration)
    {
        $columnAliases = $configuration->offsetGetByPath('[source][query_config][column_aliases]');
        $columns = [];
        if (count($columnAliases)) {
            foreach ($columnAliases as $key => $alias) {
                if (strstr($key, WorkflowStep::class . '::label') !== false) {
                    $columns[] = $alias;
                    continue;
                }
            }
        }

        return $columns;
    }

    /**
     * @param $columnName
     * @param DatagridConfiguration $configuration
     */
    private function fixColumnDefinition($columnName, DatagridConfiguration $configuration)
    {
        $path = sprintf('[columns][%s]', $columnName);
        $column = $configuration->offsetGetByPath($path);
        $column['frontend_type'] = 'html';
        $column['type'] = 'callback';
        $column['callable'] = [$this, "trans"];
        $column['params'] = [$columnName];
        $configuration->offsetSetByPath($path, $column);
    }

    /**
     * @param $columnName
     * @param DatagridConfiguration $configuration
     */
    private function fixColumnFilter($columnName, DatagridConfiguration $configuration)
    {
        $filters = $configuration->offsetGetByPath('[filters][columns]');
        if (isset($filters[$columnName])) {
            unset($filters[$columnName]);
        }
        $configuration->offsetSetByPath('[filters][columns]', $filters);
    }

    /**
     * @param $columnName
     * @param DatagridConfiguration $configuration
     */
    private function fixColumnSorter($columnName, DatagridConfiguration $configuration)
    {
        $sorters = $configuration->offsetGetByPath('[sorters][columns]');
        if (isset($sorters[$columnName])) {
            unset($sorters[$columnName]);
        }
        $configuration->offsetSetByPath('[sorters][columns]', $sorters);
    }
}<commit_msg>BAP-12024: Update workflow related templates - Filters added by Workflow Step Label<commit_after><?php

namespace Oro\Bundle\WorkflowBundle\Datagrid;

use Symfony\Component\Translation\TranslatorInterface;

use Oro\Bundle\DataGridBundle\Exception\InvalidArgumentException;
use Oro\Bundle\DataGridBundle\Datagrid\Common\DatagridConfiguration;
use Oro\Bundle\DataGridBundle\Event\BuildBefore;
use Oro\Bundle\WorkflowBundle\Entity\WorkflowStep;
use Oro\Bundle\WorkflowBundle\Form\Type\WorkflowStepSelectType;
use Oro\Bundle\WorkflowBundle\Helper\WorkflowTranslationHelper;

/**
 * Replaces translation keys (Workflow Step Label) with their translated values
 */
class WorkflowDatagridLabelListener
{
    /**
     * @var TranslatorInterface
     */
    protected $translator;

    /**
     * @param TranslatorInterface $translator
     */
    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    /**
     * @param BuildBefore $event
     */
    public function onBuildBefore(BuildBefore $event)
    {
        $configuration = $event->getConfig();
        $columns = $this->getWorkflowLabelColumns($configuration);
        if (count($columns)) {
            foreach ($columns as $columnName) {
                $this->fixColumnDefinition($columnName, $configuration);
                $this->fixColumnFilter($columnName, $configuration);
                $this->fixColumnSorter($columnName, $configuration);
            }
        }
    }

    /**
     * Used only internally, please use WorkflowTranslationHelper or '@translator.default'
     *
     * @param $id
     *
     * @return string
     */
    public function trans($id)
    {
        return $this->translator->trans($id, [], WorkflowTranslationHelper::TRANSLATION_DOMAIN);
    }

    /**
     * @param DatagridConfiguration $configuration
     *
     * @return array
     */
    private function getWorkflowLabelColumns(DatagridConfiguration $configuration)
    {
        $columnAliases = $configuration->offsetGetByPath('[source][query_config][column_aliases]');
        $columns = [];
        if (count($columnAliases)) {
            foreach ($columnAliases as $key => $alias) {
                if (strstr($key, WorkflowStep::class . '::label') !== false) {
                    $columns[] = $alias;
                    continue;
                }
            }
        }

        return $columns;
    }

    /**
     * @param $columnName
     * @param DatagridConfiguration $configuration
     */
    private function fixColumnDefinition($columnName, DatagridConfiguration $configuration)
    {
        $path = sprintf('[columns][%s]', $columnName);
        $column = $configuration->offsetGetByPath($path);
        $column['frontend_type'] = 'html';
        $column['type'] = 'callback';
        $column['callable'] = [$this, "trans"];
        $column['params'] = [$columnName];
        $configuration->offsetSetByPath($path, $column);
    }

    /**
     * @param $columnName
     * @param DatagridConfiguration $configuration
     */
    private function fixColumnFilter($columnName, DatagridConfiguration $configuration)
    {
        $filters = $configuration->offsetGetByPath('[filters][columns]');
        $label = $configuration->offsetGetByPath(sprintf('[columns][%s][label]', $columnName));
        $label = $label ?: 'oro.workflow.workflowstep.grid.label';
        if (isset($filters[$columnName])) {
            $tableAlias = $this->getTableAliasForColumnName($columnName, $configuration);
            $filters[$columnName] = [
                'label' => $label,
                'type' => 'entity',
                'data_name' => $tableAlias . '.id',
                'options' => [
                    'field_type' => WorkflowStepSelectType::NAME,
                    'field_options' => [
                        'workflow_entity_class' => $this->getRootEntityClass($configuration),
                        'multiple' => true
                    ]
                ]
            ];
        }
        $configuration->offsetSetByPath('[filters][columns]', $filters);
    }

    /**
     * @param $columnName
     * @param DatagridConfiguration $configuration
     */
    private function fixColumnSorter($columnName, DatagridConfiguration $configuration)
    {
        $sorters = $configuration->offsetGetByPath('[sorters][columns]');
        if (isset($sorters[$columnName])) {
            unset($sorters[$columnName]);
        }
        $configuration->offsetSetByPath('[sorters][columns]', $sorters);
    }

    /**
     * @param $columnName
     * @param DatagridConfiguration $configuration
     *
     * @throws InvalidArgumentException
     *
     * @return mixed
     */
    private function getTableAliasForColumnName($columnName, DatagridConfiguration $configuration)
    {
        $selects = $configuration->offsetGetByPath('[source][query][select]');
        foreach ($selects as $select) {
            $matches = [];
            if (preg_match('/^(.*)\.[a-zA-Z0-9_]+\sas\s' . $columnName . '$/', $select, $matches)) {
                if ($matches && isset($matches[1])) {
                    return $matches[1];
                }
            }
        }

        throw new InvalidArgumentException(sprintf('Source table for "%s" column not found', $columnName));
    }

    /**
     * @param DatagridConfiguration $configuration
     *
     * @throws InvalidArgumentException
     *
     * @return string
     */
    private function getRootEntityClass(DatagridConfiguration $configuration)
    {
        $from = $configuration->offsetGetByPath('[source][query][from][0]');
        if ($from && isset($from['table'])) {
            return $from['table'];
        }

        throw new InvalidArgumentException('Unable to find root entity class');
    }
}
{'fraction_non_alphanumeric': 0.13206147323794382, 'fraction_numerical': 0.0010598834128245894, 'mean_word_length': 2.5851063829787235, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 48, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5108721', 'n_tokens_mistral': 2579, 'n_tokens_neox': 2518, 'n_words': 441}