- Added some SearchRequest attributes ; now it's even simpler to add searchable fields

- Began decoupling of QueryBuilder from native MySQL method ; some works needs to be done on for the Repository object splitting also.
This commit is contained in:
Dave Mc Nicoll committed 2024-04-09 19:14:27 -04:00
1 parent 15be1597b8
commit 4571517dc8
30 files changed
+1007 -615

No files matched your search

@@ -0,0 +1,83 @@
<?php
namespace Ulmus\SearchRequest;
use Psr\Http\Message\ServerRequestInterface;
use Ulmus\SearchRequest\Attribute\SearchParameter;
use Ulmus\SearchRequest\Attribute\SearchWhere;
trait SearchRequestFromRequestTrait
{
protected array $wheres = [];
protected array $likes = [];
protected array $groups = [];
protected array $orders = [];
public function fromRequest(ServerRequestInterface $request)
{
$get = new \ArrayObject(array_filter($request->getQueryParams(), function($i) { return $i !== ""; }));
$this->page = $get->offsetExists('page') ? $get['page'] : 1;
$classReflection = new \ReflectionClass($this);
foreach($classReflection->getProperties() as $property) {
foreach($property->getAttributes() as $attributeReflection) {
$attribute = $attributeReflection->newInstance();
# We can't simply pass this class as first arguments of getAttributes() since it do not check for inheritance
if (! $attribute instanceof Attribute\SearchParameter) {
continue;
}
$propertyName = $property->getName();
$fieldName = $attribute->field ?? $property->getName();
$queryParamName = $attribute->parameter ?? $property->getName();
if ($attribute->toggle) {
$this->$propertyName = $get->offsetExists('rental');
} else {
$this->$propertyName = $get->offsetExists($queryParamName) ? $get[$queryParamName] : null;
}
$field = (string) $fieldName;
switch ($attribute->method) {
case SearchMethodEnum::Where:
$this->wheres[$field] = $this->$propertyName;
break;
case SearchMethodEnum::Like:
$this->likes[$field] = "%{$this->$propertyName}%";
break;
case SearchMethodEnum::LikeLeft:
$this->likes[$field] = "%{$this->$propertyName}";
break;
case SearchMethodEnum::LikeRight:
$this->likes[$field] = "{$this->$propertyName}%";
break;
case SearchMethodEnum::OrderByAsc:
$this->orders[$field] = "ASC";
break;
case SearchMethodEnum::OrderByDesc:
$this->orders[$field] = "DESC";
break;
case SearchMethodEnum::GroupBy:
$this->groups[$field] = "DESC";
break;
}
}
}
return $this;
}
}