Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Metayaml Laravel Package

romaricdrigon/metayaml

MetaYAML is a PHP library for loading YAML files and validating their contents against a schema. It catches configuration errors early, supports typed fields and constraints, and builds on Symfony's YAML parser for reliable structured data. Ideal for validating app configuration and metadata files.

Deep Wiki
Context7

Getting Started

Install the package and its YAML parser with Composer:

composer require romaricdrigon/metayaml

The package pulls in symfony/yaml and exposes two main pieces:

  • RomaricDrigon\MetaYaml\Loader\YamlLoader (and JsonLoader) — parses schema/data files into PHP arrays.
  • RomaricDrigon\MetaYaml\MetaYaml — compiles the schema and validates data against it.

Look first at the README schema reference and the package tests/fixtures: they are the quickest way to learn the schema grammar (root, type, children, required, partial, etc.). The main entry point is MetaYaml::validate(), which throws a ValidationException on failure.

Minimal first use case — validating an application YAML config file:

use RomaricDrigon\MetaYaml\Loader\YamlLoader;
use RomaricDrigon\MetaYaml\MetaYaml;
use RomaricDrigon\MetaYaml\Exception\ValidationException;

$yaml   = new YamlLoader();
$schema = $yaml->loadFromFile(base_path('schemas/app.schema.yml'));
$data   = $yaml->loadFromFile(base_path('config/app.yml'));

$metaYaml = new MetaYaml($schema, $yaml);

try {
    $metaYaml->validate($data);
} catch (ValidationException $e) {
    // Invalid config: fail deployment, log, or surface to the user
    throw $e;
}

A small schema looks like this:

root:
  type: array
  children:
    name:  { type: string, required: true }
    debug: { type: boolean }
    port:  { type: number, min: 1, max: 65535 }
    tags:
      type: array
      prototype: { type: string }

The first practical win is a CI/deploy step that validates every YAML file your app depends on before it reaches production.

Implementation Patterns

Artisan config-lint command. Wrap validation in a console command that globs your YAML files, validates each against a schema, and reports all failures. Return a non-zero exit code so CI/deploy scripts fail fast.

foreach (glob(config_path('*.yml')) as $file) {
    try {
        $metaYaml->validate($yaml->loadFromFile($file));
    } catch (ValidationException $e) {
        $this->error(basename($file).': '.$e->getMessage());
        $failed = true;
    }
}

Service-container binding. Load and compile the schema once, not per file or per request. Bind a configured MetaYaml instance as a singleton in a service provider, or expose a small factory that caches parsed schema arrays by name.

Laravel validation-rule adapter. If YAML config is edited at runtime, wrap MetaYaml in a custom rule so failures appear as normal validation errors:

public function validate($attribute, $value, $fail): void
{
    try {
        $this->metaYaml->validate($value);
    } catch (ValidationException $e) {
        $fail($e->getMessage());
    }
}

Schema composition with partials. Use partials for repeated structures — addresses, service definitions, queue configs — and reference them from root or nested children. This keeps large schemas maintainable instead of duplicating the same child tree.

Fixture-driven tests. Keep valid and invalid YAML fixtures and a PHPUnit data provider that asserts valid files pass and invalid files throw ValidationException. Schema changes then get regression coverage instead of silently loosening validation.

Parse → validate → hydrate. Treat validation as a gate before mapping the parsed array into DTOs or passing it to config(). Do not use partially validated arrays; validate the entire document, then consume it.

Cache compiled schemas. YAML parsing plus MetaYaml construction is not free. Cache the parsed schema array (or the constructed validator) in bootstrap/cache and rebuild on deploy.

JSON payloads too. JsonLoader gives the same flow for JSON API payloads; Metayaml is not limited to .yml files.

Gotchas and Tips

YAML parse errors are not validation errors. A malformed file throws a Symfony YAML ParseException before MetaYaml ever sees it. Catch both exception types in your lint command, and report the file path alongside the message.

Symfony YAML type coercion will surprise you. Unquoted yes/no/on/off become booleans; numeric-looking strings become integers/floats; older Symfony YAML versions convert ISO dates to timestamps. A schema expecting type: string can fail on an unquoted value. Quote values in config files or use a custom loader configured with explicit parse flags.

number vs integer. Be explicit. YAML 3 is an integer and 3.0 is a float; choose the schema type that matches how the value is actually written.

Regex patterns need delimiters and anchors. pattern values are PCRE expressions, so write /^[a-z_]+$/, not [a-z_]+. Anchor with ^...$ when you mean a full-string match; otherwise preg_match accepts substrings. In YAML, single-quote patterns or use a block scalar to avoid backslash escaping pain.

required means “key must be present,” not “value must be non-empty.” An empty string or empty array may still satisfy the type check. Add length/bounds constraints where emptiness matters.

Unknown keys may be allowed by default. Enable strict/unknown-key rejection where available in your schema version, otherwise typos like prot instead of port silently pass. Roll it out file-by-file; strict mode can break configs with legacy extra keys.

Partial references are the main reuse mechanism — keep them acyclic and simple. Deep or recursive partial graphs are hard to debug and may not behave the way you expect. Prefer small, named leaf partials composed at the root.

Error messages can be terse and may omit the full data path. When a validation failure is ambiguous, validate a smaller subtree or wrap the exception with the file name and the section being checked. Do not show raw library messages directly to end users.

Do not rebuild the validator per request. In long-running workers (queue workers, Octane), construct the schema once per process and reuse it. Clear cached schemas on deploy so schema changes take effect.

Check maintenance and PHP compatibility before adopting. This is an older, low-activity package. Verify it installs cleanly on your PHP and Symfony YAML versions; on modern stacks you may need to pin symfony/yaml or maintain a fork. For brand-new projects, compare with actively maintained JSON-Schema validators or Laravel’s native validation; Metayaml is most compelling when you already have YAML-heavy config and want schema-driven checks.

Custom loaders are the extension point. Implement LoaderInterface if you need env-var interpolation, custom YAML tags, or data pulled from a database. Resolve environment variables before validation so the schema sees the final values.

Test the schema itself. A too-permissive schema silently lets bad config through. Keep at least one intentionally invalid fixture per important constraint (required key, enum, bounds, pattern) and assert that it fails.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
adachsoft/php-code-style