The PHP companion to @silarhi/app-js for Symfony.
load_page(), PHP enums and constants as TypeScript modules, and form shapes that check formView() paths when compiling.
load_page(), the Twig function behind thedata-pagelistener;app-js:dump-enums, the PHP enums marked#[EnumToJs]as TypeScript or JavaScript modules;app-js:dump-constants, the public constants of the classes marked#[ConstantsToJs], so a limit lives in one place;app-js:dump-forms, the shape of the form types marked#[FormToJs], forformView<Shape>()to check form paths when compiling.
composer require silarhi/app-js-bundle// config/bundles.php
return [
// ...
Silarhi\AppJsBundle\SilarhiAppJsBundle::class => ['all' => true],
];<div {{ load_page('party', {id: party.id}) }}></div>
<div {{ load_page(['party', 'address']) }}></div>renders the data-page and data-page-params attributes that @silarhi/app-js reads to load the page modules.
use Silarhi\AppJsBundle\Attribute\EnumToJs;
#[EnumToJs]
enum LeaseStatus: string
{
case Draft = 'draft';
case Active = 'active';
}bin/console app-js:dump-enumswrites assets/js/enums/LeaseStatus.ts:
export const DRAFT_NAME = 'Draft'
export const ACTIVE_NAME = 'Active'
const LeaseStatus = Object.freeze({
Draft: 'draft',
Active: 'active',
})
export default LeaseStatusOnly the enums marked #[EnumToJs] are dumped (#[EnumToJs(name: 'Status')] renames the module). Unit enums take
their case names as values.
On Symfony 7.3+, the bundle finds them through autoconfiguration, wherever they live: an enum must be loaded by a
service resource of the application, as the default App\ resource of config/services.yaml loads src/, and not
sit under one of its exclude paths. Symfony 6.4 to 7.2 registers no enum in the container: list their directories in
enums.paths instead (see Configuration).
use Silarhi\AppJsBundle\Attribute\ConstantsToJs;
#[ConstantsToJs]
final class MediaUpload
{
public const MAX_SIZE = 2_000_000; // the #[Assert\File(maxSize: self::MAX_SIZE)] of the class, and the page's text
public const MIME_TYPES = ['image/jpeg', 'image/png'];
private const MAX_PIXELS = 25_000_000; // not dumped
}bin/console app-js:dump-constantswrites assets/js/constants/MediaUpload.ts:
// Generated by app-js:dump-constants from App\Model\MediaUpload, do not edit
export const MAX_SIZE = 2000000
export const MIME_TYPES = Object.freeze(['image/jpeg', 'image/png'])Only the public constants are dumped, in their order: a class keeps out what is not the page's business by making it
private or protected. A value is a scalar, null, an enum case (its value, or its name for a unit enum) or an array
of those: a list becomes a frozen array, a map a frozen object. Any other object fails the dump. #[ConstantsToJs(name: 'Limits')] renames the module. An enum may carry the attribute too: its constants are dumped, not its cases
(#[EnumToJs] does).
The classes are found through autoconfiguration, like the enums: a class must be loaded by a service resource of the
application (the default App\ one loads src/). For a class no resource loads (an excluded src/Entity, for
instance), list its directory in constants.paths (see Configuration).
use Silarhi\AppJsBundle\Attribute\FormToJs;
#[FormToJs]
final class PartyType extends AbstractType
{
// name, address (an AddressType), phones (a collection of PhoneType)
}bin/console app-js:dump-formswrites assets/js/forms/PartyForm.ts:
// Generated by app-js:dump-forms from App\Form\PartyType, do not edit
import type { FormCollection, FormField } from '@silarhi/app-js/form'
export interface PartyForm {
name: FormField<HTMLInputElement, string>
country: FormField<HTMLSelectElement, string | null>
tags: FormField<HTMLElement, string[]>
address: {
street: FormField<HTMLInputElement, string>
city: FormField<HTMLInputElement, string>
}
phones: FormCollection<{
number: FormField<HTMLInputElement, string>
}>
}and the page checks its paths when compiling:
import type { PartyForm } from '@/js/forms/PartyForm'
const form = formView<PartyForm>(container.querySelector('form'))
form.get('phones.0.number')
form.get('adress.city') // TS2345
form.get('country').element // HTMLSelectElement | null
form.field('tags').value // string[]The shape is read from the form view, as formView() reads the DOM: embedded forms are nested objects, collections
take the shape of their prototype and rendered items, expanded choices are one field. The CSRF token is left out.
A field names the element it is rendered as and the value field().value reads, from the core type it extends:
- a choice (an entity, an enum, a country) is an
HTMLSelectElementread asstring | null, orstring[]when multiple; expanded, the container of its options read asstring, orstring[]when multiple; - a checkbox is read as a
boolean, a radio asstring | undefined(the checked value of its group); - a textarea and the other core types rendered as an input are read as a
string; a button has no value.
A type no core type tells about, or a field two variants render differently, is a plain FormField: an HTMLElement
read as any value. A form type of your own whose widget renders something else than its parent, or a field whose
behavior (bindField()) reads another value, should extend a type that renders and reads the same.
An embedded form whose type is marked #[FormToJs] too is a reference to its interface, imported from its file:
import type { FormCollection, FormField } from '@silarhi/app-js/form'
import type { AddressForm } from './AddressForm'
import type { PhoneForm } from './PhoneForm'
export interface PartyForm {
name: FormField
address: AddressForm
phones: FormCollection<PhoneForm>
}Only when the shapes are the same: an embedded form built with options that change its fields
(->add('billingAddress', AddressType::class, ['with_country' => true])) keeps its own shape, written out.
A form whose fields depend on its options or its data is built once per variant. A field missing from a variant
becomes optional (siren?: FormField), so the page reads it with form.find().
A build without data (no variant, or a variant that gives none) gets the form's empty data, as Symfony computes it when
the form is submitted empty: a new instance of its data_class by default, or what its own empty_data gives (a type
whose class needs constructor arguments sets it). It is computed from the resolved options, so neither buildForm()
nor a PRE_SET_DATA listener ever runs without data: a type that reads $options['data'], or whose listeners add
fields, renders as the page of a new entity and needs no variant for an empty entity. Only an object counts: a type
without data_class ([]), required: false (null) or an empty_data that fails (reading submitted fields, a class
that cannot be built) keeps the build without data; -v tells which failed.
The options every build needs go in options, and the values an option takes in matrix: the form is built once per
combination, with the options (2 × 2 = 4 builds here):
#[FormToJs(
options: ['profile' => Profile::Landlord],
matrix: [
'person_type' => [PersonType::Company, PersonType::Individual],
'new' => [false, true],
],
)]
final class PartyType extends AbstractTypeA matrix builds every combination, so it fits options that change the form on their own. Builds that need objects or services, or options that only go together, come from a provider, a service by its class:
#[FormToJs(variants: LeaseFormVariants::class)]
final class LeaseType extends AbstractType
final class LeaseFormVariants implements FormVariantProviderInterface
{
public function getVariants(): iterable
{
yield 'furnished' => new FormVariant(data: (new Lease())->setFurnished(true));
yield 'unfurnished' => new FormVariant(['issuer' => new Issuer()]); // data: a new Lease, its empty data
}
}With options or a matrix too, each variant of the provider is built with each combination, its own options winning.
A matrix stops at 64 builds.
Build the data in memory: the dump must give the same files on every machine, never read it from a database.
A field every build has, but the template renders only sometimes ({% if … %}{{ form_row(form.sharedAccount) }}, the
others marked rendered with setRendered), is made optional by its dot path, so the shape does not promise it:
#[FormToJs(optional: ['sharedAccount', 'address.country', 'phones.{index}.fax'])]
final class SubscriptionType extends AbstractTypeA path that matches no field of any build fails the dump. A field no build has cannot be made optional: its element and value come from a build, so give a variant that renders it.
Fields added by a PRE_SET_DATA listener only appear with data. app-js:dump-forms warns about each form type with
such a listener and no build with data (given, or its empty data); #[FormToJs(dynamic: false)] silences it for
listeners that add no field.
Other options: #[FormToJs(name: 'Party')] names the interface and its file (PartyForm for PartyType by default).
# config/packages/silarhi_app_js.yaml
silarhi_app_js:
enums:
output_dir: '%kernel.project_dir%/assets/js/enums' # owned by app-js:dump-enums: its other .ts files are removed
format: ts # or js
# Symfony 6.4 to 7.2 only: the directories scanned for #[EnumToJs] enums, with their namespace prefix
paths:
'%kernel.project_dir%/src/Enum': 'App\Enum'
constants:
output_dir: '%kernel.project_dir%/assets/js/constants' # owned by app-js:dump-constants
format: ts # or js
# The directories scanned for #[ConstantsToJs] classes no service resource loads, with their namespace prefix
paths:
'%kernel.project_dir%/src/Entity': 'App\Entity'
forms:
output_dir: '%kernel.project_dir%/assets/js/forms' # owned by app-js:dump-forms
format: ts # or jsWith format: js, the enums are .js modules (the same code), and the form shapes .d.ts declarations: a shape is a
type only. A JavaScript page reads it through JSDoc, and checkJs checks the paths:
/** @type {import('@silarhi/app-js/form').FormView<import('@/js/forms/PartyForm').PartyForm>} */
const form = formView(container.querySelector('form'))Commit the dumped files and check they are up to date:
bin/console app-js:dump-enums --check
bin/console app-js:dump-constants --check
bin/console app-js:dump-forms --check --strict--check fails when a file would change, without writing it; --strict fails on the warnings.
MIT