Passed
Push — master ( be9b76...46473c )
by George
03:25
created

PostgresqlValidator::validate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2

Importance

Changes 8
Bugs 0 Features 1
Metric Value
c 8
b 0
f 1
dl 0
loc 22
ccs 11
cts 11
cp 1
rs 9.2
cc 2
eloc 12
nc 2
nop 3
crap 2
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 73
    public function validate($rowHash, $referenceResource, array $referenceFields)
26 73
    {
27 73
        $referenceFields = implode(" || ', ' || ", $referenceFields);
28
29
        $validationSql =   "SELECT
30
                                    COUNT(*)
31
                                FROM
32
                                    $referenceResource
33
                                WHERE
34 73
                                    $referenceFields = :row_hash";
35
36 73
        $statement = Base::$pdoConnection->prepare($validationSql);
37 73
        $statement->bindParam(':row_hash', $rowHash);
38 73
        $results = $statement->fetchAll();
39
40 73
        if (false === $results) {
41 1
            throw new \Exception("Could not validate the foreign key for $referenceResource
42 1
                fields $referenceFields with hash of $rowHash.");
43
        }
44
45 72
        return (0 !== $results[0]['count']);
46
    }
47
}
48