> */ private static array $extra = []; /** @param array $definition see `Blocks\CoreTypes` */ public static function register(string $key, array $definition): void { self::$extra[$key] = $definition; } public static function forgetRegistered(): void { self::$extra = []; } /** The choices of every style option: what ships, over which the site sets its own. @return array> */ public static function tokens(): array { $out = CoreTypes::tokens(); foreach ((array) config('manager.blocks.tokens', []) as $name => $choices) { if (is_string($name) && is_array($choices) && $choices !== []) { $out[$name] = array_map('strval', $choices); } } return $out; } /** * Every block type that is available now: a type of a feature that is off is not there. * * @return array, resolves: ?string, fields: array>}> */ public static function types(): array { $definitions = array_replace(CoreTypes::all(), (array) config('manager.blocks.types', []), self::$extra); $tokens = self::tokens(); $out = []; foreach ($definitions as $key => $definition) { if (! is_string($key) || ! preg_match('/^[a-z][a-z0-9_]{0,39}$/', $key) || ! is_array($definition)) { continue; } if (isset($definition['feature']) && ! Features::on((string) $definition['feature'])) { continue; } $fields = (array) ($definition['fields'] ?? []); // A block that shows the records of a list offers the lists the site has. if (($definition['resolves'] ?? null) === 'list' && isset($fields['source'])) { $fields['source']['options'] = array_map(fn (array $resource) => $resource['label'], Resources::all()); } $out[$key] = [ 'key' => $key, 'label' => (string) ($definition['label'] ?? ucfirst(str_replace('_', ' ', $key))), 'simple_label' => Fields::simpleText($definition, 'label'), 'group' => (string) ($definition['group'] ?? 'Content'), 'icon' => (string) ($definition['icon'] ?? $key), 'style' => array_values(array_filter((array) ($definition['style'] ?? []), fn ($name) => is_string($name) && isset($tokens[$name]))), 'resolves' => isset($definition['resolves']) ? (string) $definition['resolves'] : null, 'fields' => Fields::normalize($fields), ]; } return $out; } /** * What the screen needs to offer the types (the fields as the form builds them, and the style choices). * * @param ?list $allowed null: every type * @return list> */ public static function catalogue(?array $allowed = null): array { $tokens = self::tokens(); $out = []; foreach (self::types() as $key => $type) { if ($allowed !== null && ! in_array($key, $allowed, true)) { continue; } $out[] = [ 'key' => $key, 'label' => $type['label'], 'simple_label' => $type['simple_label'], 'group' => $type['group'], 'icon' => $type['icon'], 'fields' => Fields::described($type['fields']), 'style' => array_map(fn (string $name) => ['key' => $name, 'options' => $tokens[$name], 'default' => array_key_first($tokens[$name])], $type['style']), ]; } return $out; } /** * What may be saved: unknown types and types a page does not allow are dropped, the data is cleaned by the fields of the type, the * style options are kept to the choices there are, and every block gets an id. * * @param array $input * @param ?list $allowed * @return list, style: array, hidden: bool}> */ public static function clean(array $input, ?array $allowed = null): array { $types = self::types(); $max = max(1, (int) config('manager.blocks.max', 100)); $out = []; foreach ($input as $block) { $type = is_array($block) && is_string($block['type'] ?? null) ? $block['type'] : null; if ($type === null || ! isset($types[$type]) || ($allowed !== null && ! in_array($type, $allowed, true))) { continue; } $out[] = [ 'id' => self::id($block['id'] ?? null), 'type' => $type, 'data' => Fields::clean($types[$type]['fields'], (array) ($block['data'] ?? [])), 'style' => self::style($types[$type], (array) ($block['style'] ?? [])), 'hidden' => filter_var($block['hidden'] ?? false, FILTER_VALIDATE_BOOLEAN), ]; if (count($out) >= $max) { break; } } return $out; } /** * Validation rules for the blocks of a request, keyed `blocks`, `blocks..…`. * * @param array $input * @param ?list $allowed * @return array */ public static function rules(array $input, ?array $allowed = null, bool $bindings = false): array { $types = self::types(); $rules = [ 'blocks' => ['nullable', 'array', 'max:'.max(1, (int) config('manager.blocks.max', 100))], 'blocks.*' => ['array'], 'blocks.*.type' => ['required', 'string', 'max:40'], 'blocks.*.id' => ['nullable', 'string', 'max:40'], 'blocks.*.hidden' => ['boolean'], 'blocks.*.style' => ['nullable', 'array'], 'blocks.*.data' => ['nullable', 'array'], ]; foreach ($input as $index => $block) { $type = is_array($block) && is_string($block['type'] ?? null) ? $block['type'] : null; if ($type !== null && isset($types[$type]) && ($allowed === null || in_array($type, $allowed, true))) { $fieldRules = Fields::rules($types[$type]['fields'], "blocks.{$index}.data."); $rules = [...$rules, ...($bindings ? self::allowBindings($fieldRules) : $fieldRules)]; } } return $rules; } /** * For a page layout: an address or picture may also begin with `{record.}` (the value is checked when it is drawn). * * @param array> $rules * @return array> */ private static function allowBindings(array $rules): array { $address = 'regex:'.Fields::ADDRESS; $binding = '#^\{record\.[a-z][a-z0-9_]*\}[^\s<>"\']*$#i'; return array_map(fn (array $list) => array_map(fn ($rule) => $rule === $address ? function (string $attribute, mixed $value, \Closure $fail) use ($binding): void { if (! is_string($value) || (preg_match(Fields::ADDRESS, $value) !== 1 && preg_match($binding, $value) !== 1)) { $fail(__('The :attribute must be a web address, a path of the site or {record.}.', ['attribute' => $attribute])); } } : $rule, $list), $rules); } /** * The stored blocks as the editor shows them: every block of a known type, hidden ones too, every field with its value. * * @param array $stored * @return list, style: array, hidden: bool}> */ public static function forEditor(array $stored): array { $types = self::types(); $out = []; foreach ($stored as $block) { $type = is_array($block) && is_string($block['type'] ?? null) ? $block['type'] : null; if ($type === null || ! isset($types[$type])) { continue; } $out[] = [ 'id' => self::id($block['id'] ?? null), 'type' => $type, 'data' => Fields::values($types[$type]['fields'], (array) ($block['data'] ?? [])), 'style' => self::style($types[$type], (array) ($block['style'] ?? [])), 'hidden' => (bool) ($block['hidden'] ?? false), ]; } return $out; } /** * What the public site draws for a page: the visible blocks in order, each with its data (defaults filled in) and style, and, for a * block that shows a list, the records of that list. A block of a feature that is off, or of a list that is gone, is left out. * * @return list, style: array, items?: list>}> */ public static function for(string $slug): array { // A person editing the page sees the blocks of the preview they asked for, not the saved ones. $saved = Page::query()->where('slug', $slug)->first()?->blocks; $stored = BlockPreview::current($slug) ?? (is_array($saved) ? $saved : []); return self::render($stored, null); } /** * The page of one record (a service, a project): the blocks of the page layout of its list (`manager.resources..template`), * with `{record.}` in the text, address and picture fields filled in from the record, as `for()` gives them. A `cards` block * can show only what belongs to the record (`match_list` = `match_record`) and leave the record itself out. Empty when the list * has no page layout, is off, or the record is not active. * * @param Eloquent|array{id: mixed, values: array} $record a model of the list, or `Resources::row()` * @return list, style: array, items?: list>}> */ public static function forRecord(string $resource, Eloquent|array $record): array { $definition = Resources::find($resource); if ($definition === null || $definition['template'] === false) { return []; } $row = $record instanceof Eloquent ? Resources::row($definition, $record) : $record; if (! ($row['values']['is_active'] ?? true)) { return []; } $template = BlockTemplate::query()->where('resource', $resource)->first(); $allowed = self::templateTypes($resource); return self::render(is_array($template?->blocks) ? $template->blocks : [], ['resource' => $resource, 'row' => $row], $allowed); } /** * The block types the page layout of a list may use (`manager.resources..template`: `true` for all, or a list). Empty without one. * * @return list */ public static function templateTypes(string $resource): array { $allowed = Resources::find($resource)['template'] ?? false; $known = array_keys(self::types()); if ($allowed === true) { return $known; } return is_array($allowed) ? array_values(array_intersect($known, $allowed)) : []; } /** * @param array $stored * @param ?array{resource: string, row: array{id: mixed, values: array}} $context the record a page layout is drawn for * @param ?list $allowed * @return list> */ private static function render(array $stored, ?array $context, ?array $allowed = null): array { $types = self::types(); $out = []; foreach (self::forEditor($stored) as $block) { if ($block['hidden'] || ($allowed !== null && ! in_array($block['type'], $allowed, true))) { continue; } $fields = $types[$block['type']]['fields']; $data = $context === null ? $block['data'] : self::bind($fields, $block['data'], $context['row']); $entry = ['id' => $block['id'], 'type' => $block['type'], 'data' => self::withHtml($fields, $data), 'style' => $block['style']]; if ($types[$block['type']]['resolves'] === 'list') { $items = self::items($data, $context); if ($items === null) { continue; } $entry['items'] = $items; } $out[] = $entry; } return $out; } /** * `{record.}` in the text, address and picture fields of a block (also in a list or a repeater) becomes the value of that * field of the record, or nothing when the record has no such field. The value is text like any other: it is escaped when it is drawn, * Markdown cannot carry HTML, and an address or picture that comes out unsafe becomes `#` (an address) or nothing (a picture). * * @param array> $fields normalized * @param array $data * @param array{id: mixed, values: array} $row * @return array */ private static function bind(array $fields, array $data, array $row): array { $values = ['id' => $row['id']] + $row['values']; $fill = function (string $text) use ($values): string { return (string) preg_replace_callback('/\{record\.([a-z][a-z0-9_]*)\}/', function (array $match) use ($values): string { $value = $values[$match[1]] ?? null; return is_scalar($value) ? (is_bool($value) ? ($value ? '1' : '') : (string) $value) : ''; }, $text); }; foreach ($fields as $key => $field) { $value = $data[$key] ?? null; switch ($field['type']) { case 'text': case 'textarea': case 'markdown': $data[$key] = is_string($value) ? $fill($value) : $value; break; case 'url': case 'media': if (is_string($value) && str_contains($value, '{record.')) { $address = self::safeUrl($fill($value)); $data[$key] = $address === '#' && $field['type'] === 'media' ? '' : $address; } break; case 'list': case 'media_list': $data[$key] = is_array($value) ? array_map(function ($item) use ($fill, $field) { if (! is_string($item) || ! str_contains($item, '{record.')) { return $item; } $filled = $fill($item); return $field['type'] === 'media_list' ? (self::safeUrl($filled) === '#' ? '' : $filled) : $filled; }, $value) : $value; break; case 'repeater': $data[$key] = is_array($value) ? array_map(fn ($row2) => is_array($row2) ? self::bind($field['items'], $row2, $row) : $row2, $value) : $value; break; } } return $data; } /** * Markdown fields come with their safe HTML next to them: `body` gets a `body_html`. Raw HTML in the text is escaped by `Markdown`, so a * frontend may print `*_html` as it is and must print everything else as text. The same goes for a repeater with a markdown field. * * @param array> $fields normalized * @param array $data * @return array */ public static function withHtml(array $fields, array $data): array { foreach ($fields as $key => $field) { if ($field['type'] === 'markdown') { $data[$key.'_html'] = Markdown::toHtml((string) ($data[$key] ?? '')); } elseif ($field['type'] === 'repeater' && is_array($data[$key] ?? null)) { $data[$key] = array_map(fn ($row) => is_array($row) ? self::withHtml($field['items'], $row) : $row, $data[$key]); } } return $data; } /** The view that draws a block type: one of the site (`resources/views/blocks/.blade.php`), else the package's. Null when there is none. */ public static function view(string $type): ?string { if (preg_match('/^[a-z][a-z0-9_]{0,39}$/', $type) !== 1) { return null; } foreach (["blocks.{$type}", "manager::blocks.{$type}"] as $view) { if (view()->exists($view)) { return $view; } } return null; } /** CSS classes for the style options of a block: `mb--background-dark mb--width-wide`. */ public static function classes(array $style): string { $classes = []; foreach ($style as $name => $value) { $classes[] = 'mb--'.preg_replace('/[^a-z0-9_-]/i', '', (string) $name).'-'.preg_replace('/[^a-z0-9_-]/i', '', (string) $value); } return implode(' ', $classes); } /** An address that is safe in an `href` or `src`: http(s), a path, `mailto:`, `tel:` or an anchor; anything else becomes `#`. */ public static function safeUrl(mixed $url): string { $url = is_string($url) ? trim($url) : ''; // No quote, bracket, backslash or space either: the address may end up in an attribute or in a CSS `url()`. return preg_match('~^(https?://|/(?!/)|#|mailto:|tel:)~i', $url) === 1 && preg_match('~[\s"\'()<>\\\\]~', $url) !== 1 ? $url : '#'; } /** * Structured data for search engines that the blocks of a page give: a `faq` block is a `FAQPage`. Print each as JSON in * `