summaryrefslogtreecommitdiff
path: root/libs/SimpleValidator/Validators/Exists.php
blob: 1998e6738a5916aa3a375093da4f5eb9354ac75a (plain)
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
<?php

namespace SimpleValidator\Validators;

use PDO;

class Exists extends Base
{
    private $pdo;
    private $key;
    private $table;

    public function __construct($field, $error_message, PDO $pdo, $table, $key = '')
    {
        parent::__construct($field, $error_message);

        $this->pdo = $pdo;
        $this->table = $table;
        $this->key = $key;
    }


    public function execute(array $data)
    {
        if (! $this->isFieldNotEmpty($data)) {
            return true;
        }

        if ($this->key === '') {
            $this->key = $this->field;
        }

        $rq = $this->pdo->prepare('SELECT 1 FROM '.$this->table.' WHERE '.$this->key.'=?');
        $rq->execute(array($data[$this->field]));

        return $rq->fetchColumn() == 1;
    }
}