Download the PHP package softcreatr/json-payload-contract without Composer

On this page you can find all versions of the php package softcreatr/json-payload-contract. 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 json-payload-contract

JSON Payload Contract

Tests Latest Stable Version PHP Version Require

Extract stable, typed application data from changing and untrusted JSON payloads.

APIs rename fields. Webhook versions overlap. Queue producers deploy independently. Generated JSON is almost correct until it is not. JSON Payload Contract gives these inputs one explicit boundary: select only the values your application needs, normalize them into a stable shape, and receive structured diagnostics when the contract is not met.

The package is deliberately not tied to a framework or DTO implementation. Its output is a predictable PHP array that can feed a constructor, command, message handler, serializer, or mapper.

Contents

Why use it?

A conventional validator checks whether a known structure is valid. This library also solves the boundary problems that happen before validation:

Use JSON Schema when the JSON document itself is the public artifact and full schema interoperability is the primary requirement. Use a DTO mapper when the main task is constructing typed objects from an already stable shape. JSON Payload Contract is for selecting and stabilizing the small application-owned shape hidden inside payloads that may move, grow, or coexist in several versions.

Requirements

Installation

Core model

A contract maps output names to immutable field definitions:

One extraction follows this order:

  1. Validate the decoded value graph and its resource budget.
  2. Evaluate selectors in fallback order and stop at the first non-empty result.
  3. Enforce global and field-level match limits.
  4. Apply required, optional, or many-value cardinality.
  5. Insert an optional default when no selector matched.
  6. Handle nullability.
  7. Check the strict type or perform explicitly enabled coercion.
  8. Apply a nested contract, if configured.
  9. Run field validators in declaration order.
  10. Run transformations in declaration order.
  11. If every field passed, run all contract-level validators.

Independent fields continue after a failure, so one result can describe the whole payload. If one element of a many() field fails, that entire output field is omitted from partial data; successful unrelated fields remain available.

Contracts and fields are immutable. Configure them once and safely reuse the same instances across requests or long-running workers.

Selectors and fallbacks

Selectors are absolute RFC 9535 JSONPath expressions:

Every selector is parsed and type-checked when the contract is defined. Invalid or relative expressions throw ContractDefinitionException before payload processing begins.

Fallbacks solve payload-version drift without branching application code:

A fallback is tried only when every preceding selector matched nothing. A primary selector that matches an invalid value or too many values does not fall through, because doing so would hide malformed input. MatchResult::$selector and MatchResult::$usedFallback show which path won.

Selectors that are shared by several fields are evaluated once per extraction and served from an internal cache.

Cardinality, missing values, and null

Cardinality describes selector matches, not the value's type:

Factory Accepted matches Output when no match Output when matched
Field::required() exactly 1 missing_required violation one value
Field::optional() 0 or 1 omitted, or configured default one value
Field::many() 0 or more an empty list a list of values

Singular fields report multiple_matches rather than silently picking one value. Many-value fields can narrow their accepted count:

Missing and null are intentionally different:

Definition Missing JSON null
required()->string() violation violation
optional()->string() omitted violation
optional()->string()->default('x') 'x' violation
optional()->nullable()->string() omitted null
required()->null() violation null
many() [] depends on the selector and field nullability

An accepted null is returned unchanged. Nested contracts, validators, and transformations are not run for it.

Types and coercion

Types are strict by default:

Method Accepted PHP value
mixed() any value
null() only null
scalar() string, integer, float, or boolean
string() string
integer() integer
float() float, not integer
number() integer or float
boolean() boolean
array() any PHP array
list() array with consecutive integer keys starting at zero
associativeArray() non-list array with a named or sparse key
object() object
collection() array or object

An empty PHP array is a list. Raw JSON is decoded to objects by default, so {} and [] stay distinguishable.

Call coerce() explicitly when transport representations should be converted:

Target Additional accepted input
string scalar or Stringable, converted with (string)
scalar Stringable, converted to string
integer signed decimal integer string within the platform integer range
float integer or finite numeric string
number integer string when possible, otherwise finite float input
boolean integer or string accepted by PHP's boolean filter

Collections are never interconverted. Coercion does not turn objects into arrays, associative arrays into lists, or arbitrary values into null.

Built-in constraints

Constraints run after type handling and return stable machine-readable codes:

Method Meaning Violation code
nonEmpty() rejects empty strings, arrays, and objects empty
email() valid email syntax invalid_email
oneOf($values) strict non-empty allowlist not_allowed
matching($pattern) matches a developer-supplied PCRE pattern pattern_mismatch
minimum($number) inclusive numeric minimum below_minimum
maximum($number) inclusive numeric maximum above_maximum
between($min, $max) inclusive numeric range boundary-specific code
minLength($length) minimum Unicode code-point count too_short
maxLength($length) maximum Unicode code-point count too_long
startsWith($prefix) starts with a non-empty prefix missing_prefix
endsWith($suffix) ends with a non-empty suffix missing_suffix
contains($substring) contains a non-empty substring substring_not_found
minItems($count) minimum PHP array item count too_few_items
maxItems($count) maximum PHP array item count too_many_items
uuid() canonical hyphenated UUID syntax invalid_uuid
url($schemes) absolute URL using an allowed scheme invalid_url
ip() valid IPv4 or IPv6 address invalid_ip
dateTime($format) accepted without warnings by a DateTimeImmutable format invalid_date_time

url() allows only HTTP and HTTPS by default. Pass an explicit list to narrow or extend the schemes. This validates syntax and scheme only; it is not an SSRF defense for outbound requests.

Text comparisons are strictly case-sensitive by default. Configure ASCII-only case-insensitive comparisons once for the complete contract:

The policy applies to oneOf(), startsWith(), endsWith(), and contains(). It does not alter JSONPath member names, explicit PCRE flags in matching(), or formats whose casing rules are defined by their own standards. Empty prefixes, suffixes, and substrings are rejected at definition time because they would create rules that always pass. Exact UTF-8 strings work in case-sensitive mode; Unicode-aware case folding is intentionally not implied by the dependency-free insensitive mode.

Nested and reusable contracts

Nested shapes

Apply a contract to one object or to every item selected by a many-value field:

Nested input must be an array or object. Nested failures retain useful locations such as items.2.quantity; valid nested output is always the nested contract's normalized array.

Composition

Use extend() for local additions and merge() for reusable fragments:

Both operations return a new contract. Duplicate output names are rejected instead of silently overwritten. merge() retains validators from both contracts, uses the stricter value from each contract's resource limits, and keeps case-sensitive comparisons when either contract requires them.

Custom validation and transformation

Field validation

Domain rules can provide their own message and stable code:

Validators must return exactly true. A false result or thrown Throwable fails closed. Validators run in order and stop at the first failure for that value.

Transformations

Transform only after type and validation rules pass:

Transformations run in declaration order. A thrown Throwable becomes a transformation_failed violation; it does not escape from extract().

Cross-field validation

Contract validators receive the complete normalized output after every field succeeds:

All contract validators run so their failures can be returned together. They are skipped when any field failed, preventing misleading secondary errors and preserving their normalized input assumptions.

Results and error handling

Choose the API according to whether invalid input is expected:

Input Structured result Throw on invalid result
decoded PHP value extract() apply()
raw JSON string extractJson() applyJson()

apply() and applyJson() return normalized data or throw ExtractionException. The exception retains the complete Result.

Use extract() when validation failure is part of normal control flow:

data() can contain successful independent fields even when the result is invalid. Never treat partial data as a validated payload; use value() at trust boundaries.

Match metadata

Every processed field has a MatchResult:

Metadata contains the output field, winning selector, original match count, fallback usage, and default usage.

JSON diagnostics

Result, Violation, and MatchResult implement JsonSerializable:

Violation order follows contract field order. Nested field names use dot-separated output locations.

Violation codes

The complete stable code set is grouped below:

Category Codes
Input invalid_json, duplicate_object_member, cyclic_payload, unsupported_payload_type, payload_too_deep, payload_too_large, payload_too_complex, evaluation_limit_exceeded, selector_evaluation_failed, too_many_violations
Cardinality missing_required, multiple_matches, too_few_matches, too_many_matches
Type/null unexpected_type, null_not_allowed
Generic rules empty, not_allowed, pattern_mismatch, validation_failed, transformation_failed
Numbers below_minimum, above_maximum
Strings too_short, too_long, missing_prefix, missing_suffix, substring_not_found, invalid_email, invalid_uuid, invalid_url, invalid_ip, invalid_date_time
Arrays too_few_items, too_many_items

Security and resource limits

No payload value or JSONPath expression is evaluated as PHP. The package does not use eval(), dynamic code generation, shell execution, or payload-selected callbacks.

Every contract uses these defaults:

Limit Default Applied to
raw JSON bytes 16 MiB extractJson() / applyJson() before decoding
JSON depth 64 raw decoding and decoded arrays/objects
matches per field 10,000 selector output before normalization
decoded value nodes 100,000 arrays, objects, and scalar values before selection
selector bytes 4,096 each selector at contract-definition time
evaluation steps 1,000,000 shared selector and intermediate-match work per extraction
violations 1,000 diagnostics retained per extraction

Override them for the endpoint's real budget:

The global match limit is a backstop. Use maxMatches() to express a smaller domain limit for a specific list. The input-node and evaluation budgets prevent broad or recursive selectors from turning bounded payloads into unbounded work. Match limits are still checked after a selector produces its result, while intermediate selector work consumes the shared evaluation budget.

extractJson() rejects duplicate object member names before selection. This avoids parser differentials where another service, signer, or policy layer might choose a different duplicate value. Set rejectDuplicateObjectMembers: false only when compatibility with last-member-wins JSON is explicitly required.

extract() applies the same depth and node limits to decoded values. Arrays, scalars, and stdClass objects are accepted; cyclic references, resources, non-finite floats, and custom objects fail closed. Application-owned objects and ArrayAccess can be enabled with allowCustomObjects: true, but their methods may then execute during selection and their internal graph cannot be fully budgeted. Treat that option as a trusted-input compatibility mode, never as an untrusted deserialization boundary.

Custom callbacks and PCRE patterns are trusted application code. Do not construct them from payload data. PHP cannot safely interrupt arbitrary callbacks, so network access and expensive work belong outside latency-sensitive contracts. Likewise, url() validates syntax and schemes but does not resolve hosts, follow redirects, block private addresses, or replace an outbound-request SSRF policy.

Recommended boundary pattern:

  1. Apply an HTTP-server request-size limit.
  2. Call applyJson() with endpoint-specific ContractOptions and ResourceLimits.
  3. Use strict types and coercion only where the transport contract requires it.
  4. Cap every attacker-controlled collection with maxMatches() and/or maxItems().
  5. Keep custom-object traversal disabled and duplicate-member rejection enabled.
  6. Pass only the returned normalized array into business logic.
  7. Log violation codes and match metadata, but avoid logging secret payload values.

Recipes

Versioned webhooks

Put the newest location first and legacy locations behind fallbacks:

Monitor usedFallback to decide when legacy selectors can be removed. A complete runnable version is in examples/versioned-webhook.php.

Queue and event consumers

Define the contract once when constructing the consumer and reuse it for every message. Required identifiers fail closed, list outputs remain lists, and malformed messages produce complete diagnostics suitable for dead-letter metadata:

This avoids retrying permanently malformed messages and keeps raw message data out of application handlers. See examples/queue-consumer.php.

Third-party API responses

Select only the fields your application owns conceptually. Provider-specific nesting, naming, and added response fields then stop leaking into domain code.

The complete example normalizes a legacy commerce response, nested customer data, line items, numeric strings, and renamed keys: examples/third-party-api.php.

OpenAI and other LLM structured output

An LLM can produce syntactically valid JSON that is still unsuitable for your application. Validate both the provider envelope and the generated JSON before storing it, displaying it, or using it to select an action.

For an OpenAI Responses API integration, the first contract can require a completed response and extract its output_text; the second contract owns the generated application shape:

OpenAI's Structured Outputs can constrain model output to a JSON Schema. The local contract remains useful as the application boundary: it selects the provider response, enforces domain-specific limits, normalizes the result, and produces stable diagnostics independently of the HTTP client or SDK. A complete runnable support-ticket analysis example is in examples/openai-structured-output.php.

Configuration migration

Read the current key first, use fallbacks for old stored formats, and apply defaults only when every selector is missing:

Match metadata provides migration progress without inspecting source documents again. See examples/configuration-migration.php.

HTTP request boundaries

Apply a contract immediately after the server's request-size limit and JSON content-type checks. Unknown client properties are discarded, and business logic receives only the named, validated shape:

The framework-independent runnable version also demonstrates bounded referral codes: examples/http-request.php.

DTO construction

Keep transport normalization separate from object construction:

Framework controllers

The library needs no framework adapter. Read the raw request body, apply a reusable contract service, and translate violations into the framework's error response at the outermost layer. This keeps contract behavior identical in HTTP, CLI, queue, and test environments.

API reference

Contract

Method Purpose
Contract::define(array $fields, ?ContractOptions $options = null) validates and creates a contract
extend(array $fields) returns a contract with additional unique fields
merge(Contract $contract) combines unique fields and validators; stricter limits win
validate(Closure $validator, string $message = ..., string $field = '$') adds a cross-field validator
extract(mixed $payload) returns a Result for decoded input
extractJson(string $json) decodes raw JSON and returns a Result
apply(mixed $payload) returns valid normalized data or throws
applyJson(string $json) decodes and returns valid normalized data or throws
fields() returns the field-definition map
limits() returns effective resource limits
options() returns comparison and resource options

ContractOptions

Option Default Purpose
caseSensitive true controls built-in textual comparisons across the contract
limits new ResourceLimits() controls raw JSON and selector resource ceilings
allowCustomObjects false permits trusted application objects and ArrayAccess during decoded extraction
rejectDuplicateObjectMembers true rejects ambiguous repeated object names in raw JSON

Field

Group Methods
factories required(), optional(), many()
selection from(), fallback()
presence nullable(), default()
typing mixed(), null(), scalar(), string(), integer(), float(), number(), boolean(), array(), list(), associativeArray(), object(), collection(), coerce()
match count minMatches(), maxMatches(), matchesBetween()
constraints nonEmpty(), email(), oneOf(), matching(), minimum(), maximum(), between(), minLength(), maxLength(), startsWith(), endsWith(), contains(), minItems(), maxItems(), uuid(), url(), ip(), dateTime()
composition shape()
extension validate(), map()

All configuration methods return a new field. Introspection methods expose selectors, cardinality, type, nullability, coercion, default, nested contract, validators, transformations, and match limits.

Result

Method Purpose
isValid() whether no violations occurred
data() successful fields, possibly partial
value() complete valid data or ExtractionException
violations() ordered list of every violation
matches() all match metadata keyed by field
match($field) metadata for one field or null
jsonSerialize() logging-friendly result shape

Design guarantees

Performance

Contract construction validates and primes selectors once. During extraction, one JSONPath evaluator is reused and duplicate selector results are cached for that payload. Fallback evaluation stops at the first match. Validation and transformation run only for selected values, and resource checks happen before per-item normalization.

Define contracts once and reuse them—for example as services, static definitions, or long-lived worker dependencies. Rebuilding a contract per payload repeats selector parsing and discards the main optimization.

Run the bundled representative benchmark on the production PHP build and hardware you care about:

The benchmark reuses a four-field contract with a list and a shared selector. It reports throughput and latency without enforcing a machine-dependent threshold. Compare before and after changes under the same PHP build, extensions, CPU policy, and operating system.

Examples

Run any example after composer install:

Development

composer check requires exactly 100% class, method, and line coverage before running PHPStan, PHPCS, and PHP-CS-Fixer. CI tests supported PHP versions independently and runs the coverage gate with Xdebug.

License

ISC © Sascha Greuel.

ISC provides the practical freedoms of a short permissive license while keeping the full license text compact.


All versions of json-payload-contract with dependencies

PHP Build Version
Package Version
Requires php Version ^8.2
ext-filter Version *
ext-json Version *
softcreatr/jsonpath Version ^2.2.1
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 softcreatr/json-payload-contract contains the following files

Loading the files please wait ...