Skip to content

Commit

Permalink
Modernize code for PHP8
Browse files Browse the repository at this point in the history
  • Loading branch information
adoy committed Feb 14, 2023
1 parent c973dd3 commit e315602
Show file tree
Hide file tree
Showing 9 changed files with 70 additions and 116 deletions.
16 changes: 4 additions & 12 deletions src/Dumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -156,18 +156,10 @@ private function dumpIndexedArray(array $var): string
private function dumpString(string $var): string
{
if (!$this->hasOption(self::QUOTE_STR) && preg_match('#^(' . Lexer::REGEX_NAME . ')$#A', $var)) {
switch ($var) {
case 'true':
case 'false':
case 'on':
case 'off':
case 'yes':
case 'no':
case 'null':
return '"' . $var . '"';
default:
return $var;
}
return match ($var) {
'true', 'false', 'on', 'off', 'yes', 'no', 'null' => '"' . $var . '"',
default => $var,
};
}

return '"' . strtr($var, [
Expand Down
71 changes: 28 additions & 43 deletions src/Lexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,18 @@ class Lexer extends AbstractLexer
protected const STATE_INSTRING = 1;
protected const STATE_INHEREDOC = 2;

const REGEX_SPACE = '[ \t\n\r]+';
const REGEX_COMMENT = '(?://|\#).*';
const REGEX_COMMENT_ML = '/\*';
const REGEX_NAME = '[A-Za-z_][A-Za-z0-9_-]*';
const REGEX_VAR = '?:\${([A-Za-z0-9_]+)}';
const REGEX_NUM = '(?:[0-9]*\.?[0-9]+|[0-9]+\.)(?:[eE](?:\+|-)?[0-9]+)?(?:m(?:in|s)|[KkGgMm][Bb]?|[b|s|h|d|w|y])?';
const REGEX_DQUOTE = '"';
const REGEX_HEREDOC = '?:<<<([A-Za-z0-9_]+)\n';
const REGEX_BOOL = '(?:true|false|yes|no|on|off)\b';
const REGEX_NULL = 'null\b';
const REGEX_TOKEN = '[\[\]=:{};,.()&|%^/*+-]|<<|>>';
const REGEX_ANY = '.';
public const REGEX_SPACE = '[ \t\n\r]+';
public const REGEX_COMMENT = '(?://|\#).*';
public const REGEX_COMMENT_ML = '/\*';
public const REGEX_NAME = '[A-Za-z_][A-Za-z0-9_-]*';
public const REGEX_VAR = '?:\${([A-Za-z0-9_]+)}';
public const REGEX_NUM = '(?:[0-9]*\.?[0-9]+|[0-9]+\.)(?:[eE](?:\+|-)?[0-9]+)?(?:m(?:in|s)|[KkGgMm][Bb]?|[b|s|h|d|w|y])?';
public const REGEX_DQUOTE = '"';
public const REGEX_HEREDOC = '?:<<<([A-Za-z0-9_]+)\n';
public const REGEX_BOOL = '(?:true|false|yes|no|on|off)\b';
public const REGEX_NULL = 'null\b';
public const REGEX_TOKEN = '[\[\]=:{};,.()&|%^/*+-]|<<|>>';
public const REGEX_ANY = '.';

private string $textBuffer;

Expand Down Expand Up @@ -69,9 +69,7 @@ protected function getRules(): array

return Token::T_NUM;
},
self::REGEX_NAME => function () {
return Token::T_NAME;
},
self::REGEX_NAME => fn() => Token::T_NAME,
self::REGEX_HEREDOC => function (&$yylval) {
$needle = "\n" . $yylval;
$pos = strpos($this->content, $needle, $this->count);
Expand All @@ -86,18 +84,12 @@ protected function getRules(): array

return Token::T_END_STR;
},
self::REGEX_TOKEN => function ($yylval) {
return $yylval;
},
self::REGEX_VAR => function () {
return Token::T_VAR;
},
self::REGEX_TOKEN => fn($yylval) => $yylval,
self::REGEX_VAR => fn() => Token::T_VAR,
self::REGEX_ANY => function ($yylval) {
$this->error('Unexpected char \'' . $yylval . '\'');
},
self::EOF => function () {
return Token::T_EOF;
},
self::EOF => fn() => Token::T_EOF,
],
self::STATE_INSTRING => [
'[^\\\"$]+' => function (&$yylval) {
Expand Down Expand Up @@ -167,24 +159,17 @@ protected function getRules(): array

private function fromCharCode(int $bytes): string
{
switch (true) {
case (0x7F & $bytes) == $bytes:
return chr($bytes);

case (0x07FF & $bytes) == $bytes:
return chr(0xc0 | ($bytes >> 6))
. chr(0x80 | ($bytes & 0x3F));

case (0xFFFF & $bytes) == $bytes:
return chr(0xe0 | ($bytes >> 12))
. chr(0x80 | (($bytes >> 6) & 0x3F))
. chr(0x80 | ($bytes & 0x3F));

default:
return chr(0xF0 | ($bytes >> 18))
. chr(0x80 | (($bytes >> 12) & 0x3F))
. chr(0x80 | (($bytes >> 6) & 0x3F))
. chr(0x80 | ($bytes & 0x3F));
}
return match (true) {
(0x7F & $bytes) == $bytes => chr($bytes),
(0x07FF & $bytes) == $bytes => chr(0xc0 | ($bytes >> 6))
. chr(0x80 | ($bytes & 0x3F)),
(0xFFFF & $bytes) == $bytes => chr(0xe0 | ($bytes >> 12))
. chr(0x80 | (($bytes >> 6) & 0x3F))
. chr(0x80 | ($bytes & 0x3F)),
default => chr(0xF0 | ($bytes >> 18))
. chr(0x80 | (($bytes >> 12) & 0x3F))
. chr(0x80 | (($bytes >> 6) & 0x3F))
. chr(0x80 | ($bytes & 0x3F)),
};
}
}
23 changes: 7 additions & 16 deletions src/Macros/Env.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,21 +42,12 @@ public function execute(mixed $parameter, array $options = []): mixed

private function cast(mixed $value, string $type): bool|string|int|float
{
switch ($type) {
case 'bool':
case 'boolean':
return TypeCaster::toBool($value);
case 'int':
case 'integer':
return (int) TypeCaster::toNum($value);
case 'num':
case 'numeric':
return TypeCaster::toNum($value);
case 'str':
case 'string':
return $value;
default:
throw new \InvalidArgumentException('Unknown type: ' . $type);
}
return match ($type) {
'bool', 'boolean' => TypeCaster::toBool($value),
'int', 'integer' => (int) TypeCaster::toNum($value),
'num', 'numeric' => TypeCaster::toNum($value),
'str', 'string' => $value,
default => throw new \InvalidArgumentException('Unknown type: ' . $type),
};
}
}
2 changes: 1 addition & 1 deletion src/Nacl.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

class Nacl
{
private static $macros = [];
private static array $macros = [];

public static function registerMacro(MacroInterface $macro): void
{
Expand Down
22 changes: 11 additions & 11 deletions src/OperationNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,17 @@

class OperationNode extends Node
{
const ADD = '+';
const SUB = '-';
const OR_OPERATOR = '|';
const AND_OPERATOR = '&';
const SHIFT_LEFT = '<<';
const SHIFT_RIGHT = '>>';
const MOD = '%';
const DIV = '/';
const MUL = '*';
const POW = '**';
const CONCAT = '.';
public const ADD = '+';
public const SUB = '-';
public const OR_OPERATOR = '|';
public const AND_OPERATOR = '&';
public const SHIFT_LEFT = '<<';
public const SHIFT_RIGHT = '>>';
public const MOD = '%';
public const DIV = '/';
public const MUL = '*';
public const POW = '**';
public const CONCAT = '.';

private mixed $left;
private mixed $right;
Expand Down
12 changes: 4 additions & 8 deletions src/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -397,11 +397,11 @@ private function doInclude(Node|string $fileName, ObjectNode $options): mixed
$includeValue = new ObjectNode();

$fileName = $fileName instanceof Node ? $fileName->getNativeValue() : $fileName;
if (isset($options['glob']) ? $options['glob'] : false) {
if ($options['glob'] ?? false) {
$files = $this->glob($fileName);
} else {
if (!$path = $this->resolvePath($fileName)) {
if (isset($options['required']) ? $options['required'] : true) {
if ($options['required'] ?? true) {
$this->error('Unable to include file \'' . $fileName . '\'');
}

Expand Down Expand Up @@ -433,16 +433,12 @@ private function doInclude(Node|string $fileName, ObjectNode $options): mixed

public function resolvePath(string $file): string|false
{
return $this->relativeToCurrentFile(function () use ($file) {
return realpath($file);
});
return $this->relativeToCurrentFile(fn() => realpath($file));
}

private function glob(string $pattern): array
{
return $this->relativeToCurrentFile(function () use ($pattern) {
return array_map('realpath', glob($pattern) ?: []);
});
return $this->relativeToCurrentFile(fn() => array_map('realpath', glob($pattern) ?: []));
}

private function relativeToCurrentFile(callable $cb): mixed
Expand Down
2 changes: 1 addition & 1 deletion src/ReferenceNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

class ReferenceNode extends Node
{
const ROOT = '/';
public const ROOT = '/';

private mixed $path;
private bool $isResolving = false;
Expand Down
4 changes: 2 additions & 2 deletions tests/DumperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,14 @@ public static function getJsonFiles(): iterable
*/
public function parsedDumpOutputIsEqualToDumpInput($options, $json)
{
$expected = json_decode($json, true);
$expected = json_decode($json, true, 512, JSON_THROW_ON_ERROR);

$dumper = new Dumper($options);
$nacl = $dumper->dump($expected);

try {
$result = Nacl::parse($nacl);
} catch (\Exception $e) {
} catch (\Exception) {
$result = null;
}

Expand Down
34 changes: 12 additions & 22 deletions tests/NaclTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@ public static function getJsonFiles(): iterable
{
$files = glob(__DIR__ . '/json/*.json');

return array_map(function ($f) {
return [$f];
}, $files);
return array_map(fn($f) => [$f], $files);
}

/**
Expand All @@ -30,7 +28,7 @@ public static function getJsonFiles(): iterable
public function naclIsJsonCompatible(string $jsonFile): void
{
$this->assertSame(
json_decode(file_get_contents($jsonFile), true),
json_decode(file_get_contents($jsonFile), true, 512, JSON_THROW_ON_ERROR),
Nacl::parseFile($jsonFile)
);
}
Expand All @@ -54,27 +52,21 @@ public function testNacl(string $naclFile, string $jsonFile): void
{
$this->parser = Nacl::createParser();

$this->parser->registerMacro(new Macros\Callback('testMacroWithOptions', function ($p, $a = []) {
return [
'param' => $p,
'options' => $a
];
}));
$this->parser->registerMacro(new Macros\Callback('testMacroWithOptions', fn($p, $a = []) => [
'param' => $p,
'options' => $a
]));

$this->parser->registerMacro(new Macros\Callback('testMacro', function ($p, $a = []) {
return $p;
}));
$this->parser->registerMacro(new Macros\Callback('testMacro', fn($p, $a = []) => $p));

$this->parser->registerMacro(new Macros\Callback('json_encode', function ($p) {
return json_encode($p);
}));
$this->parser->registerMacro(new Macros\Callback('json_encode', fn($p) => json_encode($p, JSON_THROW_ON_ERROR)));

$this->parser->setVariable('BAR', 'bar');
$this->parser->setVariable('MY_VAR', 'my var value');
$result = $this->parser->parseFile($naclFile);
try {
$this->assertEquals(
file_exists($jsonFile) ? json_decode(file_get_contents($jsonFile), true) : [],
file_exists($jsonFile) ? json_decode(file_get_contents($jsonFile), true, 512, JSON_THROW_ON_ERROR) : [],
$result
);
} catch (\Exception $e) {
Expand Down Expand Up @@ -124,7 +116,7 @@ public function testParseErrorMessageWithTokenName(): void
$this->expectException(ParsingException::class);
$this->expectExceptionMessage('Syntax error, unexpected \'10\' (T_NUM)');

Nacl::parse('foo bar baz {}10;', 'file');
Nacl::parse('foo bar baz {}10;');
}

/**
Expand All @@ -135,7 +127,7 @@ public function testParseErrorMesageWithoutTokenName(): void
$this->expectException(ParsingException::class);
$this->expectExceptionMessage('Syntax error, unexpected \';\'');

Nacl::parse('+;', 'file');
Nacl::parse('+;');
}

/**
Expand Down Expand Up @@ -175,9 +167,7 @@ public function contentAfterScalarRootValueThrowsParsingExcpetion(): void
*/
public function testRegisterMacro(): void
{
Nacl::registerMacro($macro = new Macros\Callback('strtoupper', function ($p) {
return strtoupper($p);
}));
Nacl::registerMacro($macro = new Macros\Callback('strtoupper', fn($p) => strtoupper($p)));
$this->assertSame(['foo' => 'BAR'], Nacl::parse('foo .strtoupper bar'));
$this->assertSame(['foo' => 'BAR'], Nacl::parse('${BAR} = .strtoupper bar; foo ${BAR};'));
}
Expand Down

0 comments on commit e315602

Please sign in to comment.