Unreleased
Unreleased
Added
Descriptor::unless(Closure): the negation ofwhen().Export\RegexPattern::of()andExport\DatePattern::of()are public contract (no longer@internal): a generator gets the ECMApatternJsonSchemaExporterwrites for a string pattern, or for a date format JSON Schema does not name (Y-m-d, RFC 3339 and RFC 3339 extended exportformat),nullwhen there is none.Checking\Checker::forClasses(ClassFinder): the checker the provider binds on a subset of the classes, every built-in, Laravel and tagged rule included, so a consumer's own check command does not rebuild the list;CheckContext::$subsettells a check it runs on a subset, andLockMismatchthen reports no locked class gone.- Automatic date ↔ date-time conversions (
Conversion\BuiltIn\DateTimeToDate,DateToDateTime), lossless in both directions: a date-time that was a date (or a date that was a date-time) needs nodown:/up:any more. The day is written in the timezone of the value (never shifted to UTC); a date becomes midnight of its day. A date-time sent where the head is a date warnsconversion-lossy(its time is dropped). - Descriptor macros:
Schema\DescriptorMacros::register($name, Closure)adds a fluent method to every descriptor, served byDescriptor::__call()(Schema::string()->whenInFields('notes')). The closure receives the descriptor, then the arguments, and must return an instance of the descriptor's class; a nameDescriptordeclares is refused and a public method of the descriptor's own class wins. NewDefinitionException::invalidMacroName(),unknownMacro()andinvalidMacroResult(). PHPStan:apiRevisions.macrosmaps each name to its static method (PHPStan\DescriptorMacrosExtension), typed with the method's parameters after the descriptor and returning the receiver's type. - Projection plan:
Projection\Projector::plan(Shape, descriptors, ?keys)resolves a projection once per render into aProjection\ProjectionPlan, run per subject (run($subject));keyskeeps those head keys of the top level (a sparse fieldset).Projector::project()runs through it. - Paths in a projection plan: a
keysentry ofProjector::plan()may be a dotted path of head keys (address.city,tags.*.name), keeping only that member of an object or of each item of a list; a member left out is never evaluated (source, conditions, conversions, value errors). A shorter path wins; a path into a field converted at the revision, a list through a key, a resource or a scalar keeps the field whole; a head key of the top level holding a dot is still kept whole. RevisionedResource::collection()returns aLaravel\Resources\RevisionedResourceCollection:toArray()runs once per render on a template instance and every item goes through one plan (about 4.5 times faster on the benchmark). A resource whose structure depends on its model in plain PHP opts out withstatic revisionedPerSubject(): boolreturningtrue; plain values and native conditions keep the per-item path.- Benchmark: a
lookupscenario keepsShapes::for()on a cached class at one array read and oneunserialize()(against the bareunserialize()of the same entries). Checking\Declarations: the discovered classes with their declaration kinds (declarations()), or those existing at one revision (at()), resolvable from the container.- Public contract under semver from 1.0, named in
docs/architecture.md§4: the definition model,Shape,JsonSchemaExporter::export()/objects(), the structure ofrevision:export,Changelog::changes()/markdown()withChange/ChangeKind,ClassFinderandDeclarations. - Documentation: the README (install, the enum, a resource, a request, resolution, check and lock in CI, retiring a
revision, outside HTTP, testing) and the guide
docs/guide.md, covering every feature. - Without configured enum (
revisions.enumleftnull), the library works on the implicit one-caseRevisions\Unrevisioned(head): resources render, requests validate and every command succeeds, with no history; therevisionmiddleware resolves nothing and adds no revision header, a queued job captures no revision,revision:changeloghas no change to list (as for any one-case enum without--from/--to),revision:locklocks nothing, a job captured earlier runs in the head. Adefaultother thanlatest/oldestwithout enum is refused;Route::revisioned()andwithRevision()throw, naming the missing enum. - Checks contributed by a package or an application: a
Checking\ChecktaggedLaravel\RevisionsServiceProvider::CHECKS('revisions.checks') is built by the container and run after the built-in checks byrevision:checkandassertRevisionsAreConsistent(); a tagged service that is not aCheckthrowsConfigurationException::notACheck(). Conversion\Converters::identity(string $name)(andisIdentity()): a custom type declares, in itsDeclaresConversions::conversions(), that its values do not depend on its fragment. Awas(schema:)changing only its fragment then plans no conversion step (noconversion-missing), still shown in the export, the lock and the changelog; such a type is exported in place rather than as a$defscomponent, so two of its fragments in one revision never conflict.Compilation\Shapes::converters()gives the registry the shapes are planned against.- Class lifetime: a
Revisionedclass implementingSchema\HasLifetime(static revisionedLifetime(): Lifetime, with the newLifetime::since(R)/Lifetime::until(R)) exists only in those revisions;Schema\ClassLifetime::exists()tells whether it exists at a revision. Compiling it elsewhere throwsDefinitionException::classAbsent(). The check,revision:cache,revision:export, the lock andassertRendersAtEveryRevision()skip the revisions it does not exist in (a lock file lists the classes existing at its revision); the changelog lists the class added and removed. New check coderesource-absent: a visibleSchema::resource()field nesting a class absent at its revision. A locked revision holding a class now absent there is alock-mismatch. - A class implementing
Schema\Revisioneditself, without the Laravel traits, is a supported path (compiled, cached, checked, locked, exported);Revisioned::describeRevisioned()is no longer@internal, and may build the declaration on the implementer's own stand-in instead of theProbe. - Agent skill
skills/laravel-api-revisions/, shipped with the package:SKILL.md(the rules that prevent most mistakes, such as the writing rule of the bounds and the value adown:closure receives),reference.md(every public entry point) andrecipes.md(tested examples of the common tasks). - Package skeleton:
Ark4ne\ApiRevisions\Laravel\RevisionsServiceProvider, auto-discovered by Laravel. - Revisions: the
Revisions\Revisioncontract and theRevisions\IsRevisiontrait for an application's revision enum (isBefore(),isAfter(),isAtLeast(),isAtMost(),previous(),next(),latest(),oldest()), ordered by its explicitorder(), never by declaration or backed value; string- and int-backed enums. #[Revisions\Meta]on a revision case (description,publishedAt,deprecatedAt,sunsetAtasY-m-ddays, checked when read),Revision::meta()(an emptyMetawhen absent),Meta::isDeprecated()/isSunset()from their day included;DefinitionException::invalidMetaDate()/invalidMeta().- Current revision:
Revision::current()(the innermostusing(), else the revision of the context, else the head) andRevision::using($revision, $callback)(restores the previous revision, even when the callback throws; render inside the callback);Revisions\RevisionScope, the only holder of the current revision, found throughRevisionScope::provider(). - Schema vocabulary:
Schema\Schema::string(),int(),float(),bool()returningStringSchema(min(),max(),format(),pattern()),IntSchema/FloatSchema(min(),max()),BoolSchema; every descriptor (Schema\Descriptor, the extension base) has a lazy source (the declared key, a key or dotted path, or a closure($value, $subject); an evaluated value throwsDefinitionException::eagerSource()),nullable(),required(),sometimes(),describe(),example(),deprecated(),rules(), and returns a new instance on every modifier. normalize()/serialize()of the scalars; a refused value is returned as aSchema\InvalidValuecarrying its lenient cast. An evaluated source is refused even in a file withoutstrict_types.Schema::date()/dateTime()(DateSchema/DateTimeSchema,format(), else the configured default:Y-m-dand RFC 3339) andSchema::enum(BackedEnum::class)(EnumSchema: the case or its backed value, serialized as the backed value; its type exports the enum, its backing kind and its values).Schema::list(Descriptor $items, $source)(ListSchema,min()/max()on the size; anyiterablenormalized to a list) andSchema::object(array<string, Descriptor> $children, $source)(ObjectSchema, its value is the subject of its children; serialized as a JSON object even when empty), nested freely;configure()reaches items and children; the children are projected before the composite's own conversions. An object without source reads its children on the parent's subject (Schema\Source::parent()).TypeDefinitionexportsitemsandchildren.Schema::rule(array $rules, $source)(RuleSchema, the escape hatch: kindAny, any value rendered as it is) andSchema\DescribesSchema: a rule object implementing it adds its JSON Schema keywords to the type of the field it is declared on (TypeDefinition::$jsonSchema), whatever the descriptor; non JSON-ready keywords throwDefinitionException::invalidJsonSchema().- Conditions on every descriptor:
when(Closure $condition)(called($value, $subject)after normalization) andwhenHas(?string $key)(aSchema\Presence, checked before the source;DefinitionException::invalidPresenceKey());isConditional(),conditions(),presences(). - Lifetime of a field:
Descriptor::since(Revision, $default)(from the revision included; a default for older clients,Support\Undefinedwhen none) anduntil(Revision)(up to the revision included), read asDefinition\Lifetime(covers(Revision)); asincenewer than theuntilthrowsDefinitionException::invertedLifetime(); a bound set twice keeps the last call and is recorded (Descriptor::repeatedBounds()). - Groups:
Schema::since(Revision, array $fields, $default)andSchema::until(Revision, array $fields)return the array with each member bounded, to spread with its string keys (in a declaration or inSchema::object()); a member's own narrower bound and own default win, a wider one throwsDefinitionException::sinceOlderThanGroup()/untilNewerThanGroup(); a group never records a repeated bound. - Conversions:
Definition\Direction(Down,Up), theConversion\Converterstrategy (convert(),lossless(),extraRules()) and theConversion\Convertersregistry keyed by(from Kind, to Kind, Direction)(builtIn(),register()with a factory receiving both types,find(),key()), with the built-ins in both directions (Conversion\BuiltIn\*: int ↔ float / string / bool, float → string / int, bool → string / int, string → bool, enum ↔ backed value);Exceptions\ConversionException::invalidEnumValue().Converter::convert($value, $subject = null): only a closure reads the subject. - Explicit conversions: the
Conversion\ExplicitConvertermarker (never warnedconversion-lossy),Conversion\ClosureConverter(adown:/up:closure($value, $subject)) andConversion\Cast::round(),floor(),ceil()(float → int, aConversion\Rounding). A float → int conversion (FloatToIntincluded) of a float outside the int range throwsConversionException::outOfIntRange(). - Custom types:
Schema\TypeRegistry(register($name, MoneySchema::class)at boot,has(),make(),flush(); static like Laravel's macros) served bySchema::__callStatic()(Schema::money('total'));TypeDefinition::custom($name, $fragment)(Kind::Custom, the name the type declares, its JSON Schema fragment infragment, apart from the rule keywords ofjsonSchema);DefinitionException::unknownType(),invalidTypeName(),invalidCustomType(),invalidTypeFragment(). - PHPStan extension (
extension.neon, registered forphpstan/extension-installer): the custom types mapped inapiRevisions.typesare static methods ofSchematyped with their class and their constructor's parameters (PHPStan\CustomTypesExtension). - Conversion chains:
Conversion\ConversionChain(empty(),withStep(),bind(),apply($value, $subject),stepOf(),missing(),isEmpty()), the steps of one field at one revision in one direction, planned from types and references only (Conversion\ConversionStep,Conversion\StepKind: registered, explicit, missing) so it serializes; two types holding the same values add no step;ConversionException::missing()when a step without converter is applied. - Shapes:
Compilation\ShapeSelector::at($head, $revision, $direction, $converters), the one function giving theCompilation\Shapeof a revision (names(),field(), the fields added later for a request, the nameCompilation\Collisions): per visible field aCompilation\FieldDefinition(name, type, nullable, required, sometimes, conditional, default and lifetime at the revision, itsCompilation\FieldVersionat every applicablewas(), its unbound conversion chain in the direction of the shape, the items of a list, the children of an object as a nestedShape), every omittedwas()argument inherited from the next newer shape. Closure-free and serializable. - Compilation:
Schema\Revisioned(staticdeclarationKinds()and the@internalbridgedescribeRevisioned(DeclarationKind, $subject): the probe at compilation, the value of a nested resource at projection),Schema\DeclarationKind(Response,RequestBody,RequestQuery;direction()),Compilation\Probe(throwsDefinitionException::subjectReadAtCompilation()on any access),Compilation\Compiler::compile($class, $kind, $revision)(configured descriptors, the shape of the revision naming its class and kind:Shape::$class,Shape::$kind);DefinitionException::notRevisioned(),undeclaredKind(),invalidDeclaration().Descriptor::configured()configures a descriptor and the schemas of itswas(); composites configure their parts through it. - Projection:
Projection\Projector::project(Shape, $descriptors, $subject)(built with theConfiguration, theConvertersand aProjection\SourceReader) renders the visible fields of a shape under their name at its revision: presence conditions, source (a renamed field reads its head key), normalization,when()(kept ontrue), down chain bound to the fresh descriptors, serialization by the type in force at the revision;nullskips normalization and conversions.SourceReader::read()(keys and dotted paths on arrays,ArrayAccess, public properties,__get()withoutisset()),has(),peek()(no side effect).Exceptions\ValueException(refused(),nullNotAllowed(),unconvertible();class,field,revision; never the value);DefinitionException::missingDescriptor(). - Upgrade:
Upgrade\Upgrader::upgrade($shape, $descriptors, $input, ?$hook)takes a validated input of a request shape's revision to the head, step by step: renames andupconversions of eachwas()read from a snapshot of the step (values normalized to the type of the step first), theUpgrade\UpgradesInputhook, the defaults of the fields added in the newer revision (never over an explicitnull), the fields retired dropped; converted and defaulted values serialized back to raw values, the result in the head order; a response shape throwsDefinitionException::notAnUpShape().FieldVersion::$schemaChangeandFieldDefinition::nameAt()give the descriptor in force and the name at a revision. Objects, lists and nested resources are upgraded too, in the same step as their parent; theUpgradertakes an optionalShapesfor the nested resources. - Laravel:
config/revisions.php(publish with--tag=revisions-config), validated lazily byLaravel\RevisionsConfig(Exceptions\ConfigurationException); the service provider binds the coreConfiguration, oneShapes, theRevisionScopeof each request (scoped, its base the configured fixed default outside a request) and theValueErrorHandler(strict_values,nullfollowingapp.debug; lenient errors reported once per class and field and request). - Resolvers: the
Laravel\Http\RevisionResolvercontract (resolve(Request): ?Revision),HeaderResolver(name,Api-Revision),QueryResolver(name,revision) andPathResolver(parameter,revision) inLaravel\Http\Resolvers, chained byResolverChain(ascopedbinding built fromrevisions.resolvers, each resolver made by the container with its options as named arguments; the first revision wins, thendefault: a fixed revision, or a resolver class whosenullgives the head). A value naming no revision throwsExceptions\UnknownRevisionException(the value and the accepted ones).RevisionsConfigrefuses a resolver or a classdefaultnot implementingRevisionResolver;resolversdefaults to the header resolver. - Middleware
Laravel\Http\ResolveRevision(aliasrevision): resolves the revision of the request through theResolverChain, makes it the request's current revision, and adds theresponse_header,Varyon the revision headers,Deprecation(RFC 9745) andSunset(RFC 8594) from the revision's#[Meta]; an unknown revision is answered 400 with{message, revision, accepted}.UnknownRevisionExceptioncuts the value it echoes to 64 characters. A resolver reading request headers implements the optionalLaravel\Http\VariesOncontract (headers(), implemented byHeaderResolver):ResolverChain::headers()collects them forVary. - Path mode: the route macro
Route::revisioned(fn (Router $router) => …)(Laravel\Routing\RevisionedRoutes) prefixes its routes with{revision}(theparameterof the configuredPathResolver, required:ConfigurationException::pathModeWithoutResolver()), constrained to the revision values, under therevisionmiddleware; the middleware forgets the parameter and sets it as a URL default, so controllers never receive it and generated URLs keep the revision.PathResolver::parameter(),ResolverChain::parameters(),RevisionsConfig::pathParameter().extension.neondeclares the macro to PHPStan (PHPStan\RevisionedRouteExtension;PHPStan\CustomTypeMethodbecomesPHPStan\DeclaredMethod). Laravel\Resources\RevisionedResource, the trait of a revisionedJsonResource:toArray()returns descriptors,resolve()projects them on the model at the current revision, in the order oftoArray();with(),additional(), wrapping, collections and pagination unchanged; implements theRevisionedbridge (a response). A plain value is rendered as it is (a nullableanyin the shape:Schema\EagerSchema); a nativewhen(),whenLoaded()ormergeWhen()is honoured at run time and kept out of the shape;Arrayablevalues are rendered as arrays; lenient value errors are reported. TheProjectoris bound in the container (scoped).Descriptor::whenLoaded('relation')(dotted for a nested relation,Schema\Presence::loaded()): the field is kept only when the relation is loaded, checked before the source; on a subject without relations, the key is present.Projection\SourceReaderis now an interface (read(),has(),peek(),loaded()), implemented byProjection\PlainSourceReader(the former class) and decorated for Eloquent byLaravel\Resources\EloquentSourceReader(attributes present ingetAttributes(), relations loaded, never a lazy load).- Validation rules of a request shape:
Laravel\Validation\RuleCompiler::compile($shape, $descriptors)(bound in the container) gives the Laravel rules under the names of the client's revision (dotted for children and nested resources,.*for items):sometimes/required/nullableas declared, the rules of the type (oneLaravel\Validation\RuleMapperper kind, replaceable: string length, pattern and known formats,integer/numeric,boolean,date_format:, Laravel'sEnum,list/array), those of the first up conversion (numeric,integer, the values of an enum), then the descriptor'srules()as given. A required child of a parent the client may leave out getsrequired_unless:<parent>,null.DefinitionException::rulesOfAResponse(),unknownKind()(a mapper keyed by no kind). Laravel\Requests\RevisionedRequest, the trait of a revisionedFormRequest: the head body inbody(), the head query parameters inqueryParameters(), theprotected upgrade()hook on the body;rules()validates the input in the client's revision under its names, then the input is upgraded to the head, whichvalidated()/safe()return (input()/all()keep the input as sent). A name declared in both the body and the query at a revision throwsDefinitionException::declaredTwice(). TheUpgraderis bound in the container (singleton).- A value the upgrade rejects is a validation error on the client's key: the upgrader throws
Exceptions\InvalidInputException(key,reason) for aConversionExceptionor aValueException(instead of the exception itself); anup:closure rejects an input withConversionException::invalid($message), its message being the error; any other rejection gets Laravel'svalidation.inmessage.ConversionException::missing()stays a declaration error (ConversionException::$declarationError), as do the other exceptions of a closure . - Queued jobs outside HTTP: a job implementing the marker interface
Laravel\Queue\CapturesRevisionruns in the revision current when it was dispatched (handle(), its middleware andfailed()insideusing(), thesyncqueue included); the payload stores the backed value underark4ne:revision. A revision the enum no longer knows fails the attempt withUnknownRevisionException, andfailed()runs in the base revision. Other jobs run in the base revision. - Compiled shapes:
php artisan revision:cache(run byphp artisan optimize) compiles every declaration kind of every class implementingRevisionedfound underdiscovery.paths(plusdiscovery.classes) at every revision, and writescache_path(bootstrap/cache/revisions.php);revision:clear(run byoptimize:clear) removes it.Compilation\CompiledShapesreads and writes the file (load(),write(),get(); one serialized shape perclass@kind@revision, unserialized on first use),Shapestakes it as its second argument and reads it before compiling;Laravel\Discovery\PathClassFinderfinds the classes;Exceptions\CacheException. Changing the date formats, a declaration or a custom type requiresrevision:cacheagain, as forroute:cache. - Benchmark gate:
composer benchmark(bin/benchmark.php, referencebin/benchmark/reference.json,--update) compares the projection at the head and at the oldest revision with a plainJsonResource(time and memory ratios, 10 % tolerance); run in CI. A projection costs about ×19 the time of the plain resource:TypeRegistry::converters()without argument is built once until the nextregister()orflush(), the projector configures only the serializer's own defaults (configure()), and awas()inserts its change without sorting the history. - Value errors:
Projection\ValueErrorHandlerwithStrictValues(throws) andLenientValues(an optional reporter; renders the cast of a refused value as it is,nullfor a failed conversion or a non-nullablenull), given to theProjectoror chosen fromConfiguration::$strictValues(trueby default); a non-nullable field or item resolvingnullis a value error. - Nested projection: objects project their head children on their value (or the parent's subject), lists each item
(an item whose condition fails is dropped), a
Schema::resource()the shape of its class at the same revision with its descriptors built on the value (Projectortakes an optionalShapes); the composite'swhen()/down:receive the projected children.FieldDefinition::$children/$itemsare those of the head composite atFieldDefinition::$headAt, the revision after its newestwas(schema:). - Shapes repository:
Compilation\Shapes(built with aCompiler, the default one by default),for($class, $kind, $revision)compiling each(class, declaration kind, revision)once,flush(). - Nested resources:
Schema::resource(class-string<Revisioned>, $source)(Schema\ResourceSchema,class();DefinitionException::notRevisioned()for another class): anObjectkind referencing the class (TypeDefinition::$resource,withResource()), never a copy of its shape, so cycles compile. The nested shape is the class's declaration of the same kind at the same revision: the compiler refuses a nested class that does not declare it (undeclaredKind()). Two types referencing different classes hold other values: changing the referenced class needs a converter (a missing step otherwise). - Conversions of custom types: a custom type implementing
Schema\DeclaresConversionsregisters its conversions (conversions(Converters): Converters);TypeRegistry::converters()gives the built-in registry with those of every registered type, to give toShapeSelector::at().Converters::register()takes a custom type's name as a side (Kind::Customand an empty name throwDefinitionException::invalidConversionSide());Converters::keyOf()keys a custom type by its name (custom(money)>float:down), so two custom types never overwrite each other. - Defaults:
Configuration::$missingDefault(Configuration\MissingDefault::Error, the default, orNull); withNull, arequired()->since(R)field declared withoutdefault:getsnullas default in the shapes (ShapeSelector::at(..., configuration:)), an optional one keeps none. - History:
Descriptor::was(Revision, name:, schema:, down:, up:)(down:/up:a closure, kept as aClosureConverter, or aCast) adds aSchema\Changeto the field'sSchema\History(its lifetime and its changes, newest first whatever the call order;Descriptor::history()); no effect on the head type.DefinitionException::invalidHistory()(awas()on the head, twice on a revision),emptyHistoryName(),emptyChange()(awas()changing nothing) andsourceInHistory()(aschema:, its items or children with a source, a lifetime, a history, a default or a condition). Configuration\Configuration(dateFormat,dateTimeFormat), given to descriptors byDescriptor::configure().Definition\TypeDefinitionandDefinition\Kind, the type of a field as read by the tools.Revisions\RevisionOrder:index(),compare(),previous(),next(),latest(),oldest(),between().Exceptions\RevisionsException, marker of the package exceptions, andExceptions\DefinitionException(mixedRevisions()when revisions of two enums are compared,foreignRevision()when a revision of another enum is used or current,invalidOrder()whenorder()misses a case, lists one twice, lists a foreign case, is not a list or is empty).- Check foundations:
Support\Diagnostic(code,severity,class,field,revisionas its backed value,message,isError()),Support\Severity(Error,Warning) andSupport\Diagnostics(collected in order,errors(),warnings(),hasErrors(), countable and iterable);Checking\Check(one rule, run once on the revision enum then once per declaring class),Checking\CheckContext(the target, its shapes,error()/warning()),Checking\Checker(runs the checks with a freshShapesper run) and theChecking\ClassFindercontract, implemented byLaravel\Discovery\PathClassFinder;DefinitionException::noShapeForRevisions()when a check asks a shape of the enum,foreignRevision()for a diagnostic on a revision of another enum. - Check rules:
Checking\Checker::builtIn()—Checks\OrderMissingCase,OrderDuplicateCase,BoundRepeated(warning),HistoryBeforeSince,HistoryAfterUntil,ConversionMissing,ConversionLossy(warning),NameCollision(also a name in both the body and the query of a request),RequiredSinceWithoutDefault(none undermissing_default: null),EagerValue;Laravel\Checking\NativeCondition(warning). ADefinitionExceptionof a descriptor in aRevisionedResource::toArray()is no longer wrapped infailedDescribing(). Before its rules, the checker builds each class (descriptors, shapes at every revision): anything thrown is one error under the code of itsDefinitionException(DefinitionException::$checkCode:lifetime-inverted,since-older-than-group,until-newer-than-group,history-unordered,unknown-resource), elsedefinition-error, and the check goes on; an invalidorder()stops it after the enum.Compiler::describe()(the configured head descriptors) andCompiler::converters();CheckContext::order(),kinds(),descriptors(),converters().schema-overridecomes with the export. php artisan revision:check(Laravel\Console\CheckCommand): runsChecker::builtIn()plusNativeConditionon the enum and every class ofdiscovery.paths/discovery.classes, with the application's configuration; a table of diagnostics (--format=jsonfor CI tools), fails on an error, warnings alone pass;--listprints the discovered classes. The container bindsChecking\ClassFinder(PathClassFinderover the discovery, also used byrevision:cache) andChecking\Checker.Support\Diagnostic::toArray().Testing\InteractsWithRevisionsfor an application'sTestCase:assertRevisionsAreConsistent()fails with every diagnostic when one is an error.- JSON Schema export:
Export\JsonSchemaExporter(draft 2020-12;export($class, $kind, $revision),visit(Shape),typeKeywords()), implementing theExport\SchemaVisitorcontract: one document per class, kind and revision, its revisionmeta()in$comment; types and constraints, enum values, nullable (nullintype/enum, oranyOf),required(a response field unless conditional, a request fieldrequired()withoutsometimes()), descriptions, examples,deprecated, custom fragments, dates in their wire format (apatternfor a numeric PHP format), theDescribesSchemakeywords last; nested resources in$defs($ref, cycles included); objects open.php artisan revision:export {--revision=} {--class=}prints it as JSON. - A
pattern()is exported without its delimiters when its flags areu/Donly, otherwise described in$comment.Definition\TypeDefinition::$nullable(withNullable()): the nullability of the items and children of a composite. The compiled-shapes cache format is now2: runphp artisan revision:cacheagain after upgrading. - Check rule
schema-override(warning,Checking\Checks\SchemaOverride, inChecker::builtIn()): a rule keyword overriding a keyword of its field's type. - Lock of the published revisions:
Checking\Lock(one<value>.jsonper locked revision underlock_path: the structure of every class and kind, documentation left out, keys sorted, and the revision before it),Checking\LockedRevision,Exceptions\LockException.php artisan revision:lockwrites the revisions but the head that have no lock yet;--revision=(re)locks one, the head included. Check ruleslock-mismatch(per field, keyword, class or kind; a class or kind added only when it has fields there) andlock-order-changed(Checking\Checks\LockMismatch,LockOrderChanged), added by the Laravel binding of theCheckerover the configuredlock_path. - Components:
Schema\ObjectSchema::component($name)names an object, a custom type is one under itsTypeDefinition::custom()name; each is defined once in the$defsof a document (Export\Components) and referenced#/$defs/<name>from every use, its body at the revision exported (so its history applies everywhere).Definition\TypeDefinition::$component(withComponent()); the compiled-shapes cache format is now3(runphp artisan revision:cacheagain). Two bodies under one name throwDefinitionException::componentConflict()(DefinitionException::$field) and are reported by the check rulecomponent-conflict(error,Checking\Checks\ComponentConflict, inChecker::builtIn()). A custom type is now a$refin the export instead of its fragment inline. - Changelog:
Export\Changelog(changes($class, $kind, $revision): what a revision changes against the one before it, fields matched by their head key path through object children and list items;markdown($classes, $from, $to): newest first, each revision headed by itsmeta()),Export\Change,Export\ChangeKind(added, removed, renamed, type changed).php artisan revision:changelog {--from=} {--to=}prints it. - Test helpers: on
Testing\InteractsWithRevisions,withRevision(Revision)(a header, the route parameter of path mode or the query, as the first resolver of the chain reads it) andassertRendersAtEveryRevision($class, $subject, ?$revisions)(a head fixture projected at each revision and validated); theTestResponsemacroassertMatchesRevisionSchema($class, ?Revision $revision)(registered by the trait'ssetUpInteractsWithRevisions(); the revision of the response header by default, thedataof a wrapped body, a list item by item) —Testing\TestResponseMacros,Testing\RevisionSchema. They validate against the export with closed objects:JsonSchemaExportertakesclosed: true.opis/json-schemais suggested (needed by these assertions). The PHPStan extension declares the macro (PHPStan\RevisionSchemaAssertionExtension). HeaderResolver::DEFAULT_NAME(Api-Revision) andQueryResolver::DEFAULT_NAME(revision): the names they read when thenameoption is not set.- Prune:
Checking\Prune(run($classes): aChecking\PruneReportof theChecking\PruneCandidates —until(P),was(P),since(P)of the oldest revisionP,Checking\PrunedDeclaration— and the classes that did not build),Checking\DeclarationLocator(the file and line of a field key, by reflection).php artisan revision:prunelists them, relative to the application, and always succeeds. Export\JsonSchemaExporter::objects(): a document ready forjson_encode(). Fixed:revision:exportwrote ananyfield as[]instead of{}.Checking\CheckContext::$classes(every class of the run),revision()(a case by its backed value) andexport()(the JSON Schema of the checked class from the shapes of the run).
Changed
- Breaking:
when()runs before the value is read, after the presence conditions: a field refused is never read (its source closure never called), normalized, projected nor converted. Its closure receives($subject, string $attribute)instead of($value, $subject): the subject of the level (the model a resource wraps, an object's value for its children, a list's element for its items) and the key read (the source key or path, else the declared key;*for an item). A composite'swhen()no longer receives its projected children. A condition on the value reads the attribute on the subject. Projection\PlainSourceReaderno longer callsget_object_vars()on every read: an initialized public property is read directly (the properties of a class listed once by reflection), a dynamic one found withproperty_exists();get_object_vars()decides only the rare cases (uninitialized, lazy, non-public, internal classes). Same outputs; an Eloquent model no longer keeps a property table per instance read.- A descriptor that does not match its shape (missing, or a composite on one side only) throws
DefinitionException::missingDescriptor()when the projection is planned, even when its value isnull; it threw only on a non-null value. CompiledShapes::load()no longer walks the compiled file: an entry is checked when first read, and an invalid one (nullincluded) throwsCacheException::invalidFile()then; a cached shape loads neither its declaring class nor a descriptor.