1: <?php
2:
3: namespace Alchemy\orm;
4: use Alchemy\core\schema\Table;
5: use Alchemy\util\DataTypeLexer;
6:
7:
8: /**
9: * Defines a table aware of relationships and other abstractions
10: */
11: class ORMTable extends Table {
12:
13: protected $relationships = array();
14:
15:
16: public function getClass() {
17: return $this->args['class'];
18: }
19:
20:
21: public function getRef() {
22: return new ORMTableRef($this);
23: }
24:
25:
26: public function addRelationship($name, $rel) {
27: if (is_string($rel)) {
28: $type = new DataTypeLexer($rel);
29: $t = $type->getType();
30: $rel = Relationship::$t($type->getArgs(), $this, $name);
31: }
32:
33: $this->args['relationships'][$name] = $rel;
34: $this->relationships[$name] = $rel;
35: }
36:
37:
38: public function getRelationship($name) {
39: if (!array_key_exists($name, $this->relationships)) {
40: if (array_key_exists($name, $this->args['relationships'])) {
41: $this->addRelationship($name, $this->args['relationships'][$name]);
42: } else {
43: throw new \Exception("Unknown relationship '{$this->name}.{$name}'");
44: }
45: }
46:
47: return $this->relationships[$name];
48: }
49:
50:
51: public function hasRelationship($name) {
52: return array_key_exists($name, $this->args['relationships']);
53: }
54:
55:
56: public function listRelationships() {
57: $this->resolve();
58: return $this->relationships;
59: }
60:
61:
62: protected function resolve() {
63: if ($this->resolved) return;
64: parent::resolve();
65:
66: foreach ($this->args['relationships'] as $name => $rel) {
67: $rel = $this->getRelationship($name);
68: }
69: }
70: }
71: