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 96
|
<?php declare(strict_types=1);
/*
* This file is part of sebastian/global-state.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\GlobalState;
use function array_keys;
use function define;
use function ini_get;
use function ini_set;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\TestCase;
#[CoversClass(CodeExporter::class)]
#[UsesClass(ExcludeList::class)]
#[UsesClass(Snapshot::class)]
final class CodeExporterTest extends TestCase
{
public function testCanExportGlobalVariablesToCode(): void
{
$expected = <<<'EOT'
call_user_func(
function ()
{
foreach (array_keys($GLOBALS) as $key) {
unset($GLOBALS[$key]);
}
}
);
$GLOBALS['foo'] = 'bar';
EOT;
$this->cleanGlobals();
$GLOBALS['foo'] = 'bar';
$snapshot = new Snapshot(null, true, false, false, false, false, false, false, false, false);
$exporter = new CodeExporter;
$this->assertSame($expected, $exporter->globalVariables($snapshot));
}
public function testCanExportIniSettingsToCode(): void
{
$iniSettingName = 'display_errors';
ini_set($iniSettingName, '1');
$iniValue = ini_get($iniSettingName);
$snapshot = new Snapshot(null, false, false, false, false, false, false, false, true, false);
$export = (new CodeExporter)->iniSettings($snapshot);
$pattern = "/@ini_set\('{$iniSettingName}', '{$iniValue}'\);/";
$this->assertMatchesRegularExpression(
$pattern,
$export,
);
}
public function testCanExportConstantsToCode(): void
{
define('FOO', 'BAR');
$snapshot = new Snapshot(null, false, false, true, false, false, false, false, false, false);
$exporter = new CodeExporter;
$this->assertStringContainsString(
"if (!defined('FOO')) define('FOO', 'BAR');",
$exporter->constants($snapshot),
);
}
/**
* @see https://github.com/sebastianbergmann/global-state/issues/31
* @see https://wiki.php.net/rfc/restrict_globals_usage
*/
private function cleanGlobals(): void
{
foreach (array_keys($GLOBALS) as $key) {
if ($key === 'GLOBALS') {
continue;
}
unset($GLOBALS[$key]);
}
}
}
|