/
DbalRecordExistsFilter.php
43 lines (33 loc) · 1.25 KB
/
DbalRecordExistsFilter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php
declare(strict_types = 1);
namespace Zfegg\ContentValidation\Opis\Filter;
use Opis\JsonSchema\Filter;
use Opis\JsonSchema\Schema;
use Opis\JsonSchema\ValidationContext;
use Psr\Container\ContainerInterface;
class DbalRecordExistsFilter implements Filter
{
private ContainerInterface $container;
private string $defaultId;
public function __construct(ContainerInterface $container, string $defaultId = 'db')
{
$this->container = $container;
$this->defaultId = $defaultId;
}
public function validate(ValidationContext $context, Schema $schema, array $args = []): bool
{
/** @var \Doctrine\DBAL\Connection $db */
$db = $this->container->get($args['db'] ?? $this->defaultId);
if (isset($args['sql'])) {
$sql = $args['sql'];
} elseif (isset($args['table']) && isset($args['field'])) {
$sql = sprintf('SELECT COUNT(*) FROM %s WHERE %s=?', $args['table'], $args['field']);
} else {
throw new \InvalidArgumentException('Invalid args.');
}
$exists = $args['exists'] ?? false;
$sth = $db->prepare($sql);
$row = $sth->executeQuery([$context->currentData()])->fetchNumeric();
return $row[0] == $exists;
}
}