Skip to content

Extract filter processing logic to a seperate class #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,12 @@
],
"require": {
"php": "^7.2 || ^8.0",
"ext-json": "*",
"ext-pdo": "*",
"event-engine/php-persistence": "^0.9"
},
"require-dev": {
"infection/infection": "^0.15.3",
"infection/infection": "^0.26.6",
"malukenho/docheader": "^0.1.8",
"phpspec/prophecy": "^1.12.1",
"phpstan/phpstan": "^0.12.48",
Expand All @@ -45,6 +46,10 @@
"config": {
"sort-packages": true,
"platform": {
},
"allow-plugins": {
"ocramius/package-versions": true,
"infection/extension-installer": true
}
},
"prefer-stable": true,
Expand Down
34 changes: 34 additions & 0 deletions src/Filter/FilterClause.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php
/**
* This file is part of the event-engine/php-postgres-document-store.
* (c) 2019-2021 prooph software GmbH <contact@prooph.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace EventEngine\DocumentStore\Postgres\Filter;

final class FilterClause
{
private $clause;
private $args;

public function __construct(?string $clause, array $args = [])
{
$this->clause = $clause;
$this->args = $args;
}

public function clause(): ?string
{
return $this->clause;
}

public function args(): array
{
return $this->args;
}
}
19 changes: 19 additions & 0 deletions src/Filter/FilterProcessor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php
/**
* This file is part of the event-engine/php-postgres-document-store.
* (c) 2019-2021 prooph software GmbH <contact@prooph.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace EventEngine\DocumentStore\Postgres\Filter;

use EventEngine\DocumentStore\Filter\Filter;

interface FilterProcessor
{
public function process(Filter $filter): FilterClause;
}
199 changes: 199 additions & 0 deletions src/Filter/PostgresFilterProcessor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
<?php
/**
* This file is part of the event-engine/php-postgres-document-store.
* (c) 2019-2021 prooph software GmbH <contact@prooph.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace EventEngine\DocumentStore\Postgres\Filter;

use EventEngine\DocumentStore;
use EventEngine\DocumentStore\Filter\Filter;
use EventEngine\DocumentStore\Postgres\Exception\InvalidArgumentException;
use EventEngine\DocumentStore\Postgres\Exception\RuntimeException;

/**
* Default filter processor class for converting a filter to a where clause.
*/
final class PostgresFilterProcessor implements FilterProcessor
{
/**
* @var bool
*/
private $useMetadataColumns;

public function __construct(bool $useMetadataColumns = false)
{
$this->useMetadataColumns = $useMetadataColumns;
}

public function process(Filter $filter): FilterClause
{
[$filterClause, $args] = $this->processFilter($filter);

return new FilterClause($filterClause, $args);
}

/**
* @param Filter $filter
* @param int $argsCount
* @return array
*/
private function processFilter(Filter $filter, int $argsCount = 0): array
{
if($filter instanceof DocumentStore\Filter\AnyFilter) {
if($argsCount > 0) {
throw new InvalidArgumentException('AnyFilter cannot be used together with other filters.');
}
return [null, [], $argsCount];
}

if($filter instanceof DocumentStore\Filter\AndFilter) {
[$filterA, $argsA, $argsCount] = $this->processFilter($filter->aFilter(), $argsCount);
[$filterB, $argsB, $argsCount] = $this->processFilter($filter->bFilter(), $argsCount);
return ["($filterA AND $filterB)", array_merge($argsA, $argsB), $argsCount];
}

if($filter instanceof DocumentStore\Filter\OrFilter) {
[$filterA, $argsA, $argsCount] = $this->processFilter($filter->aFilter(), $argsCount);
[$filterB, $argsB, $argsCount] = $this->processFilter($filter->bFilter(), $argsCount);
return ["($filterA OR $filterB)", array_merge($argsA, $argsB), $argsCount];
}

switch (get_class($filter)) {
case DocumentStore\Filter\DocIdFilter::class:
/** @var DocumentStore\Filter\DocIdFilter $filter */
return ["id = :a$argsCount", ["a$argsCount" => $filter->val()], ++$argsCount];
case DocumentStore\Filter\AnyOfDocIdFilter::class:
/** @var DocumentStore\Filter\AnyOfDocIdFilter $filter */
return $this->makeInClause('id', $filter->valList(), $argsCount);
case DocumentStore\Filter\AnyOfFilter::class:
/** @var DocumentStore\Filter\AnyOfFilter $filter */
return $this->makeInClause($this->propToJsonPath($filter->prop()), $filter->valList(), $argsCount, $this->shouldJsonEncodeVal($filter->prop()));
case DocumentStore\Filter\EqFilter::class:
/** @var DocumentStore\Filter\EqFilter $filter */
$prop = $this->propToJsonPath($filter->prop());
return ["$prop = :a$argsCount", ["a$argsCount" => $this->prepareVal($filter->val(), $filter->prop())], ++$argsCount];
case DocumentStore\Filter\GtFilter::class:
/** @var DocumentStore\Filter\GtFilter $filter */
$prop = $this->propToJsonPath($filter->prop());
return ["$prop > :a$argsCount", ["a$argsCount" => $this->prepareVal($filter->val(), $filter->prop())], ++$argsCount];
case DocumentStore\Filter\GteFilter::class:
/** @var DocumentStore\Filter\GteFilter $filter */
$prop = $this->propToJsonPath($filter->prop());
return ["$prop >= :a$argsCount", ["a$argsCount" => $this->prepareVal($filter->val(), $filter->prop())], ++$argsCount];
case DocumentStore\Filter\LtFilter::class:
/** @var DocumentStore\Filter\LtFilter $filter */
$prop = $this->propToJsonPath($filter->prop());
return ["$prop < :a$argsCount", ["a$argsCount" => $this->prepareVal($filter->val(), $filter->prop())], ++$argsCount];
case DocumentStore\Filter\LteFilter::class:
/** @var DocumentStore\Filter\LteFilter $filter */
$prop = $this->propToJsonPath($filter->prop());
return ["$prop <= :a$argsCount", ["a$argsCount" => $this->prepareVal($filter->val(), $filter->prop())], ++$argsCount];
case DocumentStore\Filter\LikeFilter::class:
/** @var DocumentStore\Filter\LikeFilter $filter */
$prop = $this->propToJsonPath($filter->prop());
$propParts = explode('->', $prop);
$lastProp = array_pop($propParts);
$prop = implode('->', $propParts) . '->>'.$lastProp;
return ["$prop iLIKE :a$argsCount", ["a$argsCount" => $filter->val()], ++$argsCount];
case DocumentStore\Filter\NotFilter::class:
/** @var DocumentStore\Filter\NotFilter $filter */
$innerFilter = $filter->innerFilter();

if (!$this->isPropFilter($innerFilter)) {
throw new RuntimeException('Not filter cannot be combined with a non prop filter!');
}

[$innerFilterStr, $args, $argsCount] = $this->processFilter($innerFilter, $argsCount);

if($innerFilter instanceof DocumentStore\Filter\AnyOfFilter || $innerFilter instanceof DocumentStore\Filter\AnyOfDocIdFilter) {
if ($argsCount === 0) {
return [
str_replace(' 1 != 1 ', ' 1 = 1 ', $innerFilterStr),
$args,
$argsCount
];
}

$inPos = strpos($innerFilterStr, ' IN(');
$filterStr = substr_replace($innerFilterStr, ' NOT IN(', $inPos, 4 /* " IN(" */);
return [$filterStr, $args, $argsCount];
}

return ["NOT $innerFilterStr", $args, $argsCount];
case DocumentStore\Filter\InArrayFilter::class:
/** @var DocumentStore\Filter\InArrayFilter $filter */
$prop = $this->propToJsonPath($filter->prop());
return ["$prop @> :a$argsCount", ["a$argsCount" => '[' . $this->prepareVal($filter->val(), $filter->prop()) . ']'], ++$argsCount];
case DocumentStore\Filter\ExistsFilter::class:
/** @var DocumentStore\Filter\ExistsFilter $filter */
$prop = $this->propToJsonPath($filter->prop());
$propParts = explode('->', $prop);
$lastProp = trim(array_pop($propParts), "'");
$parentProps = implode('->', $propParts);
return ["JSONB_EXISTS($parentProps, '$lastProp')", [], $argsCount];
default:
throw new RuntimeException('Unsupported filter type. Got ' . get_class($filter));
}
}

private function makeInClause(string $prop, array $valList, int $argsCount, bool $jsonEncode = false): array
{
if ($valList === []) {
return [' 1 != 1 ', [], 0];
}
$argList = [];
$params = \implode(",", \array_map(function ($val) use (&$argsCount, &$argList, $jsonEncode) {
$param = ":a$argsCount";
$argList["a$argsCount"] = $jsonEncode? \json_encode($val) : $val;
$argsCount++;
return $param;
}, $valList));

return ["$prop IN($params)", $argList, $argsCount];
}

private function shouldJsonEncodeVal(string $prop): bool
{
if($this->useMetadataColumns && strpos($prop, 'metadata.') === 0) {
return false;
}

return true;
}

private function propToJsonPath(string $field): string
{
if($this->useMetadataColumns && strpos($field, 'metadata.') === 0) {
return str_replace('metadata.', '', $field);
}

return "doc->'" . str_replace('.', "'->'", $field) . "'";
}

private function isPropFilter(Filter $filter): bool
{
switch (get_class($filter)) {
case DocumentStore\Filter\AndFilter::class:
case DocumentStore\Filter\OrFilter::class:
case DocumentStore\Filter\NotFilter::class:
return false;
default:
return true;
}
}

private function prepareVal($value, string $prop)
{
if(!$this->shouldJsonEncodeVal($prop)) {
return $value;
}

return \json_encode($value);
}
}
Loading