1
|
|
|
<?php |
2
|
|
|
namespace MetaHydrator\Parser; |
3
|
|
|
|
4
|
|
|
use MetaHydrator\Database\DBProvider; |
5
|
|
|
use MetaHydrator\Exception\DBException; |
6
|
|
|
use MetaHydrator\Exception\HydratingException; |
7
|
|
|
use MetaHydrator\Exception\ParsingException; |
8
|
|
|
use Mouf\Hydrator\Hydrator; |
9
|
|
|
|
10
|
|
|
class DBParser extends AbstractParser |
11
|
|
|
{ |
12
|
|
|
/** @var DBProvider */ |
13
|
|
|
protected $dbProvider; |
14
|
|
|
public function getDbProvider() { return $this->dbProvider; } |
15
|
|
|
public function setDbProvider(DBProvider $dbProvider) { $this->dbProvider = $dbProvider; } |
16
|
|
|
/** @var string */ |
17
|
|
|
protected $table; |
18
|
|
|
public function getTable() { return $this->table; } |
19
|
|
|
public function setTable(string $table) { $this->table = $table; } |
20
|
|
|
/** @var Hydrator */ |
21
|
|
|
private $hydrator; |
22
|
|
|
public function getHydrator() { return $this->hydrator; } |
23
|
|
|
public function setHydrator(Hydrator $hydrator) { $this->hydrator = $hydrator; } |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* DBParser constructor. |
27
|
|
|
* @param DBProvider $dbProvider |
28
|
|
|
* @param string $table |
29
|
|
|
* @param Hydrator $hydrator |
30
|
|
|
* @param string $errorMessage |
31
|
|
|
*/ |
32
|
|
|
public function __construct(DBProvider $dbProvider, string $table, Hydrator $hydrator, string $errorMessage = "") |
33
|
|
|
{ |
34
|
|
|
parent::__construct($errorMessage); |
35
|
|
|
$this->dbProvider = $dbProvider; |
36
|
|
|
$this->table = $table; |
37
|
|
|
$this->hydrator = $hydrator; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param $rawValue |
42
|
|
|
* @return mixed |
43
|
|
|
* |
44
|
|
|
* @throws ParsingException |
45
|
|
|
*/ |
46
|
|
|
public function parse($rawValue) |
47
|
|
|
{ |
48
|
|
|
if ($rawValue === null) { |
49
|
|
|
return null; |
50
|
|
|
} |
51
|
|
|
if (!is_array($rawValue)) { |
52
|
|
|
throw new ParsingException($this->getErrorMessage()); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
try { |
56
|
|
|
$object = $this->dbProvider->getObject($this->table, $rawValue); |
57
|
|
|
} catch (DBException $exception) { |
58
|
|
|
throw new ParsingException($this->getErrorMessage()); |
59
|
|
|
} |
60
|
|
|
try { |
61
|
|
|
if ($object === null) { |
62
|
|
|
$className = $this->dbProvider->getClassName($this->table); |
63
|
|
|
return $this->hydrator->hydrateNewObject($rawValue, $className); |
64
|
|
|
} else { |
65
|
|
|
$this->hydrator->hydrateObject($rawValue, $object); |
66
|
|
|
return $object; |
67
|
|
|
} |
68
|
|
|
} catch (HydratingException $exception) { |
69
|
|
|
throw new ParsingException($exception->getErrorsMap()); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
} |