Skip to content
trkPublic

About

Config-driven dynamic field builder and JSON-backed storage module for ProcessWire CMS/CMF.

Topics

Resources

Stars

12 stars

Watchers

4 watching

Forks

Latest commit

 

History

80 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Mystique for ProcessWire

Documentation: docs.totoglu.com/mystique/

Config-driven dynamic field builder and JSON-backed storage module for ProcessWire CMS/CMF. Define structured subfield sets in static PHP arrays, dynamic PHP Closures, JSON config files, reusable @fieldset: partials, or inline field JSON — with native ProcessWire Page, Pageimage, Pagefile, multi-language, Repeater/RepeaterMatrix/Tab/AJAX support, and type-aware JSON selectors.

Requirements

  • PHP >= 8.4
  • ProcessWire >= 3.0.210
  • Bundled companion modules: FieldtypeMystique and InputfieldMystique

Installation

Install via Composer:

composer require trk/mystique

Then install the module through ProcessWire CLI or the Admin Modules screen:

php vendor/bin/wire module:install --name=Mystique

Installing Mystique automatically installs FieldtypeMystique and InputfieldMystique.

Quick Start

  1. Create a resource file in site/templates/configs/Mystique.seo-fields.php:
<?php

declare(strict_types=1);

namespace ProcessWire;

return [
	'name' => 'seo-fields',
	'title' => __('SEO Fields', __FILE__),
	'fields' => [
		'window_title' => [
			'label' => __('Window Title', __FILE__),
			'type' => Mystique::TEXT,
			'useLanguages' => true,
			'required' => true,
			'attr' => [
				'placeholder' => __('Enter a window title', __FILE__),
			],
		],
		'navigation_title' => [
			'label' => __('Navigation Title', __FILE__),
			'type' => Mystique::TEXT,
			'useLanguages' => true,
			'showIf' => [
				'window_title' => "!=''",
			],
			'requiredIf' => 'show_on_nav=1',
		],
		'og_image' => [
			'label' => __('Social Share Image', __FILE__),
			'type' => Mystique::IMAGE,
			'maxFiles' => 1,
			'extensions' => 'jpg jpeg png webp',
		],
		'page_type' => [
			'label' => __('Page Type', __FILE__),
			'type' => Mystique::SELECT,
			'options' => [
				'basic' => __('Basic Page', __FILE__),
				'gallery' => __('Gallery', __FILE__),
				'blog' => __('Blog', __FILE__),
			],
		],
		'show_on_nav' => [
			'label' => __('Display on Navigation', __FILE__),
			'type' => Mystique::CHECKBOX,
		],
	],
];
  1. Create a ProcessWire field of type Mystique (FieldtypeMystique), select SEO Fields (templates) under Input > Resource, and add it to a template.

  2. Read native ProcessWire values, update programmatically, and query with selectors in templates:

<?php

declare(strict_types=1);

namespace ProcessWire;

/** @var \Totoglu\Mystique\MystiqueValue $seo */
$seo = $page->seo_fields;

echo $sanitizer->entities((string) $seo->getLanguageValue('window_title'));

// Native Pageimage (when maxFiles=1 and $page->of(true)) or Pageimages
if ($seo->og_image instanceof Pageimage) {
	echo $seo->og_image->size(1200, 630)->url;
}

// Programmatic update
$page->of(false);
$page->setAndSave('seo_fields', [
	'page_type' => 'gallery',
	'show_on_nav' => 1,
]);

// Type-aware ProcessWire selectors
$galleryPages = $pages->find('template=page, seo_fields.page_type=gallery, seo_fields.show_on_nav=1, limit=25');

Resource Formats & Discovery

Mystique automatically discovers config files matching Mystique.<name>.php and Mystique.<name>.json in:

  • site/templates/configs/ (caller: templates.<name>)
  • site/modules/<ModuleName>/configs/ (caller: <modulename>.<name>)

Four schema sources are supported:

  1. Static PHP Array (Mystique.<name>.php) — fast, translatable, and cached via filemtime + filesize.
  2. Dynamic PHP Closure (Mystique.<name>.php) — evaluated live with page, field, and current value context (never cached across pages):
<?php

declare(strict_types=1);

namespace ProcessWire;

use Totoglu\Mystique\MystiqueValue;

return static function (?Page $page = null, ?Field $field = null, ?MystiqueValue $value = null): array {
	$fields = [
		'mode' => [
			'label' => __('Mode', __FILE__),
			'type' => Mystique::SELECT,
			'options' => ['standard' => 'Standard', 'advanced' => 'Advanced'],
			'defaultValue' => 'standard',
		],
	];

	if ($page instanceof Page && $page->id > 0 && $page->template->name === 'article') {
		$fields['subtitle'] = [
			'label' => __('Article Subtitle', __FILE__),
			'type' => Mystique::TEXT,
		];
	}

	return [
		'name' => 'dynamic-example',
		'title' => __('Dynamic Example', __FILE__),
		'fields' => $fields,
	];
};
  1. JSON Config File (Mystique.<name>.json) — static JSON schema discovered alongside PHP configs and cached by filemtime + filesize.
  2. Inline Field JSON (useJson + jsonString) — store the JSON schema directly in the field's Input settings (supports @fieldset: imports too).

Supported Inputfield Constants & type_fallback

You can specify any installed ProcessWire Inputfield by short name ('text', 'image', 'page'), full class name ('InputfieldText'), or one of the 23 Mystique::* constants:

Category Constants
Layout & Markup Mystique::FIELDSET, Mystique::TAB, Mystique::MARKUP
Text & Rich Text Mystique::TEXT, Mystique::TEXTAREA, Mystique::TINYMCE, Mystique::CKEDITOR
Boolean & Choice Mystique::CHECKBOX, Mystique::CHECKBOXES, Mystique::RADIOS, Mystique::TOGGLE, Mystique::TOGGLE_CHECKBOX, Mystique::SELECT, Mystique::ASM_SELECT
Numeric & Date Mystique::INTEGER, Mystique::FLOAT, Mystique::DATETIME
Relations & Files Mystique::PAGE, Mystique::IMAGE, Mystique::FILE
Visual Pickers Mystique::ICON, Mystique::ICON_PICKER, Mystique::COLOR

Use type_fallback to gracefully degrade when an optional Inputfield module is not installed:

'body' => [
	'label' => __('Body', __FILE__),
	'type' => Mystique::TINYMCE,
	'type_fallback' => Mystique::TEXTAREA,
],

Reusable Fieldsets (@fieldset:)

Define reusable fieldsets in site/templates/configs/fieldsets/*.{php,json} or site/modules/*/configs/fieldsets/*.{php,json} (or reference any existing Mystique resource):

<?php

declare(strict_types=1);

namespace ProcessWire;

return [
	'title' => __('Checkout Settings', __FILE__),
	'fields' => [
		// 1. Direct string shorthand (leading "_" auto-prefixes children with "billing_")
		'billing' => '@fieldset:_address',

		// 2. Map import with display mode ('fieldset' | 'tab' | 'inline'), prefix, exclude, and overrides
		'shipping' => [
			'import' => '@fieldset:address',
			'type' => 'tab',
			'label' => __('Shipping Address', __FILE__),
			'prefix' => true,
			'exclude' => ['tax_id'],
			'overrides' => [
				'city' => ['columnWidth' => 50, 'required' => true],
			],
		],

		// 3. Container children reference
		'company_address' => [
			'type' => Mystique::FIELDSET,
			'label' => __('Company Address', __FILE__),
			'children' => '@fieldset:_address',
		],
	],
];

Internal showIf and requiredIf sibling references inside prefixed fieldsets are automatically rewritten with the active prefix, and circular @fieldset: imports are rejected with WireException.

Inner Tabs, Repeaters, RepeaterMatrix & AJAX Loading

Inner Tabs (Mystique::TAB)

Group subfields into accessible ARIA tabs (role="tablist" / role="tab" / role="tabpanel") that work identically inside standard pages, Repeaters, RepeaterMatrix items, and AJAX-loaded fields:

'fields' => [
	'content_tab' => [
		'label' => __('Content', __FILE__),
		'type' => Mystique::TAB,
		'children' => [
			'headline' => ['label' => __('Headline', __FILE__), 'type' => Mystique::TEXT, 'required' => true],
			'body' => ['label' => __('Body', __FILE__), 'type' => Mystique::TINYMCE, 'type_fallback' => Mystique::TEXTAREA],
		],
	],
	'media_tab' => [
		'label' => __('Media', __FILE__),
		'type' => Mystique::TAB,
		'children' => [
			'hero' => ['label' => __('Hero Image', __FILE__), 'type' => Mystique::IMAGE, 'maxFiles' => 1],
		],
	],
],

Repeater, RepeaterMatrix & AJAX-Collapsed Fields

  • Zero-Item Preloading: RepeaterAssetPreloader hooks InputfieldRepeater::renderReady (and per-type matrix<N> contexts in FieldtypeRepeaterMatrix) so nested Inputfield scripts, styles, and $config->js() settings (InputfieldTinyMCE, InputfieldImage, InputfieldPageAutocomplete, etc.) are ready even when a Repeater starts with 0 items.
  • Repeater AJAX File/Image Uploads: MystiqueFileAjaxHandler automatically intercepts both standard page and Repeater/RepeaterMatrix item drag-and-drop uploads (HTTP_X_FIELDNAME: <field>_repeater<id>_<subfield>).
  • AJAX-Collapsed Support: InputfieldMystique::renderReady() cascades asset preloading to every nested subfield so collapsedYesAjax and collapsedTabAjax fields initialize cleanly when expanded.
  • Template-Context Overrides: hideWrap, useEntityEncode, allowImport, allowExport, useJson, jsonString, and resource are all editable per template context (getConfigAllowContext).

Native ProcessWire Value Types

Subfield Type Output When $page->of(false) Output When $page->of(true)
Mystique::PAGE (derefAsPage=0) PageArray PageArray
Mystique::PAGE (derefAsPage=1) Page|false Page|false
Mystique::PAGE (derefAsPage=2) Page|NullPage Page|NullPage
Mystique::IMAGE (maxFiles=1) Pageimages Pageimage|null
Mystique::IMAGE (maxFiles!=1) Pageimages Pageimages
Mystique::FILE (maxFiles=1) Pagefiles Pagefile|null
Mystique::FILE (maxFiles!=1) Pagefiles Pagefiles
Mystique::DATETIME ISO-8601 (Y-m-d / Y-m-d H:i:s) Formatted via dateOutputFormat

HostPage image and file subfields store files in isolated directories (site/assets/files/mystique/{pageId}/{fieldName}/{subfieldName}/), support native drag-and-drop AJAX uploads (InputfieldFileAjax=1), image variations (size(), webp, focus()), and automatic cleanup/cloning on Pages::deleted, Pages::cloned, and Fields::deleted.

MystiqueValue API Summary

Method Description
$val->get(string $key) / $val->$key Return subfield value as its native ProcessWire runtime type (respecting $page->of() and useEntityEncode).
$val->getLanguageValue(string $key, Language|int|string|null $lang = null) Return localized value with automatic fallback to the default language when empty.
$val->hasValue(string $property): bool Return true if the subfield holds a non-empty value (preserves numeric 0).
$val->label(string $property, ?string $optionValue = null): string Return configured subfield label (or specific select option label).
$val->optionLabel(string $property, string|int $value): string Return display label for a single select/radio/checkboxes option value.
$val->optionLabels(string $property): array Return all [value => label] options for a select-family subfield.
$val->getDataArray(): array / $val->toArray(): array Return raw serializable subfield values without hydrating Page/Pagefiles objects.
$val->getArray(): array Return all values with Page/Pagefiles subfields hydrated.
$val->toJson(bool $pretty = false): string Encode raw serializable subfield values to JSON.
(string) $val Readable key=value summary of stored subfields.

See API.md for full class signatures and method reference.

Multi-Language & Translations

  • Mark any text/textarea/rich-text subfield with 'useLanguages' => true to store per-language values (<key> + <key><langId>) inside the same JSON payload.
  • MystiqueValue::getLanguageValue() and MystiqueQueryEngine automatically fall back to the default language via COALESCE(NULLIF(langVal, ''), defaultVal) when a secondary language translation is empty.
  • Bundled admin UI translation packs are included in languages/ for 6 locales: en, tr, de, fr, es, and ru.

Caching & Schema Synchronization

  • Static PHP-array, JSON, and inline JSON resources (including transitive @fieldset: dependencies) are cached in WireCache (Mystique.Resources), fingerprinted by filemtime + filesize and scoped by active language ID.
  • Any modification to a resource file or an imported @fieldset: file immediately invalidates the cache on the next read.
  • Per-request in-memory schema metadata caching in FieldtypeMystique avoids reconstructing FormManager across bulk $pages->find() wakeups.
  • Dynamic PHP Closure resources are never cached across pages or values and always execute live.
  • ___wakeupValue() and ___sleepValue() synchronize persisted JSON against the live schema so added subfields immediately receive defaults and removed subfields are dropped on save.

Data Migrations & Subfield Renaming

Transactional Subfield Rename

Rename a subfield key (and all per-language variants <old><langId> → <new><langId>) across every persisted row inside a database transaction:

<?php

declare(strict_types=1);

namespace ProcessWire;

/** @var FieldtypeMystique $fieldtype */
$fieldtype = $modules->get('FieldtypeMystique');
$field = $fields->get('seo_fields');

$updatedRows = $fieldtype->renameSubfieldData($field, 'window_title', 'meta_title');

Column Storage Type (dataType)

Switch dataType in field settings between longtext (default, FULLTEXT-indexed), mediumtext, text, and native MySQL json. FieldtypeMystique synchronizes the table schema and FULLTEXT index automatically on save.

Configuration

Setting Type Default Description
resource string '' Resource caller identifier (base.name, e.g. templates.seo-fields).
useJson bool false Load field schema from inline jsonString instead of a config file.
jsonString string '' Inline JSON resource definition used when useJson is enabled.
hideWrap int 0 Hide surrounding Mystique fieldset wrapper, label, description, and notes.
useEntityEncode bool false Auto-HTML-entity-encode plain text subfields when $page->of(true) (HTML/RichText preserved).
dataType string 'longtext' MySQL storage column type (longtext, mediumtext, text, or json).
allowImport bool false Render collapsed JSON import textarea in page editor (1 MiB limit, depth 64).
allowExport bool false Render collapsed JSON export textarea with click-to-select in page editor.

Selectors & Searching

<?php

declare(strict_types=1);

namespace ProcessWire;

$exact = $pages->find('template=page, my_mystique.status=published, limit=25');
$notEqual = $pages->find('template=page, my_mystique.status!=draft, limit=25');
$numeric = $pages->find('template=page, my_mystique.price>=100, my_mystique.price<=500, limit=25');
$multiSelect = $pages->find('template=page, my_mystique.tags=featured, limit=25');
$pageRef = $pages->find('template=page, my_mystique.category=1042, limit=25');
$words = $pages->find('template=page, my_mystique.summary~=dynamic fields, limit=25');
$empty = $pages->find('template=page, my_mystique.subtitle="", limit=25');

FieldtypeMystique::___getSelectorInfo() also exposes every subfield, label, option list, and operator to ProcessWire Lister / InputfieldSelector.

Hooks

  • FieldtypeMystique::wakeupValue(Page $page, Field $field, mixed $value): MystiqueValue
  • FieldtypeMystique::sleepValue(Page $page, Field $field, mixed $value): array
  • FieldtypeMystique::formatValue(Page $page, Field $field, mixed $value): MystiqueValue
  • FieldtypeMystique::markupValue(Page $page, Field $field, mixed $value = null, string $property = ''): string
  • FieldtypeMystique::getSelectorInfo(Field $field, array $data = []): array
  • FieldtypeMystique::getConfigAllowContext(Field $field): array
  • InputfieldMystique::render(): string
  • InputfieldMystique::renderValue(): string
  • InputfieldMystique::processInput(WireInputData $input): InputfieldMystique
  • InputfieldMystique::getConfigInputfields(): InputfieldWrapper
  • InputfieldMystique::getConfigAllowContext(Field $field): array

Security & Permissions

  • Selector & SQL Safety: Subfield identifiers are strictly validated (/^[A-Za-z0-9_][A-Za-z0-9_-]*$/), values use PDO parameter binding, and SubfieldMigrationTools escapes table names and runs subfield renames transactionally.
  • AJAX File Upload Security: MystiqueFileAjaxHandler enforces $user->isLoggedin(), $session->CSRF->hasValidToken(), !$config->demo, $hostPage->editable($field), and ProcessWire's native WireUpload + $sanitizer->validateFile().
  • Page Reference Safety: MystiqueValue::extractPositivePageIds() accepts strictly positive integer IDs and rejects selector-injection payloads.
  • Resource Path Isolation: Config and @fieldset: discovery rejects symlinks and paths resolving outside site/templates/ or site/modules/.
  • Import Payload Limits: JSON imports enforce a 1 MiB byte cap and depth 64.

Backward Compatibility & Upgrading

  • Existing user resource config files (Mystique.*.php / Mystique.*.json), flat JSON database payloads, Mystique::* constants, and template consumer APIs remain 100% compatible.
  • All internal PHP classes use the canonical Totoglu\Mystique namespace (update direct use imports if your code references MystiqueValue or FormManager directly).
  • See API.md for the complete API reference and CHANGELOG.md for release notes.

About

Config-driven dynamic field builder and JSON-backed storage module for ProcessWire CMS/CMF.

Topics

Resources

Stars

12 stars

Watchers

4 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages