You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
87 lines
1.4 KiB
87 lines
1.4 KiB
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Cfnpp\Expression;
|
|
|
|
/**
|
|
* Token representing a numeric (integer or float) literal.
|
|
*
|
|
* @author Adam Pippin <hello@adampippin.ca>
|
|
*/
|
|
class TokenNumericLiteral extends Token
|
|
{
|
|
/**
|
|
* Numeric value this token represents.
|
|
* @var int|float
|
|
*/
|
|
protected $value;
|
|
|
|
/**
|
|
* Create a new numeric literal.
|
|
*
|
|
* @param int|float $value
|
|
*/
|
|
public function __construct($value)
|
|
{
|
|
$this->value = $value;
|
|
}
|
|
|
|
/**
|
|
* Get the value this token represents.
|
|
*
|
|
* @return int|float
|
|
*/
|
|
public function getValue()
|
|
{
|
|
return $this->value;
|
|
}
|
|
|
|
/**
|
|
* Determine whether a numeric token can be parsed from a stream.
|
|
*
|
|
* @param string $stream
|
|
* @return bool
|
|
*/
|
|
public static function isToken(string $stream): bool
|
|
{
|
|
return is_numeric($stream[0]);
|
|
}
|
|
|
|
/**
|
|
* Parse a numeric token from a stream.
|
|
*
|
|
* Returns token, and modifies stream to remove all consumed characters.
|
|
*
|
|
* @param string $stream
|
|
* @return Token
|
|
*/
|
|
public static function getToken(string &$stream): Token
|
|
{
|
|
$buffer = '';
|
|
for ($i = 0; $i < strlen($stream); $i++)
|
|
{
|
|
if (preg_match('/^[0-9]$/', $stream[$i]))
|
|
{
|
|
$buffer .= $stream[$i];
|
|
}
|
|
else
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
|
|
$stream = substr($stream, strlen($buffer));
|
|
|
|
if (stristr($buffer, '.'))
|
|
{
|
|
$buffer = (float)$buffer;
|
|
}
|
|
else
|
|
{
|
|
$buffer = (int)$buffer;
|
|
}
|
|
|
|
return new TokenNumericLiteral($buffer);
|
|
}
|
|
}
|
|
|