summaryrefslogtreecommitdiff
path: root/src/Application.php
blob: 88843acec730193987375dc9fa62689f032dd067 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php

namespace FBeans\BlaIRC;

use FBeans\BlaIRC\Command;
use Symfony\Component\Console\Application as SymfonyApplication;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\Process;

abstract class Application
{
    protected $input;
    protected $output;
    protected $application;

    // ... put here the code to run in your command

    // this method must return an integer number with the "exit status code"
    // of the command. You can also use these constants to make code more readable

    // return this if there was no problem running the command
    // (it's equivalent to returning int(0))


    // or return this if some error happened during the execution
    // (it's equivalent to returning int(1))
    // return Command::FAILURE;
    abstract protected function command(): Command;

    public function fromArgv()
    {
        return $this->setInput(new ArgvInput());
    }

    public function fromStdin()
    {
        return $this->setInput(new ArrayInput($this->readStdin()));
    }

    public function toConsole()
    {
        return $this->setOutput(new ConsoleOutput);
    }

    public function toIRC()
    {
        return null;
    }

    public function __construct(InputInterface $input = null, OutputInterface $output = null)
    {
        $this->setInput($input)->setOutput($output);
    }

    public function setInput(InputInterface $input = null)
    {
        $this->input = $input;

        return $this;
    }

    public function setOutput(OutputInterface $output = null)
    {
        $this->output = $output;

        return $this;
    }

    public function run()
    {
        $this->application = new SymfonyApplication();
        $command = $this->command();

        $this->application->add($command);
        $this->application->setDefaultCommand($command->getName());
        $this->application->run($this->input, $this->output);
    }

    protected function readStdin()
    {
        $stream = fopen("php://stdin", "r");
        $input_string = fgets($stream, 128);
        $input_string = rtrim($input_string);

        $input_array = explode(' ', $input_string);

        fclose($stream);

        return $input_array;
    }
}