rafalmasiarek / dashboard-kit-addon-content
Content type management addon for dashboard-kit. Define content types via blueprints in admin_modules, auto-generates admin CRUD, and provides ContentRepository for public module access.
Package info
github.com/rafalmasiarek/php-dashboard-kit-addon-content
pkg:composer/rafalmasiarek/dashboard-kit-addon-content
Requires
- php: >=8.2
- league/commonmark: ^2.0
- rafalmasiarek/dashboard-kit: ^4.1.1
- slim/slim: ^4.0
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-17 23:37:26 UTC
README
Blueprint-driven content type addon for rafalmasiarek/dashboard-kit.
Define content types via a content blueprint in any admin module β the addon auto-creates the database table, generates admin CRUD routes, and provides a ContentRepository for reading records in front-end modules.
License
Business Source License 1.1.
Source available; commercial use restricted until 2099-01-01.
See LICENSE for full details.
For alternative licensing, contact us.
Authors
Requirements
- PHP 8.2+
rafalmasiarek/dashboard-kit: *league/commonmark: ^2.0
Installation
composer require rafalmasiarek/dashboard-kit-addon-content
The addon is auto-discovered by Dashboard::create() when the package is installed. No explicit register() call is needed.
Blueprint format
Add a content key to any admin module's module.php:
return [ 'title' => 'Pages', 'icon' => 'π', 'content' => [ 'table' => 'pages', // optional; omit to auto-create content_{slug} 'list' => ['title', 'status'], // columns shown in the admin list view 'fields' => [ 'title' => ['type' => 'text', 'label' => 'Title', 'required' => true], 'body' => ['type' => 'richtext', 'label' => 'Content'], 'status' => ['type' => 'select', 'label' => 'Status', 'options' => ['draft', 'published']], ], ], ];
Field types
| Type | Description |
|---|---|
text |
Single-line text input |
richtext |
WYSIWYG editor (Quill) |
select |
Dropdown; requires options key |
date |
Date picker |
number |
Numeric input |
toggle |
Boolean checkbox |
All fields accept an optional width key (Bootstrap column 1β12).
Hooks
'hooks' => [ 'before_create' => function (array $data): array { return $data; }, 'before_update' => function (array $data, array $existing): array { return $data; }, 'after_create' => function (int $id, array $data): void {}, 'after_update' => function (int $id, array $data): void {}, 'before_delete' => function (int $id, array $existing): void {}, 'after_delete' => function (int $id): void {}, ],
Admin routes
All routes are protected by Auth + CSRF + admin Role middleware.
| Route | Description |
|---|---|
GET {prefix}/{slug} |
List records |
GET {prefix}/{slug}/new |
Create form |
POST {prefix}/{slug} |
Save new record |
GET {prefix}/{slug}/{id}/edit |
Edit form |
POST {prefix}/{slug}/{id} |
Save updated record |
POST {prefix}/{slug}/{id}/delete |
Delete record |
Reading records in modules
use rafalmasiarek\DashboardKitContent\ContentRepository; $repo = $container->get(ContentRepository::class); $all = $repo->findAll('pages'); $one = $repo->findOne('pages', $id); $bySlug = $repo->findBySlug('pages', 'about');
Twig filter
{{ page.body|content_render|raw }}
Renders Markdown with HTML passthrough and {.class} attribute syntax (league/commonmark).
Auto-created tables
When table is omitted, the addon creates content_{slug} with:
idβINT UNSIGNED AUTO_INCREMENT PRIMARY KEYslugβVARCHAR(255) UNIQUEcreated_at,updated_atβ timestamps
Adding a new field to the blueprint automatically adds the column via ALTER TABLE on next boot.
Index
Classes
ContentAddonβrafalmasiarek\DashboardKitContentContentRepositoryβrafalmasiarek\DashboardKitContentContentExtensionβrafalmasiarek\DashboardKitContent\Twig
ContentAddon
final class β rafalmasiarek\DashboardKitContent\ContentAddon Β· source
Wires the content management system into a Dashboard application.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
register() |
public static | void |
Register the content addon. |
buildTableSchema() |
private static | array<string, mixed> |
Translates content field definitions into a dashboard-kit table schema definition. Always prepends id (INT UNSIGNED AUTO_INCREMENT PK) and slug (VARCHAR 255). Enables timestamps so that updated_at is auto-injected by ModuleSchemaBuilder. |
ensureSlugUnique() |
private static | void |
Ensures a UNIQUE index exists on the slug column of a content table. Checked via INFORMATION_SCHEMA on MySQL and CREATE UNIQUE INDEX IF NOT EXISTS on SQLite. Fully idempotent β safe to call on every boot. |
registerUploadRoute() |
private static | void |
Register the built-in image upload endpoint for the richtext editor. Accepts a multipart/form-data POST with a 'file' field. Validates the real MIME type via finfo (not the client-supplied header). Saves to $uploadDir and returns JSON {"url": "..."} on success or {"error": "..."} on failure. The filename is "{8-char sha1}_{sanitized_basename}.{ext}" β deterministic, so re-uploading the same file produces the same name without duplicates. |
registerRoutes() |
private static | void |
Register admin CRUD routes for one content type. All routes are protected by AuthMiddleware, CsrfMiddleware, and RoleMiddleware restricted to the 'admin' role, mirroring the protection on standard admin routes. |
applyDataHook() |
public static | array<string, mixed> |
Call a before_* hook that returns modified data. When no hook is registered for the given name, returns $data unchanged. |
fireHook() |
public static | void |
Call an after_* hook that returns void. Does nothing when no hook is registered for the given name. |
extractData() |
public static | array<string, mixed> |
Extract and sanitize field values from a POST body. Toggle fields are coerced to 0/1 (unchecked checkbox sends nothing). Number fields are cast to float or null when empty. Date fields are kept as string or null when empty. All other fields are cast to string. |
slugify() |
public static | string |
Generate a URL-safe slug from an arbitrary string. Lowercases, replaces non-alphanumeric runs with hyphens, and trims edge hyphens. |
defaultListColumns() |
private static | list<string> |
Determine a sensible default set of list columns from field definitions. Picks up to three fields whose types render well in a table (text, select, date, number, toggle). Falls back to all field names when none match. |
register()
ContentAddon register()
public static function register(App $app, ContainerInterface $container, array $config): void
Register the content addon.
| Param | Type | Description |
|---|---|---|
$app |
App |
β |
$container |
ContainerInterface |
β |
$config |
array<string, mixed> |
Optional configuration overrides (unused, reserved for future use). |
buildTableSchema()
ContentAddon buildTableSchema()
private static function buildTableSchema(array $fields): array
Translates content field definitions into a dashboard-kit table schema definition. Always prepends id (INT UNSIGNED AUTO_INCREMENT PK) and slug (VARCHAR 255). Enables timestamps so that updated_at is auto-injected by ModuleSchemaBuilder.
| Param | Type | Description |
|---|---|---|
$fields |
array<string, mixed> |
Content field definitions. |
Returns: array<string, mixed> β Table schema compatible with SchemaStateManager::sync().
ensureSlugUnique()
ContentAddon ensureSlugUnique()
private static function ensureSlugUnique(PDO $pdo, string $table): void
Ensures a UNIQUE index exists on the slug column of a content table. Checked via INFORMATION_SCHEMA on MySQL and CREATE UNIQUE INDEX IF NOT EXISTS on SQLite. Fully idempotent β safe to call on every boot.
| Param | Type | Description |
|---|---|---|
$pdo |
PDO |
Active database connection. |
$table |
string |
Content table name. |
registerUploadRoute()
ContentAddon registerUploadRoute()
private static function registerUploadRoute(App $app, ContainerInterface $container, string $routePath, string $uploadDir, string $uploadPublicPrefix, string $dashboardPrefix): void
Register the built-in image upload endpoint for the richtext editor. Accepts a multipart/form-data POST with a 'file' field. Validates the real MIME type via finfo (not the client-supplied header). Saves to $uploadDir and returns JSON {"url": "..."} on success or {"error": "..."} on failure. The filename is "{8-char sha1}_{sanitized_basename}.{ext}" β deterministic, so re-uploading the same file produces the same name without duplicates.
| Param | Type | Description |
|---|---|---|
$app |
App |
β |
$container |
ContainerInterface |
β |
$routePath |
string |
Slim route path (e.g. '/admin/panel/_upload/image'). |
$uploadDir |
string |
Filesystem directory for uploaded files. |
$uploadPublicPrefix |
string |
URL prefix for serving uploaded files (e.g. '/uploads/images'). |
$dashboardPrefix |
string |
Dashboard URL prefix for RoleMiddleware redirects. |
registerRoutes()
ContentAddon registerRoutes()
private static function registerRoutes(App $app, ContainerInterface $container, string $slug, string $title, string $table, array $fields, array $hooks, array $listColumns, array $grid, string $fullAdminPrefix, string $dashboardPrefix, string $uploadUrl): void
Register admin CRUD routes for one content type. All routes are protected by AuthMiddleware, CsrfMiddleware, and RoleMiddleware restricted to the 'admin' role, mirroring the protection on standard admin routes.
| Param | Type | Description |
|---|---|---|
$app |
App |
β |
$container |
ContainerInterface |
β |
$slug |
string |
Content type slug. |
$title |
string |
Human-readable label. |
$table |
string |
DB table name. |
$fields |
array<string, mixed> |
Field definitions. |
$hooks |
array<string, callable> |
Lifecycle hook callbacks keyed by hook name. |
$listColumns |
list<string> |
Columns to show in the list view. |
$grid |
list<list<string>> |
Grid layout: rows of field name arrays. |
$fullAdminPrefix |
string |
Full URL prefix including base_path, dashboard prefix, and admin prefix. |
$dashboardPrefix |
string |
Full URL prefix including base_path and dashboard prefix only. |
$uploadUrl |
string |
Image upload endpoint URL passed to the richtext editor. |
applyDataHook()
ContentAddon applyDataHook()
public static function applyDataHook(array $hooks, string $name, array $data, mixed $extra): array
Call a before_* hook that returns modified data. When no hook is registered for the given name, returns $data unchanged.
| Param | Type | Description |
|---|---|---|
$hooks |
array<string, callable> |
β |
$name |
string |
Hook name (e.g. 'before_create'). |
$data |
array<string, mixed> |
Data to pass as the first argument. |
$extra |
mixed |
β |
Returns: array<string, mixed>
fireHook()
ContentAddon fireHook()
public static function fireHook(array $hooks, string $name, mixed $args): void
Call an after_* hook that returns void. Does nothing when no hook is registered for the given name.
| Param | Type | Description |
|---|---|---|
$hooks |
array<string, callable> |
β |
$name |
string |
Hook name (e.g. 'after_create'). |
$args |
mixed |
β |
extractData()
ContentAddon extractData()
public static function extractData(array $fields, array $post): array
Extract and sanitize field values from a POST body. Toggle fields are coerced to 0/1 (unchecked checkbox sends nothing). Number fields are cast to float or null when empty. Date fields are kept as string or null when empty. All other fields are cast to string.
| Param | Type | Description |
|---|---|---|
$fields |
array<string, mixed> |
Field definitions. |
$post |
array<string, mixed> |
Raw POST data ($_POST / getParsedBody()). |
Returns: array<string, mixed>
slugify()
ContentAddon slugify()
public static function slugify(string $value): string
Generate a URL-safe slug from an arbitrary string. Lowercases, replaces non-alphanumeric runs with hyphens, and trims edge hyphens.
| Param | Type | Description |
|---|---|---|
$value |
string |
Raw input string. |
Returns: string β URL-safe slug.
defaultListColumns()
ContentAddon defaultListColumns()
private static function defaultListColumns(array $fields): array
Determine a sensible default set of list columns from field definitions. Picks up to three fields whose types render well in a table (text, select, date, number, toggle). Falls back to all field names when none match.
| Param | Type | Description |
|---|---|---|
$fields |
array<string, mixed> |
Field definitions. |
Returns: list<string>
ContentRepository
final class β rafalmasiarek\DashboardKitContent\ContentRepository Β· source
Provides read and write access to content type records. Used both by ContentAddon for admin CRUD and by public modules in modules/ to fetch content for front-end rendering. Built on Model::on() rather than a dedicated Model subclass, since each content type's table name is only known at runtime (admin-defined blueprints) β there is no fixed set of PHP classes to extend. Connects via Model's own connection resolver, so no PDO dependency of its own. All table names and column names are validated to contain only alphanumeric characters and underscores before use in queries.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
findAll() |
public | array<int, array<string, mixed>> |
Return all records from a content table ordered by creation date descending. |
findOne() |
public | array<string, mixed>|null |
Return a single record by primary key. |
findBySlug() |
public | array<string, mixed>|null |
Return a single record by slug. |
create() |
public | int |
Insert a new content record. |
update() |
public | void |
Update an existing content record. |
delete() |
public | void |
Delete a content record by primary key. |
assertSafeIdentifier() |
private | void |
Assert that a DB identifier contains only safe characters. |
findAll()
ContentRepository findAll()
public function findAll(string $table, int $limit, int $offset): array
Return all records from a content table ordered by creation date descending.
| Param | Type | Description |
|---|---|---|
$table |
string |
Content table name. |
$limit |
int |
Maximum number of records to return. |
$offset |
int |
Number of records to skip. |
Returns: array<int, array<string, mixed>>
findOne()
ContentRepository findOne()
public function findOne(string $table, int $id): ?array
Return a single record by primary key.
| Param | Type | Description |
|---|---|---|
$table |
string |
Content table name. |
$id |
int |
Record primary key. |
Returns: array<string, mixed>\|null β Null when not found.
findBySlug()
ContentRepository findBySlug()
public function findBySlug(string $table, string $slug): ?array
Return a single record by slug.
| Param | Type | Description |
|---|---|---|
$table |
string |
Content table name. |
$slug |
string |
URL-safe slug value. |
Returns: array<string, mixed>\|null β Null when not found.
create()
ContentRepository create()
public function create(string $table, array $data): int
Insert a new content record.
| Param | Type | Description |
|---|---|---|
$table |
string |
Content table name. |
$data |
array<string, mixed> |
Column name β value map. |
Returns: int β Inserted row ID.
update()
ContentRepository update()
public function update(string $table, int $id, array $data): void
Update an existing content record.
| Param | Type | Description |
|---|---|---|
$table |
string |
Content table name. |
$id |
int |
Record primary key. |
$data |
array<string, mixed> |
Column name β value map. |
delete()
ContentRepository delete()
public function delete(string $table, int $id): void
Delete a content record by primary key.
| Param | Type | Description |
|---|---|---|
$table |
string |
Content table name. |
$id |
int |
Record primary key. |
assertSafeIdentifier()
ContentRepository assertSafeIdentifier()
private function assertSafeIdentifier(string $name): void
Assert that a DB identifier contains only safe characters.
| Param | Type | Description |
|---|---|---|
$name |
string |
β |
| Throws | When |
|---|---|
\InvalidArgumentException |
When unsafe characters are detected. |
ContentExtension
final class β rafalmasiarek\DashboardKitContent\Twig\ContentExtension Β· source
Provides the content_render Twig filter for rendering richtext fields. Uses league/commonmark with: - HTML passthrough ('html_input' => 'allow') so raw HTML is preserved. - AttributesExtension so {.class #id} syntax adds CSS classes to elements. Usage in templates: {{ page.body|content_render|raw }}
extends AbstractExtension
Depends on: MarkdownConverter
| Property | Type | Visibility | Description |
|---|---|---|---|
$converter |
MarkdownConverter|null |
private | Lazily-initialized converter instance. |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
getFilters() |
public | list<TwigFilter> |
Return the Twig filters provided by this extension. |
render() |
public | string |
Convert a richtext field value to HTML. Supports Markdown syntax, raw HTML blocks, and {.class} attribute notation. Returns an empty string for null or empty input. |
getFilters()
ContentExtension getFilters()
public function getFilters(): array
Return the Twig filters provided by this extension.
Returns: list<TwigFilter>
render()
ContentExtension render()
public function render(?string $content): string
Convert a richtext field value to HTML. Supports Markdown syntax, raw HTML blocks, and {.class} attribute notation. Returns an empty string for null or empty input.
| Param | Type | Description |
|---|---|---|
$content |
string|null |
Raw richtext content from the database. |
Returns: string β Rendered HTML.