1: <?php
2:
3: /**
4: * Deep
5: *
6: * @package rsanchez\Deep
7: * @author Rob Sanchez <info@robsanchez.com>
8: */
9:
10: namespace rsanchez\Deep\Repository;
11:
12: use rsanchez\Deep\Collection\FieldCollection;
13: use rsanchez\Deep\Model\Field;
14: use rsanchez\Deep\Repository\AbstractFieldRepository;
15: use rsanchez\Deep\Collection\ChannelCollection;
16:
17: /**
18: * Repository of all Fields
19: */
20: class FieldRepository extends AbstractFieldRepository
21: {
22: /**
23: * Array of FieldCollection keyed by group_id
24: * @var array
25: */
26: protected $fieldsByGroup = array();
27:
28: /**
29: * {@inheritdoc}
30: */
31: public function __construct(Field $model)
32: {
33: parent::__construct($model);
34: }
35:
36: /**
37: * {@inheritdoc}
38: */
39: protected function boot()
40: {
41: if (is_null($this->collection)) {
42:
43: $this->collection = $this->model
44: ->orderByRaw("field_type IN ('matrix', 'grid') DESC")
45: ->orderByRaw("field_type IN ('playa', 'relationship') DESC")
46: ->orderBy('field_order', 'asc')
47: ->get();
48:
49: foreach ($this->collection as $field) {
50: if (! array_key_exists($field->group_id, $this->fieldsByGroup)) {
51: $this->fieldsByGroup[$field->group_id] = new FieldCollection();
52: }
53:
54: $this->fieldsByGroup[$field->group_id]->push($field);
55:
56: $this->fieldsByName[$field->field_name] = $field;
57: $this->fieldsById[$field->field_id] = $field;
58: }
59: }
60: }
61:
62: /**
63: * Get a Collection of fields from the specified group
64: *
65: * @param int $groupId
66: * @return \rsanchez\Deep\Collection\FieldCollection
67: */
68: public function getFieldsByGroup($groupId)
69: {
70: $this->boot();
71:
72: return $groupId && isset($this->fieldsByGroup[$groupId]) ? $this->fieldsByGroup[$groupId] : new FieldCollection();
73: }
74:
75: /**
76: * Get the fields used by the channels in the specified collection
77: * @param \rsanchez\Deep\Collection\ChannelCollection $channels
78: * @return \rsanchez\Deep\Collection\FieldCollection
79: */
80: public function getFieldsByChannelCollection(ChannelCollection $channels)
81: {
82: $this->boot();
83:
84: $fields = new FieldCollection();
85:
86: foreach ($channels as $channel) {
87: foreach ($channel->fields as $field) {
88: $fields->push($field);
89: }
90: }
91:
92: return $fields;
93: }
94: }
95: