298 lines
13 KiB
PHP
298 lines
13 KiB
PHP
<?php
|
|
|
|
namespace IriksIT\Manager\Support;
|
|
|
|
use Illuminate\Database\Eloquent\Model as Eloquent;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Validation\Rule;
|
|
|
|
/**
|
|
* Field definitions: what a page, or any other record a site manages without code of its own, is made of.
|
|
* One definition drives the form of the screens, the validation and the cleaning of what is stored, so a
|
|
* field is declared once:
|
|
*
|
|
* 'hero_title' => ['label' => 'Title on the photo', 'type' => 'text', 'help' => 'One line.', 'max' => 120]
|
|
*
|
|
* Types: `text` (one line), `textarea` (paragraphs), `markdown` (a long text in Markdown), `lines` (one item
|
|
* per line), `media` (a picture from the media library; the value is its address), `url`, `number`, `date`,
|
|
* `toggle` (a switch) and `select` (needs `options`: a list of values, or value => label, or `source`: `['model' => Service::class, 'label' => 'title', 'value' => 'id']`
|
|
* for the rows of a table of the site). More: `slug` (an address part; `from` names the field it is made of when it is left empty), `list` (a list of short texts,
|
|
* one per line), `media_list` (a list of pictures from the media library, a gallery) and `repeater` (a list of items that each have the fields of `items`, for example
|
|
* questions and answers). The last three are stored as arrays. `required`, `default` and
|
|
* `rules` (extra Laravel rules) are optional on every type. `help` is a line of explanation under the field; `advanced`
|
|
* hides the field in the simple face of the manager (it keeps its value). `simple` gives the simple face its own words,
|
|
* for someone who is not a webmaster: `'simple' => ['label' => 'Your phone number', 'help' => 'As you want it to be read.']`; a part
|
|
* left out falls back to `label` / `help`.
|
|
*/
|
|
final class Fields
|
|
{
|
|
public const TYPES = ['text', 'textarea', 'markdown', 'lines', 'media', 'url', 'number', 'date', 'toggle', 'select', 'slug', 'list', 'media_list', 'repeater'];
|
|
|
|
/** What a repeater item may be made of. */
|
|
private const ITEM_TYPES = ['text', 'textarea', 'url', 'media'];
|
|
|
|
private const LENGTHS = ['text' => 255, 'textarea' => 20000, 'markdown' => 100000, 'lines' => 10000, 'media' => 2048, 'url' => 2048, 'date' => 40, 'select' => 255, 'slug' => 120];
|
|
|
|
/**
|
|
* The definitions in one shape, with a key, a label and a known type; what is wrong is dropped.
|
|
*
|
|
* @param array<array-key, mixed> $fields key => definition
|
|
* @return array<string, array{key: string, label: string, type: string, help: ?string, simple_label: ?string, simple_help: ?string, advanced: bool, required: bool, default: mixed, options: array<string, string>, source: ?array{model: class-string<Eloquent>, label: string, value: string}, from: ?string, items: array<string, array<string, mixed>>, max: ?int, rules: list<mixed>}>
|
|
*/
|
|
public static function normalize(array $fields): array
|
|
{
|
|
$out = [];
|
|
|
|
foreach ($fields as $key => $field) {
|
|
if (! is_string($key) || ! preg_match('/^[a-z][a-z0-9_]{0,59}$/', $key) || ! is_array($field)) {
|
|
continue;
|
|
}
|
|
|
|
$type = in_array($field['type'] ?? 'text', self::TYPES, true) ? ($field['type'] ?? 'text') : 'text';
|
|
$options = [];
|
|
|
|
$given = (array) ($field['options'] ?? []);
|
|
|
|
foreach ($given as $value => $label) {
|
|
$options[(string) (array_is_list($given) ? $label : $value)] = (string) $label;
|
|
}
|
|
|
|
$source = self::source($field['source'] ?? null);
|
|
|
|
if ($type === 'select' && $options === [] && $source === null) {
|
|
continue;
|
|
}
|
|
|
|
$items = $type === 'repeater' ? self::normalizeItems((array) ($field['items'] ?? [])) : [];
|
|
|
|
if ($type === 'repeater' && $items === []) {
|
|
continue;
|
|
}
|
|
|
|
$out[$key] = [
|
|
'key' => $key,
|
|
'label' => (string) ($field['label'] ?? ucfirst(str_replace('_', ' ', $key))),
|
|
'type' => $type,
|
|
'help' => isset($field['help']) ? (string) $field['help'] : null,
|
|
'simple_label' => self::simpleText($field, 'label'),
|
|
'simple_help' => self::simpleText($field, 'help'),
|
|
'advanced' => (bool) ($field['advanced'] ?? false),
|
|
'required' => (bool) ($field['required'] ?? false),
|
|
'default' => $field['default'] ?? self::empty($type),
|
|
'options' => $options,
|
|
'source' => $source,
|
|
'from' => $type === 'slug' && isset($field['from']) ? (string) $field['from'] : null,
|
|
'items' => $items,
|
|
'max' => isset($field['max']) ? max(1, (int) $field['max']) : null,
|
|
'rules' => array_values((array) ($field['rules'] ?? [])),
|
|
];
|
|
}
|
|
|
|
return $out;
|
|
}
|
|
|
|
/**
|
|
* The Laravel rules for the values, keyed `<prefix><key>`.
|
|
*
|
|
* @param array<string, array<string, mixed>> $fields normalized
|
|
* @return array<string, list<mixed>>
|
|
*/
|
|
public static function rules(array $fields, string $prefix = ''): array
|
|
{
|
|
$rules = [];
|
|
|
|
foreach ($fields as $key => $field) {
|
|
$type = $field['type'];
|
|
$max = $field['max'] ?? self::LENGTHS[$type] ?? null;
|
|
$presence = $field['required'] ? 'required' : 'nullable';
|
|
|
|
$rules[$prefix.$key] = [$presence, ...match ($type) {
|
|
'toggle' => ['boolean'],
|
|
'number' => ['numeric'],
|
|
'date' => ['date'],
|
|
'select' => $field['source'] === null ? ['string', Rule::in(array_keys($field['options']))] : [Rule::in(array_keys(self::optionsOf($field)))],
|
|
'media', 'url' => ['string', 'max:'.$max, 'regex:'.self::ADDRESS],
|
|
'slug' => ['string', 'max:'.$max, 'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/'],
|
|
'list' => ['array', 'max:100'],
|
|
'media_list' => ['array', 'max:50'],
|
|
'repeater' => ['array', 'max:50'],
|
|
default => ['string', 'max:'.$max],
|
|
}, ...$field['rules']];
|
|
|
|
if ($type === 'list') {
|
|
$rules[$prefix.$key.'.*'] = ['nullable', 'string', 'max:500'];
|
|
} elseif ($type === 'media_list') {
|
|
$rules[$prefix.$key.'.*'] = ['nullable', 'string', 'max:2048', 'regex:'.self::ADDRESS];
|
|
} elseif ($type === 'repeater') {
|
|
foreach (self::rules($field['items']) as $sub => $subRules) {
|
|
$rules[$prefix.$key.'.*.'.$sub] = $subRules;
|
|
}
|
|
}
|
|
}
|
|
|
|
return $rules;
|
|
}
|
|
|
|
/** A web address or a path of the site. Never `javascript:` and its kin. */
|
|
public const ADDRESS = '#^(/(?!/)|https?://)[^\s<>"\']*$#i';
|
|
|
|
/**
|
|
* What is stored: only the known keys, in the type of the field, the default where nothing is given.
|
|
*
|
|
* @param array<string, array<string, mixed>> $fields normalized
|
|
* @param array<array-key, mixed> $input
|
|
* @return array<string, mixed>
|
|
*/
|
|
public static function clean(array $fields, array $input): array
|
|
{
|
|
$out = [];
|
|
|
|
foreach ($fields as $key => $field) {
|
|
$value = array_key_exists($key, $input) ? $input[$key] : $field['default'];
|
|
|
|
$out[$key] = match ($field['type']) {
|
|
'toggle' => filter_var($value, FILTER_VALIDATE_BOOLEAN),
|
|
'number' => $value === null || $value === '' ? null : $value + 0,
|
|
// No date is no date: an empty text in a date column is an error on a strict database, and it is not what was meant.
|
|
'date' => $value === null || $value === '' ? null : (is_scalar($value) ? trim((string) $value) : null),
|
|
'select' => $field['source'] !== null && ($value === null || $value === '') ? null : (is_scalar($value) ? trim((string) $value) : ''),
|
|
'list', 'media_list' => self::strings($value),
|
|
'repeater' => self::cleanItems($field['items'], $value),
|
|
default => $value === null ? '' : (is_scalar($value) ? trim((string) $value) : ''),
|
|
};
|
|
}
|
|
|
|
// An address part that was left empty is made of the field it follows.
|
|
foreach ($fields as $key => $field) {
|
|
if ($field['type'] === 'slug' && $out[$key] === '' && $field['from'] !== null && is_string($out[$field['from']] ?? null)) {
|
|
$out[$key] = Str::slug($out[$field['from']]);
|
|
}
|
|
}
|
|
|
|
return $out;
|
|
}
|
|
|
|
/**
|
|
* The stored values over the defaults, for the screens and for the public site.
|
|
*
|
|
* @param array<string, array<string, mixed>> $fields normalized
|
|
* @param array<array-key, mixed> $stored
|
|
* @return array<string, mixed>
|
|
*/
|
|
public static function values(array $fields, array $stored): array
|
|
{
|
|
$out = [];
|
|
|
|
foreach ($fields as $key => $field) {
|
|
$out[$key] = array_key_exists($key, $stored) ? $stored[$key] : $field['default'];
|
|
}
|
|
|
|
return $out;
|
|
}
|
|
|
|
/**
|
|
* The options of a select: the fixed ones, or the rows of the table of the site it is made from (value => label).
|
|
*
|
|
* @param array<string, mixed> $field normalized
|
|
* @return array<string, string>
|
|
*/
|
|
public static function optionsOf(array $field): array
|
|
{
|
|
$source = $field['source'] ?? null;
|
|
|
|
if ($source === null) {
|
|
return $field['options'];
|
|
}
|
|
|
|
return $source['model']::query()->orderBy($source['label'])->pluck($source['label'], $source['value'])->mapWithKeys(fn ($label, $value) => [(string) $value => (string) $label])->all();
|
|
}
|
|
|
|
/**
|
|
* The fields with the options of a table of the site filled in, as the screens need them.
|
|
*
|
|
* @param array<string, array<string, mixed>> $fields normalized
|
|
* @return list<array<string, mixed>>
|
|
*/
|
|
public static function described(array $fields): array
|
|
{
|
|
return array_values(array_map(fn (array $field) => $field['source'] === null ? $field : [...$field, 'options' => self::optionsOf($field)], $fields));
|
|
}
|
|
|
|
/** @return ?array{model: class-string<Eloquent>, label: string, value: string} */
|
|
private static function source(mixed $source): ?array
|
|
{
|
|
if (! is_array($source) || ! is_string($source['model'] ?? null) || ! is_subclass_of($source['model'], Eloquent::class)) {
|
|
return null;
|
|
}
|
|
|
|
$label = (string) ($source['label'] ?? 'name');
|
|
$value = (string) ($source['value'] ?? 'id');
|
|
|
|
return preg_match('/^[a-z_][a-z0-9_]*$/i', $label.$value) === 1 ? ['model' => $source['model'], 'label' => $label, 'value' => $value] : null;
|
|
}
|
|
|
|
/**
|
|
* @param array<array-key, mixed> $items
|
|
* @return array<string, array<string, mixed>>
|
|
*/
|
|
private static function normalizeItems(array $items): array
|
|
{
|
|
$fields = array_filter(self::normalize($items), fn (array $field) => in_array($field['type'], self::ITEM_TYPES, true));
|
|
|
|
return $fields;
|
|
}
|
|
|
|
/**
|
|
* One of the words the simple face has of its own (`simple.label`, `simple.help`), or null.
|
|
*
|
|
* @param array<string, mixed> $definition
|
|
*/
|
|
public static function simpleText(array $definition, string $part): ?string
|
|
{
|
|
$text = is_array($definition['simple'] ?? null) ? ($definition['simple'][$part] ?? null) : null;
|
|
|
|
return is_string($text) && trim($text) !== '' ? trim($text) : null;
|
|
}
|
|
|
|
/**
|
|
* A list of short texts: an array, or a text with one per line; empty ones are dropped.
|
|
*
|
|
* @return list<string>
|
|
*/
|
|
private static function strings(mixed $value): array
|
|
{
|
|
$value = is_string($value) ? preg_split('/\R/u', $value) : (array) $value;
|
|
|
|
return array_values(array_filter(array_map(fn ($item) => is_scalar($item) ? trim((string) $item) : '', $value ?: []), fn ($item) => $item !== ''));
|
|
}
|
|
|
|
/**
|
|
* @param array<string, array<string, mixed>> $items normalized
|
|
* @return list<array<string, string>>
|
|
*/
|
|
private static function cleanItems(array $items, mixed $value): array
|
|
{
|
|
$out = [];
|
|
|
|
foreach (is_array($value) ? $value : [] as $item) {
|
|
$clean = self::clean($items, is_array($item) ? $item : []);
|
|
|
|
if (array_filter($clean, fn ($part) => $part !== '') !== []) {
|
|
$out[] = $clean;
|
|
}
|
|
}
|
|
|
|
return $out;
|
|
}
|
|
|
|
private static function empty(string $type): mixed
|
|
{
|
|
return match ($type) {
|
|
'toggle' => false,
|
|
'number' => null,
|
|
'list', 'media_list', 'repeater' => [],
|
|
default => '',
|
|
};
|
|
}
|
|
}
|