diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ef88b16..6be4666 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,7 +7,7 @@ on: env: fail-fast: true PHPUNIT_FLAGS: "-v" - SYMFONY_DEPRECATIONS_HELPER: 40 + SYMFONY_DEPRECATIONS_HELPER: weak jobs: build: @@ -17,11 +17,13 @@ jobs: fail-fast: false matrix: include: - - { php: 7.3, mongodb: 3.6, symfony: "4.4.*", composer-flags: '--prefer-stable'} - { php: 7.4, mongodb: 3.6, symfony: "5.4.*", composer-flags: '--prefer-stable'} - - { php: 8.0, mongodb: 3.6, symfony: "5.4.*", composer-flags: '--prefer-stable'} - - { php: 8.0, mongodb: 3.6, symfony: "6.0.*", composer-flags: '--prefer-stable'} - - { php: 8.1, mongodb: 3.6, symfony: "6.1.*@dev", composer-flags: '' } + - { php: 8.2, mongodb: 3.6, symfony: "5.4.*", composer-flags: '--prefer-stable'} + - { php: 8.2, mongodb: 3.6, symfony: "6.0.*", composer-flags: '--prefer-stable'} + - { php: 8.2, mongodb: 3.6, symfony: "6.1.*", composer-flags: '--prefer-stable' } + - { php: 8.2, mongodb: 3.6, symfony: "6.2.*", composer-flags: '--prefer-stable' } + - { php: 8.2, mongodb: 3.6, symfony: "6.3.*@dev", composer-flags: '' } + services: mongo: image: mongo:${{ matrix.mongodb }} @@ -38,25 +40,25 @@ jobs: ini-values: date.timezone="Europe/Paris" coverage: xdebug tools: "composer:v2,flex" - + - name: Show PHP version run: php -v && composer -V - + - name: Download Composer cache dependencies from cache id: composer-cache run: echo "::set-output name=dir::$(composer config cache-files-dir)" - + - name: "Require symfony/messenger" run: "composer require --dev symfony/doctrine-messenger --no-update" if: "${{ startsWith(matrix.symfony, '5.3') || startsWith(matrix.symfony, '5.4') }}" - + - name: Cache Composer dependencies uses: actions/cache@v2 with: path: ${{ steps.composer-cache.outputs.dir }} key: ${{ matrix.os }}-composer-${{ hashFiles('**/composer.json') }} restore-keys: ${{ matrix.os }}-composer- - + - name: Install dependencies run: | perl -pi -e 's/^}$/,"minimum-stability":"dev"}/' composer.json @@ -65,6 +67,6 @@ jobs: composer update ${{ matrix.composer-flags }} --prefer-dist env: SYMFONY_REQUIRE: "${{ matrix.symfony }}" - + - name: "Run PHPUnit Tests" run: "composer test" diff --git a/DependencyInjection/Compiler/FormDataExtractorPass.php b/DependencyInjection/Compiler/FormDataExtractorPass.php index 17eef28..9f9df51 100644 --- a/DependencyInjection/Compiler/FormDataExtractorPass.php +++ b/DependencyInjection/Compiler/FormDataExtractorPass.php @@ -2,9 +2,9 @@ namespace Lexik\Bundle\FormFilterBundle\DependencyInjection\Compiler; -use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Reference; /** * Add extraction methods to the data extraction service. @@ -16,13 +16,13 @@ class FormDataExtractorPass implements CompilerPassInterface /** * {@inheritdoc} */ - public function process(ContainerBuilder $container) + public function process(ContainerBuilder $container): void { if ($container->hasDefinition('lexik_form_filter.form_data_extractor')) { $definition = $container->getDefinition('lexik_form_filter.form_data_extractor'); foreach ($container->findTaggedServiceIds('lexik_form_filter.data_extraction_method') as $id => $attributes) { - $definition->addMethodCall('addMethod', array(new Reference($id))); + $definition->addMethodCall('addMethod', [new Reference($id)]); } } } diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 668b392..0876274 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -35,7 +35,7 @@ public function getConfigTreeBuilder(): TreeBuilder ->defaultValue('and') ->info('Defined the doctrine query builder method the bundle will use to add the entire filter condition.') ->validate() - ->ifNotInArray(array(null, 'and', 'or')) + ->ifNotInArray([null, 'and', 'or']) ->thenInvalid('Invalid value, please use "null", "and", "or".') ->end() ->end() @@ -44,7 +44,7 @@ public function getConfigTreeBuilder(): TreeBuilder ->defaultValue('text.starts') ->info('Default condition pattern for TextFilterType') ->validate() - ->ifNotInArray(array(null, 'text.equals', 'text.ends', 'text.contains', 'text.starts')) + ->ifNotInArray([null, 'text.equals', 'text.ends', 'text.contains', 'text.starts']) ->thenInvalid('Invalid value, please use "null", "text.contains", "text.starts", "text.ends", "text.equals".') ->end() ->end() diff --git a/DependencyInjection/LexikFormFilterExtension.php b/DependencyInjection/LexikFormFilterExtension.php index b174ad9..fe9e2f6 100644 --- a/DependencyInjection/LexikFormFilterExtension.php +++ b/DependencyInjection/LexikFormFilterExtension.php @@ -2,12 +2,13 @@ namespace Lexik\Bundle\FormFilterBundle\DependencyInjection; -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\Config\FileLocator; -use Symfony\Component\HttpKernel\DependencyInjection\Extension; -use Symfony\Component\DependencyInjection\Loader; use Lexik\Bundle\FormFilterBundle\DependencyInjection\Configuration; use Lexik\Bundle\FormFilterBundle\Filter\FilterOperands; +use Symfony\Component\Config\FileLocator; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Loader; +use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; +use Symfony\Component\HttpKernel\DependencyInjection\Extension; /** * This is the class that loads and manages your bundle configuration @@ -21,12 +22,12 @@ class LexikFormFilterExtension extends Extension /** * {@inheritDoc} */ - public function load(array $configs, ContainerBuilder $container) + public function load(array $configs, ContainerBuilder $container): void { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); - $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); + $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('services.xml'); $loader->load('form.xml'); @@ -40,7 +41,7 @@ public function load(array $configs, ContainerBuilder $container) $filterPrepareDef = $container->getDefinition('lexik_form_filter.filter_prepare'); $filterPrepareDef->addMethodCall( 'setForceCaseInsensitivity', - array($config['force_case_insensitivity']) + [$config['force_case_insensitivity']] ); } @@ -48,7 +49,7 @@ public function load(array $configs, ContainerBuilder $container) $filterPrepareDef = $container->getDefinition('lexik_form_filter.filter_prepare'); $filterPrepareDef->addMethodCall( 'setEncoding', - array($config['encoding']) + [$config['encoding']] ); } diff --git a/Event/FilterEvents.php b/Event/FilterEvents.php index 3a07cea..4a64eee 100644 --- a/Event/FilterEvents.php +++ b/Event/FilterEvents.php @@ -9,5 +9,5 @@ */ class FilterEvents { - const PREPARE = 'lexik_filter.prepare'; + public const PREPARE = 'lexik_filter.prepare'; } diff --git a/Event/GetFilterConditionEvent.php b/Event/GetFilterConditionEvent.php index 08699d0..5f95c1f 100644 --- a/Event/GetFilterConditionEvent.php +++ b/Event/GetFilterConditionEvent.php @@ -2,10 +2,10 @@ namespace Lexik\Bundle\FormFilterBundle\Event; -use Symfony\Contracts\EventDispatcher\Event; use Lexik\Bundle\FormFilterBundle\Filter\Condition\Condition; use Lexik\Bundle\FormFilterBundle\Filter\Condition\ConditionInterface; use Lexik\Bundle\FormFilterBundle\Filter\Query\QueryInterface; +use Symfony\Contracts\EventDispatcher\Event; /** * @author Jeremy Barthe @@ -42,8 +42,8 @@ class GetFilterConditionEvent extends Event public function __construct(QueryInterface $filterQuery, $field, $values) { $this->filterQuery = $filterQuery; - $this->field = $field; - $this->values = $values; + $this->field = $field; + $this->values = $values; } /** @@ -82,7 +82,7 @@ public function getValues() * @param string $expression * @param array $parameters */ - public function setCondition($expression, array $parameters = array()) + public function setCondition($expression, array $parameters = []) { $this->condition = new Condition($expression, $parameters); } diff --git a/Event/Listener/DoctrineApplyFilterListener.php b/Event/Listener/DoctrineApplyFilterListener.php index f7091c3..d10c432 100644 --- a/Event/Listener/DoctrineApplyFilterListener.php +++ b/Event/Listener/DoctrineApplyFilterListener.php @@ -2,8 +2,8 @@ namespace Lexik\Bundle\FormFilterBundle\Event\Listener; -use Doctrine\ORM\Query\Expr\Composite; use Doctrine\DBAL\Query\Expression\CompositeExpression; +use Doctrine\ORM\Query\Expr\Composite; use Lexik\Bundle\FormFilterBundle\Event\ApplyFilterConditionEvent; use Lexik\Bundle\FormFilterBundle\Filter\Condition\ConditionInterface; use Lexik\Bundle\FormFilterBundle\Filter\Condition\ConditionNodeInterface; @@ -42,7 +42,7 @@ public function onApplyFilterCondition(ApplyFilterConditionEvent $event) $qbAdapter = new DoctrineQueryBuilderAdapter($event->getQueryBuilder()); $conditionBuilder = $event->getConditionBuilder(); - $this->parameters = array(); + $this->parameters = []; $expression = $this->computeExpression($qbAdapter, $conditionBuilder->getRoot()); if (null !== $expression && $expression->count()) { @@ -50,7 +50,7 @@ public function onApplyFilterCondition(ApplyFilterConditionEvent $event) foreach ($this->parameters as $name => $value) { if (is_array($value)) { - list($value, $type) = $value; + [$value, $type] = $value; $qbAdapter->setParameter($name, $value, $type); } else { $qbAdapter->setParameter($name, $value); diff --git a/Event/Listener/DoctrineMongoDBApplyFilterListener.php b/Event/Listener/DoctrineMongoDBApplyFilterListener.php index be2338d..c9e4b06 100644 --- a/Event/Listener/DoctrineMongoDBApplyFilterListener.php +++ b/Event/Listener/DoctrineMongoDBApplyFilterListener.php @@ -41,7 +41,7 @@ protected function computeExpression(Builder $queryBuilder, ConditionNodeInterfa $method = ($node->getOperator() === ConditionNodeInterface::EXPR_AND) ? 'addAnd' : 'addOr'; - $expression = (null === $expr) ? $queryBuilder : $expr; + $expression = $expr ?? $queryBuilder; $count = 0; foreach ($node->getFields() as $condition) { diff --git a/Event/Listener/PrepareListener.php b/Event/Listener/PrepareListener.php index f82a070..46e6a6a 100644 --- a/Event/Listener/PrepareListener.php +++ b/Event/Listener/PrepareListener.php @@ -2,8 +2,13 @@ namespace Lexik\Bundle\FormFilterBundle\Event\Listener; -use Lexik\Bundle\FormFilterBundle\Event\PrepareEvent; use Doctrine\DBAL\Platforms\PostgreSqlPlatform; +use Doctrine\ODM\MongoDB\Query\Builder; +use Doctrine\ORM\QueryBuilder; +use Lexik\Bundle\FormFilterBundle\Event\PrepareEvent; +use Lexik\Bundle\FormFilterBundle\Filter\Doctrine\DBALQuery; +use Lexik\Bundle\FormFilterBundle\Filter\Doctrine\MongodbQuery; +use Lexik\Bundle\FormFilterBundle\Filter\Doctrine\ORMQuery; /** * Prepare listener event @@ -41,11 +46,11 @@ public function getForceCaseInsensitivity($qb) return $this->forceCaseInsensitivity; } - if (class_exists('\Doctrine\ORM\QueryBuilder') && $qb instanceof \Doctrine\ORM\QueryBuilder) { + if (class_exists('\\' . QueryBuilder::class) && $qb instanceof QueryBuilder) { return ($qb->getEntityManager()->getConnection()->getDatabasePlatform() instanceof PostgreSqlPlatform); } - if (class_exists('\Doctrine\DBAL\Query\QueryBuilder') && $qb instanceof \Doctrine\DBAL\Query\QueryBuilder) { + if (class_exists('\\' . \Doctrine\DBAL\Query\QueryBuilder::class) && $qb instanceof \Doctrine\DBAL\Query\QueryBuilder) { return ($qb->getConnection()->getDatabasePlatform() instanceof PostgreSqlPlatform); } } @@ -79,11 +84,7 @@ public function onFilterBuilderPrepare(PrepareEvent $event) { $qb = $event->getQueryBuilder(); - $queryClasses = array( - 'Doctrine\ORM\QueryBuilder' => 'Lexik\Bundle\FormFilterBundle\Filter\Doctrine\ORMQuery', - 'Doctrine\DBAL\Query\QueryBuilder' => 'Lexik\Bundle\FormFilterBundle\Filter\Doctrine\DBALQuery', - 'Doctrine\ODM\MongoDB\Query\Builder' => 'Lexik\Bundle\FormFilterBundle\Filter\Doctrine\MongodbQuery', - ); + $queryClasses = [QueryBuilder::class => ORMQuery::class, \Doctrine\DBAL\Query\QueryBuilder::class => DBALQuery::class, Builder::class => MongodbQuery::class]; foreach ($queryClasses as $builderClass => $queryClass) { if (class_exists($builderClass) && $qb instanceof $builderClass) { diff --git a/Event/PrepareEvent.php b/Event/PrepareEvent.php index 6f9b78f..c80a248 100644 --- a/Event/PrepareEvent.php +++ b/Event/PrepareEvent.php @@ -2,8 +2,8 @@ namespace Lexik\Bundle\FormFilterBundle\Event; -use Symfony\Contracts\EventDispatcher\Event; use Lexik\Bundle\FormFilterBundle\Filter\Query\QueryInterface; +use Symfony\Contracts\EventDispatcher\Event; /** * Get alias and expression builder for filter builder diff --git a/Event/Subscriber/AbstractDoctrineSubscriber.php b/Event/Subscriber/AbstractDoctrineSubscriber.php index e2b2cba..b8ba245 100644 --- a/Event/Subscriber/AbstractDoctrineSubscriber.php +++ b/Event/Subscriber/AbstractDoctrineSubscriber.php @@ -2,11 +2,11 @@ namespace Lexik\Bundle\FormFilterBundle\Event\Subscriber; -use Lexik\Bundle\FormFilterBundle\Filter\FilterOperands; -use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\BooleanFilterType; -use Lexik\Bundle\FormFilterBundle\Event\GetFilterConditionEvent; use Doctrine\DBAL\Connection; use Doctrine\DBAL\Types\Types; +use Lexik\Bundle\FormFilterBundle\Event\GetFilterConditionEvent; +use Lexik\Bundle\FormFilterBundle\Filter\FilterOperands; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\BooleanFilterType; /** * Provide Doctrine ORM and DBAL filters. @@ -21,7 +21,7 @@ abstract class AbstractDoctrineSubscriber */ public function filterValue(GetFilterConditionEvent $event) { - $expr = $event->getFilterQuery()->getExpr(); + $expr = $event->getFilterQuery()->getExpr(); $values = $event->getValues(); if ('' !== $values['value'] && null !== $values['value']) { @@ -29,13 +29,13 @@ public function filterValue(GetFilterConditionEvent $event) if (is_array($values['value']) && sizeof($values['value']) > 0) { $event->setCondition( - $expr->in($event->getField(), ':'.$paramName), - array($paramName => array($values['value'], Connection::PARAM_STR_ARRAY)) + $expr->in($event->getField(), ':' . $paramName), + [$paramName => [$values['value'], Connection::PARAM_STR_ARRAY]] ); } elseif (!is_array($values['value'])) { $event->setCondition( - $expr->eq($event->getField(), ':'.$paramName), - array($paramName => array($values['value'], Types::STRING)) + $expr->eq($event->getField(), ':' . $paramName), + [$paramName => [$values['value'], Types::STRING]] ); } } @@ -46,7 +46,7 @@ public function filterValue(GetFilterConditionEvent $event) */ public function filterBoolean(GetFilterConditionEvent $event) { - $expr = $event->getFilterQuery()->getExpr(); + $expr = $event->getFilterQuery()->getExpr(); $values = $event->getValues(); if (!empty($values['value'])) { @@ -55,8 +55,8 @@ public function filterBoolean(GetFilterConditionEvent $event) $value = (bool) (BooleanFilterType::VALUE_YES == $values['value']); $event->setCondition( - $expr->eq($event->getField(), ':'.$paramName), - array($paramName => array($value, Types::BOOLEAN)) + $expr->eq($event->getField(), ':' . $paramName), + [$paramName => [$value, Types::BOOLEAN]] ); } } @@ -66,15 +66,15 @@ public function filterBoolean(GetFilterConditionEvent $event) */ public function filterCheckbox(GetFilterConditionEvent $event) { - $expr = $event->getFilterQuery()->getExpr(); + $expr = $event->getFilterQuery()->getExpr(); $values = $event->getValues(); if (!empty($values['value'])) { $paramName = $this->generateParameterName($event->getField()); $event->setCondition( - $expr->eq($event->getField(), ':'.$paramName), - array($paramName => array($values['value'], Types::STRING)) + $expr->eq($event->getField(), ':' . $paramName), + [$paramName => [$values['value'], Types::STRING]] ); } } @@ -84,15 +84,15 @@ public function filterCheckbox(GetFilterConditionEvent $event) */ public function filterDate(GetFilterConditionEvent $event) { - $expr = $event->getFilterQuery()->getExpr(); + $expr = $event->getFilterQuery()->getExpr(); $values = $event->getValues(); if ($values['value'] instanceof \DateTime) { $paramName = $this->generateParameterName($event->getField()); $event->setCondition( - $expr->eq($event->getField(), ':'.$paramName), - array($paramName => array($values['value'], Types::DATE_MUTABLE)) + $expr->eq($event->getField(), ':' . $paramName), + [$paramName => [$values['value'], Types::DATE_MUTABLE]] ); } } @@ -102,9 +102,9 @@ public function filterDate(GetFilterConditionEvent $event) */ public function filterDateRange(GetFilterConditionEvent $event) { - $expr = $event->getFilterQuery()->getExpressionBuilder(); + $expr = $event->getFilterQuery()->getExpressionBuilder(); $values = $event->getValues(); - $value = $values['value']; + $value = $values['value']; if (isset($value['left_date'][0]) || isset($value['right_date'][0])) { $event->setCondition($expr->dateInRange($event->getField(), $value['left_date'][0], $value['right_date'][0])); @@ -116,15 +116,15 @@ public function filterDateRange(GetFilterConditionEvent $event) */ public function filterDateTime(GetFilterConditionEvent $event) { - $expr = $event->getFilterQuery()->getExpr(); + $expr = $event->getFilterQuery()->getExpr(); $values = $event->getValues(); if ($values['value'] instanceof \DateTime) { $paramName = $this->generateParameterName($event->getField()); $event->setCondition( - $expr->eq($event->getField(), ':'.$paramName), - array($paramName => array($values['value'], Types::DATETIME_MUTABLE)) + $expr->eq($event->getField(), ':' . $paramName), + [$paramName => [$values['value'], Types::DATETIME_MUTABLE]] ); } } @@ -134,9 +134,9 @@ public function filterDateTime(GetFilterConditionEvent $event) */ public function filterDateTimeRange(GetFilterConditionEvent $event) { - $expr = $event->getFilterQuery()->getExpressionBuilder(); + $expr = $event->getFilterQuery()->getExpressionBuilder(); $values = $event->getValues(); - $value = $values['value']; + $value = $values['value']; if (isset($value['left_datetime'][0]) || $value['right_datetime'][0]) { $event->setCondition($expr->datetimeInRange($event->getField(), $value['left_datetime'][0], $value['right_datetime'][0])); @@ -148,7 +148,7 @@ public function filterDateTimeRange(GetFilterConditionEvent $event) */ public function filterNumber(GetFilterConditionEvent $event) { - $expr = $event->getFilterQuery()->getExpr(); + $expr = $event->getFilterQuery()->getExpr(); $values = $event->getValues(); if ('' !== $values['value'] && null !== $values['value']) { @@ -157,8 +157,8 @@ public function filterNumber(GetFilterConditionEvent $event) $op = empty($values['condition_operator']) ? FilterOperands::OPERATOR_EQUAL : $values['condition_operator']; $event->setCondition( - $expr->$op($event->getField(), ':'.$paramName), - array($paramName => array($values['value'], is_int($values['value']) ? Types::INTEGER : Types::FLOAT)) + $expr->$op($event->getField(), ':' . $paramName), + [$paramName => [$values['value'], is_int($values['value']) ? Types::INTEGER : Types::FLOAT]] ); } } @@ -168,30 +168,29 @@ public function filterNumber(GetFilterConditionEvent $event) */ public function filterNumberRange(GetFilterConditionEvent $event) { - $expr = $event->getFilterQuery()->getExpr(); + $expr = $event->getFilterQuery()->getExpr(); $values = $event->getValues(); - $value = $values['value']; + $value = $values['value']; $expression = $expr->andX(); - $params = array(); + $params = []; if (isset($value['left_number'][0])) { $hasSelector = (FilterOperands::OPERAND_SELECTOR === $value['left_number']['condition_operator']); if (!$hasSelector && isset($value['left_number'][0])) { $leftValue = $value['left_number'][0]; - $leftCond = $value['left_number']['condition_operator']; - + $leftCond = $value['left_number']['condition_operator']; } elseif ($hasSelector && isset($value['left_number'][0]['text'])) { $leftValue = $value['left_number'][0]['text']; - $leftCond = $value['left_number'][0]['condition_operator']; + $leftCond = $value['left_number'][0]['condition_operator']; } if (isset($leftValue, $leftCond)) { $leftParamName = sprintf('p_%s_left', str_replace('.', '_', $event->getField())); - $expression->add($expr->$leftCond($event->getField(), ':'.$leftParamName)); - $params[$leftParamName] = array($leftValue, is_int($leftValue) ? Types::INTEGER : Types::FLOAT); + $expression->add($expr->$leftCond($event->getField(), ':' . $leftParamName)); + $params[$leftParamName] = [$leftValue, is_int($leftValue) ? Types::INTEGER : Types::FLOAT]; } } @@ -200,18 +199,17 @@ public function filterNumberRange(GetFilterConditionEvent $event) if (!$hasSelector && isset($value['right_number'][0])) { $rightValue = $value['right_number'][0]; - $rightCond = $value['right_number']['condition_operator']; - + $rightCond = $value['right_number']['condition_operator']; } elseif ($hasSelector && isset($value['right_number'][0]['text'])) { $rightValue = $value['right_number'][0]['text']; - $rightCond = $value['right_number'][0]['condition_operator']; + $rightCond = $value['right_number'][0]['condition_operator']; } if (isset($rightValue, $rightCond)) { $rightParamName = sprintf('p_%s_right', str_replace('.', '_', $event->getField())); - $expression->add($expr->$rightCond($event->getField(), ':'.$rightParamName)); - $params[$rightParamName] = array($rightValue, is_int($rightValue) ? Types::INTEGER : Types::FLOAT); + $expression->add($expr->$rightCond($event->getField(), ':' . $rightParamName)); + $params[$rightParamName] = [$rightValue, is_int($rightValue) ? Types::INTEGER : Types::FLOAT]; } } @@ -225,7 +223,7 @@ public function filterNumberRange(GetFilterConditionEvent $event) */ public function filterText(GetFilterConditionEvent $event) { - $expr = $event->getFilterQuery()->getExpressionBuilder(); + $expr = $event->getFilterQuery()->getExpressionBuilder(); $values = $event->getValues(); if ('' !== $values['value'] && null !== $values['value']) { diff --git a/Event/Subscriber/DoctrineDBALSubscriber.php b/Event/Subscriber/DoctrineDBALSubscriber.php index ee80158..b469a62 100644 --- a/Event/Subscriber/DoctrineDBALSubscriber.php +++ b/Event/Subscriber/DoctrineDBALSubscriber.php @@ -14,40 +14,39 @@ class DoctrineDBALSubscriber extends AbstractDoctrineSubscriber implements Event /** * @return array */ - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { - return array( + return [ // Lexik form filter types - 'lexik_form_filter.apply.dbal.filter_boolean' => array('filterBoolean'), - 'lexik_form_filter.apply.dbal.filter_checkbox' => array('filterCheckbox'), - 'lexik_form_filter.apply.dbal.filter_choice' => array('filterValue'), - 'lexik_form_filter.apply.dbal.filter_date' => array('filterDate'), - 'lexik_form_filter.apply.dbal.filter_date_range' => array('filterDateRange'), - 'lexik_form_filter.apply.dbal.filter_datetime' => array('filterDateTime'), - 'lexik_form_filter.apply.dbal.filter_datetime_range' => array('filterDateTimeRange'), - 'lexik_form_filter.apply.dbal.filter_number' => array('filterNumber'), - 'lexik_form_filter.apply.dbal.filter_number_range' => array('filterNumberRange'), - 'lexik_form_filter.apply.dbal.filter_text' => array('filterText'), - + 'lexik_form_filter.apply.dbal.filter_boolean' => ['filterBoolean'], + 'lexik_form_filter.apply.dbal.filter_checkbox' => ['filterCheckbox'], + 'lexik_form_filter.apply.dbal.filter_choice' => ['filterValue'], + 'lexik_form_filter.apply.dbal.filter_date' => ['filterDate'], + 'lexik_form_filter.apply.dbal.filter_date_range' => ['filterDateRange'], + 'lexik_form_filter.apply.dbal.filter_datetime' => ['filterDateTime'], + 'lexik_form_filter.apply.dbal.filter_datetime_range' => ['filterDateTimeRange'], + 'lexik_form_filter.apply.dbal.filter_number' => ['filterNumber'], + 'lexik_form_filter.apply.dbal.filter_number_range' => ['filterNumberRange'], + 'lexik_form_filter.apply.dbal.filter_text' => ['filterText'], // Symfony field types - 'lexik_form_filter.apply.dbal.text' => array('filterText'), - 'lexik_form_filter.apply.dbal.email' => array('filterValue'), - 'lexik_form_filter.apply.dbal.integer' => array('filterValue'), - 'lexik_form_filter.apply.dbal.money' => array('filterValue'), - 'lexik_form_filter.apply.dbal.number' => array('filterValue'), - 'lexik_form_filter.apply.dbal.percent' => array('filterValue'), - 'lexik_form_filter.apply.dbal.search' => array('filterValue'), - 'lexik_form_filter.apply.dbal.url' => array('filterValue'), - 'lexik_form_filter.apply.dbal.choice' => array('filterValue'), - 'lexik_form_filter.apply.dbal.country' => array('filterValue'), - 'lexik_form_filter.apply.dbal.language' => array('filterValue'), - 'lexik_form_filter.apply.dbal.locale' => array('filterValue'), - 'lexik_form_filter.apply.dbal.timezone' => array('filterValue'), - 'lexik_form_filter.apply.dbal.date' => array('filterDate'), - 'lexik_form_filter.apply.dbal.datetime' => array('filterDate'), - 'lexik_form_filter.apply.dbal.birthday' => array('filterDate'), - 'lexik_form_filter.apply.dbal.checkbox' => array('filterValue'), - 'lexik_form_filter.apply.dbal.radio' => array('filterValue'), - ); + 'lexik_form_filter.apply.dbal.text' => ['filterText'], + 'lexik_form_filter.apply.dbal.email' => ['filterValue'], + 'lexik_form_filter.apply.dbal.integer' => ['filterValue'], + 'lexik_form_filter.apply.dbal.money' => ['filterValue'], + 'lexik_form_filter.apply.dbal.number' => ['filterValue'], + 'lexik_form_filter.apply.dbal.percent' => ['filterValue'], + 'lexik_form_filter.apply.dbal.search' => ['filterValue'], + 'lexik_form_filter.apply.dbal.url' => ['filterValue'], + 'lexik_form_filter.apply.dbal.choice' => ['filterValue'], + 'lexik_form_filter.apply.dbal.country' => ['filterValue'], + 'lexik_form_filter.apply.dbal.language' => ['filterValue'], + 'lexik_form_filter.apply.dbal.locale' => ['filterValue'], + 'lexik_form_filter.apply.dbal.timezone' => ['filterValue'], + 'lexik_form_filter.apply.dbal.date' => ['filterDate'], + 'lexik_form_filter.apply.dbal.datetime' => ['filterDate'], + 'lexik_form_filter.apply.dbal.birthday' => ['filterDate'], + 'lexik_form_filter.apply.dbal.checkbox' => ['filterValue'], + 'lexik_form_filter.apply.dbal.radio' => ['filterValue'], + ]; } } diff --git a/Event/Subscriber/DoctrineMongodbSubscriber.php b/Event/Subscriber/DoctrineMongodbSubscriber.php index 99749db..fd68ae3 100644 --- a/Event/Subscriber/DoctrineMongodbSubscriber.php +++ b/Event/Subscriber/DoctrineMongodbSubscriber.php @@ -3,8 +3,8 @@ namespace Lexik\Bundle\FormFilterBundle\Event\Subscriber; use Doctrine\Common\Collections\Collection; -use Doctrine\ODM\MongoDB\Query\Expr; use Doctrine\ODM\MongoDB\Query\Builder; +use Doctrine\ODM\MongoDB\Query\Expr; use Lexik\Bundle\FormFilterBundle\Event\GetFilterConditionEvent; use Lexik\Bundle\FormFilterBundle\Filter\FilterOperands; use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\BooleanFilterType; @@ -18,42 +18,41 @@ class DoctrineMongodbSubscriber implements EventSubscriberInterface /** * @return array */ - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { - return array( + return [ // Lexik form filter types - 'lexik_form_filter.apply.mongodb.filter_boolean' => array('filterBoolean'), - 'lexik_form_filter.apply.mongodb.filter_checkbox' => array('filterCheckbox'), - 'lexik_form_filter.apply.mongodb.filter_choice' => array('filterValue'), - 'lexik_form_filter.apply.mongodb.filter_date' => array('filterDate'), - 'lexik_form_filter.apply.mongodb.filter_date_range' => array('filterDateRange'), - 'lexik_form_filter.apply.mongodb.filter_datetime' => array('filterDateTime'), - 'lexik_form_filter.apply.mongodb.filter_datetime_range' => array('filterDateTimeRange'), - 'lexik_form_filter.apply.mongodb.filter_number' => array('filterNumber'), - 'lexik_form_filter.apply.mongodb.filter_number_range' => array('filterNumberRange'), - 'lexik_form_filter.apply.mongodb.filter_text' => array('filterText'), - 'lexik_form_filter.apply.mongodb.filter_document' => array('filterDocument'), - + 'lexik_form_filter.apply.mongodb.filter_boolean' => ['filterBoolean'], + 'lexik_form_filter.apply.mongodb.filter_checkbox' => ['filterCheckbox'], + 'lexik_form_filter.apply.mongodb.filter_choice' => ['filterValue'], + 'lexik_form_filter.apply.mongodb.filter_date' => ['filterDate'], + 'lexik_form_filter.apply.mongodb.filter_date_range' => ['filterDateRange'], + 'lexik_form_filter.apply.mongodb.filter_datetime' => ['filterDateTime'], + 'lexik_form_filter.apply.mongodb.filter_datetime_range' => ['filterDateTimeRange'], + 'lexik_form_filter.apply.mongodb.filter_number' => ['filterNumber'], + 'lexik_form_filter.apply.mongodb.filter_number_range' => ['filterNumberRange'], + 'lexik_form_filter.apply.mongodb.filter_text' => ['filterText'], + 'lexik_form_filter.apply.mongodb.filter_document' => ['filterDocument'], // Symfony types - 'lexik_form_filter.apply.mongodb.text' => array('filterText'), - 'lexik_form_filter.apply.mongodb.email' => array('filterValue'), - 'lexik_form_filter.apply.mongodb.integer' => array('filterValue'), - 'lexik_form_filter.apply.mongodb.money' => array('filterValue'), - 'lexik_form_filter.apply.mongodb.number' => array('filterValue'), - 'lexik_form_filter.apply.mongodb.percent' => array('filterValue'), - 'lexik_form_filter.apply.mongodb.search' => array('filterValue'), - 'lexik_form_filter.apply.mongodb.url' => array('filterValue'), - 'lexik_form_filter.apply.mongodb.choice' => array('filterValue'), - 'lexik_form_filter.apply.mongodb.country' => array('filterValue'), - 'lexik_form_filter.apply.mongodb.language' => array('filterValue'), - 'lexik_form_filter.apply.mongodb.locale' => array('filterValue'), - 'lexik_form_filter.apply.mongodb.timezone' => array('filterValue'), - 'lexik_form_filter.apply.mongodb.date' => array('filterDate'), - 'lexik_form_filter.apply.mongodb.datetime' => array('filterDate'), - 'lexik_form_filter.apply.mongodb.birthday' => array('filterDate'), - 'lexik_form_filter.apply.mongodb.checkbox' => array('filterValue'), - 'lexik_form_filter.apply.mongodb.radio' => array('filterValue'), - ); + 'lexik_form_filter.apply.mongodb.text' => ['filterText'], + 'lexik_form_filter.apply.mongodb.email' => ['filterValue'], + 'lexik_form_filter.apply.mongodb.integer' => ['filterValue'], + 'lexik_form_filter.apply.mongodb.money' => ['filterValue'], + 'lexik_form_filter.apply.mongodb.number' => ['filterValue'], + 'lexik_form_filter.apply.mongodb.percent' => ['filterValue'], + 'lexik_form_filter.apply.mongodb.search' => ['filterValue'], + 'lexik_form_filter.apply.mongodb.url' => ['filterValue'], + 'lexik_form_filter.apply.mongodb.choice' => ['filterValue'], + 'lexik_form_filter.apply.mongodb.country' => ['filterValue'], + 'lexik_form_filter.apply.mongodb.language' => ['filterValue'], + 'lexik_form_filter.apply.mongodb.locale' => ['filterValue'], + 'lexik_form_filter.apply.mongodb.timezone' => ['filterValue'], + 'lexik_form_filter.apply.mongodb.date' => ['filterDate'], + 'lexik_form_filter.apply.mongodb.datetime' => ['filterDate'], + 'lexik_form_filter.apply.mongodb.birthday' => ['filterDate'], + 'lexik_form_filter.apply.mongodb.checkbox' => ['filterValue'], + 'lexik_form_filter.apply.mongodb.radio' => ['filterValue'], + ]; } /** @@ -68,7 +67,6 @@ public function filterValue(GetFilterConditionEvent $event) if ('' !== $values['value'] && null !== $values['value']) { if (is_array($values['value']) && sizeof($values['value']) > 0) { $event->setCondition($expr->field($event->getField())->in($values['value'])); - } elseif (!is_array($values['value'])) { $event->setCondition($expr->field($event->getField())->equals($values['value'])); } @@ -134,10 +132,8 @@ public function filterDateRange(GetFilterConditionEvent $event) $value['left_date'][0], $value['right_date'][0] ); - } elseif (isset($value['left_date'][0])) { $expression = $qb->expr()->field($event->getField())->gte($value['left_date'][0]); - } elseif (isset($value['right_date'][0])) { $expression = $qb->expr()->field($event->getField())->lte($value['right_date'][0]); } @@ -176,10 +172,8 @@ public function filterDateTimeRange(GetFilterConditionEvent $event) $value['left_datetime'][0], $value['right_datetime'][0] ); - } elseif (isset($value['left_datetime'][0])) { $expression = $qb->expr()->field($event->getField())->gte($value['left_datetime'][0]); - } elseif (isset($value['right_datetime'][0])) { $expression = $qb->expr()->field($event->getField())->lte($value['right_datetime'][0]); } @@ -222,7 +216,6 @@ public function filterNumberRange(GetFilterConditionEvent $event) if (!$hasSelector && isset($value['left_number'][0])) { $leftValue = $value['left_number'][0]; $leftOp = $value['left_number']['condition_operator']; - } elseif ($hasSelector && isset($value['left_number'][0]['text'])) { $leftValue = $value['left_number'][0]['text']; $leftOp = $value['left_number'][0]['condition_operator']; @@ -235,7 +228,6 @@ public function filterNumberRange(GetFilterConditionEvent $event) if (!$hasSelector && isset($value['right_number'][0])) { $rightValue = $value['right_number'][0]; $rightOp = $value['right_number']['condition_operator']; - } elseif ($hasSelector && isset($value['right_number'][0]['text'])) { $rightValue = $value['right_number'][0]['text']; $rightOp = $value['right_number'][0]['condition_operator']; @@ -246,18 +238,16 @@ public function filterNumberRange(GetFilterConditionEvent $event) /** @var Expr $expr */ $expression = $qb->expr() ->field($event->getField()) - ->operator('$'.$leftOp, $leftValue) - ->operator('$'.$rightOp, $rightValue); + ->operator('$' . $leftOp, $leftValue) + ->operator('$' . $rightOp, $rightValue); $event->setCondition($expression); - } elseif (isset($leftValue, $leftOp)) { $method = $this->getExprOperatorMethod($leftOp); $event->setCondition( $qb->expr()->field($event->getField())->{$method}($leftValue) ); - } elseif (isset($rightValue, $rightOp)) { $method = $this->getExprOperatorMethod($rightOp); @@ -277,14 +267,9 @@ public function filterText(GetFilterConditionEvent $event) $values = $event->getValues(); if ('' !== $values['value'] && null !== $values['value']) { - $pattern = isset($values['condition_pattern']) ? $values['condition_pattern'] : FilterOperands::STRING_CONTAINS; + $pattern = $values['condition_pattern'] ?? FilterOperands::STRING_CONTAINS; - $patternValues = array( - FilterOperands::STRING_STARTS => new \MongoRegex('/^' . $values['value'] . '.*/i'), - FilterOperands::STRING_ENDS => new \MongoRegex('/.*' . $values['value'] . '$/i'), - FilterOperands::STRING_CONTAINS => new \MongoRegex('/.*' . $values['value'] . '.*/i'), - FilterOperands::STRING_EQUALS => $values['value'], - ); + $patternValues = [FilterOperands::STRING_STARTS => new \MongoRegex('/^' . $values['value'] . '.*/i'), FilterOperands::STRING_ENDS => new \MongoRegex('/.*' . $values['value'] . '$/i'), FilterOperands::STRING_CONTAINS => new \MongoRegex('/.*' . $values['value'] . '.*/i'), FilterOperands::STRING_EQUALS => $values['value']]; if (!isset($patternValues[$pattern])) { throw new \InvalidArgumentException('Wrong type constant in string like expression mapper.'); @@ -312,25 +297,23 @@ public function filterDocument(GetFilterConditionEvent $event) if ($multipleLevels) { // replace the form field name by the referenced document name $parts = explode('.', $field); - $parts[count($parts)-1] = $values['reference_name']; + $parts[count($parts) - 1] = $values['reference_name']; $field = implode('.', $parts); } if ($values['value'] instanceof Collection) { - $ids = array(); + $ids = []; foreach ($values['value'] as $object) { $ids[] = new \MongoId($object->getId()); } if (count($ids) > 0) { - $event->setCondition($expr->field($field.'.$id')->in($ids)); + $event->setCondition($expr->field($field . '.$id')->in($ids)); } - } elseif ($multipleLevels) { $id = new \MongoId($values['value']->getId()); - $event->setCondition($expr->field($field.'.$id')->equals($id)); - + $event->setCondition($expr->field($field . '.$id')->equals($id)); } else { if ('one' === $values['reference_type']) { $condition = $expr->field($field)->references($values['value']); @@ -349,13 +332,7 @@ public function filterDocument(GetFilterConditionEvent $event) */ private function getExprOperatorMethod($operator) { - $methods = array( - 'eq' => 'equals', - 'gt' => 'gt', - 'gte' => 'gte', - 'lt' => 'lt', - 'lte' => 'lte', - ); + $methods = ['eq' => 'equals', 'gt' => 'gt', 'gte' => 'gte', 'lt' => 'lt', 'lte' => 'lte']; if (!isset($methods[$operator])) { throw new \InvalidArgumentException('Wrong type constant for number operator.'); diff --git a/Event/Subscriber/DoctrineORMSubscriber.php b/Event/Subscriber/DoctrineORMSubscriber.php index 3db9776..b4fe739 100644 --- a/Event/Subscriber/DoctrineORMSubscriber.php +++ b/Event/Subscriber/DoctrineORMSubscriber.php @@ -6,8 +6,8 @@ use Doctrine\DBAL\Connection; use Doctrine\DBAL\Types\Types; use Doctrine\ORM\EntityManagerInterface; -use Doctrine\ORM\QueryBuilder; use Doctrine\ORM\Mapping\ClassMetadataInfo; +use Doctrine\ORM\QueryBuilder; use Lexik\Bundle\FormFilterBundle\Event\GetFilterConditionEvent; use Symfony\Component\EventDispatcher\EventSubscriberInterface; @@ -21,43 +21,42 @@ class DoctrineORMSubscriber extends AbstractDoctrineSubscriber implements EventS /** * @return array */ - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { - return array( + return [ // Lexik form filter types - 'lexik_form_filter.apply.orm.filter_boolean' => array('filterBoolean'), - 'lexik_form_filter.apply.orm.filter_checkbox' => array('filterCheckbox'), - 'lexik_form_filter.apply.orm.filter_choice' => array('filterValue'), - 'lexik_form_filter.apply.orm.filter_date' => array('filterDate'), - 'lexik_form_filter.apply.orm.filter_date_range' => array('filterDateRange'), - 'lexik_form_filter.apply.orm.filter_datetime' => array('filterDateTime'), - 'lexik_form_filter.apply.orm.filter_datetime_range' => array('filterDateTimeRange'), - 'lexik_form_filter.apply.orm.filter_entity' => array('filterEntity'), - 'lexik_form_filter.apply.orm.filter_number' => array('filterNumber'), - 'lexik_form_filter.apply.orm.filter_number_range' => array('filterNumberRange'), - 'lexik_form_filter.apply.orm.filter_text' => array('filterText'), - + 'lexik_form_filter.apply.orm.filter_boolean' => ['filterBoolean'], + 'lexik_form_filter.apply.orm.filter_checkbox' => ['filterCheckbox'], + 'lexik_form_filter.apply.orm.filter_choice' => ['filterValue'], + 'lexik_form_filter.apply.orm.filter_date' => ['filterDate'], + 'lexik_form_filter.apply.orm.filter_date_range' => ['filterDateRange'], + 'lexik_form_filter.apply.orm.filter_datetime' => ['filterDateTime'], + 'lexik_form_filter.apply.orm.filter_datetime_range' => ['filterDateTimeRange'], + 'lexik_form_filter.apply.orm.filter_entity' => ['filterEntity'], + 'lexik_form_filter.apply.orm.filter_number' => ['filterNumber'], + 'lexik_form_filter.apply.orm.filter_number_range' => ['filterNumberRange'], + 'lexik_form_filter.apply.orm.filter_text' => ['filterText'], // Symfony types - 'lexik_form_filter.apply.orm.text' => array('filterText'), - 'lexik_form_filter.apply.orm.email' => array('filterValue'), - 'lexik_form_filter.apply.orm.integer' => array('filterValue'), - 'lexik_form_filter.apply.orm.money' => array('filterValue'), - 'lexik_form_filter.apply.orm.number' => array('filterValue'), - 'lexik_form_filter.apply.orm.percent' => array('filterValue'), - 'lexik_form_filter.apply.orm.search' => array('filterValue'), - 'lexik_form_filter.apply.orm.url' => array('filterValue'), - 'lexik_form_filter.apply.orm.choice' => array('filterValue'), - 'lexik_form_filter.apply.orm.entity' => array('filterEntity'), - 'lexik_form_filter.apply.orm.country' => array('filterValue'), - 'lexik_form_filter.apply.orm.language' => array('filterValue'), - 'lexik_form_filter.apply.orm.locale' => array('filterValue'), - 'lexik_form_filter.apply.orm.timezone' => array('filterValue'), - 'lexik_form_filter.apply.orm.date' => array('filterDate'), - 'lexik_form_filter.apply.orm.datetime' => array('filterDate'), - 'lexik_form_filter.apply.orm.birthday' => array('filterDate'), - 'lexik_form_filter.apply.orm.checkbox' => array('filterValue'), - 'lexik_form_filter.apply.orm.radio' => array('filterValue'), - ); + 'lexik_form_filter.apply.orm.text' => ['filterText'], + 'lexik_form_filter.apply.orm.email' => ['filterValue'], + 'lexik_form_filter.apply.orm.integer' => ['filterValue'], + 'lexik_form_filter.apply.orm.money' => ['filterValue'], + 'lexik_form_filter.apply.orm.number' => ['filterValue'], + 'lexik_form_filter.apply.orm.percent' => ['filterValue'], + 'lexik_form_filter.apply.orm.search' => ['filterValue'], + 'lexik_form_filter.apply.orm.url' => ['filterValue'], + 'lexik_form_filter.apply.orm.choice' => ['filterValue'], + 'lexik_form_filter.apply.orm.entity' => ['filterEntity'], + 'lexik_form_filter.apply.orm.country' => ['filterValue'], + 'lexik_form_filter.apply.orm.language' => ['filterValue'], + 'lexik_form_filter.apply.orm.locale' => ['filterValue'], + 'lexik_form_filter.apply.orm.timezone' => ['filterValue'], + 'lexik_form_filter.apply.orm.date' => ['filterDate'], + 'lexik_form_filter.apply.orm.datetime' => ['filterDate'], + 'lexik_form_filter.apply.orm.birthday' => ['filterDate'], + 'lexik_form_filter.apply.orm.checkbox' => ['filterValue'], + 'lexik_form_filter.apply.orm.radio' => ['filterValue'], + ]; } /** @@ -66,7 +65,7 @@ public static function getSubscribedEvents() */ public function filterEntity(GetFilterConditionEvent $event) { - $expr = $event->getFilterQuery()->getExpr(); + $expr = $event->getFilterQuery()->getExpr(); $values = $event->getValues(); if (is_object($values['value'])) { @@ -91,7 +90,7 @@ public function filterEntity(GetFilterConditionEvent $event) } if ($values['value'] instanceof Collection) { - $ids = array(); + $ids = []; foreach ($values['value'] as $value) { $ids[] = $this->getEntityIdentifier($value, $queryBuilder->getEntityManager()); @@ -99,17 +98,14 @@ public function filterEntity(GetFilterConditionEvent $event) if (count($ids) > 0) { $event->setCondition( - $expr->in($filterField, ':'.$paramName), - array($paramName => array($ids, Connection::PARAM_INT_ARRAY)) + $expr->in($filterField, ':' . $paramName), + [$paramName => [$ids, Connection::PARAM_INT_ARRAY]] ); } } else { $event->setCondition( - $expr->eq($filterField, ':'.$paramName), - array($paramName => array( - $this->getEntityIdentifier($values['value'], $queryBuilder->getEntityManager()), - Types::INTEGER - )) + $expr->eq($filterField, ':' . $paramName), + [$paramName => [$this->getEntityIdentifier($values['value'], $queryBuilder->getEntityManager()), Types::INTEGER]] ); } } diff --git a/Filter/Condition/Condition.php b/Filter/Condition/Condition.php index ff272d8..ff2cbd6 100644 --- a/Filter/Condition/Condition.php +++ b/Filter/Condition/Condition.php @@ -33,7 +33,7 @@ class Condition implements ConditionInterface * @param string $expression * @param array $parameters */ - public function __construct($expression, array $parameters = array()) + public function __construct($expression, array $parameters = []) { $this->expression = $expression; $this->parameters = $parameters; diff --git a/Filter/Condition/ConditionBuilder.php b/Filter/Condition/ConditionBuilder.php index 9b95f25..a8d9323 100644 --- a/Filter/Condition/ConditionBuilder.php +++ b/Filter/Condition/ConditionBuilder.php @@ -21,7 +21,7 @@ public function root($operator) { $operator = strtolower($operator); - if (!in_array($operator, array(ConditionNodeInterface::EXPR_AND, ConditionNodeInterface::EXPR_OR))) { + if (!in_array($operator, [ConditionNodeInterface::EXPR_AND, ConditionNodeInterface::EXPR_OR])) { throw new \RuntimeException(sprintf('Invalid operator "%s", allowed values: and, or', $operator)); } diff --git a/Filter/Condition/ConditionNode.php b/Filter/Condition/ConditionNode.php index 1fec03a..059ce2d 100644 --- a/Filter/Condition/ConditionNode.php +++ b/Filter/Condition/ConditionNode.php @@ -37,8 +37,8 @@ public function __construct($operator, ConditionNodeInterface $parent = null) { $this->operator = $operator; $this->parent = $parent; - $this->children = array(); - $this->fields = array(); + $this->children = []; + $this->fields = []; } /** diff --git a/Filter/Condition/ConditionNodeInterface.php b/Filter/Condition/ConditionNodeInterface.php index 134fd96..36e3e0f 100644 --- a/Filter/Condition/ConditionNodeInterface.php +++ b/Filter/Condition/ConditionNodeInterface.php @@ -7,8 +7,8 @@ */ interface ConditionNodeInterface { - const EXPR_AND = 'and'; - const EXPR_OR = 'or'; + public const EXPR_AND = 'and'; + public const EXPR_OR = 'or'; /** * Start a OR sub expression. diff --git a/Filter/DataExtractor/FormDataExtractor.php b/Filter/DataExtractor/FormDataExtractor.php index 9fdc9ac..9b588ba 100644 --- a/Filter/DataExtractor/FormDataExtractor.php +++ b/Filter/DataExtractor/FormDataExtractor.php @@ -21,7 +21,7 @@ class FormDataExtractor implements FormDataExtractorInterface */ public function __construct() { - $this->methods = array(); + $this->methods = []; } /** diff --git a/Filter/DataExtractor/FormDataExtractorInterface.php b/Filter/DataExtractor/FormDataExtractorInterface.php index 471639c..919aa20 100644 --- a/Filter/DataExtractor/FormDataExtractorInterface.php +++ b/Filter/DataExtractor/FormDataExtractorInterface.php @@ -2,8 +2,8 @@ namespace Lexik\Bundle\FormFilterBundle\Filter\DataExtractor; -use Symfony\Component\Form\FormInterface; use Lexik\Bundle\FormFilterBundle\Filter\DataExtractor\Method\DataExtractionMethodInterface; +use Symfony\Component\Form\FormInterface; /** * diff --git a/Filter/DataExtractor/Method/DefaultExtractionMethod.php b/Filter/DataExtractor/Method/DefaultExtractionMethod.php index c6d2d3f..821e804 100644 --- a/Filter/DataExtractor/Method/DefaultExtractionMethod.php +++ b/Filter/DataExtractor/Method/DefaultExtractionMethod.php @@ -15,7 +15,7 @@ class DefaultExtractionMethod implements DataExtractionMethodInterface /** * {@inheritdoc} */ - public function getName() + public function getName(): string { return 'default'; } @@ -25,6 +25,6 @@ public function getName() */ public function extract(FormInterface $form) { - return array('value' => $form->getData()); + return ['value' => $form->getData()]; } } diff --git a/Filter/DataExtractor/Method/TextExtractionMethod.php b/Filter/DataExtractor/Method/TextExtractionMethod.php index 6657a04..7fded20 100644 --- a/Filter/DataExtractor/Method/TextExtractionMethod.php +++ b/Filter/DataExtractor/Method/TextExtractionMethod.php @@ -15,7 +15,7 @@ class TextExtractionMethod implements DataExtractionMethodInterface /** * {@inheritdoc} */ - public function getName() + public function getName(): string { return 'text'; } @@ -25,11 +25,11 @@ public function getName() */ public function extract(FormInterface $form) { - $data = $form->getData(); - $values = array('value' => array()); + $data = $form->getData(); + $values = ['value' => []]; if (array_key_exists('text', $data)) { - $values = array('value' => $data['text']); + $values = ['value' => $data['text']]; $values += $data; } diff --git a/Filter/DataExtractor/Method/ValueKeysExtractionMethod.php b/Filter/DataExtractor/Method/ValueKeysExtractionMethod.php index 82f55b1..4b5f741 100644 --- a/Filter/DataExtractor/Method/ValueKeysExtractionMethod.php +++ b/Filter/DataExtractor/Method/ValueKeysExtractionMethod.php @@ -15,7 +15,7 @@ class ValueKeysExtractionMethod implements DataExtractionMethodInterface /** * {@inheritdoc} */ - public function getName() + public function getName(): string { return 'value_keys'; } @@ -25,15 +25,15 @@ public function getName() */ public function extract(FormInterface $form) { - $data = $form->getData() ?: array(); - $keys = array(); + $data = $form->getData() ?: []; + $keys = []; $config = $form->getConfig(); if ($config->hasAttribute('filter_value_keys')) { $keys = array_merge($data, $config->getAttribute('filter_value_keys')); } - $values = array('value' => array()); + $values = ['value' => []]; foreach ($keys as $key => $value) { if (array_key_exists($key, $data)) { diff --git a/Filter/Doctrine/DBALQuery.php b/Filter/Doctrine/DBALQuery.php index c45656e..40272e1 100644 --- a/Filter/Doctrine/DBALQuery.php +++ b/Filter/Doctrine/DBALQuery.php @@ -2,10 +2,11 @@ namespace Lexik\Bundle\FormFilterBundle\Filter\Doctrine; +use Doctrine\DBAL\Query\Expression\ExpressionBuilder; +use Doctrine\DBAL\Query\QueryBuilder; use Lexik\Bundle\FormFilterBundle\Filter\Condition\Condition; -use Lexik\Bundle\FormFilterBundle\Filter\Query\QueryInterface; use Lexik\Bundle\FormFilterBundle\Filter\Doctrine\Expression\DBALExpressionBuilder; -use Doctrine\DBAL\Query\QueryBuilder; +use Lexik\Bundle\FormFilterBundle\Filter\Query\QueryInterface; /** * @author Jeremy Barthe @@ -30,7 +31,7 @@ class DBALQuery implements QueryInterface */ public function __construct(QueryBuilder $queryBuilder, $forceCaseInsensitivity = false) { - $this->queryBuilder = $queryBuilder; + $this->queryBuilder = $queryBuilder; $this->expressionBuilder = new DBALExpressionBuilder( $this->queryBuilder->expr(), $forceCaseInsensitivity @@ -40,7 +41,7 @@ public function __construct(QueryBuilder $queryBuilder, $forceCaseInsensitivity /** * {@inheritDoc} */ - public function getEventPartName() + public function getEventPartName(): string { return 'dbal'; } @@ -56,7 +57,7 @@ public function getQueryBuilder() /** * {@inheritDoc} */ - public function createCondition($expression, array $parameters = array()) + public function createCondition($expression, array $parameters = []) { return new Condition($expression, $parameters); } @@ -64,7 +65,7 @@ public function createCondition($expression, array $parameters = array()) /** * Get QueryBuilder expr. * - * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder + * @return ExpressionBuilder */ public function getExpr() { @@ -84,7 +85,7 @@ public function getRootAlias() /** * {@inheritDoc} */ - public function hasJoinAlias($joinAlias) + public function hasJoinAlias($joinAlias): bool { $joinParts = $this->queryBuilder->getQueryPart('join'); diff --git a/Filter/Doctrine/DoctrineQueryBuilderAdapter.php b/Filter/Doctrine/DoctrineQueryBuilderAdapter.php index fc529d2..7981ab5 100644 --- a/Filter/Doctrine/DoctrineQueryBuilderAdapter.php +++ b/Filter/Doctrine/DoctrineQueryBuilderAdapter.php @@ -2,8 +2,11 @@ namespace Lexik\Bundle\FormFilterBundle\Filter\Doctrine; -use Doctrine\ORM\QueryBuilder as ORMQueryBuilder; +use Doctrine\DBAL\Query\Expression\CompositeExpression; use Doctrine\DBAL\Query\QueryBuilder as DBALQueryBuilder; +use Doctrine\ORM\Query\Expr\Andx; +use Doctrine\ORM\Query\Expr\Orx; +use Doctrine\ORM\QueryBuilder as ORMQueryBuilder; /** * @author Cédric Girard @@ -21,7 +24,7 @@ class DoctrineQueryBuilderAdapter */ public function __construct($qb) { - if (! ($qb instanceof ORMQueryBuilder || $qb instanceof DBALQueryBuilder)) { + if (!($qb instanceof ORMQueryBuilder || $qb instanceof DBALQueryBuilder)) { throw new \RuntimeException('Invalid Doctrine query builder instance.'); } @@ -29,7 +32,7 @@ public function __construct($qb) } /** - * @return \Doctrine\DBAL\Query\Expression\CompositeExpression|\Doctrine\ORM\Query\Expr\Andx + * @return CompositeExpression|Andx */ public function andX() { @@ -37,7 +40,7 @@ public function andX() } /** - * @return \Doctrine\DBAL\Query\Expression\CompositeExpression|\Doctrine\ORM\Query\Expr\Orx + * @return CompositeExpression|Orx */ public function orX() { diff --git a/Filter/Doctrine/Expression/ExpressionBuilder.php b/Filter/Doctrine/Expression/ExpressionBuilder.php index 1aefc1e..f2df901 100644 --- a/Filter/Doctrine/Expression/ExpressionBuilder.php +++ b/Filter/Doctrine/Expression/ExpressionBuilder.php @@ -2,12 +2,14 @@ namespace Lexik\Bundle\FormFilterBundle\Filter\Doctrine\Expression; +use Doctrine\ORM\Query\Expr\Comparison; +use Doctrine\ORM\Query\Expr\Literal; use Lexik\Bundle\FormFilterBundle\Filter\FilterOperands; abstract class ExpressionBuilder { - const SQL_DATE = 'Y-m-d'; - const SQL_DATE_TIME = 'Y-m-d H:i:s'; + public const SQL_DATE = 'Y-m-d'; + public const SQL_DATE_TIME = 'Y-m-d H:i:s'; /** * @var mixed @@ -51,7 +53,7 @@ public function __construct($forceCaseInsensitivity, $encoding = null) * @param number $min minimum value * @param number $max maximum value * - * @return \Doctrine\ORM\Query\Expr\Comparison|string + * @return Comparison|string */ public function inRange($field, $min, $max) { @@ -94,7 +96,7 @@ public function between($field, $min, $max) * @param null|\DateTime $min start date * @param null|\DateTime $max end date * - * @return \Doctrine\ORM\Query\Expr\Comparison|string + * @return Comparison|string */ public function dateInRange($field, $min = null, $max = null) { @@ -110,13 +112,13 @@ public function dateInRange($field, $min = null, $max = null) return $this->expr()->lte($field, $max); } elseif (null === $max) { // $min exists - return $this->expr()->gte($field, $min); + return $this->expr()->gte($field, $min); } // both $min and $max exists return $this->expr()->andX( $this->expr()->lte($field, $max), - $this->expr()->gte($field, $min) + $this->expr()->gte($field, $min) ); } @@ -128,7 +130,7 @@ public function dateInRange($field, $min = null, $max = null) * @param string|\DateTime $value alias.fieldName or mysql date string format or DateTime * @param string|\DateTime $min alias.fieldName or mysql date string format or DateTime * @param string|\DateTime $max alias.fieldName or mysql date string format or DateTime - * @return \Doctrine\ORM\Query\Expr\Comparison|string + * @return Comparison|string */ public function dateTimeInRange($value, $min = null, $max = null) { @@ -137,8 +139,8 @@ public function dateTimeInRange($value, $min = null, $max = null) } $value = $this->convertToSqlDateTime($value); - $min = $this->convertToSqlDateTime($min); - $max = $this->convertToSqlDateTime($max); + $min = $this->convertToSqlDateTime($min); + $max = $this->convertToSqlDateTime($max); if (!$max && !$min) { return null; @@ -147,11 +149,11 @@ public function dateTimeInRange($value, $min = null, $max = null) if ($min === null) { $findExpression = $this->expr()->lte($value, $max); } elseif ($max === null) { - $findExpression = $this->expr()->gte($value, $min); + $findExpression = $this->expr()->gte($value, $min); } else { $findExpression = $this->expr()->andX( $this->expr()->lte($value, $max), - $this->expr()->gte($value, $min) + $this->expr()->gte($value, $min) ); } @@ -165,7 +167,7 @@ public function dateTimeInRange($value, $min = null, $max = null) * @param string $value string value * @param int $type one of FilterOperands::STRING_* constant * - * @return \Doctrine\ORM\Query\Expr\Comparison|string + * @return Comparison|string */ public function stringLike($field, $value, $type = FilterOperands::STRING_CONTAINS) { @@ -183,11 +185,11 @@ public function stringLike($field, $value, $type = FilterOperands::STRING_CONTAI * @param \DateTime $date * @param bool $isMax * - * @return \Doctrine\ORM\Query\Expr\Literal|string + * @return Literal|string */ protected function convertToSqlDate($date, $isMax = false) { - if (! $date instanceof \DateTime) { + if (!$date instanceof \DateTime) { return; } @@ -204,7 +206,7 @@ protected function convertToSqlDate($date, $isMax = false) * Normalize date time boundary * * @param \DateTime|string $date - * @return \Doctrine\ORM\Query\Expr\Literal + * @return Literal */ protected function convertToSqlDateTime($date) { diff --git a/Filter/Doctrine/MongodbQuery.php b/Filter/Doctrine/MongodbQuery.php index 0571543..2eb0b8a 100644 --- a/Filter/Doctrine/MongodbQuery.php +++ b/Filter/Doctrine/MongodbQuery.php @@ -3,6 +3,7 @@ namespace Lexik\Bundle\FormFilterBundle\Filter\Doctrine; use Doctrine\ODM\MongoDB\Query\Builder; +use Doctrine\ODM\MongoDB\Query\Expr; use Lexik\Bundle\FormFilterBundle\Filter\Condition\Condition; use Lexik\Bundle\FormFilterBundle\Filter\Query\QueryInterface; @@ -44,7 +45,7 @@ public function getQueryBuilder() /** * {@inheritDoc} */ - public function getEventPartName() + public function getEventPartName(): string { return 'mongodb'; } @@ -52,13 +53,13 @@ public function getEventPartName() /** * {@inheritDoc} */ - public function createCondition($expression, array $parameters = array()) + public function createCondition($expression, array $parameters = []) { return new Condition($expression, $parameters); } /** - * @return \Doctrine\ODM\MongoDB\Query\Expr + * @return Expr */ public function getExpr() { diff --git a/Filter/Doctrine/ORMQuery.php b/Filter/Doctrine/ORMQuery.php index 824115a..f6dcf79 100644 --- a/Filter/Doctrine/ORMQuery.php +++ b/Filter/Doctrine/ORMQuery.php @@ -2,10 +2,12 @@ namespace Lexik\Bundle\FormFilterBundle\Filter\Doctrine; +use Doctrine\ORM\Query\Expr; +use Doctrine\ORM\QueryBuilder; use Lexik\Bundle\FormFilterBundle\Filter\Condition\Condition; -use Lexik\Bundle\FormFilterBundle\Filter\Query\QueryInterface; +use Lexik\Bundle\FormFilterBundle\Filter\Doctrine\Expression\ExpressionBuilder; use Lexik\Bundle\FormFilterBundle\Filter\Doctrine\Expression\ORMExpressionBuilder; -use Doctrine\ORM\QueryBuilder; +use Lexik\Bundle\FormFilterBundle\Filter\Query\QueryInterface; /** * @author Jeremy Barthe @@ -31,7 +33,7 @@ class ORMQuery implements QueryInterface */ public function __construct(QueryBuilder $queryBuilder, $forceCaseInsensitivity = false, $encoding = null) { - $this->queryBuilder = $queryBuilder; + $this->queryBuilder = $queryBuilder; $this->expressionBuilder = new ORMExpressionBuilder( $this->queryBuilder->expr(), $forceCaseInsensitivity, @@ -42,7 +44,7 @@ public function __construct(QueryBuilder $queryBuilder, $forceCaseInsensitivity /** * {@inheritDoc} */ - public function getEventPartName() + public function getEventPartName(): string { return 'orm'; } @@ -58,7 +60,7 @@ public function getQueryBuilder() /** * {@inheritDoc} */ - public function createCondition($expression, array $parameters = array()) + public function createCondition($expression, array $parameters = []) { return new Condition($expression, $parameters); } @@ -66,7 +68,7 @@ public function createCondition($expression, array $parameters = array()) /** * Get QueryBuilder expr. * - * @return \Doctrine\ORM\Query\Expr + * @return Expr */ public function getExpr() { @@ -80,13 +82,13 @@ public function getRootAlias() { $aliases = $this->queryBuilder->getRootAliases(); - return isset($aliases[0]) ? $aliases[0] : ''; + return $aliases[0] ?? ''; } /** * {@inheritDoc} */ - public function hasJoinAlias($joinAlias) + public function hasJoinAlias($joinAlias): bool { $joinParts = $this->queryBuilder->getDQLPart('join'); @@ -105,7 +107,7 @@ public function hasJoinAlias($joinAlias) /** * Get expr class. * - * @return \Lexik\Bundle\FormFilterBundle\Filter\Doctrine\Expression\ExpressionBuilder + * @return ExpressionBuilder */ public function getExpressionBuilder() { diff --git a/Filter/FilterBuilderExecuter.php b/Filter/FilterBuilderExecuter.php index 42d78da..dd1705f 100644 --- a/Filter/FilterBuilderExecuter.php +++ b/Filter/FilterBuilderExecuter.php @@ -34,8 +34,8 @@ class FilterBuilderExecuter implements FilterBuilderExecuterInterface public function __construct(QueryInterface $filterQuery, $alias, RelationsAliasBag $parts) { $this->filterQuery = $filterQuery; - $this->alias = $alias; - $this->parts = $parts; + $this->alias = $alias; + $this->parts = $parts; } /** diff --git a/Filter/FilterBuilderExecuterInterface.php b/Filter/FilterBuilderExecuterInterface.php index 8200b04..9a90bd5 100644 --- a/Filter/FilterBuilderExecuterInterface.php +++ b/Filter/FilterBuilderExecuterInterface.php @@ -2,6 +2,8 @@ namespace Lexik\Bundle\FormFilterBundle\Filter; +use Lexik\Bundle\FormFilterBundle\Filter\Query\QueryInterface; + /** * @author Cédric Girard */ @@ -27,7 +29,7 @@ public function getAlias(); public function getParts(); /** - * @return \Lexik\Bundle\FormFilterBundle\Filter\Query\QueryInterface + * @return QueryInterface */ public function getFilterQuery(); } diff --git a/Filter/FilterBuilderUpdater.php b/Filter/FilterBuilderUpdater.php index 7950ba7..a71b0e5 100644 --- a/Filter/FilterBuilderUpdater.php +++ b/Filter/FilterBuilderUpdater.php @@ -2,22 +2,22 @@ namespace Lexik\Bundle\FormFilterBundle\Filter; -use Symfony\Component\Form\AbstractType; -use Symfony\Component\Form\Form; -use Symfony\Component\Form\FormInterface; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; +use Lexik\Bundle\FormFilterBundle\Event\ApplyFilterConditionEvent; +use Lexik\Bundle\FormFilterBundle\Event\FilterEvents; +use Lexik\Bundle\FormFilterBundle\Event\GetFilterConditionEvent; +use Lexik\Bundle\FormFilterBundle\Event\PrepareEvent; use Lexik\Bundle\FormFilterBundle\Filter\Condition\ConditionBuilder; use Lexik\Bundle\FormFilterBundle\Filter\Condition\ConditionBuilderInterface; use Lexik\Bundle\FormFilterBundle\Filter\Condition\ConditionInterface; use Lexik\Bundle\FormFilterBundle\Filter\Condition\ConditionNodeInterface; use Lexik\Bundle\FormFilterBundle\Filter\DataExtractor\FormDataExtractorInterface; -use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\EmbeddedFilterTypeInterface; use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\CollectionAdapterFilterType; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\EmbeddedFilterTypeInterface; use Lexik\Bundle\FormFilterBundle\Filter\Query\QueryInterface; -use Lexik\Bundle\FormFilterBundle\Event\ApplyFilterConditionEvent; -use Lexik\Bundle\FormFilterBundle\Event\FilterEvents; -use Lexik\Bundle\FormFilterBundle\Event\PrepareEvent; -use Lexik\Bundle\FormFilterBundle\Event\GetFilterConditionEvent; +use Symfony\Component\Form\AbstractType; +use Symfony\Component\Form\Form; +use Symfony\Component\Form\FormInterface; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** * Build a query from a given form object, we basically add conditions to the Doctrine query builder. @@ -92,7 +92,7 @@ public function addFilterConditions(FormInterface $form, $queryBuilder, $alias = throw new \RuntimeException("Couldn't find any filter query object."); } - $alias = (null !== $alias) ? $alias : $event->getFilterQuery()->getRootAlias(); + $alias = $alias ?? $event->getFilterQuery()->getRootAlias(); // init parts (= ['joins' -> 'alias']) / the root alias does not target a join $this->parts->add('__root__', $alias); @@ -174,8 +174,8 @@ protected function addFilters(FormInterface $form, QueryInterface $filterQuery, */ protected function getFilterCondition(FormInterface $form, AbstractType $formType, QueryInterface $filterQuery, $alias) { - $values = $this->prepareFilterValues($form, $formType); - $values += array('alias' => $alias); + $values = $this->prepareFilterValues($form); + $values += ['alias' => $alias]; $field = $form->getConfig()->getAttribute('filter_field_name') ?? trim($values['alias'] . '.' . $form->getName(), '. '); $condition = null; @@ -276,7 +276,7 @@ protected function buildDefaultConditionNode(Form $form, ConditionNodeInterface foreach ($form->all() as $child) { $formType = $child->getConfig()->getType()->getInnerType(); - $name = ('' !== $parentName) ? $parentName.'.'.$child->getName() : $child->getName(); + $name = ('' !== $parentName) ? $parentName . '.' . $child->getName() : $child->getName(); if ($child->getConfig()->hasAttribute('add_shared') || $formType instanceof EmbeddedFilterTypeInterface) { $isCollection = ($formType instanceof CollectionAdapterFilterType); diff --git a/Filter/FilterOperands.php b/Filter/FilterOperands.php index 669b968..84966e1 100644 --- a/Filter/FilterOperands.php +++ b/Filter/FilterOperands.php @@ -9,23 +9,23 @@ */ final class FilterOperands { - const OPERATOR_EQUAL = 'eq'; - const OPERATOR_GREATER_THAN = 'gt'; - const OPERATOR_GREATER_THAN_EQUAL = 'gte'; - const OPERATOR_LOWER_THAN = 'lt'; - const OPERATOR_LOWER_THAN_EQUAL = 'lte'; + public const OPERATOR_EQUAL = 'eq'; + public const OPERATOR_GREATER_THAN = 'gt'; + public const OPERATOR_GREATER_THAN_EQUAL = 'gte'; + public const OPERATOR_LOWER_THAN = 'lt'; + public const OPERATOR_LOWER_THAN_EQUAL = 'lte'; - const STRING_STARTS = 1; - const STRING_ENDS = 2; - const STRING_EQUALS = 3; - const STRING_CONTAINS = 4; + public const STRING_STARTS = 1; + public const STRING_ENDS = 2; + public const STRING_EQUALS = 3; + public const STRING_CONTAINS = 4; /** * @deprecated use FilterOperands::STRING_CONTAINS */ - const STRING_BOTH = 4; + public const STRING_BOTH = 4; - const OPERAND_SELECTOR = 'selection'; + public const OPERAND_SELECTOR = 'selection'; /** * Returns all available number operands. @@ -35,13 +35,7 @@ final class FilterOperands */ public static function getNumberOperands($includeSelector = false) { - $values = array( - self::OPERATOR_EQUAL, - self::OPERATOR_GREATER_THAN, - self::OPERATOR_GREATER_THAN_EQUAL, - self::OPERATOR_LOWER_THAN, - self::OPERATOR_LOWER_THAN_EQUAL, - ); + $values = [self::OPERATOR_EQUAL, self::OPERATOR_GREATER_THAN, self::OPERATOR_GREATER_THAN_EQUAL, self::OPERATOR_LOWER_THAN, self::OPERATOR_LOWER_THAN_EQUAL]; if ($includeSelector) { $values[] = self::OPERAND_SELECTOR; @@ -58,12 +52,7 @@ public static function getNumberOperands($includeSelector = false) */ public static function getStringOperands($includeSelector = false) { - $values = array( - self::STRING_STARTS, - self::STRING_ENDS, - self::STRING_EQUALS, - self::STRING_CONTAINS, - ); + $values = [self::STRING_STARTS, self::STRING_ENDS, self::STRING_EQUALS, self::STRING_CONTAINS]; if ($includeSelector) { $values[] = self::OPERAND_SELECTOR; @@ -77,11 +66,11 @@ public static function getStringOperands($includeSelector = false) * * @return array */ - public static function getNumberOperandsChoices() + public static function getNumberOperandsChoices(): array { - $choices = array(); + $choices = []; - $reflection = new \ReflectionClass(__CLASS__); + $reflection = new \ReflectionClass(self::class); foreach ($reflection->getConstants() as $name => $value) { if ('OPERATOR_' === substr($name, 0, 9)) { $choices[$value] = strtolower(str_replace('OPERATOR_', 'number.', $name)); @@ -96,11 +85,11 @@ public static function getNumberOperandsChoices() * * @return array */ - public static function getStringOperandsChoices() + public static function getStringOperandsChoices(): array { - $choices = array(); + $choices = []; - $reflection = new \ReflectionClass(__CLASS__); + $reflection = new \ReflectionClass(self::class); foreach ($reflection->getConstants() as $name => $value) { if ('STRING_' === substr($name, 0, 7)) { $choices[$value] = strtolower(str_replace('STRING_', 'text.', $name)); @@ -123,7 +112,7 @@ public static function getStringOperandByString($operand) } $name = strtoupper(str_replace('text.', 'STRING_', $operand)); - $reflection = new \ReflectionClass(__CLASS__); + $reflection = new \ReflectionClass(self::class); return $reflection->getConstant($name); } diff --git a/Filter/Form/FilterExtension.php b/Filter/Form/FilterExtension.php index 54eb107..492abda 100644 --- a/Filter/Form/FilterExtension.php +++ b/Filter/Form/FilterExtension.php @@ -3,6 +3,18 @@ namespace Lexik\Bundle\FormFilterBundle\Filter\Form; use Lexik\Bundle\FormFilterBundle\Filter\Form\Type; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\BooleanFilterType; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\CheckboxFilterType; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\ChoiceFilterType; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\CollectionAdapterFilterType; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\DateFilterType; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\DateRangeFilterType; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\DateTimeFilterType; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\DateTimeRangeFilterType; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\NumberFilterType; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\NumberRangeFilterType; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\SharedableFilterType; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\TextFilterType; use Symfony\Component\Form\AbstractExtension; /** @@ -15,22 +27,9 @@ class FilterExtension extends AbstractExtension /** * @return array */ - protected function loadTypes() + protected function loadTypes(): array { - return array( - new Type\BooleanFilterType(), - new Type\CheckboxFilterType(), - new Type\ChoiceFilterType(), - new Type\DateFilterType(), - new Type\DateRangeFilterType(), - new Type\DateTimeFilterType(), - new Type\DateTimeRangeFilterType(), - new Type\NumberFilterType(), - new Type\NumberRangeFilterType(), - new Type\TextFilterType(), - new Type\CollectionAdapterFilterType(), - new Type\SharedableFilterType(), - ); + return [new BooleanFilterType(), new CheckboxFilterType(), new ChoiceFilterType(), new DateFilterType(), new DateRangeFilterType(), new DateTimeFilterType(), new DateTimeRangeFilterType(), new NumberFilterType(), new NumberRangeFilterType(), new TextFilterType(), new CollectionAdapterFilterType(), new SharedableFilterType()]; } /** diff --git a/Filter/Form/FilterTypeExtension.php b/Filter/Form/FilterTypeExtension.php index cee193d..43c1bb8 100644 --- a/Filter/Form/FilterTypeExtension.php +++ b/Filter/Form/FilterTypeExtension.php @@ -2,10 +2,10 @@ namespace Lexik\Bundle\FormFilterBundle\Filter\Form; -use Symfony\Component\OptionsResolver\OptionsResolver; +use Symfony\Component\Form\AbstractTypeExtension; use Symfony\Component\Form\Extension\Core\Type\FormType; use Symfony\Component\Form\FormBuilderInterface; -use Symfony\Component\Form\AbstractTypeExtension; +use Symfony\Component\OptionsResolver\OptionsResolver; /** * Define filtering options. @@ -17,7 +17,7 @@ class FilterTypeExtension extends AbstractTypeExtension /** * {@inheritdoc} */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { if (null !== $options['apply_filter']) { $builder->setAttribute('apply_filter', $options['apply_filter']); @@ -39,15 +39,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) /** * {@inheritdoc} */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { - $resolver->setDefaults(array( - 'apply_filter' => null, - 'data_extraction_method' => 'default', - 'filter_condition_builder' => null, - 'filter_field_name' => null, - 'filter_shared_name' => null, - )); + $resolver->setDefaults(['apply_filter' => null, 'data_extraction_method' => 'default', 'filter_condition_builder' => null, 'filter_field_name' => null, 'filter_shared_name' => null]); } /** diff --git a/Filter/Form/Type/BooleanFilterType.php b/Filter/Form/Type/BooleanFilterType.php index 9bd9f58..0502af4 100644 --- a/Filter/Form/Type/BooleanFilterType.php +++ b/Filter/Form/Type/BooleanFilterType.php @@ -14,13 +14,13 @@ */ class BooleanFilterType extends AbstractType { - const VALUE_YES = 'y'; - const VALUE_NO = 'n'; + public const VALUE_YES = 'y'; + public const VALUE_NO = 'n'; /** * @return ?string */ - public function getParent() + public function getParent(): ?string { return ChoiceType::class; } @@ -28,7 +28,7 @@ public function getParent() /** * @return string */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'filter_boolean'; } @@ -36,23 +36,14 @@ public function getBlockPrefix() /** * {@inheritdoc} */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver - ->setDefaults(array( - 'required' => false, - 'choices' => array( - 'boolean.yes' => self::VALUE_YES, - 'boolean.no' => self::VALUE_NO, - ), - 'placeholder' => 'boolean.yes_or_no', - 'translation_domain' => 'LexikFormFilterBundle', - 'data_extraction_method' => 'default', - )) - ->setAllowedValues('data_extraction_method', array('default')) + ->setDefaults(['required' => false, 'choices' => ['boolean.yes' => self::VALUE_YES, 'boolean.no' => self::VALUE_NO], 'placeholder' => 'boolean.yes_or_no', 'translation_domain' => 'LexikFormFilterBundle', 'data_extraction_method' => 'default']) + ->setAllowedValues('data_extraction_method', ['default']) ; - if(version_compare(Kernel::VERSION, '3.1.0') < 0) { + if (version_compare(Kernel::VERSION, '3.1.0') < 0) { $resolver->setDefault('choices_as_values', true); // must be removed for use in Symfony 3.1, needed for 2.8 } } diff --git a/Filter/Form/Type/CheckboxFilterType.php b/Filter/Form/Type/CheckboxFilterType.php index a176316..6808b88 100644 --- a/Filter/Form/Type/CheckboxFilterType.php +++ b/Filter/Form/Type/CheckboxFilterType.php @@ -16,21 +16,18 @@ class CheckboxFilterType extends AbstractType /** * {@inheritdoc} */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver - ->setDefaults(array( - 'required' => false, - 'data_extraction_method' => 'default', - )) - ->setAllowedValues('data_extraction_method', array('default')) + ->setDefaults(['required' => false, 'data_extraction_method' => 'default']) + ->setAllowedValues('data_extraction_method', ['default']) ; } /** * @return ?string */ - public function getParent() + public function getParent(): ?string { return CheckboxType::class; } @@ -38,7 +35,7 @@ public function getParent() /** * @return string */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'filter_checkbox'; } diff --git a/Filter/Form/Type/ChoiceFilterType.php b/Filter/Form/Type/ChoiceFilterType.php index a786cca..f4ce61d 100644 --- a/Filter/Form/Type/ChoiceFilterType.php +++ b/Filter/Form/Type/ChoiceFilterType.php @@ -16,21 +16,18 @@ class ChoiceFilterType extends AbstractType /** * {@inheritdoc} */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver - ->setDefaults(array( - 'required' => false, - 'data_extraction_method' => 'default', - )) - ->setAllowedValues('data_extraction_method', array('default')) + ->setDefaults(['required' => false, 'data_extraction_method' => 'default']) + ->setAllowedValues('data_extraction_method', ['default']) ; } /** * @return ?string */ - public function getParent() + public function getParent(): ?string { return ChoiceType::class; } @@ -38,7 +35,7 @@ public function getParent() /** * @return string */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'filter_choice'; } diff --git a/Filter/Form/Type/CollectionAdapterFilterType.php b/Filter/Form/Type/CollectionAdapterFilterType.php index 2184ab4..8c29eee 100644 --- a/Filter/Form/Type/CollectionAdapterFilterType.php +++ b/Filter/Form/Type/CollectionAdapterFilterType.php @@ -19,7 +19,7 @@ class CollectionAdapterFilterType extends AbstractType /** * {@inheritdoc} */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { // update collection to only get one element $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($options) { @@ -42,9 +42,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) // then add one row that will be used for filtering $index = 0; - $childOptions = array_replace(array( - 'property_path' => sprintf('[%d]', $index), - ), $options['entry_options']); + $childOptions = array_replace(['property_path' => sprintf('[%d]', $index)], $options['entry_options']); $form->add($index, $options['entry_type'], $childOptions); }); @@ -53,21 +51,17 @@ public function buildForm(FormBuilderInterface $builder, array $options) /** * {@inheritdoc} */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { - $resolver->setDefaults(array( - 'entry_type' => null, - 'entry_options' => array(), - 'default_data' => array(), - )); + $resolver->setDefaults(['entry_type' => null, 'entry_options' => [], 'default_data' => []]); - $resolver->setRequired(array('entry_type')); + $resolver->setRequired(['entry_type']); } /** * @return ?string */ - public function getParent() + public function getParent(): ?string { return SharedableFilterType::class; } @@ -75,7 +69,7 @@ public function getParent() /** * @return string */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'filter_collection_adapter'; } diff --git a/Filter/Form/Type/DateFilterType.php b/Filter/Form/Type/DateFilterType.php index f7fa9e7..129b7d6 100644 --- a/Filter/Form/Type/DateFilterType.php +++ b/Filter/Form/Type/DateFilterType.php @@ -16,21 +16,18 @@ class DateFilterType extends AbstractType /** * {@inheritdoc} */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver - ->setDefaults(array( - 'required' => false, - 'data_extraction_method' => 'default', - )) - ->setAllowedValues('data_extraction_method', array('default')) + ->setDefaults(['required' => false, 'data_extraction_method' => 'default']) + ->setAllowedValues('data_extraction_method', ['default']) ; } /** * @return ?string */ - public function getParent() + public function getParent(): ?string { return DateType::class; } @@ -38,7 +35,7 @@ public function getParent() /** * @return string */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'filter_date'; } diff --git a/Filter/Form/Type/DateRangeFilterType.php b/Filter/Form/Type/DateRangeFilterType.php index a662627..caf49f3 100644 --- a/Filter/Form/Type/DateRangeFilterType.php +++ b/Filter/Form/Type/DateRangeFilterType.php @@ -16,37 +16,29 @@ class DateRangeFilterType extends AbstractType /** * {@inheritdoc} */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('left_date', DateFilterType::class, $options['left_date_options']); $builder->add('right_date', DateFilterType::class, $options['right_date_options']); - $builder->setAttribute('filter_value_keys', array( - 'left_date' => $options['left_date_options'], - 'right_date' => $options['right_date_options'], - )); + $builder->setAttribute('filter_value_keys', ['left_date' => $options['left_date_options'], 'right_date' => $options['right_date_options']]); } /** * {@inheritdoc} */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver - ->setDefaults(array( - 'required' => false, - 'left_date_options' => array(), - 'right_date_options' => array(), - 'data_extraction_method' => 'value_keys', - )) - ->setAllowedValues('data_extraction_method', array('value_keys')) + ->setDefaults(['required' => false, 'left_date_options' => [], 'right_date_options' => [], 'data_extraction_method' => 'value_keys']) + ->setAllowedValues('data_extraction_method', ['value_keys']) ; } /** * @return string */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'filter_date_range'; } diff --git a/Filter/Form/Type/DateTimeFilterType.php b/Filter/Form/Type/DateTimeFilterType.php index 62f4928..39515de 100644 --- a/Filter/Form/Type/DateTimeFilterType.php +++ b/Filter/Form/Type/DateTimeFilterType.php @@ -16,21 +16,18 @@ class DateTimeFilterType extends AbstractType /** * {@inheritdoc} */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver - ->setDefaults(array( - 'required' => false, - 'data_extraction_method' => 'default', - )) - ->setAllowedValues('data_extraction_method', array('default')) + ->setDefaults(['required' => false, 'data_extraction_method' => 'default']) + ->setAllowedValues('data_extraction_method', ['default']) ; } /** * @return ?string */ - public function getParent() + public function getParent(): ?string { return DateTimeType::class; } @@ -38,7 +35,7 @@ public function getParent() /** * @return string */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'filter_datetime'; } diff --git a/Filter/Form/Type/DateTimeRangeFilterType.php b/Filter/Form/Type/DateTimeRangeFilterType.php index a6add7b..5151c5d 100644 --- a/Filter/Form/Type/DateTimeRangeFilterType.php +++ b/Filter/Form/Type/DateTimeRangeFilterType.php @@ -16,37 +16,29 @@ class DateTimeRangeFilterType extends AbstractType /** * {@inheritdoc} */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('left_datetime', DateTimeFilterType::class, $options['left_datetime_options']); $builder->add('right_datetime', DateTimeFilterType::class, $options['right_datetime_options']); - $builder->setAttribute('filter_value_keys', array( - 'left_datetime' => $options['left_datetime_options'], - 'right_datetime' => $options['right_datetime_options'], - )); + $builder->setAttribute('filter_value_keys', ['left_datetime' => $options['left_datetime_options'], 'right_datetime' => $options['right_datetime_options']]); } /** * {@inheritdoc} */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver - ->setDefaults(array( - 'required' => false, - 'left_datetime_options' => array(), - 'right_datetime_options' => array(), - 'data_extraction_method' => 'value_keys', - )) - ->setAllowedValues('data_extraction_method', array('value_keys')) + ->setDefaults(['required' => false, 'left_datetime_options' => [], 'right_datetime_options' => [], 'data_extraction_method' => 'value_keys']) + ->setAllowedValues('data_extraction_method', ['value_keys']) ; } /** * @return string */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'filter_datetime_range'; } diff --git a/Filter/Form/Type/DocumentFilterType.php b/Filter/Form/Type/DocumentFilterType.php index 29873a7..d391495 100644 --- a/Filter/Form/Type/DocumentFilterType.php +++ b/Filter/Form/Type/DocumentFilterType.php @@ -18,12 +18,9 @@ class DocumentFilterType extends AbstractType /** * {@inheritdoc} */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { - $builder->setAttribute('filter_options', array( - 'reference_type' => $options['reference_type'], - 'reference_name' => (null !== $options['reference_name']) ? $options['reference_name'] : ucfirst($builder->getName()), - )); + $builder->setAttribute('filter_options', ['reference_type' => $options['reference_type'], 'reference_name' => $options['reference_name'] ?? ucfirst($builder->getName())]); } /** @@ -31,25 +28,20 @@ public function buildForm(FormBuilderInterface $builder, array $options) * * @param OptionsResolver $resolver The resolver for the options. */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver - ->setDefaults(array( - 'required' => false, - 'data_extraction_method' => 'default', - 'reference_type' => 'one', - 'reference_name' => null, - )) - ->setRequired(array('reference_type')) - ->setAllowedValues('data_extraction_method', array('default')) - ->setAllowedValues('reference_type', array('one', 'many')) + ->setDefaults(['required' => false, 'data_extraction_method' => 'default', 'reference_type' => 'one', 'reference_name' => null]) + ->setRequired(['reference_type']) + ->setAllowedValues('data_extraction_method', ['default']) + ->setAllowedValues('reference_type', ['one', 'many']) ; } /** * @return ?string */ - public function getParent() + public function getParent(): ?string { return DocumentType::class; } @@ -57,7 +49,7 @@ public function getParent() /** * @return string */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'filter_document'; } diff --git a/Filter/Form/Type/EntityFilterType.php b/Filter/Form/Type/EntityFilterType.php index f61b4b6..e715dd7 100644 --- a/Filter/Form/Type/EntityFilterType.php +++ b/Filter/Form/Type/EntityFilterType.php @@ -16,21 +16,18 @@ class EntityFilterType extends AbstractType /** * {@inheritdoc} */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver - ->setDefaults(array( - 'required' => false, - 'data_extraction_method' => 'default', - )) - ->setAllowedValues('data_extraction_method', array('default')) + ->setDefaults(['required' => false, 'data_extraction_method' => 'default']) + ->setAllowedValues('data_extraction_method', ['default']) ; } /** * @return ?string */ - public function getParent() + public function getParent(): ?string { return EntityType::class; } @@ -38,7 +35,7 @@ public function getParent() /** * @return string */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'filter_entity'; } diff --git a/Filter/Form/Type/NumberFilterType.php b/Filter/Form/Type/NumberFilterType.php index 70cbf2f..5aeeff5 100644 --- a/Filter/Form/Type/NumberFilterType.php +++ b/Filter/Form/Type/NumberFilterType.php @@ -21,7 +21,7 @@ class NumberFilterType extends AbstractType /** * {@inheritdoc} */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { if (true === $options['compound']) { // if the form is compound we don't need the NumberToLocalizedStringTransformer added in the parent type. @@ -30,43 +30,28 @@ public function buildForm(FormBuilderInterface $builder, array $options) $builder->add('condition_operator', ChoiceType::class, $options['choice_options']); $builder->add('text', NumberType::class, $options['number_options']); } else { - $builder->setAttribute('filter_options', array( - 'condition_operator' => $options['condition_operator'], - )); + $builder->setAttribute('filter_options', ['condition_operator' => $options['condition_operator']]); } } /** * {@inheritdoc} */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { - $defaults = array( - 'required' => false, - 'condition_operator' => FilterOperands::OPERATOR_EQUAL, - 'compound' => function (Options $options) { - return $options['condition_operator'] == FilterOperands::OPERAND_SELECTOR; - }, - 'number_options' => array( - 'required' => false, - ), - 'choice_options' => array( - 'choices' => FilterOperands::getNumberOperandsChoices(), - 'required' => false, - 'translation_domain' => 'LexikFormFilterBundle', - ), - 'data_extraction_method' => function (Options $options) { - return $options['compound'] ? 'text' : 'default'; - }, - ); + $defaults = ['required' => false, 'condition_operator' => FilterOperands::OPERATOR_EQUAL, 'compound' => function (Options $options) { + return $options['condition_operator'] == FilterOperands::OPERAND_SELECTOR; + }, 'number_options' => ['required' => false], 'choice_options' => ['choices' => FilterOperands::getNumberOperandsChoices(), 'required' => false, 'translation_domain' => 'LexikFormFilterBundle'], 'data_extraction_method' => function (Options $options) { + return $options['compound'] ? 'text' : 'default'; + }]; - if(version_compare(Kernel::VERSION, '3.1.0') < 0) { + if (version_compare(Kernel::VERSION, '3.1.0') < 0) { $defaults['choice_options']['choices_as_values'] = true; // must be removed for use in Symfony 3.1, needed for 2.8 } $resolver ->setDefaults($defaults) - ->setAllowedValues('data_extraction_method', array('text', 'default')) + ->setAllowedValues('data_extraction_method', ['text', 'default']) ->setAllowedValues('condition_operator', FilterOperands::getNumberOperands(true)) ; } @@ -74,7 +59,7 @@ public function configureOptions(OptionsResolver $resolver) /** * @return ?string */ - public function getParent() + public function getParent(): ?string { return NumberType::class; } @@ -82,7 +67,7 @@ public function getParent() /** * @return string */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'filter_number'; } diff --git a/Filter/Form/Type/NumberRangeFilterType.php b/Filter/Form/Type/NumberRangeFilterType.php index 7e55b57..f99e44f 100644 --- a/Filter/Form/Type/NumberRangeFilterType.php +++ b/Filter/Form/Type/NumberRangeFilterType.php @@ -17,37 +17,29 @@ class NumberRangeFilterType extends AbstractType /** * {@inheritdoc} */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('left_number', NumberFilterType::class, $options['left_number_options']); $builder->add('right_number', NumberFilterType::class, $options['right_number_options']); - $builder->setAttribute('filter_value_keys', array( - 'left_number' => $options['left_number_options'], - 'right_number' => $options['right_number_options'], - )); + $builder->setAttribute('filter_value_keys', ['left_number' => $options['left_number_options'], 'right_number' => $options['right_number_options']]); } /** * {@inheritdoc} */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver - ->setDefaults(array( - 'required' => false, - 'left_number_options' => array('condition_operator' => FilterOperands::OPERATOR_GREATER_THAN_EQUAL), - 'right_number_options' => array('condition_operator' => FilterOperands::OPERATOR_LOWER_THAN_EQUAL), - 'data_extraction_method' => 'value_keys', - )) - ->setAllowedValues('data_extraction_method', array('value_keys')) + ->setDefaults(['required' => false, 'left_number_options' => ['condition_operator' => FilterOperands::OPERATOR_GREATER_THAN_EQUAL], 'right_number_options' => ['condition_operator' => FilterOperands::OPERATOR_LOWER_THAN_EQUAL], 'data_extraction_method' => 'value_keys']) + ->setAllowedValues('data_extraction_method', ['value_keys']) ; } /** * @return string */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'filter_number_range'; } diff --git a/Filter/Form/Type/SharedableFilterType.php b/Filter/Form/Type/SharedableFilterType.php index 0b88227..84ea902 100644 --- a/Filter/Form/Type/SharedableFilterType.php +++ b/Filter/Form/Type/SharedableFilterType.php @@ -17,7 +17,7 @@ class SharedableFilterType extends AbstractType /** * {@inheritdoc} */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { // keep the closure as attribute to execute it later in the query builder updater $builder->setAttribute('add_shared', $options['add_shared']); @@ -26,17 +26,16 @@ public function buildForm(FormBuilderInterface $builder, array $options) /** * {@inheritdoc} */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { - $resolver->setDefaults(array( - 'add_shared' => function (FilterBuilderExecuterInterface $qbe) {}, - )); + $resolver->setDefaults(['add_shared' => function (FilterBuilderExecuterInterface $qbe) { + }]); } /** * @return string */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'filter_sharedable'; } diff --git a/Filter/Form/Type/TextFilterType.php b/Filter/Form/Type/TextFilterType.php index 347110d..cbe6d9b 100644 --- a/Filter/Form/Type/TextFilterType.php +++ b/Filter/Form/Type/TextFilterType.php @@ -34,50 +34,34 @@ public function __construct($conditionPattern = FilterOperands::STRING_EQUALS) /** * {@inheritdoc} */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { if (true === $options['compound']) { $builder->add('condition_pattern', ChoiceType::class, $options['choice_options']); $builder->add('text', TextType::class, $options['text_options']); } else { - $builder->setAttribute('filter_options', array( - 'condition_pattern' => $options['condition_pattern'], - )); + $builder->setAttribute('filter_options', ['condition_pattern' => $options['condition_pattern']]); } } /** * {@inheritdoc} */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { - $defaults = array( - 'required' => false, - 'condition_pattern' => $this->conditionPattern, - 'compound' => function (Options $options) { - return $options['condition_pattern'] == FilterOperands::OPERAND_SELECTOR; - }, - 'text_options' => array( - 'required' => false, - 'trim' => true, - ), - 'choice_options' => array( - 'choices' => FilterOperands::getStringOperandsChoices(), - 'required' => false, - 'translation_domain' => 'LexikFormFilterBundle', - ), - 'data_extraction_method' => function (Options $options) { - return $options['compound'] ? 'text' : 'default'; - }, - ); + $defaults = ['required' => false, 'condition_pattern' => $this->conditionPattern, 'compound' => function (Options $options) { + return $options['condition_pattern'] == FilterOperands::OPERAND_SELECTOR; + }, 'text_options' => ['required' => false, 'trim' => true], 'choice_options' => ['choices' => FilterOperands::getStringOperandsChoices(), 'required' => false, 'translation_domain' => 'LexikFormFilterBundle'], 'data_extraction_method' => function (Options $options) { + return $options['compound'] ? 'text' : 'default'; + }]; - if(version_compare(Kernel::VERSION, '3.1.0') < 0) { + if (version_compare(Kernel::VERSION, '3.1.0') < 0) { $defaults['choice_options']['choices_as_values'] = true; // must be removed for use in Symfony 3.1, needed for 2.8 } $resolver ->setDefaults($defaults) - ->setAllowedValues('data_extraction_method', array('text', 'default')) + ->setAllowedValues('data_extraction_method', ['text', 'default']) ->setAllowedValues('condition_pattern', FilterOperands::getStringOperands(true)) ; } @@ -85,7 +69,7 @@ public function configureOptions(OptionsResolver $resolver) /** * @return ?string */ - public function getParent() + public function getParent(): ?string { return TextType::class; } @@ -93,7 +77,7 @@ public function getParent() /** * @return string */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'filter_text'; } diff --git a/Filter/Query/QueryInterface.php b/Filter/Query/QueryInterface.php index 8831b6b..af3de51 100644 --- a/Filter/Query/QueryInterface.php +++ b/Filter/Query/QueryInterface.php @@ -28,7 +28,7 @@ public function getEventPartName(); * @param array $parameters * @return ConditionInterface */ - public function createCondition($expression, array $parameters = array()); + public function createCondition($expression, array $parameters = []); /** * Get root alias. diff --git a/Filter/RelationsAliasBag.php b/Filter/RelationsAliasBag.php index 8088702..b2bb893 100644 --- a/Filter/RelationsAliasBag.php +++ b/Filter/RelationsAliasBag.php @@ -15,7 +15,7 @@ class RelationsAliasBag /** * @param array $aliases */ - public function __construct(array $aliases = array()) + public function __construct(array $aliases = []) { $this->aliases = $aliases; } @@ -50,7 +50,7 @@ public function has($relation) /** * @return int */ - public function count() + public function count(): int { return count($this->aliases); } diff --git a/LexikFormFilterBundle.php b/LexikFormFilterBundle.php index 4843729..403e7f2 100644 --- a/LexikFormFilterBundle.php +++ b/LexikFormFilterBundle.php @@ -3,6 +3,7 @@ namespace Lexik\Bundle\FormFilterBundle; use Lexik\Bundle\FormFilterBundle\DependencyInjection\Compiler\FormDataExtractorPass; +use Symfony\Component\DependencyInjection\Compiler\PassConfig; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Bundle\Bundle; @@ -14,10 +15,10 @@ class LexikFormFilterBundle extends Bundle /** * {@inheritdoc} */ - public function build(ContainerBuilder $container) - { - parent::build($container); + public function build(ContainerBuilder $container) + { + parent::build($container); - $container->addCompilerPass(new FormDataExtractorPass()); - } + $container->addCompilerPass(new FormDataExtractorPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 0); + } } diff --git a/README.md b/README.md index 7077ecf..24243e5 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ Please use last tag v5.* Credits ------- -* Lexik +* Lexik * [All contributors](https://github.com/lexik/LexikFormFilterBundle/graphs/contributors) License diff --git a/Tests/Event/Listenener/PrepareListenerTest.php b/Tests/Event/Listenener/PrepareListenerTest.php index 1ac2615..0429df3 100644 --- a/Tests/Event/Listenener/PrepareListenerTest.php +++ b/Tests/Event/Listenener/PrepareListenerTest.php @@ -2,6 +2,9 @@ namespace Lexik\Bundle\FormFilterBundle\Tests\Event\Listener; +use Doctrine\DBAL\Connection; +use Doctrine\ORM\EntityManager; +use Doctrine\ORM\QueryBuilder; use Lexik\Bundle\FormFilterBundle\Event\Listener\PrepareListener; use PHPUnit\Framework\TestCase; @@ -14,8 +17,9 @@ public function testGetForceCaseInsensitivity() $pgPlatform = $this->getMockBuilder('Doctrine\DBAL\Platforms\PostgreSqlPlatform')->getMock(); $myPlatform = $this->getMockBuilder('Doctrine\DBAL\Platforms\MySqlPlatform')->getMock(); - $connection = $this->getMockBuilder( - 'Doctrine\DBAL\Connection') + $connection = $this->getMockBuilder( + Connection::class + ) ->disableOriginalConstructor() ->getMock(); $connection->expects($this->any()) @@ -27,7 +31,7 @@ public function testGetForceCaseInsensitivity() $myPlatform )); - $entityManager = $this->getMockBuilder('\Doctrine\ORM\EntityManager') + $entityManager = $this->getMockBuilder('\\' . EntityManager::class) ->disableOriginalConstructor() ->getMock(); @@ -36,9 +40,9 @@ public function testGetForceCaseInsensitivity() ->will($this->returnValue($connection)); $queryBuilder = $this - ->getMockBuilder('\Doctrine\ORM\QueryBuilder') - ->setConstructorArgs(array($entityManager)) - ->setMethods(array('getEntityManager')) + ->getMockBuilder('\\' . QueryBuilder::class) + ->setConstructorArgs([$entityManager]) + ->setMethods(['getEntityManager']) ->getMock() ; @@ -50,9 +54,9 @@ public function testGetForceCaseInsensitivity() $this->assertFalse($listener->getForceCaseInsensitivity($queryBuilder)); $queryBuilder = $this - ->getMockBuilder('Doctrine\DBAL\Query\QueryBuilder') - ->setConstructorArgs(array($connection)) - ->setMethods(array('getConnection')) + ->getMockBuilder(\Doctrine\DBAL\Query\QueryBuilder::class) + ->setConstructorArgs([$connection]) + ->setMethods(['getConnection']) ->getMock() ; diff --git a/Tests/Filter/Doctrine/DBALQueryBuilderUpdaterTest.php b/Tests/Filter/Doctrine/DBALQueryBuilderUpdaterTest.php index 06d6279..b2847d6 100644 --- a/Tests/Filter/Doctrine/DBALQueryBuilderUpdaterTest.php +++ b/Tests/Filter/Doctrine/DBALQueryBuilderUpdaterTest.php @@ -11,79 +11,52 @@ class DBALQueryBuilderUpdaterTest extends DoctrineQueryBuilderUpdater { public function testBuildQuery() { - parent::createBuildQueryTest('getSQL', array( - 'SELECT i FROM item i', - 'SELECT i FROM item i WHERE i.name LIKE \'blabla\'', - 'SELECT i FROM item i WHERE (i.name LIKE \'blabla\') AND (i.position > :p_i_position)', - 'SELECT i FROM item i WHERE (i.name LIKE \'blabla\') AND (i.position > :p_i_position) AND (i.enabled = :p_i_enabled)', - 'SELECT i FROM item i WHERE (i.name LIKE \'blabla\') AND (i.position > :p_i_position) AND (i.enabled = :p_i_enabled)', - 'SELECT i FROM item i WHERE (i.name LIKE \'%blabla\') AND (i.position <= :p_i_position) AND (i.createdAt = :p_i_createdAt)', - 'SELECT i FROM item i WHERE (i.name LIKE \'%blabla\') AND (i.position <= :p_i_position) AND (i.createdAt = :p_i_createdAt)', - )); + parent::createBuildQueryTest('getSQL', ['SELECT i FROM item i', 'SELECT i FROM item i WHERE i.name LIKE \'blabla\'', 'SELECT i FROM item i WHERE (i.name LIKE \'blabla\') AND (i.position > :p_i_position)', 'SELECT i FROM item i WHERE (i.name LIKE \'blabla\') AND (i.position > :p_i_position) AND (i.enabled = :p_i_enabled)', 'SELECT i FROM item i WHERE (i.name LIKE \'blabla\') AND (i.position > :p_i_position) AND (i.enabled = :p_i_enabled)', 'SELECT i FROM item i WHERE (i.name LIKE \'%blabla\') AND (i.position <= :p_i_position) AND (i.createdAt = :p_i_createdAt)', 'SELECT i FROM item i WHERE (i.name LIKE \'%blabla\') AND (i.position <= :p_i_position) AND (i.createdAt = :p_i_createdAt)']); } public function testDisabledFieldQuery() { - parent::createDisabledFieldTest('getSQL', array( - 'SELECT i FROM item i WHERE i.position > :p_i_position', - )); + parent::createDisabledFieldTest('getSQL', ['SELECT i FROM item i WHERE i.position > :p_i_position']); } public function testApplyFilterOption() { - parent::createApplyFilterOptionTest('getSQL', array( - 'SELECT i FROM item i WHERE (i.name <> \'blabla\') AND (i.position <> 2)', - )); + parent::createApplyFilterOptionTest('getSQL', ['SELECT i FROM item i WHERE (i.name <> \'blabla\') AND (i.position <> 2)']); } public function testNumberRange() { - parent::createNumberRangeTest('getSQL', array( - 'SELECT i FROM item i WHERE (i.position > :p_i_position_left) AND (i.position < :p_i_position_right)', - )); + parent::createNumberRangeTest('getSQL', ['SELECT i FROM item i WHERE (i.position > :p_i_position_left) AND (i.position < :p_i_position_right)']); } public function testNumberRangeWithSelector() { - parent::createNumberRangeCompoundTest('getSQL', array( - 'SELECT i FROM item i WHERE (i.position_selector > :p_i_position_selector_left) AND (i.position_selector <= :p_i_position_selector_right)', - )); + parent::createNumberRangeCompoundTest('getSQL', ['SELECT i FROM item i WHERE (i.position_selector > :p_i_position_selector_left) AND (i.position_selector <= :p_i_position_selector_right)']); } public function testNumberRangeDefaultValues() { - parent::createNumberRangeDefaultValuesTest('getSQL', array( - 'SELECT i FROM item i WHERE (i.default_position >= :p_i_default_position_left) AND (i.default_position <= :p_i_default_position_right)', - )); + parent::createNumberRangeDefaultValuesTest('getSQL', ['SELECT i FROM item i WHERE (i.default_position >= :p_i_default_position_left) AND (i.default_position <= :p_i_default_position_right)']); } public function testDateRange() { - parent::createDateRangeTest('getSQL', array( - 'SELECT i FROM item i WHERE (i.createdAt <= \'2012-05-22 23:59:59\') AND (i.createdAt >= \'2012-05-12 00:00:00\')', - )); + parent::createDateRangeTest('getSQL', ['SELECT i FROM item i WHERE (i.createdAt <= \'2012-05-22 23:59:59\') AND (i.createdAt >= \'2012-05-12 00:00:00\')']); } public function testDateRangeWithTimezone() { - parent::createDateRangeWithTimezoneTest('getSQL', array( - 'SELECT i FROM item i WHERE (i.startAt <= \'2015-10-20 18:59:59\') AND (i.startAt >= \'2015-10-19 19:00:00\')', - 'SELECT i FROM item i WHERE (i.startAt <= \'2015-10-16 18:59:59\') AND (i.startAt >= \'2015-09-30 19:00:00\')', - )); + parent::createDateRangeWithTimezoneTest('getSQL', ['SELECT i FROM item i WHERE (i.startAt <= \'2015-10-20 18:59:59\') AND (i.startAt >= \'2015-10-19 19:00:00\')', 'SELECT i FROM item i WHERE (i.startAt <= \'2015-10-16 18:59:59\') AND (i.startAt >= \'2015-09-30 19:00:00\')']); } public function testDateTimeRange() { - parent::createDateTimeRangeTest('getSQL', array( - 'SELECT i FROM item i WHERE (i.updatedAt <= \'2012-06-10 22:12:00\') AND (i.updatedAt >= \'2012-05-12 14:55:00\')', - )); + parent::createDateTimeRangeTest('getSQL', ['SELECT i FROM item i WHERE (i.updatedAt <= \'2012-06-10 22:12:00\') AND (i.updatedAt >= \'2012-05-12 14:55:00\')']); } public function testFilterStandardType() { - parent::createFilterStandardTypeTest('getSQL', array( - 'SELECT i FROM item i WHERE (i.name LIKE \'%hey dude%\') AND (i.position = 99)', - )); + parent::createFilterStandardTypeTest('getSQL', ['SELECT i FROM item i WHERE (i.name LIKE \'%hey dude%\') AND (i.position = 99)']); } protected function createDoctrineQueryBuilder() diff --git a/Tests/Filter/Doctrine/DBALQueryTest.php b/Tests/Filter/Doctrine/DBALQueryTest.php index 6471a80..81e1ba8 100644 --- a/Tests/Filter/Doctrine/DBALQueryTest.php +++ b/Tests/Filter/Doctrine/DBALQueryTest.php @@ -3,8 +3,9 @@ namespace Lexik\Bundle\FormFilterBundle\Tests\Filter\Doctrine; use Doctrine\DBAL\Connection; -use Lexik\Bundle\FormFilterBundle\Filter\Doctrine\DBALQuery; +use Doctrine\DBAL\Query\Expression\ExpressionBuilder; use Doctrine\DBAL\Query\QueryBuilder; +use Lexik\Bundle\FormFilterBundle\Filter\Doctrine\DBALQuery; use PHPUnit\Framework\TestCase; /** @@ -18,7 +19,7 @@ public function testHasJoinAlias() return; $exprMock = $this - ->getMockBuilder('Doctrine\DBAL\Query\Expression\ExpressionBuilder') + ->getMockBuilder(ExpressionBuilder::class) ->disableOriginalConstructor() ->getMock(); diff --git a/Tests/Filter/Doctrine/DoctrineQueryBuilderUpdater.php b/Tests/Filter/Doctrine/DoctrineQueryBuilderUpdater.php index ce6beff..fc7fb0c 100644 --- a/Tests/Filter/Doctrine/DoctrineQueryBuilderUpdater.php +++ b/Tests/Filter/Doctrine/DoctrineQueryBuilderUpdater.php @@ -2,14 +2,16 @@ namespace Lexik\Bundle\FormFilterBundle\Tests\Filter\Doctrine; +use Doctrine\DBAL\Connection; +use Doctrine\ORM\EntityManager; use Doctrine\ORM\QueryBuilder; use Lexik\Bundle\FormFilterBundle\Filter\FilterOperands; use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\BooleanFilterType; -use Lexik\Bundle\FormFilterBundle\Tests\TestCase; -use Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Filter\RangeFilterType; +use Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Filter\FormType; use Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Filter\ItemCallbackFilterType; use Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Filter\ItemFilterType; -use Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Filter\FormType; +use Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Filter\RangeFilterType; +use Lexik\Bundle\FormFilterBundle\Tests\TestCase; /** * Filter query builder tests. @@ -17,12 +19,12 @@ abstract class DoctrineQueryBuilderUpdater extends TestCase { /** - * @var \Doctrine\ORM\EntityManager + * @var EntityManager */ protected $em; /** - * @var \Doctrine\DBAL\Connection + * @var Connection */ protected $conn; @@ -52,7 +54,7 @@ protected function getQueryBuilderParameters($qb) } if ($qb instanceof QueryBuilder) { - $params = array(); + $params = []; foreach ($qb->getParameters() as $parameter) { $params[$parameter->getName()] = $parameter->getValue(); @@ -61,7 +63,7 @@ protected function getQueryBuilderParameters($qb) return $params; } - return array(); + return []; } protected function createBuildQueryTest($method, array $dqls) @@ -77,7 +79,7 @@ protected function createBuildQueryTest($method, array $dqls) // bind a request to the form - 1 params $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); - $form->submit(array('name' => 'blabla', 'position' => '')); + $form->submit(['name' => 'blabla', 'position' => '']); $filterQueryBuilder->addFilterConditions($form, $doctrineQueryBuilder); $this->assertEquals($dqls[1], $doctrineQueryBuilder->{$method}()); @@ -86,82 +88,61 @@ protected function createBuildQueryTest($method, array $dqls) $form = $this->formFactory->create(ItemFilterType::class); $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); - $form->submit(array('name' => 'blabla', 'position' => 2)); + $form->submit(['name' => 'blabla', 'position' => 2]); $filterQueryBuilder->addFilterConditions($form, $doctrineQueryBuilder); $this->assertEquals($dqls[2], $doctrineQueryBuilder->{$method}()); - $this->assertEquals(array('p_i_position' => 2), $this->getQueryBuilderParameters($doctrineQueryBuilder)); + $this->assertEquals(['p_i_position' => 2], $this->getQueryBuilderParameters($doctrineQueryBuilder)); // bind a request to the form - 3 params $form = $this->formFactory->create(ItemFilterType::class); $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); - $form->submit(array('name' => 'blabla', 'position' => 2, 'enabled' => BooleanFilterType::VALUE_YES)); + $form->submit(['name' => 'blabla', 'position' => 2, 'enabled' => BooleanFilterType::VALUE_YES]); $filterQueryBuilder->addFilterConditions($form, $doctrineQueryBuilder); $this->assertEquals($dqls[3], $doctrineQueryBuilder->{$method}()); - $this->assertEquals(array('p_i_position' => 2, 'p_i_enabled' => true), $this->getQueryBuilderParameters($doctrineQueryBuilder)); + $this->assertEquals(['p_i_position' => 2, 'p_i_enabled' => true], $this->getQueryBuilderParameters($doctrineQueryBuilder)); // bind a request to the form - 3 params (use checkbox for enabled field) - $form = $this->formFactory->create(ItemFilterType::class, null, array( - 'checkbox' => true, - )); + $form = $this->formFactory->create(ItemFilterType::class, null, ['checkbox' => true]); $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); - $form->submit(array('name' => 'blabla', 'position' => 2, 'enabled' => 'yes')); + $form->submit(['name' => 'blabla', 'position' => 2, 'enabled' => 'yes']); $filterQueryBuilder->addFilterConditions($form, $doctrineQueryBuilder); $this->assertEquals($dqls[4], $doctrineQueryBuilder->{$method}()); - $this->assertEquals(array('p_i_position' => 2, 'p_i_enabled' => 1), $this->getQueryBuilderParameters($doctrineQueryBuilder)); + $this->assertEquals(['p_i_position' => 2, 'p_i_enabled' => 1], $this->getQueryBuilderParameters($doctrineQueryBuilder)); // bind a request to the form - date + pattern selector $year = \date('Y'); - $form = $this->formFactory->create(ItemFilterType::class, null, array( - 'with_selector' => true, - )); + $form = $this->formFactory->create(ItemFilterType::class, null, ['with_selector' => true]); $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); - $form->submit(array( - 'name' => array('text' => 'blabla', 'condition_pattern' => FilterOperands::STRING_ENDS), - 'position' => array('text' => 2, 'condition_operator' => FilterOperands::OPERATOR_LOWER_THAN_EQUAL), - 'createdAt' => array('year' => $year, 'month' => 9, 'day' => 27), - )); + $form->submit(['name' => ['text' => 'blabla', 'condition_pattern' => FilterOperands::STRING_ENDS], 'position' => ['text' => 2, 'condition_operator' => FilterOperands::OPERATOR_LOWER_THAN_EQUAL], 'createdAt' => ['year' => $year, 'month' => 9, 'day' => 27]]); $filterQueryBuilder->addFilterConditions($form, $doctrineQueryBuilder); $this->assertEquals($dqls[5], $doctrineQueryBuilder->{$method}()); - $this->assertEquals(array('p_i_position' => 2, 'p_i_createdAt' => new \DateTime("{$year}-09-27")), $this->getQueryBuilderParameters($doctrineQueryBuilder)); + $this->assertEquals(['p_i_position' => 2, 'p_i_createdAt' => new \DateTime("{$year}-09-27")], $this->getQueryBuilderParameters($doctrineQueryBuilder)); // bind a request to the form - datetime + pattern selector - $form = $this->formFactory->create(ItemFilterType::class, null, array( - 'with_selector' => true, - 'datetime' => true, - )); + $form = $this->formFactory->create(ItemFilterType::class, null, ['with_selector' => true, 'datetime' => true]); $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); - $form->submit(array( - 'name' => array('text' => 'blabla', 'condition_pattern' => FilterOperands::STRING_ENDS), - 'position' => array('text' => 2, 'condition_operator' => FilterOperands::OPERATOR_LOWER_THAN_EQUAL), - 'createdAt' => array( - 'date' => array('year' => $year, 'month' => 9, 'day' => 27), - 'time' => array('hour' => 13, 'minute' => 21), - ), - )); + $form->submit(['name' => ['text' => 'blabla', 'condition_pattern' => FilterOperands::STRING_ENDS], 'position' => ['text' => 2, 'condition_operator' => FilterOperands::OPERATOR_LOWER_THAN_EQUAL], 'createdAt' => ['date' => ['year' => $year, 'month' => 9, 'day' => 27], 'time' => ['hour' => 13, 'minute' => 21]]]); $filterQueryBuilder->addFilterConditions($form, $doctrineQueryBuilder); $this->assertEquals($dqls[6], $doctrineQueryBuilder->{$method}()); - $this->assertEquals(array('p_i_position' => 2, 'p_i_createdAt' => new \DateTime("{$year}-09-27 13:21:00")), $this->getQueryBuilderParameters($doctrineQueryBuilder)); + $this->assertEquals(['p_i_position' => 2, 'p_i_createdAt' => new \DateTime("{$year}-09-27 13:21:00")], $this->getQueryBuilderParameters($doctrineQueryBuilder)); } protected function createDisabledFieldTest($method, array $dqls) { - $form = $this->formFactory->create(ItemFilterType::class, null, array( - 'with_selector' => false, - 'disabled_name' => true, - )); + $form = $this->formFactory->create(ItemFilterType::class, null, ['with_selector' => false, 'disabled_name' => true]); $filterQueryBuilder = $this->initQueryBuilderUpdater(); $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); - $form->submit(array('name' => 'blabla', 'position' => 2)); + $form->submit(['name' => 'blabla', 'position' => 2]); $filterQueryBuilder->addFilterConditions($form, $doctrineQueryBuilder); $this->assertEquals($dqls[0], $doctrineQueryBuilder->{$method}()); @@ -173,7 +154,7 @@ protected function createApplyFilterOptionTest($method, array $dqls) $filterQueryBuilder = $this->initQueryBuilderUpdater(); $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); - $form->submit(array('name' => 'blabla', 'position' => 2)); + $form->submit(['name' => 'blabla', 'position' => 2]); $filterQueryBuilder->addFilterConditions($form, $doctrineQueryBuilder); $this->assertEquals($dqls[0], $doctrineQueryBuilder->{$method}()); @@ -186,14 +167,11 @@ protected function createNumberRangeTest($method, array $dqls) $filterQueryBuilder = $this->initQueryBuilderUpdater(); $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); - $form->submit(array('position' => array('left_number' => 1, 'right_number' => 3))); + $form->submit(['position' => ['left_number' => 1, 'right_number' => 3]]); $filterQueryBuilder->addFilterConditions($form, $doctrineQueryBuilder); $this->assertEquals($dqls[0], $doctrineQueryBuilder->{$method}()); - $this->assertEquals(array( - 'p_i_position_left' => 1, - 'p_i_position_right' => 3, - ), $this->getQueryBuilderParameters($doctrineQueryBuilder)); + $this->assertEquals(['p_i_position_left' => 1, 'p_i_position_right' => 3], $this->getQueryBuilderParameters($doctrineQueryBuilder)); } protected function createNumberRangeCompoundTest($method, array $dqls) @@ -203,17 +181,11 @@ protected function createNumberRangeCompoundTest($method, array $dqls) $filterQueryBuilder = $this->initQueryBuilderUpdater(); $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); - $form->submit(array('position_selector' => array( - 'left_number' => array('text' => 4, 'condition_operator' => FilterOperands::OPERATOR_GREATER_THAN), - 'right_number' => array('text' => 8, 'condition_operator' => FilterOperands::OPERATOR_LOWER_THAN_EQUAL), - ))); + $form->submit(['position_selector' => ['left_number' => ['text' => 4, 'condition_operator' => FilterOperands::OPERATOR_GREATER_THAN], 'right_number' => ['text' => 8, 'condition_operator' => FilterOperands::OPERATOR_LOWER_THAN_EQUAL]]]); $filterQueryBuilder->addFilterConditions($form, $doctrineQueryBuilder); $this->assertEquals($dqls[0], $doctrineQueryBuilder->{$method}()); - $this->assertEquals(array( - 'p_i_position_selector_left' => 4, - 'p_i_position_selector_right' => 8, - ), $this->getQueryBuilderParameters($doctrineQueryBuilder)); + $this->assertEquals(['p_i_position_selector_left' => 4, 'p_i_position_selector_right' => 8], $this->getQueryBuilderParameters($doctrineQueryBuilder)); } protected function createNumberRangeDefaultValuesTest($method, array $dqls) @@ -223,14 +195,11 @@ protected function createNumberRangeDefaultValuesTest($method, array $dqls) $filterQueryBuilder = $this->initQueryBuilderUpdater(); $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); - $form->submit(array('default_position' => array('left_number' => 1, 'right_number' => 3))); + $form->submit(['default_position' => ['left_number' => 1, 'right_number' => 3]]); $filterQueryBuilder->addFilterConditions($form, $doctrineQueryBuilder); $this->assertEquals($dqls[0], $doctrineQueryBuilder->{$method}()); - $this->assertEquals(array( - 'p_i_default_position_left' => 1, - 'p_i_default_position_right' => 3, - ), $this->getQueryBuilderParameters($doctrineQueryBuilder)); + $this->assertEquals(['p_i_default_position_left' => 1, 'p_i_default_position_right' => 3], $this->getQueryBuilderParameters($doctrineQueryBuilder)); } protected function createDateRangeTest($method, array $dqls) @@ -240,12 +209,7 @@ protected function createDateRangeTest($method, array $dqls) $filterQueryBuilder = $this->initQueryBuilderUpdater(); $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); - $form->submit(array( - 'createdAt' => array( - 'left_date' => '2012-05-12', - 'right_date' => array('year' => '2012', 'month' => '5', 'day' => '22'), - ), - )); + $form->submit(['createdAt' => ['left_date' => '2012-05-12', 'right_date' => ['year' => '2012', 'month' => '5', 'day' => '22']]]); $filterQueryBuilder->addFilterConditions($form, $doctrineQueryBuilder); $this->assertEquals($dqls[0], $doctrineQueryBuilder->{$method}()); @@ -255,12 +219,7 @@ protected function createDateRangeWithTimezoneTest($method, array $dqls) { // same dates $form = $this->formFactory->create(RangeFilterType::class); - $form->submit(array( - 'startAt' => array( - 'left_date' => '2015-10-20', - 'right_date' => '2015-10-20', - ), - )); + $form->submit(['startAt' => ['left_date' => '2015-10-20', 'right_date' => '2015-10-20']]); $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); @@ -270,12 +229,7 @@ protected function createDateRangeWithTimezoneTest($method, array $dqls) // different dates $form = $this->formFactory->create(RangeFilterType::class); - $form->submit(array( - 'startAt' => array( - 'left_date' => '2015-10-01', - 'right_date' => '2015-10-16', - ), - )); + $form->submit(['startAt' => ['left_date' => '2015-10-01', 'right_date' => '2015-10-16']]); $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); @@ -291,18 +245,7 @@ public function createDateTimeRangeTest($method, array $dqls) $filterQueryBuilder = $this->initQueryBuilderUpdater(); $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); - $form->submit(array( - 'updatedAt' => array( - 'left_datetime' => array( - 'date' => '2012-05-12', - 'time' => '14:55', - ), - 'right_datetime' => array( - 'date' => array('year' => '2012', 'month' => '6', 'day' => '10'), - 'time' => array('hour' => 22, 'minute' => 12), - ), - ), - )); + $form->submit(['updatedAt' => ['left_datetime' => ['date' => '2012-05-12', 'time' => '14:55'], 'right_datetime' => ['date' => ['year' => '2012', 'month' => '6', 'day' => '10'], 'time' => ['hour' => 22, 'minute' => 12]]]]); $filterQueryBuilder->addFilterConditions($form, $doctrineQueryBuilder); $this->assertEquals($dqls[0], $doctrineQueryBuilder->{$method}()); @@ -314,10 +257,7 @@ public function createFilterStandardTypeTest($method, array $dqls) $filterQueryBuilder = $this->initQueryBuilderUpdater(); $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); - $form->submit(array( - 'name' => 'hey dude', - 'position' => 99, - )); + $form->submit(['name' => 'hey dude', 'position' => 99]); $filterQueryBuilder->addFilterConditions($form, $doctrineQueryBuilder); $this->assertEquals($dqls[0], $doctrineQueryBuilder->{$method}()); diff --git a/Tests/Filter/Doctrine/MongodbQueryBuilderUpdaterTest.php b/Tests/Filter/Doctrine/MongodbQueryBuilderUpdaterTest.php index aa92f92..3d5dddd 100644 --- a/Tests/Filter/Doctrine/MongodbQueryBuilderUpdaterTest.php +++ b/Tests/Filter/Doctrine/MongodbQueryBuilderUpdaterTest.php @@ -2,16 +2,18 @@ namespace Lexik\Bundle\FormFilterBundle\Tests\Filter\Doctrine; +use Doctrine\ODM\MongoDB\DocumentManager; use Doctrine\ODM\MongoDB\Query\Builder; use Lexik\Bundle\FormFilterBundle\Filter\Condition\ConditionBuilderInterface; +use Lexik\Bundle\FormFilterBundle\Filter\FilterOperands; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\BooleanFilterType; +use Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Document\Item; use Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Filter\FormType; use Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Filter\ItemCallbackFilterType; use Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Filter\ItemEmbeddedOptionsFilterType; +use Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Filter\ItemFilterType; use Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Filter\RangeFilterType; -use Lexik\Bundle\FormFilterBundle\Filter\FilterOperands; -use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\BooleanFilterType; use Lexik\Bundle\FormFilterBundle\Tests\TestCase; -use Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Filter\ItemFilterType; /** * Mongodb query builder tests. @@ -19,7 +21,7 @@ class MongodbQueryBuilderUpdaterTest extends TestCase { /** - * @var \Doctrine\ODM\MongoDB\DocumentManager + * @var DocumentManager */ protected $dm; @@ -34,21 +36,13 @@ public function testBuildQuery() { $year = '2019'; - $bson = array( - '{}', - '{"$and":[{"name":"blabla"}]}', - '{"$and":[{"name":"blabla"},{"position":{"$gt":2}}]}', - '{"$and":[{"name":"blabla"},{"position":{"$gt":2}},{"enabled":true}]}', - '{"$and":[{"name":"blabla"},{"position":{"$gt":2}},{"enabled":true}]}', - [ - '{"$and":[{"name":{"regex":".*blabla$","flags":"i"}},{"position":{"$lte":2}},{"createdAt":{"$date":{"$numberLong":"1569535200000"}}}]}', - '{"$and":[{"name":"\/.*blabla$\/i"},{"position":{"$lte":2}},{"createdAt":{"$date":{"$numberLong":"1569535200000"}}}]}' - ], - [ - '{"$and":[{"name":{"regex":".*blabla$","flags":"i"}},{"position":{"$lte":2}},{"createdAt":{"$date":{"$numberLong":"1569583260000"}}}]}', - '{"$and":[{"name":"\/.*blabla$\/i"},{"position":{"$lte":2}},{"createdAt":{"$date":{"$numberLong":"1569583260000"}}}]}' - ], - ); + $bson = ['{}', '{"$and":[{"name":"blabla"}]}', '{"$and":[{"name":"blabla"},{"position":{"$gt":2}}]}', '{"$and":[{"name":"blabla"},{"position":{"$gt":2}},{"enabled":true}]}', '{"$and":[{"name":"blabla"},{"position":{"$gt":2}},{"enabled":true}]}', [ + '{"$and":[{"name":{"regex":".*blabla$","flags":"i"}},{"position":{"$lte":2}},{"createdAt":{"$date":{"$numberLong":"1569535200000"}}}]}', + '{"$and":[{"name":"\/.*blabla$\/i"},{"position":{"$lte":2}},{"createdAt":{"$date":{"$numberLong":"1569535200000"}}}]}' + ], [ + '{"$and":[{"name":{"regex":".*blabla$","flags":"i"}},{"position":{"$lte":2}},{"createdAt":{"$date":{"$numberLong":"1569583260000"}}}]}', + '{"$and":[{"name":"\/.*blabla$\/i"},{"position":{"$lte":2}},{"createdAt":{"$date":{"$numberLong":"1569583260000"}}}]}' + ]]; $form = $this->formFactory->create(ItemFilterType::class); $filterQueryBuilder = $this->initQueryBuilderUpdater(); @@ -61,7 +55,7 @@ public function testBuildQuery() // bind a request to the form - 1 params $mongoQB = $this->createDoctrineQueryBuilder(); - $form->submit(array('name' => 'blabla', 'position' => '')); + $form->submit(['name' => 'blabla', 'position' => '']); $filterQueryBuilder->addFilterConditions($form, $mongoQB); $this->assertEquals($bson[1], $this->toBson($mongoQB->getQueryArray())); @@ -70,7 +64,7 @@ public function testBuildQuery() $form = $this->formFactory->create(ItemFilterType::class); $mongoQB = $this->createDoctrineQueryBuilder(); - $form->submit(array('name' => 'blabla', 'position' => 2)); + $form->submit(['name' => 'blabla', 'position' => 2]); $filterQueryBuilder->addFilterConditions($form, $mongoQB); $this->assertEquals($bson[2], $this->toBson($mongoQB->getQueryArray())); @@ -79,52 +73,34 @@ public function testBuildQuery() $form = $this->formFactory->create(ItemFilterType::class); $mongoQB = $this->createDoctrineQueryBuilder(); - $form->submit(array('name' => 'blabla', 'position' => 2, 'enabled' => BooleanFilterType::VALUE_YES)); + $form->submit(['name' => 'blabla', 'position' => 2, 'enabled' => BooleanFilterType::VALUE_YES]); $filterQueryBuilder->addFilterConditions($form, $mongoQB); $this->assertEquals($bson[3], $this->toBson($mongoQB->getQueryArray())); // bind a request to the form - 3 params (use checkbox for enabled field) - $form = $this->formFactory->create(ItemFilterType::class, null, array( - 'checkbox' => true, - )); + $form = $this->formFactory->create(ItemFilterType::class, null, ['checkbox' => true]); $mongoQB = $this->createDoctrineQueryBuilder(); - $form->submit(array('name' => 'blabla', 'position' => 2, 'enabled' => 'yes')); + $form->submit(['name' => 'blabla', 'position' => 2, 'enabled' => 'yes']); $filterQueryBuilder->addFilterConditions($form, $mongoQB); $this->assertEquals($bson[4], $this->toBson($mongoQB->getQueryArray())); // bind a request to the form - date + pattern selector - $form = $this->formFactory->create(ItemFilterType::class, null, array( - 'with_selector' => true, - )); + $form = $this->formFactory->create(ItemFilterType::class, null, ['with_selector' => true]); $mongoQB = $this->createDoctrineQueryBuilder(); - $form->submit(array( - 'name' => array('text' => 'blabla', 'condition_pattern' => FilterOperands::STRING_ENDS), - 'position' => array('text' => 2, 'condition_operator' => FilterOperands::OPERATOR_LOWER_THAN_EQUAL), - 'createdAt' => array('year' => $year, 'month' => 9, 'day' => 27), - )); + $form->submit(['name' => ['text' => 'blabla', 'condition_pattern' => FilterOperands::STRING_ENDS], 'position' => ['text' => 2, 'condition_operator' => FilterOperands::OPERATOR_LOWER_THAN_EQUAL], 'createdAt' => ['year' => $year, 'month' => 9, 'day' => 27]]); $filterQueryBuilder->addFilterConditions($form, $mongoQB); $this->assertContains($this->toBson($mongoQB->getQueryArray()), $bson[5]); // bind a request to the form - datetime + pattern selector - $form = $this->formFactory->create(ItemFilterType::class, null, array( - 'with_selector' => true, - 'datetime' => true, - )); + $form = $this->formFactory->create(ItemFilterType::class, null, ['with_selector' => true, 'datetime' => true]); $mongoQB = $this->createDoctrineQueryBuilder(); - $form->submit(array( - 'name' => array('text' => 'blabla', 'condition_pattern' => FilterOperands::STRING_ENDS), - 'position' => array('text' => 2, 'condition_operator' => FilterOperands::OPERATOR_LOWER_THAN_EQUAL), - 'createdAt' => array( - 'date' => array('year' => $year, 'month' => 9, 'day' => 27), - 'time' => array('hour' => 13, 'minute' => 21), - ), - )); + $form->submit(['name' => ['text' => 'blabla', 'condition_pattern' => FilterOperands::STRING_ENDS], 'position' => ['text' => 2, 'condition_operator' => FilterOperands::OPERATOR_LOWER_THAN_EQUAL], 'createdAt' => ['date' => ['year' => $year, 'month' => 9, 'day' => 27], 'time' => ['hour' => 13, 'minute' => 21]]]); $filterQueryBuilder->addFilterConditions($form, $mongoQB); $this->assertContains($this->toBson($mongoQB->getQueryArray()), $bson[6]); @@ -132,11 +108,8 @@ public function testBuildQuery() public function testDisabledFieldQuery() { - $form = $this->formFactory->create(ItemFilterType::class, null, array( - 'with_selector' => false, - 'disabled_name' => true, - )); - $form->submit(array('name' => 'blabla', 'position' => 2)); + $form = $this->formFactory->create(ItemFilterType::class, null, ['with_selector' => false, 'disabled_name' => true]); + $form->submit(['name' => 'blabla', 'position' => 2]); $mongoQB = $this->createDoctrineQueryBuilder(); @@ -151,7 +124,7 @@ public function testDisabledFieldQuery() public function testApplyFilterOption() { $form = $this->formFactory->create(ItemCallbackFilterType::class); - $form->submit(array('name' => 'blabla', 'position' => 2)); + $form->submit(['name' => 'blabla', 'position' => 2]); $mongoQB = $this->createDoctrineQueryBuilder(); @@ -167,7 +140,7 @@ public function testNumberRange() { // use filter type options $form = $this->formFactory->create(RangeFilterType::class); - $form->submit(array('position' => array('left_number' => 1, 'right_number' => 3))); + $form->submit(['position' => ['left_number' => 1, 'right_number' => 3]]); $mongoQB = $this->createDoctrineQueryBuilder(); @@ -183,10 +156,7 @@ public function testNumberRangeWithSelector() { // use filter type options $form = $this->formFactory->create(RangeFilterType::class); - $form->submit(array('position_selector' => array( - 'left_number' => array('text' => 4, 'condition_operator' => FilterOperands::OPERATOR_GREATER_THAN), - 'right_number' => array('text' => 8, 'condition_operator' => FilterOperands::OPERATOR_LOWER_THAN_EQUAL), - ))); + $form->submit(['position_selector' => ['left_number' => ['text' => 4, 'condition_operator' => FilterOperands::OPERATOR_GREATER_THAN], 'right_number' => ['text' => 8, 'condition_operator' => FilterOperands::OPERATOR_LOWER_THAN_EQUAL]]]); $mongoQB = $this->createDoctrineQueryBuilder(); @@ -202,7 +172,7 @@ public function testNumberRangeDefaultValues() { // use filter type options $form = $this->formFactory->create(RangeFilterType::class); - $form->submit(array('default_position' => array('left_number' => 1, 'right_number' => 3))); + $form->submit(['default_position' => ['left_number' => 1, 'right_number' => 3]]); $mongoQB = $this->createDoctrineQueryBuilder(); @@ -218,12 +188,7 @@ public function testDateRange() { // use filter type options $form = $this->formFactory->create(RangeFilterType::class); - $form->submit(array( - 'createdAt' => array( - 'left_date' => '2012-05-12', - 'right_date' => array('year' => '2012', 'month' => '5', 'day' => '22'), - ), - )); + $form->submit(['createdAt' => ['left_date' => '2012-05-12', 'right_date' => ['year' => '2012', 'month' => '5', 'day' => '22']]]); $leftTimestamp = (new \DateTime('2012-05-12'))->getTimestamp() * 1000; @@ -234,7 +199,7 @@ public function testDateRange() $this->initQueryBuilderUpdater()->addFilterConditions($form, $mongoQB); $this->assertEquals( - '{"$and":[{"createdAt":{"$gte":{"$date":{"$numberLong":"'.$leftTimestamp.'"}},"$lt":{"$date":{"$numberLong":"'.$rightTimestamp.'"}}}}]}', + '{"$and":[{"createdAt":{"$gte":{"$date":{"$numberLong":"' . $leftTimestamp . '"}},"$lt":{"$date":{"$numberLong":"' . $rightTimestamp . '"}}}}]}', $this->toBson($mongoQB->getQueryArray()) ); } @@ -243,18 +208,7 @@ public function testDateTimeRange() { // use filter type options $form = $this->formFactory->create(RangeFilterType::class); - $form->submit(array( - 'updatedAt' => array( - 'left_datetime' => array( - 'date' => '2012-05-12', - 'time' => '14:55', - ), - 'right_datetime' => array( - 'date' => array('year' => '2012', 'month' => '6', 'day' => '10'), - 'time' => array('hour' => 22, 'minute' => 12), - ), - ), - )); + $form->submit(['updatedAt' => ['left_datetime' => ['date' => '2012-05-12', 'time' => '14:55'], 'right_datetime' => ['date' => ['year' => '2012', 'month' => '6', 'day' => '10'], 'time' => ['hour' => 22, 'minute' => 12]]]]); $leftTimestamp = (new \DateTime('2012-05-12 14:55:00'))->getTimestamp() * 1000; $rightTimestamp = (new \DateTime('2012-06-10 22:12:00'))->getTimestamp() * 1000; @@ -264,7 +218,7 @@ public function testDateTimeRange() $this->initQueryBuilderUpdater()->addFilterConditions($form, $mongoQB); $this->assertEquals( - '{"$and":[{"updatedAt":{"$gte":{"$date":{"$numberLong":"'.$leftTimestamp.'"}},"$lt":{"$date":{"$numberLong":"'.$rightTimestamp.'"}}}}]}', + '{"$and":[{"updatedAt":{"$gte":{"$date":{"$numberLong":"' . $leftTimestamp . '"}},"$lt":{"$date":{"$numberLong":"' . $rightTimestamp . '"}}}}]}', $this->toBson($mongoQB->getQueryArray()) ); } @@ -272,10 +226,7 @@ public function testDateTimeRange() public function testFilterStandardType() { $form = $this->formFactory->create(FormType::class); - $form->submit(array( - 'name' => 'hey dude', - 'position' => 99, - )); + $form->submit(['name' => 'hey dude', 'position' => 99]); $mongoQB = $this->createDoctrineQueryBuilder(); @@ -293,10 +244,8 @@ public function testFilterStandardType() public function testEmbedFormFilter() { // doctrine query builder without any joins - $form = $this->formFactory->create(ItemEmbeddedOptionsFilterType::class, null, array( - 'doctrine_builder' => 'mongo', - )); - $form->submit(array('name' => 'dude', 'options' => array(array('label' => 'color', 'rank' => 3)))); + $form = $this->formFactory->create(ItemEmbeddedOptionsFilterType::class, null, ['doctrine_builder' => 'mongo']); + $form->submit(['name' => 'dude', 'options' => [['label' => 'color', 'rank' => 3]]]); $mongoQB = $this->createDoctrineQueryBuilder(); @@ -309,10 +258,8 @@ public function testEmbedFormFilter() ); // doctrine query builder without any joins and values for embedded field only - $form = $this->formFactory->create(ItemEmbeddedOptionsFilterType::class, null, array( - 'doctrine_builder' => 'mongo', - )); - $form->submit(array('options' => array(array('label' => 'color', 'rank' => 3)))); + $form = $this->formFactory->create(ItemEmbeddedOptionsFilterType::class, null, ['doctrine_builder' => 'mongo']); + $form->submit(['options' => [['label' => 'color', 'rank' => 3]]]); $mongoQB = $this->createDoctrineQueryBuilder(); @@ -325,15 +272,13 @@ public function testEmbedFormFilter() ); // pre-fill parts - $form = $this->formFactory->create(ItemEmbeddedOptionsFilterType::class, null, array( - 'doctrine_builder' => 'mongo', - )); - $form->submit(array('name' => 'dude', 'options' => array(array('label' => 'size', 'rank' => 5)))); + $form = $this->formFactory->create(ItemEmbeddedOptionsFilterType::class, null, ['doctrine_builder' => 'mongo']); + $form->submit(['name' => 'dude', 'options' => [['label' => 'size', 'rank' => 5]]]); $mongoQB = $this->createDoctrineQueryBuilder(); $filterQueryBuilder = $this->initQueryBuilderUpdater(); - $filterQueryBuilder->setParts(array('options' => 'options')); + $filterQueryBuilder->setParts(['options' => 'options']); $filterQueryBuilder->addFilterConditions($form, $mongoQB); $this->assertEquals( @@ -347,21 +292,18 @@ public function testCustomConditionBuilder() $filterQueryBuilder = $this->initQueryBuilderUpdater(); // doctrine query builder without any joins + custom condition builder - $form = $this->formFactory->create(ItemEmbeddedOptionsFilterType::class, null, array( - 'doctrine_builder' => 'mongo', - 'filter_condition_builder' => function (ConditionBuilderInterface $builder) { - $builder - ->root('or') - ->field('options.label') - ->andX() - ->field('options.rank') - ->field('name') - ->end() + $form = $this->formFactory->create(ItemEmbeddedOptionsFilterType::class, null, ['doctrine_builder' => 'mongo', 'filter_condition_builder' => function (ConditionBuilderInterface $builder) { + $builder + ->root('or') + ->field('options.label') + ->andX() + ->field('options.rank') + ->field('name') ->end() - ; - }, - )); - $form->submit(array('name' => 'dude', 'options' => array(array('label' => 'color', 'rank' => 6)))); + ->end() + ; + }]); + $form->submit(['name' => 'dude', 'options' => [['label' => 'color', 'rank' => 6]]]); $mongoQB = $this->createDoctrineQueryBuilder(); @@ -373,24 +315,21 @@ public function testCustomConditionBuilder() ); // doctrine query builder without any joins + custom condition builder - $form = $this->formFactory->create(ItemEmbeddedOptionsFilterType::class, null, array( - 'doctrine_builder' => 'mongo', - 'filter_condition_builder' => function (ConditionBuilderInterface $builder) { - $builder - ->root('and') - ->orX() - ->field('name') - ->field('options.label') - ->end() - ->orX() - ->field('options.rank') - ->field('position') - ->end() + $form = $this->formFactory->create(ItemEmbeddedOptionsFilterType::class, null, ['doctrine_builder' => 'mongo', 'filter_condition_builder' => function (ConditionBuilderInterface $builder) { + $builder + ->root('and') + ->orX() + ->field('name') + ->field('options.label') + ->end() + ->orX() + ->field('options.rank') + ->field('position') ->end() - ; - }, - )); - $form->submit(array('name' => 'dude', 'position' => 1, 'options' => array(array('label' => 'color', 'rank' => 6)))); + ->end() + ; + }]); + $form->submit(['name' => 'dude', 'position' => 1, 'options' => [['label' => 'color', 'rank' => 6]]]); $mongoQB = $this->createDoctrineQueryBuilder(); @@ -404,11 +343,8 @@ public function testCustomConditionBuilder() public function testWithDataClass() { - $form = $this->formFactory->create(ItemEmbeddedOptionsFilterType::class, null, array( - 'data_class' => 'Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Document\Item', - 'doctrine_builder' => 'mongo', - )); - $form->submit(array('name' => 'dude', 'options' => array(array('label' => 'color', 'rank' => 6)))); + $form = $this->formFactory->create(ItemEmbeddedOptionsFilterType::class, null, ['data_class' => Item::class, 'doctrine_builder' => 'mongo']); + $form->submit(['name' => 'dude', 'options' => [['label' => 'color', 'rank' => 6]]]); $mongoQB = $this->createDoctrineQueryBuilder(); @@ -423,7 +359,7 @@ public function testWithDataClass() protected function createDoctrineQueryBuilder(): Builder { return $this->dm - ->getRepository('Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Document\Item') + ->getRepository(Item::class) ->createQueryBuilder(); } diff --git a/Tests/Filter/Doctrine/ORMQueryBuilderUpdaterTest.php b/Tests/Filter/Doctrine/ORMQueryBuilderUpdaterTest.php index e40ca1c..f51c33a 100644 --- a/Tests/Filter/Doctrine/ORMQueryBuilderUpdaterTest.php +++ b/Tests/Filter/Doctrine/ORMQueryBuilderUpdaterTest.php @@ -3,6 +3,7 @@ namespace Lexik\Bundle\FormFilterBundle\Tests\Filter\Doctrine; use Lexik\Bundle\FormFilterBundle\Filter\Condition\ConditionBuilderInterface; +use Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item; use Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Filter\ItemEmbeddedOptionsFilterType; /** @@ -14,79 +15,52 @@ class ORMQueryBuilderUpdaterTest extends DoctrineQueryBuilderUpdater { public function testBuildQuery() { - parent::createBuildQueryTest('getDQL', array( - 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i', - 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.name LIKE \'blabla\'', - 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.name LIKE \'blabla\' AND i.position > :p_i_position', - 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.name LIKE \'blabla\' AND i.position > :p_i_position AND i.enabled = :p_i_enabled', - 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.name LIKE \'blabla\' AND i.position > :p_i_position AND i.enabled = :p_i_enabled', - 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.name LIKE \'%blabla\' AND i.position <= :p_i_position AND i.createdAt = :p_i_createdAt', - 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.name LIKE \'%blabla\' AND i.position <= :p_i_position AND i.createdAt = :p_i_createdAt', - )); + parent::createBuildQueryTest('getDQL', ['SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i', 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.name LIKE \'blabla\'', 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.name LIKE \'blabla\' AND i.position > :p_i_position', 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.name LIKE \'blabla\' AND i.position > :p_i_position AND i.enabled = :p_i_enabled', 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.name LIKE \'blabla\' AND i.position > :p_i_position AND i.enabled = :p_i_enabled', 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.name LIKE \'%blabla\' AND i.position <= :p_i_position AND i.createdAt = :p_i_createdAt', 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.name LIKE \'%blabla\' AND i.position <= :p_i_position AND i.createdAt = :p_i_createdAt']); } public function testDisabledFieldQuery() { - parent::createDisabledFieldTest('getDQL', array( - 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.position > :p_i_position', - )); + parent::createDisabledFieldTest('getDQL', ['SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.position > :p_i_position']); } public function testApplyFilterOption() { - parent::createApplyFilterOptionTest('getDQL', array( - 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.name <> \'blabla\' AND i.position <> 2', - )); + parent::createApplyFilterOptionTest('getDQL', ['SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.name <> \'blabla\' AND i.position <> 2']); } public function testNumberRange() { - parent::createNumberRangeTest('getDQL', array( - 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.position > :p_i_position_left AND i.position < :p_i_position_right', - )); + parent::createNumberRangeTest('getDQL', ['SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.position > :p_i_position_left AND i.position < :p_i_position_right']); } public function testNumberRangeWithSelector() { - parent::createNumberRangeCompoundTest('getDQL', array( - 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.position_selector > :p_i_position_selector_left AND i.position_selector <= :p_i_position_selector_right', - )); + parent::createNumberRangeCompoundTest('getDQL', ['SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.position_selector > :p_i_position_selector_left AND i.position_selector <= :p_i_position_selector_right']); } public function testNumberRangeDefaultValues() { - parent::createNumberRangeDefaultValuesTest('getDQL', array( - 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.default_position >= :p_i_default_position_left AND i.default_position <= :p_i_default_position_right', - )); + parent::createNumberRangeDefaultValuesTest('getDQL', ['SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.default_position >= :p_i_default_position_left AND i.default_position <= :p_i_default_position_right']); } public function testDateRange() { - parent::createDateRangeTest('getDQL', array( - 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.createdAt <= \'2012-05-22 23:59:59\' AND i.createdAt >= \'2012-05-12 00:00:00\'', - )); + parent::createDateRangeTest('getDQL', ['SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.createdAt <= \'2012-05-22 23:59:59\' AND i.createdAt >= \'2012-05-12 00:00:00\'']); } public function testDateRangeWithTimezone() { - parent::createDateRangeWithTimezoneTest('getDQL', array( - 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.startAt <= \'2015-10-20 18:59:59\' AND i.startAt >= \'2015-10-19 19:00:00\'', - 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.startAt <= \'2015-10-16 18:59:59\' AND i.startAt >= \'2015-09-30 19:00:00\'', - )); + parent::createDateRangeWithTimezoneTest('getDQL', ['SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.startAt <= \'2015-10-20 18:59:59\' AND i.startAt >= \'2015-10-19 19:00:00\'', 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.startAt <= \'2015-10-16 18:59:59\' AND i.startAt >= \'2015-09-30 19:00:00\'']); } public function testDateTimeRange() { - parent::createDateTimeRangeTest('getDQL', array( - 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.updatedAt <= \'2012-06-10 22:12:00\' AND i.updatedAt >= \'2012-05-12 14:55:00\'', - )); + parent::createDateTimeRangeTest('getDQL', ['SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.updatedAt <= \'2012-06-10 22:12:00\' AND i.updatedAt >= \'2012-05-12 14:55:00\'']); } public function testFilterStandardType() { - parent::createFilterStandardTypeTest('getDQL', array( - 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.name LIKE \'%hey dude%\' AND i.position = 99', - )); + parent::createFilterStandardTypeTest('getDQL', ['SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i WHERE i.name LIKE \'%hey dude%\' AND i.position = 99']); } public function testEmbedFormFilter() @@ -96,14 +70,14 @@ public function testEmbedFormFilter() $filterQueryBuilder = $this->initQueryBuilderUpdater(); $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); - $form->submit(array('name' => 'dude', 'options' => array(array('label' => 'color', 'rank' => 3)))); + $form->submit(['name' => 'dude', 'options' => [['label' => 'color', 'rank' => 3]]]); $expectedDql = 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i'; $expectedDql .= ' LEFT JOIN i.options opt WHERE i.name LIKE \'dude\' AND (opt.label LIKE \'color\' AND opt.rank = :p_opt_rank)'; $filterQueryBuilder->addFilterConditions($form, $doctrineQueryBuilder); $this->assertEquals($expectedDql, $doctrineQueryBuilder->getDql()); - $this->assertEquals(array('p_opt_rank' => 3), $this->getQueryBuilderParameters($doctrineQueryBuilder)); + $this->assertEquals(['p_opt_rank' => 3], $this->getQueryBuilderParameters($doctrineQueryBuilder)); // doctrine query builder with joins $form = $this->formFactory->create(ItemEmbeddedOptionsFilterType::class); @@ -111,99 +85,93 @@ public function testEmbedFormFilter() $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); $doctrineQueryBuilder->leftJoin('i.options', 'o'); - $form->submit(array('name' => 'dude', 'options' => array(array('label' => 'size', 'rank' => 5)))); + $form->submit(['name' => 'dude', 'options' => [['label' => 'size', 'rank' => 5]]]); $expectedDql = 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i'; $expectedDql .= ' LEFT JOIN i.options o WHERE i.name LIKE \'dude\' AND (o.label LIKE \'size\' AND o.rank = :p_o_rank)'; - $filterQueryBuilder->setParts(array('i.options' => 'o')); + $filterQueryBuilder->setParts(['i.options' => 'o']); $filterQueryBuilder->addFilterConditions($form, $doctrineQueryBuilder); $this->assertEquals($expectedDql, $doctrineQueryBuilder->getDql()); - $this->assertEquals(array('p_o_rank' => 5), $this->getQueryBuilderParameters($doctrineQueryBuilder)); + $this->assertEquals(['p_o_rank' => 5], $this->getQueryBuilderParameters($doctrineQueryBuilder)); } public function testCustomConditionBuilder() { // doctrine query builder without any joins + custom condition builder - $form = $this->formFactory->create(ItemEmbeddedOptionsFilterType::class, null, array( - 'filter_condition_builder' => function (ConditionBuilderInterface $builder) { - $builder - ->root('or') - ->field('options.label') - ->andX() - ->field('options.rank') - ->field('name') - ->end() + $form = $this->formFactory->create(ItemEmbeddedOptionsFilterType::class, null, ['filter_condition_builder' => function (ConditionBuilderInterface $builder) { + $builder + ->root('or') + ->field('options.label') + ->andX() + ->field('options.rank') + ->field('name') ->end() - ; - }, - )); + ->end() + ; + }]); $filterQueryBuilder = $this->initQueryBuilderUpdater(); $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); - $form->submit(array('name' => 'dude', 'options' => array(array('label' => 'color', 'rank' => 6)))); + $form->submit(['name' => 'dude', 'options' => [['label' => 'color', 'rank' => 6]]]); $expectedDql = 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i'; $expectedDql .= ' LEFT JOIN i.options opt WHERE opt.label LIKE \'color\' OR (opt.rank = :p_opt_rank AND i.name LIKE \'dude\')'; $filterQueryBuilder->addFilterConditions($form, $doctrineQueryBuilder); $this->assertEquals($expectedDql, $doctrineQueryBuilder->getDql()); - $this->assertEquals(array('p_opt_rank' => 6), $this->getQueryBuilderParameters($doctrineQueryBuilder)); + $this->assertEquals(['p_opt_rank' => 6], $this->getQueryBuilderParameters($doctrineQueryBuilder)); // doctrine query builder without any joins + custom condition builder - $form = $this->formFactory->create(ItemEmbeddedOptionsFilterType::class, null, array( - 'filter_condition_builder' => function (ConditionBuilderInterface $builder) { - $builder - ->root('and') - ->orX() - ->field('name') - ->field('options.label') - ->end() - ->orX() - ->field('options.rank') - ->field('position') - ->end() - ->end() - ; - }, - )); + $form = $this->formFactory->create(ItemEmbeddedOptionsFilterType::class, null, ['filter_condition_builder' => function (ConditionBuilderInterface $builder) { + $builder + ->root('and') + ->orX() + ->field('name') + ->field('options.label') + ->end() + ->orX() + ->field('options.rank') + ->field('position') + ->end() + ->end() + ; + }]); $filterQueryBuilder = $this->initQueryBuilderUpdater(); $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); - $form->submit(array('name' => 'dude', 'position' => 1, 'options' => array(array('label' => 'color', 'rank' => 6)))); + $form->submit(['name' => 'dude', 'position' => 1, 'options' => [['label' => 'color', 'rank' => 6]]]); $expectedDql = 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i'; $expectedDql .= ' LEFT JOIN i.options opt WHERE (i.name LIKE \'dude\' OR opt.label LIKE \'color\') AND (opt.rank = :p_opt_rank OR i.position = :p_i_position)'; $filterQueryBuilder->addFilterConditions($form, $doctrineQueryBuilder); $this->assertEquals($expectedDql, $doctrineQueryBuilder->getDql()); - $this->assertEquals(array('p_opt_rank' => 6, 'p_i_position' => 1), $this->getQueryBuilderParameters($doctrineQueryBuilder)); + $this->assertEquals(['p_opt_rank' => 6, 'p_i_position' => 1], $this->getQueryBuilderParameters($doctrineQueryBuilder)); } public function testWithDataClass() { // doctrine query builder without any joins + a data_class - $form = $this->formFactory->create(ItemEmbeddedOptionsFilterType::class, null, array( - 'data_class' => 'Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item', - )); + $form = $this->formFactory->create(ItemEmbeddedOptionsFilterType::class, null, ['data_class' => Item::class]); $filterQueryBuilder = $this->initQueryBuilderUpdater(); $doctrineQueryBuilder = $this->createDoctrineQueryBuilder(); - $form->submit(array('name' => 'dude', 'options' => array(array('label' => 'color', 'rank' => 6)))); + $form->submit(['name' => 'dude', 'options' => [['label' => 'color', 'rank' => 6]]]); $expectedDql = 'SELECT i FROM Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item i'; $expectedDql .= ' LEFT JOIN i.options opt WHERE i.name LIKE \'dude\' AND (opt.label LIKE \'color\' AND opt.rank = :p_opt_rank)'; $filterQueryBuilder->addFilterConditions($form, $doctrineQueryBuilder); $this->assertEquals($expectedDql, $doctrineQueryBuilder->getDql()); - $this->assertEquals(array('p_opt_rank' => 6), $this->getQueryBuilderParameters($doctrineQueryBuilder)); + $this->assertEquals(['p_opt_rank' => 6], $this->getQueryBuilderParameters($doctrineQueryBuilder)); } protected function createDoctrineQueryBuilder() { return $this->em - ->getRepository('Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Entity\Item') + ->getRepository(Item::class) ->createQueryBuilder('i'); } } diff --git a/Tests/Filter/Doctrine/ORMQueryTest.php b/Tests/Filter/Doctrine/ORMQueryTest.php index dd1ea9b..2c5f332 100644 --- a/Tests/Filter/Doctrine/ORMQueryTest.php +++ b/Tests/Filter/Doctrine/ORMQueryTest.php @@ -1,8 +1,11 @@ getMockBuilder('Doctrine\ORM\EntityManager') + $emMock = $this->getMockBuilder(EntityManager::class) ->disableOriginalConstructor() ->getMock(); $emMock ->expects($this->any()) ->method('getExpressionBuilder') - ->will($this->returnValue(new \Doctrine\ORM\Query\Expr())); + ->will($this->returnValue(new Expr())); $qb = new QueryBuilder($emMock); $qb->from('Root', 'r'); diff --git a/Tests/Fixtures/Filter/FormType.php b/Tests/Fixtures/Filter/FormType.php index 97b79e0..3c71aec 100644 --- a/Tests/Fixtures/Filter/FormType.php +++ b/Tests/Fixtures/Filter/FormType.php @@ -5,9 +5,9 @@ use Doctrine\ODM\MongoDB\Query\Expr; use Lexik\Bundle\FormFilterBundle\Filter\Query\QueryInterface; use Symfony\Component\Form\AbstractType; -use Symfony\Component\Form\FormBuilderInterface; -use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\Extension\Core\Type\IntegerType; +use Symfony\Component\Form\Extension\Core\Type\TextType; +use Symfony\Component\Form\FormBuilderInterface; /** * Form filter for tests. @@ -16,30 +16,28 @@ */ class FormType extends AbstractType { - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('name', TextType::class); - $builder->add('position', IntegerType::class, array( - 'apply_filter' => function (QueryInterface $filterQuery, $field, $values) { - if (!empty($values['value'])) { - if ($filterQuery->getExpr() instanceof Expr) { - $expr = $filterQuery->getExpr()->field($field)->equals($values['value']); - } else { - $expr = $filterQuery->getExpr()->eq($field, $values['value']); - } - - return $filterQuery->createCondition($expr); + $builder->add('position', IntegerType::class, ['apply_filter' => function (QueryInterface $filterQuery, $field, $values) { + if (!empty($values['value'])) { + if ($filterQuery->getExpr() instanceof Expr) { + $expr = $filterQuery->getExpr()->field($field)->equals($values['value']); + } else { + $expr = $filterQuery->getExpr()->eq($field, $values['value']); } - return null; - }, - )); + return $filterQuery->createCondition($expr); + } + + return null; + }]); } /** * @return string */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'my_form'; } diff --git a/Tests/Fixtures/Filter/ItemCallbackFilterType.php b/Tests/Fixtures/Filter/ItemCallbackFilterType.php index b2d29f7..d4c96e1 100644 --- a/Tests/Fixtures/Filter/ItemCallbackFilterType.php +++ b/Tests/Fixtures/Filter/ItemCallbackFilterType.php @@ -16,32 +16,28 @@ */ class ItemCallbackFilterType extends AbstractType { - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { - $builder->add('name', TextFilterType::class, array( - 'apply_filter' => array($this, 'fieldNameCallback'), - )); - $builder->add('position', NumberFilterType::class, array( - 'apply_filter' => function (QueryInterface $filterQuery, $field, $values) { - if (!empty($values['value'])) { - if ($filterQuery->getExpr() instanceof Expr) { - $expr = $filterQuery->getExpr()->field($field)->notEqual($values['value']); - } else { - $expr = $filterQuery->getExpr()->neq($field, $values['value']); - } - - return $filterQuery->createCondition($expr); + $builder->add('name', TextFilterType::class, ['apply_filter' => [$this, 'fieldNameCallback']]); + $builder->add('position', NumberFilterType::class, ['apply_filter' => function (QueryInterface $filterQuery, $field, $values) { + if (!empty($values['value'])) { + if ($filterQuery->getExpr() instanceof Expr) { + $expr = $filterQuery->getExpr()->field($field)->notEqual($values['value']); + } else { + $expr = $filterQuery->getExpr()->neq($field, $values['value']); } - return null; - }, - )); + return $filterQuery->createCondition($expr); + } + + return null; + }]); } /** * @return string */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'item_filter'; } diff --git a/Tests/Fixtures/Filter/ItemEmbeddedOptionsFilterType.php b/Tests/Fixtures/Filter/ItemEmbeddedOptionsFilterType.php index a5bd509..5e9335f 100644 --- a/Tests/Fixtures/Filter/ItemEmbeddedOptionsFilterType.php +++ b/Tests/Fixtures/Filter/ItemEmbeddedOptionsFilterType.php @@ -19,7 +19,7 @@ */ class ItemEmbeddedOptionsFilterType extends AbstractType { - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { if ('mongo' === $options['doctrine_builder']) { $addShared = function (FilterBuilderExecuterInterface $qbe) { @@ -30,29 +30,24 @@ public function buildForm(FormBuilderInterface $builder, array $options) $joinClosure = function (QueryBuilder $filterBuilder, $alias, $joinAlias, ORMExpr $expr) { $filterBuilder->leftJoin($alias . '.options', $joinAlias); }; - $qbe->addOnce($qbe->getAlias().'.options', 'opt', $joinClosure); + $qbe->addOnce($qbe->getAlias() . '.options', 'opt', $joinClosure); }; } $builder->add('name', TextFilterType::class); $builder->add('position', NumberFilterType::class); - $builder->add('options', CollectionAdapterFilterType::class, array( - 'entry_type' => OptionFilterType::class, - 'add_shared' => $addShared, - )); + $builder->add('options', CollectionAdapterFilterType::class, ['entry_type' => OptionFilterType::class, 'add_shared' => $addShared]); } - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { - $resolver->setDefaults(array( - 'doctrine_builder' => null, - )); + $resolver->setDefaults(['doctrine_builder' => null]); } /** * @return string */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'item_filter'; } diff --git a/Tests/Fixtures/Filter/ItemFilterType.php b/Tests/Fixtures/Filter/ItemFilterType.php index fed10ec..b75ab98 100644 --- a/Tests/Fixtures/Filter/ItemFilterType.php +++ b/Tests/Fixtures/Filter/ItemFilterType.php @@ -2,9 +2,6 @@ namespace Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Filter; -use Symfony\Component\Form\AbstractType; -use Symfony\Component\Form\FormBuilderInterface; -use Symfony\Component\OptionsResolver\OptionsResolver; use Lexik\Bundle\FormFilterBundle\Filter\FilterOperands; use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\BooleanFilterType; use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\CheckboxFilterType; @@ -12,6 +9,9 @@ use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\DateTimeFilterType; use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\NumberFilterType; use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\TextFilterType; +use Symfony\Component\Form\AbstractType; +use Symfony\Component\Form\FormBuilderInterface; +use Symfony\Component\OptionsResolver\OptionsResolver; /** * Form filter for tests. @@ -20,43 +20,22 @@ */ class ItemFilterType extends AbstractType { - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { if (!$options['with_selector']) { - $builder->add('name', TextFilterType::class, array( - 'apply_filter' => $options['disabled_name'] ? false : null, - )); - $builder->add('position', NumberFilterType::class, array( - 'condition_operator' => FilterOperands::OPERATOR_GREATER_THAN, - )); + $builder->add('name', TextFilterType::class, ['apply_filter' => $options['disabled_name'] ? false : null]); + $builder->add('position', NumberFilterType::class, ['condition_operator' => FilterOperands::OPERATOR_GREATER_THAN]); } else { - $builder->add('name', TextFilterType::class, array( - 'condition_pattern' => FilterOperands::OPERAND_SELECTOR, - )); - $builder->add('position', NumberFilterType::class, array( - 'condition_operator' => FilterOperands::OPERAND_SELECTOR, - )); + $builder->add('name', TextFilterType::class, ['condition_pattern' => FilterOperands::OPERAND_SELECTOR]); + $builder->add('position', NumberFilterType::class, ['condition_operator' => FilterOperands::OPERAND_SELECTOR]); } $builder->add('enabled', $options['checkbox'] ? CheckboxFilterType::class : BooleanFilterType::class); $builder->add('createdAt', $options['datetime'] ? DateTimeFilterType::class : DateFilterType::class); } - public function configureOptions(OptionsResolver $resolver) - { - $resolver->setDefaults(array( - 'with_selector' => false, - 'checkbox' => false, - 'datetime' => false, - 'disabled_name' => false, - )); - } - - /** - * @return string - */ - public function getBlockPrefix() + public function configureOptions(OptionsResolver $resolver): void { - return 'item_filter'; + $resolver->setDefaults(['with_selector' => false, 'checkbox' => false, 'datetime' => false, 'disabled_name' => false]); } } diff --git a/Tests/Fixtures/Filter/OptionFilterType.php b/Tests/Fixtures/Filter/OptionFilterType.php index a91c612..a0060a2 100644 --- a/Tests/Fixtures/Filter/OptionFilterType.php +++ b/Tests/Fixtures/Filter/OptionFilterType.php @@ -2,10 +2,10 @@ namespace Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Filter; -use Symfony\Component\Form\AbstractType; -use Symfony\Component\Form\FormBuilderInterface; use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\NumberFilterType; use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\TextFilterType; +use Symfony\Component\Form\AbstractType; +use Symfony\Component\Form\FormBuilderInterface; /** * Form filter for tests. @@ -14,7 +14,7 @@ */ class OptionFilterType extends AbstractType { - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('label', TextFilterType::class); $builder->add('rank', NumberFilterType::class); @@ -23,7 +23,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) /** * @return string */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'options_filter'; } diff --git a/Tests/Fixtures/Filter/RangeFilterType.php b/Tests/Fixtures/Filter/RangeFilterType.php index c0ae9e2..a9144a1 100644 --- a/Tests/Fixtures/Filter/RangeFilterType.php +++ b/Tests/Fixtures/Filter/RangeFilterType.php @@ -2,12 +2,12 @@ namespace Lexik\Bundle\FormFilterBundle\Tests\Fixtures\Filter; -use Symfony\Component\Form\AbstractType; -use Symfony\Component\Form\FormBuilderInterface; use Lexik\Bundle\FormFilterBundle\Filter\FilterOperands; use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\DateRangeFilterType; use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\DateTimeRangeFilterType; use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\NumberRangeFilterType; +use Symfony\Component\Form\AbstractType; +use Symfony\Component\Form\FormBuilderInterface; /** * Form filter for tests. @@ -16,45 +16,44 @@ */ class RangeFilterType extends AbstractType { - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder - ->add('position', NumberRangeFilterType::class, array( - 'left_number_options' => array('condition_operator' => FilterOperands::OPERATOR_GREATER_THAN), - 'right_number_options' => array('condition_operator' => FilterOperands::OPERATOR_LOWER_THAN), - )) - ->add('position_selector', NumberRangeFilterType::class, array( - 'left_number_options' => array('condition_operator' => FilterOperands::OPERAND_SELECTOR), - 'right_number_options' => array('condition_operator' => FilterOperands::OPERAND_SELECTOR), - )) + ->add( + 'position', + NumberRangeFilterType::class, + ['left_number_options' => ['condition_operator' => FilterOperands::OPERATOR_GREATER_THAN], 'right_number_options' => ['condition_operator' => FilterOperands::OPERATOR_LOWER_THAN]] + ) + ->add( + 'position_selector', + NumberRangeFilterType::class, + ['left_number_options' => ['condition_operator' => FilterOperands::OPERAND_SELECTOR], 'right_number_options' => ['condition_operator' => FilterOperands::OPERAND_SELECTOR]] + ) ->add('default_position', NumberRangeFilterType::class) - ->add('createdAt', DateRangeFilterType::class, array( - 'left_date_options' => array('widget' => 'single_text'), - 'right_date_options' => array('widget' => 'choice', 'years' => range(2010, 2020)), - )) - ->add('updatedAt', DateTimeRangeFilterType::class, array( - 'left_datetime_options' => array('date_widget' => 'single_text', 'time_widget' => 'single_text'), - 'right_datetime_options' => array('years' => range(2010, 2020)), - )) - ->add('startAt', DateRangeFilterType::class, array( - 'left_date_options' => array( - 'widget' => 'single_text', - 'model_timezone' => 'UTC', - 'view_timezone' => 'Asia/Karachi' - ), - 'right_date_options' => array( - 'widget' => 'single_text', - 'model_timezone' => 'UTC', - 'view_timezone' => 'Asia/Karachi' - ), - )) - ; + ->add( + 'createdAt', + DateRangeFilterType::class, + ['left_date_options' => ['widget' => 'single_text'], 'right_date_options' => ['widget' => 'choice', 'years' => range( + 2010, + 2020 + )]] + ) + ->add( + 'updatedAt', + DateTimeRangeFilterType::class, + ['left_datetime_options' => ['date_widget' => 'single_text', 'time_widget' => 'single_text'], 'right_datetime_options' => ['years' => range( + 2010, + 2020 + )]] + ) + ->add( + 'startAt', + DateRangeFilterType::class, + ['left_date_options' => ['widget' => 'single_text', 'model_timezone' => 'UTC', 'view_timezone' => 'Asia/Karachi'], 'right_date_options' => ['widget' => 'single_text', 'model_timezone' => 'UTC', 'view_timezone' => 'Asia/Karachi']] + ); } - /** - * @return string - */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'item_filter'; } diff --git a/Tests/TestCase.php b/Tests/TestCase.php index 0543dc8..6782a3f 100644 --- a/Tests/TestCase.php +++ b/Tests/TestCase.php @@ -5,11 +5,15 @@ use Doctrine\Bundle\DoctrineBundle\DependencyInjection\DoctrineExtension; use Doctrine\Bundle\DoctrineBundle\DoctrineBundle; use Doctrine\Common\Annotations\AnnotationReader; +use Doctrine\Common\Annotations\DocParser; use Doctrine\Common\Cache\Psr6\DoctrineProvider; use Doctrine\ODM\MongoDB\Configuration; use Doctrine\ODM\MongoDB\DocumentManager; use Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver; use Doctrine\ORM\EntityManager; +use Doctrine\ORM\EntityRepository; +use Doctrine\ORM\Mapping\ClassMetadataFactory; +use Doctrine\ORM\Tools\Setup; use Lexik\Bundle\FormFilterBundle\DependencyInjection\Compiler\FormDataExtractorPass; use Lexik\Bundle\FormFilterBundle\DependencyInjection\LexikFormFilterExtension; use Lexik\Bundle\FormFilterBundle\Filter\Form\FilterExtension; @@ -17,6 +21,7 @@ use Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension; use Symfony\Bundle\FrameworkBundle\FrameworkBundle; use Symfony\Component\Cache\Adapter\ArrayAdapter; +use Symfony\Component\DependencyInjection\Compiler\PassConfig; use Symfony\Component\DependencyInjection\Compiler\ResolveChildDefinitionsPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; @@ -33,6 +38,8 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase */ protected $formFactory; + private static $container; + public function setUp(): void { $this->formFactory = $this->getFormFactory(); @@ -65,13 +72,11 @@ public function getSqliteEntityManager() $arrayAdapter = new ArrayAdapter(); $cache = DoctrineProvider::wrap(new ArrayAdapter()); - $reader = new AnnotationReader(new \Doctrine\Common\Annotations\DocParser()); + $reader = new AnnotationReader(new DocParser()); - $mappingDriver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($reader, array( - __DIR__.'/Fixtures/Entity', - )); + $mappingDriver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($reader, [__DIR__ . '/Fixtures/Entity']); - $config = \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(array()); + $config = Setup::createAnnotationMetadataConfiguration([]); $config->setMetadataDriverImpl($mappingDriver); $config->setMetadataCache($arrayAdapter); @@ -79,13 +84,10 @@ public function getSqliteEntityManager() $config->setProxyDir(sys_get_temp_dir()); $config->setProxyNamespace('Proxy'); $config->setAutoGenerateProxyClasses(true); - $config->setClassMetadataFactoryName('Doctrine\ORM\Mapping\ClassMetadataFactory'); - $config->setDefaultRepositoryClassName('Doctrine\ORM\EntityRepository'); + $config->setClassMetadataFactoryName(ClassMetadataFactory::class); + $config->setDefaultRepositoryClassName(EntityRepository::class); - $conn = array( - 'driver' => 'pdo_sqlite', - 'memory' => true, - ); + $conn = ['driver' => 'pdo_sqlite', 'memory' => true]; $em = EntityManager::create($conn, $config); @@ -98,7 +100,7 @@ public function getMongodbDocumentManager(): DocumentManager $config = new Configuration(); $config->setMetadataCache($arrayAdapter); - $config->setMetadataDriverImpl(new AnnotationDriver(new AnnotationReader(), [__DIR__.'/Fixtures/Document/'])); + $config->setMetadataDriverImpl(new AnnotationDriver(new AnnotationReader(), [__DIR__ . '/Fixtures/Document/'])); $config->setAutoGenerateProxyClasses(Configuration::AUTOGENERATE_FILE_NOT_EXISTS); $config->setProxyDir(sys_get_temp_dir()); @@ -108,7 +110,7 @@ public function getMongodbDocumentManager(): DocumentManager $config->setDefaultDB('lexik_form_filter_bundle_test'); $config->setHydratorNamespace('Doctrine\ODM\MongoDB\Hydrator'); $config->setAutoGenerateHydratorClasses(true); - $config->setDefaultCommitOptions(array()); + $config->setDefaultCommitOptions([]); return DocumentManager::create(null, $config); } @@ -133,20 +135,20 @@ protected function initQueryBuilderUpdater() private static function createContainerBuilder(array $configs = []) { $container = new ContainerBuilder(new ParameterBag([ - 'kernel.bundles' => [ + 'kernel.bundles' => [ 'FrameworkBundle' => FrameworkBundle::class, 'DoctrineBundle' => DoctrineBundle::class, 'LexikFormFilterBundle' => LexikFormFilterBundle::class ], 'kernel.bundles_metadata' => [], - 'kernel.cache_dir' => __DIR__, - 'kernel.debug' => false, - 'kernel.environment' => 'test', - 'kernel.name' => 'kernel', - 'kernel.root_dir' => __DIR__, - 'kernel.project_dir' => __DIR__, - 'kernel.container_class' => 'AutowiringTestContainer', - 'kernel.charset' => 'utf8', + 'kernel.cache_dir' => __DIR__, + 'kernel.debug' => false, + 'kernel.environment' => 'test', + 'kernel.name' => 'kernel', + 'kernel.root_dir' => __DIR__, + 'kernel.project_dir' => __DIR__, + 'kernel.container_class' => 'AutowiringTestContainer', + 'kernel.charset' => 'utf8', 'env(base64:default::SYMFONY_DECRYPTION_SECRET)' => 'dummy', 'debug.file_link_format' => null, ])); @@ -180,12 +182,13 @@ private static function createContainerBuilder(array $configs = []) $container->getCompilerPassConfig()->setOptimizationPasses([new ResolveChildDefinitionsPass()]); $container->getCompilerPassConfig()->setRemovingPasses([]); - $container->addCompilerPass(new FormDataExtractorPass()); - $container->addCompilerPass(new RegisterListenersPass()); + $container->addCompilerPass(new FormDataExtractorPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 0); + $container->addCompilerPass(new RegisterListenersPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 0); + + $container->compile(false); - $container->compile(); + static::$container = $container; return $container; } } - diff --git a/Tests/bootstrap.php b/Tests/bootstrap.php index 469b032..ecd53e6 100644 --- a/Tests/bootstrap.php +++ b/Tests/bootstrap.php @@ -1,7 +1,7 @@ =7.1", + "php": ">=7.4", "doctrine/orm": "^2.10", - "symfony/form": "^4.4|^5.1|^6.0", - "symfony/framework-bundle": "^4.4|^5.1|^6.0" + "symfony/form": "^5.3|^6.0", + "symfony/framework-bundle": "^5.3|^6.0" }, "require-dev": { "doctrine/doctrine-bundle": "^1.8 || ^2.0", - "doctrine/mongodb-odm-bundle": "^4.1", - "symfony/phpunit-bridge": "^4.4|^5.1|^6.0", - "symfony/var-dumper": "^4.4|^5.1|^6.0" + "doctrine/mongodb-odm-bundle": "^4.4", + "symfony/phpunit-bridge": "^5.3|^6.0", + "symfony/var-dumper": "^5.3|^6.0" }, "autoload": { "psr-4": { "Lexik\\Bundle\\FormFilterBundle\\": "" } diff --git a/ecs.php b/ecs.php new file mode 100644 index 0000000..5d5b330 --- /dev/null +++ b/ecs.php @@ -0,0 +1,25 @@ +sets([SetList::PSR_12, ]); + $config->rule(OrderedImportsFixer::class); + $config->ruleWithConfiguration(ArraySyntaxFixer::class, [ + 'syntax' => 'short', + ]); + $config->services()->remove(PhpdocScalarFixer::class); + + $config->parallel(); + $config->paths([__DIR__]); + $config->skip([ + __DIR__ . '/.github', + __DIR__ . '/vendor', + ]); +}; diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 4abc729..37d3198 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -28,7 +28,7 @@ - + diff --git a/rector.php b/rector.php new file mode 100644 index 0000000..32ed2ee --- /dev/null +++ b/rector.php @@ -0,0 +1,45 @@ +sets([ + LevelSetList::UP_TO_PHP_71, + SymfonyLevelSetList::UP_TO_SYMFONY_44, + SymfonyLevelSetList::UP_TO_SYMFONY_62, + SymfonySetList::SYMFONY_CODE_QUALITY, + SymfonySetList::SYMFONY_CONSTRUCTOR_INJECTION, + ]); + $rectorConfig->rules([ + ReturnTypeFromStrictNativeCallRector::class, + ReturnTypeFromStrictScalarReturnExprRector::class, + ]); + $rectorConfig->phpVersion(PhpVersion::PHP_71); + $rectorConfig->importShortClasses(false); + $rectorConfig->importNames(); + $rectorConfig->bootstrapFiles([ + __DIR__ . '/vendor/autoload.php', + ]); + $rectorConfig->parallel(); + $rectorConfig->paths([__DIR__]); + $rectorConfig->skip([ + // Path + __DIR__ . '/.github', + __DIR__ . '/DependencyInjection/Configuration.php', + __DIR__ . '/vendor', + + // Rules + AddSeeTestAnnotationRector::class, + JsonThrowOnErrorRector::class, + ]); +};