| 1 |
<?php |
| 2 |
|
| 3 |
namespace Give\Framework\FieldsAPI\Concerns; |
| 4 |
|
| 5 |
use Give\Framework\FieldsAPI\Contracts\Collection; |
| 6 |
use Give\Framework\FieldsAPI\Contracts\Node; |
| 7 |
use Give\Framework\FieldsAPI\Field; |
| 8 |
|
| 9 |
trait HasNodes |
| 10 |
{ |
| 11 |
/** |
| 12 |
* @var Node[] |
| 13 |
*/ |
| 14 |
protected $nodes = []; |
| 15 |
|
| 16 |
/** |
| 17 |
* @inheritdoc |
| 18 |
*/ |
| 19 |
public function getNodeIndexByName(string $name) |
| 20 |
{ |
| 21 |
foreach ($this->nodes as $index => $node) { |
| 22 |
if ($node->getName() === $name) { |
| 23 |
return $index; |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
return null; |
| 28 |
} |
| 29 |
|
| 30 |
/** |
| 31 |
* @inheritdoc |
| 32 |
* |
| 33 |
* @return Node|null |
| 34 |
*/ |
| 35 |
public function getNodeByName(string $name) |
| 36 |
{ |
| 37 |
foreach ($this->nodes as $node) { |
| 38 |
if ($node->getName() === $name) { |
| 39 |
return $node; |
| 40 |
} |
| 41 |
if ($node instanceof Collection) { |
| 42 |
$nestedNode = $node->getNodeByName($name); |
| 43 |
if ($nestedNode !== null) { |
| 44 |
return $nestedNode; |
| 45 |
} |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
return null; |
| 50 |
} |
| 51 |
|
| 52 |
/** |
| 53 |
* @inheritdoc |
| 54 |
*/ |
| 55 |
public function all(): array |
| 56 |
{ |
| 57 |
return $this->nodes; |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* @inheritdoc |
| 62 |
* |
| 63 |
* @return Field[] |
| 64 |
*/ |
| 65 |
public function getFields(): array |
| 66 |
{ |
| 67 |
$fields = []; |
| 68 |
|
| 69 |
foreach ($this->nodes as $node) { |
| 70 |
if ($node instanceof Field) { |
| 71 |
$fields[] = $node; |
| 72 |
} elseif ($node instanceof Collection) { |
| 73 |
$nestedFields = $node->getFields(); |
| 74 |
|
| 75 |
foreach($nestedFields as $field) { |
| 76 |
$fields[] = $field; |
| 77 |
} |
| 78 |
} |
| 79 |
} |
| 80 |
|
| 81 |
return $fields; |
| 82 |
} |
| 83 |
|
| 84 |
/** |
| 85 |
* @inheritdoc |
| 86 |
*/ |
| 87 |
public function count(): int |
| 88 |
{ |
| 89 |
return count($this->nodes); |
| 90 |
} |
| 91 |
|
| 92 |
} |
| 93 |
|