Skip to content
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

Allowing Dates in Range & new Around() Syntax #206

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
46 changes: 46 additions & 0 deletions src/Domain/Syntax/Around.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

declare(strict_types=1);

namespace JeroenG\Explorer\Domain\Syntax;

use Webmozart\Assert\Assert;

class Around implements SyntaxInterface {
private string $field;

private mixed $value;

private float $tolerance;

private bool $percentage;

private bool $date;

private ?float $boost;

public function __construct(string $field, $value, float $tolerance = 5, ?bool $percentage = false, ?bool $date = false, ?float $boost = 1.0) {
$this->field = $field;
$this->value = $value;
$this->tolerance = $tolerance;
$this->percentage = $percentage;
$this->date = $date;
$this->boost = $boost;
}

public function build(): array {
if ($this->date) {
$days = (int) $this->tolerance;
$lte = date('Y-m-d H:i:s', strtotime("+{$days} day", strtotime($this->value)));
$gte = date('Y-m-d H:i:s', strtotime("-{$days} day", strtotime($this->value)));
} else {
$modifier = $this->percentage ? $this->value * $this->tolerance : $this->tolerance;
$lte = $this->value + $modifier;
$gte = $this->value - $modifier;
}

return ['range' => [
$this->field => ['lte' => $lte, 'gte' => $gte, 'boost' => $this->boost],
]];
}
}
10 changes: 8 additions & 2 deletions src/Domain/Syntax/Range.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,14 @@ class Range implements SyntaxInterface

private ?float $boost;

public function __construct(string $field, array $definitions, ?float $boost = 1.0)
private ?bool $date;

public function __construct(string $field, array $definitions, ?float $boost = 1.0, ?bool $date = false)
{
$this->field = $field;
$this->definitions = $definitions;
$this->boost = $boost;
$this->date = $date;
$this->validateDefinitions($definitions);
}

Expand All @@ -36,7 +39,10 @@ private function validateDefinitions(array $definitions): void
foreach ($definitions as $key => $value) {
Assert::inArray($key, self::RELATIONS);
Assert::notNull($value);
Assert::numeric($value);

if (!$this->date) {
Assert::numeric($value);
}
}
}
}
Loading