1: <?php
2:
3: /**
4: * Deep
5: *
6: * @package rsanchez\Deep
7: * @author Rob Sanchez <info@robsanchez.com>
8: */
9:
10: namespace rsanchez\Deep\Collection;
11:
12: use rsanchez\Deep\Collection\AbstractFieldCollection;
13:
14: /**
15: * Collection of \rsanchez\Deep\Model\Field
16: */
17: class FieldCollection extends AbstractFieldCollection
18: {
19: /**
20: * Fieldtypes used by this collection
21: * @var array
22: */
23: protected $fieldtypes = array();
24:
25: /**
26: * Map of fieldtypes to field IDs:
27: * 'fieldtype_name' => array(1, 2, 3),
28: * @var array
29: */
30: protected $fieldIdsByFieldtype = array();
31:
32: protected $fieldsByFieldtype = array();
33:
34: /**
35: * {@inheritdoc}
36: */
37: public function __construct(array $fields = array())
38: {
39: parent::__construct($fields);
40:
41: foreach ($fields as $field) {
42: $this->addFieldtype($field->field_type);
43:
44: $this->fieldIdsByFieldtype[$field->field_type][] = $field->field_id;
45:
46: if (! isset($this->fieldsByFieldtype[$field->field_type])) {
47: $this->fieldsByFieldtype[$field->field_type] = new FieldCollection();
48: }
49:
50: $this->fieldsByFieldtype[$field->field_type]->items[] = $field;
51: }
52: }
53:
54: /**
55: * {@inheritdoc}
56: */
57: public function push($field)
58: {
59: $this->addFieldtype($field->field_type);
60:
61: $this->fieldIdsByFieldtype[$field->field_type][] = $field->field_id;
62:
63: if (! isset($this->fieldsByFieldtype[$field->field_type])) {
64: $this->fieldsByFieldtype[$field->field_type] = new FieldCollection();
65: }
66:
67: $this->fieldsByFieldtype[$field->field_type]->items[] = $field;
68:
69: return parent::push($field);
70: }
71:
72: /**
73: * Check if this collection uses the specified fieldtype
74: *
75: * @param string $fieldtype
76: * @return boolean
77: */
78: public function hasFieldtype($fieldtype)
79: {
80: return in_array($fieldtype, $this->fieldtypes);
81: }
82:
83: /**
84: * Get the field IDs for the specified fieldtype
85: *
86: * @param string $fieldtype
87: * @return array
88: */
89: public function getFieldIdsByFieldtype($fieldtype)
90: {
91: return isset($this->fieldIdsByFieldtype[$fieldtype]) ? $this->fieldIdsByFieldtype[$fieldtype] : array();
92: }
93:
94: public function getFieldsByFieldtype($fieldtype)
95: {
96: return isset($this->fieldsByFieldtype[$fieldtype]) ? $this->fieldsByFieldtype[$fieldtype] : new FieldCollection();
97: }
98:
99: /**
100: * Get a list of names of fieldtypes in this collection
101: * @return array
102: */
103: public function getFieldtypes()
104: {
105: return $this->fieldtypes;
106: }
107:
108: /**
109: * Add a fieldtype to the list of fieldtypes in this collection
110: * @param string $fieldtype
111: * @return void
112: */
113: public function addFieldtype($fieldtype)
114: {
115: if (! in_array($fieldtype, $this->fieldtypes)) {
116: $this->fieldtypes[] = $fieldtype;
117: }
118: }
119: }
120: