Validation
Custom rules
Enforce your own conventions with a validation rule, checked on the written document.
A rule enforces a convention of your API: every operation has a summary, every path is in kebab case, every error
response uses the Error schema. It is a class implementing Rule, added to the validator.
Writing a rule
check() receives the document as written for the version (the array of toArray()), the version, and the
Violations to add to:
use Ark4ne\OpenApiWriter\Enums\Version;
use Ark4ne\OpenApiWriter\Support\JsonPointer;
use Ark4ne\OpenApiWriter\Validation\Rule;
use Ark4ne\OpenApiWriter\Validation\Severity;
use Ark4ne\OpenApiWriter\Validation\Violation;
use Ark4ne\OpenApiWriter\Validation\Violations;
final class OperationSummaryRule implements Rule
{
private const METHODS = ['get', 'put', 'post', 'delete', 'patch'];
public function check(
array $document,
Version $version,
Violations $violations,
): void {
$paths = is_array($document['paths'] ?? null)
? $document['paths']
: [];
foreach ($paths as $path => $pathItem) {
foreach (self::METHODS as $method) {
$operation = $pathItem[$method] ?? null;
if (is_array($operation) && !isset($operation['summary'])) {
$violations->add(new Violation(
JsonPointer::root()
->append('paths', (string) $path, $method),
'operation-summary',
'the operation has no summary',
Severity::Warning,
));
}
}
}
}
}
- Read the array defensively: the rule also runs on invalid documents.
JsonPointer::root()->append(...)escapes each segment, so/booksbecomes~1books.- The second argument of
Violationnames the rule in the messages; the severity defaults toSeverity::Error.
Adding it
use Ark4ne\OpenApiWriter\Validation\Validator;
$validator = Validator::create()->withRules(new OperationSummaryRule());
$warnings = array_map(
'strval',
$validator->validate($document)->warnings(),
);
[warning] /paths/~1books/get: the operation has no summary (operation-summary)
Because the rule reads the written document, it sees what each version writes: nullable: true in 3.0,
type: [string, "null"] in 3.1. Use $version when the check depends on it.