diff --git a/phpcs.xml b/phpcs.xml new file mode 100644 index 0000000..8b8d8cc --- /dev/null +++ b/phpcs.xml @@ -0,0 +1,86 @@ + + + + Drupal coding standard, relaxed for Features module + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + tests/features.test + + + + + includes/features.ctools.inc + + + diff --git a/src/Cache/DrupalCache.php b/src/Cache/DrupalCache.php index ed99230..8b6eaac 100644 --- a/src/Cache/DrupalCache.php +++ b/src/Cache/DrupalCache.php @@ -5,80 +5,75 @@ use Doctrine\Common\Cache\CacheProvider; use Drupal\Core\Cache\CacheBackendInterface; -class DrupalCache extends CacheProvider -{ - /** - * @var CacheBackendInterface - */ - private $cache; - - /** - * @param CacheBackendInterface $cache - */ - public function __construct(CacheBackendInterface $cache) - { - $this->cache = $cache; - } +class DrupalCache extends CacheProvider { - /** - * @inheritdoc - */ - protected function doFetch($id) - { - if ($cache = $this->cache->get($id)) { - return $cache->data; - } + /** + * @var \Drupal\Core\Cache\CacheBackendInterface + */ + private $cache; - return false; - } + /** + * @param \Drupal\Core\Cache\CacheBackendInterface $cache + */ + public function __construct(CacheBackendInterface $cache) { + $this->cache = $cache; + } - /** - * @inheritdoc - */ - protected function doContains($id) - { - return $this->doFetch($id) !== false; + /** + * @inheritdoc + */ + protected function doFetch($id) { + if ($cache = $this->cache->get($id)) { + return $cache->data; } - /** - * @inheritdoc - */ - protected function doSave($id, $data, $lifeTime = 0) - { - if ($lifeTime === 0) { - $this->cache->set($id, $data); - } else { - $this->cache->set($id, $data, time() + $lifeTime); - } - - return true; - } + return FALSE; + } - /** - * @inheritdoc - */ - protected function doDelete($id) - { - $this->cache->delete($id); + /** + * @inheritdoc + */ + protected function doContains($id) { + return $this->doFetch($id) !== FALSE; + } - return true; + /** + * @inheritdoc + */ + protected function doSave($id, $data, $lifeTime = 0) { + if ($lifeTime === 0) { + $this->cache->set($id, $data); + } + else { + $this->cache->set($id, $data, time() + $lifeTime); } - /** - * @inheritdoc - */ - protected function doFlush() - { - $this->cache->deleteAll(); + return TRUE; + } - return true; - } + /** + * @inheritdoc + */ + protected function doDelete($id) { + $this->cache->delete($id); + + return TRUE; + } + + /** + * @inheritdoc + */ + protected function doFlush() { + $this->cache->deleteAll(); + + return TRUE; + } + + /** + * @inheritdoc + */ + protected function doGetStats() { + return NULL; + } - /** - * @inheritdoc - */ - protected function doGetStats() - { - return; - } } diff --git a/src/Configuration/Cache.php b/src/Configuration/Cache.php index f84a28e..3c58dee 100644 --- a/src/Configuration/Cache.php +++ b/src/Configuration/Cache.php @@ -5,232 +5,220 @@ /** * @Annotation */ -class Cache extends ConfigurationAnnotation -{ - /** - * The expiration date as a valid date for the strtotime() function. - * - * @var string - */ - protected $expires; - - /** - * The number of seconds that the response is considered fresh by a private - * cache like a web browser. - * - * @var int - */ - protected $maxage; - - /** - * The number of seconds that the response is considered fresh by a public - * cache like a reverse proxy cache. - * - * @var int - */ - protected $smaxage; - - /** - * Whether the response is public or not. - * - * @var bool - */ - protected $public; - - /** - * Additional "Vary:"-headers. - * - * @var array - */ - protected $vary; - - /** - * An expression to compute the Last-Modified HTTP header. - * - * @var string - */ - protected $lastModified; - - /** - * An expression to compute the ETag HTTP header. - * - * @var string - */ - protected $etag; - - /** - * Returns the expiration date for the Expires header field. - * - * @return string - */ - public function getExpires() - { - return $this->expires; - } - - /** - * Sets the expiration date for the Expires header field. - * - * @param string $expires A valid php date - */ - public function setExpires($expires) - { - $this->expires = $expires; - } - - /** - * Sets the number of seconds for the max-age cache-control header field. - * - * @param int $maxage A number of seconds - */ - public function setMaxAge($maxage) - { - $this->maxage = $maxage; - } - - /** - * Returns the number of seconds the response is considered fresh by a - * private cache. - * - * @return int - */ - public function getMaxAge() - { - return $this->maxage; - } - - /** - * Sets the number of seconds for the s-maxage cache-control header field. - * - * @param int $smaxage A number of seconds - */ - public function setSMaxAge($smaxage) - { - $this->smaxage = $smaxage; - } - - /** - * Returns the number of seconds the response is considered fresh by a - * public cache. - * - * @return int - */ - public function getSMaxAge() - { - return $this->smaxage; - } - - /** - * Returns whether or not a response is public. - * - * @return bool - */ - public function isPublic() - { - return $this->public === true; - } - - /** - * Returns whether or not a response is private. - * - * @return bool - */ - public function isPrivate() - { - return $this->public === false; - } - - /** - * Sets a response public. - * - * @param bool $public A boolean value - */ - public function setPublic($public) - { - $this->public = (bool)$public; - } - - /** - * Returns the custom "Vary"-headers. - * - * @return array - */ - public function getVary() - { - return $this->vary; - } - - /** - * Add additional "Vary:"-headers. - * - * @param array $vary - */ - public function setVary($vary) - { - $this->vary = $vary; - } - - /** - * Sets the "Last-Modified"-header expression. - * - * @param string $expression - */ - public function setLastModified($expression) - { - $this->lastModified = $expression; - } - - /** - * Returns the "Last-Modified"-header expression. - * - * @return string - */ - public function getLastModified() - { - return $this->lastModified; - } - - /** - * Sets the "ETag"-header expression. - * - * @param string $expression - */ - public function setETag($expression) - { - $this->etag = $expression; - } - - /** - * Returns the "ETag"-header expression. - * - * @return string - */ - public function getETag() - { - return $this->etag; - } - - /** - * Returns the annotation alias name. - * - * @return string - * - * @see ConfigurationInterface - */ - public function getAliasName() - { - return 'cache'; - } - - /** - * Only one cache directive is allowed. - * - * @return bool - * - * @see ConfigurationInterface - */ - public function allowArray() - { - return false; - } +class Cache extends ConfigurationAnnotation { + + /** + * The expiration date as a valid date for the strtotime() function. + * + * @var string + */ + protected $expires; + + /** + * The number of seconds that the response is considered fresh by a private + * cache like a web browser. + * + * @var int + */ + protected $maxage; + + /** + * The number of seconds that the response is considered fresh by a public + * cache like a reverse proxy cache. + * + * @var int + */ + protected $smaxage; + + /** + * Whether the response is public or not. + * + * @var bool + */ + protected $public; + + /** + * Additional "Vary:"-headers. + * + * @var array + */ + protected $vary; + + /** + * An expression to compute the Last-Modified HTTP header. + * + * @var string + */ + protected $lastModified; + + /** + * An expression to compute the ETag HTTP header. + * + * @var string + */ + protected $etag; + + /** + * Returns the expiration date for the Expires header field. + * + * @return string + */ + public function getExpires() { + return $this->expires; + } + + /** + * Sets the expiration date for the Expires header field. + * + * @param string $expires + * A valid php date. + */ + public function setExpires($expires) { + $this->expires = $expires; + } + + /** + * Sets the number of seconds for the max-age cache-control header field. + * + * @param int $maxage + * A number of seconds. + */ + public function setMaxAge($maxage) { + $this->maxage = $maxage; + } + + /** + * Returns the number of seconds the response is considered fresh by a + * private cache. + * + * @return int + */ + public function getMaxAge() { + return $this->maxage; + } + + /** + * Sets the number of seconds for the s-maxage cache-control header field. + * + * @param int $smaxage + * A number of seconds. + */ + public function setSMaxAge($smaxage) { + $this->smaxage = $smaxage; + } + + /** + * Returns the number of seconds the response is considered fresh by a + * public cache. + * + * @return int + */ + public function getSMaxAge() { + return $this->smaxage; + } + + /** + * Returns whether or not a response is public. + * + * @return bool + */ + public function isPublic() { + return $this->public === TRUE; + } + + /** + * Returns whether or not a response is private. + * + * @return bool + */ + public function isPrivate() { + return $this->public === FALSE; + } + + /** + * Sets a response public. + * + * @param bool $public + * A boolean value. + */ + public function setPublic($public) { + $this->public = (bool) $public; + } + + /** + * Returns the custom "Vary"-headers. + * + * @return array + */ + public function getVary() { + return $this->vary; + } + + /** + * Add additional "Vary:"-headers. + * + * @param array $vary + */ + public function setVary($vary) { + $this->vary = $vary; + } + + /** + * Sets the "Last-Modified"-header expression. + * + * @param string $expression + */ + public function setLastModified($expression) { + $this->lastModified = $expression; + } + + /** + * Returns the "Last-Modified"-header expression. + * + * @return string + */ + public function getLastModified() { + return $this->lastModified; + } + + /** + * Sets the "ETag"-header expression. + * + * @param string $expression + */ + public function setETag($expression) { + $this->etag = $expression; + } + + /** + * Returns the "ETag"-header expression. + * + * @return string + */ + public function getETag() { + return $this->etag; + } + + /** + * Returns the annotation alias name. + * + * @return string + * + * @see ConfigurationInterface + */ + public function getAliasName() { + return 'cache'; + } + + /** + * Only one cache directive is allowed. + * + * @return bool + * + * @see ConfigurationInterface + */ + public function allowArray() { + return FALSE; + } + } diff --git a/src/Configuration/ConfigurationAnnotation.php b/src/Configuration/ConfigurationAnnotation.php index 2301fb5..1d0fc93 100644 --- a/src/Configuration/ConfigurationAnnotation.php +++ b/src/Configuration/ConfigurationAnnotation.php @@ -7,16 +7,16 @@ * * @author Johannes M. Schmitt */ -abstract class ConfigurationAnnotation implements ConfigurationInterface -{ - public function __construct(array $values) - { - foreach ($values as $k => $v) { - if (!method_exists($this, $name = 'set'.$k)) { - throw new \RuntimeException(sprintf('Unknown key "%s" for annotation "@%s".', $k, get_class($this))); - } +abstract class ConfigurationAnnotation implements ConfigurationInterface { - $this->$name($v); - } + public function __construct(array $values) { + foreach ($values as $k => $v) { + if (!method_exists($this, $name = 'set' . $k)) { + throw new \RuntimeException(sprintf('Unknown key "%s" for annotation "@%s".', $k, get_class($this))); + } + + $this->$name($v); } + } + } diff --git a/src/Configuration/ConfigurationInterface.php b/src/Configuration/ConfigurationInterface.php index 710b5f0..4e5097d 100644 --- a/src/Configuration/ConfigurationInterface.php +++ b/src/Configuration/ConfigurationInterface.php @@ -7,19 +7,20 @@ * * @author Fabien Potencier */ -interface ConfigurationInterface -{ - /** - * Returns the alias name for an annotated configuration. - * - * @return string - */ - public function getAliasName(); +interface ConfigurationInterface { + + /** + * Returns the alias name for an annotated configuration. + * + * @return string + */ + public function getAliasName(); + + /** + * Returns whether multiple annotations of this type are allowed. + * + * @return bool + */ + public function allowArray(); - /** - * Returns whether multiple annotations of this type are allowed. - * - * @return bool - */ - public function allowArray(); } diff --git a/src/Configuration/Method.php b/src/Configuration/Method.php index 3d34704..25c0a80 100644 --- a/src/Configuration/Method.php +++ b/src/Configuration/Method.php @@ -7,97 +7,92 @@ /** * @Annotation */ -class Method extends ConfigurationAnnotation implements RouteModifierMethodInterface, RouteModifierClassInterface -{ - /** - * An array of restricted HTTP methods. - * - * @var array - */ - protected $methods = array(); +class Method extends ConfigurationAnnotation implements RouteModifierMethodInterface, RouteModifierClassInterface { - /** - * Returns the array of HTTP methods. - * - * @return array - */ - public function getMethods() - { - return $this->methods; - } + /** + * An array of restricted HTTP methods. + * + * @var array + */ + protected $methods = []; - /** - * Sets the HTTP methods. - * - * @param array|string $methods An HTTP method or an array of HTTP methods - */ - public function setMethods($methods) - { - $this->methods = is_array($methods) ? $methods : array($methods); - } + /** + * Returns the array of HTTP methods. + * + * @return array + */ + public function getMethods() { + return $this->methods; + } - /** - * Sets the HTTP methods. - * - * @param array|string $methods An HTTP method or an array of HTTP methods - */ - public function setValue($methods) - { - $this->setMethods($methods); - } + /** + * Sets the HTTP methods. + * + * @param array|string $methods + * An HTTP method or an array of HTTP methods. + */ + public function setMethods($methods) { + $this->methods = is_array($methods) ? $methods : [$methods]; + } - /** - * Returns the annotation alias name. - * - * @return string - * - * @see ConfigurationInterface - */ - public function getAliasName() - { - return 'method'; - } + /** + * Sets the HTTP methods. + * + * @param array|string $methods + * An HTTP method or an array of HTTP methods. + */ + public function setValue($methods) { + $this->setMethods($methods); + } - /** - * Only one method directive is allowed. - * - * @return bool - * - * @see ConfigurationInterface - */ - public function allowArray() - { - return false; - } + /** + * Returns the annotation alias name. + * + * @return string + * + * @see ConfigurationInterface + */ + public function getAliasName() { + return 'method'; + } - /** - * @param RoutingRoute $route - * @param \ReflectionClass $class - * @param \ReflectionMethod $method - */ - public function modifyRouteClass(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method) - { - $this->modifyRoute($route); - } + /** + * Only one method directive is allowed. + * + * @return bool + * + * @see ConfigurationInterface + */ + public function allowArray() { + return FALSE; + } - /** - * @param RoutingRoute $route - * @param \ReflectionClass $class - * @param \ReflectionMethod $method - */ - public function modifyRouteMethod(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method) - { - $this->modifyRoute($route); - } + /** + * @param \Symfony\Component\Routing\Route $route + * @param \ReflectionClass $class + * @param \ReflectionMethod $method + */ + public function modifyRouteClass(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method) { + $this->modifyRoute($route); + } + + /** + * @param \Symfony\Component\Routing\Route $route + * @param \ReflectionClass $class + * @param \ReflectionMethod $method + */ + public function modifyRouteMethod(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method) { + $this->modifyRoute($route); + } + + /** + * we need to make sure this is an array instead of a string which is different in Symfony Framework + * otherwise the support for defining an array of methods will not work as expected + * + * @param \Symfony\Component\Routing\Route $route + */ + protected function modifyRoute(RoutingRoute $route) { + $route->setMethods($this->getMethods()); + } - /** - * we need to make sure this is an array instead of a string which is different in Symfony Framework - * otherwise the support for defining an array of methods will not work as expected - * - * @param RoutingRoute $route - */ - protected function modifyRoute(RoutingRoute $route) - { - $route->setMethods($this->getMethods()); - } } diff --git a/src/Configuration/ParamConverter.php b/src/Configuration/ParamConverter.php index ae3f1ed..8ee3a08 100644 --- a/src/Configuration/ParamConverter.php +++ b/src/Configuration/ParamConverter.php @@ -8,175 +8,167 @@ * @author Fabien Potencier * @Annotation */ -class ParamConverter extends ConfigurationAnnotation -{ - - /** - * The parameter name. - * - * @var string - */ - protected $name; - - /** - * The parameter class. - * - * @var string - */ - protected $class; - - /** - * An array of options. - * - * @var array - */ - protected $options = []; - - /** - * Whether or not the parameter is optional. - * - * @var bool - */ - protected $optional = false; - - /** - * Use explicitly named converter instead of iterating by priorities. - * - * @var string - */ - protected $converter; - - /** - * Returns the parameter name. - * - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * Sets the parameter name. - * - * @param string $name The parameter name - */ - public function setValue($name) - { - $this->setName($name); - } - - /** - * Sets the parameter name. - * - * @param string $name The parameter name - */ - public function setName($name) - { - $this->name = $name; - } - - /** - * Returns the parameter class name. - * - * @return string $name - */ - public function getClass() - { - return $this->class; - } - - /** - * Sets the parameter class name. - * - * @param string $class The parameter class name - */ - public function setClass($class) - { - $this->class = $class; - } - - /** - * Returns an array of options. - * - * @return array - */ - public function getOptions() - { - return $this->options; - } - - /** - * Sets an array of options. - * - * @param array $options An array of options - */ - public function setOptions($options) - { - $this->options = $options; - } - - /** - * Sets whether or not the parameter is optional. - * - * @param bool $optional Whether the parameter is optional - */ - public function setIsOptional($optional) - { - $this->optional = (bool)$optional; - } - - /** - * Returns whether or not the parameter is optional. - * - * @return bool - */ - public function isOptional() - { - return $this->optional; - } - - /** - * Get explicit converter name. - * - * @return string - */ - public function getConverter() - { - return $this->converter; - } - - /** - * Set explicit converter name. - * - * @param string $converter - */ - public function setConverter($converter) - { - $this->converter = $converter; - } - - /** - * Returns the annotation alias name. - * - * @return string - * - * @see ConfigurationInterface - */ - public function getAliasName() - { - return 'converters'; - } - - /** - * Multiple ParamConverters are allowed. - * - * @return bool - * - * @see ConfigurationInterface - */ - public function allowArray() - { - return true; - } +class ParamConverter extends ConfigurationAnnotation { + + /** + * The parameter name. + * + * @var string + */ + protected $name; + + /** + * The parameter class. + * + * @var string + */ + protected $class; + + /** + * An array of options. + * + * @var array + */ + protected $options = []; + + /** + * Whether or not the parameter is optional. + * + * @var bool + */ + protected $optional = FALSE; + + /** + * Use explicitly named converter instead of iterating by priorities. + * + * @var string + */ + protected $converter; + + /** + * Returns the parameter name. + * + * @return string + */ + public function getName() { + return $this->name; + } + + /** + * Sets the parameter name. + * + * @param string $name + * The parameter name. + */ + public function setValue($name) { + $this->setName($name); + } + + /** + * Sets the parameter name. + * + * @param string $name + * The parameter name. + */ + public function setName($name) { + $this->name = $name; + } + + /** + * Returns the parameter class name. + * + * @return string $name + */ + public function getClass() { + return $this->class; + } + + /** + * Sets the parameter class name. + * + * @param string $class + * The parameter class name. + */ + public function setClass($class) { + $this->class = $class; + } + + /** + * Returns an array of options. + * + * @return array + */ + public function getOptions() { + return $this->options; + } + + /** + * Sets an array of options. + * + * @param array $options + * An array of options. + */ + public function setOptions($options) { + $this->options = $options; + } + + /** + * Sets whether or not the parameter is optional. + * + * @param bool $optional + * Whether the parameter is optional. + */ + public function setIsOptional($optional) { + $this->optional = (bool) $optional; + } + + /** + * Returns whether or not the parameter is optional. + * + * @return bool + */ + public function isOptional() { + return $this->optional; + } + + /** + * Get explicit converter name. + * + * @return string + */ + public function getConverter() { + return $this->converter; + } + + /** + * Set explicit converter name. + * + * @param string $converter + */ + public function setConverter($converter) { + $this->converter = $converter; + } + + /** + * Returns the annotation alias name. + * + * @return string + * + * @see ConfigurationInterface + */ + public function getAliasName() { + return 'converters'; + } + + /** + * Multiple ParamConverters are allowed. + * + * @return bool + * + * @see ConfigurationInterface + */ + public function allowArray() { + return TRUE; + } + } diff --git a/src/Configuration/Route.php b/src/Configuration/Route.php index 63359f4..57d361e 100644 --- a/src/Configuration/Route.php +++ b/src/Configuration/Route.php @@ -8,100 +8,92 @@ /** * @Annotation */ -class Route extends BaseRoute implements RouteModifierMethodInterface, RouteModifierClassInterface -{ - - /** - * @var string - */ - protected $service; - - /** - * @var bool - */ - protected $admin; - - /** - * @param $service - */ - public function setService($service) - { - // avoid a BC notice in case of @Route(service="") with sf ^2.7 - if (null === $this->getPath()) { - $this->setPath(''); - } - $this->service = $service; - } +class Route extends BaseRoute implements RouteModifierMethodInterface, RouteModifierClassInterface { - public function getService() - { - return $this->service; - } + /** + * @var string + */ + protected $service; + + /** + * @var bool + */ + protected $admin; - /** - * @return bool - */ - public function isAdmin() - { - return $this->admin; + /** + * @param $service + */ + public function setService($service) { + // avoid a BC notice in case of @Route(service="") with sf ^2.7 + if (NULL === $this->getPath()) { + $this->setPath(''); } + $this->service = $service; + } - /** - * @param bool $admin - * @return Route - */ - public function setAdmin($admin) - { - $this->admin = $admin; + public function getService() { + return $this->service; + } - return $this; - } + /** + * @return bool + */ + public function isAdmin() { + return $this->admin; + } - /** - * Multiple route annotations are allowed. - * - * @return bool - * - * @see ConfigurationInterface - */ - public function allowArray() - { - return true; - } + /** + * @param bool $admin + * @return Route + */ + public function setAdmin($admin) { + $this->admin = $admin; - /** - * @param RoutingRoute $route - * @param \ReflectionClass $class - * @param \ReflectionMethod $method - */ - public function modifyRouteClass(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method) - { - $this->modifyRoute($route, $class, $method); - } + return $this; + } + + /** + * Multiple route annotations are allowed. + * + * @return bool + * + * @see ConfigurationInterface + */ + public function allowArray() { + return TRUE; + } + + /** + * @param \Symfony\Component\Routing\Route $route + * @param \ReflectionClass $class + * @param \ReflectionMethod $method + */ + public function modifyRouteClass(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method) { + $this->modifyRoute($route, $class, $method); + } - /** - * @param RoutingRoute $route - * @param \ReflectionClass $class - * @param \ReflectionMethod $method - */ - public function modifyRouteMethod(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method) - { - if ($this->getService()) { - throw new \LogicException('The service option can only be specified at class level.'); - } - - $this->modifyRoute($route, $class, $method); + /** + * @param \Symfony\Component\Routing\Route $route + * @param \ReflectionClass $class + * @param \ReflectionMethod $method + */ + public function modifyRouteMethod(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method) { + if ($this->getService()) { + throw new \LogicException('The service option can only be specified at class level.'); } - /** - * @param RoutingRoute $route - * @param \ReflectionClass $class - * @param \ReflectionMethod $method - */ - protected function modifyRoute(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method) - { - if ($this->isAdmin()) { - $route->setOption('_admin_route', true); - } + $this->modifyRoute($route, $class, $method); + } + + /** + * @param \Symfony\Component\Routing\Route $route + * @param \ReflectionClass $class + * @param \ReflectionMethod $method + */ + protected function modifyRoute(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method) { + if ($this->isAdmin()) { + $route->setOption('_admin_route', TRUE); } + } + } diff --git a/src/Configuration/RouteModifierClassInterface.php b/src/Configuration/RouteModifierClassInterface.php index 3414189..74d9cc6 100644 --- a/src/Configuration/RouteModifierClassInterface.php +++ b/src/Configuration/RouteModifierClassInterface.php @@ -4,12 +4,13 @@ use Symfony\Component\Routing\Route as RoutingRoute; -interface RouteModifierClassInterface extends RouteModifierInterface -{ - /** - * @param RoutingRoute $route - * @param \ReflectionClass $class - * @param \ReflectionMethod $method - */ - public function modifyRouteClass(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method); +interface RouteModifierClassInterface extends RouteModifierInterface { + + /** + * @param \Symfony\Component\Routing\Route $route + * @param \ReflectionClass $class + * @param \ReflectionMethod $method + */ + public function modifyRouteClass(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method); + } diff --git a/src/Configuration/RouteModifierInterface.php b/src/Configuration/RouteModifierInterface.php index 6d59789..c77c7fd 100644 --- a/src/Configuration/RouteModifierInterface.php +++ b/src/Configuration/RouteModifierInterface.php @@ -2,6 +2,6 @@ namespace Drupal\controller_annotations\Configuration; -interface RouteModifierInterface -{ +interface RouteModifierInterface { + } diff --git a/src/Configuration/RouteModifierMethodInterface.php b/src/Configuration/RouteModifierMethodInterface.php index ab8d569..d81122c 100644 --- a/src/Configuration/RouteModifierMethodInterface.php +++ b/src/Configuration/RouteModifierMethodInterface.php @@ -4,12 +4,13 @@ use Symfony\Component\Routing\Route as RoutingRoute; -interface RouteModifierMethodInterface extends RouteModifierInterface -{ - /** - * @param RoutingRoute $route - * @param \ReflectionClass $class - * @param \ReflectionMethod $method - */ - public function modifyRouteMethod(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method); +interface RouteModifierMethodInterface extends RouteModifierInterface { + + /** + * @param \Symfony\Component\Routing\Route $route + * @param \ReflectionClass $class + * @param \ReflectionMethod $method + */ + public function modifyRouteMethod(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method); + } diff --git a/src/Configuration/Security.php b/src/Configuration/Security.php index 8b6b342..c78ecd8 100644 --- a/src/Configuration/Security.php +++ b/src/Configuration/Security.php @@ -7,250 +7,229 @@ /** * @Annotation */ -class Security extends ConfigurationAnnotation implements RouteModifierMethodInterface, RouteModifierClassInterface -{ - /** - * @var string - */ - protected $permission; - - /** - * @var string - */ - protected $role; - - /** - * @var bool - */ - protected $access; - - /** - * @var string - */ - protected $entity; - - /** - * @var bool - */ - protected $csrf; - - /** - * @var string - */ - protected $custom; - - /** - * @return bool - */ - public function hasPermission() - { - return !empty($this->permission); - } - - /** - * @return string - */ - public function getPermission() - { - return $this->permission; - } - - /** - * @param string $permission - * @return Security - */ - public function setPermission($permission) - { - $this->permission = $permission; - - return $this; - } - - /** - * @return bool - */ - public function hasRole() - { - return !empty($this->role); - } - - /** - * @return string - */ - public function getRole() - { - return $this->role; - } - - /** - * @param string $role - * @return Security - */ - public function setRole($role) - { - $this->role = $role; - - return $this; - } - - /** - * @return bool - */ - public function isAccess() - { - return $this->access; - } - - /** - * @param bool $access - * @return Security - */ - public function setAccess($access) - { - $this->access = $access; - - return $this; - } - - /** - * @return bool - */ - public function hasEntity() - { - return !empty($this->entity); - } - - /** - * @return string - */ - public function getEntity() - { - return $this->entity; - } - - /** - * @param string $entity - * @return Security - */ - public function setEntity($entity) - { - $this->entity = $entity; - - return $this; - } - - /** - * @return bool - */ - public function hasCustom() - { - return !empty($this->custom); - } - - /** - * @return string - */ - public function getCustom() - { - return $this->custom; - } - - /** - * @param string $custom - * @return Security - */ - public function setCustom($custom) - { - $this->custom = $custom; - - return $this; - } - - /** - * @return bool - */ - public function hasCsrf() - { - return !empty($this->csrf); - } - - /** - * @param bool $csrf - * @return Security - */ - public function setCsrf($csrf) - { - $this->csrf = $csrf; - - return $this; - } - - public function getAliasName() - { - return 'security'; - } - - public function allowArray() - { - return false; - } - - /** - * @param RoutingRoute $route - * @param \ReflectionClass $class - * @param \ReflectionMethod $method - */ - public function modifyRouteClass(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method) - { - $this->modifyRoute($route, $class); - } - - /** - * @param RoutingRoute $route - * @param \ReflectionClass $class - * @param \ReflectionMethod $method - */ - public function modifyRouteMethod(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method) - { - $this->modifyRoute($route, $class); - } +class Security extends ConfigurationAnnotation implements RouteModifierMethodInterface, RouteModifierClassInterface { + + /** + * @var string + */ + protected $permission; + + /** + * @var string + */ + protected $role; + + /** + * @var bool + */ + protected $access; + + /** + * @var string + */ + protected $entity; + + /** + * @var bool + */ + protected $csrf; + + /** + * @var string + */ + protected $custom; + + /** + * @return bool + */ + public function hasPermission() { + return !empty($this->permission); + } + + /** + * @return string + */ + public function getPermission() { + return $this->permission; + } + + /** + * @param string $permission + * @return Security + */ + public function setPermission($permission) { + $this->permission = $permission; + + return $this; + } + + /** + * @return bool + */ + public function hasRole() { + return !empty($this->role); + } + + /** + * @return string + */ + public function getRole() { + return $this->role; + } + + /** + * @param string $role + * @return Security + */ + public function setRole($role) { + $this->role = $role; + + return $this; + } + + /** + * @return bool + */ + public function isAccess() { + return $this->access; + } + + /** + * @param bool $access + * @return Security + */ + public function setAccess($access) { + $this->access = $access; + + return $this; + } + + /** + * @return bool + */ + public function hasEntity() { + return !empty($this->entity); + } + + /** + * @return string + */ + public function getEntity() { + return $this->entity; + } + + /** + * @param string $entity + * @return Security + */ + public function setEntity($entity) { + $this->entity = $entity; + + return $this; + } + + /** + * @return bool + */ + public function hasCustom() { + return !empty($this->custom); + } + + /** + * @return string + */ + public function getCustom() { + return $this->custom; + } + + /** + * @param string $custom + * @return Security + */ + public function setCustom($custom) { + $this->custom = $custom; + + return $this; + } + + /** + * @return bool + */ + public function hasCsrf() { + return !empty($this->csrf); + } + + /** + * @param bool $csrf + * @return Security + */ + public function setCsrf($csrf) { + $this->csrf = $csrf; + + return $this; + } + + public function getAliasName() { + return 'security'; + } + + public function allowArray() { + return FALSE; + } + + /** + * @param \Symfony\Component\Routing\Route $route + * @param \ReflectionClass $class + * @param \ReflectionMethod $method + */ + public function modifyRouteClass(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method) { + $this->modifyRoute($route, $class); + } + + /** + * @param \Symfony\Component\Routing\Route $route + * @param \ReflectionClass $class + * @param \ReflectionMethod $method + */ + public function modifyRouteMethod(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method) { + $this->modifyRoute($route, $class); + } + + /** + * @param \Symfony\Component\Routing\Route $route + * @param \ReflectionClass $class + */ + protected function modifyRoute(RoutingRoute $route, \ReflectionClass $class) { + if ($this->isAccess()) { + $route->setRequirement('_access', 'TRUE'); + } + if ($this->hasPermission()) { + $route->setRequirement('_permission', $this->getPermission()); + } + if ($this->hasRole()) { + $route->setRequirement('_role', $this->getRole()); + } + if ($this->hasEntity()) { + $route->setRequirement('_entity_access', $this->getEntity()); + } + if ($this->hasCsrf()) { + $route->setRequirement('_csrf_token', 'TRUE'); + } + + $this->setCustomSecurity($route, $class); + } + + /** + * @param \Symfony\Component\Routing\Route $route + * @param \ReflectionClass $class + */ + protected function setCustomSecurity(RoutingRoute $route, \ReflectionClass $class) { + if ($this->hasCustom()) { + if (strpos($this->getCustom(), '::') === FALSE && $class->hasMethod($this->getCustom())) { + $this->setCustom(sprintf('%s::%s', $class->getName(), $this->getCustom())); + } + $route->setRequirement('_custom_access', $this->getCustom()); + } + } - /** - * @param RoutingRoute $route - * @param \ReflectionClass $class - */ - protected function modifyRoute(RoutingRoute $route, \ReflectionClass $class) - { - if ($this->isAccess()) { - $route->setRequirement('_access', 'TRUE'); - } - if ($this->hasPermission()) { - $route->setRequirement('_permission', $this->getPermission()); - } - if ($this->hasRole()) { - $route->setRequirement('_role', $this->getRole()); - } - if ($this->hasEntity()) { - $route->setRequirement('_entity_access', $this->getEntity()); - } - if ($this->hasCsrf()) { - $route->setRequirement('_csrf_token', 'TRUE'); - } - - $this->setCustomSecurity($route, $class); - } - - /** - * @param RoutingRoute $route - * @param \ReflectionClass $class - */ - protected function setCustomSecurity(RoutingRoute $route, \ReflectionClass $class) - { - if ($this->hasCustom()) { - if (strpos($this->getCustom(), '::') === false && $class->hasMethod($this->getCustom())) { - $this->setCustom(sprintf('%s::%s', $class->getName(), $this->getCustom())); - } - $route->setRequirement('_custom_access', $this->getCustom()); - } - } } diff --git a/src/Configuration/Template.php b/src/Configuration/Template.php index 377e392..adfdcf8 100644 --- a/src/Configuration/Template.php +++ b/src/Configuration/Template.php @@ -5,142 +5,134 @@ /** * @Annotation */ -class Template extends ConfigurationAnnotation -{ - - /** - * The template reference. - * - * @var string - */ - protected $template; - - /** - * The associative array of template variables. - * - * @var array - */ - protected $vars = []; - - /** - * Should the template be streamed? - * - * @var bool - */ - protected $streamable = false; - - /** - * The controller (+action) this annotation is set to. - * - * @var array - */ - private $owner; - - /** - * Returns the array of templates variables. - * - * @return array - */ - public function getVars() - { - return $this->vars; - } - - /** - * @param bool $streamable - */ - public function setIsStreamable($streamable) - { - $this->streamable = $streamable; - } - - /** - * @return bool - */ - public function isStreamable() - { - return (bool)$this->streamable; - } - - /** - * Sets the template variables. - * - * @param array $vars The template variables - */ - public function setVars($vars) - { - $this->vars = $vars; - } - - /** - * Sets the template logic name. - * - * @param string $template The template logic name - */ - public function setValue($template) - { - $this->setTemplate($template); - } - - /** - * Returns the template reference. - * - * @return string - */ - public function getTemplate() - { - return $this->template; - } - - /** - * Sets the template reference. - * - * @param string $template The template reference - */ - public function setTemplate($template) - { - $this->template = $template; - } - - /** - * Returns the annotation alias name. - * - * @return string - * - * @see ConfigurationInterface - */ - public function getAliasName() - { - return 'template'; - } - - /** - * Only one template directive is allowed. - * - * @return bool - * - * @see ConfigurationInterface - */ - public function allowArray() - { - return false; - } - - /** - * @param array $owner - */ - public function setOwner(array $owner) - { - $this->owner = $owner; - } - - /** - * The controller (+action) this annotation is attached to. - * - * @return array - */ - public function getOwner() - { - return $this->owner; - } +class Template extends ConfigurationAnnotation { + + /** + * The template reference. + * + * @var string + */ + protected $template; + + /** + * The associative array of template variables. + * + * @var array + */ + protected $vars = []; + + /** + * Should the template be streamed? + * + * @var bool + */ + protected $streamable = FALSE; + + /** + * The controller (+action) this annotation is set to. + * + * @var array + */ + private $owner; + + /** + * Returns the array of templates variables. + * + * @return array + */ + public function getVars() { + return $this->vars; + } + + /** + * @param bool $streamable + */ + public function setIsStreamable($streamable) { + $this->streamable = $streamable; + } + + /** + * @return bool + */ + public function isStreamable() { + return (bool) $this->streamable; + } + + /** + * Sets the template variables. + * + * @param array $vars + * The template variables. + */ + public function setVars($vars) { + $this->vars = $vars; + } + + /** + * Sets the template logic name. + * + * @param string $template + * The template logic name. + */ + public function setValue($template) { + $this->setTemplate($template); + } + + /** + * Returns the template reference. + * + * @return string + */ + public function getTemplate() { + return $this->template; + } + + /** + * Sets the template reference. + * + * @param string $template + * The template reference. + */ + public function setTemplate($template) { + $this->template = $template; + } + + /** + * Returns the annotation alias name. + * + * @return string + * + * @see ConfigurationInterface + */ + public function getAliasName() { + return 'template'; + } + + /** + * Only one template directive is allowed. + * + * @return bool + * + * @see ConfigurationInterface + */ + public function allowArray() { + return FALSE; + } + + /** + * @param array $owner + */ + public function setOwner(array $owner) { + $this->owner = $owner; + } + + /** + * The controller (+action) this annotation is attached to. + * + * @return array + */ + public function getOwner() { + return $this->owner; + } + } diff --git a/src/Configuration/Title.php b/src/Configuration/Title.php index dde4c6b..c3b5e1d 100644 --- a/src/Configuration/Title.php +++ b/src/Configuration/Title.php @@ -7,198 +7,180 @@ /** * @Annotation */ -class Title extends ConfigurationAnnotation implements RouteModifierMethodInterface, RouteModifierClassInterface -{ - /** - * @var string - */ - protected $value; - - /** - * @var array - */ - protected $arguments; - - /** - * @var array - */ - protected $context; - - /** - * @var string - */ - protected $callback; - - /** - * @param $title - */ - public function setValue($title) - { - $this->setTitle($title); - } - - /** - * @return bool - */ - public function hasTitle() - { - return !empty($this->value); - } - - /** - * @return string - */ - public function getTitle() - { - return $this->value; - } - - /** - * @param string $title - */ - public function setTitle($title) - { - $this->value = $title; - } - - /** - * @return bool - */ - public function hasArguments() - { - return !empty($this->arguments); - } - - /** - * @return array - */ - public function getArguments() - { - return $this->arguments; - } - - /** - * @param array $arguments - */ - public function setArguments(array $arguments) - { - $this->arguments = $arguments; - } - - /** - * @return bool - */ - public function hasContext() - { - return !empty($this->context); - } - - /** - * @return array - */ - public function getContext() - { - return $this->context; - } - - /** - * @param array $context - */ - public function setContext(array $context) - { - $this->context = $context; - } - - /** - * @return bool - */ - public function hasCallback() - { - return !empty($this->callback); - } - - /** - * @return string - */ - public function getCallback() - { - return $this->callback; - } - - /** - * @param string $callback - */ - public function setCallback($callback) - { - $this->callback = $callback; - } - - /** - * @return string - */ - public function getAliasName() - { - return 'title'; - } +class Title extends ConfigurationAnnotation implements RouteModifierMethodInterface, RouteModifierClassInterface { + + /** + * @var string + */ + protected $value; + + /** + * @var array + */ + protected $arguments; + + /** + * @var array + */ + protected $context; + + /** + * @var string + */ + protected $callback; + + /** + * @param $title + */ + public function setValue($title) { + $this->setTitle($title); + } + + /** + * @return bool + */ + public function hasTitle() { + return !empty($this->value); + } + + /** + * @return string + */ + public function getTitle() { + return $this->value; + } + + /** + * @param string $title + */ + public function setTitle($title) { + $this->value = $title; + } + + /** + * @return bool + */ + public function hasArguments() { + return !empty($this->arguments); + } + + /** + * @return array + */ + public function getArguments() { + return $this->arguments; + } + + /** + * @param array $arguments + */ + public function setArguments(array $arguments) { + $this->arguments = $arguments; + } + + /** + * @return bool + */ + public function hasContext() { + return !empty($this->context); + } + + /** + * @return array + */ + public function getContext() { + return $this->context; + } + + /** + * @param array $context + */ + public function setContext(array $context) { + $this->context = $context; + } + + /** + * @return bool + */ + public function hasCallback() { + return !empty($this->callback); + } + + /** + * @return string + */ + public function getCallback() { + return $this->callback; + } + + /** + * @param string $callback + */ + public function setCallback($callback) { + $this->callback = $callback; + } + + /** + * @return string + */ + public function getAliasName() { + return 'title'; + } + + /** + * @return bool + */ + public function allowArray() { + return FALSE; + } + + /** + * @param \Symfony\Component\Routing\Route $route + * @param \ReflectionClass $class + * @param \ReflectionMethod $method + */ + public function modifyRouteClass(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method) { + $this->modifyRoute($route, $class); + } + + /** + * @param \Symfony\Component\Routing\Route $route + * @param \ReflectionClass $class + * @param \ReflectionMethod $method + */ + public function modifyRouteMethod(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method) { + $this->modifyRoute($route, $class); + } + + /** + * @param \Symfony\Component\Routing\Route $route + * @param \ReflectionClass $class + */ + protected function modifyRoute(RoutingRoute $route, \ReflectionClass $class) { + if ($this->hasTitle()) { + $route->setDefault('_title', $this->getTitle()); + } + if ($this->hasArguments()) { + $route->setDefault('_title_arguments', $this->getArguments()); + } + if ($this->hasContext()) { + $route->setDefault('_title_context', $this->getContext()); + } + + $this->registerCallback($route, $class); + } + + /** + * @param \Symfony\Component\Routing\Route $route + * @param \ReflectionClass $class + */ + protected function registerCallback(RoutingRoute $route, \ReflectionClass $class) { + if ($this->hasCallback()) { + if (strpos($this->getCallback(), '::') === FALSE && $class->hasMethod($this->getCallback())) { + $this->setCallback(sprintf('%s::%s', $class->getName(), $this->getCallback())); + } + $route->setDefault('_title_callback', $this->getCallback()); + } + } - /** - * @return bool - */ - public function allowArray() - { - return false; - } - - /** - * @param RoutingRoute $route - * @param \ReflectionClass $class - * @param \ReflectionMethod $method - */ - public function modifyRouteClass(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method) - { - $this->modifyRoute($route, $class); - } - - /** - * @param RoutingRoute $route - * @param \ReflectionClass $class - * @param \ReflectionMethod $method - */ - public function modifyRouteMethod(RoutingRoute $route, \ReflectionClass $class, \ReflectionMethod $method) - { - $this->modifyRoute($route, $class); - } - - /** - * @param RoutingRoute $route - * @param \ReflectionClass $class - */ - protected function modifyRoute(RoutingRoute $route, \ReflectionClass $class) - { - if ($this->hasTitle()) { - $route->setDefault('_title', $this->getTitle()); - } - if ($this->hasArguments()) { - $route->setDefault('_title_arguments', $this->getArguments()); - } - if ($this->hasContext()) { - $route->setDefault('_title_context', $this->getContext()); - } - - $this->registerCallback($route, $class); - } - - /** - * @param RoutingRoute $route - * @param \ReflectionClass $class - */ - protected function registerCallback(RoutingRoute $route, \ReflectionClass $class) - { - if ($this->hasCallback()) { - if (strpos($this->getCallback(), '::') === false && $class->hasMethod($this->getCallback())) { - $this->setCallback(sprintf('%s::%s', $class->getName(), $this->getCallback())); - } - $route->setDefault('_title_callback', $this->getCallback()); - } - } } diff --git a/src/EventSubscriber/ControllerEventSubscriber.php b/src/EventSubscriber/ControllerEventSubscriber.php index 7523bc8..c774bc7 100644 --- a/src/EventSubscriber/ControllerEventSubscriber.php +++ b/src/EventSubscriber/ControllerEventSubscriber.php @@ -10,131 +10,132 @@ use Symfony\Component\HttpKernel\Event\FilterControllerEvent; use Symfony\Component\HttpKernel\KernelEvents; -class ControllerEventSubscriber implements EventSubscriberInterface -{ - /** - * @var Reader - */ - protected $reader; - - /** - * @param Reader $reader - */ - public function __construct(Reader $reader) - { - $this->reader = $reader; +class ControllerEventSubscriber implements EventSubscriberInterface { + + /** + * @var \Doctrine\Common\Annotations\Reader + */ + protected $reader; + + /** + * @param \Doctrine\Common\Annotations\Reader $reader + */ + public function __construct(Reader $reader) { + $this->reader = $reader; + } + + /** + * Modifies the Request object to apply configuration information found in + * controllers annotations like the template to render or HTTP caching + * configuration. + * + * @param \Symfony\Component\HttpKernel\Event\FilterControllerEvent $event + * + * @throws \ReflectionException + */ + public function onKernelController(FilterControllerEvent $event) { + $controller = $event->getController(); + + if (!is_array($controller) && method_exists($controller, '__invoke')) { + $controller = [$controller, '__invoke']; } - /** - * Modifies the Request object to apply configuration information found in - * controllers annotations like the template to render or HTTP caching - * configuration. - * - * @param FilterControllerEvent $event - * @throws \ReflectionException - */ - public function onKernelController(FilterControllerEvent $event) - { - $controller = $event->getController(); - - if (!is_array($controller) && method_exists($controller, '__invoke')) { - $controller = array($controller, '__invoke'); - } - - if (!is_array($controller)) { - return; - } - - $className = ClassUtils::getClass($controller[0]); - $object = new \ReflectionClass($className); - $method = $object->getMethod($controller[1]); - - $classConfigurations = $this->getConfigurations($this->reader->getClassAnnotations($object)); - $methodConfigurations = $this->getConfigurations($this->reader->getMethodAnnotations($method)); - - $this->setRequestAttributes( - $event->getRequest(), - $this->mergeConfigurations($classConfigurations, $methodConfigurations) - ); + if (!is_array($controller)) { + return; } - /** - * @param Request $request - * @param array $configurations - */ - protected function setRequestAttributes(Request $request, array $configurations) - { - foreach ($configurations as $key => $attributes) { - $request->attributes->set($key, $attributes); + $className = ClassUtils::getClass($controller[0]); + $object = new \ReflectionClass($className); + $method = $object->getMethod($controller[1]); + + $classConfigurations = $this->getConfigurations($this->reader->getClassAnnotations($object)); + $methodConfigurations = $this->getConfigurations($this->reader->getMethodAnnotations($method)); + + $this->setRequestAttributes( + $event->getRequest(), + $this->mergeConfigurations($classConfigurations, $methodConfigurations) + ); + } + + /** + * @param \Symfony\Component\HttpFoundation\Request $request + * @param array $configurations + */ + protected function setRequestAttributes(Request $request, array $configurations) { + foreach ($configurations as $key => $attributes) { + $request->attributes->set($key, $attributes); + } + } + + /** + * @param array $classConfigurations + * @param array $methodConfigurations + * + * @return array + */ + protected function mergeConfigurations(array $classConfigurations, array $methodConfigurations) { + $configurations = []; + foreach (array_merge(array_keys($classConfigurations), array_keys($methodConfigurations)) as $key) { + if (!array_key_exists($key, $classConfigurations)) { + $configurations[$key] = $methodConfigurations[$key]; + } + elseif (!array_key_exists($key, $methodConfigurations)) { + $configurations[$key] = $classConfigurations[$key]; + } + else { + if (is_array($classConfigurations[$key])) { + if (!is_array($methodConfigurations[$key])) { + throw new \UnexpectedValueException( + 'Configurations should both be an array or both not be an array' + ); + } + $configurations[$key] = array_merge($classConfigurations[$key], $methodConfigurations[$key]); } + else { + // method configuration overrides class configuration + $configurations[$key] = $methodConfigurations[$key]; + } + } } - /** - * @param array $classConfigurations - * @param array $methodConfigurations - * - * @return array - */ - protected function mergeConfigurations(array $classConfigurations, array $methodConfigurations) - { - $configurations = []; - foreach (array_merge(array_keys($classConfigurations), array_keys($methodConfigurations)) as $key) { - if (!array_key_exists($key, $classConfigurations)) { - $configurations[$key] = $methodConfigurations[$key]; - } elseif (!array_key_exists($key, $methodConfigurations)) { - $configurations[$key] = $classConfigurations[$key]; - } else { - if (is_array($classConfigurations[$key])) { - if (!is_array($methodConfigurations[$key])) { - throw new \UnexpectedValueException( - 'Configurations should both be an array or both not be an array' - ); - } - $configurations[$key] = array_merge($classConfigurations[$key], $methodConfigurations[$key]); - } else { - // method configuration overrides class configuration - $configurations[$key] = $methodConfigurations[$key]; - } - } + return $configurations; + } + + /** + * @param array $annotations + * + * @return array + */ + protected function getConfigurations(array $annotations) { + $configurations = []; + foreach ($annotations as $configuration) { + if ($configuration instanceof ConfigurationInterface) { + if ($configuration->allowArray()) { + $configurations['_' . $configuration->getAliasName()][] = $configuration; } - - return $configurations; + elseif (!isset($configurations['_' . $configuration->getAliasName()])) { + $configurations['_' . $configuration->getAliasName()] = $configuration; + } + else { + throw new \LogicException( + sprintf('Multiple "%s" annotations are not allowed.', $configuration->getAliasName()) + ); + } + } } - /** - * @param array $annotations - * - * @return array - */ - protected function getConfigurations(array $annotations) - { - $configurations = []; - foreach ($annotations as $configuration) { - if ($configuration instanceof ConfigurationInterface) { - if ($configuration->allowArray()) { - $configurations['_'.$configuration->getAliasName()][] = $configuration; - } elseif (!isset($configurations['_'.$configuration->getAliasName()])) { - $configurations['_'.$configuration->getAliasName()] = $configuration; - } else { - throw new \LogicException( - sprintf('Multiple "%s" annotations are not allowed.', $configuration->getAliasName()) - ); - } - } - } + return $configurations; + } - return $configurations; - } + /** + * @return array + */ + public static function getSubscribedEvents() { + return [ + KernelEvents::CONTROLLER => [ + ['onKernelController', 200], + ], + ]; + } - /** - * @return array - */ - public static function getSubscribedEvents() - { - return [ - KernelEvents::CONTROLLER => [ - ['onKernelController', 200], - ], - ]; - } } diff --git a/src/EventSubscriber/HttpCacheEventSubscriber.php b/src/EventSubscriber/HttpCacheEventSubscriber.php index fedc79d..106519b 100644 --- a/src/EventSubscriber/HttpCacheEventSubscriber.php +++ b/src/EventSubscriber/HttpCacheEventSubscriber.php @@ -11,277 +11,267 @@ use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\ExpressionLanguage\ExpressionLanguage; -class HttpCacheEventSubscriber implements EventSubscriberInterface -{ - - /** - * @var \SplObjectStorage - */ - private $lastModifiedDates; - - /** - * @var \SplObjectStorage - */ - private $eTags; - - /** - * @var ExpressionLanguage - */ - private $expressionLanguage; - - /** - */ - public function __construct() - { - $this->lastModifiedDates = new \SplObjectStorage(); - $this->eTags = new \SplObjectStorage(); +class HttpCacheEventSubscriber implements EventSubscriberInterface { + + /** + * @var \SplObjectStorage + */ + private $lastModifiedDates; + + /** + * @var \SplObjectStorage + */ + private $eTags; + + /** + * @var \Symfony\Component\ExpressionLanguage\ExpressionLanguage + */ + private $expressionLanguage; + + /** + */ + public function __construct() { + $this->lastModifiedDates = new \SplObjectStorage(); + $this->eTags = new \SplObjectStorage(); + } + + /** + * Handles HTTP validation headers. + * + * @param \Symfony\Component\HttpKernel\Event\FilterControllerEvent $event + */ + public function onKernelController(FilterControllerEvent $event) { + $request = $event->getRequest(); + if (!$configuration = $this->getConfiguration($request)) { + return; } - /** - * Handles HTTP validation headers. - * - * @param FilterControllerEvent $event - */ - public function onKernelController(FilterControllerEvent $event) - { - $request = $event->getRequest(); - if (!$configuration = $this->getConfiguration($request)) { - return; - } - - $response = new Response(); + $response = new Response(); - if ($configuration->getLastModified()) { - $this->setLastModified($request, $response, $configuration); - } - if ($configuration->getETag()) { - $this->setETag($request, $response, $configuration); - } - if ($response->isNotModified($request)) { - $event->setController( - function () use ($response) { - return $response; - } - ); - $event->stopPropagation(); - } + if ($configuration->getLastModified()) { + $this->setLastModified($request, $response, $configuration); } - - /** - * Modifies the response to apply HTTP cache headers when needed. - * - * @param FilterResponseEvent $event - */ - public function onKernelResponse(FilterResponseEvent $event) - { - $request = $event->getRequest(); - if (!$configuration = $this->getConfiguration($request)) { - return; - } - - $response = $event->getResponse(); - if ($this->hasUncachableStatusCode($response)) { - return; + if ($configuration->getETag()) { + $this->setETag($request, $response, $configuration); + } + if ($response->isNotModified($request)) { + $event->setController( + function () use ($response) { + return $response; } - - $this->setCacheProperties($request, $response, $configuration); + ); + $event->stopPropagation(); } - - /** - * @param Request $request - * @param Response $response - * @param Cache $configuration - */ - protected function setLastModified( - Request $request, - Response $response, - Cache $configuration - ) { - $lastModifiedDate = $this->getExpressionLanguage()->evaluate( - $configuration->getLastModified(), - $request->attributes->all() - ); - $response->setLastModified($lastModifiedDate); - $this->lastModifiedDates[$request] = $lastModifiedDate; + } + + /** + * Modifies the response to apply HTTP cache headers when needed. + * + * @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event + */ + public function onKernelResponse(FilterResponseEvent $event) { + $request = $event->getRequest(); + if (!$configuration = $this->getConfiguration($request)) { + return; } - /** - * @param Request $request - * @param Response $response - * @param Cache $configuration - */ - protected function setETag( - Request $request, - Response $response, - Cache $configuration - ) { - $eTag = $this->createETag($request, $configuration); - $response->setETag($eTag); - $this->eTags[$request] = $eTag; + $response = $event->getResponse(); + if ($this->hasUncachableStatusCode($response)) { + return; } - /** - * @param Request $request - * @param Cache $configuration - * - * @return string - */ - protected function createETag(Request $request, Cache $configuration) - { - return hash( - 'sha256', - $this->getExpressionLanguage()->evaluate( - $configuration->getETag(), - $request->attributes->all() - ) - ); + $this->setCacheProperties($request, $response, $configuration); + } + + /** + * @param \Symfony\Component\HttpFoundation\Request $request + * @param \Symfony\Component\HttpFoundation\Response $response + * @param \Drupal\controller_annotations\Configuration\Cache $configuration + */ + protected function setLastModified( + Request $request, + Response $response, + Cache $configuration + ) { + $lastModifiedDate = $this->getExpressionLanguage()->evaluate( + $configuration->getLastModified(), + $request->attributes->all() + ); + $response->setLastModified($lastModifiedDate); + $this->lastModifiedDates[$request] = $lastModifiedDate; + } + + /** + * @param \Symfony\Component\HttpFoundation\Request $request + * @param \Symfony\Component\HttpFoundation\Response $response + * @param \Drupal\controller_annotations\Configuration\Cache $configuration + */ + protected function setETag( + Request $request, + Response $response, + Cache $configuration + ) { + $eTag = $this->createETag($request, $configuration); + $response->setETag($eTag); + $this->eTags[$request] = $eTag; + } + + /** + * @param \Symfony\Component\HttpFoundation\Request $request + * @param \Drupal\controller_annotations\Configuration\Cache $configuration + * + * @return string + */ + protected function createETag(Request $request, Cache $configuration) { + return hash( + 'sha256', + $this->getExpressionLanguage()->evaluate( + $configuration->getETag(), + $request->attributes->all() + ) + ); + } + + /** + * @param $age + * + * @return float + */ + protected function calculateAge($age) { + $now = microtime(TRUE); + + return ceil(strtotime($age, $now) - $now); + } + + /** + * @param \Symfony\Component\HttpFoundation\Request $request + * + * @return \Drupal\controller_annotations\Configuration\Cache|false + */ + protected function getConfiguration(Request $request) { + $configuration = $request->attributes->get('_cache'); + if (empty($configuration) || !$configuration instanceof Cache) { + return FALSE; } - /** - * @param $age - * - * @return float - */ - protected function calculateAge($age) - { - $now = microtime(true); - - return ceil(strtotime($age, $now) - $now); + return $configuration; + } + + /** + * @param \Symfony\Component\HttpFoundation\Request $request + * @param \Symfony\Component\HttpFoundation\Response $response + * @param \Drupal\controller_annotations\Configuration\Cache $configuration + */ + protected function setCacheProperties( + Request $request, + Response $response, + Cache $configuration + ) { + if (NULL !== $age = $configuration->getSMaxAge()) { + if (!is_numeric($age)) { + $age = $this->calculateAge($configuration->getSMaxAge()); + } + + $response->setSharedMaxAge($age); } - /** - * @param Request $request - * - * @return Cache|false - */ - protected function getConfiguration(Request $request) - { - $configuration = $request->attributes->get('_cache'); - if (empty($configuration) || !$configuration instanceof Cache) { - return false; - } + if (NULL !== $age = $configuration->getMaxAge()) { + if (!is_numeric($age)) { + $age = $this->calculateAge($configuration->getMaxAge()); + } - return $configuration; + $response->setMaxAge($age); } - /** - * @param Request $request - * @param Response $response - * @param Cache $configuration - */ - protected function setCacheProperties( - Request $request, - Response $response, - Cache $configuration - ) { - if (null !== $age = $configuration->getSMaxAge()) { - if (!is_numeric($age)) { - $age = $this->calculateAge($configuration->getSMaxAge()); - } - - $response->setSharedMaxAge($age); - } - - if (null !== $age = $configuration->getMaxAge()) { - if (!is_numeric($age)) { - $age = $this->calculateAge($configuration->getMaxAge()); - } - - $response->setMaxAge($age); - } - - if (null !== $configuration->getExpires()) { - $response->setExpires($this->calculateExpires($configuration)); - } - - if (null !== $configuration->getVary()) { - $response->setVary($configuration->getVary()); - } - - if ($configuration->isPublic()) { - $response->setPublic(); - } - - if ($configuration->isPrivate()) { - $response->setPrivate(); - } - - if (isset($this->lastModifiedDates[$request])) { - $response->setLastModified($this->lastModifiedDates[$request]); - - unset($this->lastModifiedDates[$request]); - } + if (NULL !== $configuration->getExpires()) { + $response->setExpires($this->calculateExpires($configuration)); + } - if (isset($this->eTags[$request])) { - $response->setETag($this->eTags[$request]); + if (NULL !== $configuration->getVary()) { + $response->setVary($configuration->getVary()); + } - unset($this->eTags[$request]); - } + if ($configuration->isPublic()) { + $response->setPublic(); } - /** - * @param Cache $configuration - * - * @return bool|\DateTime - */ - protected function calculateExpires(Cache $configuration) - { - return \DateTime::createFromFormat( - 'U', - strtotime($configuration->getExpires()), - new \DateTimeZone('UTC') - ); + if ($configuration->isPrivate()) { + $response->setPrivate(); } - /** - * http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-12#section-3.1 - * - * @param Response $response - * - * @return bool - */ - protected function hasUncachableStatusCode(Response $response) - { - if (!in_array( - $response->getStatusCode(), - [200, 203, 300, 301, 302, 304, 404, 410] - )) { - return true; - } + if (isset($this->lastModifiedDates[$request])) { + $response->setLastModified($this->lastModifiedDates[$request]); - return false; + unset($this->lastModifiedDates[$request]); } - /** - * @codeCoverageIgnore - * @return ExpressionLanguage - */ - private function getExpressionLanguage() - { - if (null === $this->expressionLanguage) { - if (!class_exists(ExpressionLanguage::class)) { - throw new \RuntimeException( - 'Unable to use expressions as the Symfony ExpressionLanguage component is not installed.' - ); - } - $this->expressionLanguage = new ExpressionLanguage(); - } + if (isset($this->eTags[$request])) { + $response->setETag($this->eTags[$request]); - return $this->expressionLanguage; + unset($this->eTags[$request]); + } + } + + /** + * @param \Drupal\controller_annotations\Configuration\Cache $configuration + * + * @return bool|\DateTime + */ + protected function calculateExpires(Cache $configuration) { + return \DateTime::createFromFormat( + 'U', + strtotime($configuration->getExpires()), + new \DateTimeZone('UTC') + ); + } + + /** + * http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-12#section-3.1 + * + * @param \Symfony\Component\HttpFoundation\Response $response + * + * @return bool + */ + protected function hasUncachableStatusCode(Response $response) { + if (!in_array( + $response->getStatusCode(), + [200, 203, 300, 301, 302, 304, 404, 410] + )) { + return TRUE; } - /** - * @return array - */ - public static function getSubscribedEvents() - { - return [ - KernelEvents::CONTROLLER => [ - ['onKernelController', 0], - ], - KernelEvents::RESPONSE => [ - ['onKernelResponse', 100], - ], - ]; + return FALSE; + } + + /** + * @codeCoverageIgnore + * @return \Symfony\Component\ExpressionLanguage\ExpressionLanguage + */ + private function getExpressionLanguage() { + if (NULL === $this->expressionLanguage) { + if (!class_exists(ExpressionLanguage::class)) { + throw new \RuntimeException( + 'Unable to use expressions as the Symfony ExpressionLanguage component is not installed.' + ); + } + $this->expressionLanguage = new ExpressionLanguage(); } + + return $this->expressionLanguage; + } + + /** + * @return array + */ + public static function getSubscribedEvents() { + return [ + KernelEvents::CONTROLLER => [ + ['onKernelController', 0], + ], + KernelEvents::RESPONSE => [ + ['onKernelResponse', 100], + ], + ]; + } + } diff --git a/src/EventSubscriber/ParamConverterEventSubscriber.php b/src/EventSubscriber/ParamConverterEventSubscriber.php index 5d3bfff..b2ed993 100644 --- a/src/EventSubscriber/ParamConverterEventSubscriber.php +++ b/src/EventSubscriber/ParamConverterEventSubscriber.php @@ -9,128 +9,127 @@ use Symfony\Component\HttpKernel\Event\FilterControllerEvent; use Symfony\Component\HttpKernel\KernelEvents; -class ParamConverterEventSubscriber implements EventSubscriberInterface -{ - /** - * @var ParamConverterManager - */ - protected $manager; - - /** - * @var bool - */ - protected $autoConvert; - - /** - * @var bool - */ - private $isParameterTypeSupported; - - /** - * @param ParamConverterManager $manager A ParamConverterManager instance - * @param bool $autoConvert Auto convert non-configured objects - */ - public function __construct(ParamConverterManager $manager, $autoConvert = true) - { - $this->manager = $manager; - $this->autoConvert = $autoConvert; - $this->isParameterTypeSupported = method_exists('ReflectionParameter', 'getType'); +class ParamConverterEventSubscriber implements EventSubscriberInterface { + + /** + * @var \Drupal\controller_annotations\Configuration\ParamConverterManager + */ + protected $manager; + + /** + * @var bool + */ + protected $autoConvert; + + /** + * @var bool + */ + private $isParameterTypeSupported; + + /** + * @param \Drupal\controller_annotations\Configuration\ParamConverterManager $manager + * A ParamConverterManager instance. + * @param bool $autoConvert + * Auto convert non-configured objects. + */ + public function __construct(ParamConverterManager $manager, $autoConvert = TRUE) { + $this->manager = $manager; + $this->autoConvert = $autoConvert; + $this->isParameterTypeSupported = method_exists('ReflectionParameter', 'getType'); + } + + /** + * Modifies the ParamConverterManager instance. + * + * @param \Symfony\Component\HttpKernel\Event\FilterControllerEvent $event + * A FilterControllerEvent instance. + */ + public function onKernelController(FilterControllerEvent $event) { + $controller = $event->getController(); + $request = $event->getRequest(); + $configurations = []; + + if ($configuration = $request->attributes->get('_converters')) { + foreach (is_array($configuration) ? $configuration : [$configuration] as $configuration) { + $configurations[$configuration->getName()] = $configuration; + } } - /** - * Modifies the ParamConverterManager instance. - * - * @param FilterControllerEvent $event A FilterControllerEvent instance - */ - public function onKernelController(FilterControllerEvent $event) - { - $controller = $event->getController(); - $request = $event->getRequest(); - $configurations = []; - - if ($configuration = $request->attributes->get('_converters')) { - foreach (is_array($configuration) ? $configuration : [$configuration] as $configuration) { - $configurations[$configuration->getName()] = $configuration; - } - } - - // automatically apply conversion for non-configured objects - if ($this->autoConvert) { - $configurations = $this->autoConfigure($this->resolveMethod($controller), $request, $configurations); - } + // automatically apply conversion for non-configured objects + if ($this->autoConvert) { + $configurations = $this->autoConfigure($this->resolveMethod($controller), $request, $configurations); + } - $this->manager->apply($request, $configurations); + $this->manager->apply($request, $configurations); + } + + /** + * @param $controller + * + * @return \ReflectionFunction|\ReflectionMethod + */ + protected function resolveMethod($controller) { + if (is_array($controller)) { + return new \ReflectionMethod($controller[0], $controller[1]); + } + if (is_object($controller) && is_callable($controller, '__invoke')) { + return new \ReflectionMethod($controller, '__invoke'); } - /** - * @param $controller - * - * @return \ReflectionFunction|\ReflectionMethod - */ - protected function resolveMethod($controller) - { - if (is_array($controller)) { - return new \ReflectionMethod($controller[0], $controller[1]); - } - if (is_object($controller) && is_callable($controller, '__invoke')) { - return new \ReflectionMethod($controller, '__invoke'); + return new \ReflectionFunction($controller); + } + + /** + * @param \ReflectionFunctionAbstract $r + * @param \Symfony\Component\HttpFoundation\Request $request + * @param array $configurations + * + * @return array + */ + private function autoConfigure(\ReflectionFunctionAbstract $r, Request $request, $configurations) { + foreach ($r->getParameters() as $param) { + if ($param->getClass() && $param->getClass()->isInstance($request)) { + continue; + } + + $name = $param->getName(); + $class = $param->getClass(); + $hasType = $this->isParameterTypeSupported && $param->hasType(); + + if ($class || $hasType) { + if (!isset($configurations[$name])) { + $configuration = new ParamConverter([]); + $configuration->setName($name); + + $configurations[$name] = $configuration; } - return new \ReflectionFunction($controller); + if ($class && NULL === $configurations[$name]->getClass()) { + $configurations[$name]->setClass($class->getName()); + } + } + + if (isset($configurations[$name])) { + $configurations[$name]->setIsOptional( + $param->isOptional() + || $param->isDefaultValueAvailable() + || $hasType && $param->getType()->allowsNull() + ); + } } - /** - * @param \ReflectionFunctionAbstract $r - * @param \Symfony\Component\HttpFoundation\Request $request - * @param array $configurations - * - * @return array - */ - private function autoConfigure(\ReflectionFunctionAbstract $r, Request $request, $configurations) - { - foreach ($r->getParameters() as $param) { - if ($param->getClass() && $param->getClass()->isInstance($request)) { - continue; - } - - $name = $param->getName(); - $class = $param->getClass(); - $hasType = $this->isParameterTypeSupported && $param->hasType(); - - if ($class || $hasType) { - if (!isset($configurations[$name])) { - $configuration = new ParamConverter([]); - $configuration->setName($name); - - $configurations[$name] = $configuration; - } - - if ($class && null === $configurations[$name]->getClass()) { - $configurations[$name]->setClass($class->getName()); - } - } - - if (isset($configurations[$name])) { - $configurations[$name]->setIsOptional( - $param->isOptional() - || $param->isDefaultValueAvailable() - || $hasType && $param->getType()->allowsNull() - ); - } - } + return $configurations; + } - return $configurations; - } + /** + * @return array + */ + public static function getSubscribedEvents() { + return [ + KernelEvents::CONTROLLER => [ + ['onKernelController', 100], + ], + ]; + } - /** - * @return array - */ - public static function getSubscribedEvents() - { - return [ - KernelEvents::CONTROLLER => [ - ['onKernelController', 100], - ], - ]; - } } diff --git a/src/EventSubscriber/RouteEventSubscriber.php b/src/EventSubscriber/RouteEventSubscriber.php index 506dc24..680b6aa 100644 --- a/src/EventSubscriber/RouteEventSubscriber.php +++ b/src/EventSubscriber/RouteEventSubscriber.php @@ -9,88 +9,86 @@ use Symfony\Component\Routing\Loader\AnnotationDirectoryLoader; use Symfony\Component\Routing\Route; -class RouteEventSubscriber implements EventSubscriberInterface -{ - /** - * @var AnnotationDirectoryLoader - */ - private $annotationDirectoryLoader; +class RouteEventSubscriber implements EventSubscriberInterface { - /** - * @var string - */ - private $rootPath; + /** + * @var \Symfony\Component\Routing\Loader\AnnotationDirectoryLoader + */ + private $annotationDirectoryLoader; - /** - * @param AnnotationDirectoryLoader $annotationDirectoryLoader - * @param string $rootPath - */ - public function __construct(AnnotationDirectoryLoader $annotationDirectoryLoader, string $rootPath) - { - $this->registerAnnotations(); - $this->annotationDirectoryLoader = $annotationDirectoryLoader; - $this->rootPath = $rootPath; - } + /** + * @var string + */ + private $rootPath; - /** - * Configure the annotation registry to make routing annotations available - */ - private function registerAnnotations() - { - AnnotationRegistry::registerLoader('class_exists'); - } + /** + * @param \Symfony\Component\Routing\Loader\AnnotationDirectoryLoader $annotationDirectoryLoader + * @param string $rootPath + */ + public function __construct(AnnotationDirectoryLoader $annotationDirectoryLoader, string $rootPath) { + $this->registerAnnotations(); + $this->annotationDirectoryLoader = $annotationDirectoryLoader; + $this->rootPath = $rootPath; + } + /** + * Configure the annotation registry to make routing annotations available + */ + private function registerAnnotations() { + AnnotationRegistry::registerLoader('class_exists'); + } + + /** + * @param \Drupal\Core\Routing\RouteBuildEvent $event + * @throws \Exception + */ + public function onRoutes(RouteBuildEvent $event) { /** - * @param RouteBuildEvent $event - * @throws \Exception + * @var $route Route */ - public function onRoutes(RouteBuildEvent $event) - { - /** - * @var $route Route - */ - foreach ($event->getRouteCollection() as $name => $route) { - if ($route->hasOption('type') - && $route->getOption('type') === 'annotation' - ) { - $routeCollection = $this->annotationDirectoryLoader->load($this->rootPath.$this->getRoutePath($route)); - $routeCollection->addPrefix($route->getPath()); + foreach ($event->getRouteCollection() as $name => $route) { + if ($route->hasOption('type') + && $route->getOption('type') === 'annotation' + ) { + $routeCollection = $this->annotationDirectoryLoader->load($this->rootPath . $this->getRoutePath($route)); + $routeCollection->addPrefix($route->getPath()); - $event->getRouteCollection()->addCollection($routeCollection); - $event->getRouteCollection()->remove($name); - } - } + $event->getRouteCollection()->addCollection($routeCollection); + $event->getRouteCollection()->remove($name); + } } + } - /** - * @return array - */ - public static function getSubscribedEvents() - { - return [ - RoutingEvents::DYNAMIC => [ - ['onRoutes', 0], - ], - ]; + /** + * @return array + */ + public static function getSubscribedEvents() { + return [ + RoutingEvents::DYNAMIC => [ + ['onRoutes', 0], + ], + ]; + } + + /** + * @param \Symfony\Component\Routing\Route $route + * @return string + * @throws \Exception + */ + protected function getRoutePath(Route $route) { + if ($route->hasOption('path')) { + $path = $route->getOption('path'); + } + elseif ($route->hasOption('module')) { + $path = sprintf('/%s/src/Controller', drupal_get_path('module', $route->getOption('module'))); + } + else { + throw new \Exception( + 'Either the "resource" or "module" option is required to load from annotations' + ); } - /** - * @param Route $route - * @return string - * @throws \Exception - */ - protected function getRoutePath(Route $route) - { - if ($route->hasOption('path')) { - $path = $route->getOption('path'); - } elseif ($route->hasOption('module')) { - $path = sprintf('/%s/src/Controller', drupal_get_path('module', $route->getOption('module'))); - } else { - throw new \Exception( - 'Either the "resource" or "module" option is required to load from annotations' - ); - } + return $path; + } - return $path; - } } diff --git a/src/EventSubscriber/TemplateEventSubscriber.php b/src/EventSubscriber/TemplateEventSubscriber.php index 3c08796..05f03d7 100644 --- a/src/EventSubscriber/TemplateEventSubscriber.php +++ b/src/EventSubscriber/TemplateEventSubscriber.php @@ -13,186 +13,182 @@ use Symfony\Component\HttpKernel\Event\KernelEvent; use Symfony\Component\HttpKernel\KernelEvents; -class TemplateEventSubscriber implements EventSubscriberInterface -{ - /** - * @var \Twig_Environment - */ - private $twig; - - /** - * @var TemplateResolver - */ - private $resolver; - - /** - * @param \Twig_Environment $twig - * @param TemplateResolver $resolver - */ - public function __construct(\Twig_Environment $twig, TemplateResolver $resolver) - { - $this->twig = $twig; - $this->resolver = $resolver; +class TemplateEventSubscriber implements EventSubscriberInterface { + + /** + * @var \Twig_Environment + */ + private $twig; + + /** + * @var \Drupal\controller_annotations\Configuration\TemplateResolver + */ + private $resolver; + + /** + * @param \Twig_Environment $twig + * @param \Drupal\controller_annotations\Configuration\TemplateResolver $resolver + */ + public function __construct(\Twig_Environment $twig, TemplateResolver $resolver) { + $this->twig = $twig; + $this->resolver = $resolver; + } + + /** + * Guesses the template name to render and its variables and adds them to + * the request object. + * + * @param \Symfony\Component\HttpKernel\Event\FilterControllerEvent $event + * A FilterControllerEvent instance. + */ + public function onKernelController(FilterControllerEvent $event) { + $template = $this->getTemplateFromRequest($event); + if (!$template instanceof Template) { + return; } - /** - * Guesses the template name to render and its variables and adds them to - * the request object. - * - * @param FilterControllerEvent $event A FilterControllerEvent instance - */ - public function onKernelController(FilterControllerEvent $event) - { - $template = $this->getTemplateFromRequest($event); - if (!$template instanceof Template) { - return; - } - - $template->setOwner($event->getController()); - $this->normalizeTemplate($template); + $template->setOwner($event->getController()); + $this->normalizeTemplate($template); + } + + /** + * Renders the template and initializes a new response object with the + * rendered template content. + * + * @param \Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent $event + */ + public function onKernelView(GetResponseForControllerResultEvent $event) { + $template = $this->getTemplateFromRequest($event); + if (!$template instanceof Template) { + return; } - /** - * Renders the template and initializes a new response object with the - * rendered template content. - * - * @param GetResponseForControllerResultEvent $event - */ - public function onKernelView(GetResponseForControllerResultEvent $event) - { - $template = $this->getTemplateFromRequest($event); - if (!$template instanceof Template) { - return; - } - - $this->setResponse($event, $template, $this->getParameters($event, $template)); + $this->setResponse($event, $template, $this->getParameters($event, $template)); + } + + /** + * @param \Symfony\Component\HttpKernel\Event\KernelEvent $event + * @return mixed + */ + private function getTemplateFromRequest(KernelEvent $event) { + return $event->getRequest()->attributes->get('_template'); + } + + /** + * @param \Drupal\controller_annotations\Configuration\Template $template + */ + private function normalizeTemplate(Template $template) { + if (is_null($template->getTemplate())) { + $templateFile = $this->resolver->resolveByControllerAndAction( + get_class($template->getOwner()[0]), + $template->getOwner()[1] + ); } - - /** - * @param KernelEvent $event - * @return mixed - */ - private function getTemplateFromRequest(KernelEvent $event) - { - return $event->getRequest()->attributes->get('_template'); + else { + $templateFile = $this->resolver->normalize($template->getTemplate()); } - /** - * @param Template $template - */ - private function normalizeTemplate(Template $template) - { - if (is_null($template->getTemplate())) { - $templateFile = $this->resolver->resolveByControllerAndAction( - get_class($template->getOwner()[0]), - $template->getOwner()[1] - ); - } else { - $templateFile = $this->resolver->normalize($template->getTemplate()); - } - - $template->setTemplate($templateFile); - } + $template->setTemplate($templateFile); + } - /** - * @param GetResponseForControllerResultEvent $event - * @param Template $template - * @param $parameters - */ - private function setResponse(GetResponseForControllerResultEvent $event, Template $template, $parameters) - { - // make sure the owner (controller+dependencies) is not cached or stored elsewhere - $template->setOwner([]); - - if ($template->isStreamable()) { - $callback = function () use ($template, $parameters) { - $this->twig->display($template->getTemplate(), $parameters); - }; - - $event->setResponse(new StreamedResponse($callback)); - } else { - $event->setResponse(new Response($this->twig->render($template->getTemplate(), $parameters))); - } - } + /** + * @param \Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent $event + * @param \Drupal\controller_annotations\Configuration\Template $template + * @param $parameters + */ + private function setResponse(GetResponseForControllerResultEvent $event, Template $template, $parameters) { + // make sure the owner (controller+dependencies) is not cached or stored elsewhere + $template->setOwner([]); - /** - * @param GetResponseForControllerResultEvent $event - * @param Template $template - * @return array|mixed - */ - private function getParameters(GetResponseForControllerResultEvent $event, Template $template) - { - $parameters = $event->getControllerResult(); - - $owner = $template->getOwner(); - list($controller, $action) = $owner; - - // when the annotation declares no default vars and the action returns - // null, all action method arguments are used as default vars - if (null === $parameters) { - $parameters = $this->resolveDefaultParameters($event->getRequest(), $template, $controller, $action); - } - - return $parameters; - } + if ($template->isStreamable()) { + $callback = function () use ($template, $parameters) { + $this->twig->display($template->getTemplate(), $parameters); + }; - /** - * @param Request $request - * @param Template $template - * @param object $controller - * @param string $action - * @return array - */ - private function resolveDefaultParameters(Request $request, Template $template, $controller, $action) - { - $arguments = $template->getVars(); - - if (0 === count($arguments)) { - $r = new \ReflectionObject($controller); - - $arguments = []; - foreach ($r->getMethod($action)->getParameters() as $param) { - $arguments[] = $param; - } - } - - return $this->resolveParametersWithReflection($request, $arguments); + $event->setResponse(new StreamedResponse($callback)); + } + else { + $event->setResponse(new Response($this->twig->render($template->getTemplate(), $parameters))); + } + } + + /** + * @param \Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent $event + * @param \Drupal\controller_annotations\Configuration\Template $template + * @return array|mixed + */ + private function getParameters(GetResponseForControllerResultEvent $event, Template $template) { + $parameters = $event->getControllerResult(); + + $owner = $template->getOwner(); + list($controller, $action) = $owner; + + // when the annotation declares no default vars and the action returns + // null, all action method arguments are used as default vars + if (NULL === $parameters) { + $parameters = $this->resolveDefaultParameters($event->getRequest(), $template, $controller, $action); } - /** - * fetch the arguments of @Template.vars or everything if desired - * and assign them to the designated template - * - * @param Request $request - * @param array $arguments - * @return array - */ - private function resolveParametersWithReflection(Request $request, array $arguments) - { - $parameters = []; - foreach ($arguments as $argument) { - if ($argument instanceof \ReflectionParameter) { - $name = $argument->getName(); - $parameters[$name] = !$request->attributes->has($name) - && $argument->isDefaultValueAvailable() - ? $argument->getDefaultValue() - : $request->attributes->get($name); - } else { - $parameters[$argument] = $request->attributes->get($argument); - } - } - - return $parameters; + return $parameters; + } + + /** + * @param \Symfony\Component\HttpFoundation\Request $request + * @param \Drupal\controller_annotations\Configuration\Template $template + * @param object $controller + * @param string $action + * @return array + */ + private function resolveDefaultParameters(Request $request, Template $template, $controller, $action) { + $arguments = $template->getVars(); + + if (0 === count($arguments)) { + $r = new \ReflectionObject($controller); + + $arguments = []; + foreach ($r->getMethod($action)->getParameters() as $param) { + $arguments[] = $param; + } } - /** - * @return array - */ - public static function getSubscribedEvents() - { - return [ - KernelEvents::CONTROLLER => ['onKernelController', 100], - KernelEvents::VIEW => ['onKernelView', 10], - ]; + return $this->resolveParametersWithReflection($request, $arguments); + } + + /** + * fetch the arguments of @Template.vars or everything if desired + * and assign them to the designated template + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @param array $arguments + * + * @return array + */ + private function resolveParametersWithReflection(Request $request, array $arguments) { + $parameters = []; + foreach ($arguments as $argument) { + if ($argument instanceof \ReflectionParameter) { + $name = $argument->getName(); + $parameters[$name] = !$request->attributes->has($name) + && $argument->isDefaultValueAvailable() + ? $argument->getDefaultValue() + : $request->attributes->get($name); + } + else { + $parameters[$argument] = $request->attributes->get($argument); + } } + + return $parameters; + } + + /** + * @return array + */ + public static function getSubscribedEvents() { + return [ + KernelEvents::CONTROLLER => ['onKernelController', 100], + KernelEvents::VIEW => ['onKernelView', 10], + ]; + } + } diff --git a/src/Request/ParamConverter/DateTimeParamConverter.php b/src/Request/ParamConverter/DateTimeParamConverter.php index b38b3c2..9252e48 100644 --- a/src/Request/ParamConverter/DateTimeParamConverter.php +++ b/src/Request/ParamConverter/DateTimeParamConverter.php @@ -12,64 +12,64 @@ * * @author Benjamin Eberlei */ -class DateTimeParamConverter implements ParamConverterInterface -{ - /** - * {@inheritdoc} - * - * @throws NotFoundHttpException When invalid date given - */ - public function apply(Request $request, ParamConverter $configuration) - { - $param = $configuration->getName(); - if (!$request->attributes->has($param)) { - return false; - } +class DateTimeParamConverter implements ParamConverterInterface { - $value = $request->attributes->get($param); - if (!$value && $configuration->isOptional()) { - return false; - } - - $request->attributes->set( - $param, - $this->getDateTime($configuration, $value, $param) - ); + /** + * {@inheritdoc} + * + * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException + * When invalid date given. + */ + public function apply(Request $request, ParamConverter $configuration) { + $param = $configuration->getName(); + if (!$request->attributes->has($param)) { + return FALSE; + } - return true; + $value = $request->attributes->get($param); + if (!$value && $configuration->isOptional()) { + return FALSE; } - /** - * @param ParamConverter $configuration - * @param $value - * @param $param - * @return bool|DateTime - * @throws \Exception - */ - protected function getDateTime(ParamConverter $configuration, $value, $param) - { - $options = $configuration->getOptions(); + $request->attributes->set( + $param, + $this->getDateTime($configuration, $value, $param) + ); - if (isset($options['format'])) { - $date = DateTime::createFromFormat($options['format'], $value); - } elseif (false !== strtotime($value)) { - $date = new DateTime($value); - } + return TRUE; + } - if (empty($date)) { - throw new NotFoundHttpException( - sprintf('Invalid date given for parameter "%s".', $param) - ); - } + /** + * @param \Drupal\controller_annotations\Configuration\ParamConverter $configuration + * @param $value + * @param $param + * @return bool|DateTime + * @throws \Exception + */ + protected function getDateTime(ParamConverter $configuration, $value, $param) { + $options = $configuration->getOptions(); - return $date; + if (isset($options['format'])) { + $date = DateTime::createFromFormat($options['format'], $value); + } + elseif (FALSE !== strtotime($value)) { + $date = new DateTime($value); } - /** - * {@inheritdoc} - */ - public function supports(ParamConverter $configuration) - { - return \DateTime::class === $configuration->getClass(); + if (empty($date)) { + throw new NotFoundHttpException( + sprintf('Invalid date given for parameter "%s".', $param) + ); } + + return $date; + } + + /** + * {@inheritdoc} + */ + public function supports(ParamConverter $configuration) { + return \DateTime::class === $configuration->getClass(); + } + } diff --git a/src/Request/ParamConverter/EntityParamConverter.php b/src/Request/ParamConverter/EntityParamConverter.php index 4b1e2fa..f71a63c 100644 --- a/src/Request/ParamConverter/EntityParamConverter.php +++ b/src/Request/ParamConverter/EntityParamConverter.php @@ -13,101 +13,97 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -class EntityParamConverter implements ParamConverterInterface -{ +class EntityParamConverter implements ParamConverterInterface { - /** - * @var EntityTypeManagerInterface - */ - private $entityTypeManager; + /** + * @var \Drupal\Core\Entity\EntityTypeManagerInterface + */ + private $entityTypeManager; - /** - * @param EntityTypeManagerInterface $entityTypeManager - */ - public function __construct(EntityTypeManagerInterface $entityTypeManager) - { - $this->entityTypeManager = $entityTypeManager; + /** + * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager + */ + public function __construct(EntityTypeManagerInterface $entityTypeManager) { + $this->entityTypeManager = $entityTypeManager; + } + + /** + * @param \Symfony\Component\HttpFoundation\Request $request + * @param \Drupal\controller_annotations\Configuration\ParamConverter $configuration + * + * @return bool + */ + public function apply(Request $request, ParamConverter $configuration) { + $param = $configuration->getName(); + if (!$request->attributes->has($param)) { + return FALSE; } - /** - * @param Request $request - * @param ParamConverter $configuration - * - * @return bool - */ - public function apply(Request $request, ParamConverter $configuration) - { - $param = $configuration->getName(); - if (!$request->attributes->has($param)) { - return false; - } + $value = $request->attributes->get($param); + if (!$value && $configuration->isOptional()) { + return FALSE; + } - $value = $request->attributes->get($param); - if (!$value && $configuration->isOptional()) { - return false; - } + $request->attributes->set( + $param, + $this->getNode($value, $configuration) + ); - $request->attributes->set( - $param, - $this->getNode($value, $configuration) - ); + return TRUE; + } - return true; - } + /** + * @param string $value + * @param \Drupal\controller_annotations\Configuration\ParamConverter $configuration + * + * @return \Drupal\Core\Entity\EntityInterface|null + */ + protected function getNode($value, ParamConverter $configuration) { + $node = $this->entityTypeManager->getStorage('node')->load($value); + $this->assertValidNode($configuration, $node); - /** - * @param string $value - * @param ParamConverter $configuration - * - * @return EntityInterface|null - */ - protected function getNode($value, ParamConverter $configuration) - { - $node = $this->entityTypeManager->getStorage('node')->load($value); - $this->assertValidNode($configuration, $node); + return $node; + } - return $node; + /** + * @param \Drupal\controller_annotations\Configuration\ParamConverter $configuration + * @param \Drupal\Core\Entity\EntityInterface $node + */ + protected function assertValidNode( + ParamConverter $configuration, + EntityInterface $node = NULL + ) { + if (is_null($node) && $configuration->isOptional()) { + return; } - - /** - * @param ParamConverter $configuration - * @param EntityInterface $node - */ - protected function assertValidNode( - ParamConverter $configuration, - EntityInterface $node = null - ) { - if (is_null($node) && $configuration->isOptional()) { - return; - } - if (is_null($node)) { - throw new NotFoundHttpException('entity not found.'); - } - $options = $configuration->getOptions(); - if (isset($options['bundle']) && $node->bundle() !== $options['bundle']) { - throw new NotFoundHttpException( - sprintf('%s not found.', $options['bundle']) - ); - } + if (is_null($node)) { + throw new NotFoundHttpException('entity not found.'); } - - /** - * @param ParamConverter $configuration - * - * @return bool - */ - public function supports(ParamConverter $configuration) - { - return in_array( - $configuration->getClass(), - [ - NodeInterface::class, - Node::class, - EntityInterface::class, - Entity::class, - ContentEntityInterface::class, - ContentEntityBase::class, - ] - ); + $options = $configuration->getOptions(); + if (isset($options['bundle']) && $node->bundle() !== $options['bundle']) { + throw new NotFoundHttpException( + sprintf('%s not found.', $options['bundle']) + ); } + } + + /** + * @param \Drupal\controller_annotations\Configuration\ParamConverter $configuration + * + * @return bool + */ + public function supports(ParamConverter $configuration) { + return in_array( + $configuration->getClass(), + [ + NodeInterface::class, + Node::class, + EntityInterface::class, + Entity::class, + ContentEntityInterface::class, + ContentEntityBase::class, + ] + ); + } + } diff --git a/src/Request/ParamConverter/ParamConverterInterface.php b/src/Request/ParamConverter/ParamConverterInterface.php index 14fb4a9..d713458 100644 --- a/src/Request/ParamConverter/ParamConverterInterface.php +++ b/src/Request/ParamConverter/ParamConverterInterface.php @@ -11,24 +11,28 @@ * * @author Fabien Potencier */ -interface ParamConverterInterface -{ - /** - * Stores the object in the request. - * - * @param Request $request The request - * @param ParamConverter $configuration Contains the name, class and options of the object - * - * @return bool True if the object has been successfully set, else false - */ - public function apply(Request $request, ParamConverter $configuration); +interface ParamConverterInterface { + + /** + * Stores the object in the request. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * The request. + * @param \Drupal\controller_annotations\Configuration\ParamConverter $configuration + * Contains the name, class and options of the object. + * + * @return bool True if the object has been successfully set, else false + */ + public function apply(Request $request, ParamConverter $configuration); + + /** + * Checks if the object is supported. + * + * @param \Drupal\controller_annotations\Configuration\ParamConverter $configuration + * Should be an instance of ParamConverter. + * + * @return bool True if the object is supported, else false + */ + public function supports(ParamConverter $configuration); - /** - * Checks if the object is supported. - * - * @param ParamConverter $configuration Should be an instance of ParamConverter - * - * @return bool True if the object is supported, else false - */ - public function supports(ParamConverter $configuration); } diff --git a/src/Request/ParamConverter/ParamConverterManager.php b/src/Request/ParamConverter/ParamConverterManager.php index 07826e3..854af0a 100644 --- a/src/Request/ParamConverter/ParamConverterManager.php +++ b/src/Request/ParamConverter/ParamConverterManager.php @@ -2,7 +2,6 @@ namespace Drupal\controller_annotations\Request\ParamConverter; -use Drupal\controller_annotations\Configuration\ConfigurationInterface; use Drupal\controller_annotations\Configuration\ParamConverter; use Symfony\Component\HttpFoundation\Request; @@ -10,141 +9,140 @@ * @author Fabien Potencier * @author Henrik Bjornskov */ -class ParamConverterManager -{ - /** - * @var array - */ - protected $converters = []; - - /** - * @var array - */ - protected $namedConverters = []; - - /** - * Applies all converters to the passed configurations and stops when a - * converter is applied it will move on to the next configuration and so on. - * - * @param Request $request - * @param array|object $configurations - */ - public function apply(Request $request, $configurations) - { - if (is_object($configurations)) { - $configurations = [$configurations]; - } - - foreach ($configurations as $configuration) { - $this->applyConverter($request, $configuration); - } +class ParamConverterManager { + + /** + * @var array + */ + protected $converters = []; + + /** + * @var array + */ + protected $namedConverters = []; + + /** + * Applies all converters to the passed configurations and stops when a + * converter is applied it will move on to the next configuration and so on. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @param array|object $configurations + */ + public function apply(Request $request, $configurations) { + if (is_object($configurations)) { + $configurations = [$configurations]; } - /** - * Apply converter on request based on the given configuration. - * - * @param Request $request - * @param ParamConverter $configuration - */ - protected function applyConverter(Request $request, ParamConverter $configuration) - { - $value = $request->attributes->get($configuration->getName()); - $className = $configuration->getClass(); - - // If the value is already an instance of the class we are trying to - // convert it into we should continue as no conversion is required - if (is_object($value) && $value instanceof $className) { - return; - } - - if ($configuration->getConverter()) { - $this->applyNamedConverter($request, $configuration); + foreach ($configurations as $configuration) { + $this->applyConverter($request, $configuration); + } + } + + /** + * Apply converter on request based on the given configuration. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @param \Drupal\controller_annotations\Configuration\ParamConverter $configuration + */ + protected function applyConverter(Request $request, ParamConverter $configuration) { + $value = $request->attributes->get($configuration->getName()); + $className = $configuration->getClass(); + + // If the value is already an instance of the class we are trying to + // convert it into we should continue as no conversion is required + if (is_object($value) && $value instanceof $className) { + return; + } - return; - } + if ($configuration->getConverter()) { + $this->applyNamedConverter($request, $configuration); - foreach ($this->all() as $converter) { - if ($converter->supports($configuration)) { - if ($converter->apply($request, $configuration)) { - return; - } - } - } + return; } - /** - * @param Request $request - * @param ParamConverter $configuration - */ - protected function applyNamedConverter(Request $request, ParamConverter $configuration) - { - $converterName = $configuration->getConverter(); - if (!isset($this->namedConverters[$converterName])) { - throw new \RuntimeException( - sprintf( - "No converter named '%s' found for conversion of parameter '%s'.", - $converterName, - $configuration->getName() - ) - ); + foreach ($this->all() as $converter) { + if ($converter->supports($configuration)) { + if ($converter->apply($request, $configuration)) { + return; } + } + } + } + + /** + * @param \Symfony\Component\HttpFoundation\Request $request + * @param \Drupal\controller_annotations\Configuration\ParamConverter $configuration + */ + protected function applyNamedConverter(Request $request, ParamConverter $configuration) { + $converterName = $configuration->getConverter(); + if (!isset($this->namedConverters[$converterName])) { + throw new \RuntimeException( + sprintf( + "No converter named '%s' found for conversion of parameter '%s'.", + $converterName, + $configuration->getName() + ) + ); + } - $converter = $this->namedConverters[$converterName]; - - if (!$converter->supports($configuration)) { - throw new \RuntimeException( - sprintf( - "Converter '%s' does not support conversion of parameter '%s'.", - $converterName, - $configuration->getName() - ) - ); - } + $converter = $this->namedConverters[$converterName]; - $converter->apply($request, $configuration); + if (!$converter->supports($configuration)) { + throw new \RuntimeException( + sprintf( + "Converter '%s' does not support conversion of parameter '%s'.", + $converterName, + $configuration->getName() + ) + ); } - /** - * Adds a parameter converter. - * - * Converters match either explicitly via $name or by iteration over all - * converters with a $priority. If you pass a $priority = null then the - * added converter will not be part of the iteration chain and can only - * be invoked explicitly. - * - * @param ParamConverterInterface $converter A ParamConverterInterface instance - * @param int $priority The priority (between -10 and 10). - * @param string $name Name of the converter. - */ - public function add(ParamConverterInterface $converter, $priority = 0, $name = null) - { - if ($priority !== null) { - if (!isset($this->converters[$priority])) { - $this->converters[$priority] = []; - } - - $this->converters[$priority][] = $converter; - } + $converter->apply($request, $configuration); + } + + /** + * Adds a parameter converter. + * + * Converters match either explicitly via $name or by iteration over all + * converters with a $priority. If you pass a $priority = null then the + * added converter will not be part of the iteration chain and can only + * be invoked explicitly. + * + * @param \Drupal\controller_annotations\Configuration\ParamConverterInterface $converter + * A ParamConverterInterface instance. + * @param int $priority + * The priority (between -10 and 10). + * @param string $name + * Name of the converter. + */ + public function add(ParamConverterInterface $converter, $priority = 0, $name = NULL) { + if ($priority !== NULL) { + if (!isset($this->converters[$priority])) { + $this->converters[$priority] = []; + } + + $this->converters[$priority][] = $converter; + } - if (null !== $name) { - $this->namedConverters[$name] = $converter; - } + if (NULL !== $name) { + $this->namedConverters[$name] = $converter; + } + } + + /** + * Returns all registered param converters. + * + * @return array An array of param converters + */ + public function all() { + krsort($this->converters); + + $converters = []; + foreach ($this->converters as $all) { + $converters = array_merge($converters, $all); } - /** - * Returns all registered param converters. - * - * @return array An array of param converters - */ - public function all() - { - krsort($this->converters); - - $converters = array(); - foreach ($this->converters as $all) { - $converters = array_merge($converters, $all); - } + return $converters; + } - return $converters; - } } diff --git a/src/Routing/AnnotatedRouteControllerLoader.php b/src/Routing/AnnotatedRouteControllerLoader.php index e3ed0d9..ea70b22 100644 --- a/src/Routing/AnnotatedRouteControllerLoader.php +++ b/src/Routing/AnnotatedRouteControllerLoader.php @@ -8,89 +8,85 @@ use Symfony\Component\Routing\Loader\AnnotationClassLoader; use Symfony\Component\Routing\Route; -class AnnotatedRouteControllerLoader extends AnnotationClassLoader -{ - /** - * @param Route $route - * @param \ReflectionClass $class - * @param \ReflectionMethod $method - * @param mixed $annotation - */ - protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annotation) - { - $this->setController($route, $class, $method); - $this->configureClassAnnotations($route, $class, $method); - $this->configureMethodAnnotations($route, $class, $method); - } +class AnnotatedRouteControllerLoader extends AnnotationClassLoader { - /** - * @param \ReflectionClass $class - * @return array - */ - protected function getGlobals(\ReflectionClass $class): array - { - $globals = parent::getGlobals($class); + /** + * @param \Symfony\Component\Routing\Route $route + * @param \ReflectionClass $class + * @param \ReflectionMethod $method + * @param mixed $annotation + */ + protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annotation) { + $this->setController($route, $class, $method); + $this->configureClassAnnotations($route, $class, $method); + $this->configureMethodAnnotations($route, $class, $method); + } - foreach ($this->reader->getClassAnnotations($class) as $configuration) { - if ($configuration instanceof Method) { - $globals['methods'] = array_merge($globals['methods'], $configuration->getMethods()); - } - } + /** + * @param \ReflectionClass $class + * @return array + */ + protected function getGlobals(\ReflectionClass $class): array { + $globals = parent::getGlobals($class); - return $globals; + foreach ($this->reader->getClassAnnotations($class) as $configuration) { + if ($configuration instanceof Method) { + $globals['methods'] = array_merge($globals['methods'], $configuration->getMethods()); + } } - /** - * @param Route $route - * @param \ReflectionClass $class - * @param \ReflectionMethod $method - */ - protected function configureClassAnnotations(Route $route, \ReflectionClass $class, \ReflectionMethod $method) - { - foreach ($this->reader->getClassAnnotations($class) as $configuration) { - if ($configuration instanceof RouteModifierClassInterface) { - $configuration->modifyRouteClass($route, $class, $method); - } - } - } + return $globals; + } - /** - * @param Route $route - * @param \ReflectionClass $class - * @param \ReflectionMethod $method - */ - protected function configureMethodAnnotations(Route $route, \ReflectionClass $class, \ReflectionMethod $method) - { - foreach ($this->reader->getMethodAnnotations($method) as $configuration) { - if ($configuration instanceof RouteModifierMethodInterface) { - $configuration->modifyRouteMethod($route, $class, $method); - } - } + /** + * @param \Symfony\Component\Routing\Route $route + * @param \ReflectionClass $class + * @param \ReflectionMethod $method + */ + protected function configureClassAnnotations(Route $route, \ReflectionClass $class, \ReflectionMethod $method) { + foreach ($this->reader->getClassAnnotations($class) as $configuration) { + if ($configuration instanceof RouteModifierClassInterface) { + $configuration->modifyRouteClass($route, $class, $method); + } } + } - /** - * @param Route $route - * @param \ReflectionClass $class - * @param \ReflectionMethod $method - */ - protected function setController(Route $route, \ReflectionClass $class, \ReflectionMethod $method) - { - $route->setDefault('_controller', $this->getControllerName($class, $method)); + /** + * @param \Symfony\Component\Routing\Route $route + * @param \ReflectionClass $class + * @param \ReflectionMethod $method + */ + protected function configureMethodAnnotations(Route $route, \ReflectionClass $class, \ReflectionMethod $method) { + foreach ($this->reader->getMethodAnnotations($method) as $configuration) { + if ($configuration instanceof RouteModifierMethodInterface) { + $configuration->modifyRouteMethod($route, $class, $method); + } } + } - /** - * @param \ReflectionClass $class - * @param \ReflectionMethod $method - * @return string - */ - protected function getControllerName(\ReflectionClass $class, \ReflectionMethod $method) - { - $annotation = $this->reader->getClassAnnotation($class, $this->routeAnnotationClass); - if ($annotation instanceof \Drupal\controller_annotations\Configuration\Route && $service = $annotation->getService( - )) { - return sprintf('%s:%s', $service, $method->getName()); - } + /** + * @param \Symfony\Component\Routing\Route $route + * @param \ReflectionClass $class + * @param \ReflectionMethod $method + */ + protected function setController(Route $route, \ReflectionClass $class, \ReflectionMethod $method) { + $route->setDefault('_controller', $this->getControllerName($class, $method)); + } - return sprintf('%s::%s', $class->getName(), $method->getName()); + /** + * @param \ReflectionClass $class + * @param \ReflectionMethod $method + * @return string + */ + protected function getControllerName(\ReflectionClass $class, \ReflectionMethod $method) { + $annotation = $this->reader->getClassAnnotation($class, $this->routeAnnotationClass); + if ($annotation instanceof \Drupal\controller_annotations\Configuration\Route + && $service = $annotation->getService() + ) { + return sprintf('%s:%s', $service, $method->getName()); } + + return sprintf('%s::%s', $class->getName(), $method->getName()); + } + } diff --git a/src/Templating/TemplateResolver.php b/src/Templating/TemplateResolver.php index 19173ab..1ee3196 100644 --- a/src/Templating/TemplateResolver.php +++ b/src/Templating/TemplateResolver.php @@ -2,99 +2,99 @@ namespace Drupal\controller_annotations\Templating; -class TemplateResolver -{ - /** - * Convert controller class - * "Drupal\\Controller\Controller" - * and controller action - * "Action" - * into template file path: - * "modules//templates/--.html.twig" - * - * @param string $controllerClass - * @param string $action - * @return string - */ - public function resolveByControllerAndAction(string $controllerClass, string $action): string - { - preg_match('/^Drupal\\\(.*)\\\Controller\\\(.*)/', $controllerClass, $data); - if (!empty($data)) { - $module = $data[1]; - $controller = $data[2]; - } else { - throw new \InvalidArgumentException( - sprintf('Controller class "%s" not supported', $controllerClass) - ); - } +class TemplateResolver { - if (preg_match('/^(.+)Controller$/', $controller, $matchController)) { - $controller = $matchController[1]; - } - if (preg_match('/^(.+)Action$/', $action, $matchAction)) { - $action = $matchAction[1]; - } + /** + * Convert controller class + * "Drupal\\Controller\Controller" + * and controller action + * "Action" + * into template file path: + * "modules//templates/--.html.twig" + * + * @param string $controllerClass + * @param string $action + * + * @return string + */ + public function resolveByControllerAndAction(string $controllerClass, string $action): string { + preg_match('/^Drupal\\\(.*)\\\Controller\\\(.*)/', $controllerClass, $data); + if (!empty($data)) { + $module = $data[1]; + $controller = $data[2]; + } + else { + throw new \InvalidArgumentException( + sprintf('Controller class "%s" not supported', $controllerClass) + ); + } - return $this->format($module, $controller, $action); + if (preg_match('/^(.+)Controller$/', $controller, $matchController)) { + $controller = $matchController[1]; + } + if (preg_match('/^(.+)Action$/', $action, $matchAction)) { + $action = $matchAction[1]; } - /** - * Convert - * ":" - * and - * "::" - * into - * "modules//templates/-(-).html.twig" - * - * @param string $template - * @return string - */ - public function normalize(string $template): string - { - if (preg_match('/^(.+):(.+):(.+)$/', $template, $matches)) { - return $this->format($matches[1], $matches[2], $matches[3]); - } - if (preg_match('/^(.+):(.+)$/', $template, $matches)) { - return $this->format($matches[1], $matches[2]); - } + return $this->format($module, $controller, $action); + } - throw new \InvalidArgumentException( - sprintf('Template pattern "%s" not supported', $template) - ); + /** + * Convert + * ":" + * and + * "::" + * into + * "modules//templates/-(-).html.twig" + * + * @param string $template + * + * @return string + */ + public function normalize(string $template): string { + if (preg_match('/^(.+):(.+):(.+)$/', $template, $matches)) { + return $this->format($matches[1], $matches[2], $matches[3]); + } + if (preg_match('/^(.+):(.+)$/', $template, $matches)) { + return $this->format($matches[1], $matches[2]); } - /** - * @param string $module - * @param string $controller - * @param string $action - * @return string - */ - private function format(string $module, string $controller, string $action = null): string - { - $controller = $this->normalizeString($controller); + throw new \InvalidArgumentException( + sprintf('Template pattern "%s" not supported', $template) + ); + } - $templateName = sprintf('%s-%s', $module, $controller); - if (!empty($action)) { - $templateName = sprintf( - '%s-%s', - $templateName, - $this->normalizeString($action) - ); - } + /** + * @param string $module + * @param string $controller + * @param string $action + * @return string + */ + private function format(string $module, string $controller, string $action = NULL): string { + $controller = $this->normalizeString($controller); - return sprintf( - '%s/templates/%s.html.twig', - drupal_get_path('module', $module), - $templateName - ); + $templateName = sprintf('%s-%s', $module, $controller); + if (!empty($action)) { + $templateName = sprintf( + '%s-%s', + $templateName, + $this->normalizeString($action) + ); } - /** - * @param string $value - * @return string - */ - private function normalizeString(string $value): string - { - return str_replace('\\', '-', mb_strtolower($value)); - } + return sprintf( + '%s/templates/%s.html.twig', + drupal_get_path('module', $module), + $templateName + ); + } + + /** + * @param string $value + * @return string + */ + private function normalizeString(string $value): string { + return str_replace('\\', '-', mb_strtolower($value)); + } + } diff --git a/tests/modules/controller_annotations_test/src/Controller/AdminController.php b/tests/modules/controller_annotations_test/src/Controller/AdminController.php index efbeb98..8f43803 100644 --- a/tests/modules/controller_annotations_test/src/Controller/AdminController.php +++ b/tests/modules/controller_annotations_test/src/Controller/AdminController.php @@ -9,23 +9,22 @@ /** * @Route("test/admin/") */ -class AdminController extends ControllerBase -{ - /** - * @Route("admin", admin=true) - * @Security(role="administrator") - */ - public function adminAction() - { - return []; - } +class AdminController extends ControllerBase { + + /** + * @Route("admin", admin=true) + * @Security(role="administrator") + */ + public function adminAction() { + return []; + } + + /** + * @Route("normal") + * @Security(role="administrator") + */ + public function normalAction() { + return []; + } - /** - * @Route("normal") - * @Security(role="administrator") - */ - public function normalAction() - { - return []; - } } diff --git a/tests/modules/controller_annotations_test/src/Controller/BasicController.php b/tests/modules/controller_annotations_test/src/Controller/BasicController.php index 5819085..35f392c 100644 --- a/tests/modules/controller_annotations_test/src/Controller/BasicController.php +++ b/tests/modules/controller_annotations_test/src/Controller/BasicController.php @@ -10,13 +10,13 @@ /** * @Security(access=true) */ -class BasicController extends ControllerBase -{ - /** - * @Route("test/basic") - */ - public function basicAction() - { - return new Response('BasicController::basicAction'); - } +class BasicController extends ControllerBase { + + /** + * @Route("test/basic") + */ + public function basicAction() { + return new Response('BasicController::basicAction'); + } + } diff --git a/tests/modules/controller_annotations_test/src/Controller/InvokeController.php b/tests/modules/controller_annotations_test/src/Controller/InvokeController.php index da7a6bc..95680f9 100644 --- a/tests/modules/controller_annotations_test/src/Controller/InvokeController.php +++ b/tests/modules/controller_annotations_test/src/Controller/InvokeController.php @@ -10,10 +10,10 @@ * @Route("test/invoke", service="controller.invoke") * @Security(access=true) */ -class InvokeController -{ - public function __invoke() - { - return new Response('InvokeController::__invoke'); - } +class InvokeController { + + public function __invoke() { + return new Response('InvokeController::__invoke'); + } + } diff --git a/tests/modules/controller_annotations_test/src/Controller/MethodController.php b/tests/modules/controller_annotations_test/src/Controller/MethodController.php index d1905d3..46d9494 100644 --- a/tests/modules/controller_annotations_test/src/Controller/MethodController.php +++ b/tests/modules/controller_annotations_test/src/Controller/MethodController.php @@ -8,35 +8,33 @@ use Drupal\controller_annotations\Configuration\Method; use Symfony\Component\HttpFoundation\Response; -class MethodController extends ControllerBase -{ - /** - * @Route("test/method") - * @Method("GET") - * @Security(access=true) - */ - public function getAction() - { - return new Response('ClassRouteController::getAction'); - } +class MethodController extends ControllerBase { - /** - * @Route("test/method") - * @Method("POST") - * @Security(access=true) - */ - public function postAction() - { - return new Response('ClassRouteController::postAction'); - } + /** + * @Route("test/method") + * @Method("GET") + * @Security(access=true) + */ + public function getAction() { + return new Response('ClassRouteController::getAction'); + } + + /** + * @Route("test/method") + * @Method("POST") + * @Security(access=true) + */ + public function postAction() { + return new Response('ClassRouteController::postAction'); + } + + /** + * @Route("test/method/multiple") + * @Method({"GET", "POST"}) + * @Security(access=true) + */ + public function getAndPostAction() { + return new Response('ClassRouteController::getAndPostAction'); + } - /** - * @Route("test/method/multiple") - * @Method({"GET", "POST"}) - * @Security(access=true) - */ - public function getAndPostAction() - { - return new Response('ClassRouteController::getAndPostAction'); - } } diff --git a/tests/modules/controller_annotations_test/src/Controller/ParamConverterController.php b/tests/modules/controller_annotations_test/src/Controller/ParamConverterController.php index ce3cfd6..948d38c 100644 --- a/tests/modules/controller_annotations_test/src/Controller/ParamConverterController.php +++ b/tests/modules/controller_annotations_test/src/Controller/ParamConverterController.php @@ -11,49 +11,45 @@ /** * @Route("test/param-converter/") */ -class ParamConverterController extends ControllerBase -{ - - /** - * @Route("date/{start}") - * @Security(access=true) - * @ParamConverter() - */ - public function dateAction(\DateTime $start) - { - return new Response($start->format('Y-m-d')); - } +class ParamConverterController extends ControllerBase { - /** - * @Route("date-format/{start}") - * @Security(access=true) - * @ParamConverter("start", options={"format": "d-m-Y"}) - */ - public function dateFormatAction(\DateTime $start) - { - return new Response($start->format('Y-m-d')); - } + /** + * @Route("date/{start}") + * @Security(access=true) + * @ParamConverter() + */ + public function dateAction(\DateTime $start) { + return new Response($start->format('Y-m-d')); + } - /** - * @Route("date-multiple/{start}/{end}") - * @Security(access=true) - * @ParamConverter - */ - public function dateMultipleAction(\DateTime $start, \DateTime $end) - { - return new Response($start->format('Y-m-d').'-'.$end->format('Y-m-d')); - } + /** + * @Route("date-format/{start}") + * @Security(access=true) + * @ParamConverter("start", options={"format": "d-m-Y"}) + */ + public function dateFormatAction(\DateTime $start) { + return new Response($start->format('Y-m-d')); + } - /** - * @Route("date-optional/{start}") - * @Security(access=true) - * @ParamConverter() - */ - public function optionalDateAction(\DateTime $start = null) - { - if (empty($start)) { - return new Response('empty'); - } - return new Response($start->format('Y-m-d')); + /** + * @Route("date-multiple/{start}/{end}") + * @Security(access=true) + * @ParamConverter + */ + public function dateMultipleAction(\DateTime $start, \DateTime $end) { + return new Response($start->format('Y-m-d') . '-' . $end->format('Y-m-d')); + } + + /** + * @Route("date-optional/{start}") + * @Security(access=true) + * @ParamConverter() + */ + public function optionalDateAction(\DateTime $start = NULL) { + if (empty($start)) { + return new Response('empty'); } + return new Response($start->format('Y-m-d')); + } + } diff --git a/tests/modules/controller_annotations_test/src/Controller/PrefixedRouteController.php b/tests/modules/controller_annotations_test/src/Controller/PrefixedRouteController.php index 0f1931e..134267f 100644 --- a/tests/modules/controller_annotations_test/src/Controller/PrefixedRouteController.php +++ b/tests/modules/controller_annotations_test/src/Controller/PrefixedRouteController.php @@ -10,23 +10,22 @@ /** * @Route("test/prefix") */ -class PrefixedRouteController extends ControllerBase -{ - /** - * @Route - * @Security(access=true) - */ - public function emptyRouteAction() - { - return new Response('PrefixedBasicController::emptyRouteAction'); - } +class PrefixedRouteController extends ControllerBase { + + /** + * @Route + * @Security(access=true) + */ + public function emptyRouteAction() { + return new Response('PrefixedBasicController::emptyRouteAction'); + } + + /** + * @Route("/named", name="named_route") + * @Security(access=true) + */ + public function namedRouteAction() { + return new Response('PrefixedBasicController::namedRouteAction'); + } - /** - * @Route("/named", name="named_route") - * @Security(access=true) - */ - public function namedRouteAction() - { - return new Response('PrefixedBasicController::namedRouteAction'); - } } diff --git a/tests/modules/controller_annotations_test/src/Controller/SecurityController.php b/tests/modules/controller_annotations_test/src/Controller/SecurityController.php index 831bee0..8188946 100644 --- a/tests/modules/controller_annotations_test/src/Controller/SecurityController.php +++ b/tests/modules/controller_annotations_test/src/Controller/SecurityController.php @@ -15,77 +15,70 @@ * @Route("test/security/") * @Method("GET") */ -class SecurityController extends ControllerBase -{ - /** - * @Route("access") - * @Security(access=true) - */ - public function accessAction() - { - return new Response('OK'); - } +class SecurityController extends ControllerBase { - /** - * @Route("permission") - * @Security(permission="access content") - */ - public function permissionAction() - { - return new Response('OK'); - } + /** + * @Route("access") + * @Security(access=true) + */ + public function accessAction() { + return new Response('OK'); + } - /** - * @Route("role") - * @Security(role="administrator") - */ - public function roleAction() - { - return new Response('OK'); - } + /** + * @Route("permission") + * @Security(permission="access content") + */ + public function permissionAction() { + return new Response('OK'); + } - /** - * @Route("entity/{node}") - * @Security(entity="node.view") - */ - public function entityAction(Node $node) - { - return new Response('OK'); - } + /** + * @Route("role") + * @Security(role="administrator") + */ + public function roleAction() { + return new Response('OK'); + } - /** - * @Route("custom") - * @Security(custom="\Drupal\controller_annotations_test\Security\Custom::access") - */ - public function customAction() - { - return new Response('OK'); - } + /** + * @Route("entity/{node}") + * @Security(entity="node.view") + */ + public function entityAction(Node $node) { + return new Response('OK'); + } - /** - * @Route("custom-inline") - * @Security(custom="access") - */ - public function customInlineAction() - { - return new Response('OK'); - } + /** + * @Route("custom") + * @Security(custom="\Drupal\controller_annotations_test\Security\Custom::access") + */ + public function customAction() { + return new Response('OK'); + } - /** - * @Route("csrf") - * @Security(access=true, csrf=true) - */ - public function csrfAction() - { - return new Response('OK'); - } + /** + * @Route("custom-inline") + * @Security(custom="access") + */ + public function customInlineAction() { + return new Response('OK'); + } + + /** + * @Route("csrf") + * @Security(access=true, csrf=true) + */ + public function csrfAction() { + return new Response('OK'); + } + + /** + * @param \Drupal\Core\Session\AccountInterface $account + * @return \Drupal\Core\Access\AccessResult + */ + public function access(AccountInterface $account) { + return AccessResult::allowedIf($account->id() === 1337); + } - /** - * @param AccountInterface $account - * @return AccessResult - */ - public function access(AccountInterface $account) - { - return AccessResult::allowedIf($account->id() === 1337); - } } diff --git a/tests/modules/controller_annotations_test/src/Controller/ServiceController.php b/tests/modules/controller_annotations_test/src/Controller/ServiceController.php index 61d41a2..933c451 100644 --- a/tests/modules/controller_annotations_test/src/Controller/ServiceController.php +++ b/tests/modules/controller_annotations_test/src/Controller/ServiceController.php @@ -9,14 +9,14 @@ /** * @Route(service="controller.service") */ -class ServiceController -{ - /** - * @Route("test/service") - * @Security(access=true) - */ - public function getAction() - { - return new Response('ServiceController::getAction'); - } +class ServiceController { + + /** + * @Route("test/service") + * @Security(access=true) + */ + public function getAction() { + return new Response('ServiceController::getAction'); + } + } diff --git a/tests/modules/controller_annotations_test/src/Controller/TemplateController.php b/tests/modules/controller_annotations_test/src/Controller/TemplateController.php index ac76999..62f38d5 100644 --- a/tests/modules/controller_annotations_test/src/Controller/TemplateController.php +++ b/tests/modules/controller_annotations_test/src/Controller/TemplateController.php @@ -10,69 +10,63 @@ /** * @Route("test/template/") */ -class TemplateController extends ControllerBase -{ - /** - * @Route("empty") - * @Security(access=true) - * @Template - */ - public function emptyAction() - { - } +class TemplateController extends ControllerBase { - /** - * @Route("module-controller") - * @Security(access=true) - * @Template("controller_annotations_test:template") - */ - public function moduleControllerAction() - { - } + /** + * @Route("empty") + * @Security(access=true) + * @Template + */ + public function emptyAction() { + } - /** - * @Route("module-controller-action") - * @Security(access=true) - * @Template("controller_annotations_test:template:action") - */ - public function moduleControllerActionAction() - { - } + /** + * @Route("module-controller") + * @Security(access=true) + * @Template("controller_annotations_test:template") + */ + public function moduleControllerAction() { + } - /** - * @Route("parameter") - * @Security(access=true) - * @Template - */ - public function parameterAction() - { - return ['parameter' => 'value']; - } + /** + * @Route("module-controller-action") + * @Security(access=true) + * @Template("controller_annotations_test:template:action") + */ + public function moduleControllerActionAction() { + } - /** - * @Route("parameter-url/{parameter}") - * @Security(access=true) - * @Template - */ - public function parameterUrlAction($parameter, $default = 'default') - { - } + /** + * @Route("parameter") + * @Security(access=true) + * @Template + */ + public function parameterAction() { + return ['parameter' => 'value']; + } - /** - * @Route("streamable") - * @Security(access=true) - * @Template(isStreamable=true) - */ - public function streamableAction() - { - } + /** + * @Route("parameter-url/{parameter}") + * @Security(access=true) + * @Template + */ + public function parameterUrlAction($parameter, $default = 'default') { + } + + /** + * @Route("streamable") + * @Security(access=true) + * @Template(isStreamable=true) + */ + public function streamableAction() { + } + + /** + * @Route("vars/{name}") + * @Security(access=true) + * @Template() + */ + public function varsAction($name = 'World') { + } - /** - * @Route("vars/{name}") - * @Security(access=true) - * @Template() - */ - public function varsAction($name = 'World') - { - } } diff --git a/tests/modules/controller_annotations_test/src/Controller/TitleController.php b/tests/modules/controller_annotations_test/src/Controller/TitleController.php index cef3a2c..fc771bf 100644 --- a/tests/modules/controller_annotations_test/src/Controller/TitleController.php +++ b/tests/modules/controller_annotations_test/src/Controller/TitleController.php @@ -10,54 +10,49 @@ /** * @Route("test/title/") */ -class TitleController extends ControllerBase -{ - - /** - * @Route("normal") - * @Security(access=true) - * @Title("Hello World") - */ - public function normalAction() - { - return []; - } - - /** - * @Route("arguments") - * @Security(access=true) - * @Title("Hello @name", arguments={"@name":"MediaMonks"}) - */ - public function argumentsAction() - { - return []; - } - - /** - * @Route("callback") - * @Security(access=true) - * @Title(callback="\Drupal\controller_annotations_test\Title\Custom::title") - */ - public function callbackAction() - { - return []; - } - - /** - * @Route("callback-inline") - * @Security(access=true) - * @Title(callback="title") - */ - public function callbackInlineAction() - { - return []; - } - - /** - * @return string - */ - public function title() - { - return 'Hello Callback Inline'; - } +class TitleController extends ControllerBase { + + /** + * @Route("normal") + * @Security(access=true) + * @Title("Hello World") + */ + public function normalAction() { + return []; + } + + /** + * @Route("arguments") + * @Security(access=true) + * @Title("Hello @name", arguments={"@name":"MediaMonks"}) + */ + public function argumentsAction() { + return []; + } + + /** + * @Route("callback") + * @Security(access=true) + * @Title(callback="\Drupal\controller_annotations_test\Title\Custom::title") + */ + public function callbackAction() { + return []; + } + + /** + * @Route("callback-inline") + * @Security(access=true) + * @Title(callback="title") + */ + public function callbackInlineAction() { + return []; + } + + /** + * @return string + */ + public function title() { + return 'Hello Callback Inline'; + } + } diff --git a/tests/modules/controller_annotations_test/src/Security/Custom.php b/tests/modules/controller_annotations_test/src/Security/Custom.php index 70615da..b039a62 100644 --- a/tests/modules/controller_annotations_test/src/Security/Custom.php +++ b/tests/modules/controller_annotations_test/src/Security/Custom.php @@ -5,14 +5,14 @@ use Drupal\Core\Access\AccessResult; use Drupal\Core\Session\AccountInterface; -class Custom -{ - /** - * @param AccountInterface $account - * @return AccessResult - */ - public function access(AccountInterface $account) - { - return AccessResult::allowedIf($account->id() === 1337); - } +class Custom { + + /** + * @param \Drupal\Core\Session\AccountInterface $account + * @return \Drupal\Core\Access\AccessResult + */ + public function access(AccountInterface $account) { + return AccessResult::allowedIf($account->id() === 1337); + } + } diff --git a/tests/modules/controller_annotations_test/src/Title/Custom.php b/tests/modules/controller_annotations_test/src/Title/Custom.php index 48e1912..df7dab0 100644 --- a/tests/modules/controller_annotations_test/src/Title/Custom.php +++ b/tests/modules/controller_annotations_test/src/Title/Custom.php @@ -2,14 +2,13 @@ namespace Drupal\controller_annotations_test\Title; -class Custom -{ - - /** - * @return string - */ - public function title() - { - return 'Hello Callback'; - } +class Custom { + + /** + * @return string + */ + public function title() { + return 'Hello Callback'; + } + } diff --git a/tests/src/Kernel/AnnotationsTest.php b/tests/src/Kernel/AnnotationsTest.php index 3eabd2b..2dd6c73 100644 --- a/tests/src/Kernel/AnnotationsTest.php +++ b/tests/src/Kernel/AnnotationsTest.php @@ -8,150 +8,143 @@ /** * @group controller_annotations */ -class AnnotationsTest extends KernelTestBase -{ - public function testRouting() - { - $response = $this->request(Request::create('/test/basic')); - $this->assertEquals('BasicController::basicAction', $response->getContent()); - - $this->assertResponseContents(Request::create('/test/method', 'GET'), 'ClassRouteController::getAction'); - $this->assertResponseContents(Request::create('/test/method', 'POST'), 'ClassRouteController::postAction'); - $this->assertMethodNotAllowed(Request::create('/test/method', 'DELETE')); - - $path = '/test/method/multiple'; - $contents = 'ClassRouteController::getAndPostAction'; - $this->assertResponseContents(Request::create($path, 'GET'), $contents); - $this->assertResponseContents(Request::create($path, 'POST'), $contents); - $this->assertMethodNotAllowed(Request::create($path, 'DELETE')); - - $this->assertResponseContents(Request::create('/test/prefix'), 'PrefixedBasicController::emptyRouteAction'); - $this->assertResponseContents(Request::create('/test/prefix/named'), 'PrefixedBasicController::namedRouteAction'); - - $this->assertResponseContents(Request::create('/test/service'), 'ServiceController::getAction'); +class AnnotationsTest extends KernelTestBase { + + public function testRouting() { + $response = $this->request(Request::create('/test/basic')); + $this->assertEquals('BasicController::basicAction', $response->getContent()); + + $this->assertResponseContents(Request::create('/test/method', 'GET'), 'ClassRouteController::getAction'); + $this->assertResponseContents(Request::create('/test/method', 'POST'), 'ClassRouteController::postAction'); + $this->assertMethodNotAllowed(Request::create('/test/method', 'DELETE')); + + $path = '/test/method/multiple'; + $contents = 'ClassRouteController::getAndPostAction'; + $this->assertResponseContents(Request::create($path, 'GET'), $contents); + $this->assertResponseContents(Request::create($path, 'POST'), $contents); + $this->assertMethodNotAllowed(Request::create($path, 'DELETE')); + + $this->assertResponseContents(Request::create('/test/prefix'), 'PrefixedBasicController::emptyRouteAction'); + $this->assertResponseContents(Request::create('/test/prefix/named'), 'PrefixedBasicController::namedRouteAction'); + + $this->assertResponseContents(Request::create('/test/service'), 'ServiceController::getAction'); + } + + public function testAdmin() { + $this->assertForbidden(Request::create('/test/admin/admin')); + $this->setAdministratorAccount(); + $this->assertResponseContains(Request::create('/test/admin/admin'), 'currentPathIsAdmin":true'); + } + + public function testNotAdmin() { + $this->assertForbidden(Request::create('/test/admin/normal')); + $this->setAdministratorAccount(); + $this->assertResponseContains(Request::create('/test/admin/normal'), 'currentPathIsAdmin":false'); + } + + public function testTemplate() { + $this->setUpTemplate(); + $this->assertResponseContents(Request::create('/test/template/empty'), 'empty'); + $this->assertResponseContents(Request::create('/test/template/module-controller'), 'module-controller'); + $this->assertResponseContents(Request::create('/test/template/module-controller-action'), 'module-controller-action'); + $this->assertResponseContents(Request::create('/test/template/parameter'), 'value'); + $this->assertResponseContents(Request::create('/test/template/parameter-url/foo'), 'foo default'); + $this->assertResponseContents(Request::create('/test/template/streamable'), 'streamed'); + $this->assertResponseContents(Request::create('/test/template/vars/Monk'), 'Hello Monk'); + } + + private function setUpTemplate() { + $sourceModule = $this->getDrupalRoot() . '/modules/controller_annotations/tests/modules/controller_annotations_test/templates/'; + + if (!file_exists($sourceModule)) { + $this->markTestSkipped('Test module can not be located'); } - public function testAdmin() - { - $this->assertForbidden(Request::create('/test/admin/admin')); - $this->setAdministratorAccount(); - $this->assertResponseContains(Request::create('/test/admin/admin'), 'currentPathIsAdmin":true'); - } + $destinationModule = $this->getDrupalRoot() . '/modules/controller_annotations_test/templates/'; - public function testNotAdmin() - { - $this->assertForbidden(Request::create('/test/admin/normal')); - $this->setAdministratorAccount(); - $this->assertResponseContains(Request::create('/test/admin/normal'), 'currentPathIsAdmin":false'); + if (!file_exists($destinationModule)) { + mkdir($destinationModule, 0777, TRUE); } - - public function testTemplate() - { - $this->setUpTemplate(); - $this->assertResponseContents(Request::create('/test/template/empty'), 'empty'); - $this->assertResponseContents(Request::create('/test/template/module-controller'), 'module-controller'); - $this->assertResponseContents(Request::create('/test/template/module-controller-action'), 'module-controller-action'); - $this->assertResponseContents(Request::create('/test/template/parameter'), 'value'); - $this->assertResponseContents(Request::create('/test/template/parameter-url/foo'), 'foo default'); - $this->assertResponseContents(Request::create('/test/template/streamable'), 'streamed'); - $this->assertResponseContents(Request::create('/test/template/vars/Monk'), 'Hello Monk'); + foreach (new \DirectoryIterator($sourceModule) as $fileInfo) { + if (!$fileInfo->isFile()) { + continue; + } + copy($sourceModule . $fileInfo->getFilename(), $destinationModule . $fileInfo->getFilename()); } + } + + public function testSecurity() { + // all access + $this->assertResponseContents(Request::create('/test/security/access'), 'OK'); + + // only access with "access content" permission + $this->assertForbidden(Request::create('/test/security/permission')); + $this->setAccount(new UserSession([ + 'uid' => 2, + 'permissions' => ['foo'], + ])); + $this->assertForbidden(Request::create('/test/security/permission')); + $this->setAccount(new UserSession([ + 'uid' => 2, + 'permissions' => ['access content'], + ])); + + $this->assertResponseContents(Request::create('/test/security/permission'), 'OK'); + $this->setAdministratorAccount(); + $this->assertResponseContents(Request::create('/test/security/permission'), 'OK'); + + // only access with "administrator" role + $this->setAnonymousAccount(); + $this->assertForbidden(Request::create('/test/security/role')); + $this->setAuthenticatedAccount(); + $this->assertForbidden(Request::create('/test/security/role')); + $this->setAdministratorAccount(); + $this->assertResponseContents(Request::create('/test/security/role'), 'OK'); + + // custom + $this->setAnonymousAccount(); + $this->assertForbidden(Request::create('/test/security/custom')); + $this->setAuthenticatedAccount(); + $this->assertForbidden(Request::create('/test/security/custom')); + $this->setAdministratorAccount(); + $this->assertForbidden(Request::create('/test/security/custom')); + $this->setAccount(new UserSession([ + 'uid' => 1337, + ])); + $this->assertResponseContents(Request::create('/test/security/custom'), 'OK'); + + // custom inline + $this->setAnonymousAccount(); + $this->assertForbidden(Request::create('/test/security/custom-inline')); + $this->setAuthenticatedAccount(); + $this->assertForbidden(Request::create('/test/security/custom-inline')); + $this->setAdministratorAccount(); + $this->assertForbidden(Request::create('/test/security/custom-inline')); + $this->setAccount(new UserSession([ + 'uid' => 1337, + ])); + $this->assertResponseContents(Request::create('/test/security/custom-inline'), 'OK'); + + // csrf + $this->assertForbidden(Request::create('/test/security/csrf')); + $this->assertResponseContents(Request::create('/test/security/csrf', 'GET', [ + 'token' => $this->kernel->getContainer()->get('csrf_token')->get('test/security/csrf'), + ]), 'OK'); + } + + public function testTitle() { + $this->assertTitleStartsWith(Request::create('/test/title/normal'), 'Hello World'); + $this->assertTitleStartsWith(Request::create('/test/title/arguments'), 'Hello MediaMonks'); + $this->assertTitleStartsWith(Request::create('/test/title/callback'), 'Hello Callback'); + $this->assertTitleStartsWith(Request::create('/test/title/callback-inline'), 'Hello Callback Inline'); + } + + public function testParamConverter() { + $this->assertResponseContents(Request::create('/test/param-converter/date/2017-08-15'), '2017-08-15'); + $this->assertResponseContents(Request::create('/test/param-converter/date-format/15-08-2017'), '2017-08-15'); + $this->assertResponseContents(Request::create('/test/param-converter/date-multiple/14-08-2017/15-08-2017'), '2017-08-14-2017-08-15'); + $this->assertResponseContents(Request::create('/test/param-converter/date-optional/03-04-1985'), '1985-04-03'); + $this->assertResponseContents(Request::create('/test/param-converter/date-optional'), 'empty'); + } - private function setUpTemplate() - { - $sourceModule = $this->getDrupalRoot() . '/modules/controller_annotations/tests/modules/controller_annotations_test/templates/'; - - if (!file_exists($sourceModule)) { - $this->markTestSkipped('Test module can not be located'); - } - - $destinationModule = $this->getDrupalRoot() . '/modules/controller_annotations_test/templates/'; - - if (!file_exists($destinationModule)) { - mkdir($destinationModule, 0777, true); - } - foreach (new \DirectoryIterator($sourceModule) as $fileInfo) { - if (!$fileInfo->isFile()) { - continue; - } - copy($sourceModule . $fileInfo->getFilename(), $destinationModule . $fileInfo->getFilename()); - } - } - - public function testSecurity() - { - // all access - $this->assertResponseContents(Request::create('/test/security/access'), 'OK'); - - // only access with "access content" permission - $this->assertForbidden(Request::create('/test/security/permission')); - $this->setAccount(new UserSession([ - 'uid' => 2, - 'permissions' => ['foo'] - ])); - $this->assertForbidden(Request::create('/test/security/permission')); - $this->setAccount(new UserSession([ - 'uid' => 2, - 'permissions' => ['access content'] - ])); - - $this->assertResponseContents(Request::create('/test/security/permission'), 'OK'); - $this->setAdministratorAccount(); - $this->assertResponseContents(Request::create('/test/security/permission'), 'OK'); - - // only access with "administrator" role - $this->setAnonymousAccount(); - $this->assertForbidden(Request::create('/test/security/role')); - $this->setAuthenticatedAccount(); - $this->assertForbidden(Request::create('/test/security/role')); - $this->setAdministratorAccount(); - $this->assertResponseContents(Request::create('/test/security/role'), 'OK'); - - // custom - $this->setAnonymousAccount(); - $this->assertForbidden(Request::create('/test/security/custom')); - $this->setAuthenticatedAccount(); - $this->assertForbidden(Request::create('/test/security/custom')); - $this->setAdministratorAccount(); - $this->assertForbidden(Request::create('/test/security/custom')); - $this->setAccount(new UserSession([ - 'uid' => 1337 - ])); - $this->assertResponseContents(Request::create('/test/security/custom'), 'OK'); - - // custom inline - $this->setAnonymousAccount(); - $this->assertForbidden(Request::create('/test/security/custom-inline')); - $this->setAuthenticatedAccount(); - $this->assertForbidden(Request::create('/test/security/custom-inline')); - $this->setAdministratorAccount(); - $this->assertForbidden(Request::create('/test/security/custom-inline')); - $this->setAccount(new UserSession([ - 'uid' => 1337 - ])); - $this->assertResponseContents(Request::create('/test/security/custom-inline'), 'OK'); - - // csrf - $this->assertForbidden(Request::create('/test/security/csrf')); - $this->assertResponseContents(Request::create('/test/security/csrf', 'GET', [ - 'token' => $this->kernel->getContainer()->get('csrf_token')->get('test/security/csrf') - ]), 'OK'); - } - - public function testTitle() - { - $this->assertTitleStartsWith(Request::create('/test/title/normal'), 'Hello World'); - $this->assertTitleStartsWith(Request::create('/test/title/arguments'), 'Hello MediaMonks'); - $this->assertTitleStartsWith(Request::create('/test/title/callback'), 'Hello Callback'); - $this->assertTitleStartsWith(Request::create('/test/title/callback-inline'), 'Hello Callback Inline'); - } - - public function testParamConverter() - { - $this->assertResponseContents(Request::create('/test/param-converter/date/2017-08-15'), '2017-08-15'); - $this->assertResponseContents(Request::create('/test/param-converter/date-format/15-08-2017'), '2017-08-15'); - $this->assertResponseContents(Request::create('/test/param-converter/date-multiple/14-08-2017/15-08-2017'), '2017-08-14-2017-08-15'); - $this->assertResponseContents(Request::create('/test/param-converter/date-optional/03-04-1985'), '1985-04-03'); - $this->assertResponseContents(Request::create('/test/param-converter/date-optional'), 'empty'); - } } diff --git a/tests/src/Kernel/DrupalTestKernel.php b/tests/src/Kernel/DrupalTestKernel.php index 1a9c4e7..cc82c48 100644 --- a/tests/src/Kernel/DrupalTestKernel.php +++ b/tests/src/Kernel/DrupalTestKernel.php @@ -6,25 +6,24 @@ use Drupal\Core\Site\Settings; use Symfony\Component\HttpFoundation\Request; -class DrupalTestKernel extends DrupalKernel -{ - /** - * {@inheritdoc} - */ - public function setSitePath($path) - { - if (empty($this->sitePath)) { - parent::setSitePath($path); - } - } +class DrupalTestKernel extends DrupalKernel { - /** - * @param Request $request - */ - protected function initializeSettings(Request $request) - { - $settings = Settings::getAll(); - parent::initializeSettings($request); - new Settings($settings); + /** + * {@inheritdoc} + */ + public function setSitePath($path) { + if (empty($this->sitePath)) { + parent::setSitePath($path); } + } + + /** + * @param \Symfony\Component\HttpFoundation\Request $request + */ + protected function initializeSettings(Request $request) { + $settings = Settings::getAll(); + parent::initializeSettings($request); + new Settings($settings); + } + } diff --git a/tests/src/Kernel/KernelTestBase.php b/tests/src/Kernel/KernelTestBase.php index dd643f4..bf841df 100644 --- a/tests/src/Kernel/KernelTestBase.php +++ b/tests/src/Kernel/KernelTestBase.php @@ -2,151 +2,138 @@ namespace Drupal\Tests\controller_annotations\Kernel; -use Drupal\Core\DrupalKernel; use Drupal\Core\Session\AccountInterface; use Drupal\Core\Session\AnonymousUserSession; -use Drupal\Tests\controller_annotations\Kernel\TestUserSession as UserSession; use Drupal\KernelTests\KernelTestBase as BaseKernelTestBase; +use Drupal\Tests\controller_annotations\Kernel\TestUserSession as UserSession; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\StreamedResponse; -abstract class KernelTestBase extends BaseKernelTestBase -{ - /** - * @var DrupalKernel - */ - protected $kernel; - - /** - * @var array - */ - public static $modules = ['controller_annotations', 'controller_annotations_test', 'user', 'system', 'node']; - - /** - * @param Request $request - * @param $contents - */ - protected function assertResponseContents(Request $request, $contents) - { - $response = $this->request($request); - if ($response instanceof StreamedResponse) { - ob_start(); - $response->sendContent(); - $actual = ob_get_contents(); - ob_end_clean(); - } - else { - $actual = $response->getContent(); - } - - $this->assertEquals($contents, trim($actual)); - } - - /** - * @param Request $request - * @param $contents - */ - protected function assertResponseContains(Request $request, $contents) - { - $response = $this->request($request); - //echo $response->getContent(); - $this->assertTrue(strpos($response->getContent(), $contents) !== false); - } - - /** - * @param Request $request - * @param $contents - */ - protected function assertResponseNotContains(Request $request, $contents) - { - $response = $this->request($request); - $this->assertTrue(strpos($response->getContent(), $contents) === false); +abstract class KernelTestBase extends BaseKernelTestBase { + + /** + * @var \Drupal\Core\DrupalKernel + */ + protected $kernel; + + /** + * @var array + */ + public static $modules = ['controller_annotations', 'controller_annotations_test', 'user', 'system', 'node']; + + /** + * @param \Symfony\Component\HttpFoundation\Request $request + * @param $contents + */ + protected function assertResponseContents(Request $request, $contents) { + $response = $this->request($request); + if ($response instanceof StreamedResponse) { + ob_start(); + $response->sendContent(); + $actual = ob_get_contents(); + ob_end_clean(); } - - /** - * @param Request $request - */ - protected function assertNotFound(Request $request) - { - $response = $this->request($request); - $this->assertEquals(Response::HTTP_NOT_FOUND, $response->getStatusCode()); + else { + $actual = $response->getContent(); } - /** - * @param Request $request - */ - protected function assertMethodNotAllowed(Request $request) - { - $response = $this->request($request); - $this->assertEquals(Response::HTTP_METHOD_NOT_ALLOWED, $response->getStatusCode()); + $this->assertEquals($contents, trim($actual)); + } + + /** + * @param \Symfony\Component\HttpFoundation\Request $request + * @param $contents + */ + protected function assertResponseContains(Request $request, $contents) { + $response = $this->request($request); + $this->assertTrue(strpos($response->getContent(), $contents) !== FALSE); + } + + /** + * @param \Symfony\Component\HttpFoundation\Request $request + * @param $contents + */ + protected function assertResponseNotContains(Request $request, $contents) { + $response = $this->request($request); + $this->assertTrue(strpos($response->getContent(), $contents) === FALSE); + } + + /** + * @param \Symfony\Component\HttpFoundation\Request $request + */ + protected function assertNotFound(Request $request) { + $response = $this->request($request); + $this->assertEquals(Response::HTTP_NOT_FOUND, $response->getStatusCode()); + } + + /** + * @param \Symfony\Component\HttpFoundation\Request $request + */ + protected function assertMethodNotAllowed(Request $request) { + $response = $this->request($request); + $this->assertEquals(Response::HTTP_METHOD_NOT_ALLOWED, $response->getStatusCode()); + } + + /** + * @param \Symfony\Component\HttpFoundation\Request $request + */ + protected function assertForbidden(Request $request) { + $response = $this->request($request); + $this->assertEquals(Response::HTTP_FORBIDDEN, $response->getStatusCode()); + } + + /** + * @param \Symfony\Component\HttpFoundation\Request $request + */ + protected function assertTitleStartsWith(Request $request, $title) { + $this->assertResponseContains($request, '' . $title); + } + + /** + * @param \Symfony\Component\HttpFoundation\Request $request + * @return \Symfony\Component\HttpFoundation\Response + */ + protected function request(Request $request) { + if (empty($this->kernel)) { + $this->kernel = DrupalTestKernel::createFromRequest($request, $this->classLoader, 'prod'); } - /** - * @param Request $request - */ - protected function assertForbidden(Request $request) - { - $response = $this->request($request); - $this->assertEquals(Response::HTTP_FORBIDDEN, $response->getStatusCode()); - } - - /** - * @param Request $request - */ - protected function assertTitleStartsWith(Request $request, $title) - { - $this->assertResponseContains($request, '<title>'.$title); - } + return $this->kernel->handle($request); + } + + /** + * + */ + protected function setAnonymousAccount() { + $this->setAccount(new AnonymousUserSession()); + } + + /** + * + */ + protected function setAuthenticatedAccount() { + $this->setAccount(new UserSession([ + 'uid' => 2, + 'roles' => ['authenticated'], + ])); + } + + /** + * + */ + protected function setAdministratorAccount() { + $this->setAccount(new UserSession([ + 'uid' => 1, + 'roles' => ['administrator', 'authenticated'], + ])); + } + + /** + * @param \Drupal\Core\Session\AccountInterface $account + */ + protected function setAccount(AccountInterface $account) { + $this->kernel->getContainer()->get('current_user')->setAccount($account); + } - /** - * @param Request $request - * @return Response - */ - protected function request(Request $request) - { - if (empty($this->kernel)) { - $this->kernel = DrupalTestKernel::createFromRequest($request, $this->classLoader, 'prod'); - } - - return $this->kernel->handle($request); - } - - /** - * - */ - protected function setAnonymousAccount() - { - $this->setAccount(new AnonymousUserSession()); - } - - /** - * - */ - protected function setAuthenticatedAccount() - { - $this->setAccount(new UserSession([ - 'uid' => 2, - 'roles' => ['authenticated'] - ])); - } - - /** - * - */ - protected function setAdministratorAccount() - { - $this->setAccount(new UserSession([ - 'uid' => 1, - 'roles' => ['administrator', 'authenticated'] - ])); - } - - /** - * @param AccountInterface $account - */ - protected function setAccount(AccountInterface $account) - { - $this->kernel->getContainer()->get('current_user')->setAccount($account); - } } diff --git a/tests/src/Kernel/TestUserSession.php b/tests/src/Kernel/TestUserSession.php index 947eb18..6b3f903 100644 --- a/tests/src/Kernel/TestUserSession.php +++ b/tests/src/Kernel/TestUserSession.php @@ -4,23 +4,23 @@ use Drupal\Core\Session\UserSession; -class TestUserSession extends UserSession -{ - /** - * @var array - */ - protected $permissions = []; +class TestUserSession extends UserSession { - /** - * {@inheritdoc} - */ - public function hasPermission($permission) - { - // User #1 has all privileges. - if ((int) $this->id() === 1) { - return true; - } + /** + * @var array + */ + protected $permissions = []; - return in_array($permission, $this->permissions); + /** + * {@inheritdoc} + */ + public function hasPermission($permission) { + // User #1 has all privileges. + if ((int) $this->id() === 1) { + return TRUE; } + + return in_array($permission, $this->permissions); + } + } diff --git a/tests/src/Unit/Cache/DrupalCacheTest.php b/tests/src/Unit/Cache/DrupalCacheTest.php index 0b16279..b63d21c 100644 --- a/tests/src/Unit/Cache/DrupalCacheTest.php +++ b/tests/src/Unit/Cache/DrupalCacheTest.php @@ -8,98 +8,90 @@ use Mockery as m; use StdClass; -class DrupalCacheTest extends UnitTestCase -{ - public function testDoFetch() - { - $drupalCache = $this->getDrupalCacheMock(); - $drupalCache->shouldReceive('get')->once()->withArgs(['[foo][1]'])->andReturn($this->getCacheData('bar')); - - $cache = new DrupalCache($drupalCache); - - $this->assertEquals('bar', $cache->fetch('foo')); - } - - public function testDoContains() - { - $drupalCache = $this->getDrupalCacheMock(); - $drupalCache->shouldReceive('get')->once()->withArgs(['[foo][1]'])->andReturn($this->getCacheData('bar')); - $drupalCache->shouldReceive('get')->once()->withArgs(['[bar][1]'])->andReturn(false); - - $cache = new DrupalCache($drupalCache); - $this->assertTrue($cache->contains('foo')); - $this->assertFalse($cache->contains('bar')); - } - - public function testSave() - { - $drupalCache = $this->getDrupalCacheMock(); - $drupalCache->shouldReceive('set')->once()->withArgs(['[foo][1]', 'bar'])->andReturnNull(); - $drupalCache->shouldReceive('set')->once()->withArgs(['[foo][1]', 'bar', m::any()])->andReturnNull(); - - $cache = new DrupalCache($drupalCache); - $this->assertTrue($cache->save('foo', 'bar')); - $this->assertTrue($cache->save('foo', 'bar', 1)); - - m::close(); - } - - public function testDelete() - { - $drupalCache = $this->getDrupalCacheMock(); - $drupalCache->shouldReceive('delete')->once()->withArgs(['[foo][1]'])->andReturnNull(); - - $cache = new DrupalCache($drupalCache); - - $this->assertTrue($cache->delete('foo')); - } - - public function testFlushAll() - { - $drupalCache = $this->getDrupalCacheMock(); - $drupalCache->shouldReceive('deleteAll')->once()->withNoArgs()->andReturnNull(); - - $cache = new DrupalCache($drupalCache); - - $this->assertTrue($cache->flushAll()); - } - - public function testGetStats() - { - $drupalCache = $this->getDrupalCacheMock(); - $cache = new DrupalCache($drupalCache); - - $this->assertNull($cache->getStats()); - } - - /** - * @return CacheBackendInterface - */ - protected function getDrupalCacheMock() - { - $drupalCache = m::mock(CacheBackendInterface::class); - $drupalCache->shouldReceive('get')->withArgs(['DoctrineNamespaceCacheKey[]'])->andReturnNull(); - - return $drupalCache; - } - - /** - * @param $data - * - * @return StdClass - */ - protected function getCacheData($data) - { - $cacheData = new StdClass(); - $cacheData->data = $data; - - return $cacheData; - } - - protected function tearDown() - { - m::close(); - - parent::tearDown(); - } +class DrupalCacheTest extends UnitTestCase { + + public function testDoFetch() { + $drupalCache = $this->getDrupalCacheMock(); + $drupalCache->shouldReceive('get')->once()->withArgs(['[foo][1]'])->andReturn($this->getCacheData('bar')); + + $cache = new DrupalCache($drupalCache); + + $this->assertEquals('bar', $cache->fetch('foo')); + } + + public function testDoContains() { + $drupalCache = $this->getDrupalCacheMock(); + $drupalCache->shouldReceive('get')->once()->withArgs(['[foo][1]'])->andReturn($this->getCacheData('bar')); + $drupalCache->shouldReceive('get')->once()->withArgs(['[bar][1]'])->andReturn(FALSE); + + $cache = new DrupalCache($drupalCache); + $this->assertTrue($cache->contains('foo')); + $this->assertFalse($cache->contains('bar')); + } + + public function testSave() { + $drupalCache = $this->getDrupalCacheMock(); + $drupalCache->shouldReceive('set')->once()->withArgs(['[foo][1]', 'bar'])->andReturnNull(); + $drupalCache->shouldReceive('set')->once()->withArgs(['[foo][1]', 'bar', m::any()])->andReturnNull(); + + $cache = new DrupalCache($drupalCache); + $this->assertTrue($cache->save('foo', 'bar')); + $this->assertTrue($cache->save('foo', 'bar', 1)); + + m::close(); + } + + public function testDelete() { + $drupalCache = $this->getDrupalCacheMock(); + $drupalCache->shouldReceive('delete')->once()->withArgs(['[foo][1]'])->andReturnNull(); + + $cache = new DrupalCache($drupalCache); + + $this->assertTrue($cache->delete('foo')); + } + + public function testFlushAll() { + $drupalCache = $this->getDrupalCacheMock(); + $drupalCache->shouldReceive('deleteAll')->once()->withNoArgs()->andReturnNull(); + + $cache = new DrupalCache($drupalCache); + + $this->assertTrue($cache->flushAll()); + } + + public function testGetStats() { + $drupalCache = $this->getDrupalCacheMock(); + $cache = new DrupalCache($drupalCache); + + $this->assertNull($cache->getStats()); + } + + /** + * @return \Drupal\Core\Cache\CacheBackendInterface + */ + protected function getDrupalCacheMock() { + $drupalCache = m::mock(CacheBackendInterface::class); + $drupalCache->shouldReceive('get')->withArgs(['DoctrineNamespaceCacheKey[]'])->andReturnNull(); + + return $drupalCache; + } + + /** + * @param $data + * + * @return \StdClass + */ + protected function getCacheData($data) { + $cacheData = new StdClass(); + $cacheData->data = $data; + + return $cacheData; + } + + protected function tearDown() { + m::close(); + + parent::tearDown(); + } + } diff --git a/tests/src/Unit/Configuration/CacheTest.php b/tests/src/Unit/Configuration/CacheTest.php index 7f73d74..8b586f2 100644 --- a/tests/src/Unit/Configuration/CacheTest.php +++ b/tests/src/Unit/Configuration/CacheTest.php @@ -5,53 +5,51 @@ use Drupal\controller_annotations\Configuration\Cache; use Drupal\Tests\UnitTestCase; -class CacheTest extends UnitTestCase -{ - public function testProperties() - { - $cache = new Cache([]); +class CacheTest extends UnitTestCase { - $cache->setExpires('tomorrow'); - $this->assertEquals('tomorrow', $cache->getExpires()); + public function testProperties() { + $cache = new Cache([]); - $cache->setMaxAge(60); - $this->assertEquals(60, $cache->getMaxAge()); + $cache->setExpires('tomorrow'); + $this->assertEquals('tomorrow', $cache->getExpires()); - $cache->setSMaxAge(120); - $this->assertEquals(120, $cache->getSMaxAge()); + $cache->setMaxAge(60); + $this->assertEquals(60, $cache->getMaxAge()); - $this->assertFalse($cache->isPublic()); - $this->assertFalse($cache->isPrivate()); + $cache->setSMaxAge(120); + $this->assertEquals(120, $cache->getSMaxAge()); - $cache->setPublic(true); - $this->assertTrue($cache->isPublic()); - $this->assertFalse($cache->isPrivate()); + $this->assertFalse($cache->isPublic()); + $this->assertFalse($cache->isPrivate()); - $cache->setPublic(false); - $this->assertFalse($cache->isPublic()); - $this->assertTrue($cache->isPrivate()); + $cache->setPublic(TRUE); + $this->assertTrue($cache->isPublic()); + $this->assertFalse($cache->isPrivate()); - $cache->setVary('vary'); - $this->assertEquals('vary', $cache->getVary()); + $cache->setPublic(FALSE); + $this->assertFalse($cache->isPublic()); + $this->assertTrue($cache->isPrivate()); - $cache->setETag('foobar'); - $this->assertEquals('foobar', $cache->getETag()); + $cache->setVary('vary'); + $this->assertEquals('vary', $cache->getVary()); - $cache->setLastModified('yesterday'); - $this->assertEquals('yesterday', $cache->getLastModified()); - } + $cache->setETag('foobar'); + $this->assertEquals('foobar', $cache->getETag()); - public function testGetAliasName() - { - $cache = new Cache([]); + $cache->setLastModified('yesterday'); + $this->assertEquals('yesterday', $cache->getLastModified()); + } - $this->assertEquals('cache', $cache->getAliasName()); - } + public function testGetAliasName() { + $cache = new Cache([]); - public function testAllowArray() - { - $cache = new Cache([]); + $this->assertEquals('cache', $cache->getAliasName()); + } + + public function testAllowArray() { + $cache = new Cache([]); + + $this->assertFalse($cache->allowArray()); + } - $this->assertFalse($cache->allowArray()); - } } diff --git a/tests/src/Unit/Configuration/MethodTest.php b/tests/src/Unit/Configuration/MethodTest.php index 8a532fe..6c24253 100644 --- a/tests/src/Unit/Configuration/MethodTest.php +++ b/tests/src/Unit/Configuration/MethodTest.php @@ -7,51 +7,49 @@ use Mockery as m; use Symfony\Component\Routing\Route; -class MethodTest extends UnitTestCase -{ - public function testModifyRouteClass() - { - $route = m::mock(Route::class); - $route->shouldReceive('setMethods')->once()->withArgs([['GET', 'POST']]); +class MethodTest extends UnitTestCase { - $class = m::mock(\ReflectionClass::class); - $method = m::mock(\ReflectionMethod::class); + public function testModifyRouteClass() { + $route = m::mock(Route::class); + $route->shouldReceive('setMethods')->once()->withArgs([['GET', 'POST']]); - $methodConfig = new Method(['methods' => ['GET', 'POST']]); - $this->assertNull($methodConfig->modifyRouteClass($route, $class, $method)); + $class = m::mock(\ReflectionClass::class); + $method = m::mock(\ReflectionMethod::class); - m::close(); - } + $methodConfig = new Method(['methods' => ['GET', 'POST']]); + $this->assertNull($methodConfig->modifyRouteClass($route, $class, $method)); - public function testModifyRouteMethod() - { - $route = m::mock(Route::class); - $route->shouldReceive('setMethods')->once()->withArgs([['GET', 'POST']]); + m::close(); + } - $class = m::mock(\ReflectionClass::class); - $method = m::mock(\ReflectionMethod::class); + public function testModifyRouteMethod() { + $route = m::mock(Route::class); + $route->shouldReceive('setMethods')->once()->withArgs([['GET', 'POST']]); - $methodConfig = new Method(['methods' => ['GET', 'POST']]); - $this->assertNull($methodConfig->modifyRouteMethod($route, $class, $method)); + $class = m::mock(\ReflectionClass::class); + $method = m::mock(\ReflectionMethod::class); - m::close(); - } + $methodConfig = new Method(['methods' => ['GET', 'POST']]); + $this->assertNull($methodConfig->modifyRouteMethod($route, $class, $method)); - public function testModify() - { - $route = m::mock(Route::class); - $route->shouldReceive('setMethods')->once()->withArgs([['GET']]); - $route->shouldReceive('setMethods')->once()->withArgs([['POST']]); + m::close(); + } - $class = m::mock(\ReflectionClass::class); - $method = m::mock(\ReflectionMethod::class); + public function testModify() { + $route = m::mock(Route::class); + $route->shouldReceive('setMethods')->once()->withArgs([['GET']]); + $route->shouldReceive('setMethods')->once()->withArgs([['POST']]); - $methodConfig = new Method(['methods' => ['GET']]); - $this->assertNull($methodConfig->modifyRouteClass($route, $class, $method)); + $class = m::mock(\ReflectionClass::class); + $method = m::mock(\ReflectionMethod::class); - $methodConfig = new Method(['methods' => ['POST']]); - $this->assertNull($methodConfig->modifyRouteMethod($route, $class, $method)); + $methodConfig = new Method(['methods' => ['GET']]); + $this->assertNull($methodConfig->modifyRouteClass($route, $class, $method)); + + $methodConfig = new Method(['methods' => ['POST']]); + $this->assertNull($methodConfig->modifyRouteMethod($route, $class, $method)); + + m::close(); + } - m::close(); - } } diff --git a/tests/src/Unit/Configuration/RouteTest.php b/tests/src/Unit/Configuration/RouteTest.php index 3d22965..aacad01 100644 --- a/tests/src/Unit/Configuration/RouteTest.php +++ b/tests/src/Unit/Configuration/RouteTest.php @@ -7,59 +7,55 @@ use Mockery as m; use Symfony\Component\Routing\Route; -class RouteTest extends UnitTestCase -{ - public function testModifyRouteClass() - { - $route = m::mock(Route::class); - $route->shouldReceive('setOption')->once()->withArgs(['_admin_route', true]); +class RouteTest extends UnitTestCase { - $class = m::mock(\ReflectionClass::class); - $method = m::mock(\ReflectionMethod::class); + public function testModifyRouteClass() { + $route = m::mock(Route::class); + $route->shouldReceive('setOption')->once()->withArgs(['_admin_route', TRUE]); - $routeConfig = new RouteConfiguration(['admin' => true]); - $this->assertNull($routeConfig->modifyRouteClass($route, $class, $method)); + $class = m::mock(\ReflectionClass::class); + $method = m::mock(\ReflectionMethod::class); - m::close(); - } + $routeConfig = new RouteConfiguration(['admin' => TRUE]); + $this->assertNull($routeConfig->modifyRouteClass($route, $class, $method)); - public function testModifyMethodClass() - { - $route = m::mock(Route::class); + m::close(); + } - $class = m::mock(\ReflectionClass::class); - $method = m::mock(\ReflectionMethod::class); + public function testModifyMethodClass() { + $route = m::mock(Route::class); - $routeConfig = new RouteConfiguration([]); - $this->assertNull($routeConfig->modifyRouteMethod($route, $class, $method)); + $class = m::mock(\ReflectionClass::class); + $method = m::mock(\ReflectionMethod::class); - m::close(); - } + $routeConfig = new RouteConfiguration([]); + $this->assertNull($routeConfig->modifyRouteMethod($route, $class, $method)); - public function testServiceNotAllowedOnMethodLevel() - { - $this->setExpectedException(\LogicException::class); + m::close(); + } - $route = m::mock(Route::class); + public function testServiceNotAllowedOnMethodLevel() { + $this->setExpectedException(\LogicException::class); - $class = m::mock(\ReflectionClass::class); - $method = m::mock(\ReflectionMethod::class); + $route = m::mock(Route::class); - $routeConfig = new RouteConfiguration(['service' => 'foo']); - $this->assertNull($routeConfig->modifyRouteMethod($route, $class, $method)); + $class = m::mock(\ReflectionClass::class); + $method = m::mock(\ReflectionMethod::class); - m::close(); - } + $routeConfig = new RouteConfiguration(['service' => 'foo']); + $this->assertNull($routeConfig->modifyRouteMethod($route, $class, $method)); - public function testAllowArray() - { - $routeConfig = new RouteConfiguration([]); - $this->assertTrue($routeConfig->allowArray()); - } + m::close(); + } + + public function testAllowArray() { + $routeConfig = new RouteConfiguration([]); + $this->assertTrue($routeConfig->allowArray()); + } + + public function testUnknownProperty() { + $this->setExpectedException(\BadMethodCallException::class); + new RouteConfiguration(['foo' => 'bar']); + } - public function testUnknownProperty() - { - $this->setExpectedException(\BadMethodCallException::class); - new RouteConfiguration(['foo' => 'bar']); - } } diff --git a/tests/src/Unit/Configuration/SecurityTest.php b/tests/src/Unit/Configuration/SecurityTest.php index 74235d1..e1217c5 100644 --- a/tests/src/Unit/Configuration/SecurityTest.php +++ b/tests/src/Unit/Configuration/SecurityTest.php @@ -7,49 +7,48 @@ use Mockery as m; use Symfony\Component\Routing\Route; -class SecurityTest extends UnitTestCase -{ - public function testModifyRouteMethod() - { - $route = m::mock(Route::class); - $route->shouldReceive('setRequirement')->once()->withArgs(['_access', true]); - $route->shouldReceive('setRequirement')->once()->withArgs(['_permission', 'permission']); - $route->shouldReceive('setRequirement')->once()->withArgs(['_role', 'role']); - $route->shouldReceive('setRequirement')->once()->withArgs(['_entity_access', 'entity']); - $route->shouldReceive('setRequirement')->once()->withArgs(['_csrf_token', true]); - $route->shouldReceive('setRequirement')->once()->withArgs(['_custom_access', 'foo::custom']); - - $class = m::mock(\ReflectionClass::class); - $method = m::mock(\ReflectionMethod::class); - - $security = new Security([ - 'access' => true, - 'permission' => 'permission', - 'role' => 'role', - 'entity' => 'entity', - 'csrf' => true, - 'custom' => 'foo::custom' - ]); - $this->assertNull($security->modifyRouteMethod($route, $class, $method)); - - m::close(); - } - - public function testModifyRouteMethodInlineAccess() - { - $route = m::mock(Route::class); - $route->shouldReceive('setRequirement')->once()->withArgs(['_custom_access', 'foo::custom']); - - $class = m::mock(\ReflectionClass::class); - $class->shouldReceive('hasMethod')->andReturn('custom'); - $class->shouldReceive('getName')->andReturn('foo'); - $method = m::mock(\ReflectionMethod::class); - - $security = new Security([ - 'custom' => 'custom' - ]); - $this->assertNull($security->modifyRouteMethod($route, $class, $method)); - - m::close(); - } +class SecurityTest extends UnitTestCase { + + public function testModifyRouteMethod() { + $route = m::mock(Route::class); + $route->shouldReceive('setRequirement')->once()->withArgs(['_access', TRUE]); + $route->shouldReceive('setRequirement')->once()->withArgs(['_permission', 'permission']); + $route->shouldReceive('setRequirement')->once()->withArgs(['_role', 'role']); + $route->shouldReceive('setRequirement')->once()->withArgs(['_entity_access', 'entity']); + $route->shouldReceive('setRequirement')->once()->withArgs(['_csrf_token', TRUE]); + $route->shouldReceive('setRequirement')->once()->withArgs(['_custom_access', 'foo::custom']); + + $class = m::mock(\ReflectionClass::class); + $method = m::mock(\ReflectionMethod::class); + + $security = new Security([ + 'access' => TRUE, + 'permission' => 'permission', + 'role' => 'role', + 'entity' => 'entity', + 'csrf' => TRUE, + 'custom' => 'foo::custom', + ]); + $this->assertNull($security->modifyRouteMethod($route, $class, $method)); + + m::close(); + } + + public function testModifyRouteMethodInlineAccess() { + $route = m::mock(Route::class); + $route->shouldReceive('setRequirement')->once()->withArgs(['_custom_access', 'foo::custom']); + + $class = m::mock(\ReflectionClass::class); + $class->shouldReceive('hasMethod')->andReturn('custom'); + $class->shouldReceive('getName')->andReturn('foo'); + $method = m::mock(\ReflectionMethod::class); + + $security = new Security([ + 'custom' => 'custom', + ]); + $this->assertNull($security->modifyRouteMethod($route, $class, $method)); + + m::close(); + } + } diff --git a/tests/src/Unit/Configuration/TitleTest.php b/tests/src/Unit/Configuration/TitleTest.php index 11f0e7e..8fb9689 100644 --- a/tests/src/Unit/Configuration/TitleTest.php +++ b/tests/src/Unit/Configuration/TitleTest.php @@ -7,51 +7,49 @@ use Mockery as m; use Symfony\Component\Routing\Route; -class TitleTest extends UnitTestCase -{ - public function testModifyRouteMethod() - { - $route = m::mock(Route::class); - $route->shouldReceive('setDefault')->once()->withArgs(['_title', 'Hello World']); - $route->shouldReceive('setDefault')->once()->withArgs(['_title_arguments', ['arguments' => true]]); - $route->shouldReceive('setDefault')->once()->withArgs(['_title_context', ['context' => true]]); - $route->shouldReceive('setDefault')->once()->withArgs(['_title_callback', 'foo::callback']); - - $class = m::mock(\ReflectionClass::class); - $method = m::mock(\ReflectionMethod::class); - - $security = new Title([ - 'value' => 'Hello World', - 'arguments' => ['arguments' => true], - 'context' => ['context' => true], - 'callback' => 'foo::callback' - ]); - $this->assertNull($security->modifyRouteMethod($route, $class, $method)); - - m::close(); - } - - public function testModifyRouteMethodInlineAccess() - { - $route = m::mock(Route::class); - $route->shouldReceive('setDefault')->once()->withArgs(['_title_callback', 'foo::callback']); - - $class = m::mock(\ReflectionClass::class); - $class->shouldReceive('hasMethod')->andReturn('callback'); - $class->shouldReceive('getName')->andReturn('foo'); - $method = m::mock(\ReflectionMethod::class); - - $security = new Title([ - 'callback' => 'callback' - ]); - $this->assertNull($security->modifyRouteClass($route, $class, $method)); - - m::close(); - } - - public function testUnknownProperty() - { - $this->setExpectedException(\RuntimeException::class); - new Title(['foo' => 'bar']); - } +class TitleTest extends UnitTestCase { + + public function testModifyRouteMethod() { + $route = m::mock(Route::class); + $route->shouldReceive('setDefault')->once()->withArgs(['_title', 'Hello World']); + $route->shouldReceive('setDefault')->once()->withArgs(['_title_arguments', ['arguments' => TRUE]]); + $route->shouldReceive('setDefault')->once()->withArgs(['_title_context', ['context' => TRUE]]); + $route->shouldReceive('setDefault')->once()->withArgs(['_title_callback', 'foo::callback']); + + $class = m::mock(\ReflectionClass::class); + $method = m::mock(\ReflectionMethod::class); + + $security = new Title([ + 'value' => 'Hello World', + 'arguments' => ['arguments' => TRUE], + 'context' => ['context' => TRUE], + 'callback' => 'foo::callback', + ]); + $this->assertNull($security->modifyRouteMethod($route, $class, $method)); + + m::close(); + } + + public function testModifyRouteMethodInlineAccess() { + $route = m::mock(Route::class); + $route->shouldReceive('setDefault')->once()->withArgs(['_title_callback', 'foo::callback']); + + $class = m::mock(\ReflectionClass::class); + $class->shouldReceive('hasMethod')->andReturn('callback'); + $class->shouldReceive('getName')->andReturn('foo'); + $method = m::mock(\ReflectionMethod::class); + + $security = new Title([ + 'callback' => 'callback', + ]); + $this->assertNull($security->modifyRouteClass($route, $class, $method)); + + m::close(); + } + + public function testUnknownProperty() { + $this->setExpectedException(\RuntimeException::class); + new Title(['foo' => 'bar']); + } + } diff --git a/tests/src/Unit/EventSubscriber/ControllerEventSubscriberTest.php b/tests/src/Unit/EventSubscriber/ControllerEventSubscriberTest.php index ec15ce1..dc36e43 100644 --- a/tests/src/Unit/EventSubscriber/ControllerEventSubscriberTest.php +++ b/tests/src/Unit/EventSubscriber/ControllerEventSubscriberTest.php @@ -14,111 +14,106 @@ /** * @group controller_annotations */ -class ControllerEventSubscriberTest extends UnitTestCase -{ - public function testOnKernelController() - { - $reader = m::mock(Reader::class); - - $eventSubscriber = new ControllerEventSubscriber($reader); - - $event = m::mock(FilterControllerEvent::class); - $event->shouldReceive('getController')->once()->andReturn(null); - - $this->assertNull($eventSubscriber->onKernelController($event)); - } - - public function testControllerInvoke() - { - $reader = m::mock(Reader::class); - $reader->shouldReceive('getClassAnnotations')->andReturn([]); - $reader->shouldReceive('getMethodAnnotations')->andReturn([]); - - $eventSubscriber = new ControllerEventSubscriber($reader); - - $event = m::mock(FilterControllerEvent::class); - $event->shouldReceive('getController')->once()->andReturn(new ControllerInvokableController); - $event->shouldReceive('getRequest')->once()->andReturn(new Request); - - $this->assertNull($eventSubscriber->onKernelController($event)); - } - - public function testMultipleConfigurations() - { - $configuration = m::mock(ConfigurationInterface::class); - $configuration->shouldReceive('allowArray')->andReturn(true); - $configuration->shouldReceive('getAliasName')->andReturn('foo'); - - $reader = m::mock(Reader::class); - $reader->shouldReceive('getClassAnnotations')->andReturn([ - $configuration, - $configuration - ]); - $reader->shouldReceive('getMethodAnnotations')->andReturn([]); - - $eventSubscriber = new ControllerEventSubscriber($reader); - - $event = m::mock(FilterControllerEvent::class); - $event->shouldReceive('getController')->once()->andReturn(new ControllerInvokableController); - $event->shouldReceive('getRequest')->once()->andReturn(new Request); - - $this->assertNull($eventSubscriber->onKernelController($event)); - } - - public function testMergeConfigurations() - { - $classConfigurations = [ - 'foo' => 'bar' - ]; - $methodConfigurations = [ - 'foo' => 'bar' - ]; - - $reader = m::mock(Reader::class); - $method = Helper::getProtectedMethod(ControllerEventSubscriber::class, 'mergeConfigurations'); - $eventSubscriber = new ControllerEventSubscriber($reader); - $result = $method->invokeArgs($eventSubscriber, [$classConfigurations, $methodConfigurations]); - $this->assertEquals(['foo' => 'bar'], $result); - } - - public function testMergeConfigurationsArray() - { - $classConfigurations = [ - 'foo' => ['bar'] - ]; - $methodConfigurations = [ - 'foo' => ['baz'] - ]; - - $reader = m::mock(Reader::class); - $method = Helper::getProtectedMethod(ControllerEventSubscriber::class, 'mergeConfigurations'); - $eventSubscriber = new ControllerEventSubscriber($reader); - $result = $method->invokeArgs($eventSubscriber, [$classConfigurations, $methodConfigurations]); - - $this->assertEquals(['foo' => ['bar', 'baz']], $result); - } - - public function testMergeConfigurationsMismatch() - { - $this->setExpectedException(\UnexpectedValueException::class); - - $classConfigurations = [ - 'foo' => ['bar'] - ]; - $methodConfigurations = [ - 'foo' => 'bar' - ]; - - $reader = m::mock(Reader::class); - $method = Helper::getProtectedMethod(ControllerEventSubscriber::class, 'mergeConfigurations'); - $eventSubscriber = new ControllerEventSubscriber($reader); - $method->invokeArgs($eventSubscriber, [$classConfigurations, $methodConfigurations]); - } +class ControllerEventSubscriberTest extends UnitTestCase { + + public function testOnKernelController() { + $reader = m::mock(Reader::class); + + $eventSubscriber = new ControllerEventSubscriber($reader); + + $event = m::mock(FilterControllerEvent::class); + $event->shouldReceive('getController')->once()->andReturn(NULL); + + $this->assertNull($eventSubscriber->onKernelController($event)); + } + + public function testControllerInvoke() { + $reader = m::mock(Reader::class); + $reader->shouldReceive('getClassAnnotations')->andReturn([]); + $reader->shouldReceive('getMethodAnnotations')->andReturn([]); + + $eventSubscriber = new ControllerEventSubscriber($reader); + + $event = m::mock(FilterControllerEvent::class); + $event->shouldReceive('getController')->once()->andReturn(new ControllerInvokableController()); + $event->shouldReceive('getRequest')->once()->andReturn(new Request()); + + $this->assertNull($eventSubscriber->onKernelController($event)); + } + + public function testMultipleConfigurations() { + $configuration = m::mock(ConfigurationInterface::class); + $configuration->shouldReceive('allowArray')->andReturn(TRUE); + $configuration->shouldReceive('getAliasName')->andReturn('foo'); + + $reader = m::mock(Reader::class); + $reader->shouldReceive('getClassAnnotations')->andReturn([ + $configuration, + $configuration, + ]); + $reader->shouldReceive('getMethodAnnotations')->andReturn([]); + + $eventSubscriber = new ControllerEventSubscriber($reader); + + $event = m::mock(FilterControllerEvent::class); + $event->shouldReceive('getController')->once()->andReturn(new ControllerInvokableController()); + $event->shouldReceive('getRequest')->once()->andReturn(new Request()); + + $this->assertNull($eventSubscriber->onKernelController($event)); + } + + public function testMergeConfigurations() { + $classConfigurations = [ + 'foo' => 'bar', + ]; + $methodConfigurations = [ + 'foo' => 'bar', + ]; + + $reader = m::mock(Reader::class); + $method = Helper::getProtectedMethod(ControllerEventSubscriber::class, 'mergeConfigurations'); + $eventSubscriber = new ControllerEventSubscriber($reader); + $result = $method->invokeArgs($eventSubscriber, [$classConfigurations, $methodConfigurations]); + $this->assertEquals(['foo' => 'bar'], $result); + } + + public function testMergeConfigurationsArray() { + $classConfigurations = [ + 'foo' => ['bar'], + ]; + $methodConfigurations = [ + 'foo' => ['baz'], + ]; + + $reader = m::mock(Reader::class); + $method = Helper::getProtectedMethod(ControllerEventSubscriber::class, 'mergeConfigurations'); + $eventSubscriber = new ControllerEventSubscriber($reader); + $result = $method->invokeArgs($eventSubscriber, [$classConfigurations, $methodConfigurations]); + + $this->assertEquals(['foo' => ['bar', 'baz']], $result); + } + + public function testMergeConfigurationsMismatch() { + $this->setExpectedException(\UnexpectedValueException::class); + + $classConfigurations = [ + 'foo' => ['bar'], + ]; + $methodConfigurations = [ + 'foo' => 'bar', + ]; + + $reader = m::mock(Reader::class); + $method = Helper::getProtectedMethod(ControllerEventSubscriber::class, 'mergeConfigurations'); + $eventSubscriber = new ControllerEventSubscriber($reader); + $method->invokeArgs($eventSubscriber, [$classConfigurations, $methodConfigurations]); + } + } -class ControllerInvokableController -{ - public function __invoke() - { - } +class ControllerInvokableController { + + public function __invoke() { + } + } diff --git a/tests/src/Unit/EventSubscriber/HttpCacheListenerTest.php b/tests/src/Unit/EventSubscriber/HttpCacheListenerTest.php index 7e34e29..2d48502 100644 --- a/tests/src/Unit/EventSubscriber/HttpCacheListenerTest.php +++ b/tests/src/Unit/EventSubscriber/HttpCacheListenerTest.php @@ -10,251 +10,230 @@ use Symfony\Component\HttpKernel\Event\FilterControllerEvent; use Symfony\Component\HttpKernel\Event\FilterResponseEvent; -class HttpCacheListenerTest extends UnitTestCase -{ - public function setUp() - { - $this->listener = new HttpCacheEventSubscriber(); - $this->response = new Response(); - $this->cache = new Cache(array()); - $this->request = $this->createRequest($this->cache); - $this->event = $this->createEventMock($this->request, $this->response); - } - - public function testWontReassignResponseWhenResponseIsUnsuccessful() - { - $this->event - ->expects($this->never()) - ->method('setResponse') - ; - - $this->response->setStatusCode(500); - - $this->assertInternalType('null', $this->listener->onKernelResponse($this->event)); - } - - public function testWontReassignResponseWhenNoConfigurationIsPresent() - { - $this->event - ->expects($this->never()) - ->method('setResponse') - ; - - $this->request->attributes->remove('_cache'); - - $this->assertInternalType('null', $this->listener->onKernelResponse($this->event)); - } - - public function testResponseIsPublicIfConfigurationIsPublicTrue() - { - $request = $this->createRequest(new Cache(array( - 'public' => true, - ))); - - $this->listener->onKernelResponse($this->createEventMock($request, $this->response)); - - $this->assertTrue($this->response->headers->hasCacheControlDirective('public')); - $this->assertFalse($this->response->headers->hasCacheControlDirective('private')); - } - - public function testResponseIsPrivateIfConfigurationIsPublicFalse() - { - $request = $this->createRequest(new Cache(array( - 'public' => false, - ))); - - $this->listener->onKernelResponse($this->createEventMock($request, $this->response)); - - $this->assertFalse($this->response->headers->hasCacheControlDirective('public')); - $this->assertTrue($this->response->headers->hasCacheControlDirective('private')); - } - - public function testResponseVary() - { - $vary = array('foobar'); - $request = $this->createRequest(new Cache(array('vary' => $vary))); - - $this->listener->onKernelResponse($this->createEventMock($request, $this->response)); - $this->assertTrue($this->response->hasVary()); - $result = $this->response->getVary(); - $this->assertEquals($vary, $result); - } - - public function testResponseVaryWhenVaryNotSet() - { - $request = $this->createRequest(new Cache(array())); - $vary = array('foobar'); - $this->response->setVary($vary); - - $this->listener->onKernelResponse($this->createEventMock($request, $this->response)); - $this->assertTrue($this->response->hasVary()); - $result = $this->response->getVary(); - $this->assertFalse(empty($result), 'Existing vary headers should not be removed'); - $this->assertEquals($vary, $result, 'Vary header should not be changed'); - } - - public function testResponseIsPrivateIfConfigurationIsPublicNotSet() - { - $request = $this->createRequest(new Cache(array())); - - $this->listener->onKernelResponse($this->createEventMock($request, $this->response)); - - $this->assertFalse($this->response->headers->hasCacheControlDirective('public')); - } - - public function testConfigurationAttributesAreSetOnResponse() - { - $this->assertInternalType('null', $this->response->getMaxAge()); - $this->assertInternalType('null', $this->response->getExpires()); - $this->assertFalse($this->response->headers->hasCacheControlDirective('s-maxage')); - - $this->request->attributes->set('_cache', new Cache(array( - 'expires' => 'tomorrow', - 'smaxage' => '15', - 'maxage' => '15', - ))); - - $this->listener->onKernelResponse($this->event); - - $this->assertEquals('15', $this->response->getMaxAge()); - $this->assertEquals('15', $this->response->headers->getCacheControlDirective('s-maxage')); - $this->assertInstanceOf('DateTime', $this->response->getExpires()); - } - - public function testCacheMaxAgeSupportsStrtotimeFormat() - { - $this->request->attributes->set('_cache', new Cache(array( - 'smaxage' => '1 day', - 'maxage' => '1 day', - ))); - - $this->listener->onKernelResponse($this->event); - - $this->assertEquals(60 * 60 * 24, $this->response->headers->getCacheControlDirective('s-maxage')); - $this->assertEquals(60 * 60 * 24, $this->response->getMaxAge()); - } - - public function testLastModifiedNotModifiedResponse() - { - $request = $this->createRequest(new Cache(array('lastModified' => 'test.getDate()'))); - $request->attributes->set('test', new TestEntity()); - $request->headers->add(array('If-Modified-Since' => 'Fri, 23 Aug 2013 00:00:00 GMT')); - - $listener = new HttpCacheEventSubscriber(); - $controllerEvent = new FilterControllerEvent($this->getKernel(), function () { - return new Response(500); - }, $request, null); - - $listener->onKernelController($controllerEvent); - $response = call_user_func($controllerEvent->getController()); - - $this->assertEquals(304, $response->getStatusCode()); - } - - public function testLastModifiedHeader() - { - $request = $this->createRequest(new Cache(array('lastModified' => 'test.getDate()'))); - $request->attributes->set('test', new TestEntity()); - $response = new Response(); - - $listener = new HttpCacheEventSubscriber(); - $controllerEvent = new FilterControllerEvent($this->getKernel(), function () { - return new Response(); - }, $request, null); - $listener->onKernelController($controllerEvent); - - $responseEvent = new FilterResponseEvent($this->getKernel(), $request, null, call_user_func($controllerEvent->getController())); - $listener->onKernelResponse($responseEvent); - - $response = $responseEvent->getResponse(); - - $this->assertEquals(200, $response->getStatusCode()); - $this->assertTrue($response->headers->has('Last-Modified')); - $this->assertEquals('Fri, 23 Aug 2013 00:00:00 GMT', $response->headers->get('Last-Modified')); - } - - public function testETagNotModifiedResponse() - { - $request = $this->createRequest(new Cache(array('etag' => 'test.getId()'))); - $request->attributes->set('test', $entity = new TestEntity()); - $request->headers->add(array('If-None-Match' => sprintf('"%s"', hash('sha256', $entity->getId())))); - - $listener = new HttpCacheEventSubscriber(); - $controllerEvent = new FilterControllerEvent($this->getKernel(), function () { - return new Response(500); - }, $request, null); - - $listener->onKernelController($controllerEvent); - $response = call_user_func($controllerEvent->getController()); - - $this->assertEquals(304, $response->getStatusCode()); - } - - public function testETagHeader() - { - $request = $this->createRequest(new Cache(array('ETag' => 'test.getId()'))); - $request->attributes->set('test', $entity = new TestEntity()); - $response = new Response(); - - $listener = new HttpCacheEventSubscriber(); - $controllerEvent = new FilterControllerEvent($this->getKernel(), function () { - return new Response(); - }, $request, null); - $listener->onKernelController($controllerEvent); - - $responseEvent = new FilterResponseEvent($this->getKernel(), $request, null, call_user_func($controllerEvent->getController())); - $listener->onKernelResponse($responseEvent); - - $response = $responseEvent->getResponse(); - - $this->assertEquals(200, $response->getStatusCode()); - $this->assertTrue($response->headers->has('ETag')); - $this->assertContains(hash('sha256', $entity->getId()), $response->headers->get('ETag')); - } - - private function createRequest(Cache $cache = null) - { - return new Request(array(), array(), array( - '_cache' => $cache, - )); - } - - private function createEventMock(Request $request, Response $response) - { - $event = $this - ->getMockBuilder('Symfony\Component\HttpKernel\Event\FilterResponseEvent') - ->disableOriginalConstructor() - ->getMock(); - $event - ->expects($this->any()) - ->method('getRequest') - ->will($this->returnValue($request)) - ; - - $event - ->expects($this->any()) - ->method('getResponse') - ->will($this->returnValue($response)) - ; - - return $event; - } - - private function getKernel() - { - return $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(); - } +class HttpCacheListenerTest extends UnitTestCase { + + public function setUp() { + $this->listener = new HttpCacheEventSubscriber(); + $this->response = new Response(); + $this->cache = new Cache([]); + $this->request = $this->createRequest($this->cache); + $this->event = $this->createEventMock($this->request, $this->response); + } + + public function testWontReassignResponseWhenResponseIsUnsuccessful() { + $this->event + ->expects($this->never()) + ->method('setResponse'); + + $this->response->setStatusCode(500); + + $this->assertInternalType('null', $this->listener->onKernelResponse($this->event)); + } + + public function testWontReassignResponseWhenNoConfigurationIsPresent() { + $this->event + ->expects($this->never()) + ->method('setResponse'); + + $this->request->attributes->remove('_cache'); + + $this->assertInternalType('null', $this->listener->onKernelResponse($this->event)); + } + + public function testResponseIsPublicIfConfigurationIsPublicTrue() { + $request = $this->createRequest(new Cache([ + 'public' => TRUE, + ])); + + $this->listener->onKernelResponse($this->createEventMock($request, $this->response)); + + $this->assertTrue($this->response->headers->hasCacheControlDirective('public')); + $this->assertFalse($this->response->headers->hasCacheControlDirective('private')); + } + + public function testResponseIsPrivateIfConfigurationIsPublicFalse() { + $request = $this->createRequest(new Cache([ + 'public' => FALSE, + ])); + + $this->listener->onKernelResponse($this->createEventMock($request, $this->response)); + + $this->assertFalse($this->response->headers->hasCacheControlDirective('public')); + $this->assertTrue($this->response->headers->hasCacheControlDirective('private')); + } + + public function testResponseVary() { + $vary = ['foobar']; + $request = $this->createRequest(new Cache(['vary' => $vary])); + + $this->listener->onKernelResponse($this->createEventMock($request, $this->response)); + $this->assertTrue($this->response->hasVary()); + $result = $this->response->getVary(); + $this->assertEquals($vary, $result); + } + + public function testResponseVaryWhenVaryNotSet() { + $request = $this->createRequest(new Cache([])); + $vary = ['foobar']; + $this->response->setVary($vary); + + $this->listener->onKernelResponse($this->createEventMock($request, $this->response)); + $this->assertTrue($this->response->hasVary()); + $result = $this->response->getVary(); + $this->assertFalse(empty($result), 'Existing vary headers should not be removed'); + $this->assertEquals($vary, $result, 'Vary header should not be changed'); + } + + public function testResponseIsPrivateIfConfigurationIsPublicNotSet() { + $request = $this->createRequest(new Cache([])); + + $this->listener->onKernelResponse($this->createEventMock($request, $this->response)); + + $this->assertFalse($this->response->headers->hasCacheControlDirective('public')); + } + + public function testConfigurationAttributesAreSetOnResponse() { + $this->assertInternalType('null', $this->response->getMaxAge()); + $this->assertInternalType('null', $this->response->getExpires()); + $this->assertFalse($this->response->headers->hasCacheControlDirective('s-maxage')); + + $this->request->attributes->set('_cache', new Cache([ + 'expires' => 'tomorrow', + 'smaxage' => '15', + 'maxage' => '15', + ])); + + $this->listener->onKernelResponse($this->event); + + $this->assertEquals('15', $this->response->getMaxAge()); + $this->assertEquals('15', $this->response->headers->getCacheControlDirective('s-maxage')); + $this->assertInstanceOf('DateTime', $this->response->getExpires()); + } + + public function testCacheMaxAgeSupportsStrtotimeFormat() { + $this->request->attributes->set('_cache', new Cache([ + 'smaxage' => '1 day', + 'maxage' => '1 day', + ])); + + $this->listener->onKernelResponse($this->event); + + $this->assertEquals(60 * 60 * 24, $this->response->headers->getCacheControlDirective('s-maxage')); + $this->assertEquals(60 * 60 * 24, $this->response->getMaxAge()); + } + + public function testLastModifiedNotModifiedResponse() { + $request = $this->createRequest(new Cache(['lastModified' => 'test.getDate()'])); + $request->attributes->set('test', new TestEntity()); + $request->headers->add(['If-Modified-Since' => 'Fri, 23 Aug 2013 00:00:00 GMT']); + + $listener = new HttpCacheEventSubscriber(); + $controllerEvent = new FilterControllerEvent($this->getKernel(), function () { + return new Response(500); + }, $request, NULL); + + $listener->onKernelController($controllerEvent); + $response = call_user_func($controllerEvent->getController()); + + $this->assertEquals(304, $response->getStatusCode()); + } + + public function testLastModifiedHeader() { + $request = $this->createRequest(new Cache(['lastModified' => 'test.getDate()'])); + $request->attributes->set('test', new TestEntity()); + $response = new Response(); + + $listener = new HttpCacheEventSubscriber(); + $controllerEvent = new FilterControllerEvent($this->getKernel(), function () { + return new Response(); + }, $request, NULL); + $listener->onKernelController($controllerEvent); + + $responseEvent = new FilterResponseEvent($this->getKernel(), $request, NULL, call_user_func($controllerEvent->getController())); + $listener->onKernelResponse($responseEvent); + + $response = $responseEvent->getResponse(); + + $this->assertEquals(200, $response->getStatusCode()); + $this->assertTrue($response->headers->has('Last-Modified')); + $this->assertEquals('Fri, 23 Aug 2013 00:00:00 GMT', $response->headers->get('Last-Modified')); + } + + public function testETagNotModifiedResponse() { + $request = $this->createRequest(new Cache(['etag' => 'test.getId()'])); + $request->attributes->set('test', $entity = new TestEntity()); + $request->headers->add(['If-None-Match' => sprintf('"%s"', hash('sha256', $entity->getId()))]); + + $listener = new HttpCacheEventSubscriber(); + $controllerEvent = new FilterControllerEvent($this->getKernel(), function () { + return new Response(500); + }, $request, NULL); + + $listener->onKernelController($controllerEvent); + $response = call_user_func($controllerEvent->getController()); + + $this->assertEquals(304, $response->getStatusCode()); + } + + public function testETagHeader() { + $request = $this->createRequest(new Cache(['ETag' => 'test.getId()'])); + $request->attributes->set('test', $entity = new TestEntity()); + $response = new Response(); + + $listener = new HttpCacheEventSubscriber(); + $controllerEvent = new FilterControllerEvent($this->getKernel(), function () { + return new Response(); + }, $request, NULL); + $listener->onKernelController($controllerEvent); + + $responseEvent = new FilterResponseEvent($this->getKernel(), $request, NULL, call_user_func($controllerEvent->getController())); + $listener->onKernelResponse($responseEvent); + + $response = $responseEvent->getResponse(); + + $this->assertEquals(200, $response->getStatusCode()); + $this->assertTrue($response->headers->has('ETag')); + $this->assertContains(hash('sha256', $entity->getId()), $response->headers->get('ETag')); + } + + private function createRequest(Cache $cache = NULL) { + return new Request([], [], [ + '_cache' => $cache, + ]); + } + + private function createEventMock(Request $request, Response $response) { + $event = $this + ->getMockBuilder('Symfony\Component\HttpKernel\Event\FilterResponseEvent') + ->disableOriginalConstructor() + ->getMock(); + $event + ->expects($this->any()) + ->method('getRequest') + ->will($this->returnValue($request)); + + $event + ->expects($this->any()) + ->method('getResponse') + ->will($this->returnValue($response)); + + return $event; + } + + private function getKernel() { + return $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(); + } + } -class TestEntity -{ - public function getDate() - { - return new \DateTime('Fri, 23 Aug 2013 00:00:00 GMT'); - } - - public function getId() - { - return '12345'; - } +class TestEntity { + + public function getDate() { + return new \DateTime('Fri, 23 Aug 2013 00:00:00 GMT'); + } + + public function getId() { + return '12345'; + } + } diff --git a/tests/src/Unit/EventSubscriber/ParamConverterEventSubscriberTest.php b/tests/src/Unit/EventSubscriber/ParamConverterEventSubscriberTest.php index 82b7ffa..320f337 100644 --- a/tests/src/Unit/EventSubscriber/ParamConverterEventSubscriberTest.php +++ b/tests/src/Unit/EventSubscriber/ParamConverterEventSubscriberTest.php @@ -12,198 +12,185 @@ use Symfony\Component\HttpKernel\HttpKernelInterface; use Mockery as m; -class ParamConverterEventSubscriberTest extends UnitTestCase -{ - - /** - * @dataProvider getControllerWithNoArgsFixtures - */ - public function testRequestIsSkipped($controllerCallable) - { - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); - $request = new Request(); - - $eventSubscriber = new ParamConverterEventSubscriber( - $this->getParamConverterManager($request, []) - ); - $event = new FilterControllerEvent( - $kernel, - $controllerCallable, - $request, - null - ); - - $eventSubscriber->onKernelController($event); - } - - public function getControllerWithNoArgsFixtures() - { - return [ - [[new ParamConverterTestController(), 'noArgAction']], - [new ParamConverterInvokableNoArgController()], - ]; - } - - /** - * @dataProvider getControllerWithArgsFixtures - */ - public function testAutoConvert($controllerCallable) - { - $kernel = $this->getMockBuilder( - HttpKernelInterface::class - )->getMock(); - $request = new Request([], [], ['date' => '2014-03-14 09:00:00']); - - $converter = new ParamConverter( - ['name' => 'date', 'class' => 'DateTime'] - ); - - $eventSubscriber = new ParamConverterEventSubscriber( - $this->getParamConverterManager($request, ['date' => $converter]) - ); - $event = new FilterControllerEvent( - $kernel, - $controllerCallable, - $request, - null - ); - - $eventSubscriber->onKernelController($event); - } - - /** - * @dataProvider settingOptionalParamProvider - * @requires PHP 7.1 - */ - public function testSettingOptionalParam($function, $isOptional) - { - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); - $request = new Request(); - - $converter = new ParamConverter( - ['name' => 'param', 'class' => 'DateTime'] - ); - $converter->setIsOptional($isOptional); - - $eventSubscriber = new ParamConverterEventSubscriber( - $this->getParamConverterManager($request, ['param' => $converter]), - true - ); - $event = new FilterControllerEvent( - $kernel, - [ - new FooControllerNullableParameter(), - $function, - ], - $request, - null - ); - - $eventSubscriber->onKernelController($event); - } - - public function settingOptionalParamProvider() - { - return [ - ['requiredParamAction', false], - ['defaultParamAction', true], - ['nullableParamAction', true], - ]; - } - - /** - * @dataProvider getControllerWithArgsFixtures - */ - public function testNoAutoConvert($controllerCallable) - { - $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); - $request = new Request([], [], ['date' => '2014-03-14 09:00:00']); - - $eventSubscriber = new ParamConverterEventSubscriber( - $this->getParamConverterManager($request, []), - false - ); - $event = new FilterControllerEvent( - $kernel, - $controllerCallable, - $request, - null - ); - - $eventSubscriber->onKernelController($event); - } - - public function getControllerWithArgsFixtures() - { - return [ - [[new ParamConverterTestController(), 'dateAction']], - [new ParamConverterInvokableController()], - ]; - } - - protected function getParamConverterManager(Request $request, $configurations) - { - $manager = $this->getMockBuilder(ParamConverterManager::class)->getMock(); - $manager - ->expects($this->once()) - ->method('apply') - ->with($this->equalTo($request), $this->equalTo($configurations)); - - return $manager; - } - - public function testPredefinedConfigurations() - { - $configuration = m::mock(\stdClass::class); - $configuration->shouldReceive('getName')->andReturn('foo'); - - $configurations = [$configuration]; - - $kernel = m::mock(HttpKernelInterface::class); - $request = new Request(); - $request->attributes->set('_converters', $configurations); - - $event = new FilterControllerEvent( - $kernel, - 'time', - $request, - null - ); - - $manager = m::mock(ParamConverterManager::class); - $manager->shouldReceive('apply')->once()->withArgs([$request, ['foo' => $configuration]]); - - $eventSubscriber = new ParamConverterEventSubscriber($manager, false); - $eventSubscriber->onKernelController($event); - - $this->assertNull(m::close()); - } +class ParamConverterEventSubscriberTest extends UnitTestCase { + + /** + * @dataProvider getControllerWithNoArgsFixtures + */ + public function testRequestIsSkipped($controllerCallable) { + $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $request = new Request(); + + $eventSubscriber = new ParamConverterEventSubscriber( + $this->getParamConverterManager($request, []) + ); + $event = new FilterControllerEvent( + $kernel, + $controllerCallable, + $request, + NULL + ); + + $eventSubscriber->onKernelController($event); + } + + public function getControllerWithNoArgsFixtures() { + return [ + [[new ParamConverterTestController(), 'noArgAction']], + [new ParamConverterInvokableNoArgController()], + ]; + } + + /** + * @dataProvider getControllerWithArgsFixtures + */ + public function testAutoConvert($controllerCallable) { + $kernel = $this->getMockBuilder( + HttpKernelInterface::class + )->getMock(); + $request = new Request([], [], ['date' => '2014-03-14 09:00:00']); + + $converter = new ParamConverter( + ['name' => 'date', 'class' => 'DateTime'] + ); + + $eventSubscriber = new ParamConverterEventSubscriber( + $this->getParamConverterManager($request, ['date' => $converter]) + ); + $event = new FilterControllerEvent( + $kernel, + $controllerCallable, + $request, + NULL + ); + + $eventSubscriber->onKernelController($event); + } + + /** + * @dataProvider settingOptionalParamProvider + * @requires PHP 7.1 + */ + public function testSettingOptionalParam($function, $isOptional) { + $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $request = new Request(); + + $converter = new ParamConverter( + ['name' => 'param', 'class' => 'DateTime'] + ); + $converter->setIsOptional($isOptional); + + $eventSubscriber = new ParamConverterEventSubscriber( + $this->getParamConverterManager($request, ['param' => $converter]), + TRUE + ); + $event = new FilterControllerEvent( + $kernel, + [ + new FooControllerNullableParameter(), + $function, + ], + $request, + NULL + ); + + $eventSubscriber->onKernelController($event); + } + + public function settingOptionalParamProvider() { + return [ + ['requiredParamAction', FALSE], + ['defaultParamAction', TRUE], + ['nullableParamAction', TRUE], + ]; + } + + /** + * @dataProvider getControllerWithArgsFixtures + */ + public function testNoAutoConvert($controllerCallable) { + $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + $request = new Request([], [], ['date' => '2014-03-14 09:00:00']); + + $eventSubscriber = new ParamConverterEventSubscriber( + $this->getParamConverterManager($request, []), + FALSE + ); + $event = new FilterControllerEvent( + $kernel, + $controllerCallable, + $request, + NULL + ); + + $eventSubscriber->onKernelController($event); + } + + public function getControllerWithArgsFixtures() { + return [ + [[new ParamConverterTestController(), 'dateAction']], + [new ParamConverterInvokableController()], + ]; + } + + protected function getParamConverterManager(Request $request, $configurations) { + $manager = $this->getMockBuilder(ParamConverterManager::class)->getMock(); + $manager + ->expects($this->once()) + ->method('apply') + ->with($this->equalTo($request), $this->equalTo($configurations)); + + return $manager; + } + + public function testPredefinedConfigurations() { + $configuration = m::mock(\stdClass::class); + $configuration->shouldReceive('getName')->andReturn('foo'); + + $configurations = [$configuration]; + + $kernel = m::mock(HttpKernelInterface::class); + $request = new Request(); + $request->attributes->set('_converters', $configurations); + + $event = new FilterControllerEvent( + $kernel, + 'time', + $request, + NULL + ); + + $manager = m::mock(ParamConverterManager::class); + $manager->shouldReceive('apply')->once()->withArgs([$request, ['foo' => $configuration]]); + + $eventSubscriber = new ParamConverterEventSubscriber($manager, FALSE); + $eventSubscriber->onKernelController($event); + + $this->assertNull(m::close()); + } + } -class ParamConverterTestController -{ +class ParamConverterTestController { + + public function noArgAction(Request $request) { + } - public function noArgAction(Request $request) - { - } + public function dateAction(\DateTime $date) { + } - public function dateAction(\DateTime $date) - { - } } -class ParamConverterInvokableNoArgController -{ +class ParamConverterInvokableNoArgController { + + public function __invoke(Request $request) { + } - public function __invoke(Request $request) - { - } } -class ParamConverterInvokableController -{ +class ParamConverterInvokableController { + + public function __invoke(\DateTime $date) { + } - public function __invoke(\DateTime $date) - { - } } diff --git a/tests/src/Unit/EventSubscriber/RouteEventSubscriberTest.php b/tests/src/Unit/EventSubscriber/RouteEventSubscriberTest.php index a8ba981..f2ab9b0 100644 --- a/tests/src/Unit/EventSubscriber/RouteEventSubscriberTest.php +++ b/tests/src/Unit/EventSubscriber/RouteEventSubscriberTest.php @@ -13,112 +13,105 @@ /** * @group controller_annotations */ -class RouteEventSubscriberTest extends UnitTestCase -{ - /** - * @var RouteCollection - */ - protected $routeCollection; - - /** - * @var RouteCollection - */ - protected $annotatedRouteCollection; - - /** - * @var RouteEventSubscriber - */ - protected $eventSubscriber; - - protected function setUpEventSubscriber() - { - $annotationDirectoryLoader = m::mock(AnnotationDirectoryLoader::class); - $annotationDirectoryLoader->shouldReceive('load')->andReturn($this->getAnnotatedRouteCollection()); - - $this->eventSubscriber = new RouteEventSubscriber($annotationDirectoryLoader, ''); +class RouteEventSubscriberTest extends UnitTestCase { + + /** + * @var \Symfony\Component\Routing\RouteCollection + */ + protected $routeCollection; + + /** + * @var \Symfony\Component\Routing\RouteCollection + */ + protected $annotatedRouteCollection; + + /** + * @var \Drupal\controller_annotations\EventSubscriber\RouteEventSubscriber + */ + protected $eventSubscriber; + + protected function setUpEventSubscriber() { + $annotationDirectoryLoader = m::mock(AnnotationDirectoryLoader::class); + $annotationDirectoryLoader->shouldReceive('load')->andReturn($this->getAnnotatedRouteCollection()); + + $this->eventSubscriber = new RouteEventSubscriber($annotationDirectoryLoader, ''); + } + + /** + * @return \Symfony\Component\Routing\RouteCollection + */ + protected function getRouteCollection() { + if (empty($this->routeCollection)) { + $this->routeCollection = new RouteCollection(); } - /** - * @return RouteCollection - */ - protected function getRouteCollection() - { - if (empty($this->routeCollection)) { - $this->routeCollection = new RouteCollection; - } + return $this->routeCollection; + } - return $this->routeCollection; + /** + * @return \Symfony\Component\Routing\RouteCollection + */ + protected function getAnnotatedRouteCollection() { + if (empty($this->annotatedRouteCollection)) { + $this->annotatedRouteCollection = new RouteCollection(); } - /** - * @return RouteCollection - */ - protected function getAnnotatedRouteCollection() - { - if (empty($this->annotatedRouteCollection)) { - $this->annotatedRouteCollection = new RouteCollection; - } + return $this->annotatedRouteCollection; + } - return $this->annotatedRouteCollection; + protected function triggerOnRoutes() { + if (empty($this->eventSubscriber)) { + $this->setUpEventSubscriber(); } + $this->eventSubscriber->onRoutes(new RouteBuildEvent($this->getRouteCollection())); + } - protected function triggerOnRoutes() - { - if (empty($this->eventSubscriber)) { - $this->setUpEventSubscriber(); - } - $this->eventSubscriber->onRoutes(new RouteBuildEvent($this->getRouteCollection())); - } + public function testOnRoutesWithEmptyRouteCollection() { + $this->triggerOnRoutes(); + $this->assertEquals(0, $this->getRouteCollection()->count()); + } - public function testOnRoutesWithEmptyRouteCollection() - { - $this->triggerOnRoutes(); - $this->assertEquals(0, $this->getRouteCollection()->count()); - } + public function testOnRoutesWithoutAnnotatedRoutes() { + $route = new Route('/foo'); + $route->setOption('type', 'annotation'); + $route->setOption('path', 'foo'); - public function testOnRoutesWithoutAnnotatedRoutes() - { - $route = new Route('/foo'); - $route->setOption('type', 'annotation'); - $route->setOption('path', 'foo'); + $this->getRouteCollection()->add('foo', new Route('/foo')); - $this->getRouteCollection()->add('foo', new Route('/foo')); + $this->triggerOnRoutes(); + $this->assertEquals(1, $this->getRouteCollection()->count()); + } - $this->triggerOnRoutes(); - $this->assertEquals(1, $this->getRouteCollection()->count()); - } + public function testOnRoutesWithAnnotatedRoute() { + $annotatedRoute = new Route('/bar'); - public function testOnRoutesWithAnnotatedRoute() - { - $annotatedRoute = new Route('/bar'); + $annotatedRouteCollection = $this->getAnnotatedRouteCollection(); + $annotatedRouteCollection->add('bar', $annotatedRoute); - $annotatedRouteCollection = $this->getAnnotatedRouteCollection(); - $annotatedRouteCollection->add('bar', $annotatedRoute); + $route = new Route('/foo'); + $route->setOption('type', 'annotation'); + $route->setOption('path', 'foo'); - $route = new Route('/foo'); - $route->setOption('type', 'annotation'); - $route->setOption('path', 'foo'); + $this->getRouteCollection()->add('foo', $route); + $this->triggerOnRoutes(); + $this->assertEquals(1, $this->getRouteCollection()->count()); + $this->assertEquals($annotatedRoute, $this->getRouteCollection()->all()['bar']); + } - $this->getRouteCollection()->add('foo', $route); - $this->triggerOnRoutes(); - $this->assertEquals(1, $this->getRouteCollection()->count()); - $this->assertEquals($annotatedRoute, $this->getRouteCollection()->all()['bar']); - } + public function testOnRoutesWithoutRequiredOptions() { + $this->setExpectedException(\Exception::class); - public function testOnRoutesWithoutRequiredOptions() - { - $this->setExpectedException(\Exception::class); + $annotatedRoute = new Route('/bar'); - $annotatedRoute = new Route('/bar'); + $annotatedRouteCollection = $this->getAnnotatedRouteCollection(); + $annotatedRouteCollection->add('bar', $annotatedRoute); - $annotatedRouteCollection = $this->getAnnotatedRouteCollection(); - $annotatedRouteCollection->add('bar', $annotatedRoute); + $route = new Route('/foo'); + $route->setOption('type', 'annotation'); - $route = new Route('/foo'); - $route->setOption('type', 'annotation'); + $this->getRouteCollection()->add('foo', $route); - $this->getRouteCollection()->add('foo', $route); + $this->triggerOnRoutes(); + } - $this->triggerOnRoutes(); - } } diff --git a/tests/src/Unit/EventSubscriber/TemplateEventSubscriberTest.php b/tests/src/Unit/EventSubscriber/TemplateEventSubscriberTest.php index 6d985b8..4f27c42 100644 --- a/tests/src/Unit/EventSubscriber/TemplateEventSubscriberTest.php +++ b/tests/src/Unit/EventSubscriber/TemplateEventSubscriberTest.php @@ -17,173 +17,167 @@ /** * @group controller_annotations */ -class TemplateEventSubscriberTest extends UnitTestCase -{ - public function testOnKernelControllerWithoutTemplate() - { - $twig = m::mock(\Twig_Environment::class); - $templateResolver = m::mock(TemplateResolver::class); +class TemplateEventSubscriberTest extends UnitTestCase { - $request = new Request(); + public function testOnKernelControllerWithoutTemplate() { + $twig = m::mock(\Twig_Environment::class); + $templateResolver = m::mock(TemplateResolver::class); - $event = m::mock(FilterControllerEvent::class); - $event->shouldReceive('getRequest')->once()->andReturn($request); + $request = new Request(); - $eventSubscriber = new TemplateEventSubscriber($twig, $templateResolver); - $this->assertNull($eventSubscriber->onKernelController($event)); + $event = m::mock(FilterControllerEvent::class); + $event->shouldReceive('getRequest')->once()->andReturn($request); - $event = m::mock(GetResponseForControllerResultEvent::class); - $event->shouldReceive('getRequest')->once()->andReturn($request); + $eventSubscriber = new TemplateEventSubscriber($twig, $templateResolver); + $this->assertNull($eventSubscriber->onKernelController($event)); - $eventSubscriber = new TemplateEventSubscriber($twig, $templateResolver); - $this->assertNull($eventSubscriber->onKernelView($event)); - } + $event = m::mock(GetResponseForControllerResultEvent::class); + $event->shouldReceive('getRequest')->once()->andReturn($request); - public function testOnKernelControllerWithInvalidTemplate() - { - $twig = m::mock(\Twig_Environment::class); - $templateResolver = m::mock(TemplateResolver::class); + $eventSubscriber = new TemplateEventSubscriber($twig, $templateResolver); + $this->assertNull($eventSubscriber->onKernelView($event)); + } - $request = new Request(); - $request->attributes->set('_template', 'foo'); + public function testOnKernelControllerWithInvalidTemplate() { + $twig = m::mock(\Twig_Environment::class); + $templateResolver = m::mock(TemplateResolver::class); - $event = m::mock(FilterControllerEvent::class); - $event->shouldReceive('getRequest')->once()->andReturn($request); + $request = new Request(); + $request->attributes->set('_template', 'foo'); - $eventSubscriber = new TemplateEventSubscriber($twig, $templateResolver); - $this->assertNull($eventSubscriber->onKernelController($event)); + $event = m::mock(FilterControllerEvent::class); + $event->shouldReceive('getRequest')->once()->andReturn($request); - $event = m::mock(GetResponseForControllerResultEvent::class); - $event->shouldReceive('getRequest')->once()->andReturn($request); + $eventSubscriber = new TemplateEventSubscriber($twig, $templateResolver); + $this->assertNull($eventSubscriber->onKernelController($event)); - $eventSubscriber = new TemplateEventSubscriber($twig, $templateResolver); - $this->assertNull($eventSubscriber->onKernelView($event)); - } + $event = m::mock(GetResponseForControllerResultEvent::class); + $event->shouldReceive('getRequest')->once()->andReturn($request); - public function testOnKernelControllerWithTemplate() - { - $templateName = 'resolved_template'; + $eventSubscriber = new TemplateEventSubscriber($twig, $templateResolver); + $this->assertNull($eventSubscriber->onKernelView($event)); + } - $twig = m::mock(\Twig_Environment::class); - $templateResolver = m::mock(TemplateResolver::class); - $templateResolver->shouldReceive('resolveByControllerAndAction')->once()->andReturn($templateName); + public function testOnKernelControllerWithTemplate() { + $templateName = 'resolved_template'; - $template = new Template([]); + $twig = m::mock(\Twig_Environment::class); + $templateResolver = m::mock(TemplateResolver::class); + $templateResolver->shouldReceive('resolveByControllerAndAction')->once()->andReturn($templateName); - $request = new Request(); - $request->attributes->set('_template', $template); + $template = new Template([]); - $controller = m::mock(ControllerBase::class); - $owner = [$controller, 'testAction']; + $request = new Request(); + $request->attributes->set('_template', $template); - $event = m::mock(FilterControllerEvent::class); - $event->shouldReceive('getRequest')->once()->andReturn($request); - $event->shouldReceive('getController')->once()->andReturn($owner); + $controller = m::mock(ControllerBase::class); + $owner = [$controller, 'testAction']; - $eventSubscriber = new TemplateEventSubscriber($twig, $templateResolver); - $eventSubscriber->onKernelController($event); + $event = m::mock(FilterControllerEvent::class); + $event->shouldReceive('getRequest')->once()->andReturn($request); + $event->shouldReceive('getController')->once()->andReturn($owner); - $this->assertEquals($templateName, $template->getTemplate()); - $this->assertEquals($owner, $template->getOwner()); - } + $eventSubscriber = new TemplateEventSubscriber($twig, $templateResolver); + $eventSubscriber->onKernelController($event); - public function testOnKernelControllerWithTemplateName() - { - $templateName = 'resolved_template'; + $this->assertEquals($templateName, $template->getTemplate()); + $this->assertEquals($owner, $template->getOwner()); + } - $twig = m::mock(\Twig_Environment::class); - $templateResolver = m::mock(TemplateResolver::class); - $templateResolver->shouldReceive('normalize')->once()->andReturn($templateName); + public function testOnKernelControllerWithTemplateName() { + $templateName = 'resolved_template'; - $template = new Template([ - 'template' => $templateName - ]); + $twig = m::mock(\Twig_Environment::class); + $templateResolver = m::mock(TemplateResolver::class); + $templateResolver->shouldReceive('normalize')->once()->andReturn($templateName); - $request = new Request(); - $request->attributes->set('_template', $template); + $template = new Template([ + 'template' => $templateName, + ]); - $controller = m::mock(ControllerBase::class); - $owner = [$controller, 'testAction']; + $request = new Request(); + $request->attributes->set('_template', $template); - $event = m::mock(FilterControllerEvent::class); - $event->shouldReceive('getRequest')->once()->andReturn($request); - $event->shouldReceive('getController')->once()->andReturn($owner); + $controller = m::mock(ControllerBase::class); + $owner = [$controller, 'testAction']; - $eventSubscriber = new TemplateEventSubscriber($twig, $templateResolver); - $eventSubscriber->onKernelController($event); + $event = m::mock(FilterControllerEvent::class); + $event->shouldReceive('getRequest')->once()->andReturn($request); + $event->shouldReceive('getController')->once()->andReturn($owner); - $this->assertEquals($templateName, $template->getTemplate()); - $this->assertEquals($owner, $template->getOwner()); - } + $eventSubscriber = new TemplateEventSubscriber($twig, $templateResolver); + $eventSubscriber->onKernelController($event); - public function testOnKernelView() - { - $renderedContent = 'rendered_page'; - $templateName = 'template.html.twig'; + $this->assertEquals($templateName, $template->getTemplate()); + $this->assertEquals($owner, $template->getOwner()); + } - $twig = m::mock(\Twig_Environment::class); - $twig->shouldReceive('render')->once()->andReturn($renderedContent); + public function testOnKernelView() { + $renderedContent = 'rendered_page'; + $templateName = 'template.html.twig'; - $templateResolver = m::mock(TemplateResolver::class); + $twig = m::mock(\Twig_Environment::class); + $twig->shouldReceive('render')->once()->andReturn($renderedContent); - $template = m::mock(Template::class); - $template->shouldReceive('getOwner')->andReturn(['controller', 'action']); - $template->shouldReceive('isStreamable')->andReturn(false); - $template->shouldReceive('setOwner')->once()->withArgs([[]]); - $template->shouldReceive('getTemplate')->once()->andReturn($templateName); + $templateResolver = m::mock(TemplateResolver::class); - $request = new Request(); - $request->attributes->set('_template', $template); + $template = m::mock(Template::class); + $template->shouldReceive('getOwner')->andReturn(['controller', 'action']); + $template->shouldReceive('isStreamable')->andReturn(FALSE); + $template->shouldReceive('setOwner')->once()->withArgs([[]]); + $template->shouldReceive('getTemplate')->once()->andReturn($templateName); - $property = null; - $value = null; + $request = new Request(); + $request->attributes->set('_template', $template); - $kernel = m::mock(HttpKernelInterface::class); - $event = new GetResponseForControllerResultEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST, []); + $property = NULL; + $value = NULL; - $eventSubscriber = new TemplateEventSubscriber($twig, $templateResolver); - $eventSubscriber->onKernelView($event); + $kernel = m::mock(HttpKernelInterface::class); + $event = new GetResponseForControllerResultEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST, []); - $response = $event->getResponse(); - $this->assertEquals($renderedContent, $response->getContent()); - } + $eventSubscriber = new TemplateEventSubscriber($twig, $templateResolver); + $eventSubscriber->onKernelView($event); - public function testOnKernelViewStreamed() - { - $templateName = 'template.html.twig'; + $response = $event->getResponse(); + $this->assertEquals($renderedContent, $response->getContent()); + } - $twig = m::mock(\Twig_Environment::class); - $twig->shouldReceive('display')->once()->withArgs([$templateName, []]); + public function testOnKernelViewStreamed() { + $templateName = 'template.html.twig'; - $templateResolver = m::mock(TemplateResolver::class); + $twig = m::mock(\Twig_Environment::class); + $twig->shouldReceive('display')->once()->withArgs([$templateName, []]); - $template = m::mock(Template::class); - $template->shouldReceive('getOwner')->andReturn(['controller', 'action']); - $template->shouldReceive('isStreamable')->andReturn(true); - $template->shouldReceive('setOwner')->once()->withArgs([[]]); - $template->shouldReceive('getTemplate')->once()->andReturn($templateName); + $templateResolver = m::mock(TemplateResolver::class); - $request = new Request(); - $request->attributes->set('_template', $template); + $template = m::mock(Template::class); + $template->shouldReceive('getOwner')->andReturn(['controller', 'action']); + $template->shouldReceive('isStreamable')->andReturn(TRUE); + $template->shouldReceive('setOwner')->once()->withArgs([[]]); + $template->shouldReceive('getTemplate')->once()->andReturn($templateName); - $property = null; - $value = null; + $request = new Request(); + $request->attributes->set('_template', $template); - $kernel = m::mock(HttpKernelInterface::class); - $event = new GetResponseForControllerResultEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST, []); + $property = NULL; + $value = NULL; - $eventSubscriber = new TemplateEventSubscriber($twig, $templateResolver); - $eventSubscriber->onKernelView($event); + $kernel = m::mock(HttpKernelInterface::class); + $event = new GetResponseForControllerResultEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST, []); - $response = $event->getResponse(); - $this->assertEquals(false, $response->getContent()); - $this->assertInstanceOf(StreamedResponse::class, $response); + $eventSubscriber = new TemplateEventSubscriber($twig, $templateResolver); + $eventSubscriber->onKernelView($event); - $response->sendContent(); - } + $response = $event->getResponse(); + $this->assertEquals(FALSE, $response->getContent()); + $this->assertInstanceOf(StreamedResponse::class, $response); + + $response->sendContent(); + } + + public function tearDown() { + m::close(); + } - public function tearDown() - { - m::close(); - } } diff --git a/tests/src/Unit/Fixture/FooControllerNullableParameter.php b/tests/src/Unit/Fixture/FooControllerNullableParameter.php index a2fb417..3c2482e 100644 --- a/tests/src/Unit/Fixture/FooControllerNullableParameter.php +++ b/tests/src/Unit/Fixture/FooControllerNullableParameter.php @@ -2,17 +2,15 @@ namespace Drupal\Tests\controller_annotations\Unit\Fixture; -class FooControllerNullableParameter -{ - public function requiredParamAction(\DateTime $param) - { - } +class FooControllerNullableParameter { - public function defaultParamAction(\DateTime $param = null) - { - } + public function requiredParamAction(\DateTime $param) { + } + + public function defaultParamAction(\DateTime $param = NULL) { + } + + public function nullableParamAction(?\DateTime $param) { + } - public function nullableParamAction(?\DateTime $param) - { - } } diff --git a/tests/src/Unit/Fixture/FooControllerParamConverterAtClassAndMethod.php b/tests/src/Unit/Fixture/FooControllerParamConverterAtClassAndMethod.php index c077b6e..0c8ff33 100644 --- a/tests/src/Unit/Fixture/FooControllerParamConverterAtClassAndMethod.php +++ b/tests/src/Unit/Fixture/FooControllerParamConverterAtClassAndMethod.php @@ -7,12 +7,12 @@ /** * @ParamConverter("test") */ -class FooControllerParamConverterAtClassAndMethod -{ - /** - * @ParamConverter("test2") - */ - public function barAction($test, $test2) - { - } +class FooControllerParamConverterAtClassAndMethod { + + /** + * @ParamConverter("test2") + */ + public function barAction($test, $test2) { + } + } diff --git a/tests/src/Unit/Helper.php b/tests/src/Unit/Helper.php index b512722..3a4e5ce 100644 --- a/tests/src/Unit/Helper.php +++ b/tests/src/Unit/Helper.php @@ -2,14 +2,14 @@ namespace Drupal\Tests\controller_annotations\Unit; -class Helper -{ - public static function getProtectedMethod($class, $name) - { - $class = new \ReflectionClass($class); - $method = $class->getMethod($name); - $method->setAccessible(true); - - return $method; - } +class Helper { + + public static function getProtectedMethod($class, $name) { + $class = new \ReflectionClass($class); + $method = $class->getMethod($name); + $method->setAccessible(TRUE); + + return $method; + } + } diff --git a/tests/src/Unit/Request/ParamConverter/DateTimeParamConverterTest.php b/tests/src/Unit/Request/ParamConverter/DateTimeParamConverterTest.php index 379428d..cd5702b 100644 --- a/tests/src/Unit/Request/ParamConverter/DateTimeParamConverterTest.php +++ b/tests/src/Unit/Request/ParamConverter/DateTimeParamConverterTest.php @@ -10,117 +10,109 @@ /** * @group controller_annotations */ -class DateTimeParamConverterTest extends UnitTestCase -{ - - private $converter; - - public function setUp() - { - $this->converter = new DateTimeParamConverter(); - } - - public function testSupports() - { - $config = $this->createConfiguration('DateTime'); - $this->assertTrue($this->converter->supports($config)); - - $config = $this->createConfiguration(__CLASS__); - $this->assertFalse($this->converter->supports($config)); - - $config = $this->createConfiguration(); - $this->assertFalse($this->converter->supports($config)); - } - - public function testApply() - { - $request = new Request([], [], ['start' => '2012-07-21 00:00:00']); - $config = $this->createConfiguration('DateTime', 'start'); - - $this->converter->apply($request, $config); - - $this->assertInstanceOf('DateTime', $request->attributes->get('start')); - $this->assertEquals( - '2012-07-21', - $request->attributes->get('start')->format('Y-m-d') - ); +class DateTimeParamConverterTest extends UnitTestCase { + + private $converter; + + public function setUp() { + $this->converter = new DateTimeParamConverter(); + } + + public function testSupports() { + $config = $this->createConfiguration('DateTime'); + $this->assertTrue($this->converter->supports($config)); + + $config = $this->createConfiguration(__CLASS__); + $this->assertFalse($this->converter->supports($config)); + + $config = $this->createConfiguration(); + $this->assertFalse($this->converter->supports($config)); + } + + public function testApply() { + $request = new Request([], [], ['start' => '2012-07-21 00:00:00']); + $config = $this->createConfiguration('DateTime', 'start'); + + $this->converter->apply($request, $config); + + $this->assertInstanceOf('DateTime', $request->attributes->get('start')); + $this->assertEquals( + '2012-07-21', + $request->attributes->get('start')->format('Y-m-d') + ); + } + + public function testApplyInvalidDate404Exception() { + $request = new Request([], [], ['start' => 'Invalid DateTime Format']); + $config = $this->createConfiguration('DateTime', 'start'); + + $this->setExpectedException( + 'Symfony\Component\HttpKernel\Exception\NotFoundHttpException', + 'Invalid date given for parameter "start".' + ); + $this->converter->apply($request, $config); + } + + public function testApplyWithFormatInvalidDate404Exception() { + $request = new Request([], [], ['start' => '2012-07-21']); + $config = $this->createConfiguration('DateTime', 'start'); + $config->expects($this->any())->method('getOptions')->will( + $this->returnValue(['format' => 'd.m.Y']) + ); + + $this->setExpectedException( + 'Symfony\Component\HttpKernel\Exception\NotFoundHttpException', + 'Invalid date given for parameter "start".' + ); + $this->converter->apply($request, $config); + } + + public function testApplyOptionalWithEmptyAttribute() { + $request = new Request([], [], ['start' => NULL]); + $config = $this->createConfiguration('DateTime', 'start'); + $config->expects($this->once()) + ->method('isOptional') + ->will($this->returnValue(TRUE)); + + $this->assertFalse($this->converter->apply($request, $config)); + $this->assertNull($request->attributes->get('start')); + } + + public function testApplyEmptyAttribute() { + $request = new Request(); + $config = $this->createConfiguration('DateTime', 'start'); + + $this->assertFalse($this->converter->apply($request, $config)); + } + + public function createConfiguration($class = NULL, $name = NULL) { + $config = $this + ->getMockBuilder(ParamConverter::class) + ->setMethods( + [ + 'getClass', + 'getAliasName', + 'getOptions', + 'getName', + 'allowArray', + 'isOptional', + ] + ) + ->disableOriginalConstructor() + ->getMock(); + + if ($name !== NULL) { + $config->expects($this->any()) + ->method('getName') + ->will($this->returnValue($name)); } - - public function testApplyInvalidDate404Exception() - { - $request = new Request([], [], ['start' => 'Invalid DateTime Format']); - $config = $this->createConfiguration('DateTime', 'start'); - - $this->setExpectedException( - 'Symfony\Component\HttpKernel\Exception\NotFoundHttpException', - 'Invalid date given for parameter "start".' - ); - $this->converter->apply($request, $config); - } - - public function testApplyWithFormatInvalidDate404Exception() - { - $request = new Request([], [], ['start' => '2012-07-21']); - $config = $this->createConfiguration('DateTime', 'start'); - $config->expects($this->any())->method('getOptions')->will( - $this->returnValue(['format' => 'd.m.Y']) - ); - - $this->setExpectedException( - 'Symfony\Component\HttpKernel\Exception\NotFoundHttpException', - 'Invalid date given for parameter "start".' - ); - $this->converter->apply($request, $config); - } - - public function testApplyOptionalWithEmptyAttribute() - { - $request = new Request([], [], ['start' => null]); - $config = $this->createConfiguration('DateTime', 'start'); - $config->expects($this->once()) - ->method('isOptional') - ->will($this->returnValue(true)); - - $this->assertFalse($this->converter->apply($request, $config)); - $this->assertNull($request->attributes->get('start')); + if ($class !== NULL) { + $config->expects($this->any()) + ->method('getClass') + ->will($this->returnValue($class)); } - public function testApplyEmptyAttribute() - { - $request = new Request(); - $config = $this->createConfiguration('DateTime', 'start'); + return $config; + } - $this->assertFalse($this->converter->apply($request, $config)); - } - - public function createConfiguration($class = null, $name = null) - { - $config = $this - ->getMockBuilder(ParamConverter::class) - ->setMethods( - [ - 'getClass', - 'getAliasName', - 'getOptions', - 'getName', - 'allowArray', - 'isOptional', - ] - ) - ->disableOriginalConstructor() - ->getMock(); - - if ($name !== null) { - $config->expects($this->any()) - ->method('getName') - ->will($this->returnValue($name)); - } - if ($class !== null) { - $config->expects($this->any()) - ->method('getClass') - ->will($this->returnValue($class)); - } - - return $config; - } } diff --git a/tests/src/Unit/Request/ParamConverter/EntityParamConverterTest.php b/tests/src/Unit/Request/ParamConverter/EntityParamConverterTest.php index 2e0dc04..9cd1005 100644 --- a/tests/src/Unit/Request/ParamConverter/EntityParamConverterTest.php +++ b/tests/src/Unit/Request/ParamConverter/EntityParamConverterTest.php @@ -15,246 +15,235 @@ /** * @group controller_annotations */ -class EntityParamConverterTest extends UnitTestCase -{ - private function getEntityParamConverter() - { - $node = m::mock(Node::class); +class EntityParamConverterTest extends UnitTestCase { - $entityInterface = m::mock(EntityInterface::class); - $entityInterface->shouldReceive('load')->andReturn($node); + private function getEntityParamConverter() { + $node = m::mock(Node::class); - $entityTypeManager = m::mock(EntityTypeManager::class); - $entityTypeManager->shouldReceive('getStorage')->andReturn($entityInterface); + $entityInterface = m::mock(EntityInterface::class); + $entityInterface->shouldReceive('load')->andReturn($node); - return new EntityParamConverter($entityTypeManager); - } + $entityTypeManager = m::mock(EntityTypeManager::class); + $entityTypeManager->shouldReceive('getStorage')->andReturn($entityInterface); - public function testSupports() - { - $paramConverter = m::mock(ParamConverter::class); - $paramConverter->shouldReceive('getClass')->once()->andReturn(Node::class); - $this->assertTrue($this->getEntityParamConverter()->supports($paramConverter)); - } + return new EntityParamConverter($entityTypeManager); + } - public function testNotSupports() - { - $paramConverter = m::mock(ParamConverter::class); - $paramConverter->shouldReceive('getClass')->once()->andReturn(self::class); - $this->assertFalse($this->getEntityParamConverter()->supports($paramConverter)); - } + public function testSupports() { + $paramConverter = m::mock(ParamConverter::class); + $paramConverter->shouldReceive('getClass')->once()->andReturn(Node::class); + $this->assertTrue($this->getEntityParamConverter()->supports($paramConverter)); + } - public function testApply() - { - $name = 'test'; - $request = new Request(); - $request->attributes->set($name, 1); + public function testNotSupports() { + $paramConverter = m::mock(ParamConverter::class); + $paramConverter->shouldReceive('getClass')->once()->andReturn(self::class); + $this->assertFalse($this->getEntityParamConverter()->supports($paramConverter)); + } - $node = m::mock(Node::class); + public function testApply() { + $name = 'test'; + $request = new Request(); + $request->attributes->set($name, 1); - $paramConverter = m::mock(ParamConverter::class); - $paramConverter->shouldReceive('getClass')->once()->andReturn(Node::class); - $paramConverter->shouldReceive('getName')->once()->andReturn($name); - $paramConverter->shouldReceive('getOptions')->once()->andReturn([]); + $node = m::mock(Node::class); - $this->assertTrue($this->getEntityParamConverter()->supports($paramConverter)); - $this->getEntityParamConverter()->apply($request, $paramConverter); + $paramConverter = m::mock(ParamConverter::class); + $paramConverter->shouldReceive('getClass')->once()->andReturn(Node::class); + $paramConverter->shouldReceive('getName')->once()->andReturn($name); + $paramConverter->shouldReceive('getOptions')->once()->andReturn([]); - $this->assertTrue($request->attributes->has($name)); - $this->assertEquals($node, $request->attributes->get($name)); - } + $this->assertTrue($this->getEntityParamConverter()->supports($paramConverter)); + $this->getEntityParamConverter()->apply($request, $paramConverter); - public function testApplyNonExistingEntity() - { - $this->setExpectedException(NotFoundHttpException::class); + $this->assertTrue($request->attributes->has($name)); + $this->assertEquals($node, $request->attributes->get($name)); + } - $entityInterface = m::mock(EntityInterface::class); - $entityInterface->shouldReceive('load')->andReturnNull(); + public function testApplyNonExistingEntity() { + $this->setExpectedException(NotFoundHttpException::class); - $entityTypeManager = m::mock(EntityTypeManager::class); - $entityTypeManager->shouldReceive('getStorage')->andReturn($entityInterface); + $entityInterface = m::mock(EntityInterface::class); + $entityInterface->shouldReceive('load')->andReturnNull(); - $name = 'test'; - $request = new Request(); - $request->attributes->set($name, 1); + $entityTypeManager = m::mock(EntityTypeManager::class); + $entityTypeManager->shouldReceive('getStorage')->andReturn($entityInterface); - $paramConverter = m::mock(ParamConverter::class); - $paramConverter->shouldReceive('getClass')->once()->andReturn(Node::class); - $paramConverter->shouldReceive('getName')->once()->andReturn($name); - $paramConverter->shouldReceive('isOptional')->once()->andReturn(false); + $name = 'test'; + $request = new Request(); + $request->attributes->set($name, 1); - $entityParamConverter = new EntityParamConverter($entityTypeManager); + $paramConverter = m::mock(ParamConverter::class); + $paramConverter->shouldReceive('getClass')->once()->andReturn(Node::class); + $paramConverter->shouldReceive('getName')->once()->andReturn($name); + $paramConverter->shouldReceive('isOptional')->once()->andReturn(FALSE); - $this->assertTrue($entityParamConverter->supports($paramConverter)); - $entityParamConverter->apply($request, $paramConverter); - } + $entityParamConverter = new EntityParamConverter($entityTypeManager); - public function testApplyWithBundle() - { - $id = 1; - $bundle = 'article'; + $this->assertTrue($entityParamConverter->supports($paramConverter)); + $entityParamConverter->apply($request, $paramConverter); + } - $node = m::mock(Node::class); - $node->shouldReceive('bundle')->once()->andReturn($bundle); + public function testApplyWithBundle() { + $id = 1; + $bundle = 'article'; - $entityInterface = m::mock(EntityInterface::class); - $entityInterface->shouldReceive('load')->withArgs([$id])->andReturn($node); + $node = m::mock(Node::class); + $node->shouldReceive('bundle')->once()->andReturn($bundle); - $entityTypeManager = m::mock(EntityTypeManager::class); - $entityTypeManager->shouldReceive('getStorage')->withArgs(['node'])->andReturn($entityInterface); + $entityInterface = m::mock(EntityInterface::class); + $entityInterface->shouldReceive('load')->withArgs([$id])->andReturn($node); - $nodeParamConverter = new EntityParamConverter($entityTypeManager); + $entityTypeManager = m::mock(EntityTypeManager::class); + $entityTypeManager->shouldReceive('getStorage')->withArgs(['node'])->andReturn($entityInterface); - $name = 'test'; - $request = new Request(); - $request->attributes->set($name, $id); + $nodeParamConverter = new EntityParamConverter($entityTypeManager); - $paramConverter = m::mock(ParamConverter::class); - $paramConverter->shouldReceive('getClass')->once()->andReturn(Node::class); - $paramConverter->shouldReceive('getName')->once()->andReturn($name); - $paramConverter->shouldReceive('getOptions')->once()->andReturn(['bundle' => $bundle]); + $name = 'test'; + $request = new Request(); + $request->attributes->set($name, $id); - $this->assertTrue($nodeParamConverter->supports($paramConverter)); - $nodeParamConverter->apply($request, $paramConverter); + $paramConverter = m::mock(ParamConverter::class); + $paramConverter->shouldReceive('getClass')->once()->andReturn(Node::class); + $paramConverter->shouldReceive('getName')->once()->andReturn($name); + $paramConverter->shouldReceive('getOptions')->once()->andReturn(['bundle' => $bundle]); - $this->assertTrue($request->attributes->has($name)); - $this->assertEquals($node, $request->attributes->get($name)); - } + $this->assertTrue($nodeParamConverter->supports($paramConverter)); + $nodeParamConverter->apply($request, $paramConverter); - public function testApplyWithWrongBundle() - { - $this->setExpectedException(NotFoundHttpException::class); + $this->assertTrue($request->attributes->has($name)); + $this->assertEquals($node, $request->attributes->get($name)); + } - $id = 1; - $bundle = 'article'; + public function testApplyWithWrongBundle() { + $this->setExpectedException(NotFoundHttpException::class); - $node = m::mock(Node::class); - $node->shouldReceive('bundle')->once()->andReturn('not_an_article'); + $id = 1; + $bundle = 'article'; - $entityInterface = m::mock(EntityInterface::class); - $entityInterface->shouldReceive('load')->withArgs([$id])->andReturn($node); + $node = m::mock(Node::class); + $node->shouldReceive('bundle')->once()->andReturn('not_an_article'); - $entityTypeManager = m::mock(EntityTypeManager::class); - $entityTypeManager->shouldReceive('getStorage')->withArgs(['node'])->andReturn($entityInterface); + $entityInterface = m::mock(EntityInterface::class); + $entityInterface->shouldReceive('load')->withArgs([$id])->andReturn($node); - $nodeParamConverter = new EntityParamConverter($entityTypeManager); + $entityTypeManager = m::mock(EntityTypeManager::class); + $entityTypeManager->shouldReceive('getStorage')->withArgs(['node'])->andReturn($entityInterface); - $name = 'test'; - $request = new Request(); - $request->attributes->set($name, $id); + $nodeParamConverter = new EntityParamConverter($entityTypeManager); - $paramConverter = m::mock(ParamConverter::class); - $paramConverter->shouldReceive('getClass')->once()->andReturn(Node::class); - $paramConverter->shouldReceive('getName')->once()->andReturn($name); - $paramConverter->shouldReceive('getOptions')->once()->andReturn(['bundle' => $bundle]); + $name = 'test'; + $request = new Request(); + $request->attributes->set($name, $id); - $this->assertTrue($nodeParamConverter->supports($paramConverter)); - $nodeParamConverter->apply($request, $paramConverter); - } + $paramConverter = m::mock(ParamConverter::class); + $paramConverter->shouldReceive('getClass')->once()->andReturn(Node::class); + $paramConverter->shouldReceive('getName')->once()->andReturn($name); + $paramConverter->shouldReceive('getOptions')->once()->andReturn(['bundle' => $bundle]); - public function testApplyOptionalWhenEmpty() - { - $id = 1; + $this->assertTrue($nodeParamConverter->supports($paramConverter)); + $nodeParamConverter->apply($request, $paramConverter); + } - $entityInterface = m::mock(EntityInterface::class); - $entityInterface->shouldReceive('load')->withArgs([$id])->andReturn(null); + public function testApplyOptionalWhenEmpty() { + $id = 1; - $entityTypeManager = m::mock(EntityTypeManager::class); - $entityTypeManager->shouldReceive('getStorage')->withArgs(['node'])->andReturn($entityInterface); + $entityInterface = m::mock(EntityInterface::class); + $entityInterface->shouldReceive('load')->withArgs([$id])->andReturn(NULL); - $nodeParamConverter = new EntityParamConverter($entityTypeManager); + $entityTypeManager = m::mock(EntityTypeManager::class); + $entityTypeManager->shouldReceive('getStorage')->withArgs(['node'])->andReturn($entityInterface); - $name = 'test'; - $request = new Request(); - $request->attributes->set($name, $id); + $nodeParamConverter = new EntityParamConverter($entityTypeManager); - $paramConverter = m::mock(ParamConverter::class); - $paramConverter->shouldReceive('getClass')->once()->andReturn(Node::class); - $paramConverter->shouldReceive('getName')->once()->andReturn($name); - $paramConverter->shouldReceive('isOptional')->once()->andReturn(true); + $name = 'test'; + $request = new Request(); + $request->attributes->set($name, $id); - $this->assertTrue($nodeParamConverter->supports($paramConverter)); - $nodeParamConverter->apply($request, $paramConverter); + $paramConverter = m::mock(ParamConverter::class); + $paramConverter->shouldReceive('getClass')->once()->andReturn(Node::class); + $paramConverter->shouldReceive('getName')->once()->andReturn($name); + $paramConverter->shouldReceive('isOptional')->once()->andReturn(TRUE); - $this->assertTrue($request->attributes->has($name)); - $this->assertEquals(null, $request->attributes->get($name)); - } + $this->assertTrue($nodeParamConverter->supports($paramConverter)); + $nodeParamConverter->apply($request, $paramConverter); - public function testApplyWithoutAttribute() - { - $id = 1; - $bundle = 'article'; + $this->assertTrue($request->attributes->has($name)); + $this->assertEquals(NULL, $request->attributes->get($name)); + } - $entityInterface = m::mock(EntityInterface::class); - $entityInterface->shouldReceive('load')->withArgs([$id])->andReturn(null); + public function testApplyWithoutAttribute() { + $id = 1; + $bundle = 'article'; - $entityTypeManager = m::mock(EntityTypeManager::class); - $entityTypeManager->shouldReceive('getStorage')->withArgs(['node'])->andReturn($entityInterface); + $entityInterface = m::mock(EntityInterface::class); + $entityInterface->shouldReceive('load')->withArgs([$id])->andReturn(NULL); - $nodeParamConverter = new EntityParamConverter($entityTypeManager); + $entityTypeManager = m::mock(EntityTypeManager::class); + $entityTypeManager->shouldReceive('getStorage')->withArgs(['node'])->andReturn($entityInterface); - $name = 'test'; - $request = new Request(); + $nodeParamConverter = new EntityParamConverter($entityTypeManager); - $paramConverter = m::mock(ParamConverter::class); - $paramConverter->shouldReceive('getClass')->once()->andReturn(Node::class); - $paramConverter->shouldReceive('getName')->once()->andReturn($name); - $paramConverter->shouldReceive('getOptions')->never()->andReturn(['bundle' => $bundle]); + $name = 'test'; + $request = new Request(); - $this->assertTrue($nodeParamConverter->supports($paramConverter)); - $this->assertFalse($nodeParamConverter->apply($request, $paramConverter)); - } + $paramConverter = m::mock(ParamConverter::class); + $paramConverter->shouldReceive('getClass')->once()->andReturn(Node::class); + $paramConverter->shouldReceive('getName')->once()->andReturn($name); + $paramConverter->shouldReceive('getOptions')->never()->andReturn(['bundle' => $bundle]); - public function testOptional() - { - $id = 1; - $bundle = 'article'; + $this->assertTrue($nodeParamConverter->supports($paramConverter)); + $this->assertFalse($nodeParamConverter->apply($request, $paramConverter)); + } - $entityInterface = m::mock(EntityInterface::class); - $entityInterface->shouldReceive('load')->withArgs([$id])->andReturn(null); + public function testOptional() { + $id = 1; + $bundle = 'article'; - $entityTypeManager = m::mock(EntityTypeManager::class); - $entityTypeManager->shouldReceive('getStorage')->withArgs(['node'])->andReturn($entityInterface); + $entityInterface = m::mock(EntityInterface::class); + $entityInterface->shouldReceive('load')->withArgs([$id])->andReturn(NULL); - $nodeParamConverter = new EntityParamConverter($entityTypeManager); + $entityTypeManager = m::mock(EntityTypeManager::class); + $entityTypeManager->shouldReceive('getStorage')->withArgs(['node'])->andReturn($entityInterface); - $name = 'test'; - $request = new Request(); + $nodeParamConverter = new EntityParamConverter($entityTypeManager); - $paramConverter = m::mock(ParamConverter::class); - $paramConverter->shouldReceive('getName')->once()->andReturn($name); - $paramConverter->shouldReceive('getOptions')->never()->andReturn(['bundle' => $bundle]); + $name = 'test'; + $request = new Request(); - $this->assertFalse($nodeParamConverter->apply($request, $paramConverter)); - } + $paramConverter = m::mock(ParamConverter::class); + $paramConverter->shouldReceive('getName')->once()->andReturn($name); + $paramConverter->shouldReceive('getOptions')->never()->andReturn(['bundle' => $bundle]); - public function testOptionalEmptyAttribute() - { - $id = 1; - $bundle = 'article'; + $this->assertFalse($nodeParamConverter->apply($request, $paramConverter)); + } - $entityInterface = m::mock(EntityInterface::class); - $entityInterface->shouldReceive('load')->withArgs([$id])->andReturn(null); + public function testOptionalEmptyAttribute() { + $id = 1; + $bundle = 'article'; - $entityTypeManager = m::mock(EntityTypeManager::class); - $entityTypeManager->shouldReceive('getStorage')->withArgs(['node'])->andReturn($entityInterface); + $entityInterface = m::mock(EntityInterface::class); + $entityInterface->shouldReceive('load')->withArgs([$id])->andReturn(NULL); - $nodeParamConverter = new EntityParamConverter($entityTypeManager); + $entityTypeManager = m::mock(EntityTypeManager::class); + $entityTypeManager->shouldReceive('getStorage')->withArgs(['node'])->andReturn($entityInterface); - $name = 'test'; - $request = new Request(); - $request->attributes->set($name, ''); + $nodeParamConverter = new EntityParamConverter($entityTypeManager); - $paramConverter = m::mock(ParamConverter::class); - $paramConverter->shouldReceive('getName')->once()->andReturn($name); - $paramConverter->shouldReceive('getOptions')->never()->andReturn(['bundle' => $bundle]); - $paramConverter->shouldReceive('isOptional')->once()->andReturn(true); + $name = 'test'; + $request = new Request(); + $request->attributes->set($name, ''); - $this->assertFalse($nodeParamConverter->apply($request, $paramConverter)); - } + $paramConverter = m::mock(ParamConverter::class); + $paramConverter->shouldReceive('getName')->once()->andReturn($name); + $paramConverter->shouldReceive('getOptions')->never()->andReturn(['bundle' => $bundle]); + $paramConverter->shouldReceive('isOptional')->once()->andReturn(TRUE); + + $this->assertFalse($nodeParamConverter->apply($request, $paramConverter)); + } + + public function tearDown() { + m::close(); + } - public function tearDown() - { - m::close(); - } } diff --git a/tests/src/Unit/Request/ParamConverter/ParamConverterManagerTest.php b/tests/src/Unit/Request/ParamConverter/ParamConverterManagerTest.php index 9fd30d1..e52237f 100644 --- a/tests/src/Unit/Request/ParamConverter/ParamConverterManagerTest.php +++ b/tests/src/Unit/Request/ParamConverter/ParamConverterManagerTest.php @@ -11,186 +11,168 @@ /** * @group controller_annotations */ -class ParamConverterManagerTest extends UnitTestCase -{ - public function testPriorities() - { - $manager = new ParamConverterManager(); - $this->assertEquals(array(), $manager->all()); - - $high = $this->createParamConverterMock(); - $low = $this->createParamConverterMock(); - - $manager->add($low); - $manager->add($high, 10); - - $this->assertEquals(array($high, $low), $manager->all()); - } - - public function testApply() - { - $supported = $this->createParamConverterMock(); - $supported - ->expects($this->once()) - ->method('supports') - ->will($this->returnValue(true)) - ; - $supported - ->expects($this->once()) - ->method('apply') - ->will($this->returnValue(false)) - ; - - $invalid = $this->createParamConverterMock(); - $invalid - ->expects($this->once()) - ->method('supports') - ->will($this->returnValue(false)) - ; - $invalid - ->expects($this->never()) - ->method('apply') - ; - - $configurations = array( - new Configuration\ParamConverter(array( - 'name' => 'var', - )), - ); - - $manager = new ParamConverterManager(); - $manager->add($supported); - $manager->add($invalid); - $manager->apply(new Request(), $configurations); - } - - public function testApplyNamedConverter() - { - $converter = $this->createParamConverterMock(); - $converter - ->expects($this->any()) - ->method('supports') - ->will($this->returnValue(true)) - ; - - $converter - ->expects($this->any()) - ->method('apply') - ; - - $request = new Request(); - $request->attributes->set('param', '1234'); - - $configuration = new Configuration\ParamConverter(array( - 'name' => 'param', - 'class' => 'stdClass', - 'converter' => 'test', - )); - - $manager = new ParamConverterManager(); - $manager->add($converter, 0, 'test'); - $this->assertNull($manager->apply($request, array($configuration))); - } - - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Converter 'test' does not support conversion of parameter 'param'. - */ - public function testApplyNamedConverterNotSupportsParameter() - { - $converter = $this->createParamConverterMock(); - $converter - ->expects($this->any()) - ->method('supports') - ->will($this->returnValue(false)) - ; - - $request = new Request(); - $request->attributes->set('param', '1234'); - - $configuration = new Configuration\ParamConverter(array( - 'name' => 'param', - 'class' => 'stdClass', - 'converter' => 'test', - )); - - $manager = new ParamConverterManager(); - $manager->add($converter, 0, 'test'); - $manager->apply($request, array($configuration)); - } - - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage No converter named 'test' found for conversion of parameter 'param'. - */ - public function testApplyNamedConverterNoConverter() - { - $request = new Request(); - $request->attributes->set('param', '1234'); - - $configuration = new Configuration\ParamConverter(array( - 'name' => 'param', - 'class' => 'stdClass', - 'converter' => 'test', - )); - - $manager = new ParamConverterManager(); - $manager->apply($request, array($configuration)); - } - - public function testApplyNotCalledOnAlreadyConvertedObjects() - { - $converter = $this->createParamConverterMock(); - $converter - ->expects($this->never()) - ->method('supports') - ; - - $converter - ->expects($this->never()) - ->method('apply') - ; - - $request = new Request(); - $request->attributes->set('converted', new \stdClass()); - - $configuration = new Configuration\ParamConverter(array( - 'name' => 'converted', - 'class' => 'stdClass', - )); - - $manager = new ParamConverterManager(); - $manager->add($converter); - $manager->apply($request, array($configuration)); - } - - public function testApplyWithoutArray() - { - $converter = $this->createParamConverterMock(); - $converter - ->expects($this->any()) - ->method('supports') - ->will($this->returnValue(false)) - ; - - $converter - ->expects($this->never()) - ->method('apply') - ; - - $request = new Request(); - - $configuration = new Configuration\ParamConverter(array( - 'name' => 'var', - )); - - $manager = new ParamConverterManager(); - $manager->add($converter); - $manager->apply($request, $configuration); - } - - protected function createParamConverterMock() - { - return $this->getMockBuilder(ParamConverterInterface::class)->getMock(); - } +class ParamConverterManagerTest extends UnitTestCase { + + public function testPriorities() { + $manager = new ParamConverterManager(); + $this->assertEquals([], $manager->all()); + + $high = $this->createParamConverterMock(); + $low = $this->createParamConverterMock(); + + $manager->add($low); + $manager->add($high, 10); + + $this->assertEquals([$high, $low], $manager->all()); + } + + public function testApply() { + $supported = $this->createParamConverterMock(); + $supported + ->expects($this->once()) + ->method('supports') + ->will($this->returnValue(TRUE)); + $supported + ->expects($this->once()) + ->method('apply') + ->will($this->returnValue(FALSE)); + + $invalid = $this->createParamConverterMock(); + $invalid + ->expects($this->once()) + ->method('supports') + ->will($this->returnValue(FALSE)); + $invalid + ->expects($this->never()) + ->method('apply'); + + $configurations = [ + new Configuration\ParamConverter([ + 'name' => 'var', + ]), + ]; + + $manager = new ParamConverterManager(); + $manager->add($supported); + $manager->add($invalid); + $manager->apply(new Request(), $configurations); + } + + public function testApplyNamedConverter() { + $converter = $this->createParamConverterMock(); + $converter + ->expects($this->any()) + ->method('supports') + ->will($this->returnValue(TRUE)); + + $converter + ->expects($this->any()) + ->method('apply'); + + $request = new Request(); + $request->attributes->set('param', '1234'); + + $configuration = new Configuration\ParamConverter([ + 'name' => 'param', + 'class' => 'stdClass', + 'converter' => 'test', + ]); + + $manager = new ParamConverterManager(); + $manager->add($converter, 0, 'test'); + $this->assertNull($manager->apply($request, [$configuration])); + } + + /** + * @expectedException \RuntimeException + * @expectedExceptionMessage Converter 'test' does not support conversion of parameter 'param'. + */ + public function testApplyNamedConverterNotSupportsParameter() { + $converter = $this->createParamConverterMock(); + $converter + ->expects($this->any()) + ->method('supports') + ->will($this->returnValue(FALSE)); + + $request = new Request(); + $request->attributes->set('param', '1234'); + + $configuration = new Configuration\ParamConverter([ + 'name' => 'param', + 'class' => 'stdClass', + 'converter' => 'test', + ]); + + $manager = new ParamConverterManager(); + $manager->add($converter, 0, 'test'); + $manager->apply($request, [$configuration]); + } + + /** + * @expectedException \RuntimeException + * @expectedExceptionMessage No converter named 'test' found for conversion of parameter 'param'. + */ + public function testApplyNamedConverterNoConverter() { + $request = new Request(); + $request->attributes->set('param', '1234'); + + $configuration = new Configuration\ParamConverter([ + 'name' => 'param', + 'class' => 'stdClass', + 'converter' => 'test', + ]); + + $manager = new ParamConverterManager(); + $manager->apply($request, [$configuration]); + } + + public function testApplyNotCalledOnAlreadyConvertedObjects() { + $converter = $this->createParamConverterMock(); + $converter + ->expects($this->never()) + ->method('supports'); + + $converter + ->expects($this->never()) + ->method('apply'); + + $request = new Request(); + $request->attributes->set('converted', new \stdClass()); + + $configuration = new Configuration\ParamConverter([ + 'name' => 'converted', + 'class' => 'stdClass', + ]); + + $manager = new ParamConverterManager(); + $manager->add($converter); + $manager->apply($request, [$configuration]); + } + + public function testApplyWithoutArray() { + $converter = $this->createParamConverterMock(); + $converter + ->expects($this->any()) + ->method('supports') + ->will($this->returnValue(FALSE)); + + $converter + ->expects($this->never()) + ->method('apply'); + + $request = new Request(); + + $configuration = new Configuration\ParamConverter([ + 'name' => 'var', + ]); + + $manager = new ParamConverterManager(); + $manager->add($converter); + $manager->apply($request, $configuration); + } + + protected function createParamConverterMock() { + return $this->getMockBuilder(ParamConverterInterface::class)->getMock(); + } + } diff --git a/tests/src/Unit/Routing/AnnotatedRouteControllerLoaderTest.php b/tests/src/Unit/Routing/AnnotatedRouteControllerLoaderTest.php index 69d1022..6bce74a 100644 --- a/tests/src/Unit/Routing/AnnotatedRouteControllerLoaderTest.php +++ b/tests/src/Unit/Routing/AnnotatedRouteControllerLoaderTest.php @@ -13,44 +13,44 @@ /** * @group controller_annotations */ -class AnnotatedRouteControllerLoaderTest extends UnitTestCase -{ - public function testConfigureRoute() - { - $routeConfiguration = m::mock(\Drupal\controller_annotations\Configuration\Route::class); - $routeConfiguration->shouldReceive('getService')->andReturn(false); - $routeConfiguration->shouldReceive('isAdmin')->andReturn(true); - $routeConfiguration->shouldReceive('modifyRouteMethod')->andReturnNull(); - $routeConfiguration->shouldReceive('modifyRouteClass')->andReturnNull(); - - $methodConfiguration = m::mock(Method::class); - $methodConfiguration->shouldReceive('getMethods')->andReturn(['GET']); - $methodConfiguration->shouldReceive('modifyRouteMethod')->andReturnNull(); - $methodConfiguration->shouldReceive('modifyRouteClass')->andReturnNull(); - - $reader = m::mock(Reader::class); - $reader->shouldReceive('getClassAnnotation')->andReturn($routeConfiguration); - $reader->shouldReceive('getMethodAnnotations')->andReturn([ - $routeConfiguration, - $methodConfiguration - ]); - $reader->shouldReceive('getClassAnnotations')->andReturn([]); - - $route = m::mock(Route::class); - $route->shouldReceive('setDefault')->once(); - - $reflectionClass = m::mock(\ReflectionClass::class); - $reflectionClass->shouldReceive('getName')->once()->andReturn('Controller'); - - $reflectionMethod = m::mock(\ReflectionMethod::class); - $reflectionMethod->shouldReceive('getName')->once()->andReturn('action'); - - $method = Helper::getProtectedMethod(AnnotatedRouteControllerLoader::class, 'configureRoute'); - $annotatedRouteControllerLoader = new AnnotatedRouteControllerLoader($reader); - $method->invokeArgs($annotatedRouteControllerLoader, [$route, $reflectionClass, $reflectionMethod, null]); - - $this->assertTrue(true); - - m::close(); - } +class AnnotatedRouteControllerLoaderTest extends UnitTestCase { + + public function testConfigureRoute() { + $routeConfiguration = m::mock(\Drupal\controller_annotations\Configuration\Route::class); + $routeConfiguration->shouldReceive('getService')->andReturn(FALSE); + $routeConfiguration->shouldReceive('isAdmin')->andReturn(TRUE); + $routeConfiguration->shouldReceive('modifyRouteMethod')->andReturnNull(); + $routeConfiguration->shouldReceive('modifyRouteClass')->andReturnNull(); + + $methodConfiguration = m::mock(Method::class); + $methodConfiguration->shouldReceive('getMethods')->andReturn(['GET']); + $methodConfiguration->shouldReceive('modifyRouteMethod')->andReturnNull(); + $methodConfiguration->shouldReceive('modifyRouteClass')->andReturnNull(); + + $reader = m::mock(Reader::class); + $reader->shouldReceive('getClassAnnotation')->andReturn($routeConfiguration); + $reader->shouldReceive('getMethodAnnotations')->andReturn([ + $routeConfiguration, + $methodConfiguration, + ]); + $reader->shouldReceive('getClassAnnotations')->andReturn([]); + + $route = m::mock(Route::class); + $route->shouldReceive('setDefault')->once(); + + $reflectionClass = m::mock(\ReflectionClass::class); + $reflectionClass->shouldReceive('getName')->once()->andReturn('Controller'); + + $reflectionMethod = m::mock(\ReflectionMethod::class); + $reflectionMethod->shouldReceive('getName')->once()->andReturn('action'); + + $method = Helper::getProtectedMethod(AnnotatedRouteControllerLoader::class, 'configureRoute'); + $annotatedRouteControllerLoader = new AnnotatedRouteControllerLoader($reader); + $method->invokeArgs($annotatedRouteControllerLoader, [$route, $reflectionClass, $reflectionMethod, NULL]); + + $this->assertTrue(TRUE); + + m::close(); + } + } diff --git a/tests/src/Unit/Templating/TemplateResolverTest.php b/tests/src/Unit/Templating/TemplateResolverTest.php index 8158fb7..79b9d22 100644 --- a/tests/src/Unit/Templating/TemplateResolverTest.php +++ b/tests/src/Unit/Templating/TemplateResolverTest.php @@ -5,102 +5,97 @@ use Drupal\controller_annotations\Templating\TemplateResolver; use Drupal\Tests\UnitTestCase; -require_once __DIR__.'/../../polyfill.php'; +require_once __DIR__ . '/../../polyfill.php'; /** * @group controller_annotations */ -class TemplateResolverTest extends UnitTestCase -{ - /** - * @var TemplateResolver - */ - private $templateResolver; +class TemplateResolverTest extends UnitTestCase { - public function setUp() - { - $this->templateResolver = new TemplateResolver(); - } + /** + * @var \Drupal\controller_annotations\Templating\TemplateResolver + */ + private $templateResolver; - /** - * @dataProvider controllerActionProvider - */ - public function testResolveByControllerAndAction( + public function setUp() { + $this->templateResolver = new TemplateResolver(); + } + + /** + * @dataProvider controllerActionProvider + */ + public function testResolveByControllerAndAction( + $controller, + $action, + $expected + ) { + $this->assertEquals( + $expected, + $this->templateResolver->resolveByControllerAndAction( $controller, - $action, - $expected - ) { - $this->assertEquals( - $expected, - $this->templateResolver->resolveByControllerAndAction( - $controller, - $action - ) - ); - } + $action + ) + ); + } + + /** + * @return array + */ + public function controllerActionProvider() { + $expected = 'modules/foo/templates/foo-foo-bar.html.twig'; - /** - * @return array - */ - public function controllerActionProvider() - { - $expected = 'modules/foo/templates/foo-foo-bar.html.twig'; + return [ + ['Drupal\foo\Controller\FooController', 'barAction', $expected], + ['Drupal\foo\Controller\Foo', 'barAction', $expected], + ['Drupal\foo\Controller\FooController', 'bar', $expected], + ['Drupal\foo\Controller\Foo', 'bar', $expected], + [ + 'Drupal\foo\Controller\Bar\FooController', + 'barAction', + 'modules/foo/templates/foo-bar-foo-bar.html.twig', + ], + [ + 'Drupal\foo\Controller\Foo\FooController', + 'barAction', + 'modules/foo/templates/foo-foo-foo-bar.html.twig', + ], + [ + 'Drupal\foo\Controller\Foo\FooController', + 'fooAction', + 'modules/foo/templates/foo-foo-foo-foo.html.twig', + ], + ]; + } - return [ - ['Drupal\foo\Controller\FooController', 'barAction', $expected], - ['Drupal\foo\Controller\Foo', 'barAction', $expected], - ['Drupal\foo\Controller\FooController', 'bar', $expected], - ['Drupal\foo\Controller\Foo', 'bar', $expected], - [ - 'Drupal\foo\Controller\Bar\FooController', - 'barAction', - 'modules/foo/templates/foo-bar-foo-bar.html.twig', - ], - [ - 'Drupal\foo\Controller\Foo\FooController', - 'barAction', - 'modules/foo/templates/foo-foo-foo-bar.html.twig', - ], - [ - 'Drupal\foo\Controller\Foo\FooController', - 'fooAction', - 'modules/foo/templates/foo-foo-foo-foo.html.twig', - ], - ]; - } + /** + * @dataProvider normalizeProvider + */ + public function testNormalize($template, $expected) { + $this->assertEquals( + $expected, + $this->templateResolver->normalize($template) + ); + } - /** - * @dataProvider normalizeProvider - */ - public function testNormalize($template, $expected) - { - $this->assertEquals( - $expected, - $this->templateResolver->normalize($template) - ); - } + /** + * @return array + */ + public function normalizeProvider() { + return [ + ['foo:bar', 'modules/foo/templates/foo-bar.html.twig'], + ['foobar:baz', 'modules/foobar/templates/foobar-baz.html.twig'], + ['foo:bar:baz', 'modules/foo/templates/foo-bar-baz.html.twig'], + ]; + } - /** - * @return array - */ - public function normalizeProvider() - { - return [ - ['foo:bar', 'modules/foo/templates/foo-bar.html.twig'], - ['foobar:baz', 'modules/foobar/templates/foobar-baz.html.twig'], - ['foo:bar:baz', 'modules/foo/templates/foo-bar-baz.html.twig'], - ]; - } + public function testNormalizeWithInvalidTemplate() { + $this->setExpectedException(\InvalidArgumentException::class); + $this->templateResolver->normalize('foo'); + } - public function testNormalizeWithInvalidTemplate() - { - $this->setExpectedException(\InvalidArgumentException::class); - $this->templateResolver->normalize('foo'); - } + public function testResolveByControllerAndActionWithInvalidController() { + $this->setExpectedException(\InvalidArgumentException::class); + $this->templateResolver->resolveByControllerAndAction('Foo', 'fooAction'); + } - public function testResolveByControllerAndActionWithInvalidController() - { - $this->setExpectedException(\InvalidArgumentException::class); - $this->templateResolver->resolveByControllerAndAction('Foo', 'fooAction'); - } } diff --git a/tests/src/polyfill.php b/tests/src/polyfill.php index 1134fd7..d262810 100644 --- a/tests/src/polyfill.php +++ b/tests/src/polyfill.php @@ -1,15 +1,16 @@ <?php if (!function_exists('drupal_get_path')) { - function drupal_get_path($type, $name) - { - switch ($type) { - case 'module': - return 'modules/'.$name; - } - - throw new \LogicException( - sprintf('Type "%s" not implemented by this polyfill method', $type) - ); + + function drupal_get_path($type, $name) { + switch ($type) { + case 'module': + return 'modules/' . $name; } + + throw new \LogicException( + sprintf('Type "%s" not implemented by this polyfill method', $type) + ); + } + }