Completed
Pull Request — 1.x (#7)
by Dorian
01:28
created

DBRetriever::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
c 0
b 0
f 0
rs 9.4285
cc 1
eloc 4
nc 1
nop 3
1
<?php
2
namespace MetaHydrator\Parser;
3
4
use MetaHydrator\Database\DBProvider;
5
use MetaHydrator\Exception\DBException;
6
use MetaHydrator\Exception\ParsingException;
7
8
class DBRetriever extends AbstractParser
9
{
10
    /** @var DBProvider */
11
    protected $dbProvider;
12
    public function getDbProvider() { return $this->dbProvider; }
13
    public function setDbProvider(DBProvider $dbProvider) { $this->dbProvider = $dbProvider; }
14
    /** @var string */
15
    protected $table;
16
    public function getTable() { return $this->table; }
17
    public function setTable(string $table) { $this->table = $table; }
18
19
    /**
20
     * DBRetriever constructor.
21
     * @param DBProvider $dbProvider
22
     * @param string $table
23
     * @param string $errorMessage
24
     */
25
    public function __construct(DBProvider $dbProvider, string $table, string $errorMessage = "")
26
    {
27
        parent::__construct($errorMessage);
28
        $this->dbProvider = $dbProvider;
29
        $this->table = $table;
30
    }
31
32
    /**
33
     * @param $rawValue
34
     * @return mixed
35
     *
36
     * @throws ParsingException
37
     */
38
    public function parse($rawValue)
39
    {
40
        if ($rawValue === null) {
41
            return null;
42
        }
43
        if (!is_array($rawValue)) {
44
            throw new ParsingException($this->getErrorMessage());
45
        }
46
        try {
47
            $object = $this->dbProvider->getObject($this->table, $rawValue);
48
            if ($object === null) {
49
                throw new ParsingException($this->getErrorMessage());
50
            } else {
51
                return $object;
52
            }
53
        } catch (DBException $exception) {
54
            throw new ParsingException($this->getErrorMessage());
55
        }
56
    }
57
}