Documentation version: nextdevelopment documentation
Skip to content

Rewrite code with Rector ​

Gesso ships Rector sets for the PHP side of a migration. Config keys and CLI flags are not PHP code: rewrite those with gesso config:migrate.

SetConstantRewrites
Gesso v2 → v3GessoSetList::V3the PHP renames and removals in Prepare for Gesso 3.0
kirschbaum → GessoGessoSetList::KIRSCHBAUM_TO_GESSOkirschbaum-development/laravel-openapi-validator's trait
Spectator → GessoGessoSetList::SPECTATOR_TO_GESSOhotmeteor/spectator's assertions
osteel → GessoGessoSetList::OSTEEL_TO_GESSOosteel/openapi-httpfoundation-testing's validator calls
league → GessoGessoSetList::LEAGUE_TO_GESSOleague/openapi-psr7-validator's validator calls

The constants live in Studio\Gesso\Rector\GessoSetList. They and the files they name are stable for 3.x. What each set rewrites is best-effort: review the diff, then run your suite.

Install and run ​

Gesso does not install Rector for you. The sets need rector/rector ^2.7:

bash
composer require --dev "rector/rector:^2.7"

Run a set once, without a rector.php:

bash
vendor/bin/rector process tests --dry-run --config vendor/studio-design/gesso/src/Rector/config/gesso-v3.php
vendor/bin/rector process tests --config vendor/studio-design/gesso/src/Rector/config/gesso-v3.php

For the kirschbaum set, pass vendor/studio-design/gesso/src/Rector/config/kirschbaum-to-gesso.php; for the Spectator set, vendor/studio-design/gesso/src/Rector/config/spectator-to-gesso.php; for the osteel set, vendor/studio-design/gesso/src/Rector/config/osteel-to-gesso.php; for the league set, vendor/studio-design/gesso/src/Rector/config/league-to-gesso.php.

Run with --config and Rector writes fully qualified names and leaves the old use import in place; the code runs, but the import is stale. To get short names and drop the stale imports, add the set to a rector.php instead:

php
<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Studio\Gesso\Rector\GessoSetList;

return RectorConfig::configure()
    ->withPaths([__DIR__ . '/tests'])
    ->withSets([GessoSetList::V3])
    ->withImportNames(removeUnusedImports: true);

withImportNames() imports every name in the processed paths, not only the renamed ones. Leave it out if that would change code you do not want touched, and let PHP-CS-Fixer's no_unused_imports drop the stale imports.

Gesso v2 → v3 ​

Run it on v2.9 or v3; a second run changes nothing.

v2v3
Studio\Gesso\Fuzz\{ContractCheck, ContractCheckFailure, ContractCheckPlan, ContractCheckProbe, ContractCheckSkip, ContractCheckSummary, OpenApiContractChecks}the same class under Studio\Gesso\Contract\
EnumBindingException::forBinding(...)new EnumBindingException(...), same arguments
OpenApiCoverageTracker::hasAnyCoverage($spec)OpenApiCoverageTracker::current()->hasAnyCoverageOn($spec)
OpenApiSpecLoader::configure(..., enumBasePath: ...)the argument removed, named or positional
$this->failOpenApi(), failPsr7(), failExplore()$this->fail()
$this->assertOpenApi(), assertPsr7()$this->assertTrue()
$this->shouldSkipOpenApi()$this->findSkipOpenApiAttribute() !== null
assertResponseMatchesOpenApiSchema() and the other v2 assertion namesassertOpenApiResponse(), assertOpenApiRequest(), assertOpenApiExchange(), response first; see Assertion methods

The private-helper rows apply only in a class that uses the Gesso trait that composed the helper, and not when the class declares a method of that name. The assertion rows apply to $this->, self::, and static:: calls; a Laravel call is told from a Symfony one by its arguments (one argument, or a null or HttpMethod second). A positional sixth argument to configure() is removed only when it cannot be an array, because v3 has allowedRemoteRefHosts at that position. Remove an untyped variable there by hand.

Not rewritten, because the replacement needs a decision:

  • #[BoundToOpenApiEnum('path/to/file.json')]: replace the path with the component name, or delete the attribute when the names match. See Enum binding.
  • OpenApiSpecLoader::getEnumBasePath() and the removed EnumBindingReason cases: there is no replacement. Delete the code that uses them.

kirschbaum-development/laravel-openapi-validator ​

The set renames the trait Kirschbaum\OpenApiValidator\ValidatesOpenApiSpec to Studio\Gesso\Laravel\ValidatesOpenApiSchema. These calls keep their names and need no rewrite: withoutValidation(), withoutRequestValidation(), withoutResponseValidation(), and skipResponseCode().

kirschbaum validates every request and response. Gesso does that only with laravel.auto_assert and laravel.auto_validate_request on, which gesso config:migrate proposes when it finds the package. The set does not rewrite these, because Gesso has no 1:1 equivalent:

kirschbaumGessoWhy it is manual
protected $responseCodesToSkip = [...]validation.skip_response_codes in gesso.phpkirschbaum's property is per class; Gesso's setting is per suite, and the Laravel trait has no per-class hook.
skipResponseCode(...)same nameSame call, other semantics: kirschbaum keeps the codes for the rest of the test and matches them unanchored; Gesso applies them to the next request only and anchors them. Run vendor/bin/gesso config:migrate before removing kirschbaum: it lists every call with its file and line, and --check fails CI until the package is gone.
overriding getAuthenticatedRequest()laravel.auto_inject_dummy_credentialsThe override is code; Gesso's setting is config.
overriding getOpenApiSpecPath(), getSpecFileType(), or getOpenApiValidatorBuilder()spec.base_path and spec.defaultGesso reads the spec from config. Delete the override.

See kirschbaum-development/laravel-openapi-validator for the rest of the migration.

hotmeteor/spectator ​

Run gesso config:migrate first, while the Spectator::using() calls are still there: it turns a single spec name into spec.default and proposes laravel.auto_assert and laravel.auto_validate_request. Those two settings replace the assertions the set deletes; without them the migrated tests validate nothing.

SpectatorGesso
->assertValidRequest()deleted; laravel.auto_validate_request validates every request
->assertValidResponse()deleted; laravel.auto_assert validates every response
->assertValidResponse($status)->assertStatus($status)
$this->getJson(...)->assertInvalidRequest()$this->expectInvalidRequest()->getJson(...)
$this->getJson(...)->assertInvalidResponse($status)$this->expectInvalidResponse()->getJson(...)->assertStatus($status)
Spectator::using(...);deleted; spec.default, or #[OpenApiSpec('name')] when the tests use several specs
Spectator::reset();deleted; Gesso keeps no per-test spec state. Requests after a mid-test reset() are validated too
a class that used any of theseadds use ValidatesOpenApiSchema;

A statement left with nothing but a variable, such as $response->assertValidResponse();, is deleted. The assertions are TestResponse macros, so the set matches them by name; it leaves a call alone when the receiver's type declares a method of that name itself.

Not rewritten, because the replacement needs a decision:

  • assertInvalidRequest() and assertInvalidResponse() on a variable, such as $response->assertInvalidRequest(): the expectation must be declared before the HTTP call, so move it there as expectInvalidRequest().
  • assertErrorsContain(), assertValidationMessage(), and dumpSpecErrors(): call withoutRequestValidation() or withoutResponseValidation() and assert on the validator result instead.
  • assertPathExists(): compare routes and spec with php artisan gesso:routes.
  • Pest test files: add the trait with uses(ValidatesOpenApiSchema::class).

gesso config:migrate lists every remaining call with its file and line. See Spectator for the rest of the migration.

osteel/openapi-httpfoundation-testing ​

Run gesso config:migrate first and name the spec in gesso.php; the set does not carry over the file passed to ValidatorBuilder.

The set rewrites a call on a value typed as osteel's ValidatorInterface or Validator, by the static type of the message it validates:

osteelGesso
$validator->validate($response, '/users/{id}', 'get')$this->assertOpenApiResponse($response, method: 'get', path: '/users/{id}')
$validator->post($response, '/users') and the other method shortcuts$this->assertOpenApiResponse($response, method: 'POST', path: '/users')
$validator->post($request, '/users')$this->assertOpenApiRequest($request); Gesso finds the operation from the request
$this->assertTrue($validator->...)the assertion alone
expectException(ValidationException::class)expectException(AssertionFailedError::class)
try { <rewritten calls> } catch (ValidationException $e) { $this->fail(...); }the rewritten calls alone
a class that used any of theseadds Gesso's Symfony trait for HttpFoundation messages, or the PSR-7 trait for PSR-7 messages

Not rewritten, because the replacement needs a decision:

  • ValidatorBuilder::from...()->getValidator() and the property or variable that holds the validator: delete them once nothing calls them.
  • A call whose result is used, such as $valid = $validator->get(...), and a try/catch (ValidationException) that does more than call fail(): Gesso's assertions return nothing and fail the test instead.
  • A message or validator whose type Rector cannot see, such as an untyped property: add the type, then run the set again.
  • A class with both HttpFoundation and PSR-7 messages, whose two Gesso traits cannot be combined, and a class that already has assertOpenApiResponse() from elsewhere, such as Gesso's Laravel trait.

gesso config:migrate lists every remaining call with its file and line. See osteel/openapi-httpfoundation-testing for the rest of the migration.

league/openapi-psr7-validator ​

Run gesso config:migrate first and name the spec in gesso.php; the set does not carry over the file passed to ValidatorBuilder.

The set rewrites a statement that calls validate() on a value typed as one of league's validators, and adds Gesso's PSR-7 trait to the class:

leagueGesso
ServerRequestValidator or RequestValidator: ->validate($request)$this->assertOpenApiRequest($request)
RoutedServerRequestValidator: ->validate($address, $request)$this->assertOpenApiRequest($request); Gesso finds the operation from the request
ResponseValidator: ->validate(new OperationAddress($path, $method), $response)$this->assertOpenApiResponse($response, method: $method, path: $path)
expectException(ValidationFailed::class)expectException(AssertionFailedError::class)
try { <rewritten calls> } catch (ValidationFailed $e) { $this->fail(...); }the rewritten calls alone

Not rewritten, because the replacement needs a decision:

  • (new ValidatorBuilder())->from...() and the variables that hold the validators: delete them once nothing calls them.
  • $address = $validator->validate($request), and a response validated against that $address: replace the pair with $this->assertOpenApiExchange($request, $response).
  • An OperationAddress built elsewhere than in the validate() call: pass its path and method as method: and path:.
  • A catch of a ValidationFailed subclass, such as InvalidBody, and a catch that does more than call fail(): Gesso fails the test itself. To inspect the issues, use OpenApiPsr7Validator and its result's issues().
  • The callback validators, and a class that already has assertOpenApiResponse() from elsewhere, such as Gesso's Laravel trait.

gesso config:migrate lists every remaining call with its file and line. See league/openapi-psr7-validator for the rest of the migration.