1: <?php
2:
3: 4: 5: 6: 7: 8:
9:
10: namespace rsanchez\Deep\Hydrator;
11:
12: use Illuminate\Database\Eloquent\Model;
13: use Illuminate\Database\Eloquent\Collection;
14: use rsanchez\Deep\Collection\EntryCollection;
15: use rsanchez\Deep\Collection\AssetCollection;
16: use rsanchez\Deep\Model\AbstractProperty;
17: use rsanchez\Deep\Model\AbstractEntity;
18: use rsanchez\Deep\Hydrator\AbstractHydrator;
19: use rsanchez\Deep\Model\Asset;
20: use rsanchez\Deep\Repository\UploadPrefRepositoryInterface;
21:
22: 23: 24:
25: class AssetsHydrator extends AbstractHydrator
26: {
27: 28: 29:
30: protected $model;
31:
32: 33: 34: 35:
36: protected $selections = array();
37:
38: 39: 40: 41:
42: protected $uploadPrefRepository;
43:
44: 45: 46: 47: 48: 49: 50:
51: public function __construct(EntryCollection $collection, $fieldtype, Asset $model, UploadPrefRepositoryInterface $uploadPrefRepository)
52: {
53: parent::__construct($collection, $fieldtype);
54:
55: $this->model = $model;
56:
57: $this->uploadPrefRepository = $uploadPrefRepository;
58: }
59:
60: 61: 62:
63: public function preload(array $entryIds)
64: {
65: $assets = $this->model->entryId($entryIds)->get();
66:
67: foreach ($assets as $asset) {
68: if (! $asset->filedir_id || ! $uploadPref = $this->uploadPrefRepository->find($asset->filedir_id)) {
69: if ( ! is_null($asset->source_id) && $asset->source_settings) {
70: $uploadPref = null;
71: } else {
72: continue;
73: }
74: }
75:
76: $asset->setUploadPref($uploadPref);
77:
78: if ($asset->content_type === 'matrix' || $asset->content_type === 'grid') {
79: if (! isset($this->selections[$asset->content_type][$asset->row_id][$asset->col_id])) {
80: $this->selections[$asset->content_type][$asset->row_id][$asset->col_id] = new AssetCollection();
81: }
82:
83: $this->selections[$asset->content_type][$asset->row_id][$asset->col_id]->push($asset);
84: } else {
85: if (! isset($this->selections['entry'][$asset->entry_id][$asset->field_id])) {
86: $this->selections['entry'][$asset->entry_id][$asset->field_id] = new AssetCollection();
87: }
88:
89: $this->selections['entry'][$asset->entry_id][$asset->field_id]->push($asset);
90: }
91: }
92: }
93:
94: 95: 96:
97: public function hydrate(AbstractEntity $entity, AbstractProperty $property)
98: {
99: if (isset($this->selections[$entity->getType()][$entity->getId()][$property->getId()])) {
100: $value = $this->selections[$entity->getType()][$entity->getId()][$property->getId()];
101: } else {
102: $value = new AssetCollection();
103: }
104:
105: $entity->setAttribute($property->getName(), $value);
106:
107: return $value;
108: }
109: }
110: