PHP code example of neuron-php / cli

1. Go to this page and download the library: Download neuron-php/cli library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

neuron-php / cli example snippets




namespace Neuron\YourComponent\Cli;

class CommandProvider
{
    public static function register($app): void
    {
        // Register your commands
        $app->register('component:command1', Command1::class);
        $app->register('component:command2', Command2::class);
        $app->register('component:command3', Command3::class);
    }
}



namespace Neuron\YourComponent\Commands;

use Neuron\Cli\Commands\Command;

class MakeControllerCommand extends Command
{
    /**
     * Get the command name (how it's invoked)
     */
    public function getName(): string
    {
        return 'make:controller';
    }
    
    /**
     * Get the command description (shown in list)
     */
    public function getDescription(): string
    {
        return 'Create a new controller class';
    }
    
    /**
     * Configure arguments and options
     */
    public function configure(): void
    {
        // Add e to use', 'default');
    }
    
    /**
     * Execute the command
     * 
     * @return int Exit code (0 for success)
     */
    public function execute(): int
    {
        // Get arguments
        $name = $this->input->getArgument('name');
        $namespace = $this->input->getArgument('namespace');
        
        // Get options
        $isResource = $this->input->getOption('resource');
        $model = $this->input->getOption('model');
        
        // Output messages
        $this->output->info("Creating controller: {$name}");
        
        // Show progress for long operations
        $progress = $this->output->createProgressBar(100);
        $progress->start();
        
        for ($i = 0; $i < 100; $i++) {
            // Do work...
            $progress->advance();
            usleep(10000);
        }
        
        $progress->finish();
        
        // Success message
        $this->output->success("Controller created successfully!");
        
        return 0; // Success
    }
}

// Simple messages
$this->output->write('Simple message');
$this->output->writeln('Message with newline', 'green');

// Styled messages
$this->output->info('Information message');      // Cyan
$this->output->success('Success message');       // Green with ✓
$this->output->warning('Warning message');       // Yellow with ⚠
$this->output->error('Error message');          // Red with ✗
$this->output->comment('Comment');              // Yellow

// Sections and titles
$this->output->title('Command Title');
$this->output->section('Section Header');

$this->output->table(
    ['Name', 'Version', 'Description'],
    [
        ['cli', '1.0.0', 'CLI component'],
        ['mvc', '0.6.0', 'MVC framework'],
        ['cms', '0.5.0', 'Content management'],
    ]
);

$progress = $this->output->createProgressBar(100);
$progress->start();

foreach ($items as $item) {
    // Process item...
    $progress->advance();
}

$progress->finish();

// Check if terminal is interactive
if (!$this->input->isInteractive()) {
    $this->output->error('This command onymous');

// Ask without default (returns empty string if no input)
$email = $this->input->ask('Enter your email');

// Ask yes/no questions
if ($this->input->confirm('Do you want to continue?', true)) {
    // User confirmed (pressed y/yes/1/true or Enter with default true)
}

// Read raw input with custom prompt
$line = $this->input->readLine('> ');

class SetupCommand extends Command
{
    public function execute(): int
    {
        if (!$this->input->isInteractive()) {
            $this->output->error('Setup ut->ask('Author name');
        $email = $this->input->ask('Author email');
        
        // Validate email
        while (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->output->error('Invalid email format');
            $email = $this->input->ask('Author email');
        }
        
        // Show summary
        $this->output->section('Configuration Summary');
        $this->output->write("Project: {$project}");
        $this->output->write("Author: {$author} <{$email}>");
        
        // Confirm
        if (!$this->input->confirm('Create project with these settings?', true)) {
            $this->output->warning('Setup cancelled');
            return 1;
        }
        
        // Proceed with setup...
        $this->output->success('Project created successfully!');
        return 0;
    }
}

// Ask for password (input will be hidden)
$password = $this->input->askSecret('Enter password');

// Confirm password
$confirm = $this->input->askSecret('Confirm password');

if ($password !== $confirm) {
    $this->output->error('Passwords do not match');
    return 1;
}

// Simple choice from array
$colors = ['Red', 'Green', 'Blue'];
$color = $this->input->choice('Pick a color:', $colors, 'Blue');

// Associative array (key => display value)
$environments = [
    'dev' => 'Development',
    'staging' => 'Staging', 
    'prod' => 'Production'
];
$env = $this->input->choice('Select environment:', $environments, 'dev');

// Multiple selection
$features = [
    'api' => 'REST API',
    'auth' => 'Authentication',
    'cache' => 'Caching'
];
$selected = $this->input->choice(
    'Select features to enable:',
    $features,
    null,        // No default
    true         // Allow multiple
);
// Returns array like: ['api', 'auth']

// Users can select by:
// - Number: Type "1" for first option
// - Key: Type "dev" for development
// - Value: Type "Development" (case-insensitive)
// - Multiple: "1,3" or "api,cache" (when multiple allowed)

public function execute(): int
{
    try {
        // Command logic...
        return 0;
    } catch (ValidationException $e) {
        $this->output->error('Validation failed: ' . $e->getMessage());
        return 2;
    } catch (\Exception $e) {
        $this->output->error('An error occurred: ' . $e->getMessage());
        return 1;
    }
}

use PHPUnit\Framework\TestCase;
use Neuron\Cli\Console\Input;
use Neuron\Cli\Console\Output;

class MakeControllerCommandTest extends TestCase
{
    public function testExecute(): void
    {
        $command = new MakeControllerCommand();

        // Mock input
        $input = new Input(['UserController', '--resource']);
        $output = new Output(false); // No colors for testing

        $command->setInput($input);
        $command->setOutput($output);
        $command->configure();
        $input->parse($command);

        $exitCode = $command->execute();

        $this->assertEquals(0, $exitCode);
    }
}

use PHPUnit\Framework\TestCase;
use Neuron\Cli\Console\Input;
use Neuron\Cli\Console\Output;
use Neuron\Cli\IO\TestInputReader;

class SetupCommandTest extends TestCase
{
    public function testInteractiveSetup(): void
    {
        $command = new SetupCommand();

        // Create test input reader with pre-programmed responses
        $inputReader = new TestInputReader();
        $inputReader->addResponse('my-project');        // Project name
        $inputReader->addResponse('John Doe');          // Author name
        $inputReader->addResponse('[email protected]');  // Email
        $inputReader->addResponse('yes');               // Confirmation

        // Configure command
        $input = new Input([]);
        $output = new Output(false);

        $command->setInput($input);
        $command->setOutput($output);
        $command->setInputReader($inputReader);

        // Execute command
        $exitCode = $command->execute();

        // Assertions
        $this->assertEquals(0, $exitCode);

        // Verify the prompts that were shown
        $prompts = $inputReader->getPromptHistory();
        $this->assertCount(4, $prompts);
        $this->assertStringContainsString('Project name', $prompts[0]);
        $this->assertStringContainsString('Author name', $prompts[1]);
    }

    public function testUserCancelsSetup(): void
    {
        $command = new SetupCommand();

        // User will cancel the setup
        $inputReader = new TestInputReader();
        $inputReader->addResponses([
            'test-project',
            'Test User',
            '[email protected]',
            'no'  // Cancel confirmation
        ]);

        $input = new Input([]);
        $output = new Output(false);

        $command->setInput($input);
        $command->setOutput($output);
        $command->setInputReader($inputReader);

        $exitCode = $command->execute();

        // Should return non-zero exit code when cancelled
        $this->assertNotEquals(0, $exitCode);
    }
}

class SetupCommand extends Command
{
    public function execute(): int
    {
        // Use built-in convenience methods instead of reading STDIN directly
        $name = $this->prompt('Enter project name: ');

        if ($this->confirm('Enable caching?', true)) {
            // User confirmed
        }

        $password = $this->secret('Enter password: ');

        $env = $this->choice(
            'Select environment:',
            ['development', 'staging', 'production'],
            'development'
        );

        return 0;
    }
}

$reader = new TestInputReader();
$reader
    ->addResponse('value1')
    ->addResponse('value2')
    ->addResponse('yes');

// Check if there are responses remaining
if ($reader->hasMoreResponses()) {
    $count = $reader->getRemainingResponseCount();
}

// Get history of prompts
$prompts = $reader->getPromptHistory();

// Reset for reuse
$reader->reset();
bash
composer 
bash
composer global