Field::with()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 10
1
<?php
2
3
4
namespace Riclep\Storyblok;
5
6
use Exception;
7
use Illuminate\Support\Str;
8
use Riclep\Storyblok\Traits\HasMeta;
9
10
abstract class Field
11
{
12
	use HasMeta;
13
14
	/**
15
	 * Key/value pairs of additional content you want the
16
	 * field to have access to. Pass anything you like
17
	 *
18
	 * @var array
19
	 */
20
	public array $with;
21
22
	/**
23
	 * Creates the new field taking it’s content and a reference
24
	 * to the parent Block
25
	 *
26
	 * @param $content
27
	 * @param $block
28
	 */
29
	public function __construct(protected $content, protected $block)
30
	{
31
		if (method_exists($this, 'init')) {
32
			$this->init();
33
		}
34
	}
35
36
	/**
37
	 * Returns the content of the Field
38
	 *
39
	 * @return array|string
40
	 */
41
	public function content(): mixed
42
	{
43
		return $this->content;
44
	}
45
46
	/**
47
	 * Returns the Block this Field belongs to
48
	 *
49
	 * @return Block
50
	 */
51
	public function block(): Block
52
	{
53
		return $this->block;
54
	}
55
56
	/**
57
	 * Checks if the requested key is in the Field’s content
58
	 *
59
	 * @param $key
60
	 * @return bool
61
	 */
62
	public function has($key): bool
63
	{
64
		return array_key_exists($key, $this->content);
65
	}
66
67
68
	/**
69
	 * Allows key/value pairs to be passed into the Field such as CSS
70
	 * classes when rendering __toString or another content.
71
	 * Example: {{ $field->with(['classes' => 'my-class']) }}
72
	 *
73
	 * @param $with
74
	 * @return Field
75
	 */
76
	public function with($with): Field
77
	{
78
		$this->with = $with;
79
80
		return $this;
81
	}
82
83
	/**
84
	 * Magic accessor to pull content from the content. Works just like
85
	 * Laravel’s model accessors.
86
	 *
87
	 * @param $key
88
	 * @return false|mixed|string
89
	 */
90
	public function __get($key) {
91
		$accessor = 'get' . Str::studly($key) . 'Attribute';
92
93
		if (method_exists($this, $accessor)) {
94
			return $this->$accessor();
95
		}
96
97
		try {
98
			if ($this->has($key)) {
99
				return $this->content[$key];
100
			}
101
102
			return false;
103
		} catch (Exception $e) {
104
			return 'Caught exception: ' .  $e->getMessage();
105
		}
106
	}
107
108
	/**
109
	 * Prints the Field as a string
110
	 *
111
	 * @return string
112
	 */
113
	abstract public function __toString(): string;
114
}