Skip to content

Instantly share code, notes, and snippets.

@alefcastelo
Created July 17, 2019 01:09
Show Gist options
  • Save alefcastelo/e6c08a7c0c3856aaae6e0a384cdd427b to your computer and use it in GitHub Desktop.
Save alefcastelo/e6c08a7c0c3856aaae6e0a384cdd427b to your computer and use it in GitHub Desktop.
<?php
interface QueryBuilderInterface
{
public function getConfig(): array;
}
class UserQueryBuilder implements QueryBuilderInterface
{
private $config = [];
public function __construct(array $config = [])
{
$this->config = $config;
}
public function fields(array $fields = [])
{
$this->config['fields'] = $fields;
return $this;
}
public function active(bool $isAtive = true)
{
$this->config['where']['active'] = $isAtive;
return $this;
}
public function getConfig(): array
{
return $this->config;
}
}
class UserRepository
{
public function query(QueryBuilderInterface $queryBuilder)
{
$queryConfig = $queryBuilder->getConfig();
$fields = join(', ', $queryConfig['fields']);
$SQL = <<<SQL
SELECT
{$fields}
FROM
`user`
SQL;
$criterias = [];
if (count($queryConfig['where'])) {
foreach ($queryConfig['where'] as $criteria => $value) {
$criterias[] = "`{$criteria}` = '{$value}'";
}
$where = join(' AND', $criterias);
$SQL .= $where;
}
return $this->em->query($SQL);
}
}
class UserReport
{
private $repository;
public function __construct(
UserRepository $repository
) {
$this->repository = $repository;
}
public function getActives()
{
$userQueryBuilder = new UserQueryBuilder();
$userQueryBuilder
->fields(['*'])
->active()
;
return $this->repository->query($userQueryBuilder);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment