Download the PHP package precision-soft/symfony-json-form without Composer

On this page you can find all versions of the php package precision-soft/symfony-json-form. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package symfony-json-form

Symfony json form

ci PHP >= 8.2 PHPStan Level 8 Code Style PER-CS2.0

You may fork and modify it as you wish.

Any suggestions are welcomed.

Purpose

The purpose of this library is to create forms for single page applications, with a symfony backend. The forms are constructed in the backend and serialized to json, that can be rendered in the frontend. In the assets folder you can find a react component to render the form.

A form is described by three pieces that you provide per form:

render() serializes the form (plus the DTO values) to a json structure for the frontend; handleRequest() takes the incoming request, sanitizes it, and denormalizes it back into the DTO.

render() builds a dto through getDtoClass() when none is given, so a dto must be constructible without arguments; one that is not is reported as the package's Exception (constructDto() is the hook to build it differently).

V1 vs V2

There are 2 versions of the react renderer. They consume the same backend json — only the frontend components differ:

Both are maintained in parallel and every fix lands in both. What actually differs:

formV1 formV2
the formik form passed down as a form prop read from FormContext
entry points Form.tsx, FormBuilder.tsx, FormButtons.tsx, FormControl.tsx Form.tsx re-exports everything; FormButton.tsx
prototype collections rendered inside FormField/FormBuilder its own PrototypeCollectionField.tsx
mutating a prototype collection FormFieldCallbacksType, filled in by the field PrototypeCollectionModifiersType, handed to the render prop
checkboxes the bool branch of FormField CheckboxField.tsx, with checkboxIcon/checkboxCheckedIcon render props
the language context React.useContext(LanguageContext) useLanguageContext()
the url generator useUrlGenerator() from service/UrlGenerator useUrlGeneratorContext(), host provided
mui autocomplete types @mui/base/AutocompleteUnstyled/useAutocomplete @mui/material/useAutocomplete

The field components themselves (TextField, DateField, DateTimeField, SelectField, AutocompleteField) are the same in both apart from those imports. The schema logic they share — turning the rendered json into the form's initial values — lives in service/Element.ts and is used by both.

Usage

Add this to your services.yaml so every form service receives the serializer:

A form service must implement four abstract methods: getDtoClass(), getMethod(), getAction(DtoInterface $dto) and build(Form $form, DtoInterface $dto).

Form elements

Each element renders to a json node with a type the frontend dispatches on. All take name and label first; the most relevant extra constructor arguments are noted below.

Element json type Extra arguments
StringElement string —
NumberElement number ?float $min, ?float $max, ?float $step
BoolElement bool —
DateElement date string $format = 'Y-m-d', ?string $min, ?string $max
DateTimeElement dateTime string $format = 'Y-m-d H:i', ?string $min, ?string $max
PasswordElement password —
HiddenElement hidden (label is not required)
LabelElement label display-only
FileElement file —
ArrayElement array array $options, string $mode (MODE_SINGLE/MODE_MULTIPLE)
AutocompleteElement autocomplete string $route, string $mode, string $parameter = 'query'
CollectionElement collection nested elements via addElement()
PrototypeCollectionElement prototypeCollection nested elements via addElement() (repeatable)

ArrayElement and AutocompleteElement throw InvalidModeException for an unknown $mode. Element names must be alphanumeric (ctype_alnum) — this is enforced and intentional.

DateElement and DateTimeElement validate the value strictly against $format: a value that does not round-trip through the format (e.g. an overflow date such as 2021-02-30) throws InvalidValueException. When $min and/or $max are set, the value is also enforced server-side to fall within that inclusive range — an out-of-range value throws InvalidValueException. A $min or $max that does not itself parse in the element's $format throws InvalidValueException at construction: it used to be skipped silently, which turned the range off without saying so.

NumberElement enforces $min/$max the same way — inclusive, server-side, InvalidValueException when the value falls outside — and rejects a $min greater than $max at construction. $step is a frontend hint only.

CollectionElement and PrototypeCollectionElement throw InvalidValueException when the value — or, for the prototype collection, any item — is not an array. ArrayElement throws it for any item that is not scalar, because the options it is compared against always are.

Request handling and sanitization

handleRequest(Request $request, ?DtoInterface $dto = null, bool $sanitizeData = true):

When $sanitizeData is true (default), sanitizeData() applies the following rules before denormalization:

Pass sanitizeData: false to denormalize the raw payload unchanged.

Serializer context

render() and handleRequest() hand a context array to the serializer, and a form declares its own by overriding two hooks:

This is what lets a DTO hold a real DateTimeImmutable rather than a string: with no datetime_format the serializer normalizes it to RFC3339, which then fails the element's own format validation.

The two formats are deliberately not the same string:

Precedence: the context derived from the request wins over getDenormalizationContext(), and the $dto argument of handleRequest() always wins over an OBJECT_TO_POPULATE the form declared.

React

Use the components from ./assets/react to interpret the backend response. This package ships the sources only; the host application is responsible for bundling them (there is no build step here). The Config component is project specific — it holds the locale context of the application. It is integrated with:

Tests

PHP tests run in the dev container:

The suite is written on precision-soft/symfony-phpunit: every test class extends AbstractTestCase and declares its subject or collaborator through getMockDto(); AbstractFormServiceTest drives the form services against a Mockery double of the Symfony Serializer (the class implements the three interfaces the intersection type demands), so an expectation the code does not meet fails the test. composer test excludes the integration group; composer test-integration runs only it. The integration suite (tests/Functional/) drives the whole round trip with nothing mocked — a form service renders a DTO to json, that json comes back as a real request body, and the service denormalizes it into a DTO again. It needs no external service.

The framework-agnostic react asset services (service/Element.ts, service/Utility.ts) are covered by a dependency-free harness using Node's built-in test runner (the dev container ships Node):

The react sources are type-checked with tsc --noEmit. There is no build step and no node_modules here: the host application bundles these sources and owns the dependencies, so the typescript compiler lives in the dev image and the dependencies are declared in assets/react/types/vendor.d.ts. The modules the host is expected to provide (../context/*, ../component/*, ../config/Config, ../exception/Exception, ../form/Form, ../service/Logger) are declared as .d.ts stubs beside their import paths, which doubles as the contract the host has to satisfy; a real .tsx in the host tree takes precedence over the stub.

The sources import types with import type, and the typecheck runs with verbatimModuleSyntax, so a host bundling them with a compiler that does not elide unused imports — or with verbatimModuleSyntax of its own — meets no type-only import at run time.

Exception context

Every exception in this package carries a structured context array next to its message, so the facts describing a failure do not have to be parsed back out of a string:

getContext() returns [] when nothing was attached. setContext() replaces it and returns the exception, and the constructor accepts it as an optional fourth argument. Values are expected to be scalars, so the array stays serialisable by a logger.

The context is purely additive: no message, code or previous throwable changed when it was introduced, so code that logs only getMessage() behaves exactly as before.

What this package attaches: AbstractFormService::getDataAndContext() reports formName and requestMethod when a request body is not valid JSON. The form name was previously only available interpolated into the message, and the request method was not reported at all.

Every exception in the package implements Contract\ExceptionInterface, so a consumer can read the context off any of them without knowing the concrete class. A subclass of your own that already declares a $context property or a getContext()/setContext() method will collide with Exception\Trait\ExceptionTrait.

Example application

A runnable product editor lives under .example/: three form services on the product nomenclator that use every element type the package ships, a value object built through the context hooks, and the react half that renders the same json with both formV1 and formV2 and derives its initial values from it — the minimum of code that shows the maximum of the library, with a test for every scenario. It installs the package from the working tree through a path repository, so it always tests the code as it stands; run it with .dev/validate/all.sh --example or cd .example && composer install && composer check, then cd assets/react && npm run typecheck && node --test for the react half. The directory is export-ignored and never reaches a consumer's vendor/.

Dev

Run the full gate the way the pre-commit hook runs it - the CI workflow in .github/workflows/ci.yml calls the same composer scripts and node commands, so the two cannot drift — cs-check, phpstan, phpunit, tsc --noEmit and the node tests:

Mutation testing is opt-in for the same reason, plus cost - it runs the suite once per mutant:

Infection is a pinned phar in the image, not a composer dependency, and infection.json5 carries a minMsi floor equal to the last measured score, so the section fails when a change makes the suite weaker rather than only reporting a number. Raise the floor when the score improves.

The React asset tests run through Node's own test runner, inside the same container:

Build against another PHP version with the PHP_VERSION build argument - each version is tagged as its own image, so switching back and forth costs nothing:

Coverage is available through pcov, which is installed but disabled by default:

After editing a file, ./dc restart dev (a few seconds) is enough to be sure the container is not serving a stale copy - the bind mount can keep the old inode after an atomic rewrite.

Todo


All versions of symfony-json-form with dependencies

PHP Build Version
Package Version
Requires php Version >=8.2
symfony/http-foundation Version ^7.0 || ^8.0
symfony/serializer Version ^7.0 || ^8.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package precision-soft/symfony-json-form contains the following files

Loading the files please wait ...