Console

Use a console command for work you want to run from the terminal or a script. Atom resolves command classes through its injector and binds command-line values to the parameters of execute().

Command Class

This command checks a JSON file. Its required $path parameter is a positional argument. The boolean $quiet parameter is an option that defaults to false.

app/Commands/CheckJsonCommand.php
<?php

declare(strict_types=1);

namespace App\Commands;

use Atom\Console\Command;

final class CheckJsonCommand extends Command
{
    protected static string $name = "json:check";
    protected static string $description = "Check the syntax of a JSON file";

    protected function execute(string $path, bool $quiet = false): int
    {
        $json = @file_get_contents($path);
        if ($json === false) {
            $this->errorLine("Cannot read {$path}.");
            return 1;
        }

        if (!json_validate($json)) {
            $this->errorLine("Invalid JSON in {$path}: " . json_last_error_msg());
            return 1;
        }

        if (!$quiet) {
            $this->line("Valid JSON in {$path}.");
        }

        return 0;
    }
}

line() writes normal output and errorLine() writes to standard error. The integer returned by execute() becomes the command's exit code. Here 0 means the file is valid and 1 means the check failed.

Register Commands

Register the class with the application's console in bootstrap(). add() uses the name and description declared on the class.

app/Application.php (excerpt)
use App\Commands\CheckJsonCommand;
use Atom\Di\Injector;

protected function bootstrap(Injector $injector): void
{
    $this->getConsole()->add(CheckJsonCommand::class);
}

If your application already discovers the directory through a console provider, saving the class there is enough.

Run

From the project root, pass the JSON path after the command name. Add --quiet to suppress the success message. Errors still go to standard error.

php atom json:check composer.json
php atom json:check composer.json --quiet

Use php atom help to list registered commands. See Publishing for commands that copy framework or module files into an application.