Passed
Push — master ( 21c694...dd5bf3 )
by Garion
04:35 queued 11s
created
src/ReadonlyTagField.php 2 patches
Indentation   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -12,29 +12,29 @@
 block discarded – undo
12 12
  */
13 13
 class ReadonlyTagField extends TagField
14 14
 {
15
-    /**
16
-     * {@inheritDoc}
17
-     */
18
-    protected $readonly = true;
15
+	/**
16
+	 * {@inheritDoc}
17
+	 */
18
+	protected $readonly = true;
19 19
 
20
-    /**
21
-     * Render the readonly field as HTML.
22
-     *
23
-     * @param array $properties
24
-     * @return HTMLText
25
-     */
26
-    public function Field($properties = array())
27
-    {
28
-        $options = array();
20
+	/**
21
+	 * Render the readonly field as HTML.
22
+	 *
23
+	 * @param array $properties
24
+	 * @return HTMLText
25
+	 */
26
+	public function Field($properties = array())
27
+	{
28
+		$options = array();
29 29
 
30
-        foreach ($this->getOptions()->filter('Selected', true) as $option) {
31
-            $options[] = $option->Title;
32
-        }
30
+		foreach ($this->getOptions()->filter('Selected', true) as $option) {
31
+			$options[] = $option->Title;
32
+		}
33 33
 
34
-        $field = ReadonlyField::create($this->name . '_Readonly', $this->title);
34
+		$field = ReadonlyField::create($this->name . '_Readonly', $this->title);
35 35
 
36
-        $field->setForm($this->form);
37
-        $field->setValue(implode(', ', $options));
38
-        return $field->Field();
39
-    }
36
+		$field->setForm($this->form);
37
+		$field->setValue(implode(', ', $options));
38
+		return $field->Field();
39
+	}
40 40
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -31,7 +31,7 @@
 block discarded – undo
31 31
             $options[] = $option->Title;
32 32
         }
33 33
 
34
-        $field = ReadonlyField::create($this->name . '_Readonly', $this->title);
34
+        $field = ReadonlyField::create($this->name.'_Readonly', $this->title);
35 35
 
36 36
         $field->setForm($this->form);
37 37
         $field->setValue(implode(', ', $options));
Please login to merge, or discard this patch.
tests/Stub/StringTagFieldTestController.php 1 patch
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -12,21 +12,21 @@
 block discarded – undo
12 12
 
13 13
 class StringTagFieldTestController extends Controller implements TestOnly
14 14
 {
15
-    public function StringTagFieldTestForm()
16
-    {
17
-        $fields = new FieldList(
18
-            $tagField = new StringTagField('Tags')
19
-        );
15
+	public function StringTagFieldTestForm()
16
+	{
17
+		$fields = new FieldList(
18
+			$tagField = new StringTagField('Tags')
19
+		);
20 20
 
21
-        $actions = new FieldList(
22
-            new FormAction('StringTagFieldTestFormSubmit')
23
-        );
21
+		$actions = new FieldList(
22
+			new FormAction('StringTagFieldTestFormSubmit')
23
+		);
24 24
 
25
-        return new Form($this, 'StringTagFieldTestForm', $fields, $actions);
26
-    }
25
+		return new Form($this, 'StringTagFieldTestForm', $fields, $actions);
26
+	}
27 27
 
28
-    public function StringTagFieldTestFormSubmit(DataObject $dataObject, Form $form)
29
-    {
30
-        $form->saveInto($dataObject);
31
-    }
28
+	public function StringTagFieldTestFormSubmit(DataObject $dataObject, Form $form)
29
+	{
30
+		$form->saveInto($dataObject);
31
+	}
32 32
 }
Please login to merge, or discard this patch.
tests/Stub/TagFieldTestBlogPost.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -8,14 +8,14 @@
 block discarded – undo
8 8
 
9 9
 class TagFieldTestBlogPost extends DataObject implements TestOnly
10 10
 {
11
-    private static $table_name = 'TagFieldTestBlogPost';
11
+	private static $table_name = 'TagFieldTestBlogPost';
12 12
 
13
-    private static $db = [
14
-        'Title'   => 'Text',
15
-        'Content' => 'Text'
16
-    ];
13
+	private static $db = [
14
+		'Title'   => 'Text',
15
+		'Content' => 'Text'
16
+	];
17 17
 
18
-    private static $many_many = [
19
-        'Tags' => TagFieldTestBlogTag::class
20
-    ];
18
+	private static $many_many = [
19
+		'Tags' => TagFieldTestBlogTag::class
20
+	];
21 21
 }
Please login to merge, or discard this patch.
tests/Stub/TagFieldTestController.php 1 patch
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -13,21 +13,21 @@
 block discarded – undo
13 13
 
14 14
 class TagFieldTestController extends Controller implements TestOnly
15 15
 {
16
-    public function TagFieldTestForm()
17
-    {
18
-        $fields = new FieldList(
19
-            $tagField = new TagField('Tags', '', new DataList('TagFieldTestBlogTag'))
20
-        );
16
+	public function TagFieldTestForm()
17
+	{
18
+		$fields = new FieldList(
19
+			$tagField = new TagField('Tags', '', new DataList('TagFieldTestBlogTag'))
20
+		);
21 21
 
22
-        $actions = new FieldList(
23
-            new FormAction('TagFieldTestFormSubmit')
24
-        );
22
+		$actions = new FieldList(
23
+			new FormAction('TagFieldTestFormSubmit')
24
+		);
25 25
 
26
-        return new Form($this, 'TagFieldTestForm', $fields, $actions);
27
-    }
26
+		return new Form($this, 'TagFieldTestForm', $fields, $actions);
27
+	}
28 28
 
29
-    public function TagFieldTestFormSubmit(DataObject $dataObject, Form $form)
30
-    {
31
-        $form->saveInto($dataObject);
32
-    }
29
+	public function TagFieldTestFormSubmit(DataObject $dataObject, Form $form)
30
+	{
31
+		$form->saveInto($dataObject);
32
+	}
33 33
 }
Please login to merge, or discard this patch.
tests/Stub/TagFieldTestBlogTag.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -8,15 +8,15 @@
 block discarded – undo
8 8
 
9 9
 class TagFieldTestBlogTag extends DataObject implements TestOnly
10 10
 {
11
-    private static $table_name = 'TagFieldTestBlogTag';
11
+	private static $table_name = 'TagFieldTestBlogTag';
12 12
 
13
-    private static $default_sort = '"TagFieldTestBlogTag"."ID" ASC';
13
+	private static $default_sort = '"TagFieldTestBlogTag"."ID" ASC';
14 14
 
15
-    private static $db = [
16
-        'Title' => 'Varchar(200)'
17
-    ];
15
+	private static $db = [
16
+		'Title' => 'Varchar(200)'
17
+	];
18 18
 
19
-    private static $belongs_many_many = [
20
-        'BlogPosts' => TagFieldTestBlogPost::class
21
-    ];
19
+	private static $belongs_many_many = [
20
+		'BlogPosts' => TagFieldTestBlogPost::class
21
+	];
22 22
 }
Please login to merge, or discard this patch.
tests/Stub/StringTagFieldTestBlogPost.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -7,11 +7,11 @@
 block discarded – undo
7 7
 
8 8
 class StringTagFieldTestBlogPost extends DataObject implements TestOnly
9 9
 {
10
-    private static $table_name = 'StringTagFieldTestBlogPost';
10
+	private static $table_name = 'StringTagFieldTestBlogPost';
11 11
 
12
-    private static $db = [
13
-        'Title' => 'Text',
14
-        'Content' => 'Text',
15
-        'Tags' => 'Text',
16
-    ];
12
+	private static $db = [
13
+		'Title' => 'Text',
14
+		'Content' => 'Text',
15
+		'Tags' => 'Text',
16
+	];
17 17
 }
Please login to merge, or discard this patch.
src/StringTagField.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -161,7 +161,7 @@
 block discarded – undo
161 161
         $schema = array_merge(
162 162
             parent::getSchemaDataDefaults(),
163 163
             [
164
-                'name' => $this->getName() . '[]',
164
+                'name' => $this->getName().'[]',
165 165
                 'lazyLoad' => $this->getShouldLazyLoad(),
166 166
                 'creatable' => $this->getCanCreate(),
167 167
                 'multi' => $this->getIsMultiple(),
Please login to merge, or discard this patch.
Indentation   +330 added lines, -330 removed lines patch added patch discarded remove patch
@@ -26,334 +26,334 @@
 block discarded – undo
26 26
  */
27 27
 class StringTagField extends DropdownField
28 28
 {
29
-    /**
30
-     * @var array
31
-     */
32
-    private static $allowed_actions = [
33
-        'suggest',
34
-    ];
35
-
36
-    /**
37
-     * @var bool
38
-     */
39
-    protected $shouldLazyLoad = false;
40
-
41
-    /**
42
-     * @var int
43
-     */
44
-    protected $lazyLoadItemLimit = 10;
45
-
46
-    /**
47
-     * @var bool
48
-     */
49
-    protected $canCreate = true;
50
-
51
-    /**
52
-     * @var null|DataObject
53
-     */
54
-    protected $record;
55
-
56
-    /**
57
-     * @var bool
58
-     */
59
-    protected $isMultiple = true;
60
-
61
-    /**
62
-     * @return bool
63
-     */
64
-    public function getShouldLazyLoad()
65
-    {
66
-        return $this->shouldLazyLoad;
67
-    }
68
-
69
-    /**
70
-     * @param bool $shouldLazyLoad
71
-     * @return $this
72
-     */
73
-    public function setShouldLazyLoad($shouldLazyLoad)
74
-    {
75
-        $this->shouldLazyLoad = $shouldLazyLoad;
76
-
77
-        return $this;
78
-    }
79
-
80
-    /**
81
-     * @return int
82
-     */
83
-    public function getLazyLoadItemLimit()
84
-    {
85
-        return $this->lazyLoadItemLimit;
86
-    }
87
-
88
-    /**
89
-     * @param int $lazyLoadItemLimit
90
-     * @return $this
91
-     */
92
-    public function setLazyLoadItemLimit($lazyLoadItemLimit)
93
-    {
94
-        $this->lazyLoadItemLimit = $lazyLoadItemLimit;
95
-
96
-        return $this;
97
-    }
98
-
99
-    /**
100
-     * @return bool
101
-     */
102
-    public function getIsMultiple()
103
-    {
104
-        return $this->isMultiple;
105
-    }
106
-
107
-    /**
108
-     * @param bool $isMultiple
109
-     * @return $this
110
-     */
111
-    public function setIsMultiple($isMultiple)
112
-    {
113
-        $this->isMultiple = $isMultiple;
114
-
115
-        return $this;
116
-    }
117
-
118
-    /**
119
-     * @return null|DataObject
120
-     */
121
-    public function getRecord()
122
-    {
123
-        if ($this->record) {
124
-            return $this->record;
125
-        }
126
-
127
-        if ($form = $this->getForm()) {
128
-            return $form->getRecord();
129
-        }
130
-
131
-        return null;
132
-    }
133
-
134
-    /**
135
-     * @param DataObject $record
136
-     * @return $this
137
-     */
138
-    public function setRecord(DataObject $record)
139
-    {
140
-        $this->record = $record;
141
-
142
-        return $this;
143
-    }
144
-
145
-    public function Field($properties = [])
146
-    {
147
-        $this->addExtraClass('ss-tag-field');
148
-
149
-        return $this
150
-            ->customise($properties)
151
-            ->renderWith(TagField::class);
152
-    }
153
-
154
-    /**
155
-     * Provide TagField data to the JSON schema for the frontend component
156
-     *
157
-     * @return array
158
-     */
159
-    public function getSchemaDataDefaults()
160
-    {
161
-        $schema = array_merge(
162
-            parent::getSchemaDataDefaults(),
163
-            [
164
-                'name' => $this->getName() . '[]',
165
-                'lazyLoad' => $this->getShouldLazyLoad(),
166
-                'creatable' => $this->getCanCreate(),
167
-                'multi' => $this->getIsMultiple(),
168
-                'value' => $this->formatOptions($this->Value()),
169
-                'disabled' => $this->isDisabled() || $this->isReadonly(),
170
-            ]
171
-        );
172
-
173
-        if (!$this->getShouldLazyLoad()) {
174
-            $schema['options'] = $this->getOptions()->toNestedArray();
175
-        } else {
176
-            $schema['optionUrl'] = $this->getSuggestURL();
177
-        }
178
-
179
-        return $schema;
180
-    }
181
-
182
-    protected function formatOptions($fieldValue)
183
-    {
184
-        if (empty($fieldValue)) {
185
-            return [];
186
-        }
187
-
188
-        $formattedValue = [];
189
-        foreach ($fieldValue as $value) {
190
-            $formattedValue[] = [
191
-                'Title' => $value,
192
-                'Value' => $value,
193
-            ];
194
-        }
195
-        return $formattedValue;
196
-    }
197
-
198
-    /**
199
-     * When not used in a React form factory context, this adds the schema data to SilverStripe template
200
-     * rendered attributes lists
201
-     *
202
-     * @return array
203
-     */
204
-    public function getAttributes()
205
-    {
206
-        $attributes = parent::getAttributes();
207
-        $attributes['data-schema'] = json_encode($this->getSchemaData());
208
-        return $attributes;
209
-    }
210
-
211
-    /**
212
-     * @return string
213
-     */
214
-    protected function getSuggestURL()
215
-    {
216
-        return Controller::join_links($this->Link(), 'suggest');
217
-    }
218
-
219
-    /**
220
-     * @return ArrayList
221
-     */
222
-    protected function getOptions()
223
-    {
224
-        $options = ArrayList::create();
225
-
226
-        $source = $this->getSource();
227
-
228
-        if ($source instanceof Iterator) {
229
-            $source = iterator_to_array($source);
230
-        }
231
-
232
-        foreach ($source as $value) {
233
-            $options->push(
234
-                ArrayData::create([
235
-                    'Title' => $value,
236
-                    'Value' => $value,
237
-                ])
238
-            );
239
-        }
240
-
241
-        return $options;
242
-    }
243
-
244
-    public function setValue($value, $source = null)
245
-    {
246
-        if (is_string($value)) {
247
-            $value = explode(',', $value);
248
-        }
249
-
250
-        if ($source instanceof DataObject) {
251
-            $name = $this->getName();
252
-            $value = explode(',', $source->$name);
253
-        }
254
-
255
-        if ($source instanceof SS_List) {
256
-            $value = $source->column('ID');
257
-        }
258
-
259
-        if ($value === null) {
260
-            $value = [];
261
-        }
262
-
263
-        return parent::setValue(array_filter($value));
264
-    }
265
-
266
-    public function saveInto(DataObjectInterface $record)
267
-    {
268
-        parent::saveInto($record);
269
-
270
-        $name = $this->getName();
271
-
272
-        $record->$name = $this->dataValue();
273
-        $record->write();
274
-    }
275
-
276
-    /**
277
-     * Ensure that arrays are imploded before being saved
278
-     *
279
-     * @return mixed|string
280
-     */
281
-    public function dataValue()
282
-    {
283
-        return implode(',', $this->value);
284
-    }
285
-
286
-    /**
287
-     * Returns a JSON string of tags, for lazy loading.
288
-     *
289
-     * @param  HTTPRequest $request
290
-     * @return HTTPResponse
291
-     */
292
-    public function suggest(HTTPRequest $request)
293
-    {
294
-        $responseBody = json_encode(
295
-            ['items' => $this->getTags($request->getVar('term'))]
296
-        );
297
-
298
-        $response = HTTPResponse::create();
299
-        $response->addHeader('Content-Type', 'application/json');
300
-        $response->setBody($responseBody);
301
-
302
-        return $response;
303
-    }
304
-
305
-    /**
306
-     * Returns array of arrays representing tags that partially match the given search term
307
-     *
308
-     * @param string $term
309
-     * @return array
310
-     */
311
-    protected function getTags($term)
312
-    {
313
-        $items = [];
314
-        foreach ($this->getOptions() as $i => $tag) {
315
-            /** @var ArrayData $tag */
316
-            $tagValue = $tag->Value;
317
-            // Map into a distinct list (prevent duplicates)
318
-            if (stripos($tagValue, $term) !== false && !array_key_exists($tagValue, $items)) {
319
-                $items[$tagValue] = [
320
-                    'id' => $tag->Title,
321
-                    'text' => $tag->Value,
322
-                ];
323
-            }
324
-        }
325
-        // @todo do we actually need lazy loading limits for StringTagField?
326
-        return array_slice(array_values($items), 0, $this->getLazyLoadItemLimit());
327
-    }
328
-
329
-    /**
330
-     * DropdownField assumes value will be a scalar so we must
331
-     * override validate. This only applies to Silverstripe 3.2+
332
-     *
333
-     * @param Validator $validator
334
-     * @return bool
335
-     */
336
-    public function validate($validator)
337
-    {
338
-        return true;
339
-    }
340
-
341
-    /**
342
-     * @return bool
343
-     */
344
-    public function getCanCreate()
345
-    {
346
-        return $this->canCreate;
347
-    }
348
-
349
-    /**
350
-     * @param bool $canCreate
351
-     * @return $this
352
-     */
353
-    public function setCanCreate($canCreate)
354
-    {
355
-        $this->canCreate = $canCreate;
356
-
357
-        return $this;
358
-    }
29
+	/**
30
+	 * @var array
31
+	 */
32
+	private static $allowed_actions = [
33
+		'suggest',
34
+	];
35
+
36
+	/**
37
+	 * @var bool
38
+	 */
39
+	protected $shouldLazyLoad = false;
40
+
41
+	/**
42
+	 * @var int
43
+	 */
44
+	protected $lazyLoadItemLimit = 10;
45
+
46
+	/**
47
+	 * @var bool
48
+	 */
49
+	protected $canCreate = true;
50
+
51
+	/**
52
+	 * @var null|DataObject
53
+	 */
54
+	protected $record;
55
+
56
+	/**
57
+	 * @var bool
58
+	 */
59
+	protected $isMultiple = true;
60
+
61
+	/**
62
+	 * @return bool
63
+	 */
64
+	public function getShouldLazyLoad()
65
+	{
66
+		return $this->shouldLazyLoad;
67
+	}
68
+
69
+	/**
70
+	 * @param bool $shouldLazyLoad
71
+	 * @return $this
72
+	 */
73
+	public function setShouldLazyLoad($shouldLazyLoad)
74
+	{
75
+		$this->shouldLazyLoad = $shouldLazyLoad;
76
+
77
+		return $this;
78
+	}
79
+
80
+	/**
81
+	 * @return int
82
+	 */
83
+	public function getLazyLoadItemLimit()
84
+	{
85
+		return $this->lazyLoadItemLimit;
86
+	}
87
+
88
+	/**
89
+	 * @param int $lazyLoadItemLimit
90
+	 * @return $this
91
+	 */
92
+	public function setLazyLoadItemLimit($lazyLoadItemLimit)
93
+	{
94
+		$this->lazyLoadItemLimit = $lazyLoadItemLimit;
95
+
96
+		return $this;
97
+	}
98
+
99
+	/**
100
+	 * @return bool
101
+	 */
102
+	public function getIsMultiple()
103
+	{
104
+		return $this->isMultiple;
105
+	}
106
+
107
+	/**
108
+	 * @param bool $isMultiple
109
+	 * @return $this
110
+	 */
111
+	public function setIsMultiple($isMultiple)
112
+	{
113
+		$this->isMultiple = $isMultiple;
114
+
115
+		return $this;
116
+	}
117
+
118
+	/**
119
+	 * @return null|DataObject
120
+	 */
121
+	public function getRecord()
122
+	{
123
+		if ($this->record) {
124
+			return $this->record;
125
+		}
126
+
127
+		if ($form = $this->getForm()) {
128
+			return $form->getRecord();
129
+		}
130
+
131
+		return null;
132
+	}
133
+
134
+	/**
135
+	 * @param DataObject $record
136
+	 * @return $this
137
+	 */
138
+	public function setRecord(DataObject $record)
139
+	{
140
+		$this->record = $record;
141
+
142
+		return $this;
143
+	}
144
+
145
+	public function Field($properties = [])
146
+	{
147
+		$this->addExtraClass('ss-tag-field');
148
+
149
+		return $this
150
+			->customise($properties)
151
+			->renderWith(TagField::class);
152
+	}
153
+
154
+	/**
155
+	 * Provide TagField data to the JSON schema for the frontend component
156
+	 *
157
+	 * @return array
158
+	 */
159
+	public function getSchemaDataDefaults()
160
+	{
161
+		$schema = array_merge(
162
+			parent::getSchemaDataDefaults(),
163
+			[
164
+				'name' => $this->getName() . '[]',
165
+				'lazyLoad' => $this->getShouldLazyLoad(),
166
+				'creatable' => $this->getCanCreate(),
167
+				'multi' => $this->getIsMultiple(),
168
+				'value' => $this->formatOptions($this->Value()),
169
+				'disabled' => $this->isDisabled() || $this->isReadonly(),
170
+			]
171
+		);
172
+
173
+		if (!$this->getShouldLazyLoad()) {
174
+			$schema['options'] = $this->getOptions()->toNestedArray();
175
+		} else {
176
+			$schema['optionUrl'] = $this->getSuggestURL();
177
+		}
178
+
179
+		return $schema;
180
+	}
181
+
182
+	protected function formatOptions($fieldValue)
183
+	{
184
+		if (empty($fieldValue)) {
185
+			return [];
186
+		}
187
+
188
+		$formattedValue = [];
189
+		foreach ($fieldValue as $value) {
190
+			$formattedValue[] = [
191
+				'Title' => $value,
192
+				'Value' => $value,
193
+			];
194
+		}
195
+		return $formattedValue;
196
+	}
197
+
198
+	/**
199
+	 * When not used in a React form factory context, this adds the schema data to SilverStripe template
200
+	 * rendered attributes lists
201
+	 *
202
+	 * @return array
203
+	 */
204
+	public function getAttributes()
205
+	{
206
+		$attributes = parent::getAttributes();
207
+		$attributes['data-schema'] = json_encode($this->getSchemaData());
208
+		return $attributes;
209
+	}
210
+
211
+	/**
212
+	 * @return string
213
+	 */
214
+	protected function getSuggestURL()
215
+	{
216
+		return Controller::join_links($this->Link(), 'suggest');
217
+	}
218
+
219
+	/**
220
+	 * @return ArrayList
221
+	 */
222
+	protected function getOptions()
223
+	{
224
+		$options = ArrayList::create();
225
+
226
+		$source = $this->getSource();
227
+
228
+		if ($source instanceof Iterator) {
229
+			$source = iterator_to_array($source);
230
+		}
231
+
232
+		foreach ($source as $value) {
233
+			$options->push(
234
+				ArrayData::create([
235
+					'Title' => $value,
236
+					'Value' => $value,
237
+				])
238
+			);
239
+		}
240
+
241
+		return $options;
242
+	}
243
+
244
+	public function setValue($value, $source = null)
245
+	{
246
+		if (is_string($value)) {
247
+			$value = explode(',', $value);
248
+		}
249
+
250
+		if ($source instanceof DataObject) {
251
+			$name = $this->getName();
252
+			$value = explode(',', $source->$name);
253
+		}
254
+
255
+		if ($source instanceof SS_List) {
256
+			$value = $source->column('ID');
257
+		}
258
+
259
+		if ($value === null) {
260
+			$value = [];
261
+		}
262
+
263
+		return parent::setValue(array_filter($value));
264
+	}
265
+
266
+	public function saveInto(DataObjectInterface $record)
267
+	{
268
+		parent::saveInto($record);
269
+
270
+		$name = $this->getName();
271
+
272
+		$record->$name = $this->dataValue();
273
+		$record->write();
274
+	}
275
+
276
+	/**
277
+	 * Ensure that arrays are imploded before being saved
278
+	 *
279
+	 * @return mixed|string
280
+	 */
281
+	public function dataValue()
282
+	{
283
+		return implode(',', $this->value);
284
+	}
285
+
286
+	/**
287
+	 * Returns a JSON string of tags, for lazy loading.
288
+	 *
289
+	 * @param  HTTPRequest $request
290
+	 * @return HTTPResponse
291
+	 */
292
+	public function suggest(HTTPRequest $request)
293
+	{
294
+		$responseBody = json_encode(
295
+			['items' => $this->getTags($request->getVar('term'))]
296
+		);
297
+
298
+		$response = HTTPResponse::create();
299
+		$response->addHeader('Content-Type', 'application/json');
300
+		$response->setBody($responseBody);
301
+
302
+		return $response;
303
+	}
304
+
305
+	/**
306
+	 * Returns array of arrays representing tags that partially match the given search term
307
+	 *
308
+	 * @param string $term
309
+	 * @return array
310
+	 */
311
+	protected function getTags($term)
312
+	{
313
+		$items = [];
314
+		foreach ($this->getOptions() as $i => $tag) {
315
+			/** @var ArrayData $tag */
316
+			$tagValue = $tag->Value;
317
+			// Map into a distinct list (prevent duplicates)
318
+			if (stripos($tagValue, $term) !== false && !array_key_exists($tagValue, $items)) {
319
+				$items[$tagValue] = [
320
+					'id' => $tag->Title,
321
+					'text' => $tag->Value,
322
+				];
323
+			}
324
+		}
325
+		// @todo do we actually need lazy loading limits for StringTagField?
326
+		return array_slice(array_values($items), 0, $this->getLazyLoadItemLimit());
327
+	}
328
+
329
+	/**
330
+	 * DropdownField assumes value will be a scalar so we must
331
+	 * override validate. This only applies to Silverstripe 3.2+
332
+	 *
333
+	 * @param Validator $validator
334
+	 * @return bool
335
+	 */
336
+	public function validate($validator)
337
+	{
338
+		return true;
339
+	}
340
+
341
+	/**
342
+	 * @return bool
343
+	 */
344
+	public function getCanCreate()
345
+	{
346
+		return $this->canCreate;
347
+	}
348
+
349
+	/**
350
+	 * @param bool $canCreate
351
+	 * @return $this
352
+	 */
353
+	public function setCanCreate($canCreate)
354
+	{
355
+		$this->canCreate = $canCreate;
356
+
357
+		return $this;
358
+	}
359 359
 }
Please login to merge, or discard this patch.
tests/StringTagFieldTest.php 1 patch
Indentation   +140 added lines, -140 removed lines patch added patch discarded remove patch
@@ -15,144 +15,144 @@
 block discarded – undo
15 15
  */
16 16
 class StringTagFieldTest extends SapphireTest
17 17
 {
18
-    /**
19
-     * @var string
20
-     */
21
-    protected static $fixture_file = 'StringTagFieldTest.yml';
22
-
23
-    /**
24
-     * @var array
25
-     */
26
-    protected static $extra_dataobjects = [
27
-        StringTagFieldTestBlogPost::class,
28
-    ];
29
-
30
-    public function testItSavesTagsOnNewRecords()
31
-    {
32
-        $record = $this->getNewStringTagFieldTestBlogPost('BlogPost1');
33
-
34
-        $field = new StringTagField('Tags');
35
-        $field->setValue(['Tag1', 'Tag2']);
36
-        $field->saveInto($record);
37
-
38
-        $record->write();
39
-
40
-        $this->assertEquals('Tag1,Tag2', $record->Tags);
41
-    }
42
-
43
-    /**
44
-     * @param string $name
45
-     *
46
-     * @return StringTagFieldTestBlogPost
47
-     */
48
-    protected function getNewStringTagFieldTestBlogPost($name)
49
-    {
50
-        return $this->objFromFixture(
51
-            StringTagFieldTestBlogPost::class,
52
-            $name
53
-        );
54
-    }
55
-
56
-    public function testItSavesTagsOnExistingRecords()
57
-    {
58
-        $record = $this->getNewStringTagFieldTestBlogPost('BlogPost1');
59
-        $record->write();
60
-
61
-        $field = new StringTagField('Tags');
62
-        $field->setValue(['Tag1', 'Tag2']);
63
-        $field->saveInto($record);
64
-
65
-        $this->assertEquals('Tag1,Tag2', $record->Tags);
66
-    }
67
-
68
-    public function testItSuggestsTags()
69
-    {
70
-        $field = new StringTagField('SomeField', 'Some field', ['Tag1', 'Tag2'], []);
71
-
72
-        /**
73
-         * Partial tag title match.
74
-         */
75
-        $request = $this->getNewRequest(['term' => 'Tag']);
76
-
77
-        $this->assertEquals(
78
-            '{"items":[{"id":"Tag1","text":"Tag1"},{"id":"Tag2","text":"Tag2"}]}',
79
-            $field->suggest($request)->getBody()
80
-        );
81
-
82
-        /**
83
-         * Exact tag title match.
84
-         */
85
-        $request = $this->getNewRequest(['term' => 'Tag1']);
86
-
87
-        $this->assertEquals($field->suggest($request)->getBody(), '{"items":[{"id":"Tag1","text":"Tag1"}]}');
88
-
89
-        /**
90
-         * Case-insensitive tag title match.
91
-         */
92
-        $request = $this->getNewRequest(['term' => 'TAG1']);
93
-
94
-        $this->assertEquals(
95
-            '{"items":[{"id":"Tag1","text":"Tag1"}]}',
96
-            $field->suggest($request)->getBody()
97
-        );
98
-
99
-        /**
100
-         * No tag title match.
101
-         */
102
-        $request = $this->getNewRequest(['term' => 'unknown']);
103
-
104
-        $this->assertEquals(
105
-            '{"items":[]}',
106
-            $field->suggest($request)->getBody()
107
-        );
108
-    }
109
-
110
-    public function testGetSchemaDataDefaults()
111
-    {
112
-        $form = new Form(null, 'Form', new FieldList(), new FieldList());
113
-        $field = new StringTagField('TestField', 'Test Field', ['one', 'two']);
114
-        $field->setForm($form);
115
-
116
-        $field
117
-            ->setShouldLazyLoad(false)
118
-            ->setCanCreate(false);
119
-
120
-        $schema = $field->getSchemaDataDefaults();
121
-        $this->assertSame('TestField[]', $schema['name']);
122
-        $this->assertFalse($schema['lazyLoad']);
123
-        $this->assertFalse($schema['creatable']);
124
-        $this->assertEquals([
125
-            ['Title' => 'one', 'Value' => 'one'],
126
-            ['Title' => 'two', 'Value' => 'two'],
127
-        ], $schema['options']);
128
-
129
-        $field
130
-            ->setShouldLazyLoad(true)
131
-            ->setCanCreate(true);
132
-
133
-        $schema = $field->getSchemaDataDefaults();
134
-        $this->assertTrue($schema['lazyLoad']);
135
-        $this->assertTrue($schema['creatable']);
136
-        $this->assertContains('suggest', $schema['optionUrl']);
137
-    }
138
-
139
-    public function testSchemaIsAddedToAttributes()
140
-    {
141
-        $field = new StringTagField('TestField');
142
-        $attributes = $field->getAttributes();
143
-        $this->assertNotEmpty($attributes['data-schema']);
144
-    }
145
-
146
-    /**
147
-     * @param array $parameters
148
-     * @return HTTPRequest
149
-     */
150
-    protected function getNewRequest(array $parameters)
151
-    {
152
-        return new HTTPRequest(
153
-            'get',
154
-            'StringTagFieldTestController/StringTagFieldTestForm/fields/Tags/suggest',
155
-            $parameters
156
-        );
157
-    }
18
+	/**
19
+	 * @var string
20
+	 */
21
+	protected static $fixture_file = 'StringTagFieldTest.yml';
22
+
23
+	/**
24
+	 * @var array
25
+	 */
26
+	protected static $extra_dataobjects = [
27
+		StringTagFieldTestBlogPost::class,
28
+	];
29
+
30
+	public function testItSavesTagsOnNewRecords()
31
+	{
32
+		$record = $this->getNewStringTagFieldTestBlogPost('BlogPost1');
33
+
34
+		$field = new StringTagField('Tags');
35
+		$field->setValue(['Tag1', 'Tag2']);
36
+		$field->saveInto($record);
37
+
38
+		$record->write();
39
+
40
+		$this->assertEquals('Tag1,Tag2', $record->Tags);
41
+	}
42
+
43
+	/**
44
+	 * @param string $name
45
+	 *
46
+	 * @return StringTagFieldTestBlogPost
47
+	 */
48
+	protected function getNewStringTagFieldTestBlogPost($name)
49
+	{
50
+		return $this->objFromFixture(
51
+			StringTagFieldTestBlogPost::class,
52
+			$name
53
+		);
54
+	}
55
+
56
+	public function testItSavesTagsOnExistingRecords()
57
+	{
58
+		$record = $this->getNewStringTagFieldTestBlogPost('BlogPost1');
59
+		$record->write();
60
+
61
+		$field = new StringTagField('Tags');
62
+		$field->setValue(['Tag1', 'Tag2']);
63
+		$field->saveInto($record);
64
+
65
+		$this->assertEquals('Tag1,Tag2', $record->Tags);
66
+	}
67
+
68
+	public function testItSuggestsTags()
69
+	{
70
+		$field = new StringTagField('SomeField', 'Some field', ['Tag1', 'Tag2'], []);
71
+
72
+		/**
73
+		 * Partial tag title match.
74
+		 */
75
+		$request = $this->getNewRequest(['term' => 'Tag']);
76
+
77
+		$this->assertEquals(
78
+			'{"items":[{"id":"Tag1","text":"Tag1"},{"id":"Tag2","text":"Tag2"}]}',
79
+			$field->suggest($request)->getBody()
80
+		);
81
+
82
+		/**
83
+		 * Exact tag title match.
84
+		 */
85
+		$request = $this->getNewRequest(['term' => 'Tag1']);
86
+
87
+		$this->assertEquals($field->suggest($request)->getBody(), '{"items":[{"id":"Tag1","text":"Tag1"}]}');
88
+
89
+		/**
90
+		 * Case-insensitive tag title match.
91
+		 */
92
+		$request = $this->getNewRequest(['term' => 'TAG1']);
93
+
94
+		$this->assertEquals(
95
+			'{"items":[{"id":"Tag1","text":"Tag1"}]}',
96
+			$field->suggest($request)->getBody()
97
+		);
98
+
99
+		/**
100
+		 * No tag title match.
101
+		 */
102
+		$request = $this->getNewRequest(['term' => 'unknown']);
103
+
104
+		$this->assertEquals(
105
+			'{"items":[]}',
106
+			$field->suggest($request)->getBody()
107
+		);
108
+	}
109
+
110
+	public function testGetSchemaDataDefaults()
111
+	{
112
+		$form = new Form(null, 'Form', new FieldList(), new FieldList());
113
+		$field = new StringTagField('TestField', 'Test Field', ['one', 'two']);
114
+		$field->setForm($form);
115
+
116
+		$field
117
+			->setShouldLazyLoad(false)
118
+			->setCanCreate(false);
119
+
120
+		$schema = $field->getSchemaDataDefaults();
121
+		$this->assertSame('TestField[]', $schema['name']);
122
+		$this->assertFalse($schema['lazyLoad']);
123
+		$this->assertFalse($schema['creatable']);
124
+		$this->assertEquals([
125
+			['Title' => 'one', 'Value' => 'one'],
126
+			['Title' => 'two', 'Value' => 'two'],
127
+		], $schema['options']);
128
+
129
+		$field
130
+			->setShouldLazyLoad(true)
131
+			->setCanCreate(true);
132
+
133
+		$schema = $field->getSchemaDataDefaults();
134
+		$this->assertTrue($schema['lazyLoad']);
135
+		$this->assertTrue($schema['creatable']);
136
+		$this->assertContains('suggest', $schema['optionUrl']);
137
+	}
138
+
139
+	public function testSchemaIsAddedToAttributes()
140
+	{
141
+		$field = new StringTagField('TestField');
142
+		$attributes = $field->getAttributes();
143
+		$this->assertNotEmpty($attributes['data-schema']);
144
+	}
145
+
146
+	/**
147
+	 * @param array $parameters
148
+	 * @return HTTPRequest
149
+	 */
150
+	protected function getNewRequest(array $parameters)
151
+	{
152
+		return new HTTPRequest(
153
+			'get',
154
+			'StringTagFieldTestController/StringTagFieldTestForm/fields/Tags/suggest',
155
+			$parameters
156
+		);
157
+	}
158 158
 }
Please login to merge, or discard this patch.
src/TagField.php 2 patches
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -220,7 +220,7 @@  discard block
 block discarded – undo
220 220
         $schema = array_merge(
221 221
             parent::getSchemaDataDefaults(),
222 222
             [
223
-                'name' => $this->getName() . '[]',
223
+                'name' => $this->getName().'[]',
224 224
                 'lazyLoad' => $this->getShouldLazyLoad(),
225 225
                 'creatable' => $this->getCanCreate(),
226 226
                 'multi' => $this->getIsMultiple(),
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
         }
278 278
 
279 279
         // Prep a function to parse a dataobject into an option
280
-        $addOption = function (DataObject $item) use ($options, $values) {
280
+        $addOption = function(DataObject $item) use ($options, $values) {
281 281
             $titleField = $this->getTitleField();
282 282
             $option = $item->$titleField;
283 283
             $options->push(ArrayData::create([
@@ -325,7 +325,7 @@  discard block
 block discarded – undo
325 325
         return array_merge(
326 326
             parent::getAttributes(),
327 327
             [
328
-                'name' => $this->getName() . '[]',
328
+                'name' => $this->getName().'[]',
329 329
                 'style' => 'width: 100%',
330 330
                 'data-schema' => json_encode($this->getSchemaData()),
331 331
             ]
@@ -437,7 +437,7 @@  discard block
 block discarded – undo
437 437
         $titleField = $this->getTitleField();
438 438
 
439 439
         $query = $source
440
-            ->filter($titleField . ':PartialMatch:nocase', $term)
440
+            ->filter($titleField.':PartialMatch:nocase', $term)
441 441
             ->sort($titleField)
442 442
             ->limit($this->getLazyLoadItemLimit());
443 443
 
Please login to merge, or discard this patch.
Indentation   +525 added lines, -525 removed lines patch added patch discarded remove patch
@@ -26,529 +26,529 @@
 block discarded – undo
26 26
  */
27 27
 class TagField extends MultiSelectField
28 28
 {
29
-    /**
30
-     * @var array
31
-     */
32
-    private static $allowed_actions = [
33
-        'suggest',
34
-    ];
35
-
36
-    /**
37
-     * @var bool
38
-     */
39
-    protected $shouldLazyLoad = false;
40
-
41
-    /**
42
-     * @var int
43
-     */
44
-    protected $lazyLoadItemLimit = 10;
45
-
46
-    /**
47
-     * @var bool
48
-     */
49
-    protected $canCreate = true;
50
-
51
-    /**
52
-     * @var string
53
-     */
54
-    protected $titleField = 'Title';
55
-
56
-    /**
57
-     * @var DataList
58
-     */
59
-    protected $sourceList;
60
-
61
-    /**
62
-     * @var bool
63
-     */
64
-    protected $isMultiple = true;
65
-
66
-    /** @skipUpgrade */
67
-    protected $schemaComponent = 'TagField';
68
-
69
-    /**
70
-     * @param string $name
71
-     * @param string $title
72
-     * @param null|DataList|array $source
73
-     * @param null|DataList $value
74
-     * @param string $titleField
75
-     */
76
-    public function __construct($name, $title = '', $source = [], $value = null, $titleField = 'Title')
77
-    {
78
-        $this->setTitleField($titleField);
79
-        parent::__construct($name, $title, $source, $value);
80
-
81
-        $this->addExtraClass('ss-tag-field');
82
-    }
83
-
84
-    /**
85
-     * @return bool
86
-     */
87
-    public function getShouldLazyLoad()
88
-    {
89
-        return $this->shouldLazyLoad;
90
-    }
91
-
92
-    /**
93
-     * @param bool $shouldLazyLoad
94
-     *
95
-     * @return static
96
-     */
97
-    public function setShouldLazyLoad($shouldLazyLoad)
98
-    {
99
-        $this->shouldLazyLoad = $shouldLazyLoad;
100
-
101
-        return $this;
102
-    }
103
-
104
-    /**
105
-     * @return int
106
-     */
107
-    public function getLazyLoadItemLimit()
108
-    {
109
-        return $this->lazyLoadItemLimit;
110
-    }
111
-
112
-    /**
113
-     * @param int $lazyLoadItemLimit
114
-     *
115
-     * @return static
116
-     */
117
-    public function setLazyLoadItemLimit($lazyLoadItemLimit)
118
-    {
119
-        $this->lazyLoadItemLimit = $lazyLoadItemLimit;
120
-
121
-        return $this;
122
-    }
123
-
124
-    /**
125
-     * @return bool
126
-     */
127
-    public function getIsMultiple()
128
-    {
129
-        return $this->isMultiple;
130
-    }
131
-
132
-    /**
133
-     * @param bool $isMultiple
134
-     *
135
-     * @return static
136
-     */
137
-    public function setIsMultiple($isMultiple)
138
-    {
139
-        $this->isMultiple = $isMultiple;
140
-
141
-        return $this;
142
-    }
143
-
144
-    /**
145
-     * @return bool
146
-     */
147
-    public function getCanCreate()
148
-    {
149
-        return $this->canCreate;
150
-    }
151
-
152
-    /**
153
-     * @param bool $canCreate
154
-     *
155
-     * @return static
156
-     */
157
-    public function setCanCreate($canCreate)
158
-    {
159
-        $this->canCreate = $canCreate;
160
-
161
-        return $this;
162
-    }
163
-
164
-    /**
165
-     * @return string
166
-     */
167
-    public function getTitleField()
168
-    {
169
-        return $this->titleField;
170
-    }
171
-
172
-    /**
173
-     * @param string $titleField
174
-     *
175
-     * @return $this
176
-     */
177
-    public function setTitleField($titleField)
178
-    {
179
-        $this->titleField = $titleField;
180
-
181
-        return $this;
182
-    }
183
-
184
-    /**
185
-     * Get the DataList source. The 4.x upgrade for SelectField::setSource starts to convert this to an array.
186
-     * If empty use getSource() for array version
187
-     *
188
-     * @return DataList
189
-     */
190
-    public function getSourceList()
191
-    {
192
-        return $this->sourceList;
193
-    }
194
-
195
-    /**
196
-     * Set the model class name for tags
197
-     *
198
-     * @param DataList $sourceList
199
-     * @return self
200
-     */
201
-    public function setSourceList($sourceList)
202
-    {
203
-        $this->sourceList = $sourceList;
204
-        return $this;
205
-    }
206
-
207
-    /**
208
-     * {@inheritdoc}
209
-     */
210
-    public function Field($properties = [])
211
-    {
212
-        $this->addExtraClass('entwine');
213
-
214
-        return $this->customise($properties)->renderWith(self::class);
215
-    }
216
-
217
-    /**
218
-     * Provide TagField data to the JSON schema for the frontend component
219
-     *
220
-     * @return array
221
-     */
222
-    public function getSchemaDataDefaults()
223
-    {
224
-        $options = $this->getOptions(true);
225
-        $schema = array_merge(
226
-            parent::getSchemaDataDefaults(),
227
-            [
228
-                'name' => $this->getName() . '[]',
229
-                'lazyLoad' => $this->getShouldLazyLoad(),
230
-                'creatable' => $this->getCanCreate(),
231
-                'multi' => $this->getIsMultiple(),
232
-                'value' => $options->count() ? $options->toNestedArray() : null,
233
-                'disabled' => $this->isDisabled() || $this->isReadonly(),
234
-            ]
235
-        );
236
-
237
-        if (!$this->getShouldLazyLoad()) {
238
-            $schema['options'] = array_values($this->getOptions()->toNestedArray());
239
-        } else {
240
-            $schema['optionUrl'] = $this->getSuggestURL();
241
-        }
242
-
243
-        return $schema;
244
-    }
245
-
246
-    /**
247
-     * @return string
248
-     */
249
-    protected function getSuggestURL()
250
-    {
251
-        return Controller::join_links($this->Link(), 'suggest');
252
-    }
253
-
254
-    /**
255
-     * @return ArrayList
256
-     */
257
-    protected function getOptions($onlySelected = false)
258
-    {
259
-        $options = ArrayList::create();
260
-        $source = $this->getSourceList();
261
-
262
-        // No source means we have no options
263
-        if (!$source) {
264
-            return ArrayList::create();
265
-        }
266
-
267
-        $dataClass = $source->dataClass();
268
-
269
-        $values = $this->Value();
270
-
271
-        // If we have no values and we only want selected options we can bail here
272
-        if (empty($values) && $onlySelected) {
273
-            return ArrayList::create();
274
-        }
275
-
276
-        // Convert an array of values into a datalist of options
277
-        if (is_array($values) && !empty($values)) {
278
-            $values = DataList::create($dataClass)
279
-                ->filter($this->getTitleField(), $values);
280
-        } else {
281
-            $values = ArrayList::create();
282
-        }
283
-
284
-        // Prep a function to parse a dataobject into an option
285
-        $addOption = function (DataObject $item) use ($options, $values) {
286
-            $titleField = $this->getTitleField();
287
-            $option = $item->$titleField;
288
-            $options->push(ArrayData::create([
289
-                'Title' => $option,
290
-                'Value' => $option,
291
-                'Selected' => (bool) $values->find('ID', $item->ID)
292
-            ]));
293
-        };
294
-
295
-        // Only parse the values if we only want the selected items in the values list (this is for lazy-loading)
296
-        if ($onlySelected) {
297
-            $values->each($addOption);
298
-            return $options;
299
-        }
300
-
301
-        $source->each($addOption);
302
-        return $options;
303
-    }
304
-
305
-    /**
306
-     * {@inheritdoc}
307
-     */
308
-    public function setValue($value, $source = null)
309
-    {
310
-        if ($source instanceof DataObject) {
311
-            $name = $this->getName();
312
-
313
-            if ($source->hasMethod($name)) {
314
-                $value = $source->$name()->column($this->getTitleField());
315
-            }
316
-        }
317
-
318
-        if (!is_array($value)) {
319
-            return parent::setValue($value);
320
-        }
321
-
322
-        return parent::setValue(array_filter($value));
323
-    }
324
-
325
-    /**
326
-     * Gets the source array if required
327
-     *
328
-     * Note: this is expensive for a SS_List
329
-     *
330
-     * @return array
331
-     */
332
-    public function getSource()
333
-    {
334
-        if (is_null($this->source)) {
335
-            $this->source = $this->getListMap($this->getSourceList());
336
-        }
337
-        return $this->source;
338
-    }
339
-
340
-    /**
341
-     * Intercept DataList source
342
-     *
343
-     * @param mixed $source
344
-     * @return $this
345
-     */
346
-    public function setSource($source)
347
-    {
348
-        // When setting a datalist force internal list to null
349
-        if ($source instanceof DataList) {
350
-            $this->source = null;
351
-            $this->setSourceList($source);
352
-        } else {
353
-            parent::setSource($source);
354
-        }
355
-        return $this;
356
-    }
357
-
358
-    /**
359
-     * @param DataObject|DataObjectInterface $record DataObject to save data into
360
-     * @throws Exception
361
-     */
362
-    public function getAttributes()
363
-    {
364
-        return array_merge(
365
-            parent::getAttributes(),
366
-            [
367
-                'name' => $this->getName() . '[]',
368
-                'style' => 'width: 100%',
369
-                'data-schema' => json_encode($this->getSchemaData()),
370
-            ]
371
-        );
372
-    }
373
-
374
-    /**
375
-     * {@inheritdoc}
376
-     */
377
-    public function saveInto(DataObjectInterface $record)
378
-    {
379
-        $name = $this->getName();
380
-        $titleField = $this->getTitleField();
381
-        $values = $this->Value();
382
-
383
-        /** @var Relation $relation */
384
-        $relation = $record->$name();
385
-        $ids = [];
386
-
387
-        if (!$values) {
388
-            $values = [];
389
-        }
390
-
391
-        if (empty($record) || empty($titleField)) {
392
-            return;
393
-        }
394
-
395
-        if (!$record->hasMethod($name)) {
396
-            throw new Exception(
397
-                sprintf("%s does not have a %s method", get_class($record), $name)
398
-            );
399
-        }
400
-
401
-        foreach ($values as $key => $value) {
402
-            // Get or create record
403
-            $record = $this->getOrCreateTag($value);
404
-            if ($record) {
405
-                $ids[] = $record->ID;
406
-                $values[$key] = $record->Title;
407
-            }
408
-        }
409
-
410
-        $relation->setByIDList(array_filter($ids));
411
-    }
412
-
413
-    /**
414
-     * Get or create tag with the given value
415
-     *
416
-     * @param  string $term
417
-     * @return DataObject|bool
418
-     */
419
-    protected function getOrCreateTag($term)
420
-    {
421
-        // Check if existing record can be found
422
-        $source = $this->getSourceList();
423
-        if (!$source) {
424
-            return false;
425
-        }
426
-
427
-        $titleField = $this->getTitleField();
428
-        $record = $source
429
-            ->filter($titleField, $term)
430
-            ->first();
431
-        if ($record) {
432
-            return $record;
433
-        }
434
-
435
-        // Create new instance if not yet saved
436
-        if ($this->getCanCreate()) {
437
-            $dataClass = $source->dataClass();
438
-            $record = Injector::inst()->create($dataClass);
439
-
440
-            if (is_array($term)) {
441
-                $term = $term['Value'];
442
-            }
443
-
444
-            $record->{$titleField} = $term;
445
-            $record->write();
446
-            if ($source instanceof SS_List) {
447
-                $source->add($record);
448
-            }
449
-            return $record;
450
-        }
451
-
452
-        return false;
453
-    }
454
-
455
-    /**
456
-     * Returns a JSON string of tags, for lazy loading.
457
-     *
458
-     * @param  HTTPRequest $request
459
-     * @return HTTPResponse
460
-     */
461
-    public function suggest(HTTPRequest $request)
462
-    {
463
-        $tags = $this->getTags($request->getVar('term'));
464
-
465
-        $response = HTTPResponse::create();
466
-        $response->addHeader('Content-Type', 'application/json');
467
-        $response->setBody(json_encode(['items' => $tags]));
468
-
469
-        return $response;
470
-    }
471
-
472
-    /**
473
-     * Returns array of arrays representing tags.
474
-     *
475
-     * @param  string $term
476
-     * @return array
477
-     */
478
-    protected function getTags($term)
479
-    {
480
-        $source = $this->getSourceList();
481
-        if (!$source) {
482
-            return [];
483
-        }
484
-
485
-        $titleField = $this->getTitleField();
486
-
487
-        $query = $source
488
-            ->filter($titleField . ':PartialMatch:nocase', $term)
489
-            ->sort($titleField)
490
-            ->limit($this->getLazyLoadItemLimit());
491
-
492
-        // Map into a distinct list
493
-        $items = [];
494
-        $titleField = $this->getTitleField();
495
-        foreach ($query->map('ID', $titleField) as $id => $title) {
496
-            $items[$title] = [
497
-                'Title' => $title,
498
-                'Value' => $title,
499
-            ];
500
-        }
501
-
502
-        return array_values($items);
503
-    }
504
-
505
-    /**
506
-     * DropdownField assumes value will be a scalar so we must
507
-     * override validate. This only applies to Silverstripe 3.2+
508
-     *
509
-     * @param Validator $validator
510
-     * @return bool
511
-     */
512
-    public function validate($validator)
513
-    {
514
-        return true;
515
-    }
516
-
517
-    /**
518
-     * Converts the field to a readonly variant.
519
-     *
520
-     * @return ReadonlyTagField
521
-     */
522
-    public function performReadonlyTransformation()
523
-    {
524
-        /** @var ReadonlyTagField $copy */
525
-        $copy = $this->castedCopy(ReadonlyTagField::class);
526
-        $copy->setSourceList($this->getSourceList());
527
-        return $copy;
528
-    }
529
-
530
-    /**
531
-     * Prevent the default, which would return "tag"
532
-     *
533
-     * @return string
534
-     */
535
-    public function Type()
536
-    {
537
-        return '';
538
-    }
539
-
540
-    public function getSchemaStateDefaults()
541
-    {
542
-        $data = parent::getSchemaStateDefaults();
543
-
544
-        // Add options to 'data'
545
-        $data['lazyLoad'] = $this->getShouldLazyLoad();
546
-        $data['multi'] = $this->getIsMultiple();
547
-        $data['optionUrl'] = $this->getSuggestURL();
548
-        $data['creatable'] = $this->getCanCreate();
549
-        $options = $this->getOptions(true);
550
-        $data['value'] = $options->count() ? $options->toNestedArray() : null;
551
-
552
-        return $data;
553
-    }
29
+	/**
30
+	 * @var array
31
+	 */
32
+	private static $allowed_actions = [
33
+		'suggest',
34
+	];
35
+
36
+	/**
37
+	 * @var bool
38
+	 */
39
+	protected $shouldLazyLoad = false;
40
+
41
+	/**
42
+	 * @var int
43
+	 */
44
+	protected $lazyLoadItemLimit = 10;
45
+
46
+	/**
47
+	 * @var bool
48
+	 */
49
+	protected $canCreate = true;
50
+
51
+	/**
52
+	 * @var string
53
+	 */
54
+	protected $titleField = 'Title';
55
+
56
+	/**
57
+	 * @var DataList
58
+	 */
59
+	protected $sourceList;
60
+
61
+	/**
62
+	 * @var bool
63
+	 */
64
+	protected $isMultiple = true;
65
+
66
+	/** @skipUpgrade */
67
+	protected $schemaComponent = 'TagField';
68
+
69
+	/**
70
+	 * @param string $name
71
+	 * @param string $title
72
+	 * @param null|DataList|array $source
73
+	 * @param null|DataList $value
74
+	 * @param string $titleField
75
+	 */
76
+	public function __construct($name, $title = '', $source = [], $value = null, $titleField = 'Title')
77
+	{
78
+		$this->setTitleField($titleField);
79
+		parent::__construct($name, $title, $source, $value);
80
+
81
+		$this->addExtraClass('ss-tag-field');
82
+	}
83
+
84
+	/**
85
+	 * @return bool
86
+	 */
87
+	public function getShouldLazyLoad()
88
+	{
89
+		return $this->shouldLazyLoad;
90
+	}
91
+
92
+	/**
93
+	 * @param bool $shouldLazyLoad
94
+	 *
95
+	 * @return static
96
+	 */
97
+	public function setShouldLazyLoad($shouldLazyLoad)
98
+	{
99
+		$this->shouldLazyLoad = $shouldLazyLoad;
100
+
101
+		return $this;
102
+	}
103
+
104
+	/**
105
+	 * @return int
106
+	 */
107
+	public function getLazyLoadItemLimit()
108
+	{
109
+		return $this->lazyLoadItemLimit;
110
+	}
111
+
112
+	/**
113
+	 * @param int $lazyLoadItemLimit
114
+	 *
115
+	 * @return static
116
+	 */
117
+	public function setLazyLoadItemLimit($lazyLoadItemLimit)
118
+	{
119
+		$this->lazyLoadItemLimit = $lazyLoadItemLimit;
120
+
121
+		return $this;
122
+	}
123
+
124
+	/**
125
+	 * @return bool
126
+	 */
127
+	public function getIsMultiple()
128
+	{
129
+		return $this->isMultiple;
130
+	}
131
+
132
+	/**
133
+	 * @param bool $isMultiple
134
+	 *
135
+	 * @return static
136
+	 */
137
+	public function setIsMultiple($isMultiple)
138
+	{
139
+		$this->isMultiple = $isMultiple;
140
+
141
+		return $this;
142
+	}
143
+
144
+	/**
145
+	 * @return bool
146
+	 */
147
+	public function getCanCreate()
148
+	{
149
+		return $this->canCreate;
150
+	}
151
+
152
+	/**
153
+	 * @param bool $canCreate
154
+	 *
155
+	 * @return static
156
+	 */
157
+	public function setCanCreate($canCreate)
158
+	{
159
+		$this->canCreate = $canCreate;
160
+
161
+		return $this;
162
+	}
163
+
164
+	/**
165
+	 * @return string
166
+	 */
167
+	public function getTitleField()
168
+	{
169
+		return $this->titleField;
170
+	}
171
+
172
+	/**
173
+	 * @param string $titleField
174
+	 *
175
+	 * @return $this
176
+	 */
177
+	public function setTitleField($titleField)
178
+	{
179
+		$this->titleField = $titleField;
180
+
181
+		return $this;
182
+	}
183
+
184
+	/**
185
+	 * Get the DataList source. The 4.x upgrade for SelectField::setSource starts to convert this to an array.
186
+	 * If empty use getSource() for array version
187
+	 *
188
+	 * @return DataList
189
+	 */
190
+	public function getSourceList()
191
+	{
192
+		return $this->sourceList;
193
+	}
194
+
195
+	/**
196
+	 * Set the model class name for tags
197
+	 *
198
+	 * @param DataList $sourceList
199
+	 * @return self
200
+	 */
201
+	public function setSourceList($sourceList)
202
+	{
203
+		$this->sourceList = $sourceList;
204
+		return $this;
205
+	}
206
+
207
+	/**
208
+	 * {@inheritdoc}
209
+	 */
210
+	public function Field($properties = [])
211
+	{
212
+		$this->addExtraClass('entwine');
213
+
214
+		return $this->customise($properties)->renderWith(self::class);
215
+	}
216
+
217
+	/**
218
+	 * Provide TagField data to the JSON schema for the frontend component
219
+	 *
220
+	 * @return array
221
+	 */
222
+	public function getSchemaDataDefaults()
223
+	{
224
+		$options = $this->getOptions(true);
225
+		$schema = array_merge(
226
+			parent::getSchemaDataDefaults(),
227
+			[
228
+				'name' => $this->getName() . '[]',
229
+				'lazyLoad' => $this->getShouldLazyLoad(),
230
+				'creatable' => $this->getCanCreate(),
231
+				'multi' => $this->getIsMultiple(),
232
+				'value' => $options->count() ? $options->toNestedArray() : null,
233
+				'disabled' => $this->isDisabled() || $this->isReadonly(),
234
+			]
235
+		);
236
+
237
+		if (!$this->getShouldLazyLoad()) {
238
+			$schema['options'] = array_values($this->getOptions()->toNestedArray());
239
+		} else {
240
+			$schema['optionUrl'] = $this->getSuggestURL();
241
+		}
242
+
243
+		return $schema;
244
+	}
245
+
246
+	/**
247
+	 * @return string
248
+	 */
249
+	protected function getSuggestURL()
250
+	{
251
+		return Controller::join_links($this->Link(), 'suggest');
252
+	}
253
+
254
+	/**
255
+	 * @return ArrayList
256
+	 */
257
+	protected function getOptions($onlySelected = false)
258
+	{
259
+		$options = ArrayList::create();
260
+		$source = $this->getSourceList();
261
+
262
+		// No source means we have no options
263
+		if (!$source) {
264
+			return ArrayList::create();
265
+		}
266
+
267
+		$dataClass = $source->dataClass();
268
+
269
+		$values = $this->Value();
270
+
271
+		// If we have no values and we only want selected options we can bail here
272
+		if (empty($values) && $onlySelected) {
273
+			return ArrayList::create();
274
+		}
275
+
276
+		// Convert an array of values into a datalist of options
277
+		if (is_array($values) && !empty($values)) {
278
+			$values = DataList::create($dataClass)
279
+				->filter($this->getTitleField(), $values);
280
+		} else {
281
+			$values = ArrayList::create();
282
+		}
283
+
284
+		// Prep a function to parse a dataobject into an option
285
+		$addOption = function (DataObject $item) use ($options, $values) {
286
+			$titleField = $this->getTitleField();
287
+			$option = $item->$titleField;
288
+			$options->push(ArrayData::create([
289
+				'Title' => $option,
290
+				'Value' => $option,
291
+				'Selected' => (bool) $values->find('ID', $item->ID)
292
+			]));
293
+		};
294
+
295
+		// Only parse the values if we only want the selected items in the values list (this is for lazy-loading)
296
+		if ($onlySelected) {
297
+			$values->each($addOption);
298
+			return $options;
299
+		}
300
+
301
+		$source->each($addOption);
302
+		return $options;
303
+	}
304
+
305
+	/**
306
+	 * {@inheritdoc}
307
+	 */
308
+	public function setValue($value, $source = null)
309
+	{
310
+		if ($source instanceof DataObject) {
311
+			$name = $this->getName();
312
+
313
+			if ($source->hasMethod($name)) {
314
+				$value = $source->$name()->column($this->getTitleField());
315
+			}
316
+		}
317
+
318
+		if (!is_array($value)) {
319
+			return parent::setValue($value);
320
+		}
321
+
322
+		return parent::setValue(array_filter($value));
323
+	}
324
+
325
+	/**
326
+	 * Gets the source array if required
327
+	 *
328
+	 * Note: this is expensive for a SS_List
329
+	 *
330
+	 * @return array
331
+	 */
332
+	public function getSource()
333
+	{
334
+		if (is_null($this->source)) {
335
+			$this->source = $this->getListMap($this->getSourceList());
336
+		}
337
+		return $this->source;
338
+	}
339
+
340
+	/**
341
+	 * Intercept DataList source
342
+	 *
343
+	 * @param mixed $source
344
+	 * @return $this
345
+	 */
346
+	public function setSource($source)
347
+	{
348
+		// When setting a datalist force internal list to null
349
+		if ($source instanceof DataList) {
350
+			$this->source = null;
351
+			$this->setSourceList($source);
352
+		} else {
353
+			parent::setSource($source);
354
+		}
355
+		return $this;
356
+	}
357
+
358
+	/**
359
+	 * @param DataObject|DataObjectInterface $record DataObject to save data into
360
+	 * @throws Exception
361
+	 */
362
+	public function getAttributes()
363
+	{
364
+		return array_merge(
365
+			parent::getAttributes(),
366
+			[
367
+				'name' => $this->getName() . '[]',
368
+				'style' => 'width: 100%',
369
+				'data-schema' => json_encode($this->getSchemaData()),
370
+			]
371
+		);
372
+	}
373
+
374
+	/**
375
+	 * {@inheritdoc}
376
+	 */
377
+	public function saveInto(DataObjectInterface $record)
378
+	{
379
+		$name = $this->getName();
380
+		$titleField = $this->getTitleField();
381
+		$values = $this->Value();
382
+
383
+		/** @var Relation $relation */
384
+		$relation = $record->$name();
385
+		$ids = [];
386
+
387
+		if (!$values) {
388
+			$values = [];
389
+		}
390
+
391
+		if (empty($record) || empty($titleField)) {
392
+			return;
393
+		}
394
+
395
+		if (!$record->hasMethod($name)) {
396
+			throw new Exception(
397
+				sprintf("%s does not have a %s method", get_class($record), $name)
398
+			);
399
+		}
400
+
401
+		foreach ($values as $key => $value) {
402
+			// Get or create record
403
+			$record = $this->getOrCreateTag($value);
404
+			if ($record) {
405
+				$ids[] = $record->ID;
406
+				$values[$key] = $record->Title;
407
+			}
408
+		}
409
+
410
+		$relation->setByIDList(array_filter($ids));
411
+	}
412
+
413
+	/**
414
+	 * Get or create tag with the given value
415
+	 *
416
+	 * @param  string $term
417
+	 * @return DataObject|bool
418
+	 */
419
+	protected function getOrCreateTag($term)
420
+	{
421
+		// Check if existing record can be found
422
+		$source = $this->getSourceList();
423
+		if (!$source) {
424
+			return false;
425
+		}
426
+
427
+		$titleField = $this->getTitleField();
428
+		$record = $source
429
+			->filter($titleField, $term)
430
+			->first();
431
+		if ($record) {
432
+			return $record;
433
+		}
434
+
435
+		// Create new instance if not yet saved
436
+		if ($this->getCanCreate()) {
437
+			$dataClass = $source->dataClass();
438
+			$record = Injector::inst()->create($dataClass);
439
+
440
+			if (is_array($term)) {
441
+				$term = $term['Value'];
442
+			}
443
+
444
+			$record->{$titleField} = $term;
445
+			$record->write();
446
+			if ($source instanceof SS_List) {
447
+				$source->add($record);
448
+			}
449
+			return $record;
450
+		}
451
+
452
+		return false;
453
+	}
454
+
455
+	/**
456
+	 * Returns a JSON string of tags, for lazy loading.
457
+	 *
458
+	 * @param  HTTPRequest $request
459
+	 * @return HTTPResponse
460
+	 */
461
+	public function suggest(HTTPRequest $request)
462
+	{
463
+		$tags = $this->getTags($request->getVar('term'));
464
+
465
+		$response = HTTPResponse::create();
466
+		$response->addHeader('Content-Type', 'application/json');
467
+		$response->setBody(json_encode(['items' => $tags]));
468
+
469
+		return $response;
470
+	}
471
+
472
+	/**
473
+	 * Returns array of arrays representing tags.
474
+	 *
475
+	 * @param  string $term
476
+	 * @return array
477
+	 */
478
+	protected function getTags($term)
479
+	{
480
+		$source = $this->getSourceList();
481
+		if (!$source) {
482
+			return [];
483
+		}
484
+
485
+		$titleField = $this->getTitleField();
486
+
487
+		$query = $source
488
+			->filter($titleField . ':PartialMatch:nocase', $term)
489
+			->sort($titleField)
490
+			->limit($this->getLazyLoadItemLimit());
491
+
492
+		// Map into a distinct list
493
+		$items = [];
494
+		$titleField = $this->getTitleField();
495
+		foreach ($query->map('ID', $titleField) as $id => $title) {
496
+			$items[$title] = [
497
+				'Title' => $title,
498
+				'Value' => $title,
499
+			];
500
+		}
501
+
502
+		return array_values($items);
503
+	}
504
+
505
+	/**
506
+	 * DropdownField assumes value will be a scalar so we must
507
+	 * override validate. This only applies to Silverstripe 3.2+
508
+	 *
509
+	 * @param Validator $validator
510
+	 * @return bool
511
+	 */
512
+	public function validate($validator)
513
+	{
514
+		return true;
515
+	}
516
+
517
+	/**
518
+	 * Converts the field to a readonly variant.
519
+	 *
520
+	 * @return ReadonlyTagField
521
+	 */
522
+	public function performReadonlyTransformation()
523
+	{
524
+		/** @var ReadonlyTagField $copy */
525
+		$copy = $this->castedCopy(ReadonlyTagField::class);
526
+		$copy->setSourceList($this->getSourceList());
527
+		return $copy;
528
+	}
529
+
530
+	/**
531
+	 * Prevent the default, which would return "tag"
532
+	 *
533
+	 * @return string
534
+	 */
535
+	public function Type()
536
+	{
537
+		return '';
538
+	}
539
+
540
+	public function getSchemaStateDefaults()
541
+	{
542
+		$data = parent::getSchemaStateDefaults();
543
+
544
+		// Add options to 'data'
545
+		$data['lazyLoad'] = $this->getShouldLazyLoad();
546
+		$data['multi'] = $this->getIsMultiple();
547
+		$data['optionUrl'] = $this->getSuggestURL();
548
+		$data['creatable'] = $this->getCanCreate();
549
+		$options = $this->getOptions(true);
550
+		$data['value'] = $options->count() ? $options->toNestedArray() : null;
551
+
552
+		return $data;
553
+	}
554 554
 }
Please login to merge, or discard this patch.