Skip to content

Commit 0ef5376

Browse files
committed
Added interfaces, traits, and tests for the Visitor pattern
1 parent e063a71 commit 0ef5376

File tree

6 files changed

+89
-0
lines changed

6 files changed

+89
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?php
2+
3+
namespace Jeremeamia\PhpPatterns\Behavioral;
4+
5+
interface VisitableInterface
6+
{
7+
public function accept(VisitorInterface $visitor);
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
3+
namespace Jeremeamia\PhpPatterns\Behavioral;
4+
5+
use Jeremeamia\PhpPatterns\Structural\Collection\TraversableTrait;
6+
7+
trait VisitableTrait
8+
{
9+
use TraversableTrait;
10+
11+
public function accept(VisitorInterface $visitor)
12+
{
13+
foreach ($this->getIterator() as $item) {
14+
$visitor->visit($item);
15+
}
16+
17+
return $this;
18+
}
19+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?php
2+
3+
namespace Jeremeamia\PhpPatterns\Behavioral;
4+
5+
interface VisitorInterface
6+
{
7+
public function visit($node);
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php
2+
3+
namespace Jeremeamia\PhpPatterns\Test\Behavioral;
4+
5+
use Jeremeamia\PhpPatterns\Behavioral\VisitableInterface;
6+
use Jeremeamia\PhpPatterns\Behavioral\VisitableTrait;
7+
use Jeremeamia\PhpPatterns\Structural\Collection\GetDataTrait;
8+
9+
class VisitableFixture implements VisitableInterface, \IteratorAggregate
10+
{
11+
use GetDataTrait, VisitableTrait;
12+
13+
public function __construct(array $data)
14+
{
15+
$this->data = $data;
16+
}
17+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php
2+
3+
namespace Jeremeamia\PhpPatterns\Test\Behavioral;
4+
5+
/**
6+
* @covers Jeremeamia\PhpPatterns\Behavioral\VisitableTrait
7+
*/
8+
class VisitableTraitTest extends \PHPUnit_Framework_TestCase
9+
{
10+
public function testAcceptVisitsNodes()
11+
{
12+
$visitor = new VisitorFixture();
13+
$visitable = new VisitableFixture([2, 4, 6, 8]);
14+
$visitable->accept($visitor);
15+
$this->assertEquals(20, $visitor->getSum());
16+
}
17+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
namespace Jeremeamia\PhpPatterns\Test\Behavioral;
4+
5+
use Jeremeamia\PhpPatterns\Behavioral\VisitorInterface;
6+
7+
class VisitorFixture implements VisitorInterface
8+
{
9+
protected $sum = 0;
10+
11+
public function getSum()
12+
{
13+
return $this->sum;
14+
}
15+
16+
public function visit($node)
17+
{
18+
$this->sum += (int) $node;
19+
}
20+
}

0 commit comments

Comments
 (0)