Skip to content

Commit c443387

Browse files
committed
Refactor CLI detection into a separate function to be able to mock it
1 parent 679b5e7 commit c443387

File tree

3 files changed

+60
-1
lines changed

3 files changed

+60
-1
lines changed

src/Debug.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ public function printValue($var, int $flags = null)
154154
}
155155

156156
$output = static::debugValue($var, $flags);
157-
if (PHP_SAPI !== 'cli') {
157+
if (!$this->isCli()) {
158158
$output = "<pre>{$output}</pre>";
159159
}
160160
echo $output;
@@ -204,4 +204,14 @@ public function logValue($var, int $flags = null)
204204
{
205205
$this->Logger->addDebug(static::debugValue($var, $flags));
206206
}
207+
208+
/**
209+
* Check whether we are in a CLI environment.
210+
*
211+
* @return bool
212+
*/
213+
protected function isCli(): bool
214+
{
215+
return substr(PHP_SAPI, 0, 3) === 'cli';
216+
}
207217
}

tests/DbgTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,27 @@ public function testPrintArray()
4545
[2] => third
4646
)
4747

48+
EOT;
49+
$this->assertEquals($expected, $this->captureOutput($var));
50+
}
51+
52+
/**
53+
* Test printing output in non-CLI environment.
54+
*
55+
* @return void
56+
*/
57+
public function testPrintArrayNonCli()
58+
{
59+
TestDebug::init();
60+
$var = ['first', 'second', 'third'];
61+
$expected = <<<'EOT'
62+
<pre>Array
63+
(
64+
[0] => first
65+
[1] => second
66+
[2] => third
67+
)
68+
</pre>
4869
EOT;
4970
$this->assertEquals($expected, $this->captureOutput($var));
5071
}

tests/TestDebug.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php
2+
3+
/**
4+
* Debug class for testing.
5+
*
6+
* @copyright Fabian Wiget <fabacino@gmail.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Fabacino\Debug\Test;
13+
14+
class TestDebug extends \Fabacino\Debug\Debug
15+
{
16+
/**
17+
* Check whether we are in a CLI environment.
18+
*
19+
* @return bool
20+
*/
21+
protected function isCli(): bool
22+
{
23+
// PHPUnit is always executed through CLI. In order to be able to check
24+
// functionality which is working only in a non-CLI environment, we just
25+
// pretend that PHP is running in a non-CLI environment.
26+
return false;
27+
}
28+
}

0 commit comments

Comments
 (0)