2013-08-17 19:20:23 -04:00
|
|
|
<?php
|
|
|
|
|
2014-04-15 22:25:48 -03:00
|
|
|
namespace DesignPatterns\Behavioral\Visitor;
|
2013-08-17 19:20:23 -04:00
|
|
|
|
|
|
|
/**
|
2013-09-24 13:01:41 +02:00
|
|
|
* class Role
|
2013-08-17 19:20:23 -04:00
|
|
|
*/
|
|
|
|
abstract class Role
|
|
|
|
{
|
|
|
|
/**
|
2013-09-12 11:20:10 +02:00
|
|
|
* This method handles a double dispatch based on the short name of the Visitor
|
|
|
|
*
|
2013-08-17 19:20:23 -04:00
|
|
|
* Feel free to override it if your object must call another visiting behavior
|
2013-09-12 11:20:10 +02:00
|
|
|
*
|
2014-04-15 22:25:48 -03:00
|
|
|
* @param \DesignPatterns\Behavioral\Visitor\RoleVisitorInterface $visitor
|
2013-09-12 11:20:10 +02:00
|
|
|
*
|
|
|
|
* @throws \InvalidArgumentException
|
2013-08-17 19:20:23 -04:00
|
|
|
*/
|
2013-09-12 11:20:10 +02:00
|
|
|
public function accept(RoleVisitorInterface $visitor)
|
2013-08-17 19:20:23 -04:00
|
|
|
{
|
|
|
|
// this trick to simulate double-dispatch based on type-hinting
|
2013-09-12 11:20:10 +02:00
|
|
|
$klass = get_called_class();
|
|
|
|
preg_match('#([^\\\\]+)$#', $klass, $extract);
|
2013-08-17 19:20:23 -04:00
|
|
|
$visitingMethod = 'visit' . $extract[1];
|
|
|
|
|
2013-08-19 12:42:36 -04:00
|
|
|
// this ensures strong typing with visitor interface, not some visitor objects
|
2013-09-12 11:20:10 +02:00
|
|
|
if (!method_exists(__NAMESPACE__ . '\RoleVisitorInterface', $visitingMethod)) {
|
|
|
|
throw new \InvalidArgumentException("The visitor you provide cannot visit a $klass instance");
|
2013-08-17 19:20:23 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
call_user_func(array($visitor, $visitingMethod), $this);
|
|
|
|
}
|
|
|
|
}
|