diff --git a/composer.json b/composer.json index b9431e1..8277c40 100644 --- a/composer.json +++ b/composer.json @@ -27,9 +27,9 @@ "bin": ["bin/wave"], "require": { - "php": ">=7.4", - "twig/twig": "1.*", - "monolog/monolog": "1.*", + "php": ">=8.1", + "twig/twig": "3.*", + "monolog/monolog": "2.*", "dragonmantank/cron-expression": "^3.3" }, diff --git a/src/Wave/Annotation.php b/src/Wave/Annotation.php index 4d9a301..4d92d95 100755 --- a/src/Wave/Annotation.php +++ b/src/Wave/Annotation.php @@ -12,7 +12,8 @@ use Wave\Annotation\Validate; use Wave\DB\Model; -class Annotation { +class Annotation +{ const FOR_CLASS = 'class'; @@ -33,19 +34,21 @@ class Annotation { 'schedule' => Schedule::class, ); - public static function factory($key, $value, $from_class = null){ + public static function factory($key, $value, $from_class = null) + { $class = __CLASS__; - if(isset(self::$handlers[$key])){ + if (isset(self::$handlers[$key])) { $class = self::$handlers[$key]; } return new $class($key, $value, $from_class); } - public static function parse($block, $originating_class){ + public static function parse($block, $originating_class) + { - if(empty($block)) return array(); + if (empty($block)) return array(); $block = self::sanitizeDocBlock($block); @@ -68,34 +71,41 @@ public static function parse($block, $originating_class){ * @param $docblock * @return mixed */ - protected static function sanitizeDocBlock($docblock){ + protected static function sanitizeDocBlock($docblock) + { return preg_replace('/^([\t\f ]*\*[\t\f ]+)/m', '', $docblock); } - public function __construct($key, $value, $from_class = null) { + public function __construct($key, $value, $from_class = null) + { $this->key = $key; $this->value = $value; $this->from_class = $from_class; } - public function apply(Router\Action &$action){} + public function apply(Router\Action &$action) + { + } /** * @return mixed */ - public function getKey() { + public function getKey() + { return $this->key; } /** * @return mixed */ - public function getValue() { + public function getValue() + { return $this->value; } - protected function validOnSubclassesOf($annotatedClass, $baseClass) { - if( $annotatedClass != $baseClass && !is_subclass_of($annotatedClass, $baseClass) ) + protected function validOnSubclassesOf($annotatedClass, $baseClass) + { + if ($annotatedClass != $baseClass && !is_subclass_of($annotatedClass, $baseClass)) throw new InvalidAnnotationException(get_class($this) . " is only valid on objects of type {$baseClass}."); } diff --git a/src/Wave/Annotation/ArrayArguments.php b/src/Wave/Annotation/ArrayArguments.php index 8474326..7518284 100644 --- a/src/Wave/Annotation/ArrayArguments.php +++ b/src/Wave/Annotation/ArrayArguments.php @@ -1,44 +1,50 @@ parameters = $this->parseParameters(); $this->validate($from_class); - if(!empty($this->errors)){ - throw new InvalidAnnotationException('Annotation format error, '.implode(', ', $this->errors), 0); + if (!empty($this->errors)) { + throw new InvalidAnnotationException('Annotation format error, ' . implode(', ', $this->errors), 0); } $this->build(); } - protected function validate($class){} - protected function build(){} + protected function validate($class) + { + } - protected function parseParameters(){ + protected function build() + { + } + + protected function parseParameters() + { $arguments = array(); - foreach(explode(',', $this->value) as $argument){ + foreach (explode(',', $this->value) as $argument) { // attempt to explode the argument into a key:value list($k, $value) = explode(':', $argument) + array(null, null); // no value means it was just a plain argument, so just clean it and insert as normal $k = trim($k, ' \'"'); - if($value === null){ + if ($value === null) { $arguments[] = $k; - } - else { + } else { $arguments[strtolower($k)] = trim($value, ' \'"'); } } @@ -47,61 +53,70 @@ protected function parseParameters(){ } - protected function acceptedKeys($keys) { - foreach($this->parameters as $key => $value) { + protected function acceptedKeys($keys) + { + foreach ($this->parameters as $key => $value) { if (is_string($key) && !in_array($key, $keys)) { $this->errors[] = "Invalid parameter: \"$key\"."; } } } - protected function requiredKeys($keys) { - foreach($keys as $key) { - if(!array_key_exists($key, $this->parameters)) { + protected function requiredKeys($keys) + { + foreach ($keys as $key) { + if (!array_key_exists($key, $this->parameters)) { $this->errors[] = get_class($this) . " requires a '$key' parameter."; } } } - protected function acceptedKeylessValues($values) { - foreach($this->parameters as $key => $value) { - if(!is_string($key) && !in_array($value, $values)) { + protected function acceptedKeylessValues($values) + { + foreach ($this->parameters as $key => $value) { + if (!is_string($key) && !in_array($value, $values)) { $this->errors[] = "Unknown parameter: \"$value\"."; } } } - protected function acceptedIndexedValues($index, $values, $optional = true) { - if($optional && !isset($this->parameters[$index])) return; + protected function acceptedIndexedValues($index, $values, $optional = true) + { + if ($optional && !isset($this->parameters[$index])) return; - if(!in_array($this->parameters[$index],$values)) { + if (!in_array($this->parameters[$index], $values)) { $this->errors[] = "Parameter $index is set to \"" . $this->parameters[$index] . "\". Valid values: " . implode(', ', $values) . '.'; } } - protected function acceptsNoKeylessValues() { + protected function acceptsNoKeylessValues() + { $this->acceptedKeylessValues(array()); } - protected function acceptsNoKeyedValues() { + protected function acceptsNoKeyedValues() + { $this->acceptedKeys(array()); } - protected function minimumParameterCount($count) { - if( ! (count($this->parameters) >= $count) ) { + protected function minimumParameterCount($count) + { + if (!(count($this->parameters) >= $count)) { $this->errors[] = get_class($this) . " takes at least $count parameters."; } } - protected function maximumParameterCount($count) { - if( ! (count($this->parameters) <= $count) ) { + protected function maximumParameterCount($count) + { + if (!(count($this->parameters) <= $count)) { $this->errors[] = get_class($this) . " takes at most $count parameters."; } } - protected function exactParameterCount($count) { - if ( count($this->parameters) != $count ) { + protected function exactParameterCount($count) + { + if (count($this->parameters) != $count) { $this->errors[] = get_class($this) . " requires exactly $count parameters."; } } diff --git a/src/Wave/Annotation/BaseRoute.php b/src/Wave/Annotation/BaseRoute.php index 881530d..0fbbc3a 100755 --- a/src/Wave/Annotation/BaseRoute.php +++ b/src/Wave/Annotation/BaseRoute.php @@ -6,15 +6,18 @@ use Wave\Annotation; use Wave\Router\Action; -class BaseRoute extends ArrayArguments { - - protected function validate($class) { +class BaseRoute extends ArrayArguments +{ + + protected function validate($class) + { $this->minimumParameterCount(1); $this->maximumParameterCount(1); $this->validOnSubclassesOf($class, Annotation::CLASS_CONTROLLER); } - public function apply(Action &$action) { + public function apply(Action &$action) + { $action->addBaseRoute($this->parameters[0]); } diff --git a/src/Wave/Annotation/BaseURL.php b/src/Wave/Annotation/BaseURL.php index c1a8934..49c895a 100755 --- a/src/Wave/Annotation/BaseURL.php +++ b/src/Wave/Annotation/BaseURL.php @@ -6,18 +6,21 @@ use Wave\Annotation; use Wave\Router\Action; -class BaseURL extends ArrayArguments { - - const DEFAULT_KEYWORD = 'default'; - - public function validate($class) { - $this->minimumParameterCount(1); - $this->maximumParameterCount(1); - $this->validOnSubclassesOf($class, Annotation::CLASS_CONTROLLER); - } - - public function apply(Action &$action) { - $action->setProfile($this->parameters[0]); - } +class BaseURL extends ArrayArguments +{ + + const DEFAULT_KEYWORD = 'default'; + + public function validate($class) + { + $this->minimumParameterCount(1); + $this->maximumParameterCount(1); + $this->validOnSubclassesOf($class, Annotation::CLASS_CONTROLLER); + } + + public function apply(Action &$action) + { + $action->setProfile($this->parameters[0]); + } } diff --git a/src/Wave/Annotation/InvalidAnnotationException.php b/src/Wave/Annotation/InvalidAnnotationException.php index 47a3231..57fff02 100644 --- a/src/Wave/Annotation/InvalidAnnotationException.php +++ b/src/Wave/Annotation/InvalidAnnotationException.php @@ -6,4 +6,6 @@ use Wave\Exception; -class InvalidAnnotationException extends Exception {} \ No newline at end of file +class InvalidAnnotationException extends Exception +{ +} \ No newline at end of file diff --git a/src/Wave/Annotation/RequiresLevel.php b/src/Wave/Annotation/RequiresLevel.php index 9051750..fa9fe59 100755 --- a/src/Wave/Annotation/RequiresLevel.php +++ b/src/Wave/Annotation/RequiresLevel.php @@ -6,26 +6,30 @@ use Wave\Annotation; use Wave\Router\Action; -class RequiresLevel extends ArrayArguments { - - const DEFAULT_KEYWORD = 'default'; - - public function validate($class) { - $this->minimumParameterCount(1); - $this->validOnSubclassesOf($class, Annotation::CLASS_CONTROLLER); - } - - public function build(){ - $this->inherit = true; - if(isset($this->parameters['inherit'])){ - $this->inherit = $this->parameters['inherit'] == 'true'; - unset($this->parameters['inherit']); - } - $this->methods = $this->parameters; - } - - public function apply(Action &$action){ - return $action->setRequiresLevel($this->methods, $this->inherit); - } +class RequiresLevel extends ArrayArguments +{ + + const DEFAULT_KEYWORD = 'default'; + + public function validate($class) + { + $this->minimumParameterCount(1); + $this->validOnSubclassesOf($class, Annotation::CLASS_CONTROLLER); + } + + public function build() + { + $this->inherit = true; + if (isset($this->parameters['inherit'])) { + $this->inherit = $this->parameters['inherit'] == 'true'; + unset($this->parameters['inherit']); + } + $this->methods = $this->parameters; + } + + public function apply(Action &$action) + { + return $action->setRequiresLevel($this->methods, $this->inherit); + } } diff --git a/src/Wave/Annotation/RespondsWith.php b/src/Wave/Annotation/RespondsWith.php index 2ec6dcc..94c36c6 100755 --- a/src/Wave/Annotation/RespondsWith.php +++ b/src/Wave/Annotation/RespondsWith.php @@ -6,28 +6,32 @@ use Wave\Http\Response; use Wave\Router\Action; -class RespondsWith extends ArrayArguments { - - public $inherit = true; - public $methods = array(); - - public function validate($class) { - $this->minimumParameterCount(1); - $this->validOnSubclassesOf($class, Annotation::CLASS_CONTROLLER); - } - - - public function build(){ - $this->inherit = false; - if(isset($this->parameters['inherit'])){ - $this->inherit = $this->parameters['inherit'] == 'true'; - unset($this->parameters['inherit']); - } - - $this->methods = $this->parameters; - } - - public function apply(Action &$action){ - $action->setRespondsWith($this->methods, $this->inherit); - } +class RespondsWith extends ArrayArguments +{ + + public $inherit = true; + public $methods = array(); + + public function validate($class) + { + $this->minimumParameterCount(1); + $this->validOnSubclassesOf($class, Annotation::CLASS_CONTROLLER); + } + + + public function build() + { + $this->inherit = false; + if (isset($this->parameters['inherit'])) { + $this->inherit = $this->parameters['inherit'] == 'true'; + unset($this->parameters['inherit']); + } + + $this->methods = $this->parameters; + } + + public function apply(Action &$action) + { + $action->setRespondsWith($this->methods, $this->inherit); + } } \ No newline at end of file diff --git a/src/Wave/Annotation/Route.php b/src/Wave/Annotation/Route.php index b2e0f57..2c1bf31 100755 --- a/src/Wave/Annotation/Route.php +++ b/src/Wave/Annotation/Route.php @@ -5,24 +5,28 @@ use Wave\Annotation; use Wave\Router\Action; -class Route extends ArrayArguments { +class Route extends ArrayArguments +{ protected $methods; protected $url; - public function validate($class) { - $this->minimumParameterCount(2); - $this->maximumParameterCount(2); - $this->validOnSubclassesOf($class, Annotation::CLASS_CONTROLLER); - } - - public function build(){ - $this->methods = explode('|', $this->parameters[0]); - $this->url = $this->parameters[1]; - } - - public function apply(Action &$action){ - $action->addRoute($this->methods, $this->url); - } - + public function validate($class) + { + $this->minimumParameterCount(2); + $this->maximumParameterCount(2); + $this->validOnSubclassesOf($class, Annotation::CLASS_CONTROLLER); + } + + public function build() + { + $this->methods = explode('|', $this->parameters[0]); + $this->url = $this->parameters[1]; + } + + public function apply(Action &$action) + { + $action->addRoute($this->methods, $this->url); + } + } diff --git a/src/Wave/Annotation/Validate.php b/src/Wave/Annotation/Validate.php index a8e720d..0e083b8 100644 --- a/src/Wave/Annotation/Validate.php +++ b/src/Wave/Annotation/Validate.php @@ -5,20 +5,24 @@ use Wave\Annotation; use Wave\Router\Action; -class Validate extends ArrayArguments { +class Validate extends ArrayArguments +{ private $schema; - public function validate($class) { + public function validate($class) + { $this->exactParameterCount(1); $this->validOnSubclassesOf($class, Annotation::CLASS_CONTROLLER); } - public function build(){ + public function build() + { $this->schema = $this->parameters[0]; } - public function apply(Action &$action){ + public function apply(Action &$action) + { $action->setValidationSchema($this->schema); } diff --git a/src/Wave/Auth.php b/src/Wave/Auth.php index 9958c87..857930a 100644 --- a/src/Wave/Auth.php +++ b/src/Wave/Auth.php @@ -5,7 +5,8 @@ use Wave\Config; use Wave\Storage\Cookie; -class Auth { +class Auth +{ const SUCCESS = 'success'; const FAILURE_NO_IDENTITY = 'no-identity'; @@ -21,11 +22,12 @@ class Auth { public static $_is_loaded = false; - public static function registerHandler($class, $autoload = true) { - if(!class_implements($class)) + public static function registerHandler($class, $autoload = true) + { + if (!class_implements($class)) throw new \Wave\Exception('Auth Handler class (' . $class . ') must implement \Wave\IAuthable'); - if($autoload) $class::loadPersistentAuth(); + if ($autoload) $class::loadPersistentAuth(); self::$_handler = $class; @@ -34,16 +36,17 @@ public static function registerHandler($class, $autoload = true) { } - public static function checkIdentity($primary, $secondary) { + public static function checkIdentity($primary, $secondary) + { $class = self::$_handler; $auth_object = $class::loadByIdentifier($primary); - if($auth_object instanceof IAuthable) { + if ($auth_object instanceof IAuthable) { $_is_valid = true; // check the secondary credentials - foreach($secondary as $key => $value) { - if((is_callable($value) && $value($auth_object->$key)) + foreach ($secondary as $key => $value) { + if ((is_callable($value) && $value($auth_object->$key)) || (isset($auth_object->$key) && $auth_object->$key == $value) ) continue; @@ -56,7 +59,7 @@ public static function checkIdentity($primary, $secondary) { $_is_valid = false; } - if($_is_valid) { + if ($_is_valid) { self::$_valid_auth = $auth_object; self::registerIdentity($auth_object); return self::SUCCESS; @@ -69,22 +72,25 @@ public static function checkIdentity($primary, $secondary) { } } - public static function registerIdentity($identity) { + public static function registerIdentity($identity) + { return Registry::store('__wave_identity', $identity); } - public static function deregisterIdentity() { + public static function deregisterIdentity() + { return Registry::destroy('__wave_identity'); } - public static function persistIdentity($identity, $type = null, $expires = null) { + public static function persistIdentity($identity, $type = null, $expires = null) + { $config = Config::get('deploy')->auth; - if($type === null) + if ($type === null) $type = $config->persist_type; - if($expires === null) + if ($expires === null) $expires = $config->$type->expires; - if($type == 'cookie') { + if ($type == 'cookie') { Cookie::store( $config->cookie->name, @@ -100,12 +106,13 @@ public static function persistIdentity($identity, $type = null, $expires = null) } - public static function ceaseIdentity($type = null) { + public static function ceaseIdentity($type = null) + { $config = Config::get('deploy')->auth; - if($type === null) + if ($type === null) $type = $config->persist_type; - if($type == 'cookie') { + if ($type == 'cookie') { Cookie::store( $config->cookie->name, @@ -119,15 +126,18 @@ public static function ceaseIdentity($type = null) { } - public static function getAuthProblems() { + public static function getAuthProblems() + { return self::$_auth_problems; } - public static function getIdentity() { + public static function getIdentity() + { return Registry::fetch('__wave_identity'); } - public static function getHandlerClass() { + public static function getHandlerClass() + { return self::$_handler; } diff --git a/src/Wave/Cache.php b/src/Wave/Cache.php index 2261d3b..8f9f080 100644 --- a/src/Wave/Cache.php +++ b/src/Wave/Cache.php @@ -2,40 +2,46 @@ namespace Wave; -class Cache { +class Cache +{ private static $_ready = false; private static $_cachepath = null; - public static function init() { + public static function init() + { self::$_cachepath = Config::get('wave')->path->cache; self::$_ready = true; } - public static function load($key) { + public static function load($key) + { $filename = self::$_cachepath . $key; - if(file_exists($filename)) + if (file_exists($filename)) return unserialize(file_get_contents(self::$_cachepath . $key)); else return null; } - public static function store($key, $data) { + public static function store($key, $data) + { $path = self::$_cachepath . $key; $dir = dirname($path); - if(!is_dir($dir)) + if (!is_dir($dir)) @mkdir($dir, 0770, true); file_put_contents($path, serialize($data)); } - public static function delete($key) { + public static function delete($key) + { @unlink(self::$_cachepath . $key); } - public static function cachetime($key) { + public static function cachetime($key) + { $filename = self::$_cachepath . $key; - if(file_exists($filename)) + if (file_exists($filename)) return filemtime(self::$_cachepath . $key); else return 0; diff --git a/src/Wave/Config.php b/src/Wave/Config.php index 1fa0f73..34711a4 100644 --- a/src/Wave/Config.php +++ b/src/Wave/Config.php @@ -4,7 +4,8 @@ use Wave\Config\Row; -class Config { +class Config +{ private static $base_directory = null; @@ -12,26 +13,30 @@ class Config { private $_data = false; - public static function init($base_path) { - if(!is_readable($base_path)) { + public static function init($base_path) + { + if (!is_readable($base_path)) { throw new \Wave\Exception('Base config directory ' . $base_path . ' is not readable'); } self::$base_directory = $base_path; } - public function __construct($namespace) { + public function __construct($namespace) + { $config_data = call_user_func(self::$resolver, $namespace); $this->_data = new Row($config_data); } - public function __get($offset) { + public function __get($offset) + { return $this->_data->{$offset}; } - public function offsetExists($offset){ + public function offsetExists($offset) + { return isset($this->_data->{$offset}); } @@ -39,22 +44,25 @@ public function offsetExists($offset){ * @param $namespace * @return $this */ - public static function get($namespace) { + public static function get($namespace) + { static $configs; - if(!isset($configs[$namespace])) { + if (!isset($configs[$namespace])) { $configs[$namespace] = new self($namespace); } return $configs[$namespace]; } - public static function setResolver(callable $resolver) { + public static function setResolver(callable $resolver) + { self::$resolver = $resolver; } - public static function defaultResolver($namespace) { + public static function defaultResolver($namespace) + { $file_path = self::$base_directory . "/$namespace.php"; - if(!is_readable($file_path)) + if (!is_readable($file_path)) throw new \Wave\Exception("Could not load configuration file $namespace. Looked in $file_path"); return include $file_path; diff --git a/src/Wave/Config/Row.php b/src/Wave/Config/Row.php index d8e3af4..5bfe6db 100644 --- a/src/Wave/Config/Row.php +++ b/src/Wave/Config/Row.php @@ -4,12 +4,14 @@ use ArrayObject; -class Row extends ArrayObject { +class Row extends ArrayObject +{ - public function __construct(array $config) { + public function __construct(array $config) + { - foreach($config as $key => $value) { - if(is_array($value)) { + foreach ($config as $key => $value) { + if (is_array($value)) { $value = new static($value); } $this->offsetSet($key, $value); @@ -17,22 +19,25 @@ public function __construct(array $config) { } - public function __get($property) { - if(isset($this[$property])) { + public function __get($property) + { + if (isset($this[$property])) { return $this[$property]; } throw new UnknownConfigOptionException("Unknown config option [$property]"); } - public function __isset($property) { + public function __isset($property) + { return isset($this[$property]); } - public function getArrayCopy() { + public function getArrayCopy(): array + { $self = parent::getArrayCopy(); - foreach($self as $key => $value){ - if($value instanceof Row){ + foreach ($self as $key => $value) { + if ($value instanceof Row) { $self[$key] = $value->getArrayCopy(); } } diff --git a/src/Wave/Config/UnknownConfigOptionException.php b/src/Wave/Config/UnknownConfigOptionException.php index c2f5e6b..5d3769b 100644 --- a/src/Wave/Config/UnknownConfigOptionException.php +++ b/src/Wave/Config/UnknownConfigOptionException.php @@ -5,7 +5,8 @@ use Exception; -class UnknownConfigOptionException extends Exception { +class UnknownConfigOptionException extends Exception +{ } ; \ No newline at end of file diff --git a/src/Wave/Controller.php b/src/Wave/Controller.php index 9894f07..001071c 100644 --- a/src/Wave/Controller.php +++ b/src/Wave/Controller.php @@ -12,7 +12,8 @@ use Wave\Router\Action; use Wave\Validator\Exception\InvalidInputException; -class Controller { +class Controller +{ const RETURN_FORMAT_REQUEST = 'request'; const RETURN_FORMAT_RESPOND = 'respond'; @@ -53,20 +54,21 @@ class Controller { * @param array $data * @param int $invoke_type * + * @return Http\Response * @throws Http\Exception\UnauthorizedException * @throws Http\Exception\NotFoundException * @throws Exception * @throws Http\Exception\ForbiddenException - * @return Http\Response * @throws Http\Exception\ForbiddenException */ - public static final function invoke(Action $action, Request $request, $data = array(), $invoke_type = self::INVOKE_NORMAL) { + public static final function invoke(Action $action, Request $request, $data = array(), $invoke_type = self::INVOKE_NORMAL) + { list($controller_class, $action_method) = explode('.', $action->getAction(), 2) + array(null, null); - if(!isset($action_method)) + if (!isset($action_method)) $action_method = Config::get('wave')->controller->default_method; - if(class_exists($controller_class, true) && method_exists($controller_class, $action_method)) { + if (class_exists($controller_class, true) && method_exists($controller_class, $action_method)) { /** @var \Wave\Controller $controller */ $controller = new $controller_class(); @@ -76,7 +78,7 @@ public static final function invoke(Action $action, Request $request, $data = ar $controller->_response_method = $request->getFormat(); $controller->_invoke_method = $invoke_type; - switch($controller->_request->getMethod()) { + switch ($controller->_request->getMethod()) { case Request::METHOD_GET: $controller->_is_get = true; break; @@ -90,33 +92,33 @@ public static final function invoke(Action $action, Request $request, $data = ar Hook::triggerAction('controller.before_init', array(&$controller)); $controller->init(); - if($invoke_type !== self::INVOKE_SUB_REQUEST && !$action->canRespondWith($request->getFormat())) { + if ($invoke_type !== self::INVOKE_SUB_REQUEST && !$action->canRespondWith($request->getFormat())) { throw new NotFoundException( 'The requested action ' . $action->getAction() . ' can not respond with ' . $request->getFormat() . '. (Accepts: ' . implode(', ', $action->getRespondsWith()) . ')', $request ); - } else if(!$action->checkRequiredLevel($request)) { + } else if (!$action->checkRequiredLevel($request)) { throw new UnauthorizedException('You are not authorized to view this resource'); - } else if($action->needsValidation() && !$controller->inputValid($action->getValidationSchema($data))) { + } else if ($action->needsValidation() && !$controller->inputValid($action->getValidationSchema($data))) { return $controller->request(); } Hook::triggerAction('controller.before_dispatch', array(&$controller)); $parameters = array(); - foreach($action->getMethodParameters() as $parameter){ + foreach ($action->getMethodParameters() as $parameter) { list($parameter_name, $parameter_type) = $parameter; - if(isset($controller->_cleaned[$parameter_name])){ + if (isset($controller->_cleaned[$parameter_name])) { //Try first in validator output $parameters[] = $controller->_cleaned[$parameter_name]; - } elseif(isset($controller->_data[$parameter_name])){ + } elseif (isset($controller->_data[$parameter_name])) { //Then if just using the passed data - there may be a legitimate use for this? $parameters[] = $controller->_data[$parameter_name]; - } elseif($parameter_type === 'Wave\\Validator\\Result'){ + } elseif ($parameter_type === 'Wave\\Validator\\Result') { //If the validator is requested, give it $parameters[] = $controller->_cleaned; - }elseif($parameter_type === get_class($request)){ + } elseif ($parameter_type === get_class($request)) { //If the request is requested, give it $parameters[] = $request; } else { @@ -127,7 +129,7 @@ public static final function invoke(Action $action, Request $request, $data = ar try { $response = call_user_func_array(array($controller, $action_method), $parameters); - } catch(InvalidInputException $e) { + } catch (InvalidInputException $e) { $controller->_input_errors = $e->getViolations(); $response = $controller->request(); } @@ -140,22 +142,27 @@ public static final function invoke(Action $action, Request $request, $data = ar } - public function __construct() { + public function __construct() + { $this->_post =& $_POST; $this->_get =& $_GET; $this->_identity = \Wave\Auth::getIdentity(); } - public function _setResponseMethod($method) { + public function _setResponseMethod($method) + { $this->_response_method = $method; } - public function _getResponseMethod() { + public function _getResponseMethod() + { return $this->_response_method; } - public function init() {} + public function init() + { + } /** * Use the Wave Validator to check form input. If errors exist, the offending @@ -165,24 +172,25 @@ public function init() {} * @param $data - [optional] Supply a data array to use for validation * @return Boolean true for no errors, or false. */ - protected function inputValid($schema, $data = null) { - if($data === null) + protected function inputValid($schema, $data = null) + { + if ($data === null) $data = $this->_data; try { $output = Validator::validate($schema, $data); $this->_cleaned = $output; return true; - } - catch(InvalidInputException $e) { + } catch (InvalidInputException $e) { $this->_input_errors = $e->getViolations(); } return false; } - protected function _buildPayload($status, $message = '', $payload = null) { - if($payload === null) + protected function _buildPayload($status, $message = '', $payload = null) + { + if ($payload === null) $payload = $this->_getResponseProperties(); return array( @@ -192,16 +200,18 @@ protected function _buildPayload($status, $message = '', $payload = null) { ); } - protected function _buildDataSet() { + protected function _buildDataSet() + { $this->_setTemplatingGlobals(); $properties = $this->_getResponseProperties(); return array_merge($properties); } - protected function _getResponseProperties() { + protected function _getResponseProperties() + { $payload = array(); - foreach($this as $key => $val) { - if($key[0] === '_') { + foreach ($this as $key => $val) { + if ($key[0] === '_') { continue; } $payload[$key] = $val; @@ -209,49 +219,51 @@ protected function _getResponseProperties() { return $payload; } - protected function _setTemplatingGlobals() { + protected function _setTemplatingGlobals() + { View::registerGlobal('input', isset($this->_sanitized) ? $this->_sanitized : $this->_data); View::registerGlobal('errors', isset($this->_input_errors) ? $this->_input_errors : array()); View::registerGlobal('_identity', $this->_identity); } - protected function respond($payload = null) { - if($this->_invoke_method === self::INVOKE_SUB_REQUEST) { - if($payload !== null) { + protected function respond($payload = null) + { + if ($this->_invoke_method === self::INVOKE_SUB_REQUEST) { + if ($payload !== null) { return $payload; - } - else { + } else { return $this->_getResponseProperties(); } - } - else { + } else { $callable = $this->getResponseMethodHandler(self::RETURN_FORMAT_RESPOND); return call_user_func($callable, $payload); } } - protected function request($payload = null) { - if($this->_invoke_method === self::INVOKE_SUB_REQUEST) { - if($payload === null) { + protected function request($payload = null) + { + if ($this->_invoke_method === self::INVOKE_SUB_REQUEST) { + if ($payload === null) { $payload = isset($this->_input_errors) ? $this->_input_errors : array(); } return array('errors' => $payload); - } - else { + } else { $callable = $this->getResponseMethodHandler(self::RETURN_FORMAT_REQUEST); return call_user_func($callable, $payload); } } - protected function requestHTML() { - if(isset($this->_request_template)) { + protected function requestHTML() + { + if (isset($this->_request_template)) { $this->_template = $this->_request_template; } return $this->respondHTML(); } - protected function respondHTML() { - if(!isset($this->_template)) { + protected function respondHTML() + { + if (!isset($this->_template)) { throw new Exception( "Template not set for {$this->_response_method} in action {$this->_action->getAction()}"); } @@ -263,15 +275,17 @@ protected function respondHTML() { return new HtmlResponse($content); } - protected function requestDialog() { - if(isset($this->_request_template)) + protected function requestDialog() + { + if (isset($this->_request_template)) $this->_template = $this->_request_template; return $this->respondDialog(); } - protected function respondDialog() { - if(!isset($this->_template)) { + protected function respondDialog() + { + if (!isset($this->_template)) { throw new Exception( "Template not set for {$this->_response_method} in action {$this->_action->getAction()}"); } @@ -285,25 +299,27 @@ protected function respondDialog() { return $this->respondJSON(array('html' => $html)); } - protected function requestJSON($payload = null) { - if(!isset($this->_status)) { + protected function requestJSON($payload = null) + { + if (!isset($this->_status)) { $this->_status = Response::STATUS_BAD_REQUEST; } - if(!isset($this->_message)) { + if (!isset($this->_message)) { $this->_message = 'Invalid request or parameters'; } - if($payload === null) { + if ($payload === null) { $payload = array('errors' => isset($this->_input_errors) ? $this->_input_errors : array()); } return $this->respondJSON($payload); } - protected function respondJSON($payload = null) { - if(!isset($this->_status)) { + protected function respondJSON($payload = null) + { + if (!isset($this->_status)) { $this->_status = Response::STATUS_OK; } - if(!isset($this->_message)) { + if (!isset($this->_message)) { $this->_message = Response::getMessageForCode($this->_status); } @@ -314,31 +330,34 @@ protected function respondJSON($payload = null) { return new JsonResponse($payload, $this->_status); } - protected function respondXML($payload = null) { - if(!isset($this->_status)) { + protected function respondXML($payload = null) + { + if (!isset($this->_status)) { $this->_status = Response::STATUS_OK; } - if(!isset($this->_message)) { + if (!isset($this->_message)) { $this->_message = Response::getMessageForCode($this->_status); } return new XmlResponse($this->_buildPayload($this->_status, $this->_message, $payload)); } - protected function requestXML($payload = null) { - if(!isset($this->_status)) { + protected function requestXML($payload = null) + { + if (!isset($this->_status)) { $this->_status = Response::STATUS_BAD_REQUEST; } - if(!isset($this->_message)) { + if (!isset($this->_message)) { $this->_message = Response::getMessageForCode($this->_status); } return $this->respondXML($payload); } - private function getResponseMethodHandler($type) { + private function getResponseMethodHandler($type) + { $response_method = $type . strtoupper($this->_response_method); - if(method_exists($this, $response_method) && $response_method !== $type) + if (method_exists($this, $response_method) && $response_method !== $type) return [$this, $response_method]; else throw new Exception( diff --git a/src/Wave/Core.php b/src/Wave/Core.php index d672c3d..1917a5d 100644 --- a/src/Wave/Core.php +++ b/src/Wave/Core.php @@ -2,7 +2,8 @@ namespace Wave; -class Core { +class Core +{ const MODE_TEST = 'test'; const MODE_DEVELOPMENT = 'development'; @@ -10,14 +11,16 @@ class Core { static $_MODE = self::MODE_PRODUCTION; - public static function setErrorReporting($display = false) { + public static function setErrorReporting($display = false) + { error_reporting($display ? E_ALL | E_STRICT : E_ALL & ~E_DEPRECATED); ini_set('display_errors', $display ? '1' : '0'); } - public static function bootstrap(array $config) { + public static function bootstrap(array $config) + { - if(!isset($config['mode'])) + if (!isset($config['mode'])) $config['mode'] = Config::get('deploy')->mode; Debug::init($config['debug']); diff --git a/src/Wave/DB.php b/src/Wave/DB.php index 535b5e6..501a27d 100755 --- a/src/Wave/DB.php +++ b/src/Wave/DB.php @@ -15,7 +15,8 @@ use Wave\DB\Model; use Wave\DB\Query; -class DB { +class DB +{ /** @var DB[] $instances */ private static $instances = array(); @@ -56,7 +57,8 @@ class DB { * @param $config * @throws DBException */ - private function __construct($namespace, $config) { + private function __construct($namespace, $config) + { $installed_drivers = DB\Connection::getAvailableDrivers(); $this->namespace = $namespace; @@ -77,13 +79,12 @@ private function __construct($namespace, $config) { throw new DBException("Invalid database configuration - at minimum, a 'primary' configuration must be specified"); } - foreach ($connections as $alias => $conf) - { + foreach ($connections as $alias => $conf) { /** @var DB\Driver\DriverInterface $driver_class */ $driver_class = self::getDriverClass($conf->driver); // Check PDO driver is installed on system - if(!in_array($driver_class::getDriverName(), $installed_drivers)) + if (!in_array($driver_class::getDriverName(), $installed_drivers)) throw new DBException(sprintf('PDO::%s driver not installed for %s.', $driver_class::getDriverName(), $driver_class)); // Use the primary connection for default configuration @@ -104,7 +105,8 @@ private function __construct($namespace, $config) { * @return DB * @throws DB\Exception */ - private static function init($namespace, $database) { + private static function init($namespace, $database) + { $instance = new self($namespace, $database); Hook::triggerAction('db.after_init', array(&$instance)); @@ -112,20 +114,21 @@ private static function init($namespace, $database) { } - public static function getConfigForNamespace($namespace) { + public static function getConfigForNamespace($namespace) + { $databases = Config::get('db')->databases; - if(!isset($databases[$namespace])) { + if (!isset($databases[$namespace])) { throw new DBException("There is no database configuration for {$namespace}"); } - if(isset($databases[$namespace][Core::$_MODE])) + if (isset($databases[$namespace][Core::$_MODE])) $mode = Core::$_MODE; else $mode = Core::MODE_PRODUCTION; - if(!isset($databases[$namespace][$mode])) { + if (!isset($databases[$namespace][$mode])) { throw new DBException('There must be at least a PRODUCTION database defined'); } @@ -141,17 +144,18 @@ public static function getConfigForNamespace($namespace) { * @return DB * @throws Exception */ - public static function get($namespace = null) { + public static function get($namespace = null) + { - if($namespace === null) { + if ($namespace === null) { - if(!isset(self::$default_namespace)) + if (!isset(self::$default_namespace)) self::$default_namespace = self::getDefaultNamespace(); $namespace = self::$default_namespace; } - if(!isset(self::$instances[$namespace])) { + if (!isset(self::$instances[$namespace])) { $config = self::getConfigForNamespace($namespace); self::$instances[$namespace] = self::init($namespace, $config); } @@ -163,10 +167,11 @@ public static function get($namespace = null) { /** * @return DB[] */ - public static function getAll() { + public static function getAll() + { $databases = Config::get('db')->databases; - foreach($databases as $namespace => $modes) + foreach ($databases as $namespace => $modes) self::get($namespace); return self::$instances; @@ -178,7 +183,8 @@ public static function getAll() { * @return DB * @throws Exception */ - public static function reset() { + public static function reset() + { self::$instances = array(); return self::get(); @@ -193,25 +199,27 @@ public static function reset() { * * @return null|DB */ - public static function getByDatabaseName($name) { + public static function getByDatabaseName($name) + { $databases = Config::get('db')->databases; - foreach($databases as $namespace => $modes) - foreach($modes as $mode) - if((isset($mode['database']) && $mode['database'] === $name) || + foreach ($databases as $namespace => $modes) + foreach ($modes as $mode) + if ((isset($mode['database']) && $mode['database'] === $name) || (isset($mode[self::PRIMARY_CONNECTION]) && $mode[self::PRIMARY_CONNECTION]['database'] === $name)) return self::get($namespace); return null; } - public static function getByConfig($config_options) { + public static function getByConfig($config_options) + { $databases = Config::get('db')->databases; - foreach($databases as $namespace => $modes) { - foreach($modes as $mode) { - foreach($config_options as $option => $value) { - if((!isset($mode[$option]) || $mode[$option] !== $value) && + foreach ($databases as $namespace => $modes) { + foreach ($modes as $mode) { + foreach ($config_options as $option => $value) { + if ((!isset($mode[$option]) || $mode[$option] !== $value) && (!isset($mode[self::PRIMARY_CONNECTION]) || $mode[self::PRIMARY_CONNECTION][$option] !== $value)) continue 2; } @@ -230,9 +238,10 @@ public static function getByConfig($config_options) { * * @return DB\Table[] */ - public function getTables($cache = true) { + public function getTables($cache = true) + { - if(!isset($this->tables) || !$cache) { + if (!isset($this->tables) || !$cache) { $driver_class = $this->getConnection()->getDriverClass(); $this->tables = $driver_class::getTables($this); } @@ -246,11 +255,12 @@ public function getTables($cache = true) { * * @return DB\Column */ - public function getColumn($table, $column) { + public function getColumn($table, $column) + { $tables = $this->getTables(); - if(!isset($tables[$table])) + if (!isset($tables[$table])) return null; $table = $tables[$table]; @@ -262,9 +272,10 @@ public function getColumn($table, $column) { /** * @return string */ - public static function getDefaultNamespace() { + public static function getDefaultNamespace() + { - foreach(Config::get('db')->databases as $ns => $database) + foreach (Config::get('db')->databases as $ns => $database) return $ns; } @@ -274,7 +285,8 @@ public static function getDefaultNamespace() { * * @return string */ - public static function getDriverClass($driver) { + public static function getDriverClass($driver) + { return '\\Wave\\DB\\Driver\\' . $driver; } @@ -290,7 +302,8 @@ public static function getDriverClass($driver) { * @return string * @throws DBException */ - public function escape($string) { + public function escape($string) + { $driver = $this->getConnection()->getDriverClass(); return $driver::getEscapeCharacter() . $string . $driver::getEscapeCharacter(); @@ -303,7 +316,8 @@ public function escape($string) { * * @return mixed */ - public function valueToSQL($value) { + public function valueToSQL($value) + { $driver_class = $this->getConnection()->getDriverClass(); return $driver_class::valueToSQL($value); @@ -317,8 +331,9 @@ public function valueToSQL($value) { * * @return mixed */ - public function valueFromSQL($value, array $field_data) { - $driver_class =$this->getConnection()->getDriverClass(); + public function valueFromSQL($value, array $field_data) + { + $driver_class = $this->getConnection()->getDriverClass(); return $driver_class::valueFromSQL($value, $field_data); } @@ -333,7 +348,8 @@ public function valueFromSQL($value, array $field_data) { * * @return DB\Connection */ - public function getConnection($alias = self::PRIMARY_CONNECTION) { + public function getConnection($alias = self::PRIMARY_CONNECTION) + { if (!isset($this->connections[$alias])) { throw new DBException(sprintf('A connection with the alias [%s] has not been defined', $alias)); } @@ -346,7 +362,8 @@ public function getConnection($alias = self::PRIMARY_CONNECTION) { * * @return string */ - public function getNamespace($full_namespace = true) { + public function getNamespace($full_namespace = true) + { $ns_prefix = $full_namespace ? Config::get('wave')->model->base_namespace . '\\' : ''; return $ns_prefix . $this->namespace; @@ -355,15 +372,17 @@ public function getNamespace($full_namespace = true) { /** * @return mixed */ - public function getName() { + public function getName() + { return $this->config->database; } /** * @return mixed */ - public function getSchema() { - if($this->config->offsetExists('schema')) + public function getSchema() + { + if ($this->config->offsetExists('schema')) return $this->config->schema; return $this->config->database; @@ -378,7 +397,8 @@ public function getSchema() { * * @return DB\Query */ - public function from($from, &$alias = null, $fields = null) { + public function from($from, &$alias = null, $fields = null) + { $query = new Query($this->getConnection()); return $query->from($from, $alias, $fields); } @@ -390,10 +410,11 @@ public function from($from, &$alias = null, $fields = null) { * * @return bool */ - public static function save(Model &$object) { + public static function save(Model &$object) + { - if($object->_isLoaded()) { - if($object->_isDirty()) { + if ($object->_isLoaded()) { + if ($object->_isDirty()) { return self::update($object); } } else { @@ -410,7 +431,8 @@ public static function save(Model &$object) { * * @return \PDOStatement */ - public function statement($sql, array $params = array()) { + public function statement($sql, array $params = array()) + { $statement = $this->getConnection()->prepare($sql); $statement->execute($params); @@ -424,7 +446,8 @@ public function statement($sql, array $params = array()) { * @param array $params * @return \PDOStatement */ - public function basicStatement($sql, array $params = array()) { + public function basicStatement($sql, array $params = array()) + { return $this->statement($sql, $params); } @@ -435,23 +458,24 @@ public function basicStatement($sql, array $params = array()) { * * @return bool */ - public static function insert(Model &$object) { + public static function insert(Model &$object) + { $database = self::get($object::_getDatabaseNamespace()); $connection = $database->getConnection(); $fields = $params = $placeholders = array(); $object_data = $object->_getData(); - foreach($object->_getFields(true) as $object_field => $field_properties) { + foreach ($object->_getFields(true) as $object_field => $field_properties) { //Don't take any action for generated columns. - if($field_properties['generated']){ + if ($field_properties['generated']) { continue; } $object_value = $object_data[$object_field]; $fields[] = $database->escape($object_field); - if($object_value === $field_properties['default'] && $field_properties['serial'] === true) { + if ($object_value === $field_properties['default'] && $field_properties['serial'] === true) { $placeholders[] = 'DEFAULT'; } else { $params[] = $database->valueToSQL($object_value); @@ -469,10 +493,10 @@ public static function insert(Model &$object) { $connection->prepare($sql)->execute($params); $primary_key = $object::_getPrimaryKey(); - if($primary_key !== null && count($primary_key) === 1) { + if ($primary_key !== null && count($primary_key) === 1) { $column = current($primary_key); $field = $object::_getField($column); - if($field['serial'] === true){ + if ($field['serial'] === true) { $liid = intval($connection->lastInsertId($field['sequence'])); $object->$column = $liid; } @@ -489,20 +513,21 @@ public static function insert(Model &$object) { * * @return bool */ - public static function update(Model &$object) { + public static function update(Model &$object) + { $database = self::get($object::_getDatabaseNamespace()); $connection = $database->getConnection(); $updates = $criteria = $params = array(); //dirty data - foreach($object->_getDirty() as $object_field => $object_value) { + foreach ($object->_getDirty() as $object_field => $object_value) { $updates[] = sprintf('%s = ?', $database->escape($object_field)); $params[] = $database->valueToSQL($object_value); } //row identifier - foreach($object->_getIdentifyingData() as $identifying_field => $identifying_value) { + foreach ($object->_getIdentifyingData() as $identifying_field => $identifying_value) { $value = $database->valueToSQL($identifying_value); $criteria[] = DB\Query::parseWhereCondition(sprintf('%s = ?', $database->escape($identifying_field)), $value); $params = array_merge($params, $value); @@ -526,7 +551,8 @@ public static function update(Model &$object) { * * @return bool */ - public static function delete(Model &$object) { + public static function delete(Model &$object) + { $database = self::get($object::_getDatabaseNamespace()); $connection = $database->getConnection(); @@ -534,7 +560,7 @@ public static function delete(Model &$object) { //row identifier $criteria = $params = array(); - foreach($object->_getIdentifyingData() as $identifying_field => $identifying_value) { + foreach ($object->_getIdentifyingData() as $identifying_field => $identifying_value) { $value = $database->valueToSQL($identifying_value); $criteria[] = DB\Query::parseWhereCondition(sprintf('%s = ?', $database->escape($identifying_field)), $value); $params = array_merge($params, $value); diff --git a/src/Wave/DB/Column.php b/src/Wave/DB/Column.php index f344a31..0840540 100644 --- a/src/Wave/DB/Column.php +++ b/src/Wave/DB/Column.php @@ -11,7 +11,8 @@ use Wave; -class Column { +class Column +{ const TYPE_UNKNOWN = 0; const TYPE_INT = 1; @@ -45,7 +46,8 @@ class Column { /** @var array $metadata */ private $metadata = array(); - public function __construct(Table $table, $name, $nullable, $data_type, $default_value, $is_serial = false, $type_desc = '', $extra = '', $comment = '') { + public function __construct(Table $table, $name, $nullable, $data_type, $default_value, $is_serial = false, $type_desc = '', $extra = '', $comment = '') + { $this->table = $table; $this->name = $name; @@ -63,7 +65,8 @@ public function __construct(Table $table, $name, $nullable, $data_type, $default /** * @return Table */ - public function getTable() { + public function getTable() + { return $this->table; } @@ -72,28 +75,32 @@ public function getTable() { * * @return string */ - public function getName($escape = false) { + public function getName($escape = false) + { return $escape ? $this->table->getDatabase()->escape($this->name) : $this->name; } /** * @return bool */ - public function isNullable() { + public function isNullable() + { return $this->nullable; } /** * @return boolean */ - public function isSerial() { + public function isSerial() + { return $this->is_serial; } /** * @return int */ - public function getDataType() { + public function getDataType() + { return $this->data_type; } @@ -101,8 +108,9 @@ public function getDataType() { * Return the datatype for this column as a PHP compatible type * @return string */ - public function getDataTypeAsPHPType() { - switch($this->data_type) { + public function getDataTypeAsPHPType() + { + switch ($this->data_type) { case self::TYPE_INT: return 'int'; case self::TYPE_STRING: @@ -122,28 +130,32 @@ public function getDataTypeAsPHPType() { /** * @return mixed */ - public function getDefault() { + public function getDefault() + { return $this->default; } /** * @return string */ - public function getTypeDescription() { + public function getTypeDescription() + { return $this->type_desc; } /** * @return string */ - public function getExtra() { + public function getExtra() + { return $this->extra; } /** * @return string */ - public function getComment() { + public function getComment() + { return $this->comment; } @@ -151,9 +163,10 @@ public function getComment() { * @param $key * @return null */ - public function getMetadata($key = null) { - if($key !== null) { - if(array_key_exists($key, $this->metadata)) + public function getMetadata($key = null) + { + if ($key !== null) { + if (array_key_exists($key, $this->metadata)) return $this->metadata[$key]; else return null; @@ -164,7 +177,8 @@ public function getMetadata($key = null) { /** * @return bool */ - public function isPrimaryKey() { + public function isPrimaryKey() + { $pk = $this->table->getPrimaryKey(); return $pk === null ? false : in_array($this, $pk->getColumns()); @@ -178,10 +192,11 @@ public function isGenerated(): bool return strpos($this->getExtra(), 'GENERATED') !== false; } - private function parseMetadata($raw) { + private function parseMetadata($raw) + { $parsed = json_decode($raw, true); - if(json_last_error() === JSON_ERROR_NONE && is_array($parsed)) { + if (json_last_error() === JSON_ERROR_NONE && is_array($parsed)) { $this->metadata = $parsed; } @@ -190,22 +205,25 @@ private function parseMetadata($raw) { /** * @return string */ - public function getSequenceName() { + public function getSequenceName() + { return $this->sequence_name; } /** * @param string $sequence_name */ - public function setSequenceName($sequence_name) { + public function setSequenceName($sequence_name) + { $this->sequence_name = $sequence_name; } /** - * Provide a representation of this column that can be used to calculate a + * Provide a representation of this column that can be used to calculate a * fingerprint for whether it has changed or not. */ - public function __serialize() { + public function __serialize() + { return [ 'table' => $this->table->getName(), 'name' => $this->getName(), diff --git a/src/Wave/DB/Connection.php b/src/Wave/DB/Connection.php index 7242101..82384f9 100755 --- a/src/Wave/DB/Connection.php +++ b/src/Wave/DB/Connection.php @@ -13,7 +13,8 @@ use Wave\DB; use Wave\DB\Driver\DriverInterface; -class Connection extends PDO { +class Connection extends PDO +{ /** @var DriverInterface $driver_class */ private $driver_class; @@ -25,7 +26,8 @@ class Connection extends PDO { /** * @param \Wave\Config\Row $config */ - public function __construct(ConfigRow $config, $namespace) { + public function __construct(ConfigRow $config, $namespace) + { /** @var DriverInterface $driver_class */ $driver_class = DB::getDriverClass($config->driver); @@ -33,11 +35,11 @@ public function __construct(ConfigRow $config, $namespace) { $this->namespace = $namespace; $options = array(); - if(isset($config->driver_options)) { + if (isset($config->driver_options)) { // driver_options can be in two formats, either a key => value array (native) // or an array of [ key, value ], used to preserve types (i.e. integers as keys) - if(isset($config->driver_options[0])) { - foreach($config->driver_options as $option) { + if (isset($config->driver_options[0])) { + foreach ($config->driver_options as $option) { list($key, $value) = $option; $options[$key] = $value; } @@ -54,16 +56,16 @@ public function __construct(ConfigRow $config, $namespace) { } + public function prepare($sql, $options = array()): \PDOStatement|false + { - public function prepare($sql, $options = array()) { - - if(!$this->cache_enabled) + if (!$this->cache_enabled) return parent::prepare($sql, $options); $hash = md5($sql); //double-check that sql is same if it is cached - if(!isset($this->statement_cache[$hash]) || $this->statement_cache[$hash]->queryString !== $sql) { + if (!isset($this->statement_cache[$hash]) || $this->statement_cache[$hash]->queryString !== $sql) { $this->statement_cache[$hash] = parent::prepare($sql, $options); } @@ -74,7 +76,8 @@ public function prepare($sql, $options = array()) { /** * @return DriverInterface */ - public function getDriverClass() { + public function getDriverClass() + { return $this->driver_class; } @@ -84,7 +87,8 @@ public function getDriverClass() { * * @return mixed */ - public function getNamespace() { + public function getNamespace() + { return $this->namespace; } diff --git a/src/Wave/DB/Constraint.php b/src/Wave/DB/Constraint.php index ffaf9ad..8f48199 100644 --- a/src/Wave/DB/Constraint.php +++ b/src/Wave/DB/Constraint.php @@ -11,7 +11,8 @@ use Wave; -class Constraint { +class Constraint +{ const TYPE_UNKNOWN = 11; const TYPE_PRIMARY = 12; @@ -25,7 +26,8 @@ class Constraint { /** @var string $name */ private $name; - public function __construct(Column $column, $type, $name) { + public function __construct(Column $column, $type, $name) + { $this->columns = array($column); $this->type = $type; $this->name = $name; @@ -34,37 +36,42 @@ public function __construct(Column $column, $type, $name) { /** * @param Column $column */ - public function addColumn(Column $column) { - if(!in_array($column, $this->columns)) + public function addColumn(Column $column) + { + if (!in_array($column, $this->columns)) $this->columns[] = $column; } /** * @return string */ - public function getName() { + public function getName() + { return $this->name; } /** * @return string */ - public function getType() { + public function getType() + { return $this->type; } /** * @return Column[] */ - public function getColumns() { + public function getColumns() + { return $this->columns; } /** - * Provide a representation of this constraint that can be used to calculate a + * Provide a representation of this constraint that can be used to calculate a * fingerprint for whether it has changed or not. */ - public function __serialize() { + public function __serialize() + { return [ 'name' => $this->getName(), 'type' => $this->getType(), diff --git a/src/Wave/DB/Driver/DriverInterface.php b/src/Wave/DB/Driver/DriverInterface.php index cf59f39..8618cfc 100644 --- a/src/Wave/DB/Driver/DriverInterface.php +++ b/src/Wave/DB/Driver/DriverInterface.php @@ -5,7 +5,8 @@ use Wave\Config\Row; use Wave\DB; -interface DriverInterface { +interface DriverInterface +{ public static function constructDSN(Row $config); diff --git a/src/Wave/DB/Driver/MySQL.php b/src/Wave/DB/Driver/MySQL.php index 3203f53..cde55b0 100755 --- a/src/Wave/DB/Driver/MySQL.php +++ b/src/Wave/DB/Driver/MySQL.php @@ -12,19 +12,21 @@ use Wave\Config\Row; use Wave\DB; -class MySQL extends AbstractDriver implements DriverInterface { +class MySQL extends AbstractDriver implements DriverInterface +{ //Selecting from the information schema tables is slow as they are built on select so need to cache the whole set and manipulate in php. static $_column_cache; static $_relation_cache; - public static function constructDSN(Row $config) { + public static function constructDSN(Row $config) + { $dsn = "mysql:host={$config->host};dbname={$config->database};port={$config->port}"; $optional_properties = ['charset']; - foreach($optional_properties as $prop){ - if(isset($config->{$prop})) + foreach ($optional_properties as $prop) { + if (isset($config->{$prop})) $dsn .= ";{$prop}={$config->$prop}"; } @@ -32,15 +34,18 @@ public static function constructDSN(Row $config) { return $dsn; } - public static function getDriverName() { + public static function getDriverName() + { return 'mysql'; } - public static function getEscapeCharacter() { + public static function getEscapeCharacter() + { return '`'; } - public static function getTables(DB $database) { + public static function getTables(DB $database) + { $table_sql = 'SELECT TABLE_NAME, ENGINE, TABLE_COLLATION, TABLE_COMMENT ' . 'FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA` = ?;'; @@ -50,7 +55,7 @@ public static function getTables(DB $database) { $table_stmt->execute(array($database->getName())); $tables = array(); - while($table_row = $table_stmt->fetch()) { + while ($table_row = $table_stmt->fetch()) { $table = new DB\Table( $database, @@ -68,12 +73,13 @@ public static function getTables(DB $database) { } - public static function getColumns(DB\Table $table) { + public static function getColumns(DB\Table $table) + { //using namespace for the table identifier as there might be same name DBs on different servers $namespace = $table->getDatabase()->getNamespace(); - if(!isset(self::$_column_cache[$namespace])) { + if (!isset(self::$_column_cache[$namespace])) { self::$_column_cache[$namespace] = array(); @@ -83,15 +89,15 @@ public static function getColumns(DB\Table $table) { $column_stmt = $table->getDatabase()->getConnection()->prepare($column_sql); $column_stmt->execute(array($table->getDatabase()->getName())); - while($column_row = $column_stmt->fetch()) + while ($column_row = $column_stmt->fetch()) self::$_column_cache[$namespace][$column_row['TABLE_NAME']][] = $column_row; } $columns = array(); //may not be any columns - if(isset(self::$_column_cache[$namespace][$table->getName()])) { - foreach(self::$_column_cache[$namespace][$table->getName()] as $cached_row) { + if (isset(self::$_column_cache[$namespace][$table->getName()])) { + foreach (self::$_column_cache[$namespace][$table->getName()] as $cached_row) { $column = new DB\Column( $table, @@ -113,7 +119,8 @@ public static function getColumns(DB\Table $table) { } - public static function getRelations(DB\Table $table) { + public static function getRelations(DB\Table $table) + { //using namespace for the table identifier as there might be same name DBs on different servers $namespace = $table->getDatabase()->getNamespace(); @@ -122,34 +129,34 @@ public static function getRelations(DB\Table $table) { $relations = array(); //may not be any constraints - if($relation_cache !== null) { - foreach($relation_cache as $cached_row) { + if ($relation_cache !== null) { + foreach ($relation_cache as $cached_row) { //--- check both ends of the relation can be built. $local_db = DB::getByDatabaseName($cached_row['TABLE_SCHEMA']); - if($local_db === null) { + if ($local_db === null) { Wave\Log::write('mysql_driver', sprintf('Database [%s] is not referenced in the configuration - skipping building relations.', $cached_row['TABLE_SCHEMA']), Wave\Log::WARNING); continue; } $local_column = $local_db->getColumn($cached_row['TABLE_NAME'], $cached_row['COLUMN_NAME']); //skip if there's no referenced schema. This is because primary keys will be in the relation cache (no ref schema) - if($cached_row['REFERENCED_TABLE_SCHEMA'] === null) + if ($cached_row['REFERENCED_TABLE_SCHEMA'] === null) continue; $referenced_db = DB::getByDatabaseName($cached_row['REFERENCED_TABLE_SCHEMA']); - if($referenced_db === null) { + if ($referenced_db === null) { Wave\Log::write('mysql_driver', sprintf('Database [%s] is not referenced in the configuration - skipping building relations.', $cached_row['REFERENCED_TABLE_SCHEMA']), Wave\Log::WARNING); continue; } $referenced_column = $referenced_db->getColumn($cached_row['REFERENCED_TABLE_NAME'], $cached_row['REFERENCED_COLUMN_NAME']); - if($referenced_column === null) { + if ($referenced_column === null) { Wave\Log::write('mysql_driver', sprintf('Column [%s] is not referenced in the configuration - skipping building relations.', $cached_row['REFERENCED_COLUMN_NAME']), Wave\Log::WARNING); continue; } //----- - if($cached_row['REFERENCED_TABLE_SCHEMA'] != $cached_row['TABLE_SCHEMA']) { + if ($cached_row['REFERENCED_TABLE_SCHEMA'] != $cached_row['TABLE_SCHEMA']) { //print_r($cached_row); //exit; } @@ -157,7 +164,7 @@ public static function getRelations(DB\Table $table) { $relation = DB\Relation::create($local_column, $referenced_column, $cached_row['CONSTRAINT_NAME'], isset($cached_row['REVERSE'])); - if($relation !== null) + if ($relation !== null) $relations[$relation->getIdentifyingName()] = $relation; else Wave\Log::write('mysql_driver', sprintf('[%s.%s.%s] has duplicate relations.', $cached_row['TABLE_SCHEMA'], $cached_row['TABLE_NAME'], $cached_row['COLUMN_NAME']), Wave\Log::WARNING); @@ -169,21 +176,22 @@ public static function getRelations(DB\Table $table) { } - public static function getConstraints(DB\Table $table) { + public static function getConstraints(DB\Table $table) + { $constraints = array(); - if(null === $relation_cache = self::_getRelationCache($table)) + if (null === $relation_cache = self::_getRelationCache($table)) return $constraints; - foreach($relation_cache as $relation) { + foreach ($relation_cache as $relation) { $column = $table->getDatabase()->getColumn($relation['TABLE_NAME'], $relation['COLUMN_NAME']); - if($column === null) + if ($column === null) continue; - if(!isset($constraints[$relation['CONSTRAINT_NAME']])) { + if (!isset($constraints[$relation['CONSTRAINT_NAME']])) { $constraints[$relation['CONSTRAINT_NAME']] = new DB\Constraint($column, self::translateSQLConstraintType($relation['CONSTRAINT_TYPE']), $relation['CONSTRAINT_NAME']); } else { $idx = $constraints[$relation['CONSTRAINT_NAME']]; @@ -193,11 +201,12 @@ public static function getConstraints(DB\Table $table) { return $constraints; } - private static function _getRelationCache(DB\Table $table) { + private static function _getRelationCache(DB\Table $table) + { $namespace = $table->getDatabase()->getNamespace(); - if(!isset(self::$_relation_cache[$namespace])) { + if (!isset(self::$_relation_cache[$namespace])) { self::$_relation_cache[$namespace] = array(); @@ -210,7 +219,7 @@ private static function _getRelationCache(DB\Table $table) { $relations_stmt = $table->getDatabase()->getConnection()->prepare($relations_sql); $relations_stmt->execute(array($table->getDatabase()->getName(), $table->getDatabase()->getName())); - while($relations_row = $relations_stmt->fetch()) { + while ($relations_row = $relations_stmt->fetch()) { self::$_relation_cache[$namespace][$relations_row['TABLE_NAME']][] = $relations_row; //Relations added for both directions, flag the one that's reversed. $relations_row['REVERSE'] = true; @@ -222,9 +231,10 @@ private static function _getRelationCache(DB\Table $table) { } - public static function translateSQLDataType($type) { + public static function translateSQLDataType($type) + { - switch($type) { + switch ($type) { case 'varchar': return DB\Column::TYPE_STRING; @@ -254,9 +264,10 @@ public static function translateSQLDataType($type) { } - public static function translateSQLConstraintType($type) { + public static function translateSQLConstraintType($type) + { - switch($type) { + switch ($type) { case 'PRIMARY KEY': return DB\Constraint::TYPE_PRIMARY; case 'UNIQUE': @@ -269,9 +280,10 @@ public static function translateSQLConstraintType($type) { } - public static function translateSQLNullable($nullable) { + public static function translateSQLNullable($nullable) + { - switch($nullable) { + switch ($nullable) { case 'NO': return false; case 'YES': @@ -279,18 +291,19 @@ public static function translateSQLNullable($nullable) { } } - public static function translateSQLDefault($row) { + public static function translateSQLDefault($row) + { $value = $row['COLUMN_DEFAULT']; $type = self::translateSQLDataType($row['DATA_TYPE']); - if(strtolower($value) === 'null' || self::translateSQLNullable($row['IS_NULLABLE'])) { + if (strtolower($value) === 'null' || self::translateSQLNullable($row['IS_NULLABLE'])) { $value = null; - } else if(DB\Column::TYPE_FLOAT == $type) { - $value = (float) $value; - } else if(DB\Column::TYPE_INT === $type) { - $value = (int) $value; - } elseif(DB\Column::TYPE_BOOL === $type) { + } else if (DB\Column::TYPE_FLOAT == $type) { + $value = (float)$value; + } else if (DB\Column::TYPE_INT === $type) { + $value = (int)$value; + } elseif (DB\Column::TYPE_BOOL === $type) { $value = !!$value; } diff --git a/src/Wave/DB/Driver/PostgreSQL.php b/src/Wave/DB/Driver/PostgreSQL.php index 4fad7b8..6d01815 100644 --- a/src/Wave/DB/Driver/PostgreSQL.php +++ b/src/Wave/DB/Driver/PostgreSQL.php @@ -12,26 +12,31 @@ use Wave\DB; use Wave\Log; -class PostgreSQL extends AbstractDriver implements DriverInterface { +class PostgreSQL extends AbstractDriver implements DriverInterface +{ //Selecting from the information schema tables is slow as they are built on select so need to cache the whole set and manipulate in php. static $_column_cache; static $_relation_cache; - public static function constructDSN(Row $config) { + public static function constructDSN(Row $config) + { return "pgsql:host={$config->host};port={$config->port};dbname={$config->database}"; } - public static function getDriverName() { + public static function getDriverName() + { return 'pgsql'; } - public static function getEscapeCharacter() { + public static function getEscapeCharacter() + { return '"'; } - public static function getTables(DB $database) { + public static function getTables(DB $database) + { $table_sql = 'SELECT "table_name", "table_type" FROM "information_schema"."tables" WHERE "table_schema" = ?'; @@ -39,7 +44,7 @@ public static function getTables(DB $database) { $table_stmt->execute(array($database->getSchema())); $tables = array(); - while($table_row = $table_stmt->fetch()) { + while ($table_row = $table_stmt->fetch()) { $table = new DB\Table($database, $table_row['table_name']); @@ -51,12 +56,13 @@ public static function getTables(DB $database) { } - public static function getColumns(DB\Table $table) { + public static function getColumns(DB\Table $table) + { //using namespace for the table identifier as there might be same name DBs on different servers $namespace = $table->getDatabase()->getNamespace(); - if(!isset(self::$_column_cache[$namespace])) { + if (!isset(self::$_column_cache[$namespace])) { self::$_column_cache[$namespace] = array(); @@ -66,15 +72,15 @@ public static function getColumns(DB\Table $table) { $column_stmt = $table->getDatabase()->getConnection()->prepare($column_sql); $column_stmt->execute(array($table->getDatabase()->getSchema())); - while($column_row = $column_stmt->fetch()) + while ($column_row = $column_stmt->fetch()) self::$_column_cache[$namespace][$column_row['table_name']][] = $column_row; } $columns = array(); //may not be any columns - if(isset(self::$_column_cache[$namespace][$table->getName()])) { - foreach(self::$_column_cache[$namespace][$table->getName()] as $cached_row) { + if (isset(self::$_column_cache[$namespace][$table->getName()])) { + foreach (self::$_column_cache[$namespace][$table->getName()] as $cached_row) { list($default_value, $is_serial, $sequence) = self::translateSQLDefault($cached_row['column_default']); @@ -87,7 +93,7 @@ public static function getColumns(DB\Table $table) { $is_serial ); - if($sequence !== null) + if ($sequence !== null) $column->setSequenceName($sequence); $columns[$cached_row['column_name']] = $column; @@ -98,7 +104,8 @@ public static function getColumns(DB\Table $table) { } - public static function getRelations(DB\Table $table) { + public static function getRelations(DB\Table $table) + { //using namespace for the table identifier as there might be same name DBs on different servers $namespace = $table->getDatabase()->getNamespace(); @@ -107,8 +114,8 @@ public static function getRelations(DB\Table $table) { $relations = array(); //may not be any constraints - if($relation_cache !== null) { - foreach($relation_cache as $cached_row) { + if ($relation_cache !== null) { + foreach ($relation_cache as $cached_row) { //--- check both ends of the relation can be built. $local_db = DB::getByConfig( @@ -117,14 +124,14 @@ public static function getRelations(DB\Table $table) { 'schema' => $cached_row['table_schema'] ) ); - if($local_db === null) { + if ($local_db === null) { Log::write('pgsql_driver', sprintf('Database [%s] is not referenced in the configuration - skipping building relations.', $cached_row['table_catalog']), Log::WARNING); continue; } $local_column = $local_db->getColumn($cached_row['table_name'], $cached_row['column_name']); //skip if there's no referenced schema. This is because primary keys will be in the relation cache (no ref schema) - if($cached_row['referenced_table_schema'] === null) + if ($cached_row['referenced_table_schema'] === null) continue; $referenced_db = DB::getByConfig( @@ -133,7 +140,7 @@ public static function getRelations(DB\Table $table) { 'schema' => $cached_row['referenced_table_schema'] ) ); - if($referenced_db === null) { + if ($referenced_db === null) { Log::write('pgsql_driver', sprintf('Database [%s] is not referenced in the configuration - skipping building relations.', $cached_row['referenced_table_schema']), Log::WARNING); continue; } @@ -142,7 +149,7 @@ public static function getRelations(DB\Table $table) { $relation = DB\Relation::create($local_column, $referenced_column, $cached_row['constraint_name'], isset($cached_row['reverse'])); - if($relation !== null) + if ($relation !== null) $relations[$relation->getIdentifyingName()] = $relation; else Log::write('mysql_driver', sprintf('[%s.%s.%s] has duplicate relations.', $cached_row['table_schema'], $cached_row['table_name'], $cached_row['column_name']), Log::WARNING); @@ -154,18 +161,19 @@ public static function getRelations(DB\Table $table) { } - public static function getConstraints(DB\Table $table) { + public static function getConstraints(DB\Table $table) + { $constraints = array(); - if(null === $relation_cache = self::_getRelationCache($table)) + if (null === $relation_cache = self::_getRelationCache($table)) return $constraints; - foreach($relation_cache as $relation) { + foreach ($relation_cache as $relation) { $column = $table->getDatabase()->getColumn($relation['table_name'], $relation['column_name']); - if(!isset($constraints[$relation['constraint_name']])) { + if (!isset($constraints[$relation['constraint_name']])) { $constraints[$relation['constraint_name']] = new DB\Constraint($column, self::translateSQLConstraintType($relation['constraint_type']), $relation['constraint_name']); } else { $idx = $constraints[$relation['constraint_name']]; @@ -175,11 +183,12 @@ public static function getConstraints(DB\Table $table) { return $constraints; } - private static function _getRelationCache(DB\Table $table) { + private static function _getRelationCache(DB\Table $table) + { $namespace = $table->getDatabase()->getNamespace(); - if(!isset(self::$_relation_cache[$namespace])) { + if (!isset(self::$_relation_cache[$namespace])) { self::$_relation_cache[$namespace] = array(); @@ -205,7 +214,7 @@ private static function _getRelationCache(DB\Table $table) { $relations_stmt = $table->getDatabase()->getConnection()->prepare($relations_sql); $relations_stmt->execute(array('schema' => $table->getDatabase()->getSchema())); - while($relations_row = $relations_stmt->fetch()) { + while ($relations_row = $relations_stmt->fetch()) { self::$_relation_cache[$namespace][$relations_row['table_name']][] = $relations_row; //Relations added for both directions, flag the one that's reversed. $relations_row['reverse'] = true; @@ -217,9 +226,10 @@ private static function _getRelationCache(DB\Table $table) { } - public static function translateSQLDataType($type) { + public static function translateSQLDataType($type) + { - switch($type) { + switch ($type) { case 'text': case 'char': @@ -274,9 +284,10 @@ public static function translateSQLDataType($type) { } - public static function translateSQLConstraintType($type) { + public static function translateSQLConstraintType($type) + { - switch($type) { + switch ($type) { case 'PRIMARY KEY': return DB\Constraint::TYPE_PRIMARY; case 'UNIQUE': @@ -289,9 +300,10 @@ public static function translateSQLConstraintType($type) { } - public static function translateSQLNullable($nullable) { + public static function translateSQLNullable($nullable) + { - switch($nullable) { + switch ($nullable) { case 'NO': return false; case 'YES': @@ -299,24 +311,25 @@ public static function translateSQLNullable($nullable) { } } - public static function translateSQLDefault($column_default) { + public static function translateSQLDefault($column_default) + { list($value, $original_type) = explode('::', $column_default, 2) + array(null, null); $is_serial = false; $sequence = null; $type = self::translateSQLDataType($original_type); - if(strtolower($value) === 'null') { + if (strtolower($value) === 'null') { $value = null; - } else if(preg_match('/nextval\(\'(?.+?)\'/', $column_default, $matches)) { + } else if (preg_match('/nextval\(\'(?.+?)\'/', $column_default, $matches)) { $value = null; $is_serial = true; $sequence = $matches['sequence_name']; - } else if(DB\Column::TYPE_FLOAT == $type) { - $value = (float) $value; - } else if(DB\Column::TYPE_INT === $type) { - $value = (int) $value; - } else if('now()' === $value) { + } else if (DB\Column::TYPE_FLOAT == $type) { + $value = (float)$value; + } else if (DB\Column::TYPE_INT === $type) { + $value = (int)$value; + } else if ('now()' === $value) { $value = 'CURRENT_TIMESTAMP'; } else { // just trim any quotes and make it a string (catches enums/custom types) diff --git a/src/Wave/DB/Exception.php b/src/Wave/DB/Exception.php index cb6a488..5b9159b 100644 --- a/src/Wave/DB/Exception.php +++ b/src/Wave/DB/Exception.php @@ -4,5 +4,6 @@ use Wave; -class Exception extends Wave\Exception { +class Exception extends Wave\Exception +{ } \ No newline at end of file diff --git a/src/Wave/DB/Generator.php b/src/Wave/DB/Generator.php index 3a8c124..04527f3 100755 --- a/src/Wave/DB/Generator.php +++ b/src/Wave/DB/Generator.php @@ -1,20 +1,22 @@ getTables($database); $existing_files = glob(self::getModelPath($database) . '*.php'); - foreach($tables as $table) { + foreach ($tables as $table) { $base_file = self::getBaseModelPath($database) . $table->getClassName() . '.php'; $base_rendered = self::renderTemplate('base-model', array('table' => $table)); self::writeTemplateIfChanged($table, $base_file, $base_rendered); $stub_file = self::getModelPath($database) . $table->getClassName() . '.php'; - if(!file_exists($stub_file)) + if (!file_exists($stub_file)) file_put_contents($stub_file, self::renderTemplate('stub-model', array('table' => $table))); $current_files[] = $stub_file; @@ -58,18 +61,18 @@ public static function generate(&$orphans = null) { * * @return bool */ - private static function writeTemplateIfChanged($table, $filepath, $contents) { + private static function writeTemplateIfChanged($table, $filepath, $contents) + { - if(file_exists($filepath)){ - $rendered_fingerprint = $table->getSchemaFingerprint(); + if (file_exists($filepath)) { + $rendered_fingerprint = $table->getSchemaFingerprint(); $current_contents = file_get_contents($filepath); preg_match('/@fingerprint: ([0-9a-f]{32})/', $current_contents, $matches); - if(!isset($matches[1]) || $rendered_fingerprint !== $matches[1]){ + if (!isset($matches[1]) || $rendered_fingerprint !== $matches[1]) { Wave\Log::write('generator', sprintf('Table [%s] has changed, updating base model file...', $table->getName()), Wave\Log::DEBUG); file_put_contents($filepath, $contents); } - } - else { + } else { Wave\Log::write('generator', sprintf('Base Model for table [%s] doesn\'t exist, creating...', $table->getName()), Wave\Log::DEBUG); file_put_contents($filepath, $contents); } @@ -83,38 +86,41 @@ private static function writeTemplateIfChanged($table, $filepath, $contents) { * * @return string */ - private static function renderTemplate($template, $data, $template_ext = '.phpt') { + private static function renderTemplate($template, $data, $template_ext = '.phpt') + { - $loaded_template = self::$twig->loadTemplate($template . $template_ext); + $loaded_template = self::$twig->load($template . $template_ext); return $loaded_template->render($data); } - private static function initTwig() { + private static function initTwig() + { - $loader = new Twig_Loader_Filesystem(__DIR__ . DS . 'Generator' . DS . 'Templates'); - self::$twig = new Twig_Environment($loader, array('autoescape' => false)); - self::$twig->addFilter('addslashes', new \Twig_Filter_Function('addslashes')); + $loader = new FilesystemLoader(__DIR__ . DS . 'Generator' . DS . 'Templates'); + self::$twig = new Environment($loader, array('autoescape' => false)); + self::$twig->addFilter(new TwigFilter('addslashes')); self::$twig->addFilter( - 'export', new \Twig_Filter_Function( + new TwigFilter('export', function ($var) { return var_export($var, true); } ) ); - self::$twig->addFilter('implode', new \Twig_Filter_Function('implode')); - self::$twig->addFilter('singularize', new \Twig_Filter_Function('\\Wave\\Inflector::singularize')); - self::$twig->addFilter('formatType', new \Twig_Filter_Function('\\Wave\\DB\\Generator::formatTypeForSource')); + self::$twig->addFilter(new TwigFilter('implode')); + self::$twig->addFilter(new TwigFilter('singularize', '\\Wave\\Inflector::singularize')); + self::$twig->addFilter(new TwigFilter('formatType', '\\Wave\\DB\\Generator::formatTypeForSource')); self::$twig->addGlobal('baseModelClass', static::$baseModelClass); } - public static function formatTypeForSource($type) { + public static function formatTypeForSource($type) + { - if(null === $type) + if (null === $type) return "null"; - else if(is_int($type) || is_float($type)) + else if (is_int($type) || is_float($type)) return "$type"; - else if(is_bool($type)) + else if (is_bool($type)) return $type ? "true" : "false"; else return "'$type'"; @@ -124,11 +130,12 @@ public static function formatTypeForSource($type) { /** * @param Wave\DB $database */ - private static function createModelDirectory(Wave\DB $database) { + private static function createModelDirectory(Wave\DB $database) + { $basedir = self::getBaseModelPath($database); - if(!file_exists($basedir)) + if (!file_exists($basedir)) mkdir($basedir, 0775, true); } @@ -137,7 +144,8 @@ private static function createModelDirectory(Wave\DB $database) { * * @return string */ - private static function getBaseModelPath(Wave\DB $database) { + private static function getBaseModelPath(Wave\DB $database) + { return self::getModelPath($database) . 'Base' . DS; } @@ -146,7 +154,8 @@ private static function getBaseModelPath(Wave\DB $database) { * * @return string */ - private static function getModelPath(Wave\DB $database) { + private static function getModelPath(Wave\DB $database) + { $namespace = $database->getNamespace(false); $model_directory = Wave\Config::get('wave')->path->models; @@ -155,7 +164,8 @@ private static function getModelPath(Wave\DB $database) { } - public static function setBaseModelClass($baseModelClass) { + public static function setBaseModelClass($baseModelClass) + { self::$baseModelClass = $baseModelClass; } diff --git a/src/Wave/DB/Generator/Templates/base-model.phpt b/src/Wave/DB/Generator/Templates/base-model.phpt index 2365096..9bf37a6 100644 --- a/src/Wave/DB/Generator/Templates/base-model.phpt +++ b/src/Wave/DB/Generator/Templates/base-model.phpt @@ -36,8 +36,8 @@ use Wave\DB; {% endif %} {% endfor %} */ -abstract class {{ table.ClassName }} extends {{ baseModelClass }} { - +abstract class {{ table.ClassName }} extends {{ baseModelClass }} +{ //Table name protected static $_database = '{{ table.Database.getNamespace(false) }}'; protected static $_table_name = '{{ table.Name }}'; @@ -96,11 +96,13 @@ abstract class {{ table.ClassName }} extends {{ baseModelClass }} { {% for column in table.Columns %} //{{ column.TypeDescription|raw }} {{ column.Extra }} {{ column.Comment }} - public function get{{ column.Name }}(){ + public function get{{ column.Name }}() + { return $this->_data['{{ column.Name }}']; } - public function set{{ column.Name }}($value){ + public function set{{ column.Name }}($value) + { $this->_data['{{ column.Name }}'] = $value; $this->_dirty['{{ column.Name }}'] = true; return $this; diff --git a/src/Wave/DB/Generator/Templates/relations/many-to-many.phpt b/src/Wave/DB/Generator/Templates/relations/many-to-many.phpt index f3ac1b5..61f6e67 100644 --- a/src/Wave/DB/Generator/Templates/relations/many-to-many.phpt +++ b/src/Wave/DB/Generator/Templates/relations/many-to-many.phpt @@ -9,7 +9,8 @@ * * @return $this **/ - public function add{{ relation.Name|singularize }}({{ relation.TargetRelation.ReferencedTable.getClassName(true) }} &$object, $create_relation = true, array $join_data = array()){ + public function add{{ relation.Name|singularize }}({{ relation.TargetRelation.ReferencedTable.getClassName(true) }} &$object, $create_relation = true, array $join_data = array()) + { $this->_addRelationObject('{{ relation.Name }}', $object, $create_relation, $join_data); return $this; } @@ -21,7 +22,8 @@ * @param bool $remove_relation actually remove the relation from the database * @return $this **/ - public function remove{{ relation.Name|singularize }}({{ relation.TargetRelation.ReferencedTable.getClassName(true) }} &$object, $remove_relation = true){ + public function remove{{ relation.Name|singularize }}({{ relation.TargetRelation.ReferencedTable.getClassName(true) }} &$object, $remove_relation = true) + { $this->_removeRelationObject('{{ relation.Name }}', $object, $remove_relation); return $this; } @@ -32,7 +34,8 @@ * @param callable $transform_callback * @return {{ relation.TargetRelation.ReferencedTable.getClassName(true) }}[] **/ - public function get{{ relation.Name }}(){ + public function get{{ relation.Name }}() + { $transform_callback = func_num_args() >= 1 ? func_get_arg(0) : null; return $this->_getRelationObjects('{{ relation.Name }}', $transform_callback); } \ No newline at end of file diff --git a/src/Wave/DB/Generator/Templates/relations/many-to-one.phpt b/src/Wave/DB/Generator/Templates/relations/many-to-one.phpt index 78df04b..72a3096 100644 --- a/src/Wave/DB/Generator/Templates/relations/many-to-one.phpt +++ b/src/Wave/DB/Generator/Templates/relations/many-to-one.phpt @@ -8,7 +8,8 @@ * * @return $this **/ - public function set{{ relation.Name }}({{ relation.ReferencedTable.getClassName(true) }} &$object = null, $create_relation = true){ + public function set{{ relation.Name }}({{ relation.ReferencedTable.getClassName(true) }} &$object = null, $create_relation = true) + { $this->_setRelationObject('{{ relation.Name }}', $object, $create_relation); return $this; } @@ -19,7 +20,8 @@ * @param callable $transform_callback * @return {{ relation.ReferencedTable.getClassName(true) }} **/ - public function get{{ relation.Name }}(){ + public function get{{ relation.Name }}() + { $transform_callback = func_num_args() >= 1 ? func_get_arg(0) : null; return $this->_getRelationObjects('{{ relation.Name }}', $transform_callback); } \ No newline at end of file diff --git a/src/Wave/DB/Generator/Templates/relations/one-to-many.phpt b/src/Wave/DB/Generator/Templates/relations/one-to-many.phpt index c0bbb52..c642a82 100644 --- a/src/Wave/DB/Generator/Templates/relations/one-to-many.phpt +++ b/src/Wave/DB/Generator/Templates/relations/one-to-many.phpt @@ -8,7 +8,8 @@ * * @return $this **/ - public function add{{ relation.Name|singularize }}({{ relation.ReferencedTable.getClassName(true) }} &$object, $create_relation = true){ + public function add{{ relation.Name|singularize }}({{ relation.ReferencedTable.getClassName(true) }} &$object, $create_relation = true) + { $this->_addRelationObject('{{ relation.Name }}', $object, $create_relation); return $this; } @@ -20,7 +21,8 @@ * @param bool $delete_object whether to delete the object in the database * @return $this **/ - public function remove{{ relation.Name|singularize }}({{ relation.ReferencedTable.getClassName(true) }} $object, $delete_object = true){ + public function remove{{ relation.Name|singularize }}({{ relation.ReferencedTable.getClassName(true) }} $object, $delete_object = true) + { $this->_removeRelationObject('{{ relation.Name }}', $object, $delete_object); return $this; } @@ -31,7 +33,8 @@ * @param callable $transform_callback * @return {{ relation.ReferencedTable.getClassName(true) }}[] **/ - public function get{{ relation.Name }}(){ + public function get{{ relation.Name }}() + { $transform_callback = func_num_args() >= 1 ? func_get_arg(0) : null; return $this->_getRelationObjects('{{ relation.Name }}', $transform_callback); } \ No newline at end of file diff --git a/src/Wave/DB/Generator/Templates/relations/one-to-one.phpt b/src/Wave/DB/Generator/Templates/relations/one-to-one.phpt index 5a0f509..544e753 100644 --- a/src/Wave/DB/Generator/Templates/relations/one-to-one.phpt +++ b/src/Wave/DB/Generator/Templates/relations/one-to-one.phpt @@ -8,7 +8,8 @@ * * @return $this **/ - public function set{{ relation.Name }}(&$obj = null, $create_relation = true){ + public function set{{ relation.Name }}(&$obj = null, $create_relation = true) + { $this->_setRelationObject('{{ relation.Name }}', $obj, $create_relation); return $this; } @@ -19,7 +20,8 @@ * @param callable $transform_callback * @return {{ relation.ReferencedTable.getClassName(true) }} **/ - public function get{{ relation.Name }}(){ + public function get{{ relation.Name }}() + { $transform_callback = func_num_args() >= 1 ? func_get_arg(0) : null; return $this->_getRelationObjects('{{ relation.Name }}', $transform_callback); } \ No newline at end of file diff --git a/src/Wave/DB/Generator/Templates/stub-model.phpt b/src/Wave/DB/Generator/Templates/stub-model.phpt index 6f89107..102281c 100644 --- a/src/Wave/DB/Generator/Templates/stub-model.phpt +++ b/src/Wave/DB/Generator/Templates/stub-model.phpt @@ -16,6 +16,7 @@ namespace {{ table.Database.Namespace }}; -class {{ table.ClassName }} extends Base\{{ table.ClassName }} { +class {{ table.ClassName }} extends Base\{{ table.ClassName }} +{ } \ No newline at end of file diff --git a/src/Wave/DB/Model.php b/src/Wave/DB/Model.php index 70f6cb5..adb4ce7 100644 --- a/src/Wave/DB/Model.php +++ b/src/Wave/DB/Model.php @@ -11,7 +11,8 @@ use Wave; use Wave\DB; -class Model implements \JsonSerializable { +class Model implements \JsonSerializable +{ /** @var string */ protected static $_database; @@ -83,17 +84,18 @@ class Model implements \JsonSerializable { protected $_parent_object = null; - public function __construct($data = null, $is_loaded = false) { + public function __construct($data = null, $is_loaded = false) + { $connection = DB::get(self::_getDatabaseNamespace()); - foreach(self::_getFields() as $field) { + foreach (self::_getFields() as $field) { $this->_data[$field] = $data !== null && array_key_exists($field, $data) ? $connection->valueFromSQL($data[$field], self::_getField($field)) : self::getFieldDefault($field); } - if($is_loaded) + if ($is_loaded) $this->_setLoaded(); } @@ -106,17 +108,17 @@ public function __construct($data = null, $is_loaded = false) { * @param \Wave\Validator\Result|Array $data * @param bool $use_setters */ - public function updateFromArray($data, $use_setters = true){ + public function updateFromArray($data, $use_setters = true) + { - foreach(self::_getFields() as $field) { - if(array_key_exists($field, $data)){ + foreach (self::_getFields() as $field) { + if (array_key_exists($field, $data)) { // Handle the case where we get a model instance back from the validator instead of [object_name]_id $value = ($data[$field] instanceof self) ? $data[$field]->id : $data[$field]; - if($use_setters) { + if ($use_setters) { $this->$field = $value; - } - else { + } else { $this->_data[$field] = $value; } } @@ -132,10 +134,11 @@ public function updateFromArray($data, $use_setters = true){ * * @return null|self */ - public static function createFromArray(array $data) { + public static function createFromArray(array $data) + { - foreach(static::_getIdentifyingColumns() as $required_column) { - if(!isset($data[$required_column]) || $data[$required_column] === '') { + foreach (static::_getIdentifyingColumns() as $required_column) { + if (!isset($data[$required_column]) || $data[$required_column] === '') { return null; } } @@ -151,7 +154,8 @@ public static function createFromArray(array $data) { * * @return mixed */ - public static function getFieldDefault($field_name) { + public static function getFieldDefault($field_name) + { $field = self::_getField($field_name); return DB::get(self::_getDatabaseNamespace())->valueFromSQL($field['default'], $field); } @@ -162,11 +166,12 @@ public static function getFieldDefault($field_name) { * * @return Model */ - public static function loadByID() { + public static function loadByID() + { $stmt = DB::get(self::_getDatabaseNamespace())->from(get_called_class()); - foreach(self::_getIdentifyingColumns() as $index => $column) + foreach (self::_getIdentifyingColumns() as $index => $column) $stmt->where("$column = ?", func_get_arg($index)); return $stmt->fetchRow(); @@ -182,18 +187,19 @@ public static function loadByID() { * @return Model[] * @throws Wave\Exception */ - public static function loadAllByPage($results_per_page = null, $page_number = 0, &$number_of_results = 0) { + public static function loadAllByPage($results_per_page = null, $page_number = 0, &$number_of_results = 0) + { $stmt = DB::get(self::_getDatabaseNamespace()) ->from(get_called_class()); - if(isset($results_per_page)) { + if (isset($results_per_page)) { $stmt = $stmt->paginate($results_per_page * $page_number, $results_per_page * ($page_number + 1)); } $results = $stmt->fetchAll(); - if(isset($results_per_page)) { + if (isset($results_per_page)) { $number_of_results = $stmt->fetchRowCount(); } @@ -208,7 +214,8 @@ public static function loadAllByPage($results_per_page = null, $page_number = 0, * * @return bool */ - public function save($save_relations = true) { + public function save($save_relations = true) + { return DB::save($this, $save_relations); } @@ -217,13 +224,15 @@ public function save($save_relations = true) { * * @return bool */ - public function delete() { + public function delete() + { return DB::delete($this); } - public function _equals(Model $object) { + public function _equals(Model $object) + { return (get_class($this) === get_class($object)) && - array_diff_assoc($this->_getIdentifyingData(), $object->_getIdentifyingData()); + array_diff_assoc($this->_getIdentifyingData(), $object->_getIdentifyingData()); } /** @@ -233,9 +242,10 @@ public function _equals(Model $object) { * @param $alias * @param $resolved_class */ - public function addJoinedObject(Model &$object, $alias, $resolved_class) { + public function addJoinedObject(Model &$object, $alias, $resolved_class) + { $this->_joined_aliases[$resolved_class][] = $alias; - if(!isset($this->_joined_objects[$alias])) + if (!isset($this->_joined_objects[$alias])) $this->_joined_objects[$alias] = array(); $this->_joined_objects[$alias][] = $object; @@ -250,38 +260,43 @@ public function addJoinedObject(Model &$object, $alias, $resolved_class) { * * @return mixed */ - public function getid() { + public function getid() + { return $this->_data[self::_getTableName() . '_id']; } /** * @return array */ - public function _getData() { + public function _getData() + { return $this->_data; } /** * @return array */ - public function _getDirty() { + public function _getDirty() + { return array_intersect_key($this->_data, $this->_dirty); } /** * @return string */ - public static function _getTableName() { + public static function _getTableName() + { return static::$_table_name; } /** * @return string */ - public static function _getSchemaName() { + public static function _getSchemaName() + { $namespace = static::_getDatabaseNamespace(); - if(!isset(static::$_schema_names[$namespace])) { + if (!isset(static::$_schema_names[$namespace])) { static::$_schema_names[$namespace] = DB::get($namespace)->getSchema(); } @@ -291,7 +306,8 @@ public static function _getSchemaName() { /** * @return string */ - public static function _getDatabaseNamespace() { + public static function _getDatabaseNamespace() + { return static::$_database; } @@ -300,7 +316,8 @@ public static function _getDatabaseNamespace() { * * @return array */ - public static function _getFields($field_data = false) { + public static function _getFields($field_data = false) + { return $field_data ? static::$_fields : array_keys(static::$_fields); } @@ -309,14 +326,16 @@ public static function _getFields($field_data = false) { * * @return mixed */ - public static function _getField($field_name) { + public static function _getField($field_name) + { return static::$_fields[$field_name]; } /** * @return mixed */ - public static function _getRelations() { + public static function _getRelations() + { return static::$_relations; } @@ -329,9 +348,10 @@ public static function _getRelations() { * @return mixed * @throws \Wave\Exception */ - public static function _getRelation($relation_name) { + public static function _getRelation($relation_name) + { - if(isset(static::$_relations[$relation_name])){ + if (isset(static::$_relations[$relation_name])) { return static::$_relations[$relation_name]; } @@ -344,9 +364,10 @@ public static function _getRelation($relation_name) { * @param $class_name * @return null|string */ - public static function _findRelationName($class_name){ - foreach(static::$_relations as $rel_name => $relation){ - if($relation['related_class'] === $class_name){ + public static function _findRelationName($class_name) + { + foreach (static::$_relations as $rel_name => $relation) { + if ($relation['related_class'] === $class_name) { return $rel_name; } } @@ -356,7 +377,8 @@ public static function _findRelationName($class_name){ /** * @return array */ - public function _getJoinedObjects() { + public function _getJoinedObjects() + { return $this->_joined_objects; } @@ -367,10 +389,11 @@ public function _getJoinedObjects() { * * @return array */ - public function _getJoinedObjectsForClass($class) { + public function _getJoinedObjectsForClass($class) + { $objects = array(); - if(isset($this->_joined_aliases[$class])) { - foreach($this->_joined_aliases[$class] as $alias) { + if (isset($this->_joined_aliases[$class])) { + foreach ($this->_joined_aliases[$class] as $alias) { $objects = array_merge($objects, $this->_joined_objects[$alias]); } } @@ -385,7 +408,8 @@ public function _getJoinedObjectsForClass($class) { * * @return bool */ - public function _setLoaded($loaded = true) { + public function _setLoaded($loaded = true) + { //at this point it won't be dirty. $this->_dirty = array(); return $this->_loaded = $loaded; @@ -394,23 +418,26 @@ public function _setLoaded($loaded = true) { /** * @return bool */ - public function _isLoaded() { + public function _isLoaded() + { return $this->_loaded; } /** * @return bool */ - public function _isDirty() { + public function _isDirty() + { return count($this->_dirty) !== 0; } /** * @return null|array */ - public static function _getPrimaryKey() { - foreach(static::$_constraints as $constraint) - if($constraint['type'] === Constraint::TYPE_PRIMARY) + public static function _getPrimaryKey() + { + foreach (static::$_constraints as $constraint) + if ($constraint['type'] === Constraint::TYPE_PRIMARY) return $constraint['fields']; return null; @@ -421,7 +448,8 @@ public static function _getPrimaryKey() { * * @return array */ - public function _getIdentifyingData() { + public function _getIdentifyingData() + { $columns = self::_getIdentifyingColumns(); return array_intersect_key($this->_data, array_flip($columns)); } @@ -431,7 +459,8 @@ public function _getIdentifyingData() { * * @return array */ - public function jsonSerialize() { + public function jsonSerialize(): mixed + { return $this->_data; } @@ -444,16 +473,17 @@ public function jsonSerialize() { * * @return array */ - public static function _getIdentifyingColumns() { + public static function _getIdentifyingColumns() + { //first PK - foreach(static::$_constraints as $constraint) { - if($constraint['type'] === Constraint::TYPE_PRIMARY) + foreach (static::$_constraints as $constraint) { + if ($constraint['type'] === Constraint::TYPE_PRIMARY) return $constraint['fields']; - elseif($constraint['type'] === Constraint::TYPE_UNIQUE) + elseif ($constraint['type'] === Constraint::TYPE_UNIQUE) $unique = $constraint['fields']; } //then unique if no return for primary - if(isset($unique)) + if (isset($unique)) return $unique; //then all (if no keys are set for some reason) @todo - throw appropriate error @@ -464,10 +494,11 @@ public static function _getIdentifyingColumns() { /** * Generates a string hash of the object based on 'identifying data' returned from the above methods. */ - public function _getFingerprint(){ + public function _getFingerprint() + { $database = DB::get($this->_getDatabaseNamespace()); - $values = array_map(function($value) use ($database) { + $values = array_map(function ($value) use ($database) { return $database->valueToSQL($value); }, $this->_getIdentifyingData()); @@ -482,9 +513,10 @@ public function _getFingerprint(){ * * @return array */ - public function _toArray() { + public function _toArray(): array + { $data = array(); - foreach(static::_getFields(false) as $field) { + foreach (static::_getFields(false) as $field) { $getter = self::_getGetter($field); $data[$field] = $this->$getter(); } @@ -500,11 +532,12 @@ public function _toArray() { * * @return mixed */ - public function __set($property, $data) { + public function __set($property, $data) + { $setter = self::_getSetter($property); - if(method_exists($this, $setter)) { - if($this->$property === $data) + if (method_exists($this, $setter)) { + if ($this->$property === $data) return $data; return $this->$setter($data); @@ -521,9 +554,10 @@ public function __set($property, $data) { * * @return mixed */ - public function __get($property) { + public function __get($property) + { $getter = self::_getGetter($property); - if(!method_exists($this, $getter)) { + if (!method_exists($this, $getter)) { $stack = debug_backtrace(false); $stack = array_shift($stack); trigger_error('Notice: Undefined property ' . get_called_class() . '::' . $property . ' in ' . $stack['file'] . ' on line ' . $stack['line'] . " (via by Wave\\DB_Model::__get())\n"); @@ -540,21 +574,24 @@ public function __get($property) { * * @return bool */ - public function __isset($property) { + public function __isset($property) + { return method_exists($this, self::_getGetter($property)); } - public function __unset($property){ + public function __unset($property) + { $this->__set($property, self::getFieldDefault($property)); } - public function __clone(){ - if(null === $pk = $this->_getPrimaryKey()){ + public function __clone() + { + if (null === $pk = $this->_getPrimaryKey()) { return; } - foreach($pk as $field_name) { + foreach ($pk as $field_name) { unset($this->$field_name); } $this->_setLoaded(false); @@ -567,7 +604,8 @@ public function __clone(){ * * @return string */ - private static function _getSetter($property) { + private static function _getSetter($property) + { return 'set' . $property; } @@ -577,21 +615,24 @@ private static function _getSetter($property) { * * @return string */ - private static function _getGetter($property) { + private static function _getGetter($property) + { return 'get' . $property; } /** * @return Model */ - public function _getParentObject() { + public function _getParentObject() + { return $this->_parent_object; } /** * @param Model $parent_object */ - public function _setParentObject(Model $parent_object) { + public function _setParentObject(Model $parent_object) + { $this->_parent_object = $parent_object; } @@ -603,18 +644,19 @@ public function _setParentObject(Model $parent_object) { * @param Model $object * */ - protected function _setRelationObject($relation_name, Model $object, $create_relation) { + protected function _setRelationObject($relation_name, Model $object, $create_relation) + { $this->_data[$relation_name] = $object; $object->_setParentObject($this); - if($object !== null && $create_relation) { - if(!$object->_isLoaded()) + if ($object !== null && $create_relation) { + if (!$object->_isLoaded()) $object->save(); $relation_data = $this->_getRelation($relation_name); - foreach($relation_data['local_columns'] as $position => $local_column){ + foreach ($relation_data['local_columns'] as $position => $local_column) { $setter = self::_getSetter($local_column); $this->$setter($object->{$relation_data['related_columns'][$position]}); } @@ -630,26 +672,27 @@ protected function _setRelationObject($relation_name, Model $object, $create_rel * @param $create_relation * @throws Wave\Exception */ - protected function _addRelationObject($relation_name, Model $object, $create_relation = true, $join_data = array()) { + protected function _addRelationObject($relation_name, Model $object, $create_relation = true, $join_data = array()) + { $this->_data[$relation_name][] = $object; $relation_data = $this->_getRelation($relation_name); - if($object !== null && $create_relation) { + if ($object !== null && $create_relation) { - switch($relation_data['relation_type']) { + switch ($relation_data['relation_type']) { case Relation::MANY_TO_MANY: - if(!$object->_isLoaded()) + if (!$object->_isLoaded()) $object->save(); $related_class_name = $relation_data['related_class']; $rc = new $related_class_name(); - foreach($join_data as $key => $value){ + foreach ($join_data as $key => $value) { $rc->{$key} = $value; } - foreach($relation_data['target_relation']['local_columns'] as $position => $local_column){ + foreach ($relation_data['target_relation']['local_columns'] as $position => $local_column) { $rc->{$local_column} = $object->{$relation_data['target_relation']['related_columns'][$position]}; } @@ -657,7 +700,7 @@ protected function _addRelationObject($relation_name, Model $object, $create_rel //Deliberate non-break here so the -many logic flows on with $object reassigned. $object = $rc; case Relation::ONE_TO_MANY: - foreach($relation_data['local_columns'] as $position => $local_column) + foreach ($relation_data['local_columns'] as $position => $local_column) $object->{$relation_data['related_columns'][$position]} = $this->_data[$local_column]; $object->_setParentObject($this); @@ -677,40 +720,41 @@ protected function _addRelationObject($relation_name, Model $object, $create_rel * @return null * @throws Wave\Exception */ - protected function _getRelationObjects($relation_name, $query_transform_callback = null) { + protected function _getRelationObjects($relation_name, $query_transform_callback = null) + { $relation_data = $this->_getRelation($relation_name); - if(!isset($this->_data[$relation_name])) { + if (!isset($this->_data[$relation_name])) { $related_class = $relation_data['related_class']; $db = Wave\DB::get($related_class::_getDatabaseNamespace()); $query = $db->from($related_class, $from_alias); //Add in all of the related columns - foreach($relation_data['local_columns'] as $position => $local_column) { + foreach ($relation_data['local_columns'] as $position => $local_column) { //At this point, may as well return as there aren't null-relations - if(!isset($this->_data[$local_column])){ + if (!isset($this->_data[$local_column])) { return null; } $query->where(sprintf('%s.%s = ?', $from_alias, $db->escape($relation_data['related_columns'][$position])), $this->_data[$local_column]); } - if($query_transform_callback !== null && is_callable($query_transform_callback)){ + if ($query_transform_callback !== null && is_callable($query_transform_callback)) { call_user_func($query_transform_callback, $query); } - switch($relation_data['relation_type']){ + switch ($relation_data['relation_type']) { case Relation::MANY_TO_MANY: $target_relation = $related_class::_findRelationName($relation_data['target_relation']['related_class']); $query->with($target_relation); //I can put this here! //Relation on the 'with' will always be -to-one $this->_data[$relation_name] = array(); - while($row = $query->fetchRow()){ + while ($row = $query->fetchRow()) { $target = $row->$target_relation; //If you have a m2m in the DB without the related row? - if($target !== null) + if ($target !== null) $this->_data[$relation_name][] = $target; } break; @@ -738,12 +782,13 @@ protected function _getRelationObjects($relation_name, $query_transform_callback * @throws Exception * @throws Wave\Exception */ - public function _removeRelationObject($relation_name, Model $object, $remove_relation = true){ + public function _removeRelationObject($relation_name, Model $object, $remove_relation = true) + { - if(isset($this->_data[$relation_name])) { - foreach($this->_data[$relation_name] as $key => $relation){ - if($relation->_getFingerprint() === $object->_getFingerprint()){ + if (isset($this->_data[$relation_name])) { + foreach ($this->_data[$relation_name] as $key => $relation) { + if ($relation->_getFingerprint() === $object->_getFingerprint()) { //Unset unset($this->_data[$relation_name][$key]); //Renumber (so it doesn't accidentally map later down the track). @@ -752,40 +797,40 @@ public function _removeRelationObject($relation_name, Model $object, $remove_rel } } - if($remove_relation) { + if ($remove_relation) { $relation_data = $this->_getRelation($relation_name); - switch($relation_data['relation_type']){ + switch ($relation_data['relation_type']) { case Relation::MANY_TO_MANY: $related_class = $relation_data['related_class']; $db = Wave\DB::get($related_class::_getDatabaseNamespace()); $query = $db->from($related_class, $from_alias); //Add in all of the related columns - foreach($relation_data['local_columns'] as $position => $local_column) { + foreach ($relation_data['local_columns'] as $position => $local_column) { //At this point, may as well return as there aren't null-relations - if($this->_data[$local_column] === null) + if ($this->_data[$local_column] === null) return false; $query->where(sprintf('%s.%s = ?', $from_alias, $db->escape($relation_data['related_columns'][$position])), $this->_data[$local_column]); } //Add in all of the related columns - foreach($relation_data['target_relation']['related_columns'] as $position => $related_column) { + foreach ($relation_data['target_relation']['related_columns'] as $position => $related_column) { //At this point, may as well return as there aren't null-relations - if($object->{$related_column} === null) + if ($object->{$related_column} === null) return false; $query->where(sprintf('%s.%s = ?', $from_alias, $db->escape($relation_data['target_relation']['local_columns'][$position])), $object->{$related_column}); } - if($rc = $query->fetchRow()) + if ($rc = $query->fetchRow()) return $rc->delete(); break; case Relation::ONE_TO_MANY: - foreach($relation_data['related_columns'] as $position => $related_column) + foreach ($relation_data['related_columns'] as $position => $related_column) $object->{$related_column} = null; return $object->save(); diff --git a/src/Wave/DB/Query.php b/src/Wave/DB/Query.php index 97bdf7a..dc51984 100644 --- a/src/Wave/DB/Query.php +++ b/src/Wave/DB/Query.php @@ -15,7 +15,8 @@ * @method \Wave\DB\Query and () and ($condition, mixed $params = array()) * @method \Wave\DB\Query or () or ($condition, mixed $params = array()) */ -class Query { +class Query +{ const CLAUSE_JOIN = 1; const CLAUSE_WHERE = 2; @@ -49,7 +50,8 @@ class Query { private $relation_tables = array(); - public function __construct(Connection $connection) { + public function __construct(Connection $connection) + { $this->connection = $connection; $this->alias_counter = 'a'; } @@ -66,13 +68,14 @@ public function __construct(Connection $connection) { * * @return Query */ - public function from($from, &$alias = null, array $fields = null) { + public function from($from, &$alias = null, array $fields = null) + { //if a relative reference, add the ns prefix - will be most of the time $this->resolveNamespace($from); //populate table fields if not specified. - if($fields === null) { + if ($fields === null) { $this->manual_select = false; $this->addFieldsToSelect($from, $alias); } else { @@ -101,19 +104,20 @@ public function from($from, &$alias = null, array $fields = null) { * * @return Query */ - public function with($relation, &$alias = null) { + public function with($relation, &$alias = null) + { $from_class = $this->unaliasClass($this->from_alias); $relation_data = $from_class::_getRelation($relation); //if it's many to many, load the related class and flag the first join to be attached as relation data - if($relation_data['relation_type'] === Wave\DB\Relation::MANY_TO_MANY) { + if ($relation_data['relation_type'] === Wave\DB\Relation::MANY_TO_MANY) { $this->leftJoin($relation_data['related_class'], $related_alias, $target_alias); //more iteration for multi-column relations - foreach($relation_data['related_columns'] as $index => $related_column) { + foreach ($relation_data['related_columns'] as $index => $related_column) { $func = $index === 0 ? 'on' : 'and'; $this->$func( sprintf( @@ -125,7 +129,7 @@ public function with($relation, &$alias = null) { $this->leftJoin($relation_data['target_relation']['related_class'], $alias); - foreach($relation_data['target_relation']['related_columns'] as $index => $related_column) { + foreach ($relation_data['target_relation']['related_columns'] as $index => $related_column) { $func = $index === 0 ? 'on' : 'and'; $this->$func( sprintf( @@ -143,7 +147,7 @@ public function with($relation, &$alias = null) { $this->leftJoin($relation_data['related_class'], $alias); //more iteration for multi-column relations - foreach($relation_data['related_columns'] as $index => $related_column) { + foreach ($relation_data['related_columns'] as $index => $related_column) { $func = $index === 0 ? 'on' : 'and'; $this->$func( sprintf( @@ -169,7 +173,8 @@ public function with($relation, &$alias = null) { * Perform a left join * @see join */ - public function leftJoin($class, &$alias = null, &$target_alias = null) { + public function leftJoin($class, &$alias = null, &$target_alias = null) + { return $this->join('LEFT JOIN', $class, $alias, $target_alias); } @@ -177,7 +182,8 @@ public function leftJoin($class, &$alias = null, &$target_alias = null) { * Perform an inner join * @see join */ - public function innerJoin($class, &$alias = null, &$target_alias = null) { + public function innerJoin($class, &$alias = null, &$target_alias = null) + { return $this->join('INNER JOIN', $class, $alias, $target_alias); } @@ -185,7 +191,8 @@ public function innerJoin($class, &$alias = null, &$target_alias = null) { * Perform a right join * @see join */ - public function rightJoin($class, &$alias = null, &$target_alias = null) { + public function rightJoin($class, &$alias = null, &$target_alias = null) + { return $this->join('RIGHT JOIN', $class, $alias, $target_alias); } @@ -204,12 +211,13 @@ public function rightJoin($class, &$alias = null, &$target_alias = null) { * * @return Query */ - public function join($type, $class, &$alias = null, &$target_alias = null) { + public function join($type, $class, &$alias = null, &$target_alias = null) + { $this->_last_clause = self::CLAUSE_JOIN; //this is where to stick the joined object - if($target_alias === null) + if ($target_alias === null) $target_alias = $this->from_alias; $this->resolveNamespace($class); @@ -217,7 +225,7 @@ public function join($type, $class, &$alias = null, &$target_alias = null) { //@patrick, should this not actually select these rows? Should it be an extra parameter in the function constructor? //$join_table_alias = $this->addFieldsToSelect($class) could be replaced with: //$join_table_alias = $this->aliasClass($class); // so it didn't add the fields but still aliased the table - if(!$this->manual_select) + if (!$this->manual_select) $this->addFieldsToSelect($class, $alias); else $this->aliasClass($class, $alias); @@ -241,7 +249,8 @@ public function join($type, $class, &$alias = null, &$target_alias = null) { * * @return Query */ - public function on($condition) { + public function on($condition) + { $this->addJoinCondition("ON $condition"); return $this; @@ -255,9 +264,10 @@ public function on($condition) { * * @return Query */ - public function using($fields) { + public function using($fields) + { - if(!is_array($fields)) + if (!is_array($fields)) $fields = array($fields); $this->addJoinCondition(sprintf('USING(%s)', implode(',', $fields))); @@ -271,10 +281,11 @@ public function using($fields) { * * @throws \Wave\Exception */ - private function addJoinCondition($condition) { + private function addJoinCondition($condition) + { $last_index = count($this->joins) - 1; - if($last_index === -1) + if ($last_index === -1) throw new Wave\Exception('Wave\DB\Query::on and ::using may only be used following a join.'); $this->joins[$last_index]['condition'] .= " $condition"; @@ -299,8 +310,9 @@ private function addJoinCondition($condition) { * @return Query * @throws \Wave\Exception when called using the legacy version of the function */ - public function where($condition, $params = array()) { - if(func_num_args() > 2) throw new \Wave\Exception("Invalid use of Query::where() function"); + public function where($condition, $params = array()) + { + if (func_num_args() > 2) throw new \Wave\Exception("Invalid use of Query::where() function"); return $this->andWhere($condition, $params); } @@ -309,7 +321,8 @@ public function where($condition, $params = array()) { * * @see where */ - public function orWhere($condition, $params = array()) { + public function orWhere($condition, $params = array()) + { $this->_last_clause = self::CLAUSE_WHERE; $this->addWhereCondition($condition, $params, 'OR', true); @@ -321,7 +334,8 @@ public function orWhere($condition, $params = array()) { * * @see where */ - public function andWhere($condition, $params = array()) { + public function andWhere($condition, $params = array()) + { $this->_last_clause = self::CLAUSE_WHERE; $this->addWhereCondition($condition, $params, 'AND', true); @@ -339,28 +353,29 @@ public function andWhere($condition, $params = array()) { * * @throws \Wave\Exception */ - private function addWhereCondition($condition, $params, $type, $create = false) { + private function addWhereCondition($condition, $params, $type, $create = false) + { $current_index = count($this->where); $condition = self::parseWhereCondition($condition, $params); - if($condition === false) + if ($condition === false) return; - if($create) { + if ($create) { $this->where[] = array( 'type' => $type, 'condition' => $condition, 'params' => array() ); } else { - if($current_index-- === 0) + if ($current_index-- === 0) throw new Wave\Exception('Wave\DB\Query::and and ::or may only be used following a where.'); $this->where[$current_index]['condition'] .= sprintf(' %s %s', $type, $condition); } - if($params !== null) + if ($params !== null) $this->where[$current_index]['params'] = array_merge($this->where[$current_index]['params'], $params); } @@ -376,41 +391,42 @@ private function addWhereCondition($condition, $params, $type, $create = false) * * @return string the transformed condition */ - public static function parseWhereCondition($condition, &$params) { + public static function parseWhereCondition($condition, &$params) + { - if((stripos($condition, ' AND ') !== false && stripos($condition, 'BETWEEN') === false) || stripos($condition, ' OR ') !== false) + if ((stripos($condition, ' AND ') !== false && stripos($condition, 'BETWEEN') === false) || stripos($condition, ' OR ') !== false) trigger_error('You should be using ->or() or ->and() to add multiple criteria to a where clause.'); $num_placeholders = substr_count($condition, '?'); //if there are no placeholders, no transformation can be done on the params. - if($num_placeholders === 0) + if ($num_placeholders === 0) return $condition; - if(is_array($params)) { + if (is_array($params)) { $num_params = count($params); - if($num_params <= 0) { + if ($num_params <= 0) { $condition = 'FALSE'; } - if($num_placeholders < $num_params) { + if ($num_placeholders < $num_params) { //otherwise change the parameters to matcht he num in the array and make it an 'IN' clause. $condition = str_replace('?', '(' . implode(',', array_fill(0, $num_params, '?')) . ')', $condition); return str_replace(array('<>', '!=', '='), array('NOT IN', 'NOT IN', 'IN'), $condition); } } - if($num_placeholders === 1) { - if($params === null) + if ($num_placeholders === 1) { + if ($params === null) $condition = str_replace( array('<>', '!=', '=', '?'), array( - 'IS NOT', - 'IS NOT', - 'IS', - 'NULL' - ), $condition + 'IS NOT', + 'IS NOT', + 'IS', + 'NULL' + ), $condition ); - else if(!is_array($params)) + else if (!is_array($params)) $params = array($params); } @@ -431,8 +447,9 @@ public static function parseWhereCondition($condition, &$params) { * because or is a reserved word and cannot be used to declare a method (but can be used at runtime). * The equivalent function (without the prefixing underscore) is defined via magic methods). */ - public function _or($condition, $params = array()) { - switch($this->_last_clause) { + public function _or($condition, $params = array()) + { + switch ($this->_last_clause) { case self::CLAUSE_WHERE: $this->addWhereCondition($condition, $params, 'OR'); break; @@ -450,8 +467,9 @@ public function _or($condition, $params = array()) { * because or is a reserved word and cannot be used to declare a method (but can be used at runtime). * The equivilent function (without the prefixing underscore) is defined via magic methods). */ - public function _and($condition, $params = array()) { - switch($this->_last_clause) { + public function _and($condition, $params = array()) + { + switch ($this->_last_clause) { case self::CLAUSE_WHERE: $this->addWhereCondition($condition, $params, 'AND'); break; @@ -475,9 +493,10 @@ public function _and($condition, $params = array()) { * * @return Query */ - public function groupBy($column) { + public function groupBy($column) + { - if(!is_array($column)) + if (!is_array($column)) $column = array($column); $this->group = array_merge($this->group, $column); @@ -490,7 +509,8 @@ public function groupBy($column) { * * @return Query */ - public function orderBy($column) { + public function orderBy($column) + { $this->order = $column; return $this; @@ -503,9 +523,10 @@ public function orderBy($column) { * * @return Query */ - public function having($having, $params = array()) { + public function having($having, $params = array()) + { - if(!is_array($params)){ + if (!is_array($params)) { $params = array($params); } @@ -519,7 +540,8 @@ public function having($having, $params = array()) { * * @return Query */ - public function offset($offset) { + public function offset($offset) + { $this->offset = $offset; return $this; @@ -531,7 +553,8 @@ public function offset($offset) { * * @return Query */ - public function limit($limit) { + public function limit($limit) + { $this->limit = $limit; return $this; @@ -544,7 +567,8 @@ public function limit($limit) { * * @return Query */ - public function paginate($offset, $limit) { + public function paginate($offset, $limit) + { $this->paginate = true; @@ -560,7 +584,8 @@ public function paginate($offset, $limit) { * * @return Query */ - public function addParameter($param){ + public function addParameter($param) + { $this->_params[] = $param; return $this; @@ -571,14 +596,15 @@ public function addParameter($param){ * * @return string */ - public function buildSQL() { + public function buildSQL() + { $query = 'SELECT ' . ($this->paginate ? 'SQL_CALC_FOUND_ROWS ' : ''); $fields = array(); - foreach($this->fields as $alias => $field) { + foreach ($this->fields as $alias => $field) { //if the alias isn't a number, add it to the field - if(!is_int($alias)) + if (!is_int($alias)) $field .= ' AS ' . $alias; $fields[] = $field; } @@ -590,25 +616,25 @@ public function buildSQL() { $query .= sprintf("FROM %s.%s AS %s\n", $this->escape($from_class::_getSchemaName()), $this->escape($from_class::_getTableName()), $this->from_alias); //joins (includes withs) - foreach($this->joins as $join) { + foreach ($this->joins as $join) { /** @var Model $join_class */ $join_class = $join['class']; $query .= sprintf("%s %s.%s AS %s %s\n", $join['type'], $this->escape($join_class::_getSchemaName()), $this->escape($join_class::_getTableName()), $join['table_alias'], $join['condition']); } - foreach($this->where as $index => $where) { + foreach ($this->where as $index => $where) { $query .= ($index === 0 ? 'WHERE' : $where['type']); $query .= sprintf(" (%s)\n", $where['condition']); - if($where['params'] !== null) + if ($where['params'] !== null) $this->_params = array_merge($this->_params, $where['params']); } - if(isset($this->group[0])) $query .= 'GROUP BY ' . implode(',', $this->group) . "\n"; + if (isset($this->group[0])) $query .= 'GROUP BY ' . implode(',', $this->group) . "\n"; - if(isset($this->having)){ - foreach($this->having as $index => $having){ + if (isset($this->having)) { + foreach ($this->having as $index => $having) { $query .= ($index === 0 ? 'HAVING' : 'AND'); $query .= sprintf(' %s ', $having['condition']); $this->_params = array_merge($this->_params, $having['params']); @@ -616,11 +642,11 @@ public function buildSQL() { } - if(isset($this->order[0])) $query .= 'ORDER BY ' . $this->order . "\n"; + if (isset($this->order[0])) $query .= 'ORDER BY ' . $this->order . "\n"; - if(isset($this->limit)) { + if (isset($this->limit)) { $query .= 'LIMIT ' . $this->limit; - if(isset($this->offset)) + if (isset($this->offset)) $query .= ' OFFSET ' . $this->offset; } @@ -642,11 +668,12 @@ public function buildSQL() { * * @param bool $debug */ - public function execute($debug = false) { + public function execute($debug = false) + { $sql = $this->buildSQL(); - if($debug) { + if ($debug) { echo "QUERY: $sql\n"; echo "PARAMS: \n"; print_r($this->_params); @@ -669,10 +696,11 @@ public function execute($debug = false) { * * @return Model[]|array */ - public function fetchAll($parse_objects = true, $debug = false) { + public function fetchAll($parse_objects = true, $debug = false) + { $rows = array(); - while($row = $this->fetchRow($parse_objects, $debug)) { + while ($row = $this->fetchRow($parse_objects, $debug)) { $rows[] = $row; } @@ -690,34 +718,35 @@ public function fetchAll($parse_objects = true, $debug = false) { * * @return Model|array|null */ - public function fetchRow($parse_objects = true, $debug = false) { + public function fetchRow($parse_objects = true, $debug = false) + { $object_instances = array(); - if(!$this->_executed) + if (!$this->_executed) $this->execute($debug); - for(; ;) { + for (; ;) { - if($this->_last_row === false) + if ($this->_last_row === false) $this->_last_row = $this->_statement->fetch(); //if still false, return null (no rows left in set) - if($this->_last_row === false) + if ($this->_last_row === false) break; //if not bothering to parse object - if(!$parse_objects) { + if (!$parse_objects) { $output = array(); // if it's a manual select (fields were manually specified) then just put the // requested fields into the output directly, keyed by their aliases. - if($this->manual_select) { - if(isset($this->fields[0])) { + if ($this->manual_select) { + if (isset($this->fields[0])) { throw new Exception('An associative array must be passed in to \Wave\DB\Query::from() when not parsing objects'); } - foreach($this->fields as $alias => $field) { - if(isset($this->_last_row[$alias])) { + foreach ($this->fields as $alias => $field) { + if (isset($this->_last_row[$alias])) { $key = $this->manual_select ? $alias : $field; $output[$key] = $this->_last_row[$alias]; } @@ -726,14 +755,14 @@ public function fetchRow($parse_objects = true, $debug = false) { // otherwise, get the original column names and unalias the resultset, including the // joined rows, keyed by the aliases they were joined with else { - foreach($this->class_aliases[$this->from_alias]['columns'] as $column => $column_alias) { + foreach ($this->class_aliases[$this->from_alias]['columns'] as $column => $column_alias) { $output[$column] = $this->_last_row[$column_alias]; } - foreach($this->class_aliases as $alias => $class_details) { - if($alias === $this->from_alias) continue; + foreach ($this->class_aliases as $alias => $class_details) { + if ($alias === $this->from_alias) continue; - foreach($class_details['columns'] as $column => $column_alias) + foreach ($class_details['columns'] as $column => $column_alias) $output[$alias][$column] = $this->_last_row[$column_alias]; } } @@ -744,42 +773,42 @@ public function fetchRow($parse_objects = true, $debug = false) { //if there's no instance of the main class, create a new one. - if(!isset($object_instances[$this->from_alias])) + if (!isset($object_instances[$this->from_alias])) $object_instances[$this->from_alias] = $this->buildClassInstance($this->from_alias); - if($object_instances[$this->from_alias] === null) { + if ($object_instances[$this->from_alias] === null) { trigger_error('Insufficient data in SELECT to build object instance.'); return null; } //if there are joins, check that the current row still has the same $from_instance, if it doesn't, break. //otherwise build the related objects and put them on it. - if(isset($this->joins[0])) { + if (isset($this->joins[0])) { //if the from instance is different, break and leave it for the next call to fetchRow(). - foreach($object_instances[$this->from_alias]->_getIdentifyingData() as $property => $value) { + foreach ($object_instances[$this->from_alias]->_getIdentifyingData() as $property => $value) { $class = $this->class_aliases[$this->from_alias]['class']; $alias = $this->class_aliases[$this->from_alias]['columns'][$property]; $driver_class = $this->connection->getDriverClass(); $cast_value = $driver_class::valueFromSQL($this->_last_row[$alias], $class::_getField($property)); - if($cast_value !== $value) + if ($cast_value !== $value) return isset($object_instances[$this->from_alias]) ? $object_instances[$this->from_alias] : null; // break 2; } //otherwise build the child rows - foreach($this->joins as $join) { + foreach ($this->joins as $join) { $object_instances[$join['table_alias']] = $this->buildClassInstance($join['table_alias']); } //then check non-null child rows and add them to their parent rows - foreach($this->joins as $join) { - if($object_instances[$join['table_alias']] === null) + foreach ($this->joins as $join) { + if ($object_instances[$join['table_alias']] === null) continue; //find if is a join or a with - if(isset($this->with[$join['table_alias']])) { - switch($this->with[$join['table_alias']]['relation_type']) { + if (isset($this->with[$join['table_alias']])) { + switch ($this->with[$join['table_alias']]['relation_type']) { case Wave\DB\Relation::ONE_TO_ONE: case Wave\DB\Relation::MANY_TO_ONE: $object_instances[$join['target_alias']]->{'set' . $this->with[$join['table_alias']]['relation_name']}($object_instances[$join['table_alias']], false); @@ -817,21 +846,22 @@ public function fetchRow($parse_objects = true, $debug = false) { * * @return null|Model */ - private function buildClassInstance($class_alias) { + private function buildClassInstance($class_alias) + { /** @var Model $class */ $class = $this->unaliasClass($class_alias); $columns = $this->class_aliases[$class_alias]['columns']; $build_array = array(); - foreach($columns as $column_name => $column_alias) { + foreach ($columns as $column_name => $column_alias) { //$field = $class::_getField($column_name); //$cast_value = $this->database->valueFromSQL($this->_last_row[$column_alias], $field); $build_array[$column_name] = $this->_last_row[$column_alias]; } $instance = $class::createFromArray($build_array); - if($instance !== null) + if ($instance !== null) $instance->_setLoaded(); return $instance; @@ -840,9 +870,10 @@ private function buildClassInstance($class_alias) { //This method will not work if the last query contained a join //@todo do a seperate count on the last query. - public function fetchRowCount() { + public function fetchRowCount() + { - if($this->paginate === false) + if ($this->paginate === false) throw new \Wave\Exception('Wave\DB::fetchRowCount can only be used when paginating'); $sql = 'SELECT FOUND_ROWS() AS row_count;'; @@ -862,15 +893,16 @@ public function fetchRowCount() { * * @return string */ - private function resolveNamespace(&$class) { + private function resolveNamespace(&$class) + { - if(strpos($class, '\\') === 0 && class_exists($class)) + if (strpos($class, '\\') === 0 && class_exists($class)) return $class; $class = trim($class, '\\'); $namespace = $this->connection->getNamespace(); $namespace = Config::get('wave')->model->base_namespace . '\\' . $namespace; - if(strpos($class, $namespace) !== 0) + if (strpos($class, $namespace) !== 0) $class = $namespace . '\\' . $class; return "\\$class"; @@ -884,10 +916,11 @@ private function resolveNamespace(&$class) { * * @return null */ - private function addFieldsToSelect($class, &$class_alias = null) { + private function addFieldsToSelect($class, &$class_alias = null) + { /** @var Model $class */ $this->aliasClass($class, $class_alias); - foreach($class::_getFields() as $field) + foreach ($class::_getFields() as $field) $this->aliasColumn($class_alias, $field); //this is so the correct alias can be used in joins etc. @@ -901,9 +934,10 @@ private function addFieldsToSelect($class, &$class_alias = null) { * * @return string */ - private function aliasClass($class, &$alias = null) { + private function aliasClass($class, &$alias = null) + { - if($alias === null) + if ($alias === null) $alias = $this->getAlias(); $this->class_aliases[$alias] = array( @@ -920,7 +954,8 @@ private function aliasClass($class, &$alias = null) { * * @return mixed */ - private function unaliasClass($alias) { + private function unaliasClass($alias) + { return $this->class_aliases[$alias]['class']; } @@ -931,7 +966,8 @@ private function unaliasClass($alias) { * * @return string */ - private function aliasColumn($table, $column) { + private function aliasColumn($table, $column) + { $alias = $this->getAlias(); $column_alias = sprintf('%s.%s', $table, $this->escape($column)); @@ -948,7 +984,8 @@ private function aliasColumn($table, $column) { * * @return array */ - private function unaliasColumn($alias) { + private function unaliasColumn($alias) + { $column_alias = $this->fields[$alias]; list($class_alias, $column) = explode('.', $column_alias); @@ -968,7 +1005,8 @@ private function unaliasColumn($alias) { * * @return string */ - private function getAlias() { + private function getAlias() + { return '_' . $this->alias_counter++; } @@ -978,7 +1016,8 @@ private function getAlias() { * * @return string */ - private function escape($text) { + private function escape($text) + { $driver = $this->connection->getDriverClass(); return $driver::getEscapeCharacter() . $text . $driver::getEscapeCharacter(); } @@ -989,7 +1028,8 @@ private function escape($text) { * * @return string */ - private function unescape($text) { + private function unescape($text) + { $driver = $this->connection->getDriverClass(); return trim($text, $driver::getEscapeCharacter()); @@ -1007,14 +1047,15 @@ private function unescape($text) { * @return Query * @throws \Wave\Exception */ - public function __call($method, $args) { + public function __call($method, $args) + { - if($method != 'or' && $method != 'and') + if ($method != 'or' && $method != 'and') throw new Wave\Exception("[$method] does not exist"); $method = '_' . $method; - switch(count($args)) { + switch (count($args)) { case 1: return $this->$method($args[0]); case 2: diff --git a/src/Wave/DB/Relation.php b/src/Wave/DB/Relation.php index 9af1b90..7866155 100644 --- a/src/Wave/DB/Relation.php +++ b/src/Wave/DB/Relation.php @@ -11,7 +11,8 @@ use Wave; -class Relation { +class Relation +{ const RELATION_UNKNOWN = 00; @@ -31,7 +32,8 @@ class Relation { private $instance_name; - private function __construct(Column $local_column, Column $referenced_column, $is_reverse_relation, $instance_name = '') { + private function __construct(Column $local_column, Column $referenced_column, $is_reverse_relation, $instance_name = '') + { $this->local_columns[] = $is_reverse_relation ? $referenced_column : $local_column; $this->referenced_columns[] = $is_reverse_relation ? $local_column : $referenced_column; @@ -41,17 +43,18 @@ private function __construct(Column $local_column, Column $referenced_column, $i } - public static function create(Column $local_column, Column $referenced_column, $constraint_name, $is_reverse_relation) { + public static function create(Column $local_column, Column $referenced_column, $constraint_name, $is_reverse_relation) + { //This is to support multiple column foreign keys, any constraints with the same name will be treated as an additional column. //An assumption is made in the driver that the constraint names will be unique across the table $instance_name = sprintf( '%s.%s.%s__%s', $local_column->getTable()->getDatabase()->getName(), $local_column->getTable() - ->getName(), $constraint_name, + ->getName(), $constraint_name, $is_reverse_relation ? 'reverse' : 'forward' ); - if(isset(self::$instances[$instance_name])) { + if (isset(self::$instances[$instance_name])) { self::$instances[$instance_name]->addColumns($local_column, $referenced_column, $is_reverse_relation); } else { self::$instances[$instance_name] = new self($local_column, $referenced_column, $is_reverse_relation, $instance_name); @@ -61,28 +64,29 @@ public static function create(Column $local_column, Column $referenced_column, $ } - private function determineRelationType() { + private function determineRelationType() + { //all relation definitions based on the first column in the key - if($this->local_columns[0]->isPrimaryKey() && $this->referenced_columns[0]->isPrimaryKey()) { + if ($this->local_columns[0]->isPrimaryKey() && $this->referenced_columns[0]->isPrimaryKey()) { //will either be a one-one relation or a many-many join table - if($this->getLocalTable()->getPrimaryKey() !== null && count( + if ($this->getLocalTable()->getPrimaryKey() !== null && count( $this->getLocalTable()->getPrimaryKey()->getColumns() ) > 1 ) { //if local table has more than one PK it's modt likely a join table. $type = self::MANY_TO_ONE; - } elseif($this->getReferencedTable()->getPrimaryKey() !== null && 1 < $num_ref_column = count( + } elseif ($this->getReferencedTable()->getPrimaryKey() !== null && 1 < $num_ref_column = count( $this->getReferencedTable()->getPrimaryKey()->getColumns() ) ) { //if referencing a table with dual PK, it's most likely a m2m join table that has more to load. - if($num_ref_column === 2) { + if ($num_ref_column === 2) { $type = self::MANY_TO_MANY; //go back and find the other relation //need to iterate to find the one that's not this. - foreach($this->getReferencedTable()->getRelations() as $relation) { + foreach ($this->getReferencedTable()->getRelations() as $relation) { if ($relation->getReferencedColumns() != $this->local_columns) { $this->target_relation = $relation; break; @@ -91,7 +95,7 @@ private function determineRelationType() { //if target relation isn't found, there must be a special case, so just roll back to one-to-many //or if target relation has a dual primary key, can't base it being a join table on it anymore. - if($this->target_relation === null || count( + if ($this->target_relation === null || count( $this->target_relation->getReferencedTable()->getPrimaryKey()->getColumns() ) > 1 ) @@ -106,7 +110,7 @@ private function determineRelationType() { $type = self::ONE_TO_ONE; } - } elseif($this->is_reverse_relation) { + } elseif ($this->is_reverse_relation) { $type = self::ONE_TO_MANY; } else { $type = self::MANY_TO_ONE; @@ -116,43 +120,51 @@ private function determineRelationType() { return $type; } - public function addColumns($local_column, $referenced_column, $is_reverse_relation) { + public function addColumns($local_column, $referenced_column, $is_reverse_relation) + { $column = $is_reverse_relation ? $referenced_column : $local_column; - if(!in_array($column, $this->local_columns)) + if (!in_array($column, $this->local_columns)) $this->local_columns[] = $column; $column = $is_reverse_relation ? $local_column : $referenced_column; - if(!in_array($column, $this->referenced_columns)) + if (!in_array($column, $this->referenced_columns)) $this->referenced_columns[] = $column; } - public function getLocalColumns() { + public function getLocalColumns() + { return $this->local_columns; } - public function getLocalTable() { + public function getLocalTable() + { //it will always be the same if there are multiple columns return $this->local_columns[0]->getTable(); } - public function getReferencedColumns() { + public function getReferencedColumns() + { return $this->referenced_columns; } - public function getReferencedTable() { + public function getReferencedTable() + { //it will always be the same if there are multiple columns return $this->referenced_columns[0]->getTable(); } - public function getTargetRelation() { + public function getTargetRelation() + { return $this->target_relation; } - public function getType() { + public function getType() + { return $this->type; } - public function getIdentifyingName() { + public function getIdentifyingName() + { return $this->instance_name; } @@ -161,32 +173,33 @@ public function getIdentifyingName() { * is more than one relation to the same table, the relation won't have a unique name. * If the column ends with '_id', it will be removed. **/ - public function getName() { + public function getName() + { //$local_column - switch($this->type) { + switch ($this->type) { case self::ONE_TO_ONE: $name = $this->getReferencedTable()->getName(); break; case self::MANY_TO_ONE: //in this case we need to name the relation based on the column, trimming off _id (if it exists) $name = $this->local_columns[0]->getName(); - if(substr($name, -3) === '_id') + if (substr($name, -3) === '_id') $name = substr($name, 0, -3); break; case self::ONE_TO_MANY: //slightly more complex to remove collisions between m2m names $name = Wave\Inflector::pluralize($this->getReferencedTable()->getName()); $ref_name = $this->referenced_columns[0]->getName(); - if(substr($ref_name, -3) === '_id') + if (substr($ref_name, -3) === '_id') $ref_name = substr($ref_name, 0, -3); - if($ref_name !== $this->getLocalTable()->getName()) + if ($ref_name !== $this->getLocalTable()->getName()) $name .= '_' . $ref_name; break; case self::MANY_TO_MANY: $columns = $this->target_relation->getLocalColumns(); $name = $columns[0]->getMetadata('relation_name'); - if($name === null) { + if ($name === null) { $name = $this->target_relation->getReferencedTable()->getName(); } @@ -202,7 +215,8 @@ public function getName() { * Provide a representation of this relation that can be used to calculate a fingerprint * for whether it has changed or not. This is used by the Table getSchemaFingerprint */ - public function __serialize() { + public function __serialize() + { $serialized = [ 'instance_name' => $this->instance_name, 'local_columns' => array_map(fn($column) => $this->serializeColumn($column), $this->getLocalColumns()), @@ -217,14 +231,15 @@ public function __serialize() { } /** - * For relations, the only thing that matters is the name of the column and the - * database/table it comes from. Other attributes like type etc are not factored + * For relations, the only thing that matters is the name of the column and the + * database/table it comes from. Other attributes like type etc are not factored * in this context */ - private function serializeColumn(Column $column) { + private function serializeColumn(Column $column) + { return [ - $column->getTable()->getDatabase()->getName(), - $column->getTable()->getName(), + $column->getTable()->getDatabase()->getName(), + $column->getTable()->getName(), $column->getName() ]; } diff --git a/src/Wave/DB/Statement.php b/src/Wave/DB/Statement.php index dd5279c..224ffff 100755 --- a/src/Wave/DB/Statement.php +++ b/src/Wave/DB/Statement.php @@ -2,26 +2,31 @@ namespace Wave\DB; -class Statement extends \PDOStatement { +class Statement extends \PDOStatement +{ private $connection; - protected function __construct(Connection $connection) { + protected function __construct(Connection $connection) + { $this->setFetchMode(\PDO::FETCH_ASSOC); $this->connection = $connection; } - public function execute($input_parameters = null) { + public function execute($input_parameters = null): bool + { $start = microtime(true); - parent::execute($input_parameters); + $result = parent::execute($input_parameters); \Wave\Debug::getInstance()->addQuery($time = microtime(true) - $start, $this); //printf("%s: %s: %s\n", microtime(true), $time, implode(' ', explode("\n", $this->queryString))); + + return $result; } } diff --git a/src/Wave/DB/Table.php b/src/Wave/DB/Table.php index 0437283..965ab41 100644 --- a/src/Wave/DB/Table.php +++ b/src/Wave/DB/Table.php @@ -11,7 +11,8 @@ use Wave; -class Table { +class Table +{ /** @var \Wave\DB $database */ private $database; @@ -31,7 +32,8 @@ class Table { /** @var Constraint[] $constraints */ private $constraints; - public function __construct(Wave\DB $database, $table, $engine = '', $collation = '', $comment = '') { + public function __construct(Wave\DB $database, $table, $engine = '', $collation = '', $comment = '') + { $this->database = $database; $this->table = $table; @@ -43,9 +45,10 @@ public function __construct(Wave\DB $database, $table, $engine = '', $collation /** * @return Column[] */ - public function getColumns() { + public function getColumns() + { - if(!isset($this->columns)) { + if (!isset($this->columns)) { $driver_class = $this->database->getConnection()->getDriverClass(); $this->columns = $driver_class::getColumns($this); } @@ -56,9 +59,10 @@ public function getColumns() { /** * @return Relation[] */ - public function getRelations() { + public function getRelations() + { - if(!isset($this->relations)) { + if (!isset($this->relations)) { $driver_class = $this->database->getConnection()->getDriverClass(); $this->relations = $driver_class::getRelations($this); } @@ -69,9 +73,10 @@ public function getRelations() { /** * @return Constraint[] */ - public function getConstraints() { + public function getConstraints() + { - if(!isset($this->constraints)) { + if (!isset($this->constraints)) { $driver_class = $this->database->getConnection()->getDriverClass(); $this->constraints = $driver_class::getConstraints($this); } @@ -83,10 +88,11 @@ public function getConstraints() { /** * @return null|Constraint */ - public function getPrimaryKey() { + public function getPrimaryKey() + { - foreach($this->getConstraints() as $constraint) - if($constraint->getType() === Constraint::TYPE_PRIMARY) + foreach ($this->getConstraints() as $constraint) + if ($constraint->getType() === Constraint::TYPE_PRIMARY) return $constraint; return null; @@ -95,35 +101,40 @@ public function getPrimaryKey() { /** * @return \Wave\DB */ - public function getDatabase() { + public function getDatabase() + { return $this->database; } /** * @return string */ - public function getName() { + public function getName() + { return $this->table; } /** * @return string */ - public function getEngine() { + public function getEngine() + { return $this->engine; } /** * @return string */ - public function getCollation() { + public function getCollation() + { return $this->collation; } /** * @return string */ - public function getComment() { + public function getComment() + { return $this->comment; } @@ -132,21 +143,23 @@ public function getComment() { * * @return string */ - public function getClassName($with_namespace = false) { + public function getClassName($with_namespace = false) + { $prefix = $with_namespace ? '\\' . $this->database->getNamespace() . '\\' : ''; return $prefix . Wave\Inflector::camelize($this->table); } /** - * Returns a fingerprint of this table schema that can be used to calculate if + * Returns a fingerprint of this table schema that can be used to calculate if * the table defintion has changed. This is primarily used when generating models * to avoid recreating models that haven't changed. - * + * * Makes use of overloaded __serialize() methods on the Column, Relation, and * Constraint components to calculate a MD5 hash. */ - public function getSchemaFingerprint() { + public function getSchemaFingerprint() + { $fingerprint = [ 'database' => $this->database->getName(), 'table' => $this->table, diff --git a/src/Wave/Debug.php b/src/Wave/Debug.php index 31ace94..7fb5701 100644 --- a/src/Wave/Debug.php +++ b/src/Wave/Debug.php @@ -2,7 +2,8 @@ namespace Wave; -class Debug { +class Debug +{ private $config; @@ -17,19 +18,22 @@ class Debug { /** * @return \Wave\Debug */ - public static function getInstance() { - if(self::$instance === null) + public static function getInstance() + { + if (self::$instance === null) self::init(); return self::$instance; } - public function __construct(array $config) { + public function __construct(array $config) + { $this->config = $config; $this->resetExecutionTime($config['start_time']); } - public static function init(array $config = array()) { + public static function init(array $config = array()) + { $defaults = array( 'start_time' => microtime(true), 'log_queries' => Core::$_MODE !== Core::MODE_PRODUCTION, @@ -39,11 +43,13 @@ public static function init(array $config = array()) { self::$instance = new self(array_merge($defaults, $config)); } - public function getMemoryUsage() { + public function getMemoryUsage() + { return round(memory_get_peak_usage() / pow(1024, 2), 2); } - public function getCurrentMemoryUsage() { + public function getCurrentMemoryUsage() + { return round(memory_get_usage() / pow(1024, 2), 2); } @@ -51,23 +57,27 @@ public function getCurrentMemoryUsage() { * Returns the time in miliseconds since the initation of the object. Used to track program execution time. * @return int */ - public function getExecutionTime() { + public function getExecutionTime() + { return round((microtime(true) - $this->execution_start) * 1000, 0); } - public function resetExecutionTime($reset_time = null) { - if($reset_time === null) + public function resetExecutionTime($reset_time = null) + { + if ($reset_time === null) $reset_time = microtime(true); $this->execution_start = $reset_time; } - public function getCheckpoints() { + public function getCheckpoints() + { return $this->checkpoints; } - public function addCheckpoint($name) { - if($this->config['log_checkpoints']){ + public function addCheckpoint($name) + { + if ($this->config['log_checkpoints']) { $this->checkpoints[] = array( 'name' => $name, 'time' => $this->getExecutionTime(), @@ -79,11 +89,12 @@ public function addCheckpoint($name) { /** * Adds the details of a used file in to an array - * @return * @param object $filename * @param object $caller [optional] + * @return */ - public function addUsedFile($filename, $caller = null) { + public function addUsedFile($filename, $caller = null) + { $this->used_files[] = array('filename' => $filename, 'caller' => $caller); } @@ -91,19 +102,21 @@ public function addUsedFile($filename, $caller = null) { * Returns all files used in the process * @return */ - public function getUsedFiles() { + public function getUsedFiles() + { $out = array(); - foreach(get_included_files() as $i => $file) { + foreach (get_included_files() as $i => $file) { $out[] = array('number' => $i + 1, 'filename' => str_replace(SYS_ROOT, '', $file)); } return $out; } - public function addQuery($time, $statement) { + public function addQuery($time, $statement) + { $this->query_count++; - if($this->config['log_queries']) { + if ($this->config['log_queries']) { $sql = $statement->queryString; $rows = $statement->rowCount(); $success = $statement->errorCode() == \PDO::ERR_NONE ? true : false; @@ -126,22 +139,25 @@ public function addQuery($time, $statement) { } - public function getNumberOfFiles() { + public function getNumberOfFiles() + { return count(get_included_files()); } - public function getNumberOfQueries() { + public function getNumberOfQueries() + { return $this->query_count; } /** * Returns the queris involved in the render, sets a colour for bad ones */ - public function getQueries() { + public function getQueries() + { $out = array(); - for($i = 0; $i < count($this->queries); $i++) { + for ($i = 0; $i < count($this->queries); $i++) { $colour = $this->queries[$i]['success'] ? "green" : "red"; $sql = $this->queries[$i]['sql']; @@ -161,7 +177,8 @@ public function getQueries() { } - public function render() { + public function render() + { Hook::triggerAction('debugger.render', array(&$this)); ?> @@ -258,10 +275,11 @@ function bind() { // ]]> - Log::WARNING, @@ -36,8 +37,9 @@ class Exception extends \Exception { private static $_error_reporting_types; private static $working_dir; - public static function register($controller) { - if(!class_exists($controller) || !is_subclass_of($controller, '\\Wave\\Controller')) { + public static function register($controller) + { + if (!class_exists($controller) || !is_subclass_of($controller, '\\Wave\\Controller')) { throw new \Exception("Controller $controller must be an instance of \\Wave\\Controller"); } @@ -46,15 +48,16 @@ public static function register($controller) { Hook::registerHandler( 'router.before_routing', function (Router $router) { - if(Exception::$_response_method === null) - Exception::$_response_method = $router->getRequest()->getFormat(); + if (Exception::$_response_method === null) + Exception::$_response_method = $router->getRequest()->getFormat(); - Exception::setRequest($router->getRequest()); - } + Exception::setRequest($router->getRequest()); + } ); } - public static function registerError($error_types = -1, $reserved_memory = 10) { + public static function registerError($error_types = -1, $reserved_memory = 10) + { self::$working_dir = getcwd(); set_error_handler(array('\\Wave\\Exception', 'handleError')); register_shutdown_function(array('\\Wave\\Exception', 'handleFatalError')); @@ -62,16 +65,18 @@ public static function registerError($error_types = -1, $reserved_memory = 10) { self::$_reserved_memory = str_repeat('x', 1024 * $reserved_memory); } - public static function handleError($code, $message, $file = null, $line = 0) { - if(!(self::$_error_reporting_types & $code & error_reporting())) { + public static function handleError($code, $message, $file = null, $line = 0) + { + if (!(self::$_error_reporting_types & $code & error_reporting())) { return true; } throw new ErrorException($message, $code, $code, $file, $line); } - public static function handleFatalError() { - if(null === $lastError = error_get_last()) { + public static function handleFatalError() + { + if (null === $lastError = error_get_last()) { return; } @@ -81,12 +86,13 @@ public static function handleFatalError() { $errors = E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING | E_STRICT; - if($lastError['type'] & $errors) { + if ($lastError['type'] & $errors) { self::handleError(@$lastError['type'], @$lastError['message'], @$lastError['file'], @$lastError['line']); } } - public static function handle($e, $send_response = true) { + public static function handle($e, $send_response = true) + { try { Hook::triggerAction('exception.handle', array(&$e)); @@ -94,7 +100,7 @@ public static function handle($e, $send_response = true) { // get the channel manually so the introspection works properly. $level = Log::ERROR; - if($e instanceof ErrorException && isset(self::$levels[$e->getSeverity()])) { + if ($e instanceof ErrorException && isset(self::$levels[$e->getSeverity()])) { $level = self::$levels[$e->getSeverity()]; } @@ -105,7 +111,7 @@ public static function handle($e, $send_response = true) { ); $request = static::$request; - if($request === null) + if ($request === null) $request = Request::createFromGlobals(); $action = Action::getDefaultAction(self::$_controller); @@ -113,16 +119,16 @@ public static function handle($e, $send_response = true) { $response = Controller::invoke($action, $request, array('exception' => $e)); $response->prepare($request); - if($send_response) { + if ($send_response) { $response->send(); } return $response; - } catch(\Exception $_e) { + } catch (\Exception $_e) { $response = new Response(); $response->setStatusCode(500); - if(Core::$_MODE === Core::MODE_PRODUCTION) { + if (Core::$_MODE === Core::MODE_PRODUCTION) { $response->setContent("Internal server error"); } else { $response->setContent( @@ -136,17 +142,19 @@ public static function handle($e, $send_response = true) { } } - public function __construct($message, $code = null) { - if($code == null && is_numeric($message)) { + public function __construct($message, $code = null) + { + if ($code == null && is_numeric($message)) { $code = intval($message); $message = $this->getInternalMessage($code); } parent::__construct($message, $code); } - protected function getInternalMessage($type) { + protected function getInternalMessage($type) + { - switch($type) { + switch ($type) { case Response::STATUS_NOT_FOUND : return 'The requested resource was not found'; case Response::STATUS_FORBIDDEN : @@ -169,19 +177,22 @@ protected function getInternalMessage($type) { } } - public static function getResponseMethod() { - if(self::$_response_method == null) { - if(PHP_SAPI === 'cli') return Response::FORMAT_CLI; + public static function getResponseMethod() + { + if (self::$_response_method == null) { + if (PHP_SAPI === 'cli') return Response::FORMAT_CLI; else return Config::get('wave')->response->default_format; } else return self::$_response_method; } - public static function setRequest($request) { + public static function setRequest($request) + { self::$request = $request; } - public static function setResponse($response) { + public static function setResponse($response) + { self::$response = $response; } } diff --git a/src/Wave/Hook.php b/src/Wave/Hook.php index ffeaf3e..f32aedf 100644 --- a/src/Wave/Hook.php +++ b/src/Wave/Hook.php @@ -2,7 +2,8 @@ namespace Wave; -class Hook { +class Hook +{ private static $handlers = array(); @@ -11,12 +12,13 @@ class Hook { * The optional $priority sets when in the chain the handler is fired, lower is earlier, defaults to 10 * The optional $name can be used to deregister the handler at a later time if necessary **/ - public static function registerHandler($action, $callback, $priority = 10, $name = null) { + public static function registerHandler($action, $callback, $priority = 10, $name = null) + { - if(!isset(self::$handlers[$action])) + if (!isset(self::$handlers[$action])) self::$handlers[$action] = array(); - if(!isset(self::$handlers[$action][$priority])) + if (!isset(self::$handlers[$action][$priority])) self::$handlers[$action][$priority] = array(); self::$handlers[$action][$priority][] = $callback; @@ -26,12 +28,13 @@ public static function registerHandler($action, $callback, $priority = 10, $name /** * Fire the specified action, calling all the registered handlers for that action. **/ - public static function triggerAction($action, $data = array()) { + public static function triggerAction($action, $data = array()) + { Debug::getInstance()->addCheckpoint($action); - if(isset(self::$handlers[$action])) { - foreach(self::$handlers[$action] as $priority => $handlers) { - foreach($handlers as $handler) { - if(is_callable($handler)) { + if (isset(self::$handlers[$action])) { + foreach (self::$handlers[$action] as $priority => $handlers) { + foreach ($handlers as $handler) { + if (is_callable($handler)) { call_user_func_array($handler, $data); } } diff --git a/src/Wave/Http/Cookie.php b/src/Wave/Http/Cookie.php index d774f28..7d96346 100644 --- a/src/Wave/Http/Cookie.php +++ b/src/Wave/Http/Cookie.php @@ -10,7 +10,8 @@ namespace Wave\Http; -class Cookie { +class Cookie +{ protected $name; protected $value; @@ -20,7 +21,8 @@ class Cookie { protected $secure; protected $httpOnly; - public function __construct($name, $value = null, $expire = 0, $path = '/', $domain = null, $secure = false, $httpOnly = true) { + public function __construct($name, $value = null, $expire = 0, $path = '/', $domain = null, $secure = false, $httpOnly = true) + { $this->name = $name; $this->value = $value; $this->domain = $domain; @@ -37,7 +39,8 @@ public function __construct($name, $value = null, $expire = 0, $path = '/', $dom * * @api */ - public function getName() { + public function getName() + { return $this->name; } @@ -48,7 +51,8 @@ public function getName() { * * @api */ - public function getValue() { + public function getValue() + { return $this->value; } @@ -59,7 +63,8 @@ public function getValue() { * * @api */ - public function getDomain() { + public function getDomain() + { return $this->domain; } @@ -70,7 +75,8 @@ public function getDomain() { * * @api */ - public function getExpires() { + public function getExpires() + { return $this->expire; } @@ -81,7 +87,8 @@ public function getExpires() { * * @api */ - public function getPath() { + public function getPath() + { return $this->path; } @@ -92,7 +99,8 @@ public function getPath() { * * @api */ - public function isSecure() { + public function isSecure() + { return $this->secure; } @@ -103,7 +111,8 @@ public function isSecure() { * * @api */ - public function isHttpOnly() { + public function isHttpOnly() + { return $this->httpOnly; } @@ -114,7 +123,8 @@ public function isHttpOnly() { * * @api */ - public function isCleared() { + public function isCleared() + { return $this->expire < time(); } } \ No newline at end of file diff --git a/src/Wave/Http/Exception/BadRequestException.php b/src/Wave/Http/Exception/BadRequestException.php index 486dbb8..afbc01e 100644 --- a/src/Wave/Http/Exception/BadRequestException.php +++ b/src/Wave/Http/Exception/BadRequestException.php @@ -5,9 +5,11 @@ use Wave\Http\Response; -class BadRequestException extends HttpException { +class BadRequestException extends HttpException +{ - protected function getStatusCode() { + protected function getStatusCode() + { return Response::STATUS_BAD_REQUEST; } diff --git a/src/Wave/Http/Exception/ForbiddenException.php b/src/Wave/Http/Exception/ForbiddenException.php index 78d490c..7bf5175 100644 --- a/src/Wave/Http/Exception/ForbiddenException.php +++ b/src/Wave/Http/Exception/ForbiddenException.php @@ -4,10 +4,12 @@ use Wave\Http\Response; -class ForbiddenException extends HttpException { +class ForbiddenException extends HttpException +{ - protected function getStatusCode() { + protected function getStatusCode() + { return Response::STATUS_FORBIDDEN; } } \ No newline at end of file diff --git a/src/Wave/Http/Exception/HttpException.php b/src/Wave/Http/Exception/HttpException.php index 9a1f0ff..d64b08d 100644 --- a/src/Wave/Http/Exception/HttpException.php +++ b/src/Wave/Http/Exception/HttpException.php @@ -7,13 +7,15 @@ use Wave\Http\Request; use Wave\Http\Response; -class HttpException extends Exception { +class HttpException extends Exception +{ protected $request; protected $response; - public function __construct($message, Request $request = null, Response $response = null) { + public function __construct($message, Request $request = null, Response $response = null) + { $this->request = $request; $this->response = $response; @@ -22,7 +24,8 @@ public function __construct($message, Request $request = null, Response $respons } - protected function getStatusCode() { + protected function getStatusCode() + { return Response::STATUS_SERVER_ERROR; } diff --git a/src/Wave/Http/Exception/InvalidResponseFormatException.php b/src/Wave/Http/Exception/InvalidResponseFormatException.php index ab2f6a6..dcd7692 100644 --- a/src/Wave/Http/Exception/InvalidResponseFormatException.php +++ b/src/Wave/Http/Exception/InvalidResponseFormatException.php @@ -4,9 +4,11 @@ use Wave\Http\Response; -class InvalidResponseFormatException extends HttpException { +class InvalidResponseFormatException extends HttpException +{ - protected function getStatusCode() { + protected function getStatusCode() + { return Response::STATUS_NOT_ACCEPTABLE; } diff --git a/src/Wave/Http/Exception/NotFoundException.php b/src/Wave/Http/Exception/NotFoundException.php index 289c1c7..bd7c044 100644 --- a/src/Wave/Http/Exception/NotFoundException.php +++ b/src/Wave/Http/Exception/NotFoundException.php @@ -4,9 +4,11 @@ use Wave\Http\Response; -class NotFoundException extends HttpException { +class NotFoundException extends HttpException +{ - protected function getStatusCode() { + protected function getStatusCode() + { return Response::STATUS_NOT_FOUND; } } \ No newline at end of file diff --git a/src/Wave/Http/Exception/UnauthorizedException.php b/src/Wave/Http/Exception/UnauthorizedException.php index a5bcea4..da8f6c2 100644 --- a/src/Wave/Http/Exception/UnauthorizedException.php +++ b/src/Wave/Http/Exception/UnauthorizedException.php @@ -4,9 +4,11 @@ use Wave\Http\Response; -class UnauthorizedException extends HttpException { +class UnauthorizedException extends HttpException +{ - protected function getStatusCode() { + protected function getStatusCode() + { return Response::STATUS_UNAUTHORISED; } } \ No newline at end of file diff --git a/src/Wave/Http/HeaderBag.php b/src/Wave/Http/HeaderBag.php index 376fc0a..c58c7cb 100644 --- a/src/Wave/Http/HeaderBag.php +++ b/src/Wave/Http/HeaderBag.php @@ -14,7 +14,8 @@ * HeaderBag is a container for HTTP headers. Inspired by the HeaderBag from Symfony * */ -class HeaderBag implements \IteratorAggregate, \Countable { +class HeaderBag implements \IteratorAggregate, \Countable +{ protected $headers = array(); /** @@ -24,7 +25,8 @@ class HeaderBag implements \IteratorAggregate, \Countable { * * @api */ - public function __construct(array $headers = array()) { + public function __construct(array $headers = array()) + { $this->add($headers); } @@ -33,7 +35,8 @@ public function __construct(array $headers = array()) { * Returns the headers. * @return array An array of headers */ - public function all() { + public function all() + { return $this->headers; } @@ -41,7 +44,8 @@ public function all() { * Returns the parameter keys. * @return array An array of parameter keys */ - public function keys() { + public function keys() + { return array_keys($this->headers); } @@ -49,7 +53,8 @@ public function keys() { * Replaces the current HTTP headers by a new set. * @param array $headers An array of HTTP headers */ - public function replace(array $headers = array()) { + public function replace(array $headers = array()) + { $this->headers = array(); $this->add($headers); } @@ -61,8 +66,9 @@ public function replace(array $headers = array()) { * * @api */ - public function add(array $headers) { - foreach($headers as $key => $values) { + public function add(array $headers) + { + foreach ($headers as $key => $values) { $this->set($key, $values); } } @@ -76,19 +82,20 @@ public function add(array $headers) { * * @return string|array The first header value if $first is true, an array of values otherwise */ - public function get($key, $default = null, $first = true) { + public function get($key, $default = null, $first = true) + { $key = strtr(strtolower($key), '_', '-'); - if(!array_key_exists($key, $this->headers)) { - if(null === $default) { + if (!array_key_exists($key, $this->headers)) { + if (null === $default) { return $first ? null : array(); } return $first ? $default : array($default); } - if($first) { + if ($first) { return count($this->headers[$key]) ? $this->headers[$key][0] : $default; } @@ -104,13 +111,14 @@ public function get($key, $default = null, $first = true) { * * @api */ - public function set($key, $values, $replace = true) { + public function set($key, $values, $replace = true) + { $key = strtr(strtolower($key), '_', '-'); - $values = array_values((array) $values); + $values = array_values((array)$values); - if(true === $replace || !isset($this->headers[$key])) { + if (true === $replace || !isset($this->headers[$key])) { $this->headers[$key] = $values; } else { $this->headers[$key] = array_merge($this->headers[$key], $values); @@ -126,7 +134,8 @@ public function set($key, $values, $replace = true) { * * @api */ - public function has($key) { + public function has($key) + { return array_key_exists(strtr(strtolower($key), '_', '-'), $this->headers); } @@ -140,7 +149,8 @@ public function has($key) { * * @api */ - public function contains($key, $value) { + public function contains($key, $value) + { return in_array($value, $this->get($key, null, false)); } @@ -151,7 +161,8 @@ public function contains($key, $value) { * * @api */ - public function remove($key) { + public function remove($key) + { $key = strtr(strtolower($key), '_', '-'); unset($this->headers[$key]); @@ -162,7 +173,8 @@ public function remove($key) { * * @return \ArrayIterator An \ArrayIterator instance */ - public function getIterator() { + public function getIterator(): \ArrayIterator + { return new \ArrayIterator($this->headers); } @@ -171,7 +183,8 @@ public function getIterator() { * * @return int The number of headers */ - public function count() { + public function count(): int + { return count($this->headers); } @@ -180,17 +193,18 @@ public function count() { * * @return string The headers */ - public function __toString() { - if(!$this->headers) { + public function __toString() + { + if (!$this->headers) { return ''; } $max = max(array_map('strlen', array_keys($this->headers))) + 1; $content = ''; ksort($this->headers); - foreach($this->headers as $name => $values) { + foreach ($this->headers as $name => $values) { $name = implode('-', array_map('ucfirst', explode('-', $name))); - foreach($values as $value) { + foreach ($values as $value) { $content .= sprintf("%-{$max}s %s\r\n", $name . ':', $value); } } diff --git a/src/Wave/Http/ParameterBag.php b/src/Wave/Http/ParameterBag.php index 2ec48ed..ccbe1c7 100644 --- a/src/Wave/Http/ParameterBag.php +++ b/src/Wave/Http/ParameterBag.php @@ -16,7 +16,8 @@ /** * ParameterBag is a container for key/value pairs. */ -class ParameterBag implements \IteratorAggregate, \Countable { +class ParameterBag implements \IteratorAggregate, \Countable +{ /** * Parameter storage. @@ -30,7 +31,8 @@ class ParameterBag implements \IteratorAggregate, \Countable { * * @param array $parameters An array of parameters */ - public function __construct(array $parameters = array()) { + public function __construct(array $parameters = array()) + { $this->parameters = $parameters; } @@ -39,7 +41,8 @@ public function __construct(array $parameters = array()) { * * @return array An array of parameters */ - public function all() { + public function all() + { return $this->parameters; } @@ -48,7 +51,8 @@ public function all() { * * @return array An array of parameter keys */ - public function keys() { + public function keys() + { return array_keys($this->parameters); } @@ -57,7 +61,8 @@ public function keys() { * * @param array $parameters An array of parameters */ - public function replace(array $parameters = array()) { + public function replace(array $parameters = array()) + { $this->parameters = $parameters; } @@ -66,7 +71,8 @@ public function replace(array $parameters = array()) { * * @param array $parameters An array of parameters */ - public function add(array $parameters = array()) { + public function add(array $parameters = array()) + { $this->parameters = array_replace($this->parameters, $parameters); } @@ -77,44 +83,45 @@ public function add(array $parameters = array()) { * @param mixed $default The default value if the parameter key does not exist * @param boolean $deep If true, a path like foo[bar] will find deeper items * + * @return mixed|null * @throws \InvalidArgumentException * - * @return mixed|null */ - public function get($path, $default = null, $deep = false) { - if(!$deep || false === $pos = strpos($path, '[')) { + public function get($path, $default = null, $deep = false) + { + if (!$deep || false === $pos = strpos($path, '[')) { return array_key_exists($path, $this->parameters) ? $this->parameters[$path] : $default; } $root = substr($path, 0, $pos); - if(!array_key_exists($root, $this->parameters)) { + if (!array_key_exists($root, $this->parameters)) { return $default; } $value = $this->parameters[$root]; $currentKey = null; - for($i = $pos, $c = strlen($path); $i < $c; $i++) { + for ($i = $pos, $c = strlen($path); $i < $c; $i++) { $char = $path[$i]; - if('[' === $char) { - if(null !== $currentKey) { + if ('[' === $char) { + if (null !== $currentKey) { throw new \InvalidArgumentException(sprintf('Malformed path. Unexpected "[" at position %d.', $i)); } $currentKey = ''; - } elseif(']' === $char) { - if(null === $currentKey) { + } elseif (']' === $char) { + if (null === $currentKey) { throw new \InvalidArgumentException(sprintf('Malformed path. Unexpected "]" at position %d.', $i)); } - if(!is_array($value) || !array_key_exists($currentKey, $value)) { + if (!is_array($value) || !array_key_exists($currentKey, $value)) { return $default; } $value = $value[$currentKey]; $currentKey = null; } else { - if(null === $currentKey) { + if (null === $currentKey) { throw new \InvalidArgumentException(sprintf('Malformed path. Unexpected "%s" at position %d.', $char, $i)); } @@ -122,7 +129,7 @@ public function get($path, $default = null, $deep = false) { } } - if(null !== $currentKey) { + if (null !== $currentKey) { throw new \InvalidArgumentException(sprintf('Malformed path. Path must end with "]".')); } @@ -135,7 +142,8 @@ public function get($path, $default = null, $deep = false) { * @param string $key The key * @param mixed $value The value */ - public function set($key, $value) { + public function set($key, $value) + { $this->parameters[$key] = $value; } @@ -146,7 +154,8 @@ public function set($key, $value) { * * @return Boolean true if the parameter exists, false otherwise */ - public function has($key) { + public function has($key) + { return array_key_exists($key, $this->parameters); } @@ -155,7 +164,8 @@ public function has($key) { * * @param string $key The key */ - public function remove($key) { + public function remove($key) + { unset($this->parameters[$key]); } @@ -168,7 +178,8 @@ public function remove($key) { * * @return string The filtered value */ - public function getAlpha($key, $default = '', $deep = false) { + public function getAlpha($key, $default = '', $deep = false) + { return preg_replace('/[^[:alpha:]]/', '', $this->get($key, $default, $deep)); } @@ -181,7 +192,8 @@ public function getAlpha($key, $default = '', $deep = false) { * * @return string The filtered value */ - public function getAlnum($key, $default = '', $deep = false) { + public function getAlnum($key, $default = '', $deep = false) + { return preg_replace('/[^[:alnum:]]/', '', $this->get($key, $default, $deep)); } @@ -194,7 +206,8 @@ public function getAlnum($key, $default = '', $deep = false) { * * @return string The filtered value */ - public function getDigits($key, $default = '', $deep = false) { + public function getDigits($key, $default = '', $deep = false) + { // we need to remove - and + because they're allowed in the filter return str_replace(array('-', '+'), '', $this->filter($key, $default, $deep, FILTER_SANITIZE_NUMBER_INT)); } @@ -208,8 +221,9 @@ public function getDigits($key, $default = '', $deep = false) { * * @return integer The filtered value */ - public function getInt($key, $default = 0, $deep = false) { - return (int) $this->get($key, $default, $deep); + public function getInt($key, $default = 0, $deep = false) + { + return (int)$this->get($key, $default, $deep); } /** @@ -221,20 +235,21 @@ public function getInt($key, $default = 0, $deep = false) { * @param integer $filter FILTER_* constant. * @param mixed $options Filter options. * + * @return mixed * @see http://php.net/manual/en/function.filter-var.php * - * @return mixed */ - public function filter($key, $default = null, $deep = false, $filter = FILTER_DEFAULT, $options = array()) { + public function filter($key, $default = null, $deep = false, $filter = FILTER_DEFAULT, $options = array()) + { $value = $this->get($key, $default, $deep); // Always turn $options into an array - this allows filter_var option shortcuts. - if(!is_array($options) && $options) { + if (!is_array($options) && $options) { $options = array('flags' => $options); } // Add a convenience check for arrays. - if(is_array($value) && !isset($options['flags'])) { + if (is_array($value) && !isset($options['flags'])) { $options['flags'] = FILTER_REQUIRE_ARRAY; } @@ -246,7 +261,8 @@ public function filter($key, $default = null, $deep = false, $filter = FILTER_DE * * @return \ArrayIterator An \ArrayIterator instance */ - public function getIterator() { + public function getIterator(): \ArrayIterator + { return new \ArrayIterator($this->parameters); } @@ -255,7 +271,8 @@ public function getIterator() { * * @return int The number of parameters */ - public function count() { + public function count(): int + { return count($this->parameters); } } diff --git a/src/Wave/Http/Request.php b/src/Wave/Http/Request.php index 04b3e7d..d911f24 100644 --- a/src/Wave/Http/Request.php +++ b/src/Wave/Http/Request.php @@ -15,7 +15,8 @@ use Wave\Http\Exception\BadRequestException; use Wave\Router\Action; -class Request { +class Request +{ const METHOD_HEAD = 'HEAD'; const METHOD_GET = 'GET'; @@ -87,7 +88,8 @@ public function __construct($url, $method = self::METHOD_GET, array $parameters = array(), array $attributes = array(), array $server = array(), - array $cookies = array()) { + array $cookies = array()) + { $this->setUrl($url); $this->setMethod($method); @@ -106,38 +108,39 @@ public function __construct($url, $method = self::METHOD_GET, * * @return Request */ - public static function createFromGlobals() { + public static function createFromGlobals() + { $url = 'http://localhost'; - if(isset($_SERVER['HTTP_HOST'])) { + if (isset($_SERVER['HTTP_HOST'])) { $protocol = isset($_SERVER['HTTPS']) ? 'https' : 'http'; $url = sprintf('%s://%s', $protocol, $_SERVER['HTTP_HOST']); } - if(isset($_SERVER['SERVER_PORT']) && !in_array($_SERVER['SERVER_PORT'], array(80, 443))) { + if (isset($_SERVER['SERVER_PORT']) && !in_array($_SERVER['SERVER_PORT'], array(80, 443))) { $url .= ':' . $_SERVER['SERVER_PORT']; } - if(isset($_SERVER['PATH_INFO'])) { + if (isset($_SERVER['PATH_INFO'])) { $url .= substr($_SERVER['PATH_INFO'], strpos($_SERVER['PATH_INFO'], '.php/')); - if(isset($_SERVER['QUERY_STRING'])) + if (isset($_SERVER['QUERY_STRING'])) $url .= '?' . $_SERVER['QUERY_STRING']; - } else if(isset($_SERVER['REQUEST_URI'])) { + } else if (isset($_SERVER['REQUEST_URI'])) { $url .= $_SERVER['REQUEST_URI']; } $parameters = array(); $method = static::METHOD_CLI; - if(isset($_SERVER['REQUEST_METHOD'])) { + if (isset($_SERVER['REQUEST_METHOD'])) { $method = strtoupper($_SERVER['REQUEST_METHOD']); - if('POST' === $method && isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) { + if ('POST' === $method && isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) { $method = strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']); } - switch($method) { + switch ($method) { case static::METHOD_POST: case static::METHOD_PATCH: case static::METHOD_PUT: case static::METHOD_DELETE: - if(isset($_SERVER['CONTENT_TYPE'])) + if (isset($_SERVER['CONTENT_TYPE'])) $parameters = static::parseRequestBody($_SERVER['CONTENT_TYPE']); else $parameters = $_POST; @@ -160,24 +163,25 @@ public static function createFromGlobals() { * * @param string $content_type * - * @throws Exception\BadRequestException * @return array + * @throws Exception\BadRequestException */ - protected static function parseRequestBody($content_type = self::TYPE_FORM_ENCODED) { + protected static function parseRequestBody($content_type = self::TYPE_FORM_ENCODED) + { list($content_type) = explode(';', $content_type); - switch($content_type) { + switch ($content_type) { case static::TYPE_JSON: $data = json_decode(file_get_contents('php://input'), true); - if(json_last_error() !== JSON_ERROR_NONE) + if (json_last_error() !== JSON_ERROR_NONE) throw new BadRequestException("Error encountered while decoding JSON payload"); - if(!is_array($data)) return array(); + if (!is_array($data)) return array(); else return $data; case static::TYPE_FORM_ENCODED: parse_str(file_get_contents('php://input'), $data); - if(!is_array($data)) return array(); + if (!is_array($data)) return array(); else return $data; case static::TYPE_MULTIPART: default: @@ -195,11 +199,16 @@ protected static function parseRequestBody($content_type = self::TYPE_FORM_ENCOD * * @return string */ - protected static function parseFormat($url, $default = null) { - if(null === $default) { + protected static function parseFormat($url, $default = null) + { + if (null === $default) { $default = PHP_SAPI === 'cli' ? 'cli' : Config::get('wave')->response->default_format; } - $path = pathinfo($url); + + $path = []; + if (!empty($url)) { + $path = pathinfo($url); + } return isset($path['extension']) ? $path['extension'] : $default; } @@ -210,8 +219,9 @@ protected static function parseFormat($url, $default = null) { * * @return array */ - public function getData() { - switch($this->getMethod()) { + public function getData() + { + switch ($this->getMethod()) { case self::METHOD_POST: case self::METHOD_PUT: case self::METHOD_PATCH: @@ -224,11 +234,13 @@ public function getData() { } } - public function getAuthorization() { + public function getAuthorization() + { return $this->attributes->get('_authorization'); } - public function setAuthorization($authorization) { + public function setAuthorization($authorization) + { $this->attributes->set('_authorization', $authorization); } @@ -239,10 +251,11 @@ public function setAuthorization($authorization) { * * @return bool */ - public function has($parameter) { + public function has($parameter) + { - foreach(array('attributes', 'query', 'parameters') as $property) { - if($this->$property->has($parameter)) { + foreach (array('attributes', 'query', 'parameters') as $property) { + if ($this->$property->has($parameter)) { return true; } } @@ -258,10 +271,11 @@ public function has($parameter) { * * @return mixed */ - public function get($parameter, $default = null) { + public function get($parameter, $default = null) + { - foreach(array('attributes', 'query', 'parameters') as $property) { - if($this->$property->has($parameter)) { + foreach (array('attributes', 'query', 'parameters') as $property) { + if ($this->$property->has($parameter)) { return $this->$property->get($parameter); } } @@ -274,7 +288,8 @@ public function get($parameter, $default = null) { * * @param $url */ - public function setUrl($url) { + public function setUrl($url) + { $this->components = parse_url($url); $this->url = $url; @@ -286,7 +301,8 @@ public function setUrl($url) { * * @return string */ - public function getUrl() { + public function getUrl() + { return $this->url; } @@ -295,7 +311,8 @@ public function getUrl() { * * @return string */ - public function getMethod() { + public function getMethod() + { return $this->method; } @@ -306,9 +323,10 @@ public function getMethod() { * * @throws \InvalidArgumentException */ - public function setMethod($method) { + public function setMethod($method) + { $method = strtoupper($method); - if(!in_array( + if (!in_array( $method, array( static::METHOD_HEAD, static::METHOD_GET, @@ -334,8 +352,9 @@ public function setMethod($method) { * * @return string|null */ - public function getComponent($component) { - if(isset($this->components[$component])) + public function getComponent($component) + { + if (isset($this->components[$component])) return $this->components[$component]; else return null; @@ -346,7 +365,8 @@ public function getComponent($component) { * * @return null|string */ - public function getScheme() { + public function getScheme() + { return $this->getComponent('scheme'); } @@ -355,7 +375,8 @@ public function getScheme() { * * @return null|string */ - public function getHost() { + public function getHost() + { return $this->getComponent('host'); } @@ -364,7 +385,8 @@ public function getHost() { * * @return null|string */ - public function getPort() { + public function getPort() + { return $this->getComponent('port'); } @@ -373,11 +395,12 @@ public function getPort() { * * @return null|string */ - public function getPath($exclude_base_path = true) { + public function getPath($exclude_base_path = true) + { $path = $this->getComponent('path'); - if($exclude_base_path) { + if ($exclude_base_path) { $base = $this->getBasePath(); - if(!empty($base) && strpos($path, $base) === 0) + if (!empty($base) && strpos($path, $base) === 0) $path = substr($path, strlen($base)); } @@ -390,7 +413,8 @@ public function getPath($exclude_base_path = true) { * * @return null|string */ - public function getQueryString() { + public function getQueryString() + { return $this->getComponent('query'); } @@ -399,7 +423,8 @@ public function getQueryString() { * * @return string */ - public function getPathAndQueryString() { + public function getPathAndQueryString() + { return $this->getPath() . '?' . $this->getQueryString(); } @@ -408,20 +433,21 @@ public function getPathAndQueryString() { * * @return string base path */ - protected function prepareBasePath() { - $filename = basename($this->server->get('SCRIPT_FILENAME')); + protected function prepareBasePath() + { + $filename = basename($this->server->get('SCRIPT_FILENAME', '')); $baseUrl = $this->getBaseUrl(); - if(empty($baseUrl)) { + if (empty($baseUrl)) { return ''; } - if(basename($baseUrl) === $filename) { + if (basename($baseUrl) === $filename) { $basePath = dirname($baseUrl); } else { $basePath = $baseUrl; } - if('\\' === DIRECTORY_SEPARATOR) { + if ('\\' === DIRECTORY_SEPARATOR) { $basePath = str_replace('\\', '/', $basePath); } @@ -442,8 +468,9 @@ protected function prepareBasePath() { * * @api */ - public function getBasePath() { - if(null === $this->basePath) { + public function getBasePath() + { + if (null === $this->basePath) { $this->basePath = $this->prepareBasePath(); } @@ -462,8 +489,9 @@ public function getBasePath() { * * @api */ - public function getBaseUrl() { - if(null === $this->baseUrl) { + public function getBaseUrl() + { + if (null === $this->baseUrl) { $this->baseUrl = $this->prepareBaseUrl(); } @@ -475,13 +503,14 @@ public function getBaseUrl() { * * @return string */ - protected function prepareBaseUrl() { - $filename = basename($this->server->get('SCRIPT_FILENAME')); + protected function prepareBaseUrl() + { + $filename = basename($this->server->get('SCRIPT_FILENAME', '')); - if(basename($this->server->get('SCRIPT_NAME')) === $filename) { - $baseUrl = $this->server->get('SCRIPT_NAME'); - } elseif(basename($this->server->get('PHP_SELF')) === $filename) { - $baseUrl = $this->server->get('PHP_SELF'); + if (basename($this->server->get('SCRIPT_NAME', '')) === $filename) { + $baseUrl = $this->server->get('SCRIPT_NAME', ''); + } elseif (basename($this->server->get('PHP_SELF', '')) === $filename) { + $baseUrl = $this->server->get('PHP_SELF', ''); } else { // Backtrack up the script_filename to find the portion matching // php_self @@ -496,29 +525,29 @@ protected function prepareBaseUrl() { $seg = $segs[$index]; $baseUrl = '/' . $seg . $baseUrl; ++$index; - } while($last > $index && (false !== $pos = strpos($path, $baseUrl)) && 0 != $pos); + } while ($last > $index && (false !== $pos = strpos($path, $baseUrl)) && 0 != $pos); } // Does the baseUrl have anything in common with the request_uri? - $requestUri = $this->server->get('REQUEST_URI'); + $requestUri = $this->server->get('REQUEST_URI', ''); - if($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, $baseUrl)) { + if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, $baseUrl)) { // full $baseUrl matches return $prefix; } - if($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, dirname($baseUrl))) { + if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, dirname($baseUrl))) { // directory portion of $baseUrl matches return rtrim($prefix, '/'); } $truncatedRequestUri = $requestUri; - if(false !== $pos = strpos($requestUri, '?')) { + if (false !== $pos = strpos($requestUri, '?')) { $truncatedRequestUri = substr($requestUri, 0, $pos); } $basename = basename($baseUrl); - if(empty($basename) || !strpos(rawurldecode($truncatedRequestUri), $basename)) { + if (empty($basename) || !strpos(rawurldecode($truncatedRequestUri), $basename)) { // no match whatsoever; set it blank return ''; } @@ -526,7 +555,7 @@ protected function prepareBaseUrl() { // If using mod_rewrite or ISAPI_Rewrite strip the script filename // out of baseUrl. $pos !== 0 makes sure it is not matching a value // from PATH_INFO or QUERY_STRING - if(strlen($requestUri) >= strlen($baseUrl) && (false !== $pos = strpos($requestUri, $baseUrl)) && $pos !== 0) { + if (strlen($requestUri) >= strlen($baseUrl) && (false !== $pos = strpos($requestUri, $baseUrl)) && $pos !== 0) { $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl)); } @@ -536,14 +565,16 @@ protected function prepareBaseUrl() { /** * @return \Wave\Http\HeaderBag */ - public function getHeaders() { + public function getHeaders() + { return $this->headers; } /** * @param \Wave\Http\HeaderBag $headers */ - public function setHeaders(HeaderBag $headers) { + public function setHeaders(HeaderBag $headers) + { $this->headers = $headers; } @@ -553,7 +584,8 @@ public function setHeaders(HeaderBag $headers) { * * @return string */ - public function getFormat() { + public function getFormat() + { return $this->format; } @@ -562,21 +594,24 @@ public function getFormat() { * * @param $format */ - public function setFormat($format) { + public function setFormat($format) + { $this->format = $format; } /** * @return Action */ - public function getAction() { + public function getAction() + { return $this->action; } /** * @param Action $action */ - public function setAction(Action $action) { + public function setAction(Action $action) + { $this->action = $action; } @@ -585,7 +620,8 @@ public function setAction(Action $action) { * * @return string The request */ - public function __toString() { + public function __toString() + { return sprintf('%s %s %s', $this->getMethod(), $this->getPathAndQueryString(), $this->server->get('SERVER_PROTOCOL')) . "\r\n" . $this->headers . "\r\n" . @@ -597,8 +633,9 @@ public function __toString() { * * @return string The request body content. */ - public function getContent() { - if(null === $this->content) { + public function getContent() + { + if (null === $this->content) { $this->content = file_get_contents('php://input'); } @@ -614,14 +651,15 @@ public function getContent() { * * @return string|false The prefix as it is encoded in $string, or false */ - private function getUrlencodedPrefix($string, $prefix) { - if(0 !== strpos(rawurldecode($string), $prefix)) { + private function getUrlencodedPrefix($string, $prefix) + { + if (0 !== strpos(rawurldecode($string), $prefix)) { return false; } $len = strlen($prefix); - if(preg_match("#^(%[[:xdigit:]]{2}|.){{$len}}#", $string, $match)) { + if (preg_match("#^(%[[:xdigit:]]{2}|.){{$len}}#", $string, $match)) { return $match[0]; } diff --git a/src/Wave/Http/Request/AuthorizationAware.php b/src/Wave/Http/Request/AuthorizationAware.php index 520ea91..7fd6707 100644 --- a/src/Wave/Http/Request/AuthorizationAware.php +++ b/src/Wave/Http/Request/AuthorizationAware.php @@ -5,7 +5,8 @@ use Wave\Http\Request; -interface AuthorizationAware { +interface AuthorizationAware +{ /** * Evaluate this object for the required authorization level needed by a controller function. diff --git a/src/Wave/Http/Response.php b/src/Wave/Http/Response.php index 69ebf8c..a10ed5d 100644 --- a/src/Wave/Http/Response.php +++ b/src/Wave/Http/Response.php @@ -13,7 +13,8 @@ use Wave\Config; use Wave\Hook; -class Response { +class Response +{ const STATUS_OK = 200; const STATUS_CREATED = 201; @@ -142,7 +143,8 @@ class Response { protected $version; - public function __construct($content = '', $status = self::STATUS_OK, array $headers = array(), array $cookies = array()) { + public function __construct($content = '', $status = self::STATUS_OK, array $headers = array(), array $cookies = array()) + { $this->setHeaders(new HeaderBag($headers)); $this->setCookies($cookies); @@ -153,36 +155,38 @@ public function __construct($content = '', $status = self::STATUS_OK, array $hea } - public function prepare(Request $request) { + public function prepare(Request $request) + { - if('HTTP/1.0' != $request->server->get('SERVER_PROTOCOL')) { + if ('HTTP/1.0' != $request->server->get('SERVER_PROTOCOL')) { $this->setProtocolVersion('1.1'); } return $this; } - public function send() { + public function send() + { Hook::triggerAction('response.before_send', array(&$this)); $this->sendHeaders(); $this->sendContent(); - if(function_exists('fastcgi_finish_request')) { + if (function_exists('fastcgi_finish_request')) { fastcgi_finish_request(); - } elseif('cli' !== PHP_SAPI) { + } elseif ('cli' !== PHP_SAPI) { // ob_get_level() never returns 0 on some Windows configurations, so if // the level is the same two times in a row, the loop should be stopped. $previous = null; $obStatus = ob_get_status(1); - while(($level = ob_get_level()) > 0 && $level !== $previous) { + while (($level = ob_get_level()) > 0 && $level !== $previous) { $previous = $level; - if($obStatus[$level - 1]) { - if(version_compare(PHP_VERSION, '5.4', '>=')) { - if(isset($obStatus[$level - 1]['flags']) && ($obStatus[$level - 1]['flags'] & PHP_OUTPUT_HANDLER_REMOVABLE)) { + if ($obStatus[$level - 1]) { + if (version_compare(PHP_VERSION, '5.4', '>=')) { + if (isset($obStatus[$level - 1]['flags']) && ($obStatus[$level - 1]['flags'] & PHP_OUTPUT_HANDLER_REMOVABLE)) { ob_end_flush(); } } else { - if(isset($obStatus[$level - 1]['del']) && $obStatus[$level - 1]['del']) { + if (isset($obStatus[$level - 1]['del']) && $obStatus[$level - 1]['del']) { ob_end_flush(); } } @@ -195,8 +199,9 @@ public function send() { return $this; } - public function sendHeaders() { - if(headers_sent()) { + public function sendHeaders() + { + if (headers_sent()) { return $this; } @@ -204,13 +209,13 @@ public function sendHeaders() { header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)); // headers - foreach($this->headers->all() as $name => $values) { - foreach($values as $value) { + foreach ($this->headers->all() as $name => $values) { + foreach ($values as $value) { header($name . ': ' . $value, false); } } - foreach($this->cookies as $cookie) { + foreach ($this->cookies as $cookie) { setcookie( $cookie->getName(), $cookie->getValue(), @@ -225,67 +230,79 @@ public function sendHeaders() { return $this; } - public function sendContent() { + public function sendContent() + { echo $this->content; return $this; } - public static function getMessageForCode($_status) { - if(array_key_exists($_status, static::$statusTexts)) { + public static function getMessageForCode($_status) + { + if (array_key_exists($_status, static::$statusTexts)) { return static::$statusTexts[$_status]; } return ''; } - public function setContent($content) { + public function setContent($content) + { $this->content = $content; } - public function getContent() { + public function getContent() + { return $this->content; } - public function setStatusCode($code, $text = null) { - $this->statusCode = (int) $code; + public function setStatusCode($code, $text = null) + { + $this->statusCode = (int)$code; - if(null === $this->statusText = $text) + if (null === $this->statusText = $text) $this->statusText = isset(self::$statusTexts[$code]) ? self::$statusTexts[$code] : ''; } - public function getStatusCode() { + public function getStatusCode() + { return $this->statusCode; } /** * @return \Wave\Http\HeaderBag */ - public function getHeaders() { + public function getHeaders() + { return $this->headers; } /** * @param \Wave\Http\HeaderBag $headers */ - public function setHeaders(HeaderBag $headers) { + public function setHeaders(HeaderBag $headers) + { $this->headers = $headers; } - public function setCookies(array $cookies) { + public function setCookies(array $cookies) + { $this->cookies = $cookies; } - public function addCookie(Cookie $cookie) { + public function addCookie(Cookie $cookie) + { $this->cookies[$cookie->getName()] = $cookie; } - public function setProtocolVersion($version) { + public function setProtocolVersion($version) + { $this->version = $version; } - public function getProtocolVersion() { + public function getProtocolVersion() + { return $this->version; } @@ -300,7 +317,8 @@ public function getProtocolVersion() { * * @see prepare() */ - public function __toString() { + public function __toString() + { return sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText) . "\r\n" . $this->headers . "\r\n" . diff --git a/src/Wave/Http/Response/HtmlResponse.php b/src/Wave/Http/Response/HtmlResponse.php index 310a2d0..a913765 100644 --- a/src/Wave/Http/Response/HtmlResponse.php +++ b/src/Wave/Http/Response/HtmlResponse.php @@ -5,10 +5,12 @@ use Wave\Http\Request; use Wave\Http\Response; -class HtmlResponse extends Response { +class HtmlResponse extends Response +{ - public function prepare(Request $request) { + public function prepare(Request $request) + { parent::prepare($request); $this->headers->set('Content-Type', 'text/html; charset=utf8'); diff --git a/src/Wave/Http/Response/JsonResponse.php b/src/Wave/Http/Response/JsonResponse.php index c2abbf9..7a43456 100644 --- a/src/Wave/Http/Response/JsonResponse.php +++ b/src/Wave/Http/Response/JsonResponse.php @@ -6,7 +6,8 @@ use Wave\Http\Response; use Wave\Utils\JSON; -class JsonResponse extends Response { +class JsonResponse extends Response +{ protected static $acceptable_types = array( 'application/json', @@ -24,14 +25,15 @@ class JsonResponse extends Response { protected $jsonp_callback = null; - public function prepare(Request $request) { + public function prepare(Request $request) + { parent::prepare($request); - if($request->query->has('jsonp_callback')) { + if ($request->query->has('jsonp_callback')) { $this->jsonp_callback = $request->query->get('jsonp_callback'); } - if(!$this->headers->has('Content-Type')) { + if (!$this->headers->has('Content-Type')) { $content_types = array_map('trim', explode(',', $request->headers->get('accept', static::$default_type, true))); $allowed = array_intersect($content_types, static::$acceptable_types); $content_type = empty($allowed) ? static::$default_type : array_shift($allowed); @@ -46,8 +48,9 @@ public function prepare(Request $request) { return $this; } - public function setContent($data, $convert = true) { - if($convert) { + public function setContent($data, $convert = true) + { + if ($convert) { $this->data = $data; $data = JSON::encode($data); } @@ -55,9 +58,10 @@ public function setContent($data, $convert = true) { parent::setContent($data); } - public function sendContent() { + public function sendContent() + { - if($this->jsonp_callback !== null) { + if ($this->jsonp_callback !== null) { echo "{$this->jsonp_callback}($this->content);"; } else parent::sendContent(); @@ -66,7 +70,8 @@ public function sendContent() { /** * @return mixed */ - public function getData() { + public function getData() + { return $this->data; } diff --git a/src/Wave/Http/Response/RedirectResponse.php b/src/Wave/Http/Response/RedirectResponse.php index ec28f90..6bce7a7 100644 --- a/src/Wave/Http/Response/RedirectResponse.php +++ b/src/Wave/Http/Response/RedirectResponse.php @@ -5,21 +5,25 @@ use Wave\Http\Request; use Wave\Http\Response; -class RedirectResponse extends Response { +class RedirectResponse extends Response +{ private $target; - public function __construct($url, $status = self::STATUS_FOUND, array $headers = array()) { + public function __construct($url, $status = self::STATUS_FOUND, array $headers = array()) + { parent::__construct('', $status, $headers); $this->setTarget($url); } - public function getTarget() { + public function getTarget() + { return $this->target; } - public function setTarget($target) { + public function setTarget($target) + { $this->target = $target; $this->setContent( diff --git a/src/Wave/Http/Response/TextResponse.php b/src/Wave/Http/Response/TextResponse.php index d8c1ed2..2c4727b 100644 --- a/src/Wave/Http/Response/TextResponse.php +++ b/src/Wave/Http/Response/TextResponse.php @@ -4,5 +4,6 @@ use Wave\Http\Response; -class TextResponse extends Response { +class TextResponse extends Response +{ } \ No newline at end of file diff --git a/src/Wave/Http/Response/XmlResponse.php b/src/Wave/Http/Response/XmlResponse.php index 045123f..ab29198 100644 --- a/src/Wave/Http/Response/XmlResponse.php +++ b/src/Wave/Http/Response/XmlResponse.php @@ -6,11 +6,13 @@ use Wave\Http\Response; use Wave\Utils\XML; -class XmlResponse extends Response { +class XmlResponse extends Response +{ private $data; - public function prepare(Request $request) { + public function prepare(Request $request) + { parent::prepare($request); $this->headers->set('Cache-Control', 'no-cache, must-revalidate'); @@ -21,8 +23,9 @@ public function prepare(Request $request) { return $this; } - public function setContent($data, $convert = true) { - if($convert) { + public function setContent($data, $convert = true) + { + if ($convert) { $this->data = $data; $data = XML::encode($data); } @@ -33,7 +36,8 @@ public function setContent($data, $convert = true) { /** * @return mixed */ - public function getData() { + public function getData() + { return $this->data; } diff --git a/src/Wave/Http/ServerBag.php b/src/Wave/Http/ServerBag.php index d4026cf..1a7359d 100644 --- a/src/Wave/Http/ServerBag.php +++ b/src/Wave/Http/ServerBag.php @@ -19,25 +19,27 @@ /** * ServerBag is a container for HTTP headers from the $_SERVER variable. */ -class ServerBag extends ParameterBag { +class ServerBag extends ParameterBag +{ /** * Gets the HTTP headers. * * @return array */ - public function getHeaders() { + public function getHeaders() + { $headers = array(); - foreach($this->parameters as $key => $value) { - if(0 === strpos($key, 'HTTP_')) { + foreach ($this->parameters as $key => $value) { + if (0 === strpos($key, 'HTTP_')) { $headers[substr($key, 5)] = $value; } // CONTENT_* are not prefixed with HTTP_ - elseif(in_array($key, array('CONTENT_LENGTH', 'CONTENT_MD5', 'CONTENT_TYPE'))) { + elseif (in_array($key, array('CONTENT_LENGTH', 'CONTENT_MD5', 'CONTENT_TYPE'))) { $headers[$key] = $value; } } - if(isset($this->parameters['PHP_AUTH_USER'])) { + if (isset($this->parameters['PHP_AUTH_USER'])) { $headers['PHP_AUTH_USER'] = $this->parameters['PHP_AUTH_USER']; $headers['PHP_AUTH_PW'] = isset($this->parameters['PHP_AUTH_PW']) ? $this->parameters['PHP_AUTH_PW'] : ''; } else { @@ -56,23 +58,23 @@ public function getHeaders() { */ $authorizationHeader = null; - if(isset($this->parameters['HTTP_AUTHORIZATION'])) { + if (isset($this->parameters['HTTP_AUTHORIZATION'])) { $authorizationHeader = $this->parameters['HTTP_AUTHORIZATION']; - } elseif(isset($this->parameters['REDIRECT_HTTP_AUTHORIZATION'])) { + } elseif (isset($this->parameters['REDIRECT_HTTP_AUTHORIZATION'])) { $authorizationHeader = $this->parameters['REDIRECT_HTTP_AUTHORIZATION']; } // Decode AUTHORIZATION header into PHP_AUTH_USER and PHP_AUTH_PW when authorization header is basic - if((null !== $authorizationHeader) && (0 === stripos($authorizationHeader, 'basic'))) { + if ((null !== $authorizationHeader) && (0 === stripos($authorizationHeader, 'basic'))) { $exploded = explode(':', base64_decode(substr($authorizationHeader, 6))); - if(count($exploded) == 2) { + if (count($exploded) == 2) { list($headers['PHP_AUTH_USER'], $headers['PHP_AUTH_PW']) = $exploded; } } } // PHP_AUTH_USER/PHP_AUTH_PW - if(isset($headers['PHP_AUTH_USER'])) { + if (isset($headers['PHP_AUTH_USER'])) { $headers['AUTHORIZATION'] = 'Basic ' . base64_encode($headers['PHP_AUTH_USER'] . ':' . $headers['PHP_AUTH_PW']); } diff --git a/src/Wave/IAuthable.php b/src/Wave/IAuthable.php index 09b11bb..2f6becb 100755 --- a/src/Wave/IAuthable.php +++ b/src/Wave/IAuthable.php @@ -4,7 +4,8 @@ use Wave\Http\Request; -interface IAuthable { +interface IAuthable +{ public static function loadByIdentifier(array $params); diff --git a/src/Wave/IResource.php b/src/Wave/IResource.php index f3063ac..ed3c960 100755 --- a/src/Wave/IResource.php +++ b/src/Wave/IResource.php @@ -1,7 +1,8 @@ "$1zes", @@ -82,57 +83,60 @@ class Inflector { 'media' ); - public static function pluralize($string) { + public static function pluralize($string) + { // save some time in the case that singular and plural are the same - if(in_array(strtolower($string), self::$uncountable)) + if (in_array(strtolower($string), self::$uncountable)) return $string; // check for irregular singular forms - foreach(self::$irregular as $pattern => $result) { + foreach (self::$irregular as $pattern => $result) { $pattern = '/' . $pattern . '$/i'; - if(preg_match($pattern, $string)) + if (preg_match($pattern, $string)) return preg_replace($pattern, $result, $string); } // check for matches using regular expressions - foreach(self::$plural as $pattern => $result) { - if(preg_match($pattern, $string)) + foreach (self::$plural as $pattern => $result) { + if (preg_match($pattern, $string)) return preg_replace($pattern, $result, $string); } return $string; } - public static function singularize($string) { + public static function singularize($string) + { // save some time in the case that singular and plural are the same - if(in_array(strtolower($string), self::$uncountable)) + if (in_array(strtolower($string), self::$uncountable)) return $string; // check for irregular plural forms - foreach(self::$irregular as $result => $pattern) { + foreach (self::$irregular as $result => $pattern) { $pattern = '/' . $pattern . '$/i'; - if(preg_match($pattern, $string)) + if (preg_match($pattern, $string)) return preg_replace($pattern, $result, $string); } // check for matches using regular expressions - foreach(self::$singular as $pattern => $result) { - if(preg_match($pattern, $string)) + foreach (self::$singular as $pattern => $result) { + if (preg_match($pattern, $string)) return preg_replace($pattern, $result, $string); } return $string; } - public static function camelize($string, $suffix_to_remove = '') { + public static function camelize($string, $suffix_to_remove = '') + { $camelized = ''; $words = preg_split('/([^a-zA-Z])/', rtrim($string, $suffix_to_remove), -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); - foreach($words as $word) - if(!in_array($word, array('_', ' '))) + foreach ($words as $word) + if (!in_array($word, array('_', ' '))) $camelized .= ucfirst($word); return $camelized; diff --git a/src/Wave/Log.php b/src/Wave/Log.php index 0e60202..1f51cd6 100755 --- a/src/Wave/Log.php +++ b/src/Wave/Log.php @@ -16,12 +16,12 @@ use Monolog\Handler\AbstractHandler; use Monolog\Handler\StreamHandler; use Monolog\Logger; -use Wave\Config; use Wave\Log\CliHandler; use Wave\Log\ExceptionIntrospectionProcessor; -class Log extends Logger { +class Log extends Logger +{ protected static $default_handlers = null; private static $default_level = null; @@ -42,7 +42,8 @@ class Log extends Logger { /** * Initialise the Log with a default channel for framework logs **/ - public static function init() { + public static function init() + { } @@ -50,11 +51,12 @@ public static function init() { * Set the default level for logging messages to the * * @param int $level The new default level - * @throws Exception * @return void + * @throws Exception */ - public static function setDefaultLevel($level) { - if(!in_array($level, self::$all_levels)) + public static function setDefaultLevel($level) + { + if (!in_array($level, self::$all_levels)) throw new \Wave\Exception("Invalid default log level of $level set"); static::$default_level = $level; } @@ -62,15 +64,17 @@ public static function setDefaultLevel($level) { /** * @return int The default log level **/ - public static function getDefaultLevel() { - if(static::$default_level === null) + public static function getDefaultLevel() + { + if (static::$default_level === null) static::$default_level = Config::get('wave')->logger->file->level; return static::$default_level; } - public static function getDefaultHandlers() { - if(static::$default_handlers === null) { + public static function getDefaultHandlers() + { + if (static::$default_handlers === null) { static::$default_handlers = array(); @@ -79,7 +83,7 @@ public static function getDefaultHandlers() { $log_dir = dirname($log_path); - if(!is_writable($log_dir)) { + if (!is_writable($log_dir)) { @mkdir($log_dir, 0770, true); } @@ -88,7 +92,7 @@ public static function getDefaultHandlers() { static::pushDefaultHandler($stream_handler); - if(PHP_SAPI === 'cli') { + if (PHP_SAPI === 'cli') { $cli_handler = new CliHandler(Config::get('wave')->logger->cli->level); $cli_handler->setFormatter(new LineFormatter(CliHandler::LINE_FORMAT)); static::pushDefaultHandler($cli_handler); @@ -99,8 +103,9 @@ public static function getDefaultHandlers() { return static::$default_handlers; } - public static function pushDefaultHandler(AbstractHandler $handler) { - if(static::$default_handlers === null) { + public static function pushDefaultHandler(AbstractHandler $handler) + { + if (static::$default_handlers === null) { static::$default_handlers = self::getDefaultHandlers(); } @@ -119,8 +124,9 @@ public static function pushDefaultHandler(AbstractHandler $handler) { * * @return \Monolog\Logger A new Logger instance */ - public static function createChannel($channel, array $handlers = array(), $use_default_handlers = true) { - if($use_default_handlers) + public static function createChannel($channel, array $handlers = array(), $use_default_handlers = true) + { + if ($use_default_handlers) $handlers += static::getDefaultHandlers(); static::$channels[$channel] = new Logger($channel, $handlers); @@ -133,9 +139,10 @@ public static function createChannel($channel, array $handlers = array(), $use_d * * @return \Monolog\Logger A Logger instance for the given channel or `null` if not found */ - public static function getChannel($name, $create = true) { - if(!isset(static::$channels[$name])) { - if($create === true) return static::createChannel($name); + public static function getChannel($name, $create = true) + { + if (!isset(static::$channels[$name])) { + if ($create === true) return static::createChannel($name); else return null; } return static::$channels[$name]; @@ -149,7 +156,8 @@ public static function getChannel($name, $create = true) { * * @return \Monolog\Logger */ - public static function setChannel($name, Logger $instance) { + public static function setChannel($name, Logger $instance) + { return static::$channels[$name] = $instance; } @@ -162,7 +170,8 @@ public static function setChannel($name, Logger $instance) { * * @return Bool Whether the message has been written **/ - public static function write($channel, $message, $level = Logger::INFO, $context = array()) { + public static function write($channel, $message, $level = Logger::INFO, $context = array()) + { $channel = static::getChannel($channel); return $channel->addRecord($level, $message, $context); diff --git a/src/Wave/Log/Cli.php b/src/Wave/Log/Cli.php index ad2c090..dc73d7c 100644 --- a/src/Wave/Log/Cli.php +++ b/src/Wave/Log/Cli.php @@ -6,10 +6,12 @@ use Monolog\Handler\AbstractHandler; use Wave\Log; -class Cli extends Log { +class Cli extends Log +{ - public static function createChannel($channel, AbstractHandler $handler = null) { + public static function createChannel($channel, AbstractHandler $handler = null) + { $cli_handler = new CliHandler(); $cli_handler->setFormatter(new LineFormatter(CliHandler::LINE_FORMAT)); diff --git a/src/Wave/Log/CliHandler.php b/src/Wave/Log/CliHandler.php index 4926aea..2452557 100644 --- a/src/Wave/Log/CliHandler.php +++ b/src/Wave/Log/CliHandler.php @@ -6,7 +6,8 @@ use Monolog\Handler\AbstractProcessingHandler; use Monolog\Logger; -class CliHandler extends AbstractProcessingHandler { +class CliHandler extends AbstractProcessingHandler +{ const LINE_FORMAT = '[%level_name%] %message%'; @@ -22,16 +23,17 @@ class CliHandler extends AbstractProcessingHandler { /** * Outputs a string to the cli. * - * @param string|array $record the text to output, or array of lines + * @param string|array $record the text to output, or array of lines */ - protected function write(array $record) { + protected function write(array $record) + { $stream = $record['level'] >= Logger::ERROR ? STDERR : STDOUT; $text = static::color($record['formatted'], $record['level']); $beep = ''; - if($record['level'] >= Logger::CRITICAL) + if ($record['level'] >= Logger::CRITICAL) $beep .= static::beep(); - if($record['level'] >= Logger::ALERT) + if ($record['level'] >= Logger::ALERT) $beep .= static::beep(); fwrite($stream, $beep . $text . PHP_EOL); @@ -40,9 +42,10 @@ protected function write(array $record) { /** * Beeps a certain number of times. * - * @param int $num the number of times to beep + * @param int $num the number of times to beep */ - public static function beep($num = 1) { + public static function beep($num = 1) + { return str_repeat("\x07", $num); } @@ -50,14 +53,15 @@ public static function beep($num = 1) { /** * Returns the given text with the correct color codes for the given level * - * @param string $text the text to color - * @param int $level the level of message + * @param string $text the text to color + * @param int $level the level of message * * @return string the color coded string */ - public static function color($text, $level) { + public static function color($text, $level) + { - if(isset(static::$colors[$level])) { + if (isset(static::$colors[$level])) { $prefix = "\033[" . static::$colors[$level] . "m"; $text = $prefix . $text . "\033[0m"; } diff --git a/src/Wave/Log/ExceptionIntrospectionProcessor.php b/src/Wave/Log/ExceptionIntrospectionProcessor.php index 94d7d52..321b8bb 100644 --- a/src/Wave/Log/ExceptionIntrospectionProcessor.php +++ b/src/Wave/Log/ExceptionIntrospectionProcessor.php @@ -2,19 +2,21 @@ namespace Wave\Log; -class ExceptionIntrospectionProcessor { +class ExceptionIntrospectionProcessor +{ /** - * @param array $record + * @param array $record * @return array */ - public function __invoke(array $record) { + public function __invoke(array $record) + { $trace = debug_backtrace(); $first = end($trace); - if(isset($first['args'][0]) && $first['args'][0] instanceof \Exception) { + if (isset($first['args'][0]) && $first['args'][0] instanceof \Exception) { // the start of this trace is an exception, so get the throwing file from // the exception trace. $exception = $first['args'][0]; @@ -40,7 +42,7 @@ public function __invoke(array $record) { array_shift($trace); $i = 0; - while(isset($trace[$i]['class']) + while (isset($trace[$i]['class']) && (false !== strpos($trace[$i]['class'], 'Monolog\\') || (false !== strpos($trace[$i]['class'], 'Wave\\Log') && 'write' === $trace[$i]['function']))) { $i++; diff --git a/src/Wave/Method.php b/src/Wave/Method.php index a6eb69d..ca2fb43 100644 --- a/src/Wave/Method.php +++ b/src/Wave/Method.php @@ -2,7 +2,8 @@ namespace Wave; -abstract class Method { +abstract class Method +{ const ANY = '*'; const POST = 'POST'; diff --git a/src/Wave/Reflector.php b/src/Wave/Reflector.php index c423f0f..6eaf3d4 100755 --- a/src/Wave/Reflector.php +++ b/src/Wave/Reflector.php @@ -2,7 +2,8 @@ namespace Wave; -class Reflector { +class Reflector +{ const SCAN_DIRECTORY = 1; const SCAN_FILE = 2; @@ -15,40 +16,42 @@ class Reflector { private $_classes = null; - public function __construct($handle, $type = self::SCAN_DIRECTORY, $filter = self::DEFAULT_FILE_FILTER, $recursive = true) { - if(!file_exists($handle)) + public function __construct($handle, $type = self::SCAN_DIRECTORY, $filter = self::DEFAULT_FILE_FILTER, $recursive = true) + { + if (!file_exists($handle)) throw new \Wave\Exception('Directory ' . $handle . ' cannot be resolved in \Wave\Refector', 0); $this->_classes = array(); - if($type == self::SCAN_FILE && is_file($handle)) { + if ($type == self::SCAN_FILE && is_file($handle)) { $class = self::findClass($handle); - if($class !== false) + if ($class !== false) $this->_classes[] = $class; - } else if($type == self::SCAN_DIRECTORY && is_dir($handle)) { + } else if ($type == self::SCAN_DIRECTORY && is_dir($handle)) { - if($recursive === true) { + if ($recursive === true) { $dir_iterator = new \RecursiveDirectoryIterator($handle); $iterator = new \RecursiveIteratorIterator($dir_iterator, \RecursiveIteratorIterator::SELF_FIRST); } else { $dir_iterator = new \FilesystemIterator($handle); $iterator = new \IteratorIterator($dir_iterator, \RecursiveIteratorIterator::SELF_FIRST); } - foreach($iterator as $file) { + foreach ($iterator as $file) { $class = self::findClass($file); - if($class !== false) + if ($class !== false) $this->_classes[] = $class; } } } - public function execute($include_inherited_members = false) { - if(!isset($this->_classes[0])) + public function execute($include_inherited_members = false) + { + if (!isset($this->_classes[0])) throw new \Wave\Exception('No files to reflect on'); $classes = array(); - foreach($this->_classes as $class) { + foreach ($this->_classes as $class) { $reflector = new \ReflectionClass($class); $class_annotations = Annotation::parse($reflector->getDocComment(), $class); @@ -62,15 +65,15 @@ public function execute($include_inherited_members = false) { ); $methods = array(); - foreach($reflector->getMethods() as $method) { + foreach ($reflector->getMethods() as $method) { $declaring_class = $method->getDeclaringClass()->getName(); // don't put inherited methods on here plz - if($declaring_class != $class && !$include_inherited_members) + if ($declaring_class != $class && !$include_inherited_members) continue; $annotations = Annotation::parse($method->getDocComment(), $class); $method_annotations = array(); - foreach($annotations as $annotation) { + foreach ($annotations as $annotation) { $method_annotations[] = $annotation; } @@ -87,15 +90,15 @@ public function execute($include_inherited_members = false) { } $properties = array(); - foreach($reflector->getProperties() as $property) { + foreach ($reflector->getProperties() as $property) { $declaring_class = $property->getDeclaringClass()->getName(); // don't put inherited methods on here plz - if($declaring_class != $class && !$include_inherited_members) + if ($declaring_class != $class && !$include_inherited_members) continue; $annotations = Annotation::parse($property->getDocComment(), $class); $property_annotations = array(); - foreach($annotations as $annotation) { + foreach ($annotations as $annotation) { $property_annotations[] = $annotation; } @@ -124,38 +127,36 @@ public function execute($include_inherited_members = false) { * * @return string|false Full class name if found, false otherwise */ - protected function findClass($file) { + protected function findClass($file) + { + // skip anything that's not a regular file if (!is_file($file)) return false; - + $class = false; $namespace = false; $tokens = token_get_all(file_get_contents($file)); - for($i = 0, $count = count($tokens); $i < $count; $i++) { + for ($i = 0, $count = count($tokens); $i < $count; $i++) { $token = $tokens[$i]; - if(!is_array($token)) { + if (!is_array($token)) { continue; } - if(true === $class && T_STRING === $token[0]) { + if (true === $class && T_STRING === $token[0]) { return $namespace . '\\' . $token[1]; } - if(true === $namespace && T_STRING === $token[0]) { - $namespace = ''; - do { - $namespace .= $token[1]; - $token = $tokens[++$i]; - } while($i < $count && is_array($token) && in_array($token[0], array(T_NS_SEPARATOR, T_STRING))); + if (true === $namespace && (T_NAME_QUALIFIED === $token[0] || T_STRING === $token[0])) { + $namespace = $token[1]; } - if(T_CLASS === $token[0]) { + if (T_CLASS === $token[0]) { $class = true; } - if(T_NAMESPACE === $token[0]) { + if (T_NAMESPACE === $token[0]) { $namespace = true; } } diff --git a/src/Wave/Registry.php b/src/Wave/Registry.php index d5a8ede..3518baf 100755 --- a/src/Wave/Registry.php +++ b/src/Wave/Registry.php @@ -2,35 +2,40 @@ namespace Wave; -class Registry { +class Registry +{ private static $store = array(); - public static function store($key, $value) { + public static function store($key, $value) + { self::$store[$key] = $value; return self::$store[$key]; } - public static function fetch($key) { + public static function fetch($key) + { - if(isset(self::$store[$key])) + if (isset(self::$store[$key])) return self::$store[$key]; else return null; } - public static function destroy($key) { - if(isset(self::$store[$key])) { + public static function destroy($key) + { + if (isset(self::$store[$key])) { unset(self::$store[$key]); return true; } return false; } - public static function _isset($key) { + public static function _isset($key) + { return isset(self::$store[$key]); } diff --git a/src/Wave/Router.php b/src/Wave/Router.php index 0076b44..b59d6b4 100644 --- a/src/Wave/Router.php +++ b/src/Wave/Router.php @@ -9,7 +9,8 @@ use Wave\Router\Node; use Wave\Router\RoutingException; -class Router { +class Router +{ private static $profiles; @@ -28,10 +29,11 @@ class Router { /** @var \Wave\Http\Response $response */ protected $response; - public static function init($host = null) { + public static function init($host = null) + { Hook::triggerAction('router.before_init', array(&$host)); - if($host === null) { - if(isset($_SERVER['HTTP_HOST'])) + if ($host === null) { + if (isset($_SERVER['HTTP_HOST'])) $host = $_SERVER['HTTP_HOST']; else $host = Config::get('deploy')->profiles->default->baseurl; @@ -41,21 +43,24 @@ public static function init($host = null) { return $instance; } - public static function getActionByName($profile, $action_name) { + public static function getActionByName($profile, $action_name) + { $table = static::getRoutesTableCache($profile); $action_name = ltrim($action_name, '\\'); return isset($table[$action_name]) ? $table[$action_name] : null; } - public static function getProfiles() { - if(!isset(self::$profiles)) + public static function getProfiles() + { + if (!isset(self::$profiles)) self::$profiles = Config::get('deploy')->profiles; return self::$profiles; } - public static function getCacheName($host, $type) { + public static function getCacheName($host, $type) + { return "routes/$host.$type"; } @@ -69,49 +74,52 @@ public function getScheduledRoutes() { $table = static::getRoutesTableCache($this->profile); - return array_filter($table, function (Action $action){ + return array_filter($table, function (Action $action) { return $action->hasSchedule(); }); } - public static function getRoutesTreeCache($profile) { + public static function getRoutesTreeCache($profile) + { $root = Cache::load(self::getCacheName($profile, 'tree')); - if($root == null) { + if ($root == null) { $root = Cache::load(self::getCacheName('default', 'tree')); } - if(!($root instanceof Node)) + if (!($root instanceof Node)) throw new RoutingException("Could not load route tree for profile: {$profile} nor default profile"); return $root; } - public static function getRoutesTableCache($profile) { + public static function getRoutesTableCache($profile) + { $table = Cache::load(self::getCacheName($profile, 'table')); - if($table == null) { + if ($table == null) { $table = Cache::load(self::getCacheName('default', 'table')); } - if(!is_array($table)) + if (!is_array($table)) throw new RoutingException("Could not load routes table for profile: {$profile} nor default profile"); return $table; } - public function __construct($profile) { - if(isset(static::getProfiles()->$profile)) { + public function __construct($profile) + { + if (isset(static::getProfiles()->$profile)) { $this->profile = $profile; } else { // try looking for the profile using the baseurl instead - foreach(static::getProfiles() as $name => $config) { - if($config->baseurl == $profile) { + foreach (static::getProfiles() as $name => $config) { + if ($config->baseurl == $profile) { $this->profile = $name; break; } } } - if(!isset($this->profile)) { + if (!isset($this->profile)) { throw new RoutingException("Unknown routing profile {$profile}"); } } @@ -119,19 +127,20 @@ public function __construct($profile) { /** * @param Request $request * - * @throws \LogicException - * @throws Http\Exception\NotFoundException * @return Response + * @throws Http\Exception\NotFoundException + * @throws \LogicException */ - public function route(Request $request = null) { + public function route(Request $request = null) + { - if(null === $request) + if (null === $request) $request = Request::createFromGlobals(); $this->request = $request; $this->request_uri = $request->getPath(); - if(strrpos($this->request_uri, $request->getFormat()) !== false) { + if (strrpos($this->request_uri, $request->getFormat()) !== false) { $this->request_uri = substr($this->request_uri, 0, -(strlen($request->getFormat()) + 1)); } $this->request_method = $request->getMethod(); @@ -142,12 +151,12 @@ public function route(Request $request = null) { $node = $this->getRootNode()->findChild($url, $this->request); /** @var \Wave\Router\Action $action */ - if($node instanceof Router\Node && $action = $node->getAction()) { + if ($node instanceof Router\Node && $action = $node->getAction()) { Hook::triggerAction('router.before_invoke', array(&$action, &$this)); $this->request->setAction($action); $this->response = Controller::invoke($action, $this->request); Hook::triggerAction('router.before_response', array(&$action, &$this)); - if(!($this->response instanceof Response)) { + if (!($this->response instanceof Response)) { throw new \LogicException("Action {$action->getAction()} should return a \\Wave\\Http\\Response object", 500); } else { return $this->response->prepare($this->request); @@ -156,8 +165,9 @@ public function route(Request $request = null) { throw new NotFoundException('The requested URL ' . $url . ' does not exist', $this->request); } - public function getRootNode() { - if(!($this->root instanceof Node)) { + public function getRootNode() + { + if (!($this->root instanceof Node)) { $this->root = static::getRoutesTreeCache($this->profile); } return $this->root; @@ -166,14 +176,16 @@ public function getRootNode() { /** * @return \Wave\Http\Request */ - public function getRequest() { + public function getRequest() + { return $this->request; } /** * @param \Wave\Http\Request $request */ - public function setRequest($request) { + public function setRequest($request) + { $this->request = $request; } } diff --git a/src/Wave/Router/Generator.php b/src/Wave/Router/Generator.php index f3141eb..f3692e6 100644 --- a/src/Wave/Router/Generator.php +++ b/src/Wave/Router/Generator.php @@ -2,20 +2,23 @@ namespace Wave\Router; +use ReflectionType; use Wave; use Wave\Router; -class Generator { +class Generator +{ - public static function generate() { + public static function generate() + { $reflector = new Wave\Reflector(Wave\Config::get('wave')->path->controllers); $reflected_options = $reflector->execute(); $all_actions = self::buildRoutes($reflected_options); - foreach($all_actions as $profile => $actions) { + foreach ($all_actions as $profile => $actions) { $route_node = new Node(); - foreach($actions as $action) { - foreach($action->getRoutes() as $route) { + foreach ($actions as $action) { + foreach ($action->getRoutes() as $route) { $route_node->addChild($route, $action); } } @@ -24,28 +27,34 @@ public static function generate() { } } - public static function buildRoutes($controllers) { + public static function buildRoutes($controllers) + { $compiled_routes = array(); // iterate all the controllers and make a tree of all the possible path - foreach($controllers as $controller) { + foreach ($controllers as $controller) { $base_route = new Action(); // set the route defaults from the Controller annotations (if any) - foreach($controller['class']['annotations'] as $annotation) { + foreach ($controller['class']['annotations'] as $annotation) { $base_route->addAnnotation($annotation); } - foreach($controller['methods'] as $method) { + foreach ($controller['methods'] as $method) { $route = clone $base_route; // copy from the controller route - if($method['visibility'] == Wave\Reflector::VISIBILITY_PUBLIC) { - foreach($method['annotations'] as $annotation){ + if ($method['visibility'] == Wave\Reflector::VISIBILITY_PUBLIC) { + foreach ($method['annotations'] as $annotation) { $route->addAnnotation($annotation); } - foreach($method['parameters'] as $parameter) { + foreach ($method['parameters'] as $parameter) { /** @var \ReflectionParameter $parameter */ - $type = $parameter->getClass() !== null ? $parameter->getClass()->getName() : null; + $type = null; + $reflected_type = $parameter->getType(); + if ($reflected_type instanceof ReflectionType) { + $type = $reflected_type->getName(); + } + $route->addMethodParameter($parameter->getName(), $type); } @@ -53,8 +62,8 @@ public static function buildRoutes($controllers) { $route->setAction($controller['class']['name'] . '.' . $method['name']); - if($route->hasRoutes() || $route->hasSchedule()) { - if(isset($compiled_routes[$base_route->getProfile()][$route->getAction()])) { + if ($route->hasRoutes() || $route->hasSchedule()) { + if (isset($compiled_routes[$base_route->getProfile()][$route->getAction()])) { throw new \LogicException(sprintf("Action %s is declared twice", $route->getAction())); } $compiled_routes[$base_route->getProfile()][$route->getAction()] = $route; diff --git a/src/Wave/Router/Node.php b/src/Wave/Router/Node.php index 2230f6e..f546d9d 100755 --- a/src/Wave/Router/Node.php +++ b/src/Wave/Router/Node.php @@ -6,7 +6,8 @@ use Wave\Exception; use Wave\Http\Request; -class Node { +class Node +{ const VAR_INT = ''; const VAR_STRING = ''; @@ -16,52 +17,55 @@ class Node { private $children = array(); private $action = null; - private function setAction(Action $action) { - if($this->action === null) + private function setAction(Action $action) + { + if ($this->action === null) $this->action = $action; else { throw new Exception($this->action->getAction() . ' shares a duplicate route with ' . $action->getAction()); } } - public function addChild($route, Action $action) { + public function addChild($route, Action $action) + { // need to check if this part of the segment is a regex // and extend the segment to contain the whole expression // if it contains a `/` - if(substr_compare($route, '[^\/]*/', $route, $matches); $segment = $matches[0]; $segment_length = strlen($segment); - if($segment_length < strlen($route)) + if ($segment_length < strlen($route)) $remaining = substr($route, $segment_length + 1); } else { list($segment, $remaining) = preg_split(self::URL_SEGMENT_DELIMITER, $route, 2) + array(null, null); } - if(!isset($this->children[$segment])) { + if (!isset($this->children[$segment])) { $this->children[$segment] = new Node(); } - if(isset($remaining) && strlen($remaining) > 0) { + if (isset($remaining) && strlen($remaining) > 0) { $this->children[$segment]->addChild($remaining, $action); } else $this->children[$segment]->setAction($action); } - public function findChild($url, Request &$request) { + public function findChild($url, Request &$request) + { - if($url == null) return $this; + if ($url == null) return $this; $segment = preg_split(self::URL_SEGMENT_DELIMITER, $url, 2); - if(isset($segment[1])) $remaining = $segment[1]; + if (isset($segment[1])) $remaining = $segment[1]; else $remaining = null; $segment = $segment[0]; $node = null; // first check the segment is a directly keyed child - if(isset($this->children[$segment])) { + if (isset($this->children[$segment])) { $node = $this->children[$segment]; // if there is more to go, recurse with the rest return $node !== null ? $node->findChild($remaining, $request) : $node; @@ -69,28 +73,28 @@ public function findChild($url, Request &$request) { // otherwise, start searching through all the child paths // matching each one and recursing if a match is found $matching_node = null; - foreach($this->children as $path => $node) { + foreach ($this->children as $path => $node) { // start with the regex matches - if(substr_compare($path, ''); $pattern = '#^' . substr($path, 2, $expression_end - 2) . '#'; - if(preg_match($pattern, $url, $matches) == 1) { + if (preg_match($pattern, $url, $matches) == 1) { $segment = $matches[0]; $remaining = substr($url, strlen($segment) + 1) ?: null; $matching_node = $node->findChild($remaining, $request); - if($matching_node !== null && $matching_node->hasValidAction()) + if ($matching_node !== null && $matching_node->hasValidAction()) $request->attributes->set(substr($path, $expression_end + 2), $segment); } - } elseif((is_numeric($segment) && strpos($path, self::VAR_INT) !== false) + } elseif ((is_numeric($segment) && strpos($path, self::VAR_INT) !== false) || strpos($path, self::VAR_STRING) !== false ) { $matching_node = $node->findChild($remaining, $request); - if($matching_node !== null && $matching_node->hasValidAction()) + if ($matching_node !== null && $matching_node->hasValidAction()) $request->attributes->set(substr($path, strpos($path, '>') + 1), $segment); } - if($matching_node !== null) + if ($matching_node !== null) break; } @@ -98,11 +102,13 @@ public function findChild($url, Request &$request) { } } - public function getAction() { + public function getAction() + { return $this->action; } - public function hasValidAction() { + public function hasValidAction() + { return $this->action instanceof Action; } diff --git a/src/Wave/Router/RoutingException.php b/src/Wave/Router/RoutingException.php index 50de106..fbfe7d3 100644 --- a/src/Wave/Router/RoutingException.php +++ b/src/Wave/Router/RoutingException.php @@ -4,5 +4,6 @@ use Wave\Exception; -class RoutingException extends Exception { +class RoutingException extends Exception +{ } \ No newline at end of file diff --git a/src/Wave/Storage.php b/src/Wave/Storage.php index 441e950..f192a9d 100755 --- a/src/Wave/Storage.php +++ b/src/Wave/Storage.php @@ -2,7 +2,8 @@ namespace Wave; -abstract class Storage { +abstract class Storage +{ } diff --git a/src/Wave/Storage/Cookie.php b/src/Wave/Storage/Cookie.php index d247caa..74dfc35 100755 --- a/src/Wave/Storage/Cookie.php +++ b/src/Wave/Storage/Cookie.php @@ -2,22 +2,26 @@ namespace Wave\Storage; -class Cookie extends \Wave\Storage { +class Cookie extends \Wave\Storage +{ - public static function store($key, $data, $expires = 0, $path = '/', $domain = null, $secure = false, $httponly = true) { - if($domain === null) $domain = $_SERVER['SERVER_NAME']; + public static function store($key, $data, $expires = 0, $path = '/', $domain = null, $secure = false, $httponly = true) + { + if ($domain === null) $domain = $_SERVER['SERVER_NAME']; return setcookie($key, $data, $expires, $path, $domain, $secure, $httponly); } - public static function fetch($key) { - if(isset($_COOKIE[$key])) + public static function fetch($key) + { + if (isset($_COOKIE[$key])) return $_COOKIE[$key]; else trigger_error('Cookie ' . $key . ' is not set', E_USER_NOTICE); } - public static function key_set($key) { + public static function key_set($key) + { return isset($_COOKIE[$key]); } diff --git a/src/Wave/Utils.php b/src/Wave/Utils.php index 1e5fc2a..95d2160 100644 --- a/src/Wave/Utils.php +++ b/src/Wave/Utils.php @@ -2,26 +2,29 @@ namespace Wave; -abstract class Utils { +abstract class Utils +{ const DATE_FORMAT_MYSQL = 'Y-m-d H:i:s'; - public static function array_peek($arr) { - if(!is_array($arr)) return null; + public static function array_peek($arr) + { + if (!is_array($arr)) return null; $element = array_pop($arr); array_push($arr, $element); return $element; } - public static function redirect($uri, $profile = null, $permanent = false) { - if($permanent) + public static function redirect($uri, $profile = null, $permanent = false) + { + if ($permanent) header("Status: 302 Moved Permanently"); - if($profile !== null) { + if ($profile !== null) { $conf = Wave_Config::get('deploy')->profiles->$profile; $domain = $conf->baseurl; $protocol = 'http'; - if(isset($conf->ssl) && $conf->ssl == true) + if (isset($conf->ssl) && $conf->ssl == true) $protocol .= 's'; $uri = $protocol . '://' . $domain . $uri; } @@ -29,30 +32,32 @@ public static function redirect($uri, $profile = null, $permanent = false) { header('Location: ' . $uri); } - public static function extractFromObjectArray($key, $objs) { + public static function extractFromObjectArray($key, $objs) + { $extract = array(); - foreach($objs as $obj) { - if(isset($obj->$key)) + foreach ($objs as $obj) { + if (isset($obj->$key)) $extract[] = $obj->$key; } return $extract; } - public static function shorten($string, $length = 20, $by_word = true, $elipsis = true) { + public static function shorten($string, $length = 20, $by_word = true, $elipsis = true) + { - if(strlen($string) <= $length) return $string; + if (strlen($string) <= $length) return $string; $str = substr($string, 0, $length); - if($by_word) { + if ($by_word) { $pos = strrpos($str, ' '); - if($pos !== false) + if ($pos !== false) $str = substr($str, 0, $pos); } - if($elipsis) + if ($elipsis) $str .= '…'; return $str; diff --git a/src/Wave/Utils/JSON.php b/src/Wave/Utils/JSON.php index d43a5ad..e509a71 100755 --- a/src/Wave/Utils/JSON.php +++ b/src/Wave/Utils/JSON.php @@ -7,40 +7,42 @@ use DateTimeInterface; use Wave\DB\Model; -class JSON { +class JSON +{ - public static function encode($data) { + public static function encode($data) + { return json_encode(self::arrayify($data)); } - public static function arrayify($data) { - if($data instanceof DateTimeInterface) { + public static function arrayify($data) + { + if ($data instanceof DateTimeInterface) { /* * DateTime::ISO8601 isn't actually iso-8601 * http://php.net/manual/en/class.datetime.php#datetime.constants.iso8601 */ return $data->format(DateTime::ATOM); - } else if(is_array($data) || is_object($data)) { + } else if (is_array($data) || is_object($data)) { $jsonarr = array(); - if($data instanceof Model) { + if ($data instanceof Model) { $data = $data->_toArray(); } - if($data instanceof ArrayObject){ + if ($data instanceof ArrayObject) { $data = $data->getArrayCopy(); } - foreach($data as $key => $value) { + foreach ($data as $key => $value) { $jsonarr[$key] = self::arrayify($value); } // empty objects will be converted to arrays when json_encoded // so preserve the object type if the array is empty - if(is_object($data) && empty($jsonarr)){ - return (object) $jsonarr; - } - else { + if (is_object($data) && empty($jsonarr)) { + return (object)$jsonarr; + } else { return $jsonarr; } } else { diff --git a/src/Wave/Utils/XML.php b/src/Wave/Utils/XML.php index 079f544..6babee5 100755 --- a/src/Wave/Utils/XML.php +++ b/src/Wave/Utils/XML.php @@ -5,13 +5,15 @@ use Wave\DB\Model; use XMLWriter; -class XML { +class XML +{ const TYPE_OPEN = "open"; const TYPE_COMPLETE = "complete"; const TYPE_CLOSE = "close"; - public static function encode(array $data, $rootNodeName = 'response') { + public static function encode(array $data, $rootNodeName = 'response') + { $xml = new XmlWriter(); $xml->openMemory(); @@ -19,20 +21,21 @@ public static function encode(array $data, $rootNodeName = 'response') { $xml->startElement($rootNodeName); $data = self::arrayify($data); - function write(XMLWriter $xml, $data) { - foreach($data as $_key => $value) { + function write(XMLWriter $xml, $data) + { + foreach ($data as $_key => $value) { // check the key isnt a number, (numeric keys invalid in XML) - if(is_numeric($_key)) $key = 'element'; - else if(!is_string($_key) || empty($_key) || strncmp($_key, '_', 1) === 0) continue; + if (is_numeric($_key)) $key = 'element'; + else if (!is_string($_key) || empty($_key) || strncmp($_key, '_', 1) === 0) continue; else $key = $_key; $xml->startElement($key); // if the key is numeric, add an ID attribute to make tags properly unique - if(is_numeric($_key)) $xml->writeAttribute('id', $_key); + if (is_numeric($_key)) $xml->writeAttribute('id', $_key); // if the value is an array recurse into it - if(is_array($value)) write($xml, $value); + if (is_array($value)) write($xml, $value); // otherwise write the text to the document else $xml->text($value); @@ -48,9 +51,10 @@ function write(XMLWriter $xml, $data) { return $xml->outputMemory(); } - public static function decode($contents) { + public static function decode($contents) + { - if(!$contents) return array(); + if (!$contents) return array(); //Get the XML parser of PHP - PHP must have this module for the parser to work $parser = xml_parser_create(""); @@ -61,7 +65,7 @@ public static function decode($contents) { xml_parse_into_struct($parser, trim($contents), $xml_values); xml_parser_free($parser); - if(!$xml_values) return; + if (!$xml_values) return; //Initializations $xml_array = array(); @@ -69,26 +73,26 @@ public static function decode($contents) { $current = &$xml_array; //Go through the tags. - foreach($xml_values as $data) { + foreach ($xml_values as $data) { unset($attributes, $value); //Remove existing values // sets tag(string), type(string), level(int), attributes(array). extract($data); // Set value if it exists $result = null; - if(isset($value)) + if (isset($value)) $result = $value; //The starting of the tag '' - if($type == self::TYPE_OPEN) { + if ($type == self::TYPE_OPEN) { $parent[$level - 1] =& $current; // Insert a new tag - if(!is_array($current) or (!in_array($tag, array_keys($current)))) { + if (!is_array($current) or (!in_array($tag, array_keys($current)))) { $current[$tag] = $result; $current =& $current[$tag]; } // A duplicate key exists, make it an array else { - if(isset($current[$tag][0]) and is_array($current[$tag])) + if (isset($current[$tag][0]) and is_array($current[$tag])) $current[$tag][] = $result; //This section will make the value an array if multiple tags with the same name appear together else @@ -101,13 +105,13 @@ public static function decode($contents) { } } //Tags with no content '' - else if($type == self::TYPE_COMPLETE) { + else if ($type == self::TYPE_COMPLETE) { //See if the key is already taken. - if(!isset($current[$tag])) + if (!isset($current[$tag])) $current[$tag] = $result; else { //If it is already an array... - if(isset($current[$tag][0]) and is_array($current[$tag])) + if (isset($current[$tag][0]) and is_array($current[$tag])) $current[$tag][] = $result; //Make it an array using using the existing value and the new value else @@ -115,19 +119,20 @@ public static function decode($contents) { } } //End of tag '' - else if($type == self::TYPE_CLOSE) + else if ($type == self::TYPE_CLOSE) $current =& $parent[$level - 1]; } return $xml_array; } - public static function arrayify($data, array $force = array(), $forceEach = true) { - if(is_array($data) || is_object($data)) { + public static function arrayify($data, array $force = array(), $forceEach = true) + { + if (is_array($data) || is_object($data)) { $jsonarr = array(); - if($data instanceof Model) + if ($data instanceof Model) $data = $data->_toArray(); - foreach($data as $key => $value) { + foreach ($data as $key => $value) { $jsonarr[$key] = self::arrayify($value, $forceEach ? $force : array(), false); } return $jsonarr; diff --git a/src/Wave/Validator.php b/src/Wave/Validator.php index 1f88412..9fe6ba5 100755 --- a/src/Wave/Validator.php +++ b/src/Wave/Validator.php @@ -11,7 +11,8 @@ use Wave\Validator\Exception\ValidationException; use Wave\Validator\Result; -class Validator implements ArrayAccess { +class Validator implements ArrayAccess +{ const CONSTRAINT_CLASS_MASK = "\\Wave\\Validator\\Constraints\\%sConstraint"; @@ -36,11 +37,13 @@ class Validator implements ArrayAccess { */ public static $last_errors = array(); - public static function useExceptions($use_exceptions = false) { + public static function useExceptions($use_exceptions = false) + { self::$use_exceptions = $use_exceptions; } - public static function nullCleaned($null_cleaned = true) { + public static function nullCleaned($null_cleaned = true) + { self::$null_cleaned = $null_cleaned; } @@ -55,28 +58,29 @@ public static function nullCleaned($null_cleaned = true) { * @throws ValidationException * */ - public static function validate($schema, array $input) { + public static function validate($schema, array $input) + { $instance = new self($input, self::getSchema($schema)); - if($instance->execute()){ + if ($instance->execute()) { return new Result($instance->getCleanedData(), $instance->getViolations()); - } - else { + } else { throw new InvalidInputException($instance->getViolations()); } } - public static function getSchema($schema){ - if(!array_key_exists($schema, self::$_schema_cache)) { + public static function getSchema($schema) + { + if (!array_key_exists($schema, self::$_schema_cache)) { $schema_name = strtr($schema, '_', DIRECTORY_SEPARATOR); $schema_file = sprintf(Config::get('wave')->schemas->file_format, $schema_name); $schema_path = Config::get('wave')->path->schemas . $schema_file; - if(is_file($schema_path) && is_readable($schema_path)) { + if (is_file($schema_path) && is_readable($schema_path)) { $schema_data = include $schema_path; - if(!array_key_exists('fields', $schema_data)) + if (!array_key_exists('fields', $schema_data)) throw new InvalidArgumentException("$schema must have a 'fields' definition"); self::$_schema_cache[$schema] = &$schema_data; @@ -89,7 +93,8 @@ public static function getSchema($schema){ } - private static function translateConstraintKeyToClass($key) { + private static function translateConstraintKeyToClass($key) + { return sprintf(self::CONSTRAINT_CLASS_MASK, str_replace(' ', '', ucwords(str_replace('_', ' ', $key)))); } @@ -98,61 +103,62 @@ private static function translateConstraintKeyToClass($key) { * @param array $schema The schema to validate against * @param Validator $parent_instance */ - public function __construct(array $input, array $schema, $parent_instance = null) { + public function __construct(array $input, array $schema, $parent_instance = null) + { $this->input = $input; $this->schema = $schema['fields']; - if(array_key_exists('aliases', $schema)) { + if (array_key_exists('aliases', $schema)) { $this->aliases = $schema['aliases']; } - if(array_key_exists('options', $schema)) { + if (array_key_exists('options', $schema)) { $this->options = array_merge($this->options, $schema['options']); } $this->parent_instance = $parent_instance; } - public function execute() { + public function execute() + { - foreach($this->schema as $field_name => $definition) { + foreach ($this->schema as $field_name => $definition) { // check if the field was supplied using one of its aliases $field_alias = $field_name; - if(!isset($this->input[$field_name]) && isset($this->aliases[$field_name])) { - if(!is_array($this->aliases[$field_name])) + if (!isset($this->input[$field_name]) && isset($this->aliases[$field_name])) { + if (!is_array($this->aliases[$field_name])) $this->aliases[$field_name] = array($this->aliases[$field_name]); - foreach($this->aliases[$field_name] as $alias) { - if(isset($this->input[$alias])) { + foreach ($this->aliases[$field_name] as $alias) { + if (isset($this->input[$alias])) { $field_alias = $alias; break; } } } - if(self::$null_cleaned) { + if (self::$null_cleaned) { $this->setCleanedData($field_name, null); } $is_required = !(isset($definition['required']) && is_bool($definition['required']) && !$definition['required']); $message = 'This field is required'; - if(isset($definition['required'])) { - if(is_array($definition['required']) && isset($definition['required']['value'], $definition['required']['message'])) { + if (isset($definition['required'])) { + if (is_array($definition['required']) && isset($definition['required']['value'], $definition['required']['message'])) { $message = $definition['required']['message']; $definition['required'] = $definition['required']['value']; } - if(is_callable($definition['required'])) { + if (is_callable($definition['required'])) { $is_required = call_user_func($definition['required'], $this); - } - else if(is_string($definition['required'])) { + } else if (is_string($definition['required'])) { $is_required = isset($this->input[$definition['required']]); } } // A default value of null implies allow_null => true so prepend that constraint to the definition - if(array_key_exists('default', $definition) && $definition['default'] === null) { + if (array_key_exists('default', $definition) && $definition['default'] === null) { // use array_replace to get the allow_null early in the definition order $definition = array_replace(array('allow_null' => true), $definition); } @@ -162,60 +168,57 @@ public function execute() { // constraints if that is the case $input_present = array_key_exists($field_alias, $this->input); $is_strict = isset($definition['strict']) ? $definition['strict'] : $this->options['strict']; - if(!$is_strict && $input_present) { + if (!$is_strict && $input_present) { $empty_string = is_string($this->input[$field_alias]) && strlen($this->input[$field_alias]) <= 0; $empty_array = is_array($this->input[$field_alias]) && empty($this->input[$field_alias]); - if($empty_string || $empty_array) { + if ($empty_string || $empty_array) { unset($this->input[$field_alias]); $input_present = false; } } - if(!$input_present) { - if($is_required) { - $this->addViolation( $field_alias, array( + if (!$input_present) { + if ($is_required) { + $this->addViolation($field_alias, array( 'field_name' => $field_alias, 'reason' => 'missing', 'message' => $message )); continue; - } - else { - if(array_key_exists('default', $definition)) { + } else { + if (array_key_exists('default', $definition)) { if (is_callable($definition['default'])) { $this->setCleanedData($field_name, call_user_func($definition['default'], $this)); } else { $this->setCleanedData($field_name, $definition['default']); } - } - else { + } else { continue; } } - } - else { + } else { $this->setCleanedData($field_name, $this->input[$field_alias]); } unset($definition['required'], $definition['strict'], $definition['default']); - foreach($definition as $constraint => $arguments) { + foreach ($definition as $constraint => $arguments) { //if($constraint === 'required') continue; $handler = self::translateConstraintKeyToClass($constraint); - if(!class_exists($handler)) + if (!class_exists($handler)) throw new InvalidConstraintException("Handler for '$constraint' does not exist"); /** @var $instance \Wave\Validator\Constraints\AbstractConstraint */ $instance = new $handler($field_name, $arguments, $this); - if(!$instance->evaluate()) { + if (!$instance->evaluate()) { $violations = $instance->getViolationPayload(); - if(!empty($violations)) { + if (!empty($violations)) { $this->addViolation($field_alias, $violations); $this->unsetCleanedData($field_name, true); } break; } - if($instance instanceof CleanerInterface) { + if ($instance instanceof CleanerInterface) { $this->setCleanedData($field_name, $instance->getCleanedData()); } } @@ -228,7 +231,8 @@ public function execute() { * @param string $field the name of the field with the violation * @param array $payload information about the violation */ - public function addViolation($field, array $payload) { + public function addViolation($field, array $payload) + { $this->violations[$field] = $payload; } @@ -236,14 +240,15 @@ public function addViolation($field, array $payload) { * @param string $field the name of the field with the violation * @return */ - public function getViolation($field_name) { + public function getViolation($field_name) + { $field_alias = $field_name; - if(!isset($this->violations[$field_name]) && isset($this->aliases[$field_name])) { - if(!is_array($this->aliases[$field_name])) + if (!isset($this->violations[$field_name]) && isset($this->aliases[$field_name])) { + if (!is_array($this->aliases[$field_name])) $this->aliases[$field_name] = array($this->aliases[$field_name]); - foreach($this->aliases[$field_name] as $alias) { - if(isset($this->violations[$alias])) { + foreach ($this->aliases[$field_name] as $alias) { + if (isset($this->violations[$alias])) { return $this->violations[$alias]; } } @@ -252,67 +257,81 @@ public function getViolation($field_name) { return isset($this->violations[$field_alias]) ? $this->violations[$field_alias] : null; } - public function getViolations() { + public function getViolations() + { return $this->violations; } - public function getSchemaKey($key) { - if(array_key_exists($key, $this->schema)) + public function getSchemaKey($key) + { + if (array_key_exists($key, $this->schema)) return $this->schema[$key]; return null; } - public function setCleanedData($field, $value) { + public function setCleanedData($field, $value) + { $this->cleaned[$field] = $value; } - public function unsetCleanedData($field, $remove = false) { - if($remove) unset($this->cleaned[$field]); + public function unsetCleanedData($field, $remove = false) + { + if ($remove) unset($this->cleaned[$field]); else $this->cleaned[$field] = null; } - public function getCleanedData() { + public function getCleanedData() + { return $this->cleaned; } - public function getInputData($key = null) { - if($key === null) + public function getInputData($key = null) + { + if ($key === null) return $this->input; - elseif(isset($this->input[$key])) + elseif (isset($this->input[$key])) return $this->input[$key]; else return null; } - public function hasInputData($key) { + public function hasInputData($key) + { return array_key_exists($key, $this->input); } - public function getParentInstance() { + public function getParentInstance() + { return $this->parent_instance; } - public function offsetExists($offset) { + public function offsetExists($offset): bool + { return array_key_exists($offset, $this->cleaned); } - public function offsetGet($offset) { + public function offsetGet($offset): mixed + { return $this->cleaned[$offset]; } - public function offsetGetOrNull($offset) { + public function offsetGetOrNull($offset) + { return isset($this->cleaned[$offset]) ? $this->cleaned[$offset] : null; } - public function offsetSet($offset, $value) { + public function offsetSet($offset, $value): void + { throw new \BadMethodCallException("Setting validator input data is not supported"); } - public function offsetUnset($offset) { + public function offsetUnset($offset): void + { throw new \BadMethodCallException("Unsetting validator input data is not supported"); } - private function valueIsNullish($input) { + private function valueIsNullish($input) + { return is_null($input) // actually null || (is_string($input) && strlen($input) <= 0) // an empty string (from a query string) || (is_array($input) && empty($input)); // an empty array (from a query string) diff --git a/src/Wave/Validator/CleanerInterface.php b/src/Wave/Validator/CleanerInterface.php index b554f26..07c25a8 100644 --- a/src/Wave/Validator/CleanerInterface.php +++ b/src/Wave/Validator/CleanerInterface.php @@ -2,7 +2,8 @@ namespace Wave\Validator; -interface CleanerInterface { +interface CleanerInterface +{ public function getCleanedData(); diff --git a/src/Wave/Validator/Constraints/AbstractConstraint.php b/src/Wave/Validator/Constraints/AbstractConstraint.php index b5f86f6..af35fdb 100644 --- a/src/Wave/Validator/Constraints/AbstractConstraint.php +++ b/src/Wave/Validator/Constraints/AbstractConstraint.php @@ -4,7 +4,8 @@ use Wave\Validator; -abstract class AbstractConstraint { +abstract class AbstractConstraint +{ const ERROR_INVALID = 'invalid'; @@ -18,7 +19,8 @@ abstract class AbstractConstraint { * @param mixed $arguments the arguments for the current constraint (from the schema) * @param \Wave\Validator $validator the current instance of the validator */ - public function __construct($property, $arguments, Validator &$validator) { + public function __construct($property, $arguments, Validator &$validator) + { $this->property = $property; $this->data = isset($validator[$property]) ? $validator[$property] : null; @@ -35,7 +37,8 @@ public function __construct($property, $arguments, Validator &$validator) { abstract public function evaluate(); - protected function getViolationKey() { + protected function getViolationKey() + { return static::ERROR_INVALID; } @@ -46,11 +49,13 @@ protected function getViolationKey() { * (for example: 'Your email address' is not valid). * @return string */ - protected function getViolationMessage($context = 'This value') { + protected function getViolationMessage($context = 'This value') + { return sprintf('%s is not valid', $context); } - public function getViolationPayload() { + public function getViolationPayload() + { return array( 'reason' => $this->getViolationKey(), 'message' => $this->getViolationMessage() diff --git a/src/Wave/Validator/Constraints/AbstractLengthConstraint.php b/src/Wave/Validator/Constraints/AbstractLengthConstraint.php index cc0692f..21e598e 100644 --- a/src/Wave/Validator/Constraints/AbstractLengthConstraint.php +++ b/src/Wave/Validator/Constraints/AbstractLengthConstraint.php @@ -5,7 +5,8 @@ use DateTime; use Wave\Validator; -abstract class AbstractLengthConstraint extends AbstractConstraint { +abstract class AbstractLengthConstraint extends AbstractConstraint +{ const COMPARATOR_ARRAY = 'array'; const COMPARATOR_INT = 'int'; @@ -17,10 +18,11 @@ abstract class AbstractLengthConstraint extends AbstractConstraint { protected $count = null; protected $message = null; - public function __construct($property, $arguments, Validator $validator) { + public function __construct($property, $arguments, Validator $validator) + { parent::__construct($property, $arguments, $validator); - if(is_array($arguments)) { + if (is_array($arguments)) { $this->limit = isset($arguments['limit']) ? $arguments['limit'] : null; @@ -40,18 +42,18 @@ public function __construct($property, $arguments, Validator $validator) { $this->limit = $arguments; } - if($this->comparator === null) { - if(is_array($this->data)) + if ($this->comparator === null) { + if (is_array($this->data)) $this->count = self::COMPARATOR_ARRAY; - elseif(is_numeric($this->data)) + elseif (is_numeric($this->data)) $this->comparator = self::COMPARATOR_INT; - elseif(is_string($this->data)) + elseif (is_string($this->data)) $this->comparator = self::COMPARATOR_STRING; - elseif($this->data instanceof DateTime) + elseif ($this->data instanceof DateTime) $this->comparator = self::COMPARATOR_DATETIME; } - switch($this->comparator) { + switch ($this->comparator) { case self::COMPARATOR_ARRAY: $this->count = count($this->data); break; @@ -62,7 +64,7 @@ public function __construct($property, $arguments, Validator $validator) { $this->count = $this->data; break; default: - $this->count = (double) $this->data; + $this->count = (double)$this->data; } } diff --git a/src/Wave/Validator/Constraints/AllowNullConstraint.php b/src/Wave/Validator/Constraints/AllowNullConstraint.php index 8f0e293..7daf81f 100644 --- a/src/Wave/Validator/Constraints/AllowNullConstraint.php +++ b/src/Wave/Validator/Constraints/AllowNullConstraint.php @@ -8,14 +8,16 @@ /** * Sets the default cleaned data for this key */ -class AllowNullConstraint extends AbstractConstraint implements CleanerInterface { +class AllowNullConstraint extends AbstractConstraint implements CleanerInterface +{ /** * Always returns true, */ - public function evaluate() { + public function evaluate() + { - if($this->data === null) { + if ($this->data === null) { // we return false here but with no violations // to stop execution of subsequent constraints return false; @@ -24,12 +26,14 @@ public function evaluate() { } - public function getViolationPayload() { + public function getViolationPayload() + { return array(); } - public function getCleanedData() { + public function getCleanedData() + { return $this->data; } diff --git a/src/Wave/Validator/Constraints/AnyConstraint.php b/src/Wave/Validator/Constraints/AnyConstraint.php index 145cebe..f97845b 100755 --- a/src/Wave/Validator/Constraints/AnyConstraint.php +++ b/src/Wave/Validator/Constraints/AnyConstraint.php @@ -10,7 +10,8 @@ /** * Reads an array of sub-constraints and returns true if any one of them returns true. */ -class AnyConstraint extends AbstractConstraint implements CleanerInterface { +class AnyConstraint extends AbstractConstraint implements CleanerInterface +{ private $inherit_schema = array( 'required' => false @@ -21,32 +22,34 @@ class AnyConstraint extends AbstractConstraint implements CleanerInterface { private $message = null; - public function __construct($property, $arguments, Validator &$validator) { + public function __construct($property, $arguments, Validator &$validator) + { parent::__construct($property, $arguments, $validator); // inherit the default value from the parent instance of $schema = $validator->getSchemaKey($property); - if(array_key_exists('default', $schema)) { + if (array_key_exists('default', $schema)) { $this->inherit_schema['default'] = $schema['default']; } } /** - * @throws \InvalidArgumentException * @return bool + * @throws \InvalidArgumentException */ - public function evaluate() { + public function evaluate() + { - if(!is_array($this->arguments)) + if (!is_array($this->arguments)) throw new \InvalidArgumentException("[any] constraint requires an array argument"); - if(!isset($this->arguments[0])) + if (!isset($this->arguments[0])) $this->arguments = array($this->arguments); $input = array($this->property => $this->data); - foreach($this->arguments as $key => $constraint_group) { + foreach ($this->arguments as $key => $constraint_group) { - if($key === 'message') { + if ($key === 'message') { $this->message = $constraint_group; continue; } @@ -57,27 +60,28 @@ public function evaluate() { ) ), $this->validator); - if($instance->execute()) { + if ($instance->execute()) { $cleaned = $instance->getCleanedData(); - if(isset($cleaned[$this->property])) { + if (isset($cleaned[$this->property])) { $this->cleaned = $cleaned[$this->property]; } return true; } else { $violations = $instance->getViolations(); $messages = array_intersect_key($violations[$this->property], array_flip(array('reason', 'message'))); - if(!empty($messages)) + if (!empty($messages)) $this->violations[] = $messages; } } return empty($this->violations); } - public function getViolationPayload() { + public function getViolationPayload() + { $payload = array( 'reason' => 'invalid', ); - if($this->message !== null) { + if ($this->message !== null) { $payload['message'] = $this->message; } else { $payload['message'] = 'This value does not match any of the following conditions'; @@ -86,7 +90,8 @@ public function getViolationPayload() { return $payload; } - public function getCleanedData() { + public function getCleanedData() + { return $this->cleaned; } diff --git a/src/Wave/Validator/Constraints/CallableConstraint.php b/src/Wave/Validator/Constraints/CallableConstraint.php index d19d867..3f5a8c5 100644 --- a/src/Wave/Validator/Constraints/CallableConstraint.php +++ b/src/Wave/Validator/Constraints/CallableConstraint.php @@ -8,15 +8,17 @@ use Wave\Validator\CleanerInterface; use Wave\Validator\Exception; -class CallableConstraint extends AbstractConstraint implements CleanerInterface { +class CallableConstraint extends AbstractConstraint implements CleanerInterface +{ const ERROR_CALLABLE = 'callable'; private $key = self::ERROR_CALLABLE; private $message = '%s is not valid'; - public function __construct($property, $arguments, Validator &$validator) { - if(!is_callable($arguments)) + public function __construct($property, $arguments, Validator &$validator) + { + if (!is_callable($arguments)) throw new \InvalidArgumentException('The argument passed to [callable] must be callable'); parent::__construct($property, $arguments, $validator); @@ -26,7 +28,8 @@ public function __construct($property, $arguments, Validator &$validator) { /** * @return bool */ - public function evaluate() { + public function evaluate() + { return call_user_func_array( $this->arguments, array( &$this->data, @@ -40,15 +43,18 @@ public function evaluate() { /** * @return string */ - protected function getViolationKey() { + protected function getViolationKey() + { return $this->key; } - protected function getViolationMessage($context = 'This value') { + protected function getViolationMessage($context = 'This value') + { return sprintf($this->message, $context); } - public function getCleanedData() { + public function getCleanedData() + { return $this->data; } } \ No newline at end of file diff --git a/src/Wave/Validator/Constraints/DateConstraint.php b/src/Wave/Validator/Constraints/DateConstraint.php index 9f83b20..211349c 100644 --- a/src/Wave/Validator/Constraints/DateConstraint.php +++ b/src/Wave/Validator/Constraints/DateConstraint.php @@ -6,15 +6,17 @@ use Wave\Validator; use Wave\Validator\CleanerInterface; -class DateConstraint extends AbstractConstraint implements CleanerInterface { +class DateConstraint extends AbstractConstraint implements CleanerInterface +{ private $format = null; private $datetime; - public function __construct($property, $arguments, Validator $validator) { + public function __construct($property, $arguments, Validator $validator) + { parent::__construct($property, $arguments, $validator); - if($arguments !== '*') + if ($arguments !== '*') $this->format = $arguments; } @@ -24,33 +26,36 @@ public function __construct($property, $arguments, Validator $validator) { * * @return mixed */ - public function evaluate() { + public function evaluate() + { $this->datetime = null; try { - if($this->format !== null) + if ($this->format !== null) $this->datetime = DateTime::createFromFormat($this->format, $this->data); else $this->datetime = new DateTime($this->data); - if(!($this->datetime instanceof DateTime)) return false; + if (!($this->datetime instanceof DateTime)) return false; return true; - } catch(\Exception $e) { + } catch (\Exception $e) { return false; } } - protected function getViolationMessage($context = 'This date') { - if($this->format === null) + protected function getViolationMessage($context = 'This date') + { + if ($this->format === null) return sprintf('%s is not in a recognised date format', $context); else return sprintf('%s is not in the required format (%s)', $context, $this->format); } - public function getCleanedData() { + public function getCleanedData() + { return $this->datetime; } } diff --git a/src/Wave/Validator/Constraints/DefaultConstraint.php b/src/Wave/Validator/Constraints/DefaultConstraint.php index a702767..a2b712c 100644 --- a/src/Wave/Validator/Constraints/DefaultConstraint.php +++ b/src/Wave/Validator/Constraints/DefaultConstraint.php @@ -8,16 +8,19 @@ /** * Sets the default cleaned data for this key */ -class DefaultConstraint extends AbstractConstraint implements CleanerInterface { +class DefaultConstraint extends AbstractConstraint implements CleanerInterface +{ /** * Always returns true, */ - public function evaluate() { + public function evaluate() + { return true; } - public function getCleanedData() { + public function getCleanedData() + { return $this->validator->hasInputData($this->property) === null ? $this->arguments : $this->data; } diff --git a/src/Wave/Validator/Constraints/DependsOnConstraint.php b/src/Wave/Validator/Constraints/DependsOnConstraint.php index 1cf1048..610d9f5 100644 --- a/src/Wave/Validator/Constraints/DependsOnConstraint.php +++ b/src/Wave/Validator/Constraints/DependsOnConstraint.php @@ -5,20 +5,22 @@ use InvalidArgumentException; -class DependsOnConstraint extends AbstractConstraint { +class DependsOnConstraint extends AbstractConstraint +{ const ERROR_DEPENDS_ON = 'depends_on'; /** * @return bool */ - public function evaluate() { - if(!is_array($this->arguments)) $this->arguments = array($this->arguments); - foreach($this->arguments as $field) { - if($this->validator->getSchemaKey($field) === null) + public function evaluate() + { + if (!is_array($this->arguments)) $this->arguments = array($this->arguments); + foreach ($this->arguments as $field) { + if ($this->validator->getSchemaKey($field) === null) throw new InvalidArgumentException("Can't depend_on '{$field}' since it doesn't exist in schema"); - if(!$this->validator->offsetExists($field) || $this->validator->getViolation($field) !== null) { + if (!$this->validator->offsetExists($field) || $this->validator->getViolation($field) !== null) { return false; } @@ -26,7 +28,8 @@ public function evaluate() { return true; } - public function getViolationPayload() { + public function getViolationPayload() + { return array(); } diff --git a/src/Wave/Validator/Constraints/EqualsConstraint.php b/src/Wave/Validator/Constraints/EqualsConstraint.php index 7b026a3..7a52d96 100644 --- a/src/Wave/Validator/Constraints/EqualsConstraint.php +++ b/src/Wave/Validator/Constraints/EqualsConstraint.php @@ -2,7 +2,8 @@ namespace Wave\Validator\Constraints; -class EqualsConstraint extends AbstractConstraint { +class EqualsConstraint extends AbstractConstraint +{ const ERROR_NOT_EQUAL = 'not_equal'; @@ -11,11 +12,13 @@ class EqualsConstraint extends AbstractConstraint { * * @return mixed */ - public function evaluate() { + public function evaluate() + { return $this->data === $this->arguments; } - protected function getViolationMessage($context = 'This value') { + protected function getViolationMessage($context = 'This value') + { return sprintf("%s does not equal %s", $context, $this->arguments); } diff --git a/src/Wave/Validator/Constraints/ExistsConstraint.php b/src/Wave/Validator/Constraints/ExistsConstraint.php index 3d9f9f4..7d69fe6 100644 --- a/src/Wave/Validator/Constraints/ExistsConstraint.php +++ b/src/Wave/Validator/Constraints/ExistsConstraint.php @@ -9,7 +9,8 @@ use Wave\Validator\CleanerInterface; use Wave\Validator\Exception; -class ExistsConstraint extends AbstractConstraint implements CleanerInterface { +class ExistsConstraint extends AbstractConstraint implements CleanerInterface +{ const ERROR_NOT_EXISTS = 'not_exists'; @@ -18,18 +19,19 @@ class ExistsConstraint extends AbstractConstraint implements CleanerInterface { private $match_fields = array(); private $instance = null; - public function __construct($property, $arguments, Validator &$validator) { - if(!is_array($arguments) || !isset($arguments['model']) || !isset($arguments['property'])) + public function __construct($property, $arguments, Validator &$validator) + { + if (!is_array($arguments) || !isset($arguments['model']) || !isset($arguments['property'])) throw new \InvalidArgumentException("[{$this->type}] constraint requires a model and property to be declared"); parent::__construct($property, $arguments, $validator); $this->match_fields = $arguments['property']; - if(!is_array($arguments['property'])) { + if (!is_array($arguments['property'])) { $this->match_fields = array($arguments['property'] => $property); } - if(empty($this->match_fields)) + if (empty($this->match_fields)) throw new \InvalidArgumentException("[$this->type] constraint requires at least one property to match"); $this->message = isset($arguments['message']) ? $arguments['message'] : null; @@ -38,10 +40,11 @@ public function __construct($property, $arguments, Validator &$validator) { /** * @return bool */ - public function evaluate() { + public function evaluate() + { $statement = DB::get()->from($this->arguments['model']); - foreach($this->match_fields as $column => $input_key) { + foreach ($this->match_fields as $column => $input_key) { $statement->where($column . ' = ?', $this->validator[$input_key]); } @@ -50,18 +53,21 @@ public function evaluate() { return $this->instance instanceof Model; } - public function getCleanedData() { + public function getCleanedData() + { return $this->instance; } /** * @return string */ - protected function getViolationKey() { + protected function getViolationKey() + { return static::ERROR_NOT_EXISTS; } - protected function getViolationMessage($context = 'This value') { + protected function getViolationMessage($context = 'This value') + { $message = isset($this->message) ? $this->message : '%s does not exist'; return sprintf($message, $context); } diff --git a/src/Wave/Validator/Constraints/InstanceOfConstraint.php b/src/Wave/Validator/Constraints/InstanceOfConstraint.php index ceeb6d1..65e98a6 100755 --- a/src/Wave/Validator/Constraints/InstanceOfConstraint.php +++ b/src/Wave/Validator/Constraints/InstanceOfConstraint.php @@ -2,7 +2,8 @@ namespace Wave\Validator\Constraints; -class InstanceOfConstraint extends AbstractConstraint { +class InstanceOfConstraint extends AbstractConstraint +{ /** @@ -10,11 +11,13 @@ class InstanceOfConstraint extends AbstractConstraint { * * @return mixed */ - public function evaluate() { + public function evaluate() + { return $this->data instanceof $this->arguments; } - protected function getViolationMessage($context = 'This value') { + protected function getViolationMessage($context = 'This value') + { return sprintf("%s is not a valid %s object", $context, $this->arguments); } diff --git a/src/Wave/Validator/Constraints/MapConstraint.php b/src/Wave/Validator/Constraints/MapConstraint.php index 307d0c1..33a8807 100755 --- a/src/Wave/Validator/Constraints/MapConstraint.php +++ b/src/Wave/Validator/Constraints/MapConstraint.php @@ -10,29 +10,32 @@ /** * Reads an array of sub-constraints and returns true if any one of them returns true. */ -class MapConstraint extends AbstractConstraint implements CleanerInterface { +class MapConstraint extends AbstractConstraint implements CleanerInterface +{ private $cleaned = array(); private $violations = array(); - public function __construct($property, $arguments, &$validator) { + public function __construct($property, $arguments, &$validator) + { parent::__construct($property, $arguments, $validator); - if(!is_array($this->data)) + if (!is_array($this->data)) throw new \InvalidArgumentException("[map] constraint requires an array of input data"); } /** * @return bool */ - public function evaluate() { + public function evaluate() + { $schema = array('fields' => array($this->property => $this->arguments)); - foreach($this->data as $i => $data) { + foreach ($this->data as $i => $data) { $input = array($this->property => $data); $instance = new Validator($input, $schema, $this->validator); - if($instance->execute(true)) { + if ($instance->execute(true)) { $cleaned = $instance->getCleanedData(); $this->cleaned[$i] = $cleaned[$this->property]; } else { @@ -46,11 +49,13 @@ public function evaluate() { } - public function getViolationPayload() { + public function getViolationPayload() + { return $this->violations; } - public function getCleanedData() { + public function getCleanedData() + { return $this->cleaned; } diff --git a/src/Wave/Validator/Constraints/MaxLengthConstraint.php b/src/Wave/Validator/Constraints/MaxLengthConstraint.php index 7e58847..6b6bd8b 100644 --- a/src/Wave/Validator/Constraints/MaxLengthConstraint.php +++ b/src/Wave/Validator/Constraints/MaxLengthConstraint.php @@ -3,38 +3,43 @@ namespace Wave\Validator\Constraints; -class MaxLengthConstraint extends AbstractLengthConstraint { +class MaxLengthConstraint extends AbstractLengthConstraint +{ const ERROR_TOO_LONG = 'too_long'; /** * @return bool */ - public function evaluate() { + public function evaluate() + { return $this->count <= $this->limit; } /** * @return string */ - protected function getViolationKey() { + protected function getViolationKey() + { return static::ERROR_TOO_LONG; } - protected function getViolationMessage($context = 'This value') { - if($this->message !== null) + protected function getViolationMessage($context = 'This value') + { + if ($this->message !== null) return $this->message; - else if($this->comparator === static::COMPARATOR_ARRAY) + else if ($this->comparator === static::COMPARATOR_ARRAY) return sprintf('%s must have no more than %s members', $context, $this->limit); - elseif($this->comparator === static::COMPARATOR_INT) + elseif ($this->comparator === static::COMPARATOR_INT) return sprintf('%s must be less than %s', $context, $this->limit); - elseif($this->comparator === static::COMPARATOR_DATETIME) + elseif ($this->comparator === static::COMPARATOR_DATETIME) return sprintf('%s must be before %s', $context, $this->limit->format('c')); else return sprintf('%s must have no more than %s characters', $context, $this->limit); } - public function getViolationPayload() { + public function getViolationPayload() + { return array_merge( parent::getViolationPayload(), array( diff --git a/src/Wave/Validator/Constraints/MemberOfConstraint.php b/src/Wave/Validator/Constraints/MemberOfConstraint.php index 178edac..8eaf75d 100644 --- a/src/Wave/Validator/Constraints/MemberOfConstraint.php +++ b/src/Wave/Validator/Constraints/MemberOfConstraint.php @@ -3,29 +3,34 @@ namespace Wave\Validator\Constraints; -class MemberOfConstraint extends AbstractConstraint { +class MemberOfConstraint extends AbstractConstraint +{ const ERROR_NOT_MEMBER = 'not_member'; /** * @return bool */ - public function evaluate() { + public function evaluate() + { return in_array($this->data, $this->arguments, true); } /** * @return string */ - protected function getViolationKey() { + protected function getViolationKey() + { return static::ERROR_NOT_MEMBER; } - protected function getViolationMessage($context = 'This value') { + protected function getViolationMessage($context = 'This value') + { return sprintf('%s is not a valid choice', $context); } - public function getViolationPayload() { + public function getViolationPayload() + { return array_merge( parent::getViolationPayload(), array( diff --git a/src/Wave/Validator/Constraints/MinLengthConstraint.php b/src/Wave/Validator/Constraints/MinLengthConstraint.php index c7d3677..374002b 100644 --- a/src/Wave/Validator/Constraints/MinLengthConstraint.php +++ b/src/Wave/Validator/Constraints/MinLengthConstraint.php @@ -3,38 +3,43 @@ namespace Wave\Validator\Constraints; -class MinLengthConstraint extends AbstractLengthConstraint { +class MinLengthConstraint extends AbstractLengthConstraint +{ const ERROR_TOO_SHORT = 'too_short'; /** * @return bool */ - public function evaluate() { + public function evaluate() + { return $this->count >= $this->limit; } /** * @return string */ - protected function getViolationKey() { + protected function getViolationKey() + { return static::ERROR_TOO_SHORT; } - protected function getViolationMessage($context = 'This value') { - if($this->message !== null) + protected function getViolationMessage($context = 'This value') + { + if ($this->message !== null) return $this->message; - else if($this->comparator === static::COMPARATOR_ARRAY) + else if ($this->comparator === static::COMPARATOR_ARRAY) return sprintf('%s must have at least %s members', $context, $this->limit); - elseif($this->comparator === static::COMPARATOR_INT) + elseif ($this->comparator === static::COMPARATOR_INT) return sprintf('%s must be greater than %s', $context, $this->limit); - elseif($this->comparator === static::COMPARATOR_DATETIME) + elseif ($this->comparator === static::COMPARATOR_DATETIME) return sprintf('%s must be after %s', $context, $this->limit->format('c')); else return sprintf('%s must be at least %s characters', $context, $this->limit); } - public function getViolationPayload() { + public function getViolationPayload() + { return array_merge( parent::getViolationPayload(), array( diff --git a/src/Wave/Validator/Constraints/PropertyEqualsConstraint.php b/src/Wave/Validator/Constraints/PropertyEqualsConstraint.php index f245341..18352be 100644 --- a/src/Wave/Validator/Constraints/PropertyEqualsConstraint.php +++ b/src/Wave/Validator/Constraints/PropertyEqualsConstraint.php @@ -5,19 +5,21 @@ use Wave\Validator; use Wave\Validator\Exception; -class PropertyEqualsConstraint extends AbstractConstraint { +class PropertyEqualsConstraint extends AbstractConstraint +{ - public function __construct($property, $arguments, Validator &$validator) { - if(!is_array($arguments) || !isset($arguments['property']) || !isset($arguments['value'])) + public function __construct($property, $arguments, Validator &$validator) + { + if (!is_array($arguments) || !isset($arguments['property']) || !isset($arguments['value'])) throw new \InvalidArgumentException("[property_equals] constraint must have a property and value declared"); - if(!isset($arguments['message'])) + if (!isset($arguments['message'])) $arguments['message'] = '%s failed a property comparison'; parent::__construct($property, $arguments, $validator); - if(!is_object($this->data)) + if (!is_object($this->data)) throw new \InvalidArgumentException("[property_equals] constraint requires an object parameter"); } @@ -26,12 +28,14 @@ public function __construct($property, $arguments, Validator &$validator) { * * @return mixed */ - public function evaluate() { + public function evaluate() + { $property = $this->arguments['property']; return isset($this->data->$property) && $this->data->$property === $this->arguments['value']; } - protected function getViolationMessage($context = 'This value') { + protected function getViolationMessage($context = 'This value') + { return sprintf($this->arguments['message'], $context); } diff --git a/src/Wave/Validator/Constraints/RegexConstraint.php b/src/Wave/Validator/Constraints/RegexConstraint.php index 684cdf2..1b4640b 100644 --- a/src/Wave/Validator/Constraints/RegexConstraint.php +++ b/src/Wave/Validator/Constraints/RegexConstraint.php @@ -4,15 +4,17 @@ use Wave\Validator; -class RegexConstraint extends AbstractConstraint { +class RegexConstraint extends AbstractConstraint +{ private $message; - public function __construct($property, $arguments, Validator &$validator) { + public function __construct($property, $arguments, Validator &$validator) + { parent::__construct($property, $arguments, $validator); - if(is_array($arguments) && !is_callable($arguments)) { - if(isset($arguments['message'], $arguments['pattern'])) { + if (is_array($arguments) && !is_callable($arguments)) { + if (isset($arguments['message'], $arguments['pattern'])) { $this->message = $arguments['message']; $this->arguments = $arguments['pattern']; } else throw new \InvalidArgumentException("Invalid format for regex constraint, must contain a [message] and [pattern]"); @@ -25,12 +27,14 @@ public function __construct($property, $arguments, Validator &$validator) { * * @return mixed */ - public function evaluate() { + public function evaluate() + { return preg_match($this->arguments, $this->data) > 0; } - protected function getViolationMessage($context = 'This value') { - if(isset($this->message)) { + protected function getViolationMessage($context = 'This value') + { + if (isset($this->message)) { return sprintf($this->message, $context); } else return parent::getViolationMessage($context); } diff --git a/src/Wave/Validator/Constraints/RenameConstraint.php b/src/Wave/Validator/Constraints/RenameConstraint.php index 57a4088..4aa4eed 100644 --- a/src/Wave/Validator/Constraints/RenameConstraint.php +++ b/src/Wave/Validator/Constraints/RenameConstraint.php @@ -6,10 +6,12 @@ use Wave\Validator; -class RenameConstraint extends AbstractConstraint { +class RenameConstraint extends AbstractConstraint +{ - public function __construct($property, $arguments, Validator &$validator) { - if(!is_string($arguments)) + public function __construct($property, $arguments, Validator &$validator) + { + if (!is_string($arguments)) throw new \InvalidArgumentException('The argument passed to [rename] must be a string'); parent::__construct($property, $arguments, $validator); @@ -18,7 +20,8 @@ public function __construct($property, $arguments, Validator &$validator) { /** * @return bool */ - public function evaluate() { + public function evaluate() + { $this->validator->setCleanedData($this->arguments, $this->data); $this->validator->unsetCleanedData($this->property, true); return true; diff --git a/src/Wave/Validator/Constraints/TransformConstraint.php b/src/Wave/Validator/Constraints/TransformConstraint.php index 463baa7..2456bbd 100644 --- a/src/Wave/Validator/Constraints/TransformConstraint.php +++ b/src/Wave/Validator/Constraints/TransformConstraint.php @@ -8,14 +8,16 @@ use Wave\Validator\CleanerInterface; use Wave\Validator\Exception; -class TransformConstraint extends AbstractConstraint implements CleanerInterface { +class TransformConstraint extends AbstractConstraint implements CleanerInterface +{ protected $key; protected $value; - public function __construct($property, $arguments, Validator &$validator) { - if(!is_callable($arguments)) + public function __construct($property, $arguments, Validator &$validator) + { + if (!is_callable($arguments)) throw new \InvalidArgumentException('The argument passed to [transform] must be callable'); parent::__construct($property, $arguments, $validator); @@ -24,7 +26,8 @@ public function __construct($property, $arguments, Validator &$validator) { /** * @return bool */ - public function evaluate() { + public function evaluate() + { $this->data = call_user_func_array( $this->arguments, array( &$this->data, @@ -38,7 +41,8 @@ public function evaluate() { } - public function getCleanedData() { + public function getCleanedData() + { return $this->data; } } \ No newline at end of file diff --git a/src/Wave/Validator/Constraints/TypeConstraint.php b/src/Wave/Validator/Constraints/TypeConstraint.php index 47fbaff..3ff91dc 100644 --- a/src/Wave/Validator/Constraints/TypeConstraint.php +++ b/src/Wave/Validator/Constraints/TypeConstraint.php @@ -7,7 +7,8 @@ use Wave\Validator\CleanerInterface; use Wave\Validator\Datatypes\AbstractDatatype; -class TypeConstraint extends AbstractConstraint implements CleanerInterface { +class TypeConstraint extends AbstractConstraint implements CleanerInterface +{ const ERROR_INVALID = 'invalid'; @@ -20,22 +21,23 @@ class TypeConstraint extends AbstractConstraint implements CleanerInterface { private $message; - public function __construct($property, $arguments, Validator &$validator) { + public function __construct($property, $arguments, Validator &$validator) + { parent::__construct($property, $arguments, $validator); $this->message = '%s is not a valid %s'; - if(is_array($arguments) && !is_callable($arguments)) { - if(isset($arguments['message'], $arguments['datatype'])) { + if (is_array($arguments) && !is_callable($arguments)) { + if (isset($arguments['message'], $arguments['datatype'])) { $this->message = $arguments['message']; $this->arguments = $arguments = $arguments['datatype']; } else throw new \InvalidArgumentException("Invalid format for type constraint, must contain a [message] and [datatype]"); } - if(is_callable($arguments)) { + if (is_callable($arguments)) { $this->handler = $arguments; - } else if(is_string($arguments)) { + } else if (is_string($arguments)) { $handler_class = sprintf(self::DATATYPE_CLASS_MASK, ucfirst($arguments)); - if(!class_exists($handler_class)) + if (!class_exists($handler_class)) throw new \InvalidArgumentException("'type' handler '$arguments' is not valid for '$property'"); $this->handler = new $handler_class($this->data); @@ -47,26 +49,30 @@ public function __construct($property, $arguments, Validator &$validator) { /** * @return bool */ - public function evaluate() { + public function evaluate() + { return call_user_func($this->handler, $this->data, $this->validator); } /** * @return string */ - protected function getViolationKey() { + protected function getViolationKey() + { return static::ERROR_INVALID; } - protected function getViolationMessage($context = 'This value') { + protected function getViolationMessage($context = 'This value') + { $type = 'type'; - if($this->handler instanceof AbstractDatatype) + if ($this->handler instanceof AbstractDatatype) $type = $this->handler->getType(); return sprintf($this->message, $context, $type); } - public function getViolationPayload() { + public function getViolationPayload() + { return array_merge( parent::getViolationPayload(), array( @@ -75,8 +81,9 @@ public function getViolationPayload() { ); } - public function getCleanedData() { - if($this->handler instanceof CleanerInterface) + public function getCleanedData() + { + if ($this->handler instanceof CleanerInterface) return $this->handler->getCleanedData(); else return $this->data; diff --git a/src/Wave/Validator/Constraints/UniqueConstraint.php b/src/Wave/Validator/Constraints/UniqueConstraint.php index 1f7386e..f39290e 100644 --- a/src/Wave/Validator/Constraints/UniqueConstraint.php +++ b/src/Wave/Validator/Constraints/UniqueConstraint.php @@ -5,7 +5,8 @@ use Wave\Validator\CleanerInterface; -class UniqueConstraint extends ExistsConstraint implements CleanerInterface { +class UniqueConstraint extends ExistsConstraint implements CleanerInterface +{ const ERROR_NOT_UNIQUE = 'not_unique'; @@ -14,22 +15,26 @@ class UniqueConstraint extends ExistsConstraint implements CleanerInterface { /** * @return bool */ - public function evaluate() { + public function evaluate() + { return !parent::evaluate(); } - public function getCleanedData() { + public function getCleanedData() + { return $this->data; } /** * @return string */ - protected function getViolationKey() { + protected function getViolationKey() + { return static::ERROR_NOT_UNIQUE; } - protected function getViolationMessage($context = 'This value') { + protected function getViolationMessage($context = 'This value') + { $message = isset($this->message) ? $this->message : '%s is not unique'; return sprintf($message, $context); } diff --git a/src/Wave/Validator/Datatypes/AbstractDatatype.php b/src/Wave/Validator/Datatypes/AbstractDatatype.php index 9cc6943..4d47624 100644 --- a/src/Wave/Validator/Datatypes/AbstractDatatype.php +++ b/src/Wave/Validator/Datatypes/AbstractDatatype.php @@ -2,14 +2,16 @@ namespace Wave\Validator\Datatypes; -abstract class AbstractDatatype { +abstract class AbstractDatatype +{ /** * @var $input mixed */ protected $input; - public function __construct($input) { + public function __construct($input) + { $this->input = $input; } diff --git a/src/Wave/Validator/Datatypes/AlphanumDatatype.php b/src/Wave/Validator/Datatypes/AlphanumDatatype.php index df14474..ddb1770 100755 --- a/src/Wave/Validator/Datatypes/AlphanumDatatype.php +++ b/src/Wave/Validator/Datatypes/AlphanumDatatype.php @@ -3,10 +3,12 @@ namespace Wave\Validator\Datatypes; -class AlphanumDatatype extends AbstractDatatype { +class AlphanumDatatype extends AbstractDatatype +{ - public function __invoke() { - if(!is_scalar($this->input)) return false; + public function __invoke() + { + if (!is_scalar($this->input)) return false; return preg_match('/^[A-Za-z0-9]*$/', $this->input) > 0; } @@ -14,7 +16,8 @@ public function __invoke() { /** * @return string a type to use in the violation message */ - public function getType() { + public function getType() + { return 'alphanumeric string'; } } diff --git a/src/Wave/Validator/Datatypes/ArrayDatatype.php b/src/Wave/Validator/Datatypes/ArrayDatatype.php index c20fba6..ec1f3a8 100755 --- a/src/Wave/Validator/Datatypes/ArrayDatatype.php +++ b/src/Wave/Validator/Datatypes/ArrayDatatype.php @@ -2,10 +2,12 @@ namespace Wave\Validator\Datatypes; -class ArrayDatatype extends AbstractDatatype { +class ArrayDatatype extends AbstractDatatype +{ - public function __invoke() { + public function __invoke() + { return is_array($this->input); } @@ -14,7 +16,8 @@ public function __invoke() { /** * @return string a type to use in the violation message */ - public function getType() { + public function getType() + { return 'array'; } } diff --git a/src/Wave/Validator/Datatypes/BooleanDatatype.php b/src/Wave/Validator/Datatypes/BooleanDatatype.php index 79db2bb..c7cb2f2 100755 --- a/src/Wave/Validator/Datatypes/BooleanDatatype.php +++ b/src/Wave/Validator/Datatypes/BooleanDatatype.php @@ -4,17 +4,19 @@ use Wave\Validator\CleanerInterface; -class BooleanDatatype extends AbstractDatatype implements CleanerInterface { +class BooleanDatatype extends AbstractDatatype implements CleanerInterface +{ private $bool_true = array(true, 'true', '1', 1); private $bool_false = array(false, 'false', '0', 0); private $converted; - public function __invoke() { - if(in_array($this->input, $this->bool_true, true)) + public function __invoke() + { + if (in_array($this->input, $this->bool_true, true)) $this->converted = true; - else if(in_array($this->input, $this->bool_false, true)) + else if (in_array($this->input, $this->bool_false, true)) $this->converted = false; else return false; @@ -22,14 +24,16 @@ public function __invoke() { return true; } - public function getCleanedData() { + public function getCleanedData() + { return $this->converted; } /** * @return string a type to use in the violation message */ - public function getType() { + public function getType() + { return 'boolean'; } } diff --git a/src/Wave/Validator/Datatypes/DomainDatatype.php b/src/Wave/Validator/Datatypes/DomainDatatype.php index 582873e..45619e0 100644 --- a/src/Wave/Validator/Datatypes/DomainDatatype.php +++ b/src/Wave/Validator/Datatypes/DomainDatatype.php @@ -2,16 +2,19 @@ namespace Wave\Validator\Datatypes; -class DomainDatatype extends AbstractDatatype { +class DomainDatatype extends AbstractDatatype +{ - public function __invoke() { + public function __invoke() + { return preg_match('/^([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/i', $this->input) > 0; } /** * @return string a type to use in the violation message */ - public function getType() { + public function getType() + { return 'domain'; } } diff --git a/src/Wave/Validator/Datatypes/EmailDatatype.php b/src/Wave/Validator/Datatypes/EmailDatatype.php index 82b7cdd..6649922 100755 --- a/src/Wave/Validator/Datatypes/EmailDatatype.php +++ b/src/Wave/Validator/Datatypes/EmailDatatype.php @@ -2,23 +2,27 @@ namespace Wave\Validator\Datatypes; -class EmailDatatype extends AbstractDatatype { +class EmailDatatype extends AbstractDatatype +{ private $cleaned; - public function __invoke() { + public function __invoke() + { $this->cleaned = trim($this->input); return filter_var($this->cleaned, FILTER_VALIDATE_EMAIL); } - public function getCleanedData() { + public function getCleanedData() + { return $this->cleaned; } /** * @return string a type to use in the violation message */ - public function getType() { + public function getType() + { return 'email'; } } diff --git a/src/Wave/Validator/Datatypes/FloatDatatype.php b/src/Wave/Validator/Datatypes/FloatDatatype.php index f780849..0c5d9d3 100755 --- a/src/Wave/Validator/Datatypes/FloatDatatype.php +++ b/src/Wave/Validator/Datatypes/FloatDatatype.php @@ -4,23 +4,27 @@ use Wave\Validator\CleanerInterface; -class FloatDatatype extends AbstractDatatype implements CleanerInterface { +class FloatDatatype extends AbstractDatatype implements CleanerInterface +{ - public function __invoke() { + public function __invoke() + { - if(!is_scalar($this->input)) return false; + if (!is_scalar($this->input)) return false; return false !== filter_var($this->input, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND); } - public function getCleanedData() { + public function getCleanedData() + { return floatval(filter_var($this->input, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION)); } /** * @return string a type to use in the violation message */ - public function getType() { + public function getType() + { return 'decimal number'; } } diff --git a/src/Wave/Validator/Datatypes/IntDatatype.php b/src/Wave/Validator/Datatypes/IntDatatype.php index 164059f..57ed251 100755 --- a/src/Wave/Validator/Datatypes/IntDatatype.php +++ b/src/Wave/Validator/Datatypes/IntDatatype.php @@ -4,20 +4,24 @@ use Wave\Validator\CleanerInterface; -class IntDatatype extends AbstractDatatype implements CleanerInterface { +class IntDatatype extends AbstractDatatype implements CleanerInterface +{ - public function __invoke() { + public function __invoke() + { return (is_int($this->input) || (is_string($this->input) && strval(intval($this->input)) === $this->input)); } - public function getCleanedData() { + public function getCleanedData() + { return intval($this->input); } /** * @return string a type to use in the violation message */ - public function getType() { + public function getType() + { return 'integer'; } } diff --git a/src/Wave/Validator/Datatypes/StringDatatype.php b/src/Wave/Validator/Datatypes/StringDatatype.php index f8bf2ab..98d0479 100755 --- a/src/Wave/Validator/Datatypes/StringDatatype.php +++ b/src/Wave/Validator/Datatypes/StringDatatype.php @@ -3,16 +3,19 @@ namespace Wave\Validator\Datatypes; -class StringDatatype extends AbstractDatatype { +class StringDatatype extends AbstractDatatype +{ - public function __invoke() { + public function __invoke() + { return is_string($this->input); } /** * @return string a type to use in the violation message */ - public function getType() { + public function getType() + { return 'string'; } } diff --git a/src/Wave/Validator/Datatypes/UrlDatatype.php b/src/Wave/Validator/Datatypes/UrlDatatype.php index ba8e0cb..6ef3b0a 100755 --- a/src/Wave/Validator/Datatypes/UrlDatatype.php +++ b/src/Wave/Validator/Datatypes/UrlDatatype.php @@ -2,23 +2,27 @@ namespace Wave\Validator\Datatypes; -class UrlDatatype extends AbstractDatatype { +class UrlDatatype extends AbstractDatatype +{ private $cleaned; - public function __invoke() { + public function __invoke() + { $this->cleaned = trim($this->input); return filter_var($this->cleaned, FILTER_VALIDATE_URL); } - public function getCleanedData() { + public function getCleanedData() + { return $this->cleaned; } /** * @return string a type to use in the violation message */ - public function getType() { + public function getType() + { return 'url'; } } \ No newline at end of file diff --git a/src/Wave/Validator/Exception/InvalidConstraintException.php b/src/Wave/Validator/Exception/InvalidConstraintException.php index 6522521..43ffa47 100644 --- a/src/Wave/Validator/Exception/InvalidConstraintException.php +++ b/src/Wave/Validator/Exception/InvalidConstraintException.php @@ -3,7 +3,8 @@ namespace Wave\Validator\Exception; -class InvalidConstraintException extends ValidationException { +class InvalidConstraintException extends ValidationException +{ } ; \ No newline at end of file diff --git a/src/Wave/Validator/Exception/InvalidInputException.php b/src/Wave/Validator/Exception/InvalidInputException.php index 5f3f986..2cb71c2 100644 --- a/src/Wave/Validator/Exception/InvalidInputException.php +++ b/src/Wave/Validator/Exception/InvalidInputException.php @@ -2,17 +2,20 @@ namespace Wave\Validator\Exception; -class InvalidInputException extends ValidationException { +class InvalidInputException extends ValidationException +{ protected $violations; - public function __construct(array $violations) { + public function __construct(array $violations) + { $this->violations = $violations; parent::__construct('Input validation failed', 400); } - public function getViolations() { + public function getViolations() + { return $this->violations; } diff --git a/src/Wave/Validator/Exception/ValidationException.php b/src/Wave/Validator/Exception/ValidationException.php index 038adf0..61f16c1 100644 --- a/src/Wave/Validator/Exception/ValidationException.php +++ b/src/Wave/Validator/Exception/ValidationException.php @@ -4,5 +4,6 @@ use Wave\Exception; -class ValidationException extends Exception { +class ValidationException extends Exception +{ } diff --git a/src/Wave/Validator/Result.php b/src/Wave/Validator/Result.php index 99c38e7..dd7ccf5 100644 --- a/src/Wave/Validator/Result.php +++ b/src/Wave/Validator/Result.php @@ -7,26 +7,31 @@ use ArrayObject; use Wave\Validator; -class Result extends ArrayObject { +class Result extends ArrayObject +{ private $violations; private $validator; - public function __construct(array $cleaned, array $errors = array(), Validator $validator = null) { + public function __construct(array $cleaned, array $errors = array(), Validator $validator = null) + { parent::__construct($cleaned); $this->violations = $errors; $this->validator = $validator; } - public function isValid() { + public function isValid() + { return empty($this->violations); } - public function getViolations() { + public function getViolations() + { return $this->violations; } - public function getCleanedData() { + public function getCleanedData() + { return $this->getArrayCopy(); } diff --git a/src/Wave/View.php b/src/Wave/View.php index dfbe665..6e1d864 100644 --- a/src/Wave/View.php +++ b/src/Wave/View.php @@ -4,8 +4,12 @@ use RecursiveDirectoryIterator; use RecursiveIteratorIterator; +use Twig\Loader\FilesystemLoader; +use Twig\TwigFilter; +use Twig\TwigFunction; -class View { +class View +{ private $twig; @@ -17,30 +21,31 @@ class View { private static $instance = null; - private function __construct() { + private function __construct() + { - $loader = new \Twig_Loader_Filesystem(Config::get('wave')->path->views); + $loader = new FilesystemLoader(Config::get('wave')->path->views); $conf = array('cache' => Config::get('wave')->view->cache); - if(Core::$_MODE !== Core::MODE_PRODUCTION) { + if (Core::$_MODE !== Core::MODE_PRODUCTION) { $conf['auto_reload'] = true; $conf['debug'] = true; } $this->twig = new View\TwigEnvironment($loader, $conf); $this->twig->addExtension(new View\TwigExtension()); - foreach(self::$_filters as $name => $action) - $this->twig->addFilter($name, $action); + foreach (self::$_filters as $name => $action) + $this->twig->addFilter(new TwigFilter($name, $action)); $this->twig->registerUndefinedFilterCallback( function ($name) { - if(function_exists($name)) { - return new \Twig_Filter_Function($name); + if (function_exists($name)) { + return new TwigFunction($name); } return false; } ); - $this->twig->addFilter(new \Twig_SimpleFilter('last','\\Wave\\Utils::array_peek')); - $this->twig->addFilter(new \Twig_SimpleFilter('short', + $this->twig->addFilter(new TwigFilter('last', '\\Wave\\Utils::array_peek')); + $this->twig->addFilter(new TwigFilter('short', '\\Wave\\Utils::shorten', array( 'pre_escape' => 'html', 'is_safe' => array('html') @@ -53,35 +58,37 @@ function ($name) { $this->twig->addGlobal('_host', Config::get('deploy')->profiles->default->baseurl); $this->twig->addGlobal('_mode', Core::$_MODE); - if(self::$_timezone !== null) + if (self::$_timezone !== null) $this->twig->getExtension('core')->setTimezone(self::$_timezone); - if(self::$_date_format !== null) + if (self::$_date_format !== null) $this->twig->getExtension('core')->setDateFormat(self::$_date_format); - if(Config::get('deploy')->mode == Core::MODE_DEVELOPMENT || isset($_REQUEST['_wave_show_debugger'])) + if (Config::get('deploy')->mode == Core::MODE_DEVELOPMENT || isset($_REQUEST['_wave_show_debugger'])) $this->twig->addGlobal('_debugger', Debug::getInstance()); - foreach(self::$_globals as $key => $value) + foreach (self::$_globals as $key => $value) $this->twig->addGlobal($key, $value); } - public static function getInstance() { + public static function getInstance() + { - if(self::$instance === null) + if (self::$instance === null) self::$instance = new self(); return self::$instance; } - public function render($template, $data = array()) { + public function render($template, $data = array()) + { // locate the template file $template .= Config::get('wave')->view->extension; Hook::triggerAction('view.before_load_template', array(&$this, &$template)); - $loaded_template = $this->twig->loadTemplate($template); + $loaded_template = $this->twig->load($template); Hook::triggerAction('view.before_render', array(&$this, &$data)); $html = $loaded_template->render($data); Hook::triggerAction('view.after_render', array(&$this, &$html)); @@ -89,41 +96,46 @@ public function render($template, $data = array()) { } - public static function registerFilter($filter, $action) { - if(self::$instance == null) self::$_filters[$filter] = $action; + public static function registerFilter($filter, $action) + { + if (self::$instance == null) self::$_filters[$filter] = $action; else self::$instance->twig->addFilter($filter, $action); } - public static function registerGlobal($name, $value) { - if(self::$instance == null) self::$_globals[$name] = $value; + public static function registerGlobal($name, $value) + { + if (self::$instance == null) self::$_globals[$name] = $value; else self::$instance->twig->addGlobal($name, $value); } - public static function setTimezone($timezone) { - if(self::$instance == null) self::$_timezone = $timezone; + public static function setTimezone($timezone) + { + if (self::$instance == null) self::$_timezone = $timezone; else self::$instance->twig->getExtension('core')->setTimezone($timezone); } - public static function setDefaultDateFormat($format) { - if(self::$instance == null) self::$_date_format = $format; + public static function setDefaultDateFormat($format) + { + if (self::$instance == null) self::$_date_format = $format; else self::$instance->twig->getExtension('core')->setDateFormat($format); } - public static function generate() { + public static function generate() + { $cache_dir = Config::get('wave')->view->cache; - if(!file_exists($cache_dir)) + if (!file_exists($cache_dir)) @mkdir($cache_dir, 0770, true); - if(!file_exists($cache_dir)) + if (!file_exists($cache_dir)) throw new Exception('Could not generate views, the cache directory does not exist or is not writable'); // delete caches $dir_iterator = new RecursiveDirectoryIterator($cache_dir); $iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::CHILD_FIRST); - foreach($iterator as $file) { - if($file->getFilename() === '.' || $file->getFilename() === '..') { + foreach ($iterator as $file) { + if ($file->getFilename() === '.' || $file->getFilename() === '..') { continue; } $func = $file->isDir() ? 'rmdir' : 'unlink'; @@ -135,10 +147,10 @@ public static function generate() { $dir_iterator = new RecursiveDirectoryIterator($source_path); $iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::CHILD_FIRST); $l = strlen($source_path); - foreach($iterator as $template) { + foreach ($iterator as $template) { $filename = $template->getFilename(); - if(pathinfo($filename, PATHINFO_EXTENSION) != 'phtml') continue; - $self->twig->loadTemplate(substr($template, $l)); + if (pathinfo($filename, PATHINFO_EXTENSION) != 'phtml') continue; + $self->twig->load(substr($template, $l)); } } diff --git a/src/Wave/View/Tag/Img.php b/src/Wave/View/Tag/Img.php index 99968eb..1987403 100755 --- a/src/Wave/View/Tag/Img.php +++ b/src/Wave/View/Tag/Img.php @@ -2,72 +2,82 @@ namespace Wave\View\Tag; +use Twig\Compiler; +use Twig\Node\Node; +use Twig\Token; +use Twig\TokenParser\AbstractTokenParser; use Wave; -class Img extends \Twig_TokenParser { +class Img extends AbstractTokenParser +{ const TYPE_JS = 'js'; const TYPE_CSS = 'css'; - public function parse(\Twig_Token $token) { + public function parse(Token $token) + { $lineno = $token->getLine(); - $path = $this->parser->getStream()->expect(\Twig_Token::STRING_TYPE)->getValue(); + $path = $this->parser->getStream()->expect(Token::STRING_TYPE)->getValue(); - if(!preg_match('/http(s)?\:\/\//', $path)) + if (!preg_match('/http(s)?\:\/\//', $path)) $path = Wave\Config::get('deploy')->assets . $path; $attributes = array(); - if($this->parser->getStream()->test(\Twig_Token::STRING_TYPE)) { - $str = $this->parser->getStream()->expect(\Twig_Token::STRING_TYPE)->getValue(); + if ($this->parser->getStream()->test(Token::STRING_TYPE)) { + $str = $this->parser->getStream()->expect(Token::STRING_TYPE)->getValue(); $attributes['title'] = $str; $attributes['alt'] = $str; } - if(!$this->parser->getStream()->test(\Twig_Token::BLOCK_END_TYPE)) { + if (!$this->parser->getStream()->test(Token::BLOCK_END_TYPE)) { $array = $this->parser->getExpressionParser()->parseArrayExpression(); - foreach($array->getIterator() as $key => $node) { + foreach ($array->getIterator() as $key => $node) { $attributes[$key] = $node->getAttribute('value'); } } - $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); + $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); return new ImgNode($path, $attributes, $lineno, $this->getTag()); } - public function getTag() { + public function getTag() + { return 'img'; } } -class ImgNode extends \Twig_Node { +class ImgNode extends Node +{ - public function __construct($src, $attributes, $line, $tag = null) { + public function __construct($src, $attributes, $line, $tag = null) + { parent::__construct(array(), array('src' => $src, 'attributes' => $attributes), $line, $tag); } - public function compile(\Twig_Compiler $compiler) { + public function compile(Compiler $compiler) + { $src = $this->getAttribute('src'); $attributes = $this->getAttribute('attributes'); - if(!isset($attributes['width']) && !isset($attributes['height'])) { + if (!isset($attributes['width']) && !isset($attributes['height'])) { try { $img = getimagesize($src); $attributes['width'] = $img[0]; $attributes['height'] = $img[1]; - } catch(\Exception $e) { + } catch (\Exception $e) { } } $attributes['src'] = $src; $compiled = array(); - foreach($attributes as $key => $value) + foreach ($attributes as $key => $value) $compiled[] = $key . '="' . $value . '"'; $compiler diff --git a/src/Wave/View/Tag/Output.php b/src/Wave/View/Tag/Output.php index ef921e5..19cafe8 100755 --- a/src/Wave/View/Tag/Output.php +++ b/src/Wave/View/Tag/Output.php @@ -2,38 +2,49 @@ namespace Wave\View\Tag; -class Output extends \Twig_TokenParser { +use Twig\Compiler; +use Twig\Node\Node; +use Twig\Token; +use Twig\TokenParser\AbstractTokenParser; - public function parse(\Twig_Token $token) { +class Output extends AbstractTokenParser +{ + + public function parse(Token $token) + { $lineno = $token->getLine(); - $type = $this->parser->getStream()->expect(\Twig_Token::NAME_TYPE)->getValue(); + $type = $this->parser->getStream()->expect(Token::NAME_TYPE)->getValue(); - $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); + $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); return new OutputNode($type, $lineno, $this->getTag()); } - public function getTag() { + public function getTag() + { return 'output'; } } -class OutputNode extends \Twig_Node { +class OutputNode extends Node +{ const FORMAT_JS = ''; const FORMAT_CSS = ''; - public function __construct($type, $line, $tag = null) { + public function __construct($type, $line, $tag = null) + { parent::__construct(array(), array('type' => $type), $line, $tag); } - public function compile(\Twig_Compiler $compiler) { + public function compile(Compiler $compiler) + { $compiler ->addDebugInfo($this); diff --git a/src/Wave/View/Tag/Register.php b/src/Wave/View/Tag/Register.php index a5b0518..ba3d26f 100755 --- a/src/Wave/View/Tag/Register.php +++ b/src/Wave/View/Tag/Register.php @@ -2,73 +2,84 @@ namespace Wave\View\Tag; +use Twig\Compiler; +use Twig\Error\SyntaxError; +use Twig\Node\Node; +use Twig\Token; +use Twig\TokenParser\AbstractTokenParser; use Wave; -class Register extends \Twig_TokenParser { +class Register extends AbstractTokenParser +{ const TYPE_JS = 'js'; const TYPE_CSS = 'css'; - public function parse(\Twig_Token $token) { + public function parse(Token $token) + { $lineno = $token->getLine(); $extras = ''; - $type = $this->parser->getStream()->expect(\Twig_Token::NAME_TYPE)->getValue(); + $type = $this->parser->getStream()->expect(Token::NAME_TYPE)->getValue(); - if(!in_array($type, array(self::TYPE_JS, self::TYPE_CSS))) - throw new \Twig_SyntaxError("Register type must be 'css' or 'js'.", $lineno, $token->getFilename()); + if (!in_array($type, array(self::TYPE_JS, self::TYPE_CSS))) + throw new SyntaxError("Register type must be 'css' or 'js'.", $lineno, $token->getFilename()); - $file = $this->parser->getStream()->expect(\Twig_Token::STRING_TYPE)->getValue(); + $file = $this->parser->getStream()->expect(Token::STRING_TYPE)->getValue(); - if($type == self::TYPE_CSS) { - if($this->parser->getStream()->test(\Twig_Token::STRING_TYPE)) - $extras = $this->parser->getStream()->expect(\Twig_Token::STRING_TYPE)->getValue(); + if ($type == self::TYPE_CSS) { + if ($this->parser->getStream()->test(Token::STRING_TYPE)) + $extras = $this->parser->getStream()->expect(Token::STRING_TYPE)->getValue(); else $extras = 'all'; } - if($this->parser->getStream()->test(\Twig_Token::NUMBER_TYPE)) - $priority = $this->parser->getStream()->expect(\Twig_Token::NUMBER_TYPE)->getValue(); + if ($this->parser->getStream()->test(Token::NUMBER_TYPE)) + $priority = $this->parser->getStream()->expect(Token::NUMBER_TYPE)->getValue(); else $priority = 0; - $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); + $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); return new RegisterNode($type, $file, $extras, $priority, $lineno, $this->getTag()); } - public function getTag() { + public function getTag() + { return 'register'; } } -class RegisterNode extends \Twig_Node { +class RegisterNode extends Node +{ - public function __construct($type, $file, $extras, $priority, $line, $tag = null) { + public function __construct($type, $file, $extras, $priority, $line, $tag = null) + { parent::__construct( array(), array( - 'type' => $type, - 'file' => $file, - 'extras' => $extras, - 'priority' => $priority - ), $line, $tag + 'type' => $type, + 'file' => $file, + 'extras' => $extras, + 'priority' => $priority + ), $line, $tag ); } - public function compile(\Twig_Compiler $compiler) { + public function compile(Compiler $compiler) + { $type = $this->getAttribute('type'); $file = $this->getAttribute('file'); $extras = $this->getAttribute('extras'); $priority = $this->getAttribute('priority'); $cache_tag = null; - if(!preg_match('/http(s)?\:\/\//', $file)) { + if (!preg_match('/http(s)?\:\/\//', $file)) { $file = Wave\Config::get('deploy')->assets . $file; $cache_tag = @file_get_contents($file); - if($cache_tag !== false) $cache_tag = md5($cache_tag); + if ($cache_tag !== false) $cache_tag = md5($cache_tag); else $cache_tag = null; } diff --git a/src/Wave/View/TwigEnvironment.php b/src/Wave/View/TwigEnvironment.php index 5436ccc..9f9b834 100755 --- a/src/Wave/View/TwigEnvironment.php +++ b/src/Wave/View/TwigEnvironment.php @@ -2,13 +2,17 @@ namespace Wave\View; -class TwigEnvironment extends \Twig_Environment { +use Twig\Environment; + +class TwigEnvironment extends Environment +{ public $_wave_register = array('css' => array(), 'js' => array()); - public function _wave_register($type, $path, $extras = null, $priority = 0, $cache_key = null) { - if(is_string($cache_key)) { - if(strpos($path, '?') !== false) $path .= '&'; + public function _wave_register($type, $path, $extras = null, $priority = 0, $cache_key = null) + { + if (is_string($cache_key)) { + if (strpos($path, '?') !== false) $path .= '&'; else $path .= '?'; $path .= 'v=' . $cache_key; } diff --git a/src/Wave/View/TwigExtension.php b/src/Wave/View/TwigExtension.php index 955a302..9af2f81 100755 --- a/src/Wave/View/TwigExtension.php +++ b/src/Wave/View/TwigExtension.php @@ -2,10 +2,13 @@ namespace Wave\View; -class TwigExtension extends \Twig_Extension { +use Twig\Extension; +class TwigExtension extends Extension\AbstractExtension +{ - public function getTokenParsers() { + public function getTokenParsers() + { return array( new Tag\Register(), new Tag\Output(), @@ -13,7 +16,8 @@ public function getTokenParsers() { ); } - public function getName() { + public function getName() + { return 'wave_view'; }