Test Failed
Push — master ( 087751...3d501f )
by George
03:59
created

PostgresqlValidator::validate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 0 Features 1
Metric Value
c 8
b 0
f 1
dl 0
loc 22
rs 9.2
cc 2
eloc 12
nc 2
nop 3
1
<?php
2
namespace JsonTable\Validate\ForeignKey;
3
4
use \JsonTable\Validate\ForeignKeyValidatorInterface;
5
use \JsonTable\Base;
6
7
/**
8
 * Foreign key postgresql validator.
9
 *
10
 * @package JSON table
11
 */
12
class PostgresqlValidator implements ForeignKeyValidatorInterface
13
{
14
    /**
15
     * Check that the foreign key hash matches the specified resource.
16
     *
17
     * @access  public
18
     *
19
     * @param   string  $rowHash           The hash of data from the CSV row to be validated.
20
     * @param   string  $referenceResource The reference resource.
21
     * @param   array   $referenceFields   The reference fields.
22
     *
23
     * @return  boolean Is the data valid.
24
     *
25
     * @throws  \Exception if the foreign key couldn't be validated.
26
     */
27
    public function validate($rowHash, $referenceResource, array $referenceFields)
28
    {
29
        $referenceFields = implode(" || ', ' || ", $referenceFields);
30
31
        $validationSql =   "SELECT
32
                                    COUNT(*)
33
                                FROM
34
                                    $referenceResource
35
                                WHERE
36
                                    $referenceFields = :row_hash";
37
38
        $statement = Base::$pdoConnection->prepare($validationSql);
39
        $statement->bindParam(':row_hash', $rowHash);
40
        $results = $statement->execute();
41
42
        if (false === $results) {
43
            throw new \Exception("Could not validate the foreign key for $referenceResource
44
                fields $referenceFields with hash of $rowHash.");
45
        }
46
47
        return (0 !== $results[0]['count']);
48
    }
49
}
50