PHP code example of phpdevcommunity / php-console

1. Go to this page and download the library: Download phpdevcommunity/php-console 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/ */

    

phpdevcommunity / php-console example snippets


#!/usr/bin/php


use PhpDevCommunity\Console\CommandParser;
use PhpDevCommunity\Console\CommandRunner;
use PhpDevCommunity\Console\Output;

set_time_limit(0);

if (file_exists(dirname(__DIR__) . '/../../autoload.php')) {
    
        'curl -sS https://getcomposer.org/installer | php' . PHP_EOL .
        'php composer.phar install' . PHP_EOL
    );
}


// For modern frameworks using containers and bootstrapping (e.g., Kernel or App classes),
// make sure to retrieve the CommandRunner from the container after booting the application.
// Example for Symfony:
//
// $kernel = new Kernel('dev', true);
// $kernel->boot();
// $container = $kernel->getContainer();
// $app = $container->get(CommandRunner::class);


$app = new CommandRunner([]);
$exitCode = $app->run(new CommandParser(), new Output());
exit($exitCode);

use PhpDevCommunity\Console\Argument\CommandArgument;
use PhpDevCommunity\Console\Command\CommandInterface;
use PhpDevCommunity\Console\InputInterface;
use PhpDevCommunity\Console\Option\CommandOption;
use PhpDevCommunity\Console\OutputInterface;

class SendEmailCommand implements CommandInterface
{
    public function getName(): string
    {
        return 'send-email';
    }

    public function getDescription(): string
    {
        return 'Sends an email to the specified recipient with an optional subject.';
    }

    public function getOptions(): array
    {
        return [
            new CommandOption('subject', 's', 'The subject of the email', false),
        ];
    }

    public function getArguments(): array
    {
        return [
            new CommandArgument('recipient', true, null, 'The email address of the recipient'),
        ];
    }

    public function execute(InputInterface $input, OutputInterface $output): void
    {
        // Validate and retrieve the recipient email
        if (!$input->hasArgument('recipient')) {
            $output->writeln('Error: The recipient email is 

use PhpDevCommunity\Console\CommandRunner;

$app = new CommandRunner([
    new SendEmailCommand()
]);


use PhpDevCommunity\Console\Argument\CommandArgument;

new CommandArgument(
    'recipient', // The name of the argument
    true,        // The argument is 

use PhpDevCommunity\Console\Option\CommandOption;

new CommandOption(
    'subject',    // The name of the option
    's',          // Shortcut
    'The subject of the email', // Description
    false         // Not a flag, expects a value
);

new CommandOption(
    'verbose',    // The name of the option
    'v',          // Shortcut
    'Enable verbose output', // Description
    true          // This is a flag
);

use PhpDevCommunity\Console\Argument\CommandArgument;
use PhpDevCommunity\Console\Option\CommandOption;

public function getArguments(): array
{
    return [
        new CommandArgument('recipient', true, null, 'The email address of the recipient'),
    ];
}

public function getOptions(): array
{
    return [
        new CommandOption('subject', 's', 'The subject of the email', false),
        new CommandOption('verbose', 'v', 'Enable verbose output', true),
    ];
}

use PhpDevCommunity\Console\Argument\CommandArgument;
use PhpDevCommunity\Console\Command\CommandInterface;
use PhpDevCommunity\Console\InputInterface;
use PhpDevCommunity\Console\Option\CommandOption;
use PhpDevCommunity\Console\Output\ConsoleOutput;
use PhpDevCommunity\Console\OutputInterface;

class UserReportCommand implements CommandInterface
{
    public function getName(): string
    {
        return 'user:report';
    }

    public function getDescription(): string
    {
        return 'Generates a detailed report for a specific user.';
    }

    public function getArguments(): array
    {
        return [
            new CommandArgument('user_id', true, null, 'The ID of the user to generate the report for'),
        ];
    }

    public function getOptions(): array
    {
        return [
            new CommandOption('verbose', 'v', 'Enable verbose output', true),
            new CommandOption('export', 'e', 'Export the report to a file', false),
        ];
    }

    public function execute(InputInterface $input, OutputInterface $output): void
    {
        $console = new ConsoleOutput($output);

        // Main title
        $console->title('User Report Generation');

        // Arguments and options
        $userId = $input->getArgumentValue('user_id');
        $verbose = $input->hasOption('verbose');
        $export = $input->hasOption('export') ? $input->getOptionValue('export') : null;

        $console->info("Generating report for User ID: $userId");

        // Simulating user data retrieval
        $console->spinner();
        $userData = [
            'name' => 'John Doe',
            'email' => '[email protected]',
            'active' => true,
            'roles' => ['admin', 'user']
        ];

        if ($verbose) {
            $console->success('User data retrieved successfully.');
        }

        // Displaying user data
        $console->json($userData);

        // Displaying user roles as a list
        $console->listKeyValues([
            'Name' => $userData['name'],
            'Email' => $userData['email'],
            'Active' => $userData['active'] ? 'Yes' : 'No',
        ]);
        $console->list($userData['roles']);

        // Table of recent activities
        $headers = ['ID', 'Activity', 'Timestamp'];
        $rows = [
            ['1', 'Login', '2024-12-22 12:00:00'],
            ['2', 'Update Profile', '2024-12-22 12:30:00'],
        ];
        $console->table($headers, $rows);

        // Progress bar
        for ($i = 0; $i <= 100; $i += 20) {
            $console->progressBar(100, $i);
            usleep(500000);
        }

        // Final result
        if ($export) {
            $console->success("Report exported to: $export");
        } else {
            $console->success('Report generated successfully!');
        }

        // Confirmation for deletion
        if ($console->confirm('Do you want to delete this user?')) {
            $console->success('User deleted successfully.');
        } else {
            $console->warning('User deletion canceled.');
        }
    }
}