Passed
Pull Request — master (#242)
by Théo
02:27
created

CommandTestCase::getCommandTester()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the box project.
7
 *
8
 * (c) Kevin Herrera <[email protected]>
9
 *     Théo Fidry <[email protected]>
10
 *
11
 * This source file is subject to the MIT license that is bundled
12
 * with this source code in the file LICENSE.
13
 */
14
15
namespace KevinGH\Box\Test;
16
17
use KevinGH\Box\Console\Application;
18
use Symfony\Component\Console\Command\Command;
19
use Symfony\Component\Console\Output\StreamOutput;
20
use Symfony\Component\Console\Tester\CommandTester;
21
22
/**
23
 * @private
24
 */
25
abstract class CommandTestCase extends FileSystemTestCase
26
{
27
    /**
28
     * @var Application
29
     */
30
    protected $application;
31
32
    /**
33
     * @var CommandTester
34
     */
35
    protected $commandTester;
36
37
    /**
38
     * @var string the name of the command
39
     */
40
    private $name;
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    protected function setUp(): void
46
    {
47
        parent::setUp();
48
49
        $this->application = new Application();
50
51
        $this->name = $this->getCommand()->getName();
52
53
        $this->application->add($this->getCommand());
54
55
        $this->commandTester = new CommandTester($this->application->get($this->name));
56
    }
57
58
    /**
59
     * {@inheritdoc}
60
     */
61
    protected function tearDown(): void
62
    {
63
        parent::tearDown();
64
65
        $this->application = null;
66
    }
67
68
    /**
69
     * Returns the command to be tested.
70
     *
71
     * @return Command the command
72
     */
73
    abstract protected function getCommand(): Command;
74
75
    /**
76
     * Returns the output for the tester.
77
     *
78
     * @param CommandTester $tester the tester
79
     *
80
     * @return string the output
81
     */
82
    protected function getOutput(CommandTester $tester)
83
    {
84
        /** @var $output StreamOutput */
85
        $output = $tester->getOutput();
86
        $stream = $output->getStream();
87
        $string = '';
88
89
        rewind($stream);
90
91
        while (false === feof($stream)) {
92
            $string .= fgets($stream);
93
        }
94
95
        $string = preg_replace(
96
            [
97
                '/\x1b(\[|\(|\))[;?0-9]*[0-9A-Za-z]/',
98
                '/[\x03|\x1a]/',
99
            ],
100
            ['', '', ''],
101
            $string
102
        );
103
104
        return str_replace(PHP_EOL, "\n", $string);
105
    }
106
}
107