Completed
Push — master ( 413e80...ae17bf )
by Terry
01:39
created

TestRunner::runTests()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 29
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 18
nc 5
nop 4
dl 0
loc 29
rs 8.5806
c 0
b 0
f 0
1
#!/usr/bin/env php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 8 and the first side effect is on line 1.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
<?php declare(strict_types=1);
3
4
use Terah\Assert\Tester;
5
6
require_once __DIR__ . '/../vendor/autoload.php';
7
8
class TestRunner
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
9
{
10
    public static function run()
11
    {
12
        $fileName       = (string)static::getArg(1, getcwd());
13
        $suite          = (string)static::getArg('suite', '');
14
        $test           = (string)static::getArg('test', '');
15
        $recursive      = (bool)static::getArg('recursive', true);
16
        $generate       = (string)static::getArg('generate', '');
17
        $output         = (string)static::getArg('output', '');
18
        if ( $generate )
19
        {
20
            static::generate($generate, $output);
21
        }
22
23
        static::runTests($fileName, $suite, $test, $recursive);
24
    }
25
26
    public static function generate(string $generate, string $output)
27
    {
28
        Tester::generateTest($generate, $output);
29
30
        exit(0);
31
    }
32
33
    /**
34
     * @param string $fileName
35
     * @param string $suite
36
     * @param string $test
37
     * @param bool   $recursive
38
     */
39
    public static function runTests(string $fileName, string $suite, string $test, bool $recursive)
40
    {
41
        $totalFailed    = 0;
42
        $totalTests     = 0;
43
        $tests          = static::getTestFiles($fileName, $recursive);
44
        if ( empty($tests) )
45
        {
46
            Tester::getLogger()->error("No test files found/specified");
47
48
            exit(1);
49
        }
50
        foreach ( $tests as $fileName )
51
        {
52
            Tester::getLogger()->debug("Loading test file {$fileName}");
53
            require($fileName);
54
            $results        = Tester::run($suite, $test);
55
            $totalFailed    += $results['totalFailed'];
56
            $totalTests     += $results['totalTests'];
57
        }
58
        if ( $totalFailed )
59
        {
60
            Tester::getLogger()->error("Tests failed - {$totalFailed} of {$totalTests} tests have failed.");
61
62
            exit(1);
63
        }
64
        Tester::getLogger()->info("Tests succeeded - {$totalTests} tests have passed.");
65
66
        exit(0);
67
    }
68
69
    /**
70
     * @param string $fileName
71
     * @param bool   $recursive
72
     * @return array
73
     */
74
    protected static function getTestFiles(string $fileName='', bool $recursive=false) : array
75
    {
76
        if ( empty($fileName) )
77
        {
78
            return [];
79
        }
80
        if ( ! file_exists($fileName) )
81
        {
82
            Tester::getLogger()->error("{$fileName} does not exist; exiting");
83
84
            exit(1);
85
        }
86
        $fileName   = realpath($fileName);
87
        if ( is_dir($fileName) )
88
        {
89
            $iterator       = new \DirectoryIterator($fileName);
90
            if ( $recursive )
91
            {
92
                $iterator       = new \RecursiveDirectoryIterator($fileName);
93
                $iterator       = $recursive ? new RecursiveIteratorIterator($iterator) : $iterator;
94
            }
95
            $testFiles      = [];
96
            foreach ( $iterator as $fileInfo )
97
            {
98
                if ( preg_match('/Suite.php$/', $fileInfo->getBasename()) )
99
                {
100
                    $testFiles[] = $fileInfo->getPathname();
101
                }
102
            }
103
104
            return $testFiles;
105
        }
106
        if ( ! is_file($fileName) )
107
        {
108
            Tester::getLogger()->error("{$fileName} is not a file; exiting");
109
110
            exit(1);
111
        }
112
113
        return [$fileName];
114
    }
115
116
    /**
117
     * PARSE ARGUMENTS
118
     *
119
     * This command line option parser supports any combination of three types of options
120
     * [single character options (`-a -b` or `-ab` or `-c -d=dog` or `-cd dog`),
121
     * long options (`--foo` or `--bar=baz` or `--bar baz`)
122
     * and arguments (`arg1 arg2`)] and returns a simple array.
123
     *
124
     * [pfisher ~]$ php test.php --foo --bar=baz --spam eggs
125
     *   ["foo"]   => true
126
     *   ["bar"]   => "baz"
127
     *   ["spam"]  => "eggs"
128
     *
129
     * [pfisher ~]$ php test.php -abc foo
130
     *   ["a"]     => true
131
     *   ["b"]     => true
132
     *   ["c"]     => "foo"
133
     *
134
     * [pfisher ~]$ php test.php arg1 arg2 arg3
135
     *   [0]       => "arg1"
136
     *   [1]       => "arg2"
137
     *   [2]       => "arg3"
138
     *
139
     * [pfisher ~]$ php test.php plain-arg --foo --bar=baz --funny="spam=eggs" --also-funny=spam=eggs \
140
     * > 'plain arg 2' -abc -k=value "plain arg 3" --s="original" --s='overwrite' --s
141
     *   [0]       => "plain-arg"
142
     *   ["foo"]   => true
143
     *   ["bar"]   => "baz"
144
     *   ["funny"] => "spam=eggs"
145
     *   ["also-funny"]=> "spam=eggs"
146
     *   [1]       => "plain arg 2"
147
     *   ["a"]     => true
148
     *   ["b"]     => true
149
     *   ["c"]     => true
150
     *   ["k"]     => "value"
151
     *   [2]       => "plain arg 3"
152
     *   ["s"]     => "overwrite"
153
     *
154
     * Not supported: `-cd=dog`.
155
     *
156
     * @author              Patrick Fisher <[email protected]>
157
     * @since               August 21, 2009
158
     * @see                 https://github.com/pwfisher/CommandLine.php
159
     * @see                 http://www.php.net/manual/en/features.commandline.php
160
     *                      #81042 function arguments($argv) by technorati at gmail dot com, 12-Feb-2008
161
     *                      #78651 function getArgs($args) by B Crawford, 22-Oct-2007
162
     * @usage               $args = CommandLine::parseArgs($_SERVER['argv']);
163
     * @param array $argv
164
     * @return array
165
     */
166
    protected static function parseArgs(array $argv=[]) : array
167
    {
168
        $argv = $argv ?: ! empty($_SERVER['argv']) ? $_SERVER['argv'] : [];
169
        array_shift($argv);
170
        $out = [];
171
        for ( $i = 0, $j = count($argv); $i < $j; $i++ )
172
        {
173
            $arg = $argv[$i];
174
            // --foo --bar=baz
175
            if ( mb_substr($arg, 0, 2) === '--' )
176
            {
177
                $eqPos = mb_strpos($arg, '=');
178
                // --foo
179
                if ($eqPos === false)
180
                {
181
                    $key = mb_substr($arg, 2);
182
                    // --foo value
183
                    if ($i + 1 < $j && $argv[$i + 1][0] !== '-')
184
                    {
185
                        $value = $argv[$i + 1];
186
                        $i++;
187
                    }
188
                    else
189
                    {
190
                        $value = isset($out[$key]) ? $out[$key] : true;
191
                    }
192
                    $out[$key] = $value;
193
                }
194
                // --bar=baz
195
                else
196
                {
197
                    $key        = mb_substr($arg, 2, $eqPos - 2);
198
                    $value      = mb_substr($arg, $eqPos + 1);
199
                    $out[$key]  = $value;
200
                }
201
            }
202
            // -k=value -abc
203
            else if (mb_substr($arg, 0, 1) === '-')
204
            {
205
                // -k=value
206
                if (mb_substr($arg, 2, 1) === '=')
207
                {
208
                    $key       = mb_substr($arg, 1, 1);
209
                    $value     = mb_substr($arg, 3);
210
                    $out[$key] = $value;
211
                }
212
                // -abc
213
                else
214
                {
215
                    $chars = str_split(mb_substr($arg, 1));
216
                    $key = '';
217
                    foreach ( $chars as $char )
218
                    {
219
                        $key       = $char;
220
                        $value     = isset($out[$key]) ? $out[$key] : true;
221
                        $out[$key] = $value;
222
                    }
223
                    // -a value1 -abc value2
224
                    if ($i + 1 < $j && $argv[$i + 1][0] !== '-')
225
                    {
226
                        $out[$key] = $argv[$i + 1];
227
                        $i++;
228
                    }
229
                }
230
            }
231
            // plain-arg
232
            else
233
            {
234
                $value = $arg;
235
                $out[] = $value;
236
            }
237
        }
238
        foreach ( $out as $idx => $val )
239
        {
240
            if ( is_string($val) && strpos($val, '|') !== false )
241
            {
242
                $out[$idx] = explode('|', $val);
243
            }
244
        }
245
246
        return $out;
247
    }
248
249
    /**
250
     * @param $name
251
     * @param mixed $default
252
     * @return string
253
     */
254
    protected static function getArg($name, $default=null)
255
    {
256
        $args = static::parseArgs();
257
258
        return isset($args[$name]) && $args[$name] ? $args[$name] : $default;
259
    }
260
261
}
262
263
TestRunner::run();