Adam Pippin
3 years ago
3 changed files with 141 additions and 14 deletions
@ -0,0 +1,90 @@ |
|||||
|
<?php |
||||
|
|
||||
|
declare(strict_types=1); |
||||
|
|
||||
|
namespace App\Engine\Cfnpp\Expression; |
||||
|
|
||||
|
/** |
||||
|
* Token representing a function. |
||||
|
* |
||||
|
* @author Adam Pippin <hello@adampippin.ca> |
||||
|
*/ |
||||
|
class TokenFunction extends Token |
||||
|
{ |
||||
|
/** |
||||
|
* List of valid functions this can parse. |
||||
|
* @var string[] |
||||
|
*/ |
||||
|
public const FUNCTIONS = [ |
||||
|
'concat*', |
||||
|
'concat' |
||||
|
]; |
||||
|
|
||||
|
/** |
||||
|
* Function this token represents. |
||||
|
* @var string |
||||
|
*/ |
||||
|
protected $function; |
||||
|
|
||||
|
/** |
||||
|
* Create a new function token. |
||||
|
* |
||||
|
* @param string $function |
||||
|
*/ |
||||
|
public function __construct($function) |
||||
|
{ |
||||
|
$this->function = $function; |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* Get the function this token represents. |
||||
|
* |
||||
|
* @return string |
||||
|
*/ |
||||
|
public function getFunction(): string |
||||
|
{ |
||||
|
return $this->function; |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* Determine whether a function token can be parsed from a stream. |
||||
|
* |
||||
|
* @param string $stream |
||||
|
* @return bool |
||||
|
*/ |
||||
|
public static function isToken(string $stream): bool |
||||
|
{ |
||||
|
foreach (static::FUNCTIONS as $function) |
||||
|
{ |
||||
|
if (strlen($stream) > strlen($function) && |
||||
|
substr($stream, 0, strlen($function)) == $function) |
||||
|
{ |
||||
|
return true; |
||||
|
} |
||||
|
} |
||||
|
return false; |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* Parse a function 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 |
||||
|
{ |
||||
|
foreach (static::FUNCTIONS as $function) |
||||
|
{ |
||||
|
if (strlen($stream) > strlen($function) && |
||||
|
substr($stream, 0, strlen($function)) == $function) |
||||
|
{ |
||||
|
$function = substr($stream, 0, strlen($function)); |
||||
|
$stream = substr($stream, strlen($function)); |
||||
|
return new TokenFunction($function); |
||||
|
} |
||||
|
} |
||||
|
throw new \Exception('Could not parse function token!'); |
||||
|
} |
||||
|
} |
Loading…
Reference in new issue