julienmonnerie/kirby/src/Cms/Fieldsets.php

114 lines
2.5 KiB
PHP
Raw Normal View History

2022-06-17 17:51:59 +02:00
<?php
namespace Kirby\Cms;
use Closure;
use Kirby\Toolkit\A;
use Kirby\Toolkit\I18n;
use Kirby\Toolkit\Str;
/**
* A collection of fieldsets
* @since 3.5.0
*
* @package Kirby Cms
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://getkirby.com/license
*/
class Fieldsets extends Items
{
2022-12-19 14:56:05 +01:00
public const ITEM_CLASS = Fieldset::class;
2022-08-31 15:02:43 +02:00
2023-06-01 16:54:20 +02:00
/**
* All registered fieldsets methods
*/
2025-04-21 18:57:21 +02:00
public static array $methods = [];
2023-06-01 16:54:20 +02:00
2025-04-21 18:57:21 +02:00
protected static function createFieldsets(array $params): array
2022-08-31 15:02:43 +02:00
{
$fieldsets = [];
2025-04-21 18:57:21 +02:00
$groups = [];
2022-08-31 15:02:43 +02:00
foreach ($params as $type => $fieldset) {
if (is_int($type) === true && is_string($fieldset)) {
$type = $fieldset;
$fieldset = 'blocks/' . $type;
}
if ($fieldset === false) {
continue;
}
if ($fieldset === true) {
$fieldset = 'blocks/' . $type;
}
$fieldset = Blueprint::extend($fieldset);
// make sure the type is always set
$fieldset['type'] ??= $type;
// extract groups
if ($fieldset['type'] === 'group') {
$result = static::createFieldsets($fieldset['fieldsets'] ?? []);
$fieldsets = array_merge($fieldsets, $result['fieldsets']);
$label = $fieldset['label'] ?? Str::ucfirst($type);
$groups[$type] = [
'label' => I18n::translate($label, $label),
'name' => $type,
'open' => $fieldset['open'] ?? true,
'sets' => array_column($result['fieldsets'], 'type'),
];
} else {
$fieldsets[$fieldset['type']] = $fieldset;
}
}
return [
'fieldsets' => $fieldsets,
'groups' => $groups
];
}
2025-04-21 18:57:21 +02:00
public static function factory(
array|null $items = null,
array $params = []
): static {
2022-08-31 15:02:43 +02:00
$items ??= App::instance()->option('blocks.fieldsets', [
'code' => 'blocks/code',
'gallery' => 'blocks/gallery',
'heading' => 'blocks/heading',
'image' => 'blocks/image',
'line' => 'blocks/line',
'list' => 'blocks/list',
'markdown' => 'blocks/markdown',
'quote' => 'blocks/quote',
'text' => 'blocks/text',
'video' => 'blocks/video',
]);
$result = static::createFieldsets($items);
2025-04-21 18:57:21 +02:00
return parent::factory(
$result['fieldsets'],
['groups' => $result['groups']] + $params
);
2022-08-31 15:02:43 +02:00
}
public function groups(): array
{
return $this->options['groups'] ?? [];
}
2022-12-19 14:56:05 +01:00
public function toArray(Closure|null $map = null): array
2022-08-31 15:02:43 +02:00
{
return A::map(
$this->data,
$map ?? fn ($fieldset) => $fieldset->toArray()
);
}
2022-06-17 17:51:59 +02:00
}