storage enhancements
[m6w6/pq-gateway] / lib / pq / Mapper / Mapper.php
1 <?php
2
3 namespace pq\Mapper;
4
5 use pq\Mapper\Property\All;
6 use pq\Mapper\Property\Field;
7 use pq\Mapper\Property\Ref;
8 use ReflectionProperty;
9 use UnexpectedValueException;
10
11 class Mapper
12 {
13 /**
14 * @var MapInterface[]
15 */
16 private $maps;
17
18 /**
19 * @var ReflectionProperty[]
20 */
21 private $refp;
22
23 /**
24 * Register a mapping
25 * @param MapInterface $map
26 * @return Mapper
27 */
28 function register(MapInterface $map) {
29 $this->maps[$map->getClass()] = $map;
30 return $this;
31 }
32
33 /**
34 * Get a property reflector
35 * @param string $class
36 * @param string $prop
37 * @return ReflectionProperty
38 */
39 function getReflector($class, $prop) {
40 if (is_object($class)) {
41 $class = get_class($class);
42 }
43 $hash = "$class::$prop";
44 if (!isset($this->refp[$hash])) {
45 $this->refp[$hash] = new ReflectionProperty($class, $prop);
46 $this->refp[$hash]->setAccessible(true);
47 }
48 return $this->refp[$hash];
49 }
50
51 /**
52 * Get the mapping of $class
53 * @param string $class
54 * @return MapInterface
55 * @throws UnexpectedValueException
56 */
57 function mapOf($class) {
58 if (is_object($class)) {
59 $class = get_class($class);
60 }
61 if (!isset($this->maps[$class])) {
62 if (!is_callable([$class, "mapAs"])) {
63 throw new UnexpectedValueException("Not a mapped class: '$class'");
64 }
65 $this->register($class::mapAs($this));
66 }
67 return $this->maps[$class];
68 }
69
70 /**
71 * Create a storage for $class
72 * @param string $class
73 * @return Storage
74 */
75 function createStorage($class) {
76 return new Storage($this, $class);
77 }
78
79 /**
80 * Create a simple field mapping
81 * @param string $property
82 * @param string $field
83 * @return Field
84 */
85 function mapField($property, $field = null) {
86 return new Field($this, $property, $field);
87 }
88
89 /**
90 * Create a child rows mapping by foreign key
91 * @param string $property
92 * @return All
93 */
94 function mapAll($property) {
95 return new All($this, $property);
96 }
97
98 /**
99 * Create a parent row mapping by foreign key
100 * @param string $property
101 * @return Ref
102 */
103 function mapRef($property) {
104 return new Ref($this, $property);
105 }
106 }