| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentForm\App\Services\FormBuilder; |
| 4 |
|
| 5 |
use Closure; |
| 6 |
|
| 7 |
class Components implements \JsonSerializable |
| 8 |
{ |
| 9 |
/** |
| 10 |
* $items [Components list] |
| 11 |
* @var array |
| 12 |
*/ |
| 13 |
protected $items = array(); |
| 14 |
|
| 15 |
/** |
| 16 |
* Build the object instance |
| 17 |
* @param array $items |
| 18 |
*/ |
| 19 |
public function __construct(array $items) |
| 20 |
{ |
| 21 |
$this->items = $items; |
| 22 |
} |
| 23 |
|
| 24 |
/** |
| 25 |
* Add a component into list [$items] |
| 26 |
* @param string $name |
| 27 |
* @param array $component |
| 28 |
* @param string $group ['general'|'advanced'] |
| 29 |
* @return $this |
| 30 |
*/ |
| 31 |
public function add($name, array $component, $group) |
| 32 |
{ |
| 33 |
if (isset($this->items[$group])) { |
| 34 |
$this->items[$group][$name] = $component; |
| 35 |
} |
| 36 |
|
| 37 |
return $this; |
| 38 |
} |
| 39 |
|
| 40 |
/** |
| 41 |
* Remove a component from the list [$items] |
| 42 |
* @param string $name |
| 43 |
* @param string $group ['general'|'advanced'] |
| 44 |
* @return $this |
| 45 |
*/ |
| 46 |
public function remove($name, $group) |
| 47 |
{ |
| 48 |
if (isset($this->items[$group])) { |
| 49 |
unset($this->items[$group][$name]); |
| 50 |
} |
| 51 |
|
| 52 |
return $this; |
| 53 |
} |
| 54 |
|
| 55 |
/** |
| 56 |
* Modify an existing component |
| 57 |
* @param string $name |
| 58 |
* @param Closure $callback [to modify the component within] |
| 59 |
* @param string $group |
| 60 |
* @return $this |
| 61 |
*/ |
| 62 |
public function update($name, Closure $callback, $group) |
| 63 |
{ |
| 64 |
$element = $callback($this->items[$group][$name]); |
| 65 |
$this->items[$group][$name] = $element; |
| 66 |
return $this; |
| 67 |
} |
| 68 |
|
| 69 |
/** |
| 70 |
* Sort the components in list [$items] |
| 71 |
* @param string $sortBy [key to sort by] |
| 72 |
* @return $this |
| 73 |
*/ |
| 74 |
public function sort($sortBy = 'index') |
| 75 |
{ |
| 76 |
foreach ($this->items as $group => &$items) { |
| 77 |
usort($items, function($a, $b) { |
| 78 |
if (@$a['index'] == @$b['index']) { |
| 79 |
return 0; |
| 80 |
} |
| 81 |
return @$a['index'] < @$b['index'] ? -1 : 1; |
| 82 |
}); |
| 83 |
} |
| 84 |
|
| 85 |
return $this; |
| 86 |
} |
| 87 |
|
| 88 |
/** |
| 89 |
* Return array [$items] |
| 90 |
* @return array |
| 91 |
*/ |
| 92 |
public function toArray() |
| 93 |
{ |
| 94 |
return $this->items; |
| 95 |
} |
| 96 |
|
| 97 |
/** |
| 98 |
* Return array [$items] |
| 99 |
* @return array |
| 100 |
*/ |
| 101 |
public function jsonSerialize() |
| 102 |
{ |
| 103 |
return $this->toArray(); |
| 104 |
} |
| 105 |
|
| 106 |
/** |
| 107 |
* Getter to hook proxy call |
| 108 |
* @return mixed |
| 109 |
*/ |
| 110 |
public function __get($key) |
| 111 |
{ |
| 112 |
if (in_array($key, ['general', 'advanced'])) { |
| 113 |
return new GroupSetterProxy($this, $key); |
| 114 |
} |
| 115 |
} |
| 116 |
} |
| 117 |
|