rtex-engine/src/RTEX/Objects/Instructions/Arithmetic/Absolute.php

109 lines
2.8 KiB
PHP
Raw Normal View History

<?php
/** @noinspection PhpMissingFieldTypeInspection */
namespace RTEX\Objects\Instructions\Arithmetic;
use RTEX\Abstracts\InstructionType;
use RTEX\Classes\InstructionBuilder;
use RTEX\Classes\Utilities;
use RTEX\Engine;
use RTEX\Exceptions\EvaluationException;
use RTEX\Exceptions\InstructionException;
use RTEX\Exceptions\Runtime\TypeException;
use RTEX\Interfaces\InstructionInterface;
2022-12-30 00:46:25 -05:00
class Absolute implements InstructionInterface
{
/**
* @var mixed
*/
2022-12-30 00:46:25 -05:00
private $Value;
/**
* Returns the type of instruction
*
* @return string
*/
public function getType(): string
{
2022-12-30 00:46:25 -05:00
return InstructionType::Absolute;
}
/**
* Returns an array representation of the instruction
*
* @return array
*/
public function toArray(): array
{
return InstructionBuilder::toRaw(self::getType(), [
2022-12-30 00:46:25 -05:00
'value' => $this->Value,
]);
}
/**
* Constructs a new instance of this class from an array representation
*
* @param array $data
* @return InstructionInterface
* @throws InstructionException
*/
public static function fromArray(array $data): InstructionInterface
{
$instruction = new self();
2022-12-30 00:46:25 -05:00
$instruction->setValue($data['value'] ?? null);
return $instruction;
}
/**
* @param Engine $engine
2022-12-30 00:46:25 -05:00
* @return int|float
* @throws EvaluationException
* @throws TypeException
*/
2022-12-30 00:46:25 -05:00
public function eval(Engine $engine): int|float
{
2022-12-30 00:46:25 -05:00
$value = $engine->eval($this->Value);
2022-12-30 00:46:25 -05:00
if(!(is_int($value) || is_float($value) || is_double($value)))
throw new TypeException(sprintf('Cannot calculate the absolute value of a non-numeric value, got %s', Utilities::getType($value, true)));
2022-12-30 00:46:25 -05:00
return abs($value);
}
/**
* Returns the string representation of the instruction
*
* @return string
*/
public function __toString(): string
{
return sprintf(
self::getType() . ' %s',
2022-12-30 00:46:25 -05:00
Utilities::entityToString($this->Value),
);
}
/**
* Gets the value of A
*
* @return mixed
*/
2022-12-30 00:46:25 -05:00
public function getValue(): mixed
{
2022-12-30 00:46:25 -05:00
return $this->Value;
}
/**
* Sets the value of A
*
2022-12-30 00:46:25 -05:00
* @param mixed $Value
* @throws InstructionException
*/
2022-12-30 00:46:25 -05:00
public function setValue(mixed $Value): void
{
2022-12-30 00:46:25 -05:00
$this->Value = InstructionBuilder::fromRaw($Value);
}
}