Completed
Push — master ( 83f885...d80ec4 )
by Richard
16s queued 11s
created

Block::isLegacyImageField()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 4
rs 10
1
<?php
2
3
4
namespace Riclep\Storyblok;
5
6
use Illuminate\Support\Collection;
7
use Illuminate\Support\Str;
8
use Illuminate\View\View;
9
use Riclep\Storyblok\Exceptions\UnableToRenderException;
10
use Riclep\Storyblok\Fields\Asset;
11
use Riclep\Storyblok\Fields\Image;
12
use Riclep\Storyblok\Fields\MultiAsset;
13
use Riclep\Storyblok\Fields\RichText;
14
use Riclep\Storyblok\Fields\Table;
15
use Riclep\Storyblok\Traits\CssClasses;
16
use Riclep\Storyblok\Traits\HasChildClasses;
17
use Riclep\Storyblok\Traits\HasMeta;
18
19
class Block implements \IteratorAggregate
20
{
21
	use CssClasses;
22
	use HasChildClasses;
23
	use HasMeta;
24
25
	/**
26
	 * @var bool resolve UUID relations automatically
27
	 */
28
	public $_autoResolveRelations = false;
29
30
	/**
31
	 * @var array list of field names containing relations to resolve
32
	 */
33
	public $_resolveRelations = [];
34
35
	/**
36
	 * @var array the path of nested components
37
	 */
38
	public $_componentPath = [];
39
40
	/**
41
	 * @var array the path of nested components
42
	 */
43
	protected $_casts = [];
44
45
	/**
46
	 * @var Collection all the fields for the Block
47
	 */
48
	private $_fields;
49
50
	/**
51
	 * @var Page|Block reference to the parent Block or Page
52
	 */
53
	private $_parent;
54
55
	/**
56
	 * Takes the Block’s content and a reference to the parent
57
	 * @param $content
58
	 * @param $parent
59
	 */
60
	public function __construct($content, $parent = null)
61
	{
62
		$this->_parent = $parent;
63
64
		$this->preprocess($content);
65
66
		if ($parent) {
67
			$this->_componentPath = array_merge($parent->_componentPath, [Str::lower($this->meta()['component'])]);
68
		}
69
70
		$this->processFields();
71
72
		// run automatic traits - methods matching initTraitClassName()
73
		foreach (class_uses_recursive($this) as $trait) {
74
			if (method_exists($this, $method = 'init' . class_basename($trait))) {
75
				$this->{$method}();
76
			}
77
		}
78
	}
79
80
	/**
81
	 * Returns the containing every field of content
82
	 *
83
	 * @return Collection
84
	 */
85
	public function content() {
86
		return $this->_fields;
87
	}
88
89
	/**
90
	 * Checks if the fields contain the specified key
91
	 *
92
	 * @param $key
93
	 * @return bool
94
	 */
95
	public function has($key) {
96
		return $this->_fields->has($key);
97
	}
98
99
	/**
100
	 * Returns the parent Block
101
	 *
102
	 * @return Block
103
	 */
104
	public function parent() {
105
		return $this->_parent;
106
	}
107
108
	/**
109
	 * Returns the page this Block belongs to
110
	 *
111
	 * @return Block
112
	 */
113
	public function page() {
114
		if ($this->parent() instanceof Page) {
0 ignored issues
show
introduced by
$this->parent() is never a sub-type of Riclep\Storyblok\Page.
Loading history...
115
			return $this->parent();
116
		}
117
118
		return $this->parent()->page();
119
	}
120
121
	/**
122
	 * Returns the first matching view, passing it the fields
123
	 *
124
	 * @return View
125
	 * @throws UnableToRenderException
126
	 */
127
	public function render() {
128
		try {
129
			return view()->first($this->views(), ['block' => $this]);
130
		} catch (\Exception $exception) {
131
			throw new UnableToRenderException('None of the views in the given array exist.', $this);
132
		}
133
	}
134
135
	/**
136
	 * Returns an array of possible views for the current Block based on
137
	 * it’s $componentPath match the component prefixed by each of it’s
138
	 * ancestors in turn, starting with the closest, for example:
139
	 *
140
	 * $componentPath = ['page', 'parent', 'child', 'this_block'];
141
	 *
142
	 * Becomes a list of possible views like so:
143
	 * ['child.this_block', 'parent.this_block', 'page.this_block'];
144
	 *
145
	 * Override this method with your custom implementation for
146
	 * ultimate control
147
	 *
148
	 * @return array
149
	 */
150
	public function views() {
151
		$compontentPath = $this->_componentPath;
152
		array_pop($compontentPath);
153
154
		$views = array_map(function($path) {
155
			return config('storyblok.view_path') . 'blocks.' . $path . '.' . $this->component();
156
		}, $compontentPath);
157
158
		$views = array_reverse($views);
159
160
		$views[] = config('storyblok.view_path') . 'blocks.' . $this->component();
161
162
		return $views;
163
	}
164
165
	/**
166
	 * Returns a component X generations previous
167
	 *
168
	 * @param $generation int
169
	 * @return mixed
170
	 */
171
	public function ancestorComponentName($generation)
172
	{
173
		return $this->_componentPath[count($this->_componentPath) - ($generation + 1)];
174
	}
175
176
	/**
177
	 * Checks if the current component is a child of another
178
	 *
179
	 * @param $parent string
180
	 * @return bool
181
	 */
182
	public function isChildOf($parent)
183
	{
184
		return $this->_componentPath[count($this->_componentPath) - 2] === $parent;
185
	}
186
187
	/**
188
	 * Checks if the component is an ancestor of another
189
	 *
190
	 * @param $parent string
191
	 * @return bool
192
	 */
193
	public function isAncestorOf($parent)
194
	{
195
		return in_array($parent, $this->parent()->_componentPath);
196
	}
197
198
	/**
199
	 * Returns the current Block’s component name from Storyblok
200
	 *
201
	 * @return string
202
	 */
203
	public function component() {
204
		return $this->_meta['component'];
205
	}
206
207
208
	/**
209
	 * Returns the HTML comment required for making this Block clickable in
210
	 * Storyblok’s visual editor. Don’t forget to set comments to true in
211
	 * your Vue.js app configuration.
212
	 *
213
	 * @return string
214
	 */
215
	public function editorLink() {
216
		if (array_key_exists('_editable', $this->_meta) && config('storyblok.edit_mode')) {
217
			return $this->_meta['_editable'];
218
		}
219
220
		return '';
221
	}
222
223
224
	/**
225
	 * Magic accessor to pull content from the _fields collection. Works just like
226
	 * Laravel’s model accessors. Matches public methods with the follow naming
227
	 * convention getSomeFieldAttribute() - called via $block->some_field
228
	 *
229
	 * @param $key
230
	 * @return null|string
231
	 */
232
	public function __get($key) {
233
		$accessor = 'get' . Str::studly($key) . 'Attribute';
234
235
		if (method_exists($this, $accessor)) {
236
			return $this->$accessor();
237
		}
238
239
		if ($this->has($key)) {
240
			return $this->_fields[$key];
241
		}
242
243
		return null;
244
	}
245
246
	/**
247
	 * Loops over every field to get te ball rolling
248
	 */
249
	private function processFields() {
250
		$this->_fields->transform(function ($field, $key) {
251
			return $this->getFieldType($field, $key);
252
		});
253
	}
254
255
	/**
256
	 * Converts fields into Field Classes based on various properties of their content
257
	 *
258
	 * @param $field
259
	 * @param $key
260
	 * @return array|Collection|mixed|Asset|Image|MultiAsset|RichText|Table
261
	 * @throws \Storyblok\ApiException
262
	 */
263
	private function getFieldType($field, $key) {
264
		// TODO process old asset fields
265
		// TODO option to convert all text fields to a class - single or multiline?
266
267
		// does the Block assign any $_casts? This is key (field) => value (class)
268
		if (property_exists($this, '_casts') && array_key_exists($key, $this->_casts)) {
269
			return new $this->_casts[$key]($field, $this);
270
		}
271
272
		// find Fields specific to this Block matching: BlockNameFieldName
273
		if ($class = $this->getChildClassName('Field', $this->component() . '_' . $key)) {
274
			return new $class($field, $this);
275
		}
276
277
		// auto-match Field classes
278
		if ($class = $this->getChildClassName('Field', $key)) {
279
			return new $class($field, $this);
280
		}
281
282
		// single item relations
283
		if (Str::isUuid($field) && ($this->_autoResolveRelations || in_array($key, $this->_resolveRelations))) {
284
			return $this->getRelation(new RequestStory(), $field);
285
		}
286
287
		// complex fields
288
		if (is_array($field) && !empty($field)) {
289
			return $this->arrayFieldTypes($field, $key);
290
		}
291
292
		// legacy image fields
293
		if($this->isLegacyImageField($field)) {
294
			return new Image($field, $this);
295
		}
296
297
		// strings or anything else - do nothing
298
		return $field;
299
	}
300
301
302
	/**
303
	 * Check if given string is an legacy image field
304
	 *
305
	 * @param  $filename
306
	 * @return boolean
307
	 */
308
	public function isLegacyImageField($filename){
309
		$allowed_extentions = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
310
311
		return is_string($filename) && Str::of( $filename )->lower()->endsWith( $allowed_extentions );
312
	}
313
314
	/**
315
	 * When the field is an array we need to do more processing
316
	 *
317
	 * @param $field
318
	 * @return Collection|mixed|Asset|Image|MultiAsset|RichText|Table
319
	 */
320
	private function arrayFieldTypes($field, $key) {
321
		// match link fields
322
		if (array_key_exists('linktype', $field)) {
323
			$class = 'Riclep\Storyblok\Fields\\' . Str::studly($field['linktype']) . 'Link';
324
325
			return new $class($field, $this);
326
		}
327
328
		// match rich-text fields
329
		if (array_key_exists('type', $field) && $field['type'] === 'doc') {
330
			return new RichText($field, $this);
331
		}
332
333
		// match asset fields - detecting raster images
334
		if (array_key_exists('fieldtype', $field) && $field['fieldtype'] === 'asset') {
335
336
			// legacy image fields
337
			if($this->isLegacyImageField($field['filename'])) {
338
				return new Image($field, $this);
339
			}
340
341
			return new Asset($field, $this);
342
		}
343
344
		// match table fields
345
		if (array_key_exists('fieldtype', $field) && $field['fieldtype'] === 'table') {
346
			return new Table($field, $this);
347
		}
348
349
		if (array_key_exists(0, $field)) {
350
			// it’s an array of relations - request them if we’re auto or manual resolving
351
			if (Str::isUuid($field[0])) {
352
				if ($this->_autoResolveRelations || in_array($key, $this->_resolveRelations)) {
353
					return collect($field)->transform(function ($relation) {
354
						return $this->getRelation(new RequestStory(), $relation);
355
					});
356
				}
357
			}
358
359
			// has child items - single option, multi option and Blocks fields
360
			if (is_array($field[0])) {
361
				// resolved relationships - entire story is returned, we just want the content and a few meta items
362
				if (array_key_exists('content', $field[0])) {
363
					return collect($field)->transform(function ($relation) {
364
						$class = $this->getChildClassName('Block', $relation['content']['component']);
365
						$relationClass = new $class($relation['content'], $this);
366
367
						$relationClass->addMeta([
368
							'name' => $relation['name'],
369
							'published_at' => $relation['published_at'],
370
							'full_slug' => $relation['full_slug'],
371
						]);
372
373
						return $relationClass;
374
					});
375
				}
376
377
				// this field holds blocks!
378
				if (array_key_exists('component', $field[0])) {
379
					return collect($field)->transform(function ($block) {
380
						$class = $this->getChildClassName('Block', $block['component']);
381
382
						return new $class($block, $this);
383
					});
384
				}
385
386
				// multi assets
387
				if (array_key_exists('filename', $field[0])) {
388
					return new MultiAsset($field, $this);
389
				}
390
			}
391
		}
392
393
		// just return the array
394
		return $field;
395
	}
396
397
	/**
398
	 * Storyblok returns fields and other meta content at the same level so
399
	 * let’s do a little tidying up first
400
	 *
401
	 * @param $content
402
	 */
403
	private function preprocess($content) {
404
		$this->_fields = collect(array_diff_key($content, array_flip(['_editable', '_uid', 'component'])));
405
406
		// remove non-content keys
407
		$this->_meta = array_intersect_key($content, array_flip(['_editable', '_uid', 'component']));
408
	}
409
410
	/**
411
	 * Returns cotent of the field. In the visual editor it returns a VueJS template tag
412
	 *
413
	 * @param $field
414
	 * @return string
415
	 */
416
	public function liveField($field) {
417
		if (config('storyblok.edit_mode')) {
418
			return '{{ Object.keys(laravelStoryblokLive).length ? laravelStoryblokLive.uuid_' . str_replace('-', '_', $this->uuid()) . '.' . $field . ' : null }}';
419
		}
420
421
		return $this->{$field};
422
	}
423
424
	/**
425
	 * Flattens all the fields in an array keyed by their UUID to make linking the JS simple
426
	 */
427
	public function flatten() {
428
		$this->content()->each(function ($item, $key) {
429
430
			if ($item instanceof Collection) {
431
				$item->each(function ($item) {
432
					$item->flatten();
433
				});
434
			} elseif ($item instanceof Field) {
435
				$this->page()->liveContent['uuid_' . str_replace('-', '_', $this->uuid())][$key] = (string) $item;
0 ignored issues
show
Bug Best Practice introduced by
The property liveContent does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
436
			} else {
437
				$this->page()->liveContent['uuid_' . str_replace('-', '_', $this->uuid())][$key] = $item;
438
			}
439
		});
440
	}
441
442
	/**
443
	 * Let’s up loop over the fields in Blade without needing to
444
	 * delve deep into the content collection
445
	 *
446
	 * @return \Traversable
447
	 */
448
	public function getIterator() {
449
		return $this->_fields;
450
	}
451
452
	protected function getRelation(RequestStory $request, $relation) {
453
		$response = $request->get($relation);
454
455
		$class = $this->getChildClassName('Block', $response['content']['component']);
456
		$relationClass = new $class($response['content'], $this);
457
458
		$relationClass->addMeta([
459
			'name' => $response['name'],
460
			'published_at' => $response['published_at'],
461
			'full_slug' => $response['full_slug'],
462
		]);
463
464
		return $relationClass;
465
	}
466
}