PHP code example of softcreatr / json-payload-contract
1. Go to this page and download the library: Download softcreatr/json-payload-contract library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
softcreatr / json-payload-contract example snippets
use SoftCreatR\JsonPayloadContract\Contract;
use SoftCreatR\JsonPayloadContract\Field;
$customer = Contract::define([
'id' => Field:: ->fallback('$.customer.email')
->nullable()
->string()
->email(),
'roles' => Field::many('$.data.customer.roles[*]')
->fallback('$.customer.roles[*]')
->string()
->maxMatches(50),
]);
$data = $customer->applyJson($requestBody);
// Always the same application-facing shape:
// [
// 'id' => 'cus_123',
// 'email' => null,
// 'roles' => ['admin', 'billing'],
// ]
$contract = Contract::define([
'outputName' => Field::
Contract::define([
'id' => Field::ems[*].sku'),
'expensive' => Field::many('$.order.items[?(@.price >= 100)]'),
]);
'customerId' => Field::ustomer_id')
->fallback('$.customerId')
->string(),
Field::many('$.items[*]')->minMatches(1);
Field::many('$.items[*]')->maxMatches(100);
Field::many('$.items[*]')->matchesBetween(1, 100);
Field::asses; "2" does not.
Field:::
$contract = Contract::define([
'email' => Field::)->oneOf(['open', 'closed']),
'reference' => Field::>string()->minLength(2)->maxLength(80),
'event' => Field::ack' => Field::
use SoftCreatR\JsonPayloadContract\ContractOptions;
$contract = Contract::define([
'event' => Field::s(caseSensitive: false));
$lineItem = Contract::define([
'sku' => Field::nteger()->coerce()->minimum(1),
]);
$order = Contract::define([
'id' => Field::
$identity = Contract::define([
'id' => Field::dAt' => Field::'$.email')->string()->email()])
->merge($timestamps);
use SoftCreatR\JsonPayloadContract\ViolationCode;
$field = Field::ool => !str_starts_with($value, 'system-'),
'Reserved user name.',
ViolationCode::NotAllowed,
);
$field = Field:: ->email()
->map(static fn(string $value): string => strtolower($value));
$range = Contract::define([
'minimum' => Field::ger(),
])->validate(
static fn(array $data): bool => $data['minimum'] <= $data['maximum'],
'The minimum must not exceed the maximum.',
'range',
);
use SoftCreatR\JsonPayloadContract\Exception\ExtractionException;
try {
$data = $contract->applyJson($requestBody);
} catch (ExtractionException $exception) {
$result = $exception->result();
}
$result = $contract->extract($payload);
if (!$result->isValid()) {
foreach ($result->violations() as $violation) {
printf(
"%s [%s]: %s\n",
$violation->field,
$violation->code->value,
$violation->message,
);
}
}
$partialData = $result->data();
$data = $result->value(); // Throws unless the result is valid.
$match = $result->match('customerId');
if ($match?->usedFallback) {
// Measure whether an old producer version is still active.
}
if ($match?->usedDefault) {
// Observe reliance on a migration default.
}
echo json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
use SoftCreatR\JsonPayloadContract\ContractOptions;
use SoftCreatR\JsonPayloadContract\ResourceLimits;
$contract = Contract::define(
['events' => Field::many('$.events[*]')->maxMatches(500)],
new ContractOptions(
limits: new ResourceLimits(
maxJsonBytes: 2_000_000,
maxJsonDepth: 32,
maxMatchesPerField: 1_000,
maxInputNodes: 25_000,
maxSelectorBytes: 1_024,
maxEvaluationSteps: 100_000,
maxViolations: 100,
),
),
);
$webhook = Contract::define([
'eventId' => Field::.id')
->fallback('$.data.customer_id')
->string(),
]);
$result = $eventContract->extractJson($messageBody);
if (!$result->isValid()) {
$deadLetterQueue->publish([
'reason' => 'payload_contract_failed',
'violations' => $result->violations(),
]);
return;
}
$handler($result->value());
$orderResponse = Contract::define([
'orderId' => Field::
->string(),
'status' => Field::),
'items' => Field::many('$.data.order.items[*]')
->fallback('$.order.lines[*]')
->shape($lineItem)
->matchesBetween(1, 500),
]);
$order = $orderResponse->applyJson($providerResponseBody);
$responseEnvelope = Contract::define([
'responseId' => Field::mpleted']),
'generatedJson' => Field::dOutput = Contract::define([
'summary' => Field::$.confidence')->number()->between(0, 1),
'topics' => Field::many('$.topics[*]')->string()->maxLength(80)->maxMatches(20),
'actions' => Field::many('$.actions[*]')->shape($actionContract)->maxMatches(10),
]);
$response = $responseEnvelope->applyJson($rawOpenAiResponse);
$analysis = $generatedOutput->applyJson($response['generatedJson']);
$configuration = Contract::define([
'endpoint' => Field:: ->url(['https']),
'timeoutSeconds' => Field::optional('$.integrations.billing.timeout_seconds')
->fallback('$.billing_timeout')
->integer()
->coerce()
->between(1, 60)
->default(10),
]);
$result = $configuration->extractJson($storedConfiguration);
if ($result->match('endpoint')?->usedFallback) {
$metrics->increment('configuration.legacy_key_used');
}
$registration = Contract::define([
'email' => Field::name')
->string()
->minLength(2)
->maxLength(80),
'locale' => Field::optional('$.profile.locale')
->string()
->oneOf(['de-DE', 'en-GB', 'en-US'])
->default('en-US'),
]);
$result = $registration->extractJson($requestBody);
if (!$result->isValid()) {
return new JsonResponse(['violations' => $result->violations()], 422);
}
$commandBus->dispatch(new RegisterCustomer(...$result->value()));
$values = $customerContract->applyJson($responseBody);
$customer = new CustomerData(...$values);
bash
php examples/versioned-webhook.php
php examples/nested-order.php
php examples/openai-structured-output.php
php examples/third-party-api.php
php examples/queue-consumer.php
php examples/configuration-migration.php
php examples/http-request.php