Skip to content

Instantly share code, notes, and snippets.

@smeghead
Created October 25, 2023 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smeghead/e72dd420d3344efc90b3181ff910cd93 to your computer and use it in GitHub Desktop.
Save smeghead/e72dd420d3344efc90b3181ff910cd93 to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace Nagoya;
interface Expression {
public function toString(): string;
}
class Number implements Expression {
public function __construct(
private int $value
)
{
}
public function toString(): string
{
return sprintf('%d', $this->value);
}
}
enum Operater: string {
case Addition = '+';
case Subtraction = '-';
case Multiplication = '*';
case Division = '/';
}
class Statement implements Expression {
public function __construct(
private Expression $a,
private Operater $op,
private Expression $b
)
{
}
public function toString(): string
{
return sprintf('(%s %s %s)', $this->a->toString(), $this->op->value, $this->b->toString());
}
}
<?php
declare(strict_types=1);
use Nagoya\Number;
use Nagoya\Operater;
use Nagoya\Statement;
use PHPUnit\Framework\TestCase;
require_once('Nagoya.php');
final class NagoyaTest extends TestCase
{
public function test2たす3(): void
{
$n1 = new Number(2);
$n2 = new Number(3);
$exp = new Statement($n1, Operater::Addition, $n2);
$this->assertSame('(2 + 3)', $exp->toString());
}
public function test2たす3ひく4(): void
{
$n1 = new Number(2);
$n2 = new Number(3);
$n3 = new Number(4);
$exp = new Statement($n1, Operater::Addition, $n2);
$exp2 = new Statement($exp, Operater::Subtraction, $n3);
$this->assertSame('((2 + 3) - 4)', $exp2->toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment