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\MatrixCol;
18: use rsanchez\Deep\Model\MatrixRow;
19: use rsanchez\Deep\Collection\MatrixColCollection;
20: use rsanchez\Deep\Collection\MatrixRowCollection;
21:
22: 23: 24:
25: class MatrixHydrator 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;
48:
49: 50: 51:
52: public function __construct(EntryCollection $collection, $fieldtype, MatrixCol $colModel, MatrixRow $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 MatrixColCollection();
66: }
67:
68: $this->cols[$col->field_id]->push($col);
69: }
70:
71: $collection->setMatrixCols($cols);
72: }
73:
74: 75: 76:
77: public function preload(array $entryIds)
78: {
79: $rows = $this->rowModel->entryId($entryIds)->orderBy('row_order', 'asc')->get();
80:
81: foreach ($rows as $row) {
82: if (! isset($this->rows[$row->entry_id][$row->field_id])) {
83: $this->rows[$row->entry_id][$row->field_id] = new MatrixRowCollection();
84: }
85:
86: $cols = isset($this->cols[$row->field_id]) ? $this->cols[$row->field_id] : new MatrixColCollection();
87:
88: $row->setCols($cols);
89:
90: $this->rows[$row->entry_id][$row->field_id]->push($row);
91: }
92: }
93:
94: 95: 96:
97: public function hydrate(AbstractEntity $entity, AbstractProperty $property)
98: {
99: $value = isset($this->rows[$entity->getId()][$property->getId()]) ? $this->rows[$entity->getId()][$property->getId()] : new MatrixRowCollection();
100:
101: $entity->setAttribute($property->getName(), $value);
102:
103: return $value;
104: }
105: }
106: