Make is_windows() mockable

This commit is contained in:
John Paul E. Balandan, CPA 2022-11-24 10:50:40 +08:00
parent 7c8555b65a
commit 30a6bb1b2b
No known key found for this signature in database
GPG Key ID: FB7B51499BC27610
4 changed files with 45 additions and 2 deletions

View File

@ -725,8 +725,18 @@ if (! function_exists('is_windows')) {
/**
* Detect if platform is running in Windows.
*/
function is_windows(): bool
function is_windows(?bool $mock = null): bool
{
static $mocked;
if (func_num_args() === 1) {
$mocked = $mock;
}
if (isset($mocked)) {
return $mocked;
}
return DIRECTORY_SEPARATOR === '\\';
}
}

View File

@ -706,4 +706,19 @@ final class CommonFunctionsTest extends CIUnitTestCase
$this->assertSame(strpos(php_uname(), 'Windows') !== false, is_windows());
$this->assertSame(defined('PHP_WINDOWS_VERSION_MAJOR'), is_windows());
}
public function testIsWindowsUsingMock()
{
is_windows(true);
$this->assertTrue(is_windows());
$this->assertNotFalse(is_windows());
is_windows(false);
$this->assertFalse(is_windows());
$this->assertNotTrue(is_windows());
is_windows(null);
$this->assertSame(strpos(php_uname(), 'Windows') !== false, is_windows());
$this->assertSame(defined('PHP_WINDOWS_VERSION_MAJOR'), is_windows());
}
}

View File

@ -281,12 +281,19 @@ Miscellaneous Functions
:returns: true if you can write to the file, false otherwise.
:rtype: bool
.. php:function:: is_windows()
.. php:function:: is_windows([$mock = null])
:param bool|null $mock: If given and is a boolean then it will be used as the return value.
:rtype: bool
Detect if platform is running in Windows.
.. note:: The boolean value provided to $mock will persist in subsequent calls. To reset this
mock value, the user must pass an explicit ``null`` to the function call. This will
refresh the function to use auto-detection.
.. literalinclude:: common_functions/012.php
.. php:function:: log_message($level, $message [, $context])
:param string $level: The level of severity

View File

@ -0,0 +1,11 @@
<?php
is_windows(true);
// some code ...
if (is_windows()) {
// do something ..
}
is_windows(null); // reset