Passed
Push — master ( 0cd8c1...21e99f )
by George
03:10
created

PostgresqlValidator::validate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2.024

Importance

Changes 8
Bugs 0 Features 1
Metric Value
c 8
b 0
f 1
dl 0
loc 22
ccs 9
cts 11
cp 0.8182
rs 9.2
cc 2
eloc 12
nc 2
nop 3
crap 2.024
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
     * @param   string  $rowHash           The hash of data from the CSV row to be validated.
18
     * @param   string  $referenceResource The reference resource.
19
     * @param   array   $referenceFields   The reference fields.
20
     *
21
     * @return  boolean Is the data valid.
22
     *
23
     * @throws  \Exception if the foreign key couldn't be validated.
24
     */
25 28
    public function validate($rowHash, $referenceResource, array $referenceFields)
26 28
    {
27 28
        $referenceFields = implode(" || ', ' || ", $referenceFields);
28
29
        $validationSql =   "SELECT
30
                                    COUNT(*)
31
                                FROM
32
                                    $referenceResource
33
                                WHERE
34 28
                                    $referenceFields = :row_hash";
35
36 28
        $statement = Base::$pdoConnection->prepare($validationSql);
37 28
        $statement->bindParam(':row_hash', $rowHash);
38 28
        $results = $statement->fetchAll();
39
40 28
        if (false === $results) {
41
            throw new \Exception("Could not validate the foreign key for $referenceResource
42
                fields $referenceFields with hash of $rowHash.");
43
        }
44
45 28
        return (0 !== $results[0]['count']);
46
    }
47
}
48