1: <?php
2:
3: 4: 5: 6: 7: 8:
9:
10: namespace rsanchez\Deep\Hydrator;
11:
12: use Illuminate\Database\Eloquent\Model;
13: use rsanchez\Deep\Collection\EntryCollection;
14: use rsanchez\Deep\Model\AbstractProperty;
15: use rsanchez\Deep\Model\AbstractEntity;
16: use rsanchez\Deep\Hydrator\AbstractHydrator;
17: use rsanchez\Deep\Model\GridCol;
18: use rsanchez\Deep\Model\GridRow;
19: use rsanchez\Deep\Collection\GridColCollection;
20: use rsanchez\Deep\Collection\GridRowCollection;
21:
22: 23: 24:
25: class GridHydrator extends AbstractHydrator
26: {
27: 28: 29:
30: protected $colModel;
31:
32: 33: 34:
35: protected $rowModel;
36:
37: 38: 39: 40:
41: protected $cols;
42:
43: 44: 45: 46:
47: protected $rows = array();
48:
49: 50: 51:
52: public function __construct(EntryCollection $collection, $fieldtype, GridCol $colModel, GridRow $rowModel)
53: {
54: parent::__construct($collection, $fieldtype);
55:
56: $this->colModel = $colModel;
57: $this->rowModel = $rowModel;
58:
59: $fieldIds = $collection->getFieldIdsByFieldtype($fieldtype);
60:
61: $cols = $this->colModel->fieldId($fieldIds)->get();
62:
63: foreach ($cols as $col) {
64: if (! isset($this->cols[$col->field_id])) {
65: $this->cols[$col->field_id] = new GridColCollection();
66: }
67:
68: $this->cols[$col->field_id]->push($col);
69: }
70:
71: $collection->setGridCols($cols);
72: }
73:
74: 75: 76:
77: public function preload(array $entryIds)
78: {
79: $fieldIds = $this->collection->getFieldIdsByFieldtype($this->fieldtype);
80:
81: foreach ($fieldIds as $fieldId) {
82: $rows = $this->rowModel->fieldId($fieldId)->entryId($entryIds)->orderBy('row_order', 'asc')->get();
83:
84: foreach ($rows as $row) {
85: if (! isset($this->rows[$row->entry_id][$row->field_id])) {
86: $this->rows[$row->entry_id][$row->field_id] = new GridRowCollection();
87: }
88:
89: $cols = isset($this->cols[$row->field_id]) ? $this->cols[$row->field_id] : new GridColCollection();
90:
91: $row->setCols($cols);
92:
93: $this->rows[$row->entry_id][$row->field_id]->push($row);
94: }
95: }
96: }
97:
98: 99: 100:
101: public function hydrate(AbstractEntity $entity, AbstractProperty $property)
102: {
103: $value = isset($this->rows[$entity->getId()][$property->getId()]) ? $this->rows[$entity->getId()][$property->getId()] : new GridRowCollection();
104:
105: $entity->setAttribute($property->getName(), $value);
106:
107: return $value;
108: }
109: }
110: