725a50c9ce28eb605bb4f9ef145832bda196e3bc
[m6w6/pq-gateway] / lib / pq / Mapper / Mapper.php
1 <?php
2
3 namespace pq\Mapper;
4
5 use UnexpectedValueException;
6
7 class Mapper
8 {
9 private $maps;
10 private $refp;
11
12 /**
13 * @param \pq\Mapper\MapInterface $map
14 * @return \pq\Mapper\Mapper
15 */
16 function register(MapInterface $map) {
17 $this->maps[$map->getClass()] = $map;
18 return $this;
19 }
20
21 function getReflector($class, $prop) {
22 if (is_object($class)) {
23 $class = get_class($class);
24 }
25 $hash = "$class::$prop";
26 if (!isset($this->refp[$hash])) {
27 $this->refp[$hash] = new \ReflectionProperty($class, $prop);
28 $this->refp[$hash]->setAccessible(true);
29 }
30 return $this->refp[$hash];
31 }
32
33 /**
34 * @param string $class
35 * @return \pq\Mapper\MapInterface
36 * @throws UnexpectedValueException
37 */
38 function mapOf($class) {
39 if (is_object($class)) {
40 $class = get_class($class);
41 }
42 if (!isset($this->maps[$class])) {
43 if (!is_callable([$class, "mapAs"])) {
44 throw new UnexpectedValueException("Not a mapped class: '$class'");
45 }
46 $this->register($class::mapAs($this));
47 }
48 return $this->maps[$class];
49 }
50
51 /**
52 * @param string $class
53 * @return \pq\Mapper\Storage
54 */
55 function createStorage($class) {
56 return new Storage($this, $class);
57 }
58
59 /**
60 * @param string $property
61 * @param string $field
62 * @return \pq\Mapper\Property\Field
63 */
64 function mapField($property, $field = null) {
65 return new Property\Field($this, $property, $field);
66 }
67
68 /**
69 * @param string $property
70 * @return \pq\Mapper\Property\All
71 */
72 function mapAll($property) {
73 return new Property\All($this, $property);
74 }
75
76 /**
77 * @param string $property
78 * @return \pq\Mapper\Property\Ref
79 */
80 function mapRef($property) {
81 return new Property\Ref($this, $property);
82 }
83 }