1
0
This commit is contained in:
Philip Wagner
2024-08-31 10:01:49 +02:00
commit 78b6c0d381
1169 changed files with 235103 additions and 0 deletions

510
kirby/src/Form/Field.php Normal file
View File

@@ -0,0 +1,510 @@
<?php
namespace Kirby\Form;
use Closure;
use Exception;
use Kirby\Cms\App;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Toolkit\A;
use Kirby\Toolkit\Component;
use Kirby\Toolkit\I18n;
use Kirby\Toolkit\V;
/**
* Form Field object that takes a Vue component style
* array of properties and methods and converts them
* to a usable field option array for the API.
*
* @package Kirby Form
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*/
class Field extends Component
{
/**
* An array of all found errors
*/
protected array|null $errors = null;
/**
* Parent collection with all fields of the current form
*/
protected Fields|null $formFields;
/**
* Registry for all component mixins
*/
public static array $mixins = [];
/**
* Registry for all component types
*/
public static array $types = [];
/**
* @throws \Kirby\Exception\InvalidArgumentException
*/
public function __construct(
string $type,
array $attrs = [],
Fields|null $formFields = null
) {
if (isset(static::$types[$type]) === false) {
throw new InvalidArgumentException([
'key' => 'field.type.missing',
'data' => ['name' => $attrs['name'] ?? '-', 'type' => $type]
]);
}
if (isset($attrs['model']) === false) {
throw new InvalidArgumentException('Field requires a model');
}
$this->formFields = $formFields;
// use the type as fallback for the name
$attrs['name'] ??= $type;
$attrs['type'] = $type;
parent::__construct($type, $attrs);
}
/**
* Returns field api call
*/
public function api(): mixed
{
if (
isset($this->options['api']) === true &&
$this->options['api'] instanceof Closure
) {
return $this->options['api']->call($this);
}
return null;
}
/**
* Returns field data
*/
public function data(bool $default = false): mixed
{
$save = $this->options['save'] ?? true;
if ($default === true && $this->isEmpty($this->value)) {
$value = $this->default();
} else {
$value = $this->value;
}
if ($save === false) {
return null;
}
if ($save instanceof Closure) {
return $save->call($this, $value);
}
return $value;
}
/**
* Default props and computed of the field
*/
public static function defaults(): array
{
return [
'props' => [
/**
* Optional text that will be shown after the input
*/
'after' => function ($after = null) {
return I18n::translate($after, $after);
},
/**
* Sets the focus on this field when the form loads. Only the first field with this label gets
*/
'autofocus' => function (bool $autofocus = null): bool {
return $autofocus ?? false;
},
/**
* Optional text that will be shown before the input
*/
'before' => function ($before = null) {
return I18n::translate($before, $before);
},
/**
* Default value for the field, which will be used when a page/file/user is created
*/
'default' => function ($default = null) {
return $default;
},
/**
* If `true`, the field is no longer editable and will not be saved
*/
'disabled' => function (bool $disabled = null): bool {
return $disabled ?? false;
},
/**
* Optional help text below the field
*/
'help' => function ($help = null) {
return I18n::translate($help, $help);
},
/**
* Optional icon that will be shown at the end of the field
*/
'icon' => function (string $icon = null) {
return $icon;
},
/**
* The field label can be set as string or associative array with translations
*/
'label' => function ($label = null) {
return I18n::translate($label, $label);
},
/**
* Optional placeholder value that will be shown when the field is empty
*/
'placeholder' => function ($placeholder = null) {
return I18n::translate($placeholder, $placeholder);
},
/**
* If `true`, the field has to be filled in correctly to be saved.
*/
'required' => function (bool $required = null): bool {
return $required ?? false;
},
/**
* If `false`, the field will be disabled in non-default languages and cannot be translated. This is only relevant in multi-language setups.
*/
'translate' => function (bool $translate = true): bool {
return $translate;
},
/**
* Conditions when the field will be shown (since 3.1.0)
*/
'when' => function ($when = null) {
return $when;
},
/**
* The width of the field in the field grid. Available widths: `1/1`, `1/2`, `1/3`, `1/4`, `2/3`, `3/4`
*/
'width' => function (string $width = '1/1') {
return $width;
},
'value' => function ($value = null) {
return $value;
}
],
'computed' => [
'after' => function () {
/** @var \Kirby\Form\Field $this */
if ($this->after !== null) {
return $this->model()->toString($this->after);
}
},
'before' => function () {
/** @var \Kirby\Form\Field $this */
if ($this->before !== null) {
return $this->model()->toString($this->before);
}
},
'default' => function () {
/** @var \Kirby\Form\Field $this */
if ($this->default === null) {
return;
}
if (is_string($this->default) === false) {
return $this->default;
}
return $this->model()->toString($this->default);
},
'help' => function () {
/** @var \Kirby\Form\Field $this */
if ($this->help) {
$help = $this->model()->toSafeString($this->help);
$help = $this->kirby()->kirbytext($help);
return $help;
}
},
'label' => function () {
/** @var \Kirby\Form\Field $this */
if ($this->label !== null) {
return $this->model()->toString($this->label);
}
},
'placeholder' => function () {
/** @var \Kirby\Form\Field $this */
if ($this->placeholder !== null) {
return $this->model()->toString($this->placeholder);
}
}
]
];
}
/**
* Returns optional dialog routes for the field
*/
public function dialogs(): array
{
if (
isset($this->options['dialogs']) === true &&
$this->options['dialogs'] instanceof Closure
) {
return $this->options['dialogs']->call($this);
}
return [];
}
/**
* Returns optional drawer routes for the field
*/
public function drawers(): array
{
if (
isset($this->options['drawers']) === true &&
$this->options['drawers'] instanceof Closure
) {
return $this->options['drawers']->call($this);
}
return [];
}
/**
* Creates a new field instance
*/
public static function factory(
string $type,
array $attrs = [],
Fields|null $formFields = null
): static|FieldClass {
$field = static::$types[$type] ?? null;
if (is_string($field) && class_exists($field) === true) {
$attrs['siblings'] = $formFields;
return new $field($attrs);
}
return new static($type, $attrs, $formFields);
}
/**
* Parent collection with all fields of the current form
*/
public function formFields(): Fields|null
{
return $this->formFields;
}
/**
* Validates when run for the first time and returns any errors
*/
public function errors(): array
{
if ($this->errors === null) {
$this->validate();
}
return $this->errors;
}
/**
* Checks if the field is empty
*/
public function isEmpty(mixed ...$args): bool
{
$value = match (count($args)) {
0 => $this->value(),
default => $args[0]
};
if ($empty = $this->options['isEmpty'] ?? null) {
return $empty->call($this, $value);
}
return in_array($value, [null, '', []], true);
}
/**
* Checks if the field is hidden
*/
public function isHidden(): bool
{
return ($this->options['hidden'] ?? false) === true;
}
/**
* Checks if the field is invalid
*/
public function isInvalid(): bool
{
return empty($this->errors()) === false;
}
/**
* Checks if the field is required
*/
public function isRequired(): bool
{
return $this->required ?? false;
}
/**
* Checks if the field is valid
*/
public function isValid(): bool
{
return empty($this->errors()) === true;
}
/**
* Returns the Kirby instance
*/
public function kirby(): App
{
return $this->model()->kirby();
}
/**
* Returns the parent model
*/
public function model(): mixed
{
return $this->model;
}
/**
* Checks if the field needs a value before being saved;
* this is the case if all of the following requirements are met:
* - The field is saveable
* - The field is required
* - The field is currently empty
* - The field is not currently inactive because of a `when` rule
*/
protected function needsValue(): bool
{
// check simple conditions first
if (
$this->save() === false ||
$this->isRequired() === false ||
$this->isEmpty() === false
) {
return false;
}
// check the data of the relevant fields if there is a `when` option
if (
empty($this->when) === false &&
is_array($this->when) === true &&
$formFields = $this->formFields()
) {
foreach ($this->when as $field => $value) {
$field = $formFields->get($field);
$inputValue = $field?->value() ?? '';
// if the input data doesn't match the requested `when` value,
// that means that this field is not required and can be saved
// (*all* `when` conditions must be met for this field to be required)
if ($inputValue !== $value) {
return false;
}
}
}
// either there was no `when` condition or all conditions matched
return true;
}
/**
* Checks if the field is saveable
*/
public function save(): bool
{
return ($this->options['save'] ?? true) !== false;
}
/**
* Converts the field to a plain array
*/
public function toArray(): array
{
$array = parent::toArray();
unset($array['model']);
$array['hidden'] = $this->isHidden();
$array['saveable'] = $this->save();
$array['signature'] = md5(json_encode($array));
ksort($array);
return array_filter(
$array,
fn ($item) => $item !== null && is_object($item) === false
);
}
/**
* Runs the validations defined for the field
*/
protected function validate(): void
{
$validations = $this->options['validations'] ?? [];
$this->errors = [];
// validate required values
if ($this->needsValue() === true) {
$this->errors['required'] = I18n::translate('error.validation.required');
}
foreach ($validations as $key => $validation) {
if (is_int($key) === true) {
// predefined validation
try {
Validations::$validation($this, $this->value());
} catch (Exception $e) {
$this->errors[$validation] = $e->getMessage();
}
continue;
}
if ($validation instanceof Closure) {
try {
$validation->call($this, $this->value());
} catch (Exception $e) {
$this->errors[$key] = $e->getMessage();
}
}
}
if (
empty($this->validate) === false &&
($this->isEmpty() === false || $this->isRequired() === true)
) {
$rules = A::wrap($this->validate);
$errors = V::errors($this->value(), $rules);
if (empty($errors) === false) {
$this->errors = array_merge($this->errors, $errors);
}
}
}
/**
* Returns the value of the field if saveable
* otherwise it returns null
*/
public function value(): mixed
{
return $this->save() ? $this->value : null;
}
}

View File

@@ -0,0 +1,352 @@
<?php
namespace Kirby\Form\Field;
use Kirby\Cms\App;
use Kirby\Cms\Block;
use Kirby\Cms\Blocks as BlocksCollection;
use Kirby\Cms\Fieldset;
use Kirby\Cms\Fieldsets;
use Kirby\Cms\ModelWithContent;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Exception\NotFoundException;
use Kirby\Form\FieldClass;
use Kirby\Form\Form;
use Kirby\Form\Mixin\EmptyState;
use Kirby\Form\Mixin\Max;
use Kirby\Form\Mixin\Min;
use Kirby\Toolkit\Str;
use Throwable;
class BlocksField extends FieldClass
{
use EmptyState;
use Max;
use Min;
protected Fieldsets $fieldsets;
protected string|null $group;
protected bool $pretty;
protected mixed $value = [];
public function __construct(array $params = [])
{
$this->setFieldsets(
$params['fieldsets'] ?? null,
$params['model'] ?? App::instance()->site()
);
parent::__construct($params);
$this->setEmpty($params['empty'] ?? null);
$this->setGroup($params['group'] ?? 'blocks');
$this->setMax($params['max'] ?? null);
$this->setMin($params['min'] ?? null);
$this->setPretty($params['pretty'] ?? false);
}
public function blocksToValues(
array $blocks,
string $to = 'values'
): array {
$result = [];
$fields = [];
foreach ($blocks as $block) {
try {
$type = $block['type'];
// get and cache fields at the same time
$fields[$type] ??= $this->fields($block['type']);
// overwrite the block content with form values
$block['content'] = $this->form(
$fields[$type],
$block['content']
)->$to();
// create id if not exists
$block['id'] ??= Str::uuid();
} catch (Throwable) {
// skip invalid blocks
} finally {
$result[] = $block;
}
}
return $result;
}
public function fields(string $type): array
{
return $this->fieldset($type)->fields();
}
public function fieldset(string $type): Fieldset
{
if ($fieldset = $this->fieldsets->find($type)) {
return $fieldset;
}
throw new NotFoundException(
'The fieldset ' . $type . ' could not be found'
);
}
public function fieldsets(): Fieldsets
{
return $this->fieldsets;
}
public function fieldsetGroups(): array|null
{
$groups = $this->fieldsets()->groups();
return empty($groups) === true ? null : $groups;
}
public function fill(mixed $value = null): void
{
$value = BlocksCollection::parse($value);
$blocks = BlocksCollection::factory($value)->toArray();
$this->value = $this->blocksToValues($blocks);
}
public function form(array $fields, array $input = []): Form
{
return new Form([
'fields' => $fields,
'model' => $this->model,
'strict' => true,
'values' => $input,
]);
}
public function isEmpty(): bool
{
return count($this->value()) === 0;
}
public function group(): string
{
return $this->group;
}
public function pretty(): bool
{
return $this->pretty;
}
/**
* Paste action for blocks:
* - generates new uuids for the blocks
* - filters only supported fieldsets
* - applies max limit if defined
*/
public function pasteBlocks(array $blocks): array
{
$blocks = $this->blocksToValues($blocks);
foreach ($blocks as $index => &$block) {
$block['id'] = Str::uuid();
// remove the block if it's not available
try {
$this->fieldset($block['type']);
} catch (Throwable) {
unset($blocks[$index]);
}
}
return array_values($blocks);
}
public function props(): array
{
return [
'empty' => $this->empty(),
'fieldsets' => $this->fieldsets()->toArray(),
'fieldsetGroups' => $this->fieldsetGroups(),
'group' => $this->group(),
'max' => $this->max(),
'min' => $this->min(),
] + parent::props();
}
public function routes(): array
{
$field = $this;
return [
[
'pattern' => 'uuid',
'action' => fn (): array => ['uuid' => Str::uuid()]
],
[
'pattern' => 'paste',
'method' => 'POST',
'action' => function () use ($field): array {
$request = App::instance()->request();
$value = BlocksCollection::parse($request->get('html'));
$blocks = BlocksCollection::factory($value);
return $field->pasteBlocks($blocks->toArray());
}
],
[
'pattern' => 'fieldsets/(:any)',
'method' => 'GET',
'action' => function (
string $fieldsetType
) use ($field): array {
$fields = $field->fields($fieldsetType);
$defaults = $field->form($fields, [])->data(true);
$content = $field->form($fields, $defaults)->values();
return Block::factory([
'content' => $content,
'type' => $fieldsetType
])->toArray();
}
],
[
'pattern' => 'fieldsets/(:any)/fields/(:any)/(:all?)',
'method' => 'ALL',
'action' => function (
string $fieldsetType,
string $fieldName,
string $path = null
) use ($field) {
$fields = $field->fields($fieldsetType);
$field = $field->form($fields)->field($fieldName);
$fieldApi = $this->clone([
'routes' => $field->api(),
'data' => array_merge(
$this->data(),
['field' => $field]
)
]);
return $fieldApi->call(
$path,
$this->requestMethod(),
$this->requestData()
);
}
],
];
}
public function store(mixed $value): mixed
{
$blocks = $this->blocksToValues((array)$value, 'content');
// returns empty string to avoid storing empty array as string `[]`
// and to consistency work with `$field->isEmpty()`
if (empty($blocks) === true) {
return '';
}
return $this->valueToJson($blocks, $this->pretty());
}
protected function setDefault(mixed $default = null): void
{
// set id for blocks if not exists
if (is_array($default) === true) {
array_walk($default, function (&$block) {
$block['id'] ??= Str::uuid();
});
}
parent::setDefault($default);
}
protected function setFieldsets(
string|array|null $fieldsets,
ModelWithContent $model
): void {
if (is_string($fieldsets) === true) {
$fieldsets = [];
}
$this->fieldsets = Fieldsets::factory(
$fieldsets,
['parent' => $model]
);
}
protected function setGroup(string $group = null): void
{
$this->group = $group;
}
protected function setPretty(bool $pretty = false): void
{
$this->pretty = $pretty;
}
public function validations(): array
{
return [
'blocks' => function ($value) {
if ($this->min && count($value) < $this->min) {
throw new InvalidArgumentException([
'key' => 'blocks.min.' . ($this->min === 1 ? 'singular' : 'plural'),
'data' => [
'min' => $this->min
]
]);
}
if ($this->max && count($value) > $this->max) {
throw new InvalidArgumentException([
'key' => 'blocks.max.' . ($this->max === 1 ? 'singular' : 'plural'),
'data' => [
'max' => $this->max
]
]);
}
$fields = [];
$index = 0;
foreach ($value as $block) {
$index++;
$type = $block['type'];
try {
$fieldset = $this->fieldset($type);
$blockFields = $fields[$type] ?? $fieldset->fields() ?? [];
} catch (Throwable) {
// skip invalid blocks
continue;
}
// store the fields for the next round
$fields[$type] = $blockFields;
// overwrite the content with the serialized form
$form = $this->form($blockFields, $block['content']);
foreach ($form->fields() as $field) {
$errors = $field->errors();
// rough first validation
if (empty($errors) === false) {
throw new InvalidArgumentException([
'key' => 'blocks.validation',
'data' => [
'field' => $field->label(),
'fieldset' => $fieldset->name(),
'index' => $index
]
]);
}
}
}
return true;
}
];
}
}

View File

@@ -0,0 +1,365 @@
<?php
namespace Kirby\Form\Field;
use Kirby\Cms\App;
use Kirby\Cms\Blueprint;
use Kirby\Cms\Fieldset;
use Kirby\Cms\Layout;
use Kirby\Cms\Layouts;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Form\Form;
use Kirby\Toolkit\Str;
use Throwable;
class LayoutField extends BlocksField
{
protected array|null $layouts;
protected array|null $selector;
protected Fieldset|null $settings;
public function __construct(array $params)
{
$this->setModel($params['model'] ?? App::instance()->site());
$this->setLayouts($params['layouts'] ?? ['1/1']);
$this->setSelector($params['selector'] ?? null);
$this->setSettings($params['settings'] ?? null);
parent::__construct($params);
}
public function fill(mixed $value = null): void
{
$value = $this->valueFromJson($value);
$layouts = Layouts::factory($value, ['parent' => $this->model])->toArray();
foreach ($layouts as $layoutIndex => $layout) {
if ($this->settings !== null) {
$layouts[$layoutIndex]['attrs'] = $this->attrsForm($layout['attrs'])->values();
}
foreach ($layout['columns'] as $columnIndex => $column) {
$layouts[$layoutIndex]['columns'][$columnIndex]['blocks'] = $this->blocksToValues($column['blocks']);
}
}
$this->value = $layouts;
}
public function attrsForm(array $input = []): Form
{
$settings = $this->settings();
return new Form([
'fields' => $settings?->fields() ?? [],
'model' => $this->model,
'strict' => true,
'values' => $input,
]);
}
public function layouts(): array|null
{
return $this->layouts;
}
/**
* Creates form values for each layout
*/
public function layoutsToValues(array $layouts): array
{
foreach ($layouts as &$layout) {
$layout['id'] ??= Str::uuid();
$layout['columns'] ??= [];
array_walk($layout['columns'], function (&$column) {
$column['id'] ??= Str::uuid();
$column['blocks'] = $this->blocksToValues($column['blocks'] ?? []);
});
}
return $layouts;
}
/**
* Paste action for layouts:
* - generates new uuids for layout, column and blocks
* - filters only supported layouts
* - filters only supported fieldsets
*/
public function pasteLayouts(array $layouts): array
{
$layouts = $this->layoutsToValues($layouts);
foreach ($layouts as $layoutIndex => &$layout) {
$layout['id'] = Str::uuid();
// remove the row if layout not available for the pasted layout field
$columns = array_column($layout['columns'], 'width');
if (in_array($columns, $this->layouts()) === false) {
unset($layouts[$layoutIndex]);
continue;
}
array_walk($layout['columns'], function (&$column) {
$column['id'] = Str::uuid();
array_walk($column['blocks'], function (&$block, $index) use ($column) {
$block['id'] = Str::uuid();
// remove the block if it's not available
try {
$this->fieldset($block['type']);
} catch (Throwable) {
unset($column['blocks'][$index]);
}
});
});
}
return $layouts;
}
public function props(): array
{
$settings = $this->settings();
return array_merge(parent::props(), [
'layouts' => $this->layouts(),
'selector' => $this->selector(),
'settings' => $settings?->toArray()
]);
}
public function routes(): array
{
$field = $this;
$routes = parent::routes();
$routes[] = [
'pattern' => 'layout',
'method' => 'POST',
'action' => function () use ($field): array {
$request = App::instance()->request();
$input = $request->get('attrs') ?? [];
$defaults = $field->attrsForm($input)->data(true);
$attrs = $field->attrsForm($defaults)->values();
$columns = $request->get('columns') ?? ['1/1'];
return Layout::factory([
'attrs' => $attrs,
'columns' => array_map(fn ($width) => [
'blocks' => [],
'id' => Str::uuid(),
'width' => $width,
], $columns)
])->toArray();
},
];
$routes[] = [
'pattern' => 'layout/paste',
'method' => 'POST',
'action' => function () use ($field): array {
$request = App::instance()->request();
$value = Layouts::parse($request->get('json'));
$layouts = Layouts::factory($value);
return $field->pasteLayouts($layouts->toArray());
}
];
$routes[] = [
'pattern' => 'fields/(:any)/(:all?)',
'method' => 'ALL',
'action' => function (
string $fieldName,
string $path = null
) use ($field): array {
$form = $field->attrsForm();
$field = $form->field($fieldName);
$fieldApi = $this->clone([
'routes' => $field->api(),
'data' => array_merge(
$this->data(),
['field' => $field]
)
]);
return $fieldApi->call(
$path,
$this->requestMethod(),
$this->requestData()
);
}
];
return $routes;
}
public function selector(): array|null
{
return $this->selector;
}
protected function setDefault(mixed $default = null): void
{
// set id for layouts, columns and blocks within layout if not exists
if (is_array($default) === true) {
array_walk($default, function (&$layout) {
$layout['id'] ??= Str::uuid();
// set columns id within layout
if (isset($layout['columns']) === true) {
array_walk($layout['columns'], function (&$column) {
$column['id'] ??= Str::uuid();
// set blocks id within column
if (isset($column['blocks']) === true) {
array_walk($column['blocks'], function (&$block) {
$block['id'] ??= Str::uuid();
});
}
});
}
});
}
parent::setDefault($default);
}
protected function setLayouts(array $layouts = []): void
{
$this->layouts = array_map(
fn ($layout) => Str::split($layout),
$layouts
);
}
/**
* Layout selector's styles such as size (`small`, `medium`, `large` or `huge`) and columns
*/
protected function setSelector(array|null $selector = null): void
{
$this->selector = $selector;
}
protected function setSettings(array|string|null $settings = null): void
{
if (empty($settings) === true) {
$this->settings = null;
return;
}
$settings = Blueprint::extend($settings);
$settings['icon'] = 'dashboard';
$settings['type'] = 'layout';
$settings['parent'] = $this->model();
$this->settings = Fieldset::factory($settings);
}
public function settings(): Fieldset|null
{
return $this->settings;
}
public function store(mixed $value): mixed
{
$value = Layouts::factory($value, ['parent' => $this->model])->toArray();
// returns empty string to avoid storing empty array as string `[]`
// and to consistency work with `$field->isEmpty()`
if (empty($value) === true) {
return '';
}
foreach ($value as $layoutIndex => $layout) {
if ($this->settings !== null) {
$value[$layoutIndex]['attrs'] = $this->attrsForm($layout['attrs'])->content();
}
foreach ($layout['columns'] as $columnIndex => $column) {
$value[$layoutIndex]['columns'][$columnIndex]['blocks'] = $this->blocksToValues($column['blocks'] ?? [], 'content');
}
}
return $this->valueToJson($value, $this->pretty());
}
public function validations(): array
{
return [
'layout' => function ($value) {
$fields = [];
$layoutIndex = 0;
foreach ($value as $layout) {
$layoutIndex++;
// validate settings form
$form = $this->attrsForm($layout['attrs'] ?? []);
foreach ($form->fields() as $field) {
$errors = $field->errors();
if (empty($errors) === false) {
throw new InvalidArgumentException([
'key' => 'layout.validation.settings',
'data' => [
'index' => $layoutIndex
]
]);
}
}
// validate blocks in the layout
$blockIndex = 0;
foreach ($layout['columns'] ?? [] as $column) {
foreach ($column['blocks'] ?? [] as $block) {
$blockIndex++;
$blockType = $block['type'];
try {
$fieldset = $this->fieldset($blockType);
$blockFields = $fields[$blockType] ?? $this->fields($blockType) ?? [];
} catch (Throwable) {
// skip invalid blocks
continue;
}
// store the fields for the next round
$fields[$blockType] = $blockFields;
// overwrite the content with the serialized form
$form = $this->form($blockFields, $block['content']);
foreach ($form->fields() as $field) {
$errors = $field->errors();
// rough first validation
if (empty($errors) === false) {
throw new InvalidArgumentException([
'key' => 'layout.validation.block',
'data' => [
'blockIndex' => $blockIndex,
'field' => $field->label(),
'fieldset' => $fieldset->name(),
'layoutIndex' => $layoutIndex
]
]);
}
}
}
}
}
return true;
}
];
}
}

View File

@@ -0,0 +1,646 @@
<?php
namespace Kirby\Form;
use Closure;
use Exception;
use Kirby\Cms\App;
use Kirby\Cms\HasSiblings;
use Kirby\Cms\ModelWithContent;
use Kirby\Data\Data;
use Kirby\Toolkit\I18n;
use Kirby\Toolkit\Str;
use Throwable;
/**
* Abstract field class to be used instead
* of functional field components for more
* control.
*
* @package Kirby Form
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://getkirby.com/license
*/
abstract class FieldClass
{
use HasSiblings;
protected string|null $after;
protected bool $autofocus;
protected string|null $before;
protected mixed $default;
protected bool $disabled;
protected string|null $help;
protected string|null $icon;
protected string|null $label;
protected ModelWithContent $model;
protected string|null $name;
protected string|null $placeholder;
protected bool $required;
protected Fields $siblings;
protected bool $translate;
protected mixed $value = null;
protected array|null $when;
protected string|null $width;
public function __construct(
protected array $params = []
) {
$this->setAfter($params['after'] ?? null);
$this->setAutofocus($params['autofocus'] ?? false);
$this->setBefore($params['before'] ?? null);
$this->setDefault($params['default'] ?? null);
$this->setDisabled($params['disabled'] ?? false);
$this->setHelp($params['help'] ?? null);
$this->setIcon($params['icon'] ?? null);
$this->setLabel($params['label'] ?? null);
$this->setModel($params['model'] ?? App::instance()->site());
$this->setName($params['name'] ?? null);
$this->setPlaceholder($params['placeholder'] ?? null);
$this->setRequired($params['required'] ?? false);
$this->setSiblings($params['siblings'] ?? null);
$this->setTranslate($params['translate'] ?? true);
$this->setWhen($params['when'] ?? null);
$this->setWidth($params['width'] ?? null);
if (array_key_exists('value', $params) === true) {
$this->fill($params['value']);
}
}
public function __call(string $param, array $args): mixed
{
if (isset($this->$param) === true) {
return $this->$param;
}
return $this->params[$param] ?? null;
}
public function after(): string|null
{
return $this->stringTemplate($this->after);
}
public function api(): array
{
return $this->routes();
}
public function autofocus(): bool
{
return $this->autofocus;
}
public function before(): string|null
{
return $this->stringTemplate($this->before);
}
/**
* @deprecated 3.5.0
* @todo remove when the general field class setup has been refactored
*
* Returns the field data
* in a format to be stored
* in Kirby's content fields
*/
public function data(bool $default = false): mixed
{
return $this->store($this->value($default));
}
/**
* Returns the default value for the field,
* which will be used when a page/file/user is created
*/
public function default(): mixed
{
if (is_string($this->default) === false) {
return $this->default;
}
return $this->stringTemplate($this->default);
}
/**
* Returns optional dialog routes for the field
*/
public function dialogs(): array
{
return [];
}
/**
* If `true`, the field is no longer editable and will not be saved
*/
public function disabled(): bool
{
return $this->disabled;
}
/**
* Returns optional drawer routes for the field
*/
public function drawers(): array
{
return [];
}
/**
* Runs all validations and returns an array of
* error messages
*/
public function errors(): array
{
return $this->validate();
}
/**
* Setter for the value
*/
public function fill(mixed $value = null): void
{
$this->value = $value;
}
/**
* Optional help text below the field
*/
public function help(): string|null
{
if (empty($this->help) === false) {
$help = $this->stringTemplate($this->help);
$help = $this->kirby()->kirbytext($help);
return $help;
}
return null;
}
protected function i18n(string|array|null $param = null): string|null
{
return empty($param) === false ? I18n::translate($param, $param) : null;
}
/**
* Optional icon that will be shown at the end of the field
*/
public function icon(): string|null
{
return $this->icon;
}
public function id(): string
{
return $this->name();
}
public function isDisabled(): bool
{
return $this->disabled;
}
public function isEmpty(): bool
{
return $this->isEmptyValue($this->value());
}
public function isEmptyValue(mixed $value = null): bool
{
return in_array($value, [null, '', []], true);
}
public function isHidden(): bool
{
return false;
}
/**
* Checks if the field is invalid
*/
public function isInvalid(): bool
{
return $this->isValid() === false;
}
public function isRequired(): bool
{
return $this->required;
}
public function isSaveable(): bool
{
return true;
}
/**
* Checks if the field is valid
*/
public function isValid(): bool
{
return empty($this->errors()) === true;
}
/**
* Returns the Kirby instance
*/
public function kirby(): App
{
return $this->model->kirby();
}
/**
* The field label can be set as string or associative array with translations
*/
public function label(): string
{
return $this->stringTemplate(
$this->label ?? Str::ucfirst($this->name())
);
}
/**
* Returns the parent model
*/
public function model(): ModelWithContent
{
return $this->model;
}
/**
* Returns the field name
*/
public function name(): string
{
return $this->name ?? $this->type();
}
/**
* Checks if the field needs a value before being saved;
* this is the case if all of the following requirements are met:
* - The field is saveable
* - The field is required
* - The field is currently empty
* - The field is not currently inactive because of a `when` rule
*/
protected function needsValue(): bool
{
// check simple conditions first
if (
$this->isSaveable() === false ||
$this->isRequired() === false ||
$this->isEmpty() === false
) {
return false;
}
// check the data of the relevant fields if there is a `when` option
if (
empty($this->when) === false &&
is_array($this->when) === true &&
$formFields = $this->siblings()
) {
foreach ($this->when as $field => $value) {
$field = $formFields->get($field);
$inputValue = $field?->value() ?? '';
// if the input data doesn't match the requested `when` value,
// that means that this field is not required and can be saved
// (*all* `when` conditions must be met for this field to be required)
if ($inputValue !== $value) {
return false;
}
}
}
// either there was no `when` condition or all conditions matched
return true;
}
/**
* Returns all original params for the field
*/
public function params(): array
{
return $this->params;
}
/**
* Optional placeholder value that will be shown when the field is empty
*/
public function placeholder(): string|null
{
return $this->stringTemplate($this->placeholder);
}
/**
* Define the props that will be sent to
* the Vue component
*/
public function props(): array
{
return [
'after' => $this->after(),
'autofocus' => $this->autofocus(),
'before' => $this->before(),
'default' => $this->default(),
'disabled' => $this->isDisabled(),
'help' => $this->help(),
'hidden' => $this->isHidden(),
'icon' => $this->icon(),
'label' => $this->label(),
'name' => $this->name(),
'placeholder' => $this->placeholder(),
'required' => $this->isRequired(),
'saveable' => $this->isSaveable(),
'translate' => $this->translate(),
'type' => $this->type(),
'when' => $this->when(),
'width' => $this->width(),
];
}
/**
* If `true`, the field has to be filled in correctly to be saved.
*/
public function required(): bool
{
return $this->required;
}
/**
* Routes for the field API
*/
public function routes(): array
{
return [];
}
/**
* @deprecated 3.5.0
* @todo remove when the general field class setup has been refactored
*/
public function save(): bool
{
return $this->isSaveable();
}
protected function setAfter(array|string|null $after = null): void
{
$this->after = $this->i18n($after);
}
protected function setAutofocus(bool $autofocus = false): void
{
$this->autofocus = $autofocus;
}
protected function setBefore(array|string|null $before = null): void
{
$this->before = $this->i18n($before);
}
protected function setDefault(mixed $default = null): void
{
$this->default = $default;
}
protected function setDisabled(bool $disabled = false): void
{
$this->disabled = $disabled;
}
protected function setHelp(array|string|null $help = null): void
{
$this->help = $this->i18n($help);
}
protected function setIcon(string|null $icon = null): void
{
$this->icon = $icon;
}
protected function setLabel(array|string|null $label = null): void
{
$this->label = $this->i18n($label);
}
protected function setModel(ModelWithContent $model): void
{
$this->model = $model;
}
protected function setName(string|null $name = null): void
{
$this->name = $name;
}
protected function setPlaceholder(array|string|null $placeholder = null): void
{
$this->placeholder = $this->i18n($placeholder);
}
protected function setRequired(bool $required = false): void
{
$this->required = $required;
}
protected function setSiblings(Fields|null $siblings = null): void
{
$this->siblings = $siblings ?? new Fields([$this]);
}
protected function setTranslate(bool $translate = true): void
{
$this->translate = $translate;
}
/**
* Setter for the when condition
*/
protected function setWhen(array|null $when = null): void
{
$this->when = $when;
}
/**
* Setter for the field width
*/
protected function setWidth(string|null $width = null): void
{
$this->width = $width;
}
/**
* Returns all sibling fields
*/
protected function siblingsCollection(): Fields
{
return $this->siblings;
}
/**
* Parses a string template in the given value
*/
protected function stringTemplate(string|null $string = null): string|null
{
if ($string !== null) {
return $this->model->toString($string);
}
return null;
}
/**
* Converts the given value to a value
* that can be stored in the text file
*/
public function store(mixed $value): mixed
{
return $value;
}
/**
* Should the field be translatable?
*/
public function translate(): bool
{
return $this->translate;
}
/**
* Converts the field to a plain array
*/
public function toArray(): array
{
$props = $this->props();
$props['signature'] = md5(json_encode($props));
ksort($props);
return array_filter($props, fn ($item) => $item !== null);
}
/**
* Returns the field type
*/
public function type(): string
{
return lcfirst(basename(str_replace(['\\', 'Field'], ['/', ''], static::class)));
}
/**
* Runs the validations defined for the field
*/
protected function validate(): array
{
$validations = $this->validations();
$value = $this->value();
$errors = [];
// validate required values
if ($this->needsValue() === true) {
$errors['required'] = I18n::translate('error.validation.required');
}
foreach ($validations as $key => $validation) {
if (is_int($key) === true) {
// predefined validation
try {
Validations::$validation($this, $value);
} catch (Exception $e) {
$errors[$validation] = $e->getMessage();
}
continue;
}
if ($validation instanceof Closure) {
try {
$validation->call($this, $value);
} catch (Exception $e) {
$errors[$key] = $e->getMessage();
}
}
}
return $errors;
}
/**
* Defines all validation rules
* @codeCoverageIgnore
*/
protected function validations(): array
{
return [];
}
/**
* Returns the value of the field if saveable
* otherwise it returns null
*/
public function value(bool $default = false): mixed
{
if ($this->isSaveable() === false) {
return null;
}
if ($default === true && $this->isEmpty() === true) {
return $this->default();
}
return $this->value;
}
protected function valueFromJson(mixed $value): array
{
try {
return Data::decode($value, 'json');
} catch (Throwable) {
return [];
}
}
protected function valueFromYaml(mixed $value): array
{
return Data::decode($value, 'yaml');
}
protected function valueToJson(
array $value = null,
bool $pretty = false
): string {
$constants = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
if ($pretty === true) {
$constants |= JSON_PRETTY_PRINT;
}
return json_encode($value, $constants);
}
protected function valueToYaml(array $value = null): string
{
return Data::encode($value, 'yaml');
}
/**
* Conditions when the field will be shown
*/
public function when(): array|null
{
return $this->when;
}
/**
* Returns the width of the field in
* the Panel grid
*/
public function width(): string
{
return $this->width ?? '1/1';
}
}

52
kirby/src/Form/Fields.php Normal file
View File

@@ -0,0 +1,52 @@
<?php
namespace Kirby\Form;
use Closure;
use Kirby\Toolkit\Collection;
/**
* A collection of Field objects
*
* @package Kirby Form
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*/
class Fields extends Collection
{
/**
* Internal setter for each object in the Collection.
* This takes care of validation and of setting
* the collection prop on each object correctly.
*
* @param object|array $field
*/
public function __set(string $name, $field): void
{
if (is_array($field) === true) {
// use the array key as name if the name is not set
$field['name'] ??= $name;
$field = Field::factory($field['type'], $field, $this);
}
parent::__set($field->name(), $field);
}
/**
* Converts the fields collection to an
* array and also does that for every
* included field.
*/
public function toArray(Closure $map = null): array
{
$array = [];
foreach ($this as $field) {
$array[$field->name()] = $field->toArray();
}
return $array;
}
}

355
kirby/src/Form/Form.php Normal file
View File

@@ -0,0 +1,355 @@
<?php
namespace Kirby\Form;
use Closure;
use Kirby\Cms\App;
use Kirby\Cms\File;
use Kirby\Cms\ModelWithContent;
use Kirby\Data\Data;
use Kirby\Exception\NotFoundException;
use Kirby\Toolkit\A;
use Kirby\Toolkit\Str;
use Throwable;
/**
* The main form class, that is being
* used to create a list of form fields
* and handles global form validation
* and submission
*
* @package Kirby Form
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*/
class Form
{
/**
* An array of all found errors
*/
protected array|null $errors = null;
/**
* Fields in the form
*/
protected Fields|null $fields;
/**
* All values of form
*/
protected array $values = [];
/**
* Form constructor
*/
public function __construct(array $props)
{
$fields = $props['fields'] ?? [];
$values = $props['values'] ?? [];
$input = $props['input'] ?? [];
$strict = $props['strict'] ?? false;
$inject = $props;
// prepare field properties for multilang setups
$fields = static::prepareFieldsForLanguage(
$fields,
$props['language'] ?? null
);
// lowercase all value names
$values = array_change_key_case($values);
$input = array_change_key_case($input);
unset($inject['fields'], $inject['values'], $inject['input']);
$this->fields = new Fields();
$this->values = [];
foreach ($fields as $name => $props) {
// inject stuff from the form constructor (model, etc.)
$props = array_merge($inject, $props);
// inject the name
$props['name'] = $name = strtolower($name);
// check if the field is disabled and
// overwrite the field value if not set
$props['value'] = match ($props['disabled'] ?? false) {
true => $values[$name] ?? null,
default => $input[$name] ?? $values[$name] ?? null
};
try {
$field = Field::factory($props['type'], $props, $this->fields);
} catch (Throwable $e) {
$field = static::exceptionField($e, $props);
}
if ($field->save() !== false) {
$this->values[$name] = $field->value();
}
$this->fields->append($name, $field);
}
if ($strict !== true) {
// use all given values, no matter
// if there's a field or not.
$input = array_merge($values, $input);
foreach ($input as $key => $value) {
$this->values[$key] ??= $value;
}
}
}
/**
* Returns the data required to write to the content file
* Doesn't include default and null values
*/
public function content(): array
{
return $this->data(false, false);
}
/**
* Returns data for all fields in the form
*
* @param false $defaults
*/
public function data($defaults = false, bool $includeNulls = true): array
{
$data = $this->values;
foreach ($this->fields as $field) {
if ($field->save() === false || $field->unset() === true) {
if ($includeNulls === true) {
$data[$field->name()] = null;
} else {
unset($data[$field->name()]);
}
} else {
$data[$field->name()] = $field->data($defaults);
}
}
return $data;
}
/**
* An array of all found errors
*/
public function errors(): array
{
if ($this->errors !== null) {
return $this->errors;
}
$this->errors = [];
foreach ($this->fields as $field) {
if (empty($field->errors()) === false) {
$this->errors[$field->name()] = [
'label' => $field->label(),
'message' => $field->errors()
];
}
}
return $this->errors;
}
/**
* Shows the error with the field
*/
public static function exceptionField(
Throwable $exception,
array $props = []
): Field {
$message = $exception->getMessage();
if (App::instance()->option('debug') === true) {
$message .= ' in file: ' . $exception->getFile();
$message .= ' line: ' . $exception->getLine();
}
$props = array_merge($props, [
'label' => 'Error in "' . $props['name'] . '" field.',
'theme' => 'negative',
'text' => strip_tags($message),
]);
return Field::factory('info', $props);
}
/**
* Get the field object by name
* and handle nested fields correctly
*
* @throws \Kirby\Exception\NotFoundException
*/
public function field(string $name): Field|FieldClass
{
$form = $this;
$fieldNames = Str::split($name, '+');
$index = 0;
$count = count($fieldNames);
$field = null;
foreach ($fieldNames as $fieldName) {
$index++;
if ($field = $form->fields()->get($fieldName)) {
if ($count !== $index) {
$form = $field->form();
}
continue;
}
throw new NotFoundException('The field "' . $fieldName . '" could not be found');
}
// it can get this error only if $name is an empty string as $name = ''
if ($field === null) {
throw new NotFoundException('No field could be loaded');
}
return $field;
}
/**
* Returns form fields
*/
public function fields(): Fields|null
{
return $this->fields;
}
public static function for(
ModelWithContent $model,
array $props = []
): static {
// get the original model data
$original = $model->content($props['language'] ?? null)->toArray();
$values = $props['values'] ?? [];
// convert closures to values
foreach ($values as $key => $value) {
if ($value instanceof Closure) {
$values[$key] = $value($original[$key] ?? null);
}
}
// set a few defaults
$props['values'] = array_merge($original, $values);
$props['fields'] ??= [];
$props['model'] = $model;
// search for the blueprint
if (
method_exists($model, 'blueprint') === true &&
$blueprint = $model->blueprint()
) {
$props['fields'] = $blueprint->fields();
}
$ignoreDisabled = $props['ignoreDisabled'] ?? false;
// REFACTOR: this could be more elegant
if ($ignoreDisabled === true) {
$props['fields'] = array_map(function ($field) {
$field['disabled'] = false;
return $field;
}, $props['fields']);
}
return new static($props);
}
/**
* Checks if the form is invalid
*/
public function isInvalid(): bool
{
return $this->isValid() === false;
}
/**
* Checks if the form is valid
*/
public function isValid(): bool
{
return empty($this->errors()) === true;
}
/**
* Disables fields in secondary languages when
* they are configured to be untranslatable
*/
protected static function prepareFieldsForLanguage(
array $fields,
string|null $language = null
): array {
$kirby = App::instance(null, true);
// only modify the fields if we have a valid Kirby multilang instance
if ($kirby?->multilang() !== true) {
return $fields;
}
$language ??= $kirby->language()->code();
if ($language !== $kirby->defaultLanguage()->code()) {
foreach ($fields as $fieldName => $fieldProps) {
// switch untranslatable fields to readonly
if (($fieldProps['translate'] ?? true) === false) {
$fields[$fieldName]['unset'] = true;
$fields[$fieldName]['disabled'] = true;
}
}
}
return $fields;
}
/**
* Converts the data of fields to strings
*
* @param false $defaults
*/
public function strings($defaults = false): array
{
return A::map(
$this->data($defaults),
fn ($value) => match (true) {
is_array($value) => Data::encode($value, 'yaml'),
default => $value
}
);
}
/**
* Converts the form to a plain array
*/
public function toArray(): array
{
$array = [
'errors' => $this->errors(),
'fields' => $this->fields->toArray(fn ($item) => $item->toArray()),
'invalid' => $this->isInvalid()
];
return $array;
}
/**
* Returns form values
*/
public function values(): array
{
return $this->values;
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace Kirby\Form\Mixin;
trait EmptyState
{
protected string|null $empty;
protected function setEmpty(string|array|null $empty = null): void
{
$this->empty = $this->i18n($empty);
}
public function empty(): string|null
{
return $this->stringTemplate($this->empty);
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace Kirby\Form\Mixin;
trait Max
{
protected int|null $max;
public function max(): int|null
{
return $this->max;
}
protected function setMax(int $max = null)
{
$this->max = $max;
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace Kirby\Form\Mixin;
trait Min
{
protected int|null $min;
public function min(): int|null
{
return $this->min;
}
protected function setMin(int $min = null)
{
$this->min = $min;
}
}

View File

@@ -0,0 +1,272 @@
<?php
namespace Kirby\Form;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Toolkit\V;
/**
* Often used validation rules for fields
*
* @package Kirby Form
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*/
class Validations
{
/**
* Validates if the field value is boolean
*
* @param \Kirby\Form\Field|\Kirby\Form\FieldClass $field
* @throws \Kirby\Exception\InvalidArgumentException
*/
public static function boolean($field, $value): bool
{
if ($field->isEmpty($value) === false) {
if (is_bool($value) === false) {
throw new InvalidArgumentException([
'key' => 'validation.boolean'
]);
}
}
return true;
}
/**
* Validates if the field value is valid date
*
* @throws \Kirby\Exception\InvalidArgumentException
*/
public static function date(Field|FieldClass $field, mixed $value): bool
{
if ($field->isEmpty($value) === false) {
if (V::date($value) !== true) {
throw new InvalidArgumentException(
V::message('date', $value)
);
}
}
return true;
}
/**
* Validates if the field value is valid email
*
* @throws \Kirby\Exception\InvalidArgumentException
*/
public static function email(Field|FieldClass $field, mixed $value): bool
{
if ($field->isEmpty($value) === false) {
if (V::email($value) === false) {
throw new InvalidArgumentException(
V::message('email', $value)
);
}
}
return true;
}
/**
* Validates if the field value is maximum
*
* @throws \Kirby\Exception\InvalidArgumentException
*/
public static function max(Field|FieldClass $field, mixed $value): bool
{
if (
$field->isEmpty($value) === false &&
$field->max() !== null
) {
if (V::max($value, $field->max()) === false) {
throw new InvalidArgumentException(
V::message('max', $value, $field->max())
);
}
}
return true;
}
/**
* Validates if the field value is max length
*
* @throws \Kirby\Exception\InvalidArgumentException
*/
public static function maxlength(Field|FieldClass $field, mixed $value): bool
{
if (
$field->isEmpty($value) === false &&
$field->maxlength() !== null
) {
if (V::maxLength($value, $field->maxlength()) === false) {
throw new InvalidArgumentException(
V::message('maxlength', $value, $field->maxlength())
);
}
}
return true;
}
/**
* Validates if the field value is minimum
*
* @throws \Kirby\Exception\InvalidArgumentException
*/
public static function min(Field|FieldClass $field, mixed $value): bool
{
if (
$field->isEmpty($value) === false &&
$field->min() !== null
) {
if (V::min($value, $field->min()) === false) {
throw new InvalidArgumentException(
V::message('min', $value, $field->min())
);
}
}
return true;
}
/**
* Validates if the field value is min length
*
* @throws \Kirby\Exception\InvalidArgumentException
*/
public static function minlength(Field|FieldClass $field, mixed $value): bool
{
if (
$field->isEmpty($value) === false &&
$field->minlength() !== null
) {
if (V::minLength($value, $field->minlength()) === false) {
throw new InvalidArgumentException(
V::message('minlength', $value, $field->minlength())
);
}
}
return true;
}
/**
* Validates if the field value matches defined pattern
*
* @throws \Kirby\Exception\InvalidArgumentException
*/
public static function pattern(Field|FieldClass $field, mixed $value): bool
{
if ($field->isEmpty($value) === false && $field->pattern() !== null) {
if (V::match($value, '/' . $field->pattern() . '/i') === false) {
throw new InvalidArgumentException(
V::message('match')
);
}
}
return true;
}
/**
* Validates if the field value is required
*
* @throws \Kirby\Exception\InvalidArgumentException
*/
public static function required(Field|FieldClass $field, mixed $value): bool
{
if (
$field->isRequired() === true &&
$field->save() === true &&
$field->isEmpty($value) === true
) {
throw new InvalidArgumentException([
'key' => 'validation.required'
]);
}
return true;
}
/**
* Validates if the field value is in defined options
*
* @throws \Kirby\Exception\InvalidArgumentException
*/
public static function option(Field|FieldClass $field, mixed $value): bool
{
if ($field->isEmpty($value) === false) {
$values = array_column($field->options(), 'value');
if (in_array($value, $values, true) !== true) {
throw new InvalidArgumentException([
'key' => 'validation.option'
]);
}
}
return true;
}
/**
* Validates if the field values is in defined options
*
* @throws \Kirby\Exception\InvalidArgumentException
*/
public static function options(Field|FieldClass $field, mixed $value): bool
{
if ($field->isEmpty($value) === false) {
$values = array_column($field->options(), 'value');
foreach ($value as $val) {
if (in_array($val, $values, true) === false) {
throw new InvalidArgumentException([
'key' => 'validation.option'
]);
}
}
}
return true;
}
/**
* Validates if the field value is valid time
*
* @throws \Kirby\Exception\InvalidArgumentException
*/
public static function time(Field|FieldClass $field, mixed $value): bool
{
if ($field->isEmpty($value) === false) {
if (V::time($value) !== true) {
throw new InvalidArgumentException(
V::message('time', $value)
);
}
}
return true;
}
/**
* Validates if the field value is valid url
*
* @throws \Kirby\Exception\InvalidArgumentException
*/
public static function url(Field|FieldClass $field, mixed $value): bool
{
if ($field->isEmpty($value) === false) {
if (V::url($value) === false) {
throw new InvalidArgumentException(
V::message('url', $value)
);
}
}
return true;
}
}