vikkio88/slime

View on GitHub
novice

Summary

Maintainability
Test Coverage
#!/usr/bin/env php
<?php

use App\Lib\Helpers\Config;
use App\Lib\Helpers\TextFormatter;

require __DIR__ . '/vendor/autoload.php';

class Novice
{
    protected $commandPaths = [

    ];

    function __construct($args)
    {
        $this->args = $args;
        $this->commandPaths = Config::get('console.commandPaths');
    }

    function exec()
    {
        if (count($this->args) <= 1) {
            $this->reportError("usage: php " . $this->args[0] . " <command> [<args>]");
        }

        $args = array_slice($this->args, 2);
        $commandClass = $this->getCommandClass($this->args[1]);

        if (empty($commandClass)) {
            $this->reportError("Command not found" . $commandClass);
        }

        $command = $this->createCommandClass($commandClass, $args);
        try {
            $return = $command->run();
            exit($return);
        } catch (Exception $exception) {
            $this->reportError($exception->getMessage());
        }
    }

    private function getCommandClass($commandName)
    {
        foreach ($this->commandPaths as $commandPath) {
            $commandFullName = $this->generateClassName($commandPath, $commandName);
            if (class_exists($commandFullName)) {
                return $commandFullName;
            }
        }

        return false;
    }

    private function createCommandClass($commandClass, $args)
    {
        return new $commandClass($args);
    }

    private function reportError($message)
    {
        echo $message . PHP_EOL;
        exit(1);
    }

    private function generateClassName($commandPath, $commandName)
    {
        return $commandPath . TextFormatter::snakeToCamelCase($commandName) . 'Command';
    }
}

$novice = new Novice($argv);
$novice->exec();