From 3503fd02e3122e3863c593af9656f08f407d4c61 Mon Sep 17 00:00:00 2001 From: Sid Roberts Date: Sat, 13 Apr 2019 17:27:46 +0900 Subject: [PATCH] Tidied up codebase. --- Library/Phalcon/Avatar/Gravatar.php | 60 ++-- Library/Phalcon/Cache/Backend/Aerospike.php | 82 ++++-- Library/Phalcon/Cache/Backend/Database.php | 106 ++++++-- Library/Phalcon/Cache/Backend/Wincache.php | 5 +- Library/Phalcon/Cli/Console/Extended.php | 76 ++++-- .../Phalcon/Cli/Environment/Environment.php | 60 +++- Library/Phalcon/Config/Adapter/Xml.php | 17 +- Library/Phalcon/Config/Loader.php | 15 +- Library/Phalcon/Error/Application.php | 55 ++-- Library/Phalcon/Error/Handler.php | 110 +++++--- Library/Phalcon/Http/Client/Provider/Curl.php | 153 +++++++---- Library/Phalcon/Http/Uri.php | 26 +- Library/Phalcon/Legacy/Crypt.php | 127 ++++++++- Library/Phalcon/Logger/Adapter/Database.php | 18 +- .../Phalcon/Logger/Adapter/File/Multiple.php | 26 +- Library/Phalcon/Logger/Adapter/Firelogger.php | 33 ++- Library/Phalcon/Logger/Adapter/Udplogger.php | 26 +- .../Phalcon/Logger/Formatter/Firelogger.php | 35 ++- Library/Phalcon/Mailer/Manager.php | 47 +++- Library/Phalcon/Mailer/Message.php | 72 ++++- .../Phalcon/Mvc/Model/Behavior/Blameable.php | 26 +- .../Mvc/Model/Behavior/Blameable/Audit.php | 36 ++- .../Model/Behavior/Blameable/AuditDetail.php | 9 +- .../Phalcon/Mvc/Model/Behavior/NestedSet.php | 211 ++++++++++---- .../Mvc/Model/EagerLoading/EagerLoad.php | 10 +- .../Phalcon/Mvc/Model/EagerLoading/Loader.php | 104 +++++-- .../Mvc/Model/EagerLoading/QueryBuilder.php | 8 +- .../Phalcon/Mvc/Model/EagerLoadingTrait.php | 34 ++- .../Phalcon/Mvc/Model/MetaData/Wincache.php | 6 +- Library/Phalcon/Mvc/MongoCollection.php | 88 +++++- Library/Phalcon/Mvc/View/Engine/Mustache.php | 6 +- Library/Phalcon/Mvc/View/Engine/Twig.php | 257 +++++++++++++----- Library/Phalcon/Paginator/Pager.php | 34 ++- Library/Phalcon/Paginator/Pager/Layout.php | 15 +- Library/Phalcon/Paginator/Pager/Range.php | 5 +- Library/Phalcon/Session/Adapter/Aerospike.php | 45 ++- Library/Phalcon/Session/Adapter/Database.php | 5 +- .../Phalcon/Session/Adapter/HandlerSocket.php | 69 ++++- Library/Phalcon/Session/Adapter/Mongo.php | 34 ++- .../Test/Traits/FunctionalTestCase.php | 68 ++++- Library/Phalcon/Traits/ConfigurableTrait.php | 4 +- .../Phalcon/Traits/EventManagerAwareTrait.php | 6 +- .../Phalcon/Translate/Adapter/CsvMulti.php | 37 ++- .../Phalcon/Translate/Adapter/Database.php | 50 ++-- Library/Phalcon/Translate/Adapter/Mongo.php | 10 +- Library/Phalcon/Translate/Adapter/Redis.php | 5 +- .../Translate/Adapter/ResourceBundle.php | 12 +- Library/Phalcon/Utils/ArrayUtils.php | 19 +- Library/Phalcon/Utils/Slug.php | 23 +- .../Validator/AlphaCompleteValidator.php | 34 ++- .../Validator/AlphaNamesValidator.php | 32 ++- .../Validator/AlphaNumericValidator.php | 30 +- .../Validation/Validator/ArrayInclusionIn.php | 23 +- .../Validation/Validator/CardNumber.php | 30 +- .../Validation/Validator/ConfirmationOf.php | 6 +- .../Validation/Validator/Db/Uniqueness.php | 64 ++++- .../Phalcon/Validation/Validator/Decimal.php | 25 +- Library/Phalcon/Validation/Validator/Iban.php | 17 +- .../Validation/Validator/IpValidator.php | 4 +- .../Phalcon/Validation/Validator/MongoId.php | 10 +- .../Validation/Validator/NumericValidator.php | 38 ++- .../Validation/Validator/PasswordStrength.php | 7 +- .../Validation/Validator/ReCaptcha.php | 56 ++-- 63 files changed, 2127 insertions(+), 634 deletions(-) diff --git a/Library/Phalcon/Avatar/Gravatar.php b/Library/Phalcon/Avatar/Gravatar.php index 938d7c00b..703635338 100644 --- a/Library/Phalcon/Avatar/Gravatar.php +++ b/Library/Phalcon/Avatar/Gravatar.php @@ -104,7 +104,7 @@ class Gravatar implements Avatarable 'monsterid' => true, 'wavatar' => true, 'retro' => true, - 'blank' => true + 'blank' => true, ]; /** @@ -115,7 +115,7 @@ class Gravatar implements Avatarable self::RATING_G => true, self::RATING_PG => true, self::RATING_R => true, - self::RATING_X => true + self::RATING_X => true, ]; /** @@ -149,19 +149,27 @@ public function __construct($config) } if (!is_array($config)) { - throw new InvalidArgumentException('Config must be either an array or \Phalcon\Config instance'); + throw new InvalidArgumentException( + 'Config must be either an array or \Phalcon\Config instance' + ); } if (isset($config['default_image'])) { - $this->setDefaultImage($config['default_image']); + $this->setDefaultImage( + $config['default_image'] + ); } if (isset($config['rating'])) { - $this->setRating($config['rating']); + $this->setRating( + $config['rating'] + ); } if (isset($config['size'])) { - $this->setSize($config['size']); + $this->setSize( + $config['size'] + ); } if (isset($config['use_https']) && $config['use_https']) { @@ -232,16 +240,18 @@ public function setSize($size) $options = [ 'options' => [ 'min_range' => static::MIN_AVATAR_SIZE, - 'max_range' => static::MAX_AVATAR_SIZE + 'max_range' => static::MAX_AVATAR_SIZE, ] ]; if (false === filter_var($size, FILTER_VALIDATE_INT, $options)) { - throw new InvalidArgumentException(sprintf( - "Can't set Gravatar size. Size must be an integer within %s and %s pixels", - static::MIN_AVATAR_SIZE, - static::MAX_AVATAR_SIZE - )); + throw new InvalidArgumentException( + sprintf( + "Can't set Gravatar size. Size must be an integer within %s and %s pixels", + static::MIN_AVATAR_SIZE, + static::MAX_AVATAR_SIZE + ) + ); } $this->size = (int) $size; @@ -271,14 +281,18 @@ public function setRating($rating) { $rating = strtolower(trim($rating)); - if (!isset($this->validRatings[$rating])) { $allowed = array_keys($this->validRatings); $last = array_pop($allowed); $allowed = join(',', $allowed); throw new InvalidArgumentException( - sprintf("Invalid rating '%s' specified. Available for use only: %s or %s", $rating, $allowed, $last) + sprintf( + "Invalid rating '%s' specified. Available for use only: %s or %s", + $rating, + $allowed, + $last + ) ); } @@ -407,18 +421,28 @@ protected function buildURL($email) $query = [ 's' => $this->getSize(), - 'r' => $this->getRating() + 'r' => $this->getRating(), ]; if ($this->defaultImage) { - $query = array_merge($query, ['d' => $this->defaultImage]); + $query = array_merge( + $query, + [ + 'd' => $this->defaultImage, + ] + ); } if ($this->forceDefault) { - $query = array_merge($query, ['f' => 'y']); + $query = array_merge( + $query, + [ + 'f' => 'y', + ] + ); } - $url .= '?'.http_build_query($query, '', '&'); + $url .= '?' . http_build_query($query, '', '&'); return $url; } diff --git a/Library/Phalcon/Cache/Backend/Aerospike.php b/Library/Phalcon/Cache/Backend/Aerospike.php index 9263d24c3..5734cbb2c 100644 --- a/Library/Phalcon/Cache/Backend/Aerospike.php +++ b/Library/Phalcon/Cache/Backend/Aerospike.php @@ -34,21 +34,31 @@ * use Phalcon\Cache\Backend\Aerospike as CacheBackend; * * // Cache data for 2 days - * $frontCache = new Data(['lifetime' => 172800]); + * $frontCache = new Data( + * [ + * 'lifetime' => 172800, + * ] + * ); * * // Create the Cache setting redis connection options - * $cache = new CacheBackend($frontCache, [ - * 'hosts' => [ - * ['addr' => '127.0.0.1', 'port' => 3000] - * ], - * 'persistent' => true, - * 'namespace' => 'test', - * 'prefix' => 'cache_', - * 'options' => [ - * \Aerospike::OPT_CONNECT_TIMEOUT => 1250, - * \Aerospike::OPT_WRITE_TIMEOUT => 1500 + * $cache = new CacheBackend( + * $frontCache, + * [ + * 'hosts' => [ + * [ + * 'addr' => '127.0.0.1', + * 'port' => 3000, + * ], + * ], + * 'persistent' => true, + * 'namespace' => 'test', + * 'prefix' => 'cache_', + * 'options' => [ + * \Aerospike::OPT_CONNECT_TIMEOUT => 1250, + * \Aerospike::OPT_WRITE_TIMEOUT => 1500, + * ] * ] - * ]); + * ); * * // Cache arbitrary data * $cache->save('my-data', [1, 2, 3, 4, 5]); @@ -97,6 +107,7 @@ public function __construct(FrontendInterface $frontend, array $options) if (isset($options['namespace'])) { $this->namespace = $options['namespace']; + unset($options['namespace']); } @@ -106,6 +117,7 @@ public function __construct(FrontendInterface $frontend, array $options) if (isset($options['set']) && !empty($options['set'])) { $this->set = $options['set']; + unset($options['set']); } @@ -119,11 +131,21 @@ public function __construct(FrontendInterface $frontend, array $options) $opts = $options['options']; } - $this->db = new \Aerospike(['hosts' => $options['hosts']], $persistent, $opts); + $this->db = new \Aerospike( + [ + 'hosts' => $options['hosts'], + ], + $persistent, + $opts + ); if (!$this->db->isConnected()) { throw new Exception( - sprintf('Aerospike failed to connect [%s]: %s', $this->db->errorno(), $this->db->error()) + sprintf( + 'Aerospike failed to connect [%s]: %s', + $this->db->errorno(), + $this->db->error() + ) ); } @@ -185,12 +207,17 @@ public function save($keyName = null, $content = null, $lifetime = null, $stopBu $aKey, $bins, $lifetime, - [\Aerospike::OPT_POLICY_KEY => \Aerospike::POLICY_KEY_SEND] + [ + \Aerospike::OPT_POLICY_KEY => \Aerospike::POLICY_KEY_SEND, + ] ); if (\Aerospike::OK != $status) { throw new Exception( - sprintf('Failed storing data in Aerospike: %s', $this->db->error()), + sprintf( + 'Failed storing data in Aerospike: %s', + $this->db->error() + ), $this->db->errorno() ); } @@ -225,13 +252,24 @@ public function queryKeys($prefix = null) $keys = []; $globalPrefix = $this->_prefix; - $this->db->scan($this->namespace, $this->set, function ($record) use (&$keys, $prefix, $globalPrefix) { - $key = $record['key']['key']; - - if (empty($prefix) || 0 === strpos($key, $prefix)) { - $keys[] = preg_replace(sprintf('#^%s(.+)#u', preg_quote($globalPrefix)), '$1', $key); + $this->db->scan( + $this->namespace, + $this->set, + function ($record) use (&$keys, $prefix, $globalPrefix) { + $key = $record['key']['key']; + + if (empty($prefix) || 0 === strpos($key, $prefix)) { + $keys[] = preg_replace( + sprintf( + '#^%s(.+)#u', + preg_quote($globalPrefix) + ), + '$1', + $key + ); + } } - }); + ); return $keys; } diff --git a/Library/Phalcon/Cache/Backend/Database.php b/Library/Phalcon/Cache/Backend/Database.php index f92e73262..800ff0bec 100644 --- a/Library/Phalcon/Cache/Backend/Database.php +++ b/Library/Phalcon/Cache/Backend/Database.php @@ -66,13 +66,21 @@ public function __construct(FrontendInterface $frontend, array $options) } if (!isset($options['table']) || empty($options['table']) || !is_string($options['table'])) { - throw new Exception("Parameter 'table' is required and it must be a non empty string"); + throw new Exception( + "Parameter 'table' is required and it must be a non empty string" + ); } - $this->db = $options['db']; - $this->table = $this->db->escapeIdentifier($options['table']); + $this->db = $options['db']; - unset($options['db'], $options['table']); + $this->table = $this->db->escapeIdentifier( + $options['table'] + ); + + unset( + $options['db'], + $options['table'] + ); parent::__construct($frontend, $options); } @@ -86,9 +94,17 @@ public function __construct(FrontendInterface $frontend, array $options) */ public function get($keyName, $lifetime = null) { - $prefixedKey = $this->getPrefixedIdentifier($keyName); - $sql = "SELECT data, lifetime FROM {$this->table} WHERE key_name = ?"; - $cache = $this->db->fetchOne($sql, Db::FETCH_ASSOC, [$prefixedKey]); + $prefixedKey = $this->getPrefixedIdentifier($keyName); + $sql = "SELECT data, lifetime FROM {$this->table} WHERE key_name = ?"; + + $cache = $this->db->fetchOne( + $sql, + Db::FETCH_ASSOC, + [ + $prefixedKey, + ] + ); + $this->_lastKey = $prefixedKey; if (!$cache) { @@ -100,12 +116,19 @@ public function get($keyName, $lifetime = null) // Remove the cache if expired if ($cache['lifetime'] < time()) { - $this->db->execute("DELETE FROM {$this->table} WHERE key_name = ?", [$prefixedKey]); + $this->db->execute( + "DELETE FROM {$this->table} WHERE key_name = ?", + [ + $prefixedKey, + ] + ); return null; } - return $frontend->afterRetrieve($cache['data']); + return $frontend->afterRetrieve( + $cache['data'] + ); } /** @@ -147,15 +170,25 @@ public function save($keyName = null, $content = null, $lifetime = null, $stopBu $lifetime = time() + $lifetime; // Check if the cache already exist - $sql = "SELECT data, lifetime FROM {$this->table} WHERE key_name = ?"; - $cache = $this->db->fetchOne($sql, Db::FETCH_ASSOC, [$prefixedKey]); + $sql = "SELECT data, lifetime FROM {$this->table} WHERE key_name = ?"; - if (!$cache) { - $status = $this->db->execute("INSERT INTO {$this->table} VALUES (?, ?, ?)", [ + $cache = $this->db->fetchOne( + $sql, + Db::FETCH_ASSOC, + [ $prefixedKey, - $frontend->beforeStore($cachedContent), - $lifetime - ]); + ] + ); + + if (!$cache) { + $status = $this->db->execute( + "INSERT INTO {$this->table} VALUES (?, ?, ?)", + [ + $prefixedKey, + $frontend->beforeStore($cachedContent), + $lifetime, + ] + ); } else { $status = $this->db->execute( "UPDATE {$this->table} SET data = ?, lifetime = ? WHERE key_name = ?", @@ -194,13 +227,25 @@ public function delete($keyName) { $prefixedKey = $this->getPrefixedIdentifier($keyName); $sql = "SELECT COUNT(*) AS rowcount FROM {$this->table} WHERE key_name = ?"; - $row = $this->db->fetchOne($sql, Db::FETCH_ASSOC, [$prefixedKey]); + + $row = $this->db->fetchOne( + $sql, + Db::FETCH_ASSOC, + [ + $prefixedKey, + ] + ); if (!$row['rowcount']) { return false; } - return $this->db->execute("DELETE FROM {$this->table} WHERE key_name = ?", [$prefixedKey]); + return $this->db->execute( + "DELETE FROM {$this->table} WHERE key_name = ?", + [ + $prefixedKey, + ] + ); } /** @@ -219,9 +264,16 @@ public function queryKeys($prefix = null) if (!empty($prefix)) { $sql = "SELECT key_name FROM {$this->table} WHERE key_name LIKE ? ORDER BY lifetime"; - $rs = $this->db->query($sql, [$prefix . '%']); + + $rs = $this->db->query( + $sql, + [ + $prefix . '%', + ] + ); } else { $sql = "SELECT key_name FROM {$this->table} ORDER BY lifetime"; + $rs = $this->db->query($sql); } @@ -247,7 +299,14 @@ public function exists($keyName = null, $lifetime = null) { $prefixedKey = $this->getPrefixedIdentifier($keyName); $sql = "SELECT lifetime FROM {$this->table} WHERE key_name = ?"; - $cache = $this->db->fetchOne($sql, Db::FETCH_ASSOC, [$prefixedKey]); + + $cache = $this->db->fetchOne( + $sql, + Db::FETCH_ASSOC, + [ + $prefixedKey, + ] + ); if (!$cache) { return false; @@ -255,7 +314,12 @@ public function exists($keyName = null, $lifetime = null) // Remove the cache if expired if ($cache['lifetime'] < time()) { - $this->db->execute("DELETE FROM {$this->table} WHERE key_name = ?", [$prefixedKey]); + $this->db->execute( + "DELETE FROM {$this->table} WHERE key_name = ?", + [ + $prefixedKey, + ] + ); return false; } diff --git a/Library/Phalcon/Cache/Backend/Wincache.php b/Library/Phalcon/Cache/Backend/Wincache.php index 085694cc4..df12279bd 100644 --- a/Library/Phalcon/Cache/Backend/Wincache.php +++ b/Library/Phalcon/Cache/Backend/Wincache.php @@ -47,6 +47,7 @@ public function get($keyName, $lifetime = null) { $prefixedKey = $this->getPrefixedIdentifier($keyName); $cachedContent = wincache_ucache_get($prefixedKey, $success); + $this->_lastKey = $prefixedKey; if ($success === false) { @@ -131,7 +132,9 @@ public function save($keyName = null, $content = null, $lifetime = null, $stopBu */ public function delete($keyName) { - return wincache_ucache_delete($this->getPrefixedIdentifier($keyName)); + return wincache_ucache_delete( + $this->getPrefixedIdentifier($keyName) + ); } /** diff --git a/Library/Phalcon/Cli/Console/Extended.php b/Library/Phalcon/Cli/Console/Extended.php index 6a84fa0e5..216718eff 100644 --- a/Library/Phalcon/Cli/Console/Extended.php +++ b/Library/Phalcon/Cli/Console/Extended.php @@ -48,11 +48,13 @@ public function handle(array $arguments = null) $this->setTasksDir(); $this->createHelp(); $this->showHelp(); + return; } elseif (isset($arguments['action']) && in_array($arguments['action'], ['-h', '--help', 'help'])) { $this->setTasksDir(); $this->createHelp(); $this->showTaskHelp($arguments['task']); + return; } @@ -75,7 +77,15 @@ private function setTasksDir() private function createHelp() { - $scannedTasksDir = array_diff(scandir($this->tasksDir), ['..', '.']); + $scannedTasksDir = array_diff( + scandir( + $this->tasksDir + ), + [ + '..', + '.', + ] + ); $config = $this->getDI()->get('config'); $dispatcher = $this->getDI()->getShared('dispatcher'); @@ -95,9 +105,19 @@ private function createHelp() foreach ($scannedTasksDir as $taskFile) { $taskFileInfo = pathinfo($taskFile); $taskClass = ($namespace ? $namespace . '\\' : '') . $taskFileInfo["filename"]; - $taskName = strtolower(str_replace('Task', '', $taskFileInfo["filename"])); - $this->documentation[$taskName] = ['description' => [''], 'actions' => []]; + $taskName = strtolower( + str_replace( + 'Task', + '', + $taskFileInfo["filename"] + ) + ); + + $this->documentation[$taskName] = [ + 'description' => [''], + 'actions' => [], + ]; $reflector = $reader->get($taskClass); @@ -126,7 +146,13 @@ private function createHelp() continue; } - $actionName = strtolower(str_replace('Action', '', $action)); + $actionName = strtolower( + str_replace( + 'Action', + '', + $action + ) + ); $this->documentation[$taskName]['actions'][$actionName] = []; @@ -134,11 +160,14 @@ private function createHelp() foreach ($actionAnnotations as $actAnnotation) { $_anotation = $actAnnotation->getName(); + if ($_anotation == 'description') { $getDesc = $actAnnotation->getArguments(); + $this->documentation[$taskName]['actions'][$actionName]['description'] = $getDesc; } elseif ($_anotation == 'param') { $getParams = $actAnnotation->getArguments(); + $this->documentation[$taskName]['actions'][$actionName]['params'][] = $getParams; } } @@ -149,7 +178,9 @@ private function createHelp() private function showHelp() { $config = $this->getDI()->get('config'); + $helpOutput = PHP_EOL; + if (isset($config['appName'])) { $helpOutput .= $config['appName'] . ' '; } @@ -165,15 +196,16 @@ private function showHelp() echo PHP_EOL; echo PHP_EOL . 'To show task help type:' . PHP_EOL; echo PHP_EOL; - echo ' command -h | --help | help'. PHP_EOL; + echo ' command -h | --help | help' . PHP_EOL; echo PHP_EOL; - echo 'Available tasks '.PHP_EOL; + echo 'Available tasks ' . PHP_EOL; + foreach ($this->documentation as $task => $doc) { echo PHP_EOL; - echo ' '. $task . PHP_EOL ; + echo ' ' . $task . PHP_EOL ; foreach ($doc['description'] as $line) { - echo ' '.$line . PHP_EOL; + echo ' ' . $line . PHP_EOL; } } } @@ -181,7 +213,9 @@ private function showHelp() private function showTaskHelp($taskTogetHelp) { $config = $this->getDI()->get('config'); + $helpOutput = PHP_EOL; + if (isset($config['appName'])) { $helpOutput .= $config['appName'] . ' '; } @@ -195,50 +229,58 @@ private function showTaskHelp($taskTogetHelp) echo PHP_EOL; echo "\t" , 'command [ [ [ ... ] ] ]', PHP_EOL; echo PHP_EOL; + foreach ($this->documentation as $task => $doc) { if ($taskTogetHelp != $task) { continue; } - echo PHP_EOL; - echo "Task: " . $task . PHP_EOL . PHP_EOL ; + echo PHP_EOL; + echo "Task: " . $task . PHP_EOL . PHP_EOL; foreach ($doc['description'] as $line) { echo ' '.$line . PHP_EOL; } - echo PHP_EOL; - echo 'Available actions:'.PHP_EOL.PHP_EOL; + + echo PHP_EOL; + echo 'Available actions:' . PHP_EOL . PHP_EOL; foreach ($doc['actions'] as $actionName => $aDoc) { - echo ' '.$actionName . PHP_EOL; + echo ' ' . $actionName . PHP_EOL; + if (isset($aDoc['description'])) { echo ' '.implode(PHP_EOL, $aDoc['description']) . PHP_EOL; } + echo PHP_EOL; + if (isset($aDoc['params']) && is_array($aDoc['params'])) { - echo ' Parameters:'.PHP_EOL; + echo ' Parameters:' . PHP_EOL; + foreach ($aDoc['params'] as $param) { if (is_array($param)) { $_to_print = ''; + if (isset($param[0]['name'])) { $_to_print = $param[0]['name']; } if (isset($param[0]['type'])) { - $_to_print .= ' ( '.$param[0]['type'].' )'; + $_to_print .= ' ( ' . $param[0]['type'] . ' )'; } if (isset($param[0]['description'])) { - $_to_print .= ' '.$param[0]['description'].PHP_EOL; + $_to_print .= ' ' . $param[0]['description'] . PHP_EOL; } if (!empty($_to_print)) { - echo ' '.$_to_print; + echo ' ' . $_to_print; } } } } } + break; } } diff --git a/Library/Phalcon/Cli/Environment/Environment.php b/Library/Phalcon/Cli/Environment/Environment.php index bc7e095bf..51e0c26f8 100644 --- a/Library/Phalcon/Cli/Environment/Environment.php +++ b/Library/Phalcon/Cli/Environment/Environment.php @@ -39,7 +39,13 @@ class Environment implements EnvironmentInterface */ public function isWindows() { - return 'WIN' === strtoupper(substr(PHP_OS, 0, 3)); + return 'WIN' === strtoupper( + substr( + PHP_OS, + 0, + 3 + ) + ); } /** @@ -108,18 +114,31 @@ public function getDimensions() if ($this->isAnsicon() && preg_match('#(?:\d+x\d+)\s+\((\d+)x(\d+)\)#', trim(getenv('ANSICON')), $match)) { // ANSICON maintains an environment variable which holds the current screen size // e.g. ANSICON=200x9999 (200x100) - return [(int) $match[1], (int) $match[2]]; + return [ + (int) $match[1], + (int) $match[2], + ]; } if (1 === preg_match('/^(\d+)x(\d+)$/', $this->getModeCon(), $match)) { - return [(int) $match[1], (int) $match[2]]; + return + [ + (int) $match[1], + (int) $match[2], + ]; } } elseif (1 === preg_match('/^(\d+)x(\d+)$/', $this->getSttySize(), $match)) { - return [(int) $match[1], (int) $match[2]]; + return [ + (int) $match[1], + (int) $match[2], + ]; } // fallback mode - return [EnvironmentInterface::WIDTH, EnvironmentInterface::HEIGHT]; + return [ + EnvironmentInterface::WIDTH, + EnvironmentInterface::HEIGHT, + ]; } /** @@ -132,7 +151,10 @@ public function getDimensions() public function setDimensions($width, $height) { if ((is_int($width) || ctype_digit($width)) && (is_int($height) || ctype_digit($height))) { - $this->dimensions = [$width, $height]; + $this->dimensions = [ + $width, + $height, + ]; } return $this; @@ -153,7 +175,7 @@ public function getModeCon() $descriptorspec = [ 1 => ['pipe', 'w'], // stdout - 2 => ['pipe', 'w'] // stderr + 2 => ['pipe', 'w'], // stderr ]; $process = proc_open( @@ -162,11 +184,16 @@ public function getModeCon() $pipes, null, null, - ['suppress_errors' => true] // suppressing any error output + [ + // suppressing any error output + 'suppress_errors' => true, + ] ); if (is_resource($process)) { - $info = stream_get_contents($pipes[1]); + $info = stream_get_contents( + $pipes[1] + ); fclose($pipes[1]); fclose($pipes[2]); @@ -174,7 +201,7 @@ public function getModeCon() proc_close($process); if (1 === preg_match('/--------+\r?\n.+?(\d+)\r?\n.+?(\d+)\r?\n/', $info, $match)) { - return $match[2].'x'.$match[1]; + return $match[2] . 'x' . $match[1]; } } @@ -194,7 +221,7 @@ public function getSttySize() $descriptorspec = [ 1 => ['pipe', 'w'], // stdout - 2 => ['pipe', 'w'] // stderr + 2 => ['pipe', 'w'], // stderr ]; $process = proc_open( @@ -203,11 +230,16 @@ public function getSttySize() $pipes, null, null, - ['suppress_errors' => true] // suppressing any error output + [ + // suppressing any error output + 'suppress_errors' => true, + ] ); if (is_resource($process)) { - $info = stream_get_contents($pipes[1]); + $info = stream_get_contents( + $pipes[1] + ); fclose($pipes[1]); fclose($pipes[2]); @@ -215,7 +247,7 @@ public function getSttySize() proc_close($process); if (1 === preg_match('#(\d+) (\d+)#', $info, $match)) { - return $match[2].'x'.$match[1]; + return $match[2] . 'x' . $match[1]; } } diff --git a/Library/Phalcon/Config/Adapter/Xml.php b/Library/Phalcon/Config/Adapter/Xml.php index e44e9c717..43425ee5c 100644 --- a/Library/Phalcon/Config/Adapter/Xml.php +++ b/Library/Phalcon/Config/Adapter/Xml.php @@ -72,7 +72,12 @@ public function __construct($filePath) } libxml_use_internal_errors(true); - $data = simplexml_load_file($filePath, 'SimpleXMLElement', LIBXML_NOCDATA); + + $data = simplexml_load_file( + $filePath, + 'SimpleXMLElement', + LIBXML_NOCDATA + ); foreach (libxml_get_errors() as $error) { /** @var \LibXMLError $error */ @@ -80,6 +85,7 @@ public function __construct($filePath) case LIBXML_ERR_WARNING: trigger_error($error->message, E_USER_WARNING); break; + default: throw new Exception($error->message); } @@ -87,6 +93,13 @@ public function __construct($filePath) libxml_use_internal_errors(false); - parent::__construct(json_decode(json_encode((array) $data), true)); + parent::__construct( + json_decode( + json_encode( + (array) $data + ), + true + ) + ); } } diff --git a/Library/Phalcon/Config/Loader.php b/Library/Phalcon/Config/Loader.php index 85fd27488..1d69e5035 100644 --- a/Library/Phalcon/Config/Loader.php +++ b/Library/Phalcon/Config/Loader.php @@ -46,22 +46,33 @@ public static function load($filePath) throw new Exception('Config file not found'); } - $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION)); + $extension = strtolower( + pathinfo( + $filePath, + PATHINFO_EXTENSION + ) + ); switch ($extension) { case 'ini': return new Ini($filePath); + case 'json': return new Json($filePath); + case 'php': case 'php5': case 'inc': return new Php($filePath); + case 'yml': case 'yaml': return new Yaml($filePath); + default: - throw new Exception('Config adapter for .' . $extension . ' files is not support'); + throw new Exception( + 'Config adapter for .' . $extension . ' files is not support' + ); } } } diff --git a/Library/Phalcon/Error/Application.php b/Library/Phalcon/Error/Application.php index 51a1870da..0bfe07b2b 100644 --- a/Library/Phalcon/Error/Application.php +++ b/Library/Phalcon/Error/Application.php @@ -72,7 +72,13 @@ public function main() private function registerAutoloaders() { $loader = new Loader(); - $loader->registerNamespaces(['Phalcon\Error' => '.']); + + $loader->registerNamespaces( + [ + 'Phalcon\Error' => '.', + ] + ); + $loader->register(); } @@ -85,27 +91,42 @@ private function registerServices() { $di = new FactoryDefault(); - $di->set('config', function () { - ob_start(); - $config = include APPLICATION_ENV . '.php'; - ob_end_clean(); + $di->set( + 'config', + function () { + ob_start(); + + $config = include APPLICATION_ENV . '.php'; + + ob_end_clean(); + + return new Config($config); + } + ); + + $di->set( + 'dispatcher', + function () { + $dispatcher = new Dispatcher(); - return new Config($config); - }); + $dispatcher->setDefaultNamespace('Application\Controllers\\'); - $di->set('dispatcher', function () { - $dispatcher = new Dispatcher(); - $dispatcher->setDefaultNamespace('Application\Controllers\\'); + return $dispatcher; + } + ); - return $dispatcher; - }); + $di->set( + 'view', + function () { + $view = new View(); - $di->set('view', function () { - $view = new View(); - $view->setViewsDir(ROOT_PATH . '/application/views/'); + $view->setViewsDir( + ROOT_PATH . '/application/views/' + ); - return $view; - }); + return $view; + } + ); $this->setDI($di); } diff --git a/Library/Phalcon/Error/Handler.php b/Library/Phalcon/Error/Handler.php index 782f2ff73..6bd10bad6 100644 --- a/Library/Phalcon/Error/Handler.php +++ b/Library/Phalcon/Error/Handler.php @@ -46,6 +46,7 @@ public static function register() ini_set('display_errors', 0); error_reporting(0); break; + case Application::ENV_TEST: case Application::ENV_DEVELOPMENT: ini_set('display_errors', 1); @@ -53,41 +54,53 @@ public static function register() break; } - set_error_handler(function ($errno, $errstr, $errfile, $errline) { - if (!($errno & error_reporting())) { - return; + set_error_handler( + function ($errno, $errstr, $errfile, $errline) { + if (!($errno & error_reporting())) { + return; + } + + $options = [ + 'type' => $errno, + 'message' => $errstr, + 'file' => $errfile, + 'line' => $errline, + 'isError' => true, + ]; + + static::handle( + new Error($options) + ); + } + ); + + set_exception_handler( + function ($e) { + /** @var \Exception|\Error $e */ + $options = [ + 'type' => $e->getCode(), + 'message' => $e->getMessage(), + 'file' => $e->getFile(), + 'line' => $e->getLine(), + 'isException' => true, + 'exception' => $e, + ]; + + static::handle( + new Error($options) + ); } + ); - $options = [ - 'type' => $errno, - 'message' => $errstr, - 'file' => $errfile, - 'line' => $errline, - 'isError' => true, - ]; - - static::handle(new Error($options)); - }); - - set_exception_handler(function ($e) { - /** @var \Exception|\Error $e */ - $options = [ - 'type' => $e->getCode(), - 'message' => $e->getMessage(), - 'file' => $e->getFile(), - 'line' => $e->getLine(), - 'isException' => true, - 'exception' => $e, - ]; - - static::handle(new Error($options)); - }); - - register_shutdown_function(function () { - if (!is_null($options = error_get_last())) { - static::handle(new Error($options)); + register_shutdown_function( + function () { + if (!is_null($options = error_get_last())) { + static::handle( + new Error($options) + ); + } } - }); + ); } /** @@ -99,11 +112,15 @@ public static function handle(Error $error) { $di = Di::getDefault(); - $type = static::getErrorType($error->type()); + $type = static::getErrorType( + $error->type() + ); + $message = "$type: {$error->message()} in {$error->file()} on line {$error->line()}"; if (!$di instanceof DiInterface) { echo $message; + return; } @@ -143,7 +160,12 @@ public static function handle(Error $error) } } - $logger->log(static::getLogType($error->type()), $message); + $logger->log( + static::getLogType( + $error->type() + ), + $message + ); switch ($error->type()) { case E_WARNING: @@ -157,6 +179,7 @@ public static function handle(Error $error) case E_USER_DEPRECATED: case E_ALL: break; + case 0: case E_ERROR: case E_PARSE: @@ -179,6 +202,7 @@ public static function handle(Error $error) $view->finish(); $response->setContent($view->getContent())->send(); + return; } else { echo $message; @@ -197,34 +221,49 @@ public static function getErrorType($code) switch ($code) { case 0: return 'Uncaught exception'; + case E_ERROR: return 'E_ERROR'; + case E_WARNING: return 'E_WARNING'; + case E_PARSE: return 'E_PARSE'; + case E_NOTICE: return 'E_NOTICE'; + case E_CORE_ERROR: return 'E_CORE_ERROR'; + case E_CORE_WARNING: return 'E_CORE_WARNING'; + case E_COMPILE_ERROR: return 'E_COMPILE_ERROR'; + case E_COMPILE_WARNING: return 'E_COMPILE_WARNING'; + case E_USER_ERROR: return 'E_USER_ERROR'; + case E_USER_WARNING: return 'E_USER_WARNING'; + case E_USER_NOTICE: return 'E_USER_NOTICE'; + case E_STRICT: return 'E_STRICT'; + case E_RECOVERABLE_ERROR: return 'E_RECOVERABLE_ERROR'; + case E_DEPRECATED: return 'E_DEPRECATED'; + case E_USER_DEPRECATED: return 'E_USER_DEPRECATED'; } @@ -248,14 +287,17 @@ public static function getLogType($code) case E_USER_ERROR: case E_PARSE: return Logger::ERROR; + case E_WARNING: case E_USER_WARNING: case E_CORE_WARNING: case E_COMPILE_WARNING: return Logger::WARNING; + case E_NOTICE: case E_USER_NOTICE: return Logger::NOTICE; + case E_STRICT: case E_DEPRECATED: case E_USER_DEPRECATED: diff --git a/Library/Phalcon/Http/Client/Provider/Curl.php b/Library/Phalcon/Http/Client/Provider/Curl.php index 69182cb0c..f3f1ea75e 100644 --- a/Library/Phalcon/Http/Client/Provider/Curl.php +++ b/Library/Phalcon/Http/Client/Provider/Curl.php @@ -43,7 +43,10 @@ public function __construct() $this->handle = curl_init(); if (!is_resource($this->handle)) { - throw new HttpException(curl_error($this->handle), 'curl'); + throw new HttpException( + curl_error($this->handle), + 'curl' + ); } $this->initOptions(); @@ -72,18 +75,20 @@ public function headerFunction($ch, $headerLine) private function initOptions() { - $this->setOptions([ - CURLOPT_RETURNTRANSFER => true, - CURLOPT_AUTOREFERER => true, - CURLOPT_FOLLOWLOCATION => true, - CURLOPT_MAXREDIRS => 20, - CURLOPT_HEADER => false, - CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, - CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, - CURLOPT_USERAGENT => 'Phalcon HTTP/' . self::VERSION . ' (Curl)', - CURLOPT_CONNECTTIMEOUT => 30, - CURLOPT_TIMEOUT => 30, - ]); + $this->setOptions( + [ + CURLOPT_RETURNTRANSFER => true, + CURLOPT_AUTOREFERER => true, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_MAXREDIRS => 20, + CURLOPT_HEADER => false, + CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, + CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, + CURLOPT_USERAGENT => 'Phalcon HTTP/' . self::VERSION . ' (Curl)', + CURLOPT_CONNECTTIMEOUT => 30, + CURLOPT_TIMEOUT => 30, + ] + ); } /** @@ -97,8 +102,11 @@ private function initOptions() public function setOption($option, $value) { if ($this->isCurlOptString($option)) { - $option = constant(strtoupper($option)); + $option = constant( + strtoupper($option) + ); } + return curl_setopt($this->handle, $option, $value); } @@ -114,6 +122,7 @@ public function setOptions($options) foreach ($options as $option => $value) { if ($this->isCurlOptString($option)) { $options[constant(strtoupper($option))] = $value; + unset($options[$option]); } } @@ -171,11 +180,14 @@ protected function send(array $customHeader = [], $fullResponse = false) $header = $customHeader; } else { $header = []; + if (count($this->header) > 0) { $header = $this->header->build(); } } + $header[] = 'Expect:'; + $header = array_unique($header, SORT_STRING); $this->responseHeader = ''; @@ -190,10 +202,14 @@ protected function send(array $customHeader = [], $fullResponse = false) $content = curl_exec($this->handle); if ($errno = curl_errno($this->handle)) { - throw new HttpException(curl_error($this->handle), $errno); + throw new HttpException( + curl_error($this->handle), + $errno + ); } $response = new Response(); + $response->header->parse($this->responseHeader); $response->body = $content; @@ -238,6 +254,7 @@ protected function canUseEncoding(array $params) $classCurlFile = class_exists('\CURLFile') ? '\CURLFile' : null; + foreach ($params as $value) { if ((is_string($value) && strpos($value, '@') === 0) || ($classCurlFile && $value instanceof $classCurlFile) @@ -245,6 +262,7 @@ protected function canUseEncoding(array $params) return false; } } + return true; } @@ -257,8 +275,17 @@ protected function canUseEncoding(array $params) */ public function setAuth($user, $pass, $auth = 'basic') { - $this->setOption(CURLOPT_HTTPAUTH, constant('CURLAUTH_'.strtoupper($auth))); - $this->setOption(CURLOPT_USERPWD, $user.":".$pass); + $this->setOption( + CURLOPT_HTTPAUTH, + constant( + 'CURLAUTH_' . strtoupper($auth) + ) + ); + + $this->setOption( + CURLOPT_USERPWD, + $user . ":" . $pass + ); } /** @@ -275,6 +302,7 @@ public function setCookies(array $cookies) } $cookieList = []; + foreach ($cookies as $cookieName => $cookieValue) { $cookie = urlencode($cookieName); @@ -286,21 +314,28 @@ public function setCookies(array $cookies) $cookieList[] = $cookie; } - $this->setOption(CURLOPT_COOKIE, implode(';', $cookieList)); + $this->setOption( + CURLOPT_COOKIE, + implode(';', $cookieList) + ); } public function setProxy($host, $port = 8080, $user = null, $pass = null) { - $this->setOptions([ - CURLOPT_PROXY => $host, - CURLOPT_PROXYPORT => $port - ]); + $this->setOptions( + [ + CURLOPT_PROXY => $host, + CURLOPT_PROXYPORT => $port, + ] + ); if (!empty($user) && is_string($user)) { $pair = $user; + if (!empty($pass) && is_string($pass)) { $pair .= ':' . $pass; } + $this->setOption(CURLOPT_PROXYUSERPWD, $pair); } } @@ -313,11 +348,13 @@ public function get($uri, $params = [], $customHeader = [], $fullResponse = fals $uri->extendQuery($params); } - $this->setOptions([ - CURLOPT_URL => $uri->build(), - CURLOPT_HTTPGET => true, - CURLOPT_CUSTOMREQUEST => Method::GET, - ]); + $this->setOptions( + [ + CURLOPT_URL => $uri->build(), + CURLOPT_HTTPGET => true, + CURLOPT_CUSTOMREQUEST => Method::GET, + ] + ); return $this->send($customHeader, $fullResponse); } @@ -330,12 +367,14 @@ public function head($uri, $params = [], $customHeader = [], $fullResponse = fal $uri->extendQuery($params); } - $this->setOptions([ - CURLOPT_URL => $uri->build(), - CURLOPT_HTTPGET => true, - CURLOPT_CUSTOMREQUEST => Method::HEAD, - CURLOPT_NOBODY => true, - ]); + $this->setOptions( + [ + CURLOPT_URL => $uri->build(), + CURLOPT_HTTPGET => true, + CURLOPT_CUSTOMREQUEST => Method::HEAD, + CURLOPT_NOBODY => true, + ] + ); return $this->send($customHeader, $fullResponse); } @@ -348,22 +387,26 @@ public function delete($uri, $params = [], $customHeader = [], $fullResponse = f $uri->extendQuery($params); } - $this->setOptions([ - CURLOPT_URL => $uri->build(), - CURLOPT_HTTPGET => true, - CURLOPT_CUSTOMREQUEST => Method::DELETE, - ]); + $this->setOptions( + [ + CURLOPT_URL => $uri->build(), + CURLOPT_HTTPGET => true, + CURLOPT_CUSTOMREQUEST => Method::DELETE, + ] + ); return $this->send($customHeader, $fullResponse); } public function post($uri, $params = [], $useEncoding = true, $customHeader = [], $fullResponse = false) { - $this->setOptions([ - CURLOPT_URL => $this->resolveUri($uri), - CURLOPT_POST => true, - CURLOPT_CUSTOMREQUEST => Method::POST, - ]); + $this->setOptions( + [ + CURLOPT_URL => $this->resolveUri($uri), + CURLOPT_POST => true, + CURLOPT_CUSTOMREQUEST => Method::POST, + ] + ); $this->initPostFields($params, $useEncoding); @@ -372,11 +415,13 @@ public function post($uri, $params = [], $useEncoding = true, $customHeader = [] public function put($uri, $params = [], $useEncoding = true, $customHeader = [], $fullResponse = false) { - $this->setOptions([ - CURLOPT_URL => $this->resolveUri($uri), - CURLOPT_POST => true, - CURLOPT_CUSTOMREQUEST => Method::PUT, - ]); + $this->setOptions( + [ + CURLOPT_URL => $this->resolveUri($uri), + CURLOPT_POST => true, + CURLOPT_CUSTOMREQUEST => Method::PUT, + ] + ); $this->initPostFields($params, $useEncoding); @@ -385,11 +430,13 @@ public function put($uri, $params = [], $useEncoding = true, $customHeader = [], public function patch($uri, $params = [], $useEncoding = true, $customHeader = [], $fullResponse = false) { - $this->setOptions([ - CURLOPT_URL => $this->resolveUri($uri), - CURLOPT_POST => true, - CURLOPT_CUSTOMREQUEST => Method::PATCH, - ]); + $this->setOptions( + [ + CURLOPT_URL => $this->resolveUri($uri), + CURLOPT_POST => true, + CURLOPT_CUSTOMREQUEST => Method::PATCH, + ] + ); $this->initPostFields($params, $useEncoding); diff --git a/Library/Phalcon/Http/Uri.php b/Library/Phalcon/Http/Uri.php index dcbe99c36..95f40d8c7 100644 --- a/Library/Phalcon/Http/Uri.php +++ b/Library/Phalcon/Http/Uri.php @@ -31,9 +31,12 @@ public function __construct($uri = null) if (is_string($uri)) { $this->parts = parse_url($uri); + if (!empty($this->parts['query'])) { $query = []; + parse_str($this->parts['query'], $query); + $this->parts['query'] = $query; } @@ -85,8 +88,10 @@ public function build() if (!empty($parts['scheme'])) { $uri .= $parts['scheme'] . ':'; + if (!empty($parts['host'])) { $uri .= '//'; + if (!empty($parts['user'])) { $uri .= $parts['user']; @@ -96,6 +101,7 @@ public function build() $uri .= '@'; } + $uri .= $parts['host']; } } @@ -127,6 +133,7 @@ public function buildQuery($query) public function resolve($uri) { $newUri = new self($this); + $newUri->extend($uri); return $newUri; @@ -140,15 +147,27 @@ public function extend($uri) $this->parts = array_merge( $this->parts, - array_diff_key($uri->parts, array_flip(['query', 'path'])) + array_diff_key( + $uri->parts, + array_flip( + [ + 'query', + 'path', + ] + ) + ) ); if (!empty($uri->parts['query'])) { - $this->extendQuery($uri->parts['query']); + $this->extendQuery( + $uri->parts['query'] + ); } if (!empty($uri->parts['path'])) { - $this->extendPath($uri->parts['path']); + $this->extendPath( + $uri->parts['path'] + ); } return $this; @@ -158,6 +177,7 @@ public function extendQuery($params) { $query = empty($this->parts['query']) ? [] : $this->parts['query']; $params = empty($params) ? [] : $params; + $this->parts['query'] = array_merge($query, $params); return $this; diff --git a/Library/Phalcon/Legacy/Crypt.php b/Library/Phalcon/Legacy/Crypt.php index 282896028..4dd465779 100644 --- a/Library/Phalcon/Legacy/Crypt.php +++ b/Library/Phalcon/Legacy/Crypt.php @@ -167,6 +167,7 @@ protected function cryptPadText($text, $mode, $blockSize, $paddingType) if ($mode == MCRYPT_MODE_CBC || $mode == MCRYPT_MODE_ECB) { $paddingSize = $blockSize - (strlen($text) % $blockSize); + if ($paddingSize >= 256) { throw new Exception("Block size is bigger than 256"); } @@ -174,28 +175,51 @@ protected function cryptPadText($text, $mode, $blockSize, $paddingType) switch ($paddingType) { case self::PADDING_ANSI_X_923: $padding = str_repeat(chr(0), $paddingSize - 1) . chr($paddingSize); + break; + case self::PADDING_PKCS7: - $padding = str_repeat(chr($paddingSize), $paddingSize); + $padding = str_repeat( + chr($paddingSize), + $paddingSize + ); + break; + case self::PADDING_ISO_10126: $padding = ""; + foreach (range(0, $paddingSize - 2) as $i) { - $padding .= chr(rand()); + $padding .= chr( + rand() + ); } + $padding .= chr($paddingSize); + break; + case self::PADDING_ISO_IEC_7816_4: $padding = chr(0x80) . str_repeat(chr(0), $paddingSize - 1); + break; + case self::PADDING_ZERO: - $padding = str_repeat(chr(0), $paddingSize); + $padding = str_repeat( + chr(0), + $paddingSize + ); + break; + case self::PADDING_SPACE: $padding = str_repeat(" ", $paddingSize); + break; + default: $paddingSize = 0; + break; } } @@ -231,55 +255,80 @@ protected function cryptUnpadText($text, $mode, $blockSize, $paddingType) case self::PADDING_ANSI_X_923: $last = substr($text, $length - 1, 1); $ord = (int) ord($last); + if ($ord <= $blockSize) { $paddingSize = $ord; + $padding = str_repeat(chr(0), $paddingSize - 1) . $last; + if (substr($text, $length - $paddingSize) != $padding) { $paddingSize = 0; } } + break; + case self::PADDING_PKCS7: $last = substr($text, $length - 1, 1); $ord = (int) ord($last); + if ($ord <= $blockSize) { $paddingSize = $ord; - $padding = str_repeat(chr($paddingSize), $paddingSize); + + $padding = str_repeat( + chr($paddingSize), + $paddingSize + ); + if (substr($text, $length - $paddingSize) != $padding) { $paddingSize = 0; } } + break; + case self::PADDING_ISO_10126: $last = substr($text, $length - 1, 1); $paddingSize = (int) ord($last); + break; + case self::PADDING_ISO_IEC_7816_4: $i = $length - 1; + while ($i > 0 && $text[$i] == 0x00 && $paddingSize < $blockSize) { $paddingSize++; $i--; } + if ($text[$i] == 0x80) { $paddingSize++; } else { $paddingSize = 0; } + break; + case self::PADDING_ZERO: $i = $length - 1; + while ($i >= 0 && $text[$i] == 0x00 && $paddingSize <= $blockSize) { $paddingSize++; $i--; } + break; + case self::PADDING_SPACE: $i = $length - 1; + while ($i >= 0 && $text[$i] == 0x20 && $paddingSize <= $blockSize) { $paddingSize++; $i--; } + break; + default: break; } @@ -288,6 +337,7 @@ protected function cryptUnpadText($text, $mode, $blockSize, $paddingType) if ($paddingSize < $length) { return substr($text, 0, $length - $paddingSize); } + return ""; } } @@ -328,16 +378,32 @@ public function encrypt($text, $key = null) throw new Exception("Size of key is too large for this algorithm"); } - $iv = strval(mcrypt_create_iv($ivSize, MCRYPT_RAND)); - $blockSize = intval(mcrypt_get_block_size($this->cipher, $this->mode)); + $iv = strval( + mcrypt_create_iv($ivSize, MCRYPT_RAND) + ); + + $blockSize = intval( + mcrypt_get_block_size($this->cipher, $this->mode) + ); if ($this->padding != 0 && ($this->mode == MCRYPT_MODE_CBC || $this->mode == MCRYPT_MODE_ECB)) { - $padded = $this->cryptPadText($text, $this->mode, $blockSize, $this->padding); + $padded = $this->cryptPadText( + $text, + $this->mode, + $blockSize, + $this->padding + ); } else { $padded = $text; } - return $iv . mcrypt_encrypt($this->cipher, $encryptKey, $padded, $this->mode, $iv); + return $iv . mcrypt_encrypt( + $this->cipher, + $encryptKey, + $padded, + $this->mode, + $iv + ); } /** @@ -381,11 +447,24 @@ public function decrypt($text, $key = null) } $data = substr($text, $ivSize); - $decrypted = mcrypt_decrypt($this->cipher, $decryptKey, $data, $this->mode, substr($text, 0, $ivSize)); + + $decrypted = mcrypt_decrypt( + $this->cipher, + $decryptKey, + $data, + $this->mode, + substr($text, 0, $ivSize) + ); + $blockSize = mcrypt_get_block_size($this->cipher, $this->mode); if ($this->mode == MCRYPT_MODE_CBC || $this->mode == MCRYPT_MODE_ECB) { - return $this->cryptUnpadText($decrypted, $this->mode, $blockSize, $this->padding); + return $this->cryptUnpadText( + $decrypted, + $this->mode, + $blockSize, + $this->padding + ); } return $decrypted; @@ -402,10 +481,18 @@ public function decrypt($text, $key = null) public function encryptBase64($text, $key = null, $safe = false) { if ($safe) { - return strtr(base64_encode($this->encrypt($text, $key)), "+/", "-_"); + return strtr( + base64_encode( + $this->encrypt($text, $key) + ), + "+/", + "-_" + ); } - return base64_encode($this->encrypt($text, $key)); + return base64_encode( + $this->encrypt($text, $key) + ); } /** @@ -419,10 +506,22 @@ public function encryptBase64($text, $key = null, $safe = false) public function decryptBase64($text, $key = null, $safe = false) { if ($safe) { - return $this->decrypt(base64_decode(strtr($text, "-_", "+/")), $key); + return $this->decrypt( + base64_decode( + strtr( + $text, + "-_", + "+/" + ) + ), + $key + ); } - return $this->decrypt(base64_decode($text), $key); + return $this->decrypt( + base64_decode($text), + $key + ); } /** diff --git a/Library/Phalcon/Logger/Adapter/Database.php b/Library/Phalcon/Logger/Adapter/Database.php index 0bdc58215..1b946d367 100644 --- a/Library/Phalcon/Logger/Adapter/Database.php +++ b/Library/Phalcon/Logger/Adapter/Database.php @@ -66,7 +66,9 @@ public function __construct($name = 'phalcon', array $options = []) } if (!$options['db'] instanceof DbAdapterInterface) { - throw new Exception("Parameter 'db' must be object and implement AdapterInterface"); + throw new Exception( + "Parameter 'db' must be object and implement AdapterInterface" + ); } if (!isset($options['table'])) { @@ -122,8 +124,18 @@ public function logInternal($message, $type, $time, $context = []) { return $this->db->execute( 'INSERT INTO ' . $this->options['table'] . ' VALUES (null, ?, ?, ?, ?)', - [$this->name, $type, $this->getFormatter()->format($message, $type, $time, $context), $time], - [Column::BIND_PARAM_STR, Column::BIND_PARAM_INT, Column::BIND_PARAM_STR, Column::BIND_PARAM_INT] + [ + $this->name, + $type, + $this->getFormatter()->format($message, $type, $time, $context), + $time, + ], + [ + Column::BIND_PARAM_STR, + Column::BIND_PARAM_INT, + Column::BIND_PARAM_STR, + Column::BIND_PARAM_INT, + ] ); } diff --git a/Library/Phalcon/Logger/Adapter/File/Multiple.php b/Library/Phalcon/Logger/Adapter/File/Multiple.php index e64433831..dd33b3888 100644 --- a/Library/Phalcon/Logger/Adapter/File/Multiple.php +++ b/Library/Phalcon/Logger/Adapter/File/Multiple.php @@ -60,18 +60,22 @@ public function __construct($path, array $options = []) { $path = rtrim($path, ' ' . \DIRECTORY_SEPARATOR); if (!file_exists($path) || !is_dir($path)) { - throw new LoggerException('Directory ' . $path . ' does not exist!'); + throw new LoggerException( + 'Directory ' . $path . ' does not exist!' + ); } if (!is_writable($path)) { - throw new LoggerException('Directory ' . $path . ' is not writable!'); + throw new LoggerException( + 'Directory ' . $path . ' is not writable!' + ); } $this->path = $path; $defaults = [ 'extension' => 'log', - 'prefix' => '' + 'prefix' => '', ]; $this->options = array_merge($defaults, $options); @@ -112,7 +116,9 @@ public function logInternal($message, $type, $time, array $context = []) */ public function begin() { - throw new LoggerException('Multiple file logger transactions are not implemented yet!'); + throw new LoggerException( + 'Multiple file logger transactions are not implemented yet!' + ); } /** @@ -122,7 +128,9 @@ public function begin() */ public function commit() { - throw new LoggerException('Multiple file logger transactions are not implemented yet!'); + throw new LoggerException( + 'Multiple file logger transactions are not implemented yet!' + ); } /** @@ -132,7 +140,9 @@ public function commit() */ public function rollback() { - throw new LoggerException('Multiple file logger transactions are not implemented yet!'); + throw new LoggerException( + 'Multiple file logger transactions are not implemented yet!' + ); } /** @@ -153,17 +163,21 @@ protected function getTypeString($type) case Logger::CRITICAL: // emergence, critical return 'critical'; + case Logger::ALERT: case Logger::ERROR: // error, alert return 'error'; + case Logger::WARNING: // warning return 'warning'; + case Logger::NOTICE: case Logger::INFO: // info, notice return 'info'; + case Logger::DEBUG: case Logger::CUSTOM: case Logger::SPECIAL: diff --git a/Library/Phalcon/Logger/Adapter/Firelogger.php b/Library/Phalcon/Logger/Adapter/Firelogger.php index 297357210..61bd42c84 100644 --- a/Library/Phalcon/Logger/Adapter/Firelogger.php +++ b/Library/Phalcon/Logger/Adapter/Firelogger.php @@ -102,7 +102,7 @@ public function __construct($name = 'phalcon', array $options = []) 'password' => null, 'checkVersion' => true, 'traceable' => false, - 'triggerError' => true + 'triggerError' => true, ]; if ($name) { @@ -112,7 +112,12 @@ public function __construct($name = 'phalcon', array $options = []) $this->options = array_merge($defaults, $options); $this->enabled = $this->checkPassword() && $this->checkVersion(); - register_shutdown_function([$this, 'commit']); + register_shutdown_function( + [ + $this, + 'commit', + ] + ); } /** @@ -156,11 +161,22 @@ public function logInternal($message, $type, $time, $context = []) if (!$this->enabled) { return; } + $trace = null; + if ($this->options['traceable']) { $trace = debug_backtrace(); } - $log = $this->getFormatter()->format($message, $type, $time, $context, $trace, count($this->logs)); + + $log = $this->getFormatter()->format( + $message, + $type, + $time, + $context, + $trace, + count($this->logs) + ); + $this->logs[] = $log; // flush if this is not transaction @@ -186,6 +202,7 @@ public function begin() { // flush the previous transaction if there is any $this->commit(); + // start a new transaction $this->isTransaction = true; } @@ -252,7 +269,11 @@ protected function checkPassword() if (isset($_SERVER['HTTP_X_FIRELOGGERAUTH'])) { $clientHash = $_SERVER['HTTP_X_FIRELOGGERAUTH']; - $serverHash = md5("#FireLoggerPassword#" . $this->options['password'] . "#"); + + $serverHash = md5( + "#FireLoggerPassword#" . $this->options['password'] . "#" + ); + if ($clientHash !== $serverHash) { // passwords do not match $this->enabled = false; @@ -281,11 +302,13 @@ private function checkVersion() { if (!$this->options['checkVersion']) { $this->enabled = true; + return true; } if (!isset($_SERVER['HTTP_X_FIRELOGGER'])) { $this->enabled = false; + return false; } @@ -300,10 +323,12 @@ private function checkVersion() ); $this->enabled = false; + return false; } $this->enabled = true; + return true; } } diff --git a/Library/Phalcon/Logger/Adapter/Udplogger.php b/Library/Phalcon/Logger/Adapter/Udplogger.php index cdda9dd16..7a1bccecb 100644 --- a/Library/Phalcon/Logger/Adapter/Udplogger.php +++ b/Library/Phalcon/Logger/Adapter/Udplogger.php @@ -86,8 +86,19 @@ public function __construct($name = 'phalcon', array $options = []) $this->options = $options; - register_shutdown_function([$this, 'commit']); - register_shutdown_function([$this, 'close']); + register_shutdown_function( + [ + $this, + 'commit', + ] + ); + + register_shutdown_function( + [ + $this, + 'close', + ] + ); } /** @@ -141,6 +152,7 @@ public function close() public function begin() { $this->commit(); + $this->isTransaction = true; } @@ -156,6 +168,7 @@ public function commit() } $this->send(); + $this->isTransaction = false; } @@ -174,7 +187,14 @@ protected function send() $this->socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); } - socket_sendto($this->socket, $message, strlen($message), 0, $this->options['url'], $this->options['port']); + socket_sendto( + $this->socket, + $message, + strlen($message), + 0, + $this->options['url'], + $this->options['port'] + ); $this->logs = []; } diff --git a/Library/Phalcon/Logger/Formatter/Firelogger.php b/Library/Phalcon/Logger/Formatter/Firelogger.php index 243b48729..c4eca3f8f 100644 --- a/Library/Phalcon/Logger/Formatter/Firelogger.php +++ b/Library/Phalcon/Logger/Formatter/Firelogger.php @@ -109,17 +109,21 @@ public function getTypeString($type) case Logger::CRITICAL: // emergence, critical return 'critical'; + case Logger::ALERT: case Logger::ERROR: // error, alert return 'error'; + case Logger::WARNING: // warning return 'warning'; + case Logger::NOTICE: case Logger::INFO: // info, notice return 'info'; + case Logger::DEBUG: case Logger::CUSTOM: case Logger::SPECIAL: @@ -160,7 +164,7 @@ public function format($message, $type, $timestamp, $context = [], $trace = null 'order' => $order, // PHP is really fast, timestamp has insufficient resolution for log records ordering 'time' => gmdate('H:i:s', (int) $timestamp) . '.000', 'template' => $message, - 'message' => $message + 'message' => $message, ]; if ($this->style) { @@ -169,12 +173,16 @@ public function format($message, $type, $timestamp, $context = [], $trace = null if (isset($exception)) { // exception with backtrace - $traceInfo = $this->extractTrace($exception->getTrace()); + $traceInfo = $this->extractTrace( + $exception->getTrace() + ); + $item['exc_info'] = [ $exception->getMessage(), $exception->getFile(), $traceInfo[0] ]; + $item['exc_frames'] = $traceInfo[1]; $item['exc_text'] = get_class($exception); $item['template'] = $exception->getMessage(); @@ -191,11 +199,13 @@ public function format($message, $type, $timestamp, $context = [], $trace = null if (isset($trace)) { $traceInfo = $this->extractTrace($trace); + $item['exc_info'] = [ '', '', $traceInfo[0] ]; + $item['exc_frames'] = $traceInfo[1]; } @@ -222,7 +232,11 @@ protected function pickle($var, $level = 0) if (is_string($var)) { // intentionally @ - return @iconv('UTF-16', 'UTF-8//IGNORE', iconv($this->encoding, 'UTF-16//IGNORE', $var)); + return @iconv( + 'UTF-16', + 'UTF-8//IGNORE', + iconv($this->encoding, 'UTF-16//IGNORE', $var) + ); } if (is_array($var)) { @@ -268,7 +282,10 @@ protected function pickle($var, $level = 0) foreach ($arr as $k => &$v) { if ($k[0] === "\x00") { - $k = substr($k, strrpos($k, "\x00") + 1); + $k = substr( + $k, + strrpos($k, "\x00") + 1 + ); } $res[$this->pickle($k)] = $this->pickle($v, $level + 1); @@ -299,6 +316,7 @@ protected function extractTrace($trace) { $t = []; $f = []; + foreach ($trace as $frame) { // prevent notices about invalid indices, wasn't able to google smart solution, PHP is dumb ass $frame += [ @@ -308,14 +326,14 @@ protected function extractTrace($trace) 'type' => null, 'function' => null, 'object' => null, - 'args' => null + 'args' => null, ]; $t[] = [ $frame['file'], $frame['line'], $frame['class'] . $frame['type'] . $frame['function'], - $frame['object'] + $frame['object'], ]; $f[] = $frame['args']; @@ -352,6 +370,9 @@ protected function extractFileLine($trace) $file = $trace[0]['file']; $line = $trace[0]['line']; - return [$file, $line]; + return [ + $file, + $line, + ]; } } diff --git a/Library/Phalcon/Mailer/Manager.php b/Library/Phalcon/Mailer/Manager.php index 8b023708d..fd8d55c06 100644 --- a/Library/Phalcon/Mailer/Manager.php +++ b/Library/Phalcon/Mailer/Manager.php @@ -92,10 +92,18 @@ public function createMessage() } /** @var $message Message */ - $message = $this->getDI()->get('\Phalcon\Mailer\Message', [$this]); + $message = $this->getDI()->get( + '\Phalcon\Mailer\Message', + [ + $this, + ] + ); if (($from = $this->getConfig('from'))) { - $message->from($from['email'], isset($from['name']) ? $from['name'] : null); + $message->from( + $from['email'], + isset($from['name']) ? $from['name'] : null + ); } if ($eventsManager) { @@ -124,7 +132,11 @@ public function createMessage() public function createMessageFromView($view, $params = [], $viewsDir = null) { $message = $this->createMessage(); - $message->content($this->renderView($view, $params, $viewsDir), $message::CONTENT_TYPE_HTML); + + $message->content( + $this->renderView($view, $params, $viewsDir), + $message::CONTENT_TYPE_HTML + ); return $message; } @@ -210,7 +222,12 @@ protected function registerSwiftTransport() break; default: - throw new \InvalidArgumentException(sprintf('Driver-mail "%s" is not supported', $driver)); + throw new \InvalidArgumentException( + sprintf( + 'Driver-mail "%s" is not supported', + $driver + ) + ); } } @@ -231,12 +248,21 @@ protected function registerTransportSmtp() ->setPort($config['port']); if (isset($config['encryption'])) { - $transport->setEncryption($config['encryption']); + $transport->setEncryption( + $config['encryption'] + ); } if (isset($config['username'])) { - $transport->setUsername($this->normalizeEmail($config['username'])); - $transport->setPassword($config['password']); + $transport->setUsername( + $this->normalizeEmail( + $config['username'] + ) + ); + + $transport->setPassword( + $config['password'] + ); } return $transport; @@ -314,7 +340,12 @@ protected function registerTransportSendmail() */ protected function registerSwiftMailer() { - $this->mailer = $this->getDI()->get('\Swift_Mailer', [$this->transport]); + $this->mailer = $this->getDI()->get( + '\Swift_Mailer', + [ + $this->transport, + ] + ); } /** diff --git a/Library/Phalcon/Mailer/Message.php b/Library/Phalcon/Mailer/Message.php index f50c7e69e..f8a377df3 100644 --- a/Library/Phalcon/Mailer/Message.php +++ b/Library/Phalcon/Mailer/Message.php @@ -82,6 +82,7 @@ public function __construct(Manager $manager) public function from($email, $name = null) { $email = $this->normalizeEmail($email); + $this->getMessage()->setFrom($email, $name); return $this; @@ -118,6 +119,7 @@ public function getFrom() public function replyTo($email, $name = null) { $email = $this->normalizeEmail($email); + $this->getMessage()->setReplyTo($email, $name); return $this; @@ -154,6 +156,7 @@ public function getReplyTo() public function to($email, $name = null) { $email = $this->normalizeEmail($email); + $this->getMessage()->setTo($email, $name); return $this; @@ -190,6 +193,7 @@ public function getTo() public function cc($email, $name = null) { $email = $this->normalizeEmail($email); + $this->getMessage()->setCc($email, $name); return $this; @@ -226,6 +230,7 @@ public function getCc() public function bcc($email, $name = null) { $email = $this->normalizeEmail($email); + $this->getMessage()->setBcc($email, $name); return $this; @@ -258,6 +263,7 @@ public function getBcc() public function sender($email, $name = null) { $email = $this->normalizeEmail($email); + $this->getMessage()->setSender($email, $name); return $this; @@ -435,6 +441,7 @@ public function getPriority() public function setReadReceiptTo($email) { $email = $this->normalizeEmail($email); + $this->getMessage()->setReadReceiptTo($email); return $this; @@ -536,6 +543,7 @@ public function getFormat() public function attachment($file, array $options = []) { $attachment = $this->createAttachmentViaPath($file); + return $this->prepareAttachment($attachment, $options); } @@ -554,6 +562,7 @@ public function attachment($file, array $options = []) public function attachmentData($data, $name, array $options = []) { $attachment = $this->createAttachmentViaData($data, $name); + return $this->prepareAttachment($attachment, $options); } @@ -567,6 +576,7 @@ public function attachmentData($data, $name, array $options = []) public function embed($file) { $embed = $this->createEmbedViaPath($file); + return $this->getMessage()->embed($embed); } @@ -582,6 +592,7 @@ public function embed($file) public function embedData($data, $name, $contentType = null) { $embed = $this->createEmbedViaData($data, $name, $contentType); + return $this->getMessage()->embed($embed); } @@ -644,10 +655,20 @@ public function send() $this->failedRecipients = []; - $count = $this->getManager()->getSwift()->send($this->getMessage(), $this->failedRecipients); + $count = $this->getManager()->getSwift()->send( + $this->getMessage(), + $this->failedRecipients + ); if ($eventManager) { - $eventManager->fire('mailer:afterSend', $this, [$count, $this->failedRecipients]); + $eventManager->fire( + 'mailer:afterSend', + $this, + [ + $count, + $this->failedRecipients, + ] + ); } return $count; @@ -676,7 +697,13 @@ protected function prepareAttachment(\Swift_Attachment $attachment, array $optio $eventManager = $this->getManager()->getEventsManager(); if ($eventManager) { - $result = $eventManager->fire('mailer:beforeAttachFile', $this, [$attachment]); + $result = $eventManager->fire( + 'mailer:beforeAttachFile', + $this, + [ + $attachment, + ] + ); } else { $result = true; } @@ -685,7 +712,13 @@ protected function prepareAttachment(\Swift_Attachment $attachment, array $optio $this->getMessage()->attach($attachment); if ($eventManager) { - $eventManager->fire('mailer:afterAttachFile', $this, [$attachment]); + $eventManager->fire( + 'mailer:afterAttachFile', + $this, + [ + $attachment, + ] + ); } } @@ -704,7 +737,12 @@ protected function prepareAttachment(\Swift_Attachment $attachment, array $optio protected function createAttachmentViaPath($file) { /** @var $byteStream \Swift_ByteStream_FileByteStream */ - $byteStream = $this->getManager()->getDI()->get('\Swift_ByteStream_FileByteStream', [$file]); + $byteStream = $this->getManager()->getDI()->get( + '\Swift_ByteStream_FileByteStream', + [ + $file, + ] + ); /** @var $image \Swift_Attachment */ $attachment = $this->getManager()->getDI()->get('\Swift_Attachment') @@ -725,7 +763,13 @@ protected function createAttachmentViaPath($file) */ protected function createAttachmentViaData($data, $name) { - return $this->getManager()->getDI()->get('\Swift_Attachment', [$data, $name]); + return $this->getManager()->getDI()->get( + '\Swift_Attachment', + [ + $data, + $name, + ] + ); } /** @@ -740,7 +784,12 @@ protected function createAttachmentViaData($data, $name) protected function createEmbedViaPath($file) { /** @var $byteStream \Swift_ByteStream_FileByteStream */ - $byteStream = $this->getManager()->getDI()->get('\Swift_ByteStream_FileByteStream', [$file]); + $byteStream = $this->getManager()->getDI()->get( + '\Swift_ByteStream_FileByteStream', + [ + $file, + ] + ); /** @var $image \Swift_Image */ $image = $this->getManager()->getDI()->get('\Swift_Image') @@ -761,7 +810,13 @@ protected function createEmbedViaPath($file) */ protected function createEmbedViaData($data, $name = null) { - return $this->getManager()->getDI()->get('\Swift_Image', [$data, $name]); + return $this->getManager()->getDI()->get( + '\Swift_Image', + [ + $data, + $name, + ] + ); } /** @@ -781,6 +836,7 @@ protected function normalizeEmail($email) $emails[$k] = $this->getManager()->normalizeEmail($v); } else { $k = $this->getManager()->normalizeEmail($k); + $emails[$k] = $v; } } diff --git a/Library/Phalcon/Mvc/Model/Behavior/Blameable.php b/Library/Phalcon/Mvc/Model/Behavior/Blameable.php index f5befc9fe..9843fa65c 100644 --- a/Library/Phalcon/Mvc/Model/Behavior/Blameable.php +++ b/Library/Phalcon/Mvc/Model/Behavior/Blameable.php @@ -54,12 +54,14 @@ class Blameable extends Behavior implements BehaviorInterface public function __construct($options = null) { parent::__construct($options); + if (isset($options['auditClass'])) { if (!in_array(AuditInterface::class, class_implements($options['auditClass']))) { throw new Exception( "Your class must implement Phalcon\\Mvc\\Model\\Behavior\\Blameable\\AuditInterface" ); } + $this->auditClass = $options['auditClass']; } @@ -69,6 +71,7 @@ public function __construct($options = null) "Your class must implement Phalcon\\Mvc\\Model\\Behavior\\Blameable\\AuditDetailInterface" ); } + $this->auditDetailClass = $options['auditDetailClass']; } @@ -76,6 +79,7 @@ public function __construct($options = null) if (!is_callable($options['userCallback'])) { throw new Exception("User callback must be callable!"); } + $this->userCallback = $options['userCallback']; } @@ -118,8 +122,10 @@ public function notify($eventType, ModelInterface $model) public function createAudit($type, ModelInterface $model) { $auditClass = $this->auditClass; + /** @var AuditInterface $audit */ $audit = new $auditClass(); + $audit->setUserCallback($this->userCallback); $audit->setModel($model); $audit->setType($type); @@ -137,6 +143,7 @@ public function auditAfterCreate(ModelInterface $model) { /** @var AuditInterface|ModelInterface $audit */ $audit = $this->createAudit('C', $model); + /** @var Model\MetaData $metaData */ $metaData = $model->getModelsMetaData(); $fields = $metaData->getAttributes($model); @@ -147,13 +154,21 @@ public function auditAfterCreate(ModelInterface $model) foreach ($fields as $field) { /** @var AuditDetailInterface $auditDetail */ $auditDetail = new $auditDetailClass(); + $auditDetail->setOldValue(null); + if (empty($columnMap)) { $auditDetail->setFieldName($field); - $auditDetail->setNewValue($model->readAttribute($field)); + + $auditDetail->setNewValue( + $model->readAttribute($field) + ); } else { $auditDetail->setFieldName($columnMap[$field]); - $auditDetail->setNewValue($model->readAttribute($columnMap[$field])); + + $auditDetail->setNewValue( + $model->readAttribute($columnMap[$field]) + ); } $details[] = $auditDetail; @@ -191,15 +206,20 @@ public function auditAfterUpdate(ModelInterface $model) } else { $originalData = $model->getOldSnapshotData(); } + $auditDetailClass = $this->auditDetailClass; $details = []; foreach ($changedFields as $field) { /** @var AuditDetailInterface $auditDetail */ $auditDetail = new $auditDetailClass(); + $auditDetail->setFieldName($field); $auditDetail->setOldValue($originalData[$field]); - $auditDetail->setNewValue($model->readAttribute($field)); + + $auditDetail->setNewValue( + $model->readAttribute($field) + ); $details[] = $auditDetail; } diff --git a/Library/Phalcon/Mvc/Model/Behavior/Blameable/Audit.php b/Library/Phalcon/Mvc/Model/Behavior/Blameable/Audit.php index a3a2fae47..b420f37d2 100644 --- a/Library/Phalcon/Mvc/Model/Behavior/Blameable/Audit.php +++ b/Library/Phalcon/Mvc/Model/Behavior/Blameable/Audit.php @@ -64,7 +64,14 @@ class Audit extends Model implements AuditInterface */ public function initialize() { - $this->hasMany('id', AuditDetail::class, 'audit_id', ['alias' => 'details']); + $this->hasMany( + 'id', + AuditDetail::class, + 'audit_id', + [ + 'alias' => 'details', + ] + ); } /** @@ -80,7 +87,10 @@ public function beforeValidation() $this->user_name = $session->get('userName'); } else { $userCallback = $this->userCallback; - $this->user_name = $userCallback($this->getDI()); + + $this->user_name = $userCallback( + $this->getDI() + ); } //The model who performed the action @@ -95,14 +105,20 @@ public function beforeValidation() //Current time $this->created_at = date('Y-m-d H:i:s'); - $primaryKeys = $this->getModelsMetaData()->getPrimaryKeyAttributes($this->model); + $primaryKeys = $this->getModelsMetaData()->getPrimaryKeyAttributes( + $this->model + ); - $columnMap = $this->getModelsMetaData()->getColumnMap($this->model); + $columnMap = $this->getModelsMetaData()->getColumnMap( + $this->model + ); $primaryValues = []; if (!empty($columnMap)) { foreach ($primaryKeys as $primaryKey) { - $primaryValues[] = $this->model->readAttribute($columnMap[$primaryKey]); + $primaryValues[] = $this->model->readAttribute( + $columnMap[$primaryKey] + ); } } else { foreach ($primaryKeys as $primaryKey) { @@ -115,12 +131,18 @@ public function beforeValidation() public function afterSave() { - $this->primary_key = json_decode($this->primary_key, true); + $this->primary_key = json_decode( + $this->primary_key, + true + ); } public function afterFetch() { - $this->primary_key = json_decode($this->primary_key, true); + $this->primary_key = json_decode( + $this->primary_key, + true + ); } /** diff --git a/Library/Phalcon/Mvc/Model/Behavior/Blameable/AuditDetail.php b/Library/Phalcon/Mvc/Model/Behavior/Blameable/AuditDetail.php index 3ba5649ab..e712ef2f6 100644 --- a/Library/Phalcon/Mvc/Model/Behavior/Blameable/AuditDetail.php +++ b/Library/Phalcon/Mvc/Model/Behavior/Blameable/AuditDetail.php @@ -35,7 +35,14 @@ class AuditDetail extends Model implements AuditDetailInterface */ public function initialize() { - $this->belongsTo('audit_id', Audit::class, 'id', ['alias' => 'audit']); + $this->belongsTo( + 'audit_id', + Audit::class, + 'id', + [ + 'alias' => 'audit', + ] + ); } /** diff --git a/Library/Phalcon/Mvc/Model/Behavior/NestedSet.php b/Library/Phalcon/Mvc/Model/Behavior/NestedSet.php index b1a709f56..651ad49d0 100644 --- a/Library/Phalcon/Mvc/Model/Behavior/NestedSet.php +++ b/Library/Phalcon/Mvc/Model/Behavior/NestedSet.php @@ -117,7 +117,13 @@ public function missingMethod(ModelInterface $model, $method, $arguments = null) $this->getDbHandler($model); $this->setOwner($model); - return call_user_func_array([$this, $method], $arguments); + return call_user_func_array( + [ + $this, + $method, + ], + $arguments + ); } /** @@ -126,7 +132,10 @@ public function missingMethod(ModelInterface $model, $method, $arguments = null) public function getOwner() { if (!$this->owner instanceof ModelInterface) { - trigger_error("Owner isn't a valid ModelInterface instance.", E_USER_WARNING); + trigger_error( + "Owner isn't a valid ModelInterface instance.", + E_USER_WARNING + ); } return $this->owner; @@ -194,6 +203,7 @@ public function isRoot() public function isDescendantOf($subj) { $owner = $this->getOwner(); + $result = ($owner->{$this->leftAttribute} > $subj->{$this->leftAttribute}) && ($owner->{$this->rightAttribute} < $subj->{$this->rightAttribute}); @@ -221,20 +231,24 @@ public function descendants($depth = null, $addSelf = false) ->orderBy($this->leftAttribute); if ($depth !== null) { - $query = $query->andWhere($this->levelAttribute . '<=' . ($owner->{$this->levelAttribute} + $depth)); + $query = $query->andWhere( + $this->levelAttribute . '<=' . ($owner->{$this->levelAttribute} + $depth) + ); } if ($this->hasManyRoots) { - $query = $query->andWhere($this->rootAttribute . '=' . $owner->{$this->rootAttribute}); + $query = $query->andWhere( + $this->rootAttribute . '=' . $owner->{$this->rootAttribute} + ); } $this->fire( self::EVT_TYPE_QUERY . ':before' . self::EVT_DESCENDANTS, $query, [ - 'owner' => $owner, - 'depth' => $depth, - 'addSelf' => $addSelf + 'owner' => $owner, + 'depth' => $depth, + 'addSelf' => $addSelf, ] ); @@ -267,11 +281,15 @@ public function ancestors($depth = null) ->orderBy($this->leftAttribute); if ($depth !== null) { - $query = $query->andWhere($this->levelAttribute . '>=' . ($owner->{$this->levelAttribute} - $depth)); + $query = $query->andWhere( + $this->levelAttribute . '>=' . ($owner->{$this->levelAttribute} - $depth) + ); } if ($this->hasManyRoots) { - $query = $query->andWhere($this->rootAttribute . '=' . $owner->{$this->rootAttribute}); + $query = $query->andWhere( + $this->rootAttribute . '=' . $owner->{$this->rootAttribute} + ); } $this->fire( @@ -279,7 +297,7 @@ public function ancestors($depth = null) $query, [ 'owner' => $owner, - 'depth' => $depth + 'depth' => $depth, ] ); @@ -303,11 +321,13 @@ public function roots() self::EVT_TYPE_QUERY . ':before' . self::EVT_ROOTS, $query, [ - 'owner' => $owner + 'owner' => $owner, ] ); - return $owner::find($query->getParams()); + return $owner::find( + $query->getParams() + ); } /** @@ -326,7 +346,9 @@ public function parent() ->limit(1); if ($this->hasManyRoots) { - $query = $query->andWhere($this->rootAttribute . '=' . $owner->{$this->rootAttribute}); + $query = $query->andWhere( + $this->rootAttribute . '=' . $owner->{$this->rootAttribute} + ); } $this->fire( @@ -352,14 +374,16 @@ public function prev() ->where($this->rightAttribute . '=' . ($owner->{$this->leftAttribute} - 1)); if ($this->hasManyRoots) { - $query = $query->andWhere($this->rootAttribute . '=' . $owner->{$this->rootAttribute}); + $query = $query->andWhere( + $this->rootAttribute . '=' . $owner->{$this->rootAttribute} + ); } $this->fire( self::EVT_TYPE_QUERY . ':before' . self::EVT_PREV, $query, [ - 'owner' => $owner + 'owner' => $owner, ] ); @@ -378,14 +402,16 @@ public function next() ->where($this->leftAttribute . '=' . ($owner->{$this->rightAttribute} + 1)); if ($this->hasManyRoots) { - $query = $query->andWhere($this->rootAttribute . '=' . $owner->{$this->rootAttribute}); + $query = $query->andWhere( + $this->rootAttribute . '=' . $owner->{$this->rootAttribute} + ); } $this->fire( self::EVT_TYPE_QUERY . ':before' . self::EVT_NEXT, $query, [ - 'owner' => $owner + 'owner' => $owner, ] ); @@ -402,9 +428,16 @@ public function next() public function prependTo(ModelInterface $target, array $attributes = null) { // Re-search $target - $target = $target::findFirst($target->{$this->primaryKey}); + $target = $target::findFirst( + $target->{$this->primaryKey} + ); - return $this->addNode($target, $target->{$this->leftAttribute} + 1, 1, $attributes); + return $this->addNode( + $target, + $target->{$this->leftAttribute} + 1, + 1, + $attributes + ); } /** @@ -416,7 +449,10 @@ public function prependTo(ModelInterface $target, array $attributes = null) */ public function prepend(ModelInterface $target, array $attributes = null) { - return $target->prependTo($this->getOwner(), $attributes); + return $target->prependTo( + $this->getOwner(), + $attributes + ); } /** @@ -429,9 +465,16 @@ public function prepend(ModelInterface $target, array $attributes = null) public function appendTo(ModelInterface $target, array $attributes = null) { // Re-search $target - $target = $target::findFirst($target->{$this->primaryKey}); + $target = $target::findFirst( + $target->{$this->primaryKey} + ); - return $this->addNode($target, $target->{$this->rightAttribute}, 1, $attributes); + return $this->addNode( + $target, + $target->{$this->rightAttribute}, + 1, + $attributes + ); } /** @@ -443,7 +486,10 @@ public function appendTo(ModelInterface $target, array $attributes = null) */ public function append(ModelInterface $target, array $attributes = null) { - return $target->appendTo($this->getOwner(), $attributes); + return $target->appendTo( + $this->getOwner(), + $attributes + ); } /** @@ -455,7 +501,12 @@ public function append(ModelInterface $target, array $attributes = null) */ public function insertBefore(ModelInterface $target, array $attributes = null) { - return $this->addNode($target, $target->{$this->leftAttribute}, 0, $attributes); + return $this->addNode( + $target, + $target->{$this->leftAttribute}, + 0, + $attributes + ); } /** @@ -467,7 +518,12 @@ public function insertBefore(ModelInterface $target, array $attributes = null) */ public function insertAfter(ModelInterface $target, array $attributes = null) { - return $this->addNode($target, $target->{$this->rightAttribute} + 1, 0, $attributes); + return $this->addNode( + $target, + $target->{$this->rightAttribute} + 1, + 0, + $attributes + ); } /** @@ -478,7 +534,11 @@ public function insertAfter(ModelInterface $target, array $attributes = null) */ public function moveBefore(ModelInterface $target) { - return $this->moveNode($target, $target->{$this->leftAttribute}, 0); + return $this->moveNode( + $target, + $target->{$this->leftAttribute}, + 0 + ); } /** @@ -489,7 +549,11 @@ public function moveBefore(ModelInterface $target) */ public function moveAfter(ModelInterface $target) { - return $this->moveNode($target, $target->{$this->rightAttribute} + 1, 0); + return $this->moveNode( + $target, + $target->{$this->rightAttribute} + 1, + 0 + ); } /** @@ -500,7 +564,11 @@ public function moveAfter(ModelInterface $target) */ public function moveAsFirst(ModelInterface $target) { - return $this->moveNode($target, $target->{$this->leftAttribute} + 1, 1); + return $this->moveNode( + $target, + $target->{$this->leftAttribute} + 1, + 1 + ); } /** @@ -511,7 +579,11 @@ public function moveAsFirst(ModelInterface $target) */ public function moveAsLast(ModelInterface $target) { - return $this->moveNode($target, $target->{$this->rightAttribute}, 1); + return $this->moveNode( + $target, + $target->{$this->rightAttribute}, + 1 + ); } /** @@ -557,8 +629,9 @@ public function moveAsRoot() $this->leftAttribute => $i->{$this->leftAttribute} + $delta, $this->rightAttribute => $i->{$this->rightAttribute} + $delta, $this->levelAttribute => $i->{$this->levelAttribute} + $levelDelta, - $this->rootAttribute => $owner->{$this->primaryKey} + $this->rootAttribute => $owner->{$this->primaryKey}, ]; + if ($i->update($arr) == false) { $this->db->rollback(); $this->ignoreEvent = false; @@ -568,7 +641,10 @@ public function moveAsRoot() } $this->ignoreEvent = false; - $this->shiftLeftRight($right + 1, $left - $right - 1); + $this->shiftLeftRight( + $right + 1, + $left - $right - 1 + ); $this->db->commit(); @@ -610,17 +686,22 @@ public function deleteNode() $owner = $this->getOwner(); if ($this->getIsNewRecord()) { - throw new Exception('The node cannot be deleted because it is new.'); + throw new Exception( + 'The node cannot be deleted because it is new.' + ); } if ($this->getIsDeletedRecord()) { - throw new Exception('The node cannot be deleted because it is already deleted.'); + throw new Exception( + 'The node cannot be deleted because it is already deleted.' + ); } $this->db->begin(); if ($owner->isLeaf()) { $this->ignoreEvent = true; + if ($owner->delete() == false) { $this->db->rollback(); $this->ignoreEvent = false; @@ -636,6 +717,7 @@ public function deleteNode() } $this->ignoreEvent = true; + foreach ($owner::find($condition) as $i) { if ($i->delete() == false) { $this->db->rollback(); @@ -668,9 +750,13 @@ private function getDbHandler(ModelInterface $model) if (!$this->db instanceof AdapterInterface) { if ($model->getDi()->has('db')) { $db = $model->getDi()->getShared('db'); + if (!$db instanceof AdapterInterface) { - throw new Exception('The "db" service which was obtained from DI is invalid adapter.'); + throw new Exception( + 'The "db" service which was obtained from DI is invalid adapter.' + ); } + $this->db = $db; } else { throw new Exception('Undefined database handler.'); @@ -727,12 +813,17 @@ private function moveNode(ModelInterface $target, $key, $levelUp) // 1. Rebuild the target tree foreach ([$this->leftAttribute, $this->rightAttribute] as $attribute) { - $condition = join(' AND ', [ - $attribute . '>=' . $key, - $this->rootAttribute . '=' . $target->{$this->rootAttribute}, - ]); + $condition = join( + ' AND ', + [ + $attribute . '>=' . $key, + $this->rootAttribute . '=' . $target->{$this->rootAttribute}, + ] + ); + foreach ($target::find($condition) as $i) { $delta = $right - $left + 1; + /** @var ModelInterface $i */ if (!$i->update([$attribute => $i->{$attribute} + $delta])) { $this->db->rollback(); @@ -755,7 +846,7 @@ private function moveNode(ModelInterface $target, $key, $levelUp) $this->leftAttribute => $i->{$this->leftAttribute} + $delta, $this->rightAttribute => $i->{$this->rightAttribute} + $delta, $this->levelAttribute => $i->{$this->levelAttribute} + $levelDelta, - $this->rootAttribute => $target->{$this->rootAttribute} + $this->rootAttribute => $target->{$this->rootAttribute}, ]; if ($i->update($arr) == false) { @@ -770,10 +861,13 @@ private function moveNode(ModelInterface $target, $key, $levelUp) $this->shiftLeftRight($right + 1, $left - $right - 1, $owner); $this->ignoreEvent = false; + $this->db->commit(); } else { $delta = $right - $left + 1; + $this->ignoreEvent = true; + $this->shiftLeftRight($key, $delta); if ($left >= $key) { @@ -790,6 +884,7 @@ private function moveNode(ModelInterface $target, $key, $levelUp) foreach ($owner::find($condition) as $i) { if ($i->update([$this->levelAttribute => $i->{$this->levelAttribute} + $levelDelta]) == false) { $this->db->rollback(); + $this->ignoreEvent = false; return false; @@ -813,10 +908,13 @@ private function moveNode(ModelInterface $target, $key, $levelUp) } } - $this->shiftLeftRight($right + 1, -$delta); - $this->ignoreEvent = false; + $this->shiftLeftRight( + $right + 1, + -$delta + ); $this->ignoreEvent = false; + $this->db->commit(); } @@ -844,6 +942,7 @@ private function shiftLeftRight($key, $delta, ModelInterface $model = null) /** @var ModelInterface $i */ if ($i->update([$attribute => $i->{$attribute} + $delta]) == false) { $this->db->rollback(); + $this->ignoreEvent = false; return false; @@ -868,15 +967,21 @@ private function addNode(ModelInterface $target, $key, $levelUp, array $attribut $owner = $this->getOwner(); if (!$this->getIsNewRecord()) { - throw new Exception('The node cannot be inserted because it is not new.'); + throw new Exception( + 'The node cannot be inserted because it is not new.' + ); } if ($this->getIsDeletedRecord()) { - throw new Exception('The node cannot be inserted because it is deleted.'); + throw new Exception( + 'The node cannot be inserted because it is deleted.' + ); } if ($target->getIsDeletedRecord()) { - throw new Exception('The node cannot be inserted because target node is deleted.'); + throw new Exception( + 'The node cannot be inserted because target node is deleted.' + ); } if ($owner == $target) { @@ -904,11 +1009,14 @@ private function addNode(ModelInterface $target, $key, $levelUp, array $attribut $owner->{$this->levelAttribute} = $target->{$this->levelAttribute} + $levelUp; $this->ignoreEvent = true; + $result = $owner->create($attributes); + $this->ignoreEvent = false; if (!$result) { $db->rollback(); + $this->ignoreEvent = false; return false; @@ -943,22 +1051,33 @@ private function makeRoot($attributes, $whiteList) if ($this->hasManyRoots) { $this->db->begin(); + $this->ignoreEvent = true; + if ($owner->create($attributes, $whiteList) == false) { $this->db->rollback(); + $this->ignoreEvent = false; return false; } $pk = $owner->{$this->rootAttribute} = $owner->{$this->primaryKey}; - $owner::findFirst($pk)->update([$this->rootAttribute => $pk]); + + $owner::findFirst($pk)->update( + [ + $this->rootAttribute => $pk, + ] + ); + $this->ignoreEvent = false; $this->db->commit(); } else { if (count($owner->roots())) { - throw new Exception('Cannot create more than one root in single root mode.'); + throw new Exception( + 'Cannot create more than one root in single root mode.' + ); } if ($owner->create($attributes, $whiteList) == false) { diff --git a/Library/Phalcon/Mvc/Model/EagerLoading/EagerLoad.php b/Library/Phalcon/Mvc/Model/EagerLoading/EagerLoad.php index 0e38a6be7..a3e862963 100644 --- a/Library/Phalcon/Mvc/Model/EagerLoading/EagerLoad.php +++ b/Library/Phalcon/Mvc/Model/EagerLoading/EagerLoad.php @@ -131,10 +131,16 @@ public function load() unset($relIrValues, $row); - $builder->inWhere("[{$relReferencedField}]", array_keys($bindValues)); + $builder->inWhere( + "[{$relReferencedField}]", + array_keys($bindValues) + ); } } else { - $builder->inWhere("[{$relReferencedField}]", $bindValues); + $builder->inWhere( + "[{$relReferencedField}]", + $bindValues + ); } if ($this->constraints) { diff --git a/Library/Phalcon/Mvc/Model/EagerLoading/Loader.php b/Library/Phalcon/Mvc/Model/EagerLoading/Loader.php index 01dc47b51..73cfab379 100644 --- a/Library/Phalcon/Mvc/Model/EagerLoading/Loader.php +++ b/Library/Phalcon/Mvc/Model/EagerLoading/Loader.php @@ -52,6 +52,7 @@ public function __construct($from) } else { if ($className !== get_class($el)) { $error = true; + break; } } @@ -86,7 +87,9 @@ public function __construct($from) } if ($error) { - throw new \InvalidArgumentException(static::E_INVALID_SUBJECT); + throw new \InvalidArgumentException( + static::E_INVALID_SUBJECT + ); } $this->subject = $from; @@ -105,13 +108,24 @@ public function __construct($from) public static function from($subject) { if ($subject instanceof ModelInterface) { - $ret = call_user_func_array('static::fromModel', func_get_args()); + $ret = call_user_func_array( + 'static::fromModel', + func_get_args() + ); } elseif ($subject instanceof Simple) { - $ret = call_user_func_array('static::fromResultset', func_get_args()); + $ret = call_user_func_array( + 'static::fromResultset', + func_get_args() + ); } elseif (is_array($subject)) { - $ret = call_user_func_array('static::fromArray', func_get_args()); + $ret = call_user_func_array( + 'static::fromArray', + func_get_args() + ); } else { - throw new \InvalidArgumentException(static::E_INVALID_SUBJECT); + throw new \InvalidArgumentException( + static::E_INVALID_SUBJECT + ); } return $ret; @@ -127,7 +141,10 @@ public static function from($subject) public static function fromModel(ModelInterface $subject) { $reflection = new \ReflectionClass(__CLASS__); - $instance = $reflection->newInstanceArgs(func_get_args()); + + $instance = $reflection->newInstanceArgs( + func_get_args() + ); return $instance->execute()->get(); } @@ -142,7 +159,10 @@ public static function fromModel(ModelInterface $subject) public static function fromArray(array $subject) { $reflection = new \ReflectionClass(__CLASS__); - $instance = $reflection->newInstanceArgs(func_get_args()); + + $instance = $reflection->newInstanceArgs( + func_get_args() + ); return $instance->execute()->get(); } @@ -157,7 +177,10 @@ public static function fromArray(array $subject) public static function fromResultset(Simple $subject) { $reflection = new \ReflectionClass(__CLASS__); - $instance = $reflection->newInstanceArgs(func_get_args()); + + $instance = $reflection->newInstanceArgs( + func_get_args() + ); return $instance->execute()->get(); } @@ -232,17 +255,21 @@ private static function parseArguments(array $arguments) public function addEagerLoad($relationAlias, $constraints = null) { if (!is_string($relationAlias)) { - throw new \InvalidArgumentException(sprintf( - '$relationAlias expects to be a string, `%s` given', - gettype($relationAlias) - )); + throw new \InvalidArgumentException( + sprintf( + '$relationAlias expects to be a string, `%s` given', + gettype($relationAlias) + ) + ); } if ($constraints !== null && !is_callable($constraints)) { - throw new \InvalidArgumentException(sprintf( - '$constraints expects to be a callable, `%s` given', - gettype($constraints) - )); + throw new \InvalidArgumentException( + sprintf( + '$constraints expects to be a callable, `%s` given', + gettype($constraints) + ) + ); } $this->eagerLoads[$relationAlias] = $constraints; @@ -273,13 +300,21 @@ private function buildTree() do { do { $alias = $relationAliases[$nestingLevel]; - $name = join('.', array_slice($relationAliases, 0, $nestingLevel + 1)); + + $name = join( + '.', + array_slice($relationAliases, 0, $nestingLevel + 1) + ); } while (isset($eagerLoads[$name]) && ++$nestingLevel); if ($nestingLevel === 0) { $parentClassName = $this->subjectClassName; } else { - $parentName = join('.', array_slice($relationAliases, 0, $nestingLevel)); + $parentName = join( + '.', + array_slice($relationAliases, 0, $nestingLevel) + ); + $parentClassName = $resolvedRelations[$parentName]->getReferencedModel(); if ($parentClassName[0] === '\\') { @@ -289,14 +324,17 @@ private function buildTree() if (!isset($resolvedRelations[$name])) { $mM->load($parentClassName); + $relation = $mM->getRelationByAlias($parentClassName, $alias); if (!$relation instanceof Relation) { - throw new \RuntimeException(sprintf( - 'There is no defined relation for the model `%s` using alias `%s`', - $parentClassName, - $alias - )); + throw new \RuntimeException( + sprintf( + 'There is no defined relation for the model `%s` using alias `%s`', + $parentClassName, + $alias + ) + ); } $resolvedRelations[$name] = $relation; @@ -310,18 +348,28 @@ private function buildTree() $relType !== Relation::HAS_ONE && $relType !== Relation::HAS_MANY && $relType !== Relation::HAS_MANY_THROUGH) { - throw new \RuntimeException(sprintf('Unknown relation type `%s`', $relType)); + throw new \RuntimeException( + sprintf( + 'Unknown relation type `%s`', + $relType + ) + ); } - if (is_array($relation->getFields()) || - is_array($relation->getReferencedFields())) { - throw new \RuntimeException('Relations with composite keys are not supported'); + if (is_array($relation->getFields()) || is_array($relation->getReferencedFields())) { + throw new \RuntimeException( + 'Relations with composite keys are not supported' + ); } $parent = $nestingLevel > 0 ? $eagerLoads[$parentName] : $this; $constraints = $nestingLevel + 1 === $nestingLevels ? $queryConstraints : null; - $eagerLoads[$name] = new EagerLoad($relation, $constraints, $parent); + $eagerLoads[$name] = new EagerLoad( + $relation, + $constraints, + $parent + ); } while (++$nestingLevel < $nestingLevels); } diff --git a/Library/Phalcon/Mvc/Model/EagerLoading/QueryBuilder.php b/Library/Phalcon/Mvc/Model/EagerLoading/QueryBuilder.php index 7984b785c..899040d39 100644 --- a/Library/Phalcon/Mvc/Model/EagerLoading/QueryBuilder.php +++ b/Library/Phalcon/Mvc/Model/EagerLoading/QueryBuilder.php @@ -8,12 +8,16 @@ final class QueryBuilder extends Builder public function distinct($distinct) { - throw new \LogicException(static::E_NOT_ALLOWED_METHOD_CALL); + throw new \LogicException( + static::E_NOT_ALLOWED_METHOD_CALL + ); } public function columns($columns) { - throw new \LogicException(static::E_NOT_ALLOWED_METHOD_CALL); + throw new \LogicException( + static::E_NOT_ALLOWED_METHOD_CALL + ); } public function where($conditions, $bindParams = null, $bindTypes = null) diff --git a/Library/Phalcon/Mvc/Model/EagerLoadingTrait.php b/Library/Phalcon/Mvc/Model/EagerLoadingTrait.php index 10b094158..be1ecacaf 100644 --- a/Library/Phalcon/Mvc/Model/EagerLoadingTrait.php +++ b/Library/Phalcon/Mvc/Model/EagerLoadingTrait.php @@ -41,11 +41,15 @@ public static function with() unset($arguments[$lastArg]); if (isset($parameters['columns'])) { - throw new \LogicException('Results from database must be full models, do not use `columns` key'); + throw new \LogicException( + 'Results from database must be full models, do not use `columns` key' + ); } } } else { - throw new \BadMethodCallException(sprintf('%s requires at least one argument', __METHOD__)); + throw new \BadMethodCallException( + sprintf('%s requires at least one argument', __METHOD__) + ); } $ret = static::find($parameters); @@ -53,7 +57,10 @@ public static function with() if ($ret->count()) { array_unshift($arguments, $ret); - $ret = call_user_func_array('Phalcon\Mvc\Model\EagerLoading\Loader::fromResultset', $arguments); + $ret = call_user_func_array( + 'Phalcon\Mvc\Model\EagerLoading\Loader::fromResultset', + $arguments + ); } return $ret; @@ -80,17 +87,27 @@ public static function findFirstWith() unset($arguments[$lastArg]); if (isset($parameters['columns'])) { - throw new \LogicException('Results from database must be full models, do not use `columns` key'); + throw new \LogicException( + 'Results from database must be full models, do not use `columns` key' + ); } } } else { - throw new \BadMethodCallException(sprintf('%s requires at least one argument', __METHOD__)); + throw new \BadMethodCallException( + sprintf( + '%s requires at least one argument', + __METHOD__ + ) + ); } if ($ret = static::findFirst($parameters)) { array_unshift($arguments, $ret); - $ret = call_user_func_array('Phalcon\Mvc\Model\EagerLoading\Loader::fromModel', $arguments); + $ret = call_user_func_array( + 'Phalcon\Mvc\Model\EagerLoading\Loader::fromModel', + $arguments + ); } return $ret; @@ -118,6 +135,9 @@ public function load() array_unshift($arguments, $this); - return call_user_func_array('Phalcon\Mvc\Model\EagerLoading\Loader::fromModel', $arguments); + return call_user_func_array( + 'Phalcon\Mvc\Model\EagerLoading\Loader::fromModel', + $arguments + ); } } diff --git a/Library/Phalcon/Mvc/Model/MetaData/Wincache.php b/Library/Phalcon/Mvc/Model/MetaData/Wincache.php index b66abc798..3b65241d9 100644 --- a/Library/Phalcon/Mvc/Model/MetaData/Wincache.php +++ b/Library/Phalcon/Mvc/Model/MetaData/Wincache.php @@ -37,7 +37,11 @@ protected function getCacheBackend() { if (null === $this->wincache) { $this->wincache = new CacheBackend( - new CacheFrontend(['lifetime' => $this->options['lifetime']]), + new CacheFrontend( + [ + 'lifetime' => $this->options['lifetime'], + ] + ), [] ); } diff --git a/Library/Phalcon/Mvc/MongoCollection.php b/Library/Phalcon/Mvc/MongoCollection.php index 1570b7b42..e0a029ba3 100644 --- a/Library/Phalcon/Mvc/MongoCollection.php +++ b/Library/Phalcon/Mvc/MongoCollection.php @@ -56,6 +56,7 @@ public function setId($id) if ($this->_modelsManager->isUsingImplicitObjectIds($this)) { $this->_id = new ObjectID($id); + return; } @@ -120,15 +121,27 @@ public function save() switch ($this->_operationMade) { case self::OP_CREATE: $status = $collection->insertOne($data); + break; case self::OP_UPDATE: unset($data['_id']); - $status = $collection->updateOne(['_id' => $this->_id], ['$set' => $data]); + + $status = $collection->updateOne( + [ + '_id' => $this->_id, + ], + [ + '$set' => $data, + ] + ); + break; default: - throw new Exception('Invalid operation requested for ' . __METHOD__); + throw new Exception( + 'Invalid operation requested for ' . __METHOD__ + ); } $success = false; @@ -138,6 +151,7 @@ public function save() if (false === $exists) { $this->_id = $status->getInsertedId(); + $this->_dirtyState = self::DIRTY_STATE_PERSISTENT; } } @@ -159,6 +173,7 @@ public static function findById($id) { if (!is_object($id)) { $classname = get_called_class(); + $collection = new $classname(); /** @var MongoCollection $collection */ @@ -171,7 +186,13 @@ public static function findById($id) $mongoId = $id; } - return static::findFirst([["_id" => $mongoId]]); + return static::findFirst( + [ + [ + "_id" => $mongoId, + ] + ] + ); } /** @@ -189,7 +210,12 @@ public static function findFirst(array $parameters = null) $connection = $collection->getConnection(); - return static::_getResultset($parameters, $collection, $connection, true); + return static::_getResultset( + $parameters, + $collection, + $connection, + true + ); } /** @@ -212,6 +238,7 @@ protected static function _getResultset($params, CollectionInterface $collection */ if (isset($params['class'])) { $classname = $params['class']; + $base = new $classname(); if (!$base instanceof CollectionInterface || $base instanceof Document) { @@ -229,7 +256,9 @@ protected static function _getResultset($params, CollectionInterface $collection } if ($base instanceof PhalconCollection) { - $base->setDirtyState(PhalconCollection::DIRTY_STATE_PERSISTENT); + $base->setDirtyState( + PhalconCollection::DIRTY_STATE_PERSISTENT + ); } $source = $collection->getSource(); @@ -250,7 +279,7 @@ protected static function _getResultset($params, CollectionInterface $collection $conditions = []; if (isset($params[0])||isset($params['conditions'])) { - $conditions = (isset($params[0]))?$params[0]:$params['conditions']; + $conditions = (isset($params[0])) ? $params[0] : $params['conditions']; } /** @@ -268,7 +297,7 @@ protected static function _getResultset($params, CollectionInterface $collection if (isset($params['limit'])) { $limit = $params['limit']; - $options['limit'] = (int)$limit; + $options['limit'] = (int) $limit; if ($unique) { $options['limit'] = 1; @@ -307,13 +336,20 @@ protected static function _getResultset($params, CollectionInterface $collection $cursor = $mongoCollection->find($conditions, $options); - $cursor->setTypeMap(['root' => get_class($base), 'document' => 'array']); + $cursor->setTypeMap( + [ + 'root' => get_class($base), + 'document' => 'array', + ] + ); if (true === $unique) { /** * Looking for only the first result. */ - return current($cursor->toArray()); + return current( + $cursor->toArray() + ); } /** @@ -345,7 +381,9 @@ protected static function _getResultset($params, CollectionInterface $collection public function delete() { if (!$id = $this->_id) { - throw new Exception("The document cannot be deleted because it doesn't exist"); + throw new Exception( + "The document cannot be deleted because it doesn't exist" + ); } $disableEvents = self::$_disableEvents; @@ -389,12 +427,20 @@ public function delete() /** * Remove the instance */ - $status = $collection->deleteOne(['_id' => $mongoId], ['w' => true]); + $status = $collection->deleteOne( + [ + '_id' => $mongoId, + ], + [ + 'w' => true, + ] + ); if ($status->isAcknowledged()) { $success = true; $this->fireEvent("afterDelete"); + $this->_dirtyState = self::DIRTY_STATE_DETACHED; } @@ -486,7 +532,9 @@ public function fireEventCancel($eventName) */ public static function summatory($field, $conditions = null, $finalize = null) { - throw new Exception('The summatory() method is not implemented in the new Mvc MongoCollection'); + throw new Exception( + 'The summatory() method is not implemented in the new Mvc MongoCollection' + ); } /** @@ -523,9 +571,16 @@ public function create() * We always use safe stores to get the success state * Save the document */ - $result = $collection->insert($data, ['writeConcern' => new WriteConcern(1)]); + $result = $collection->insert( + $data, + [ + 'writeConcern' => new WriteConcern(1), + ] + ); + if ($result instanceof InsertOneResult && $result->getInsertedId()) { $success = true; + $this->_dirtyState = self::DIRTY_STATE_PERSISTENT; $this->_id = $result->getInsertedId(); } @@ -543,8 +598,11 @@ public function create() */ public function bsonUnserialize(array $data) { - $this->setDI(Di::getDefault()); - $this->_modelsManager = Di::getDefault()->getShared('collectionManager'); + $di = Di::getDefault(); + + $this->setDI($di); + + $this->_modelsManager = $di->getShared('collectionManager'); foreach ($data as $key => $val) { $this->{$key} = $val; diff --git a/Library/Phalcon/Mvc/View/Engine/Mustache.php b/Library/Phalcon/Mvc/View/Engine/Mustache.php index b67ee03f3..6fa1f3fd0 100644 --- a/Library/Phalcon/Mvc/View/Engine/Mustache.php +++ b/Library/Phalcon/Mvc/View/Engine/Mustache.php @@ -43,7 +43,11 @@ public function render($path, $params, $mustClean = false) $params['content'] = $this->_view->getContent(); } - $content = $this->mustache->render(file_get_contents($path), $params); + $content = $this->mustache->render( + file_get_contents($path), + $params + ); + if ($mustClean) { $this->_view->setContent($content); } else { diff --git a/Library/Phalcon/Mvc/View/Engine/Twig.php b/Library/Phalcon/Mvc/View/Engine/Twig.php index 1866f5052..512fdde5b 100644 --- a/Library/Phalcon/Mvc/View/Engine/Twig.php +++ b/Library/Phalcon/Mvc/View/Engine/Twig.php @@ -31,10 +31,16 @@ public function __construct( $options = [], $userFunctions = [] ) { - $loader = new \Twig_Loader_Filesystem($view->getViewsDir()); + $loader = new \Twig_Loader_Filesystem( + $view->getViewsDir() + ); + $this->twig = new Twig\Environment($di, $loader, $options); - $this->twig->addExtension(new Twig\CoreExtension()); + $this->twig->addExtension( + new Twig\CoreExtension() + ); + $this->registryFunctions($view, $di, $userFunctions); parent::__construct($view, $di); @@ -52,78 +58,174 @@ protected function registryFunctions($view, DiInterface $di, $userFunctions = [] $options = ['is_safe' => ['html']]; $functions = [ - new \Twig_SimpleFunction('content', function () use ($view) { - return $view->getContent(); - }, $options), - new \Twig_SimpleFunction('partial', function ($partialPath, $params = null) use ($view) { - return $view->partial($partialPath, $params); - }, $options), - new \Twig_SimpleFunction('linkTo', function ($parameters, $text = null, $local = true) { - return \Phalcon\Tag::linkTo($parameters, $text, $local); - }, $options), - new \Twig_SimpleFunction('textField', function ($parameters) { - return \Phalcon\Tag::textField($parameters); - }, $options), - new \Twig_SimpleFunction('passwordField', function ($parameters) { - return \Phalcon\Tag::passwordField($parameters); - }, $options), - new \Twig_SimpleFunction('hiddenField', function ($parameters) { - return \Phalcon\Tag::hiddenField($parameters); - }, $options), - new \Twig_SimpleFunction('fileField', function ($parameters) { - return \Phalcon\Tag::fileField($parameters); - }, $options), - new \Twig_SimpleFunction('checkField', function ($parameters) { - return \Phalcon\Tag::checkField($parameters); - }, $options), - new \Twig_SimpleFunction('radioField', function ($parameters) { - return \Phalcon\Tag::radioField($parameters); - }, $options), - new \Twig_SimpleFunction('submitButton', function ($parameters) { - return \Phalcon\Tag::submitButton($parameters); - }, $options), - new \Twig_SimpleFunction('selectStatic', function ($parameters, $data = []) { - return \Phalcon\Tag::selectStatic($parameters, $data); - }, $options), - new \Twig_SimpleFunction('select', function ($parameters, $data = []) { - return \Phalcon\Tag::select($parameters, $data); - }, $options), - new \Twig_SimpleFunction('textArea', function ($parameters) { - return \Phalcon\Tag::textArea($parameters); - }, $options), - new \Twig_SimpleFunction('form', function ($parameters = []) { - return \Phalcon\Tag::form($parameters); - }, $options), - new \Twig_SimpleFunction('endForm', function () { - return \Phalcon\Tag::endForm(); - }, $options), - new \Twig_SimpleFunction('getTitle', function () { - return \Phalcon\Tag::getTitle(); - }, $options), - new \Twig_SimpleFunction('stylesheetLink', function ($parameters = null, $local = true) { - return \Phalcon\Tag::stylesheetLink($parameters, $local); - }, $options), - new \Twig_SimpleFunction('javascriptInclude', function ($parameters = null, $local = true) { - return \Phalcon\Tag::javascriptInclude($parameters, $local); - }, $options), - new \Twig_SimpleFunction('image', function ($parameters = null, $local = true) { - return \Phalcon\Tag::image($parameters, $local); - }, $options), - new \Twig_SimpleFunction('friendlyTitle', function ($text, $separator = "-", $lc = true, $replace = null) { - return \Phalcon\Tag::friendlyTitle($text, $separator, $lc, $replace); - }, $options), - new \Twig_SimpleFunction('getDocType', function () { - return \Phalcon\Tag::getDocType(); - }, $options), - new \Twig_SimpleFunction('getSecurityToken', function () use ($di) { - return $di->get("security")->getToken(); - }, $options), - new \Twig_SimpleFunction('getSecurityTokenKey', function () use ($di) { - return $di->get("security")->getTokenKey(); - }, $options), - new \Twig_SimpleFunction('url', function ($route) use ($di) { - return $di->get("url")->get($route); - }, $options) + new \Twig_SimpleFunction( + 'content', + function () use ($view) { + return $view->getContent(); + }, + $options + ), + new \Twig_SimpleFunction( + 'partial', + function ($partialPath, $params = null) use ($view) { + return $view->partial($partialPath, $params); + }, + $options + ), + new \Twig_SimpleFunction( + 'linkTo', + function ($parameters, $text = null, $local = true) { + return \Phalcon\Tag::linkTo($parameters, $text, $local); + }, + $options + ), + new \Twig_SimpleFunction( + 'textField', + function ($parameters) { + return \Phalcon\Tag::textField($parameters); + }, + $options + ), + new \Twig_SimpleFunction( + 'passwordField', + function ($parameters) { + return \Phalcon\Tag::passwordField($parameters); + }, + $options + ), + new \Twig_SimpleFunction( + 'hiddenField', + function ($parameters) { + return \Phalcon\Tag::hiddenField($parameters); + }, + $options + ), + new \Twig_SimpleFunction( + 'fileField', + function ($parameters) { + return \Phalcon\Tag::fileField($parameters); + }, + $options + ), + new \Twig_SimpleFunction( + 'checkField', + function ($parameters) { + return \Phalcon\Tag::checkField($parameters); + }, + $options + ), + new \Twig_SimpleFunction( + 'radioField', + function ($parameters) { + return \Phalcon\Tag::radioField($parameters); + }, + $options + ), + new \Twig_SimpleFunction( + 'submitButton', + function ($parameters) { + return \Phalcon\Tag::submitButton($parameters); + }, + $options + ), + new \Twig_SimpleFunction( + 'selectStatic', + function ($parameters, $data = []) { + return \Phalcon\Tag::selectStatic($parameters, $data); + }, + $options + ), + new \Twig_SimpleFunction( + 'select', + function ($parameters, $data = []) { + return \Phalcon\Tag::select($parameters, $data); + }, + $options + ), + new \Twig_SimpleFunction( + 'textArea', + function ($parameters) { + return \Phalcon\Tag::textArea($parameters); + }, + $options + ), + new \Twig_SimpleFunction( + 'form', + function ($parameters = []) { + return \Phalcon\Tag::form($parameters); + }, + $options + ), + new \Twig_SimpleFunction( + 'endForm', + function () { + return \Phalcon\Tag::endForm(); + }, + $options + ), + new \Twig_SimpleFunction( + 'getTitle', + function () { + return \Phalcon\Tag::getTitle(); + }, + $options + ), + new \Twig_SimpleFunction( + 'stylesheetLink', + function ($parameters = null, $local = true) { + return \Phalcon\Tag::stylesheetLink($parameters, $local); + }, + $options + ), + new \Twig_SimpleFunction( + 'javascriptInclude', + function ($parameters = null, $local = true) { + return \Phalcon\Tag::javascriptInclude($parameters, $local); + }, + $options + ), + new \Twig_SimpleFunction( + 'image', + function ($parameters = null, $local = true) { + return \Phalcon\Tag::image($parameters, $local); + }, + $options + ), + new \Twig_SimpleFunction( + 'friendlyTitle', + function ($text, $separator = "-", $lc = true, $replace = null) { + return \Phalcon\Tag::friendlyTitle($text, $separator, $lc, $replace); + }, + $options + ), + new \Twig_SimpleFunction( + 'getDocType', + function () { + return \Phalcon\Tag::getDocType(); + }, + $options + ), + new \Twig_SimpleFunction( + 'getSecurityToken', + function () use ($di) { + return $di->get("security")->getToken(); + }, + $options + ), + new \Twig_SimpleFunction( + 'getSecurityTokenKey', + function () use ($di) { + return $di->get("security")->getTokenKey(); + }, + $options + ), + new \Twig_SimpleFunction( + 'url', + function ($route) use ($di) { + return $di->get("url")->get($route); + }, + $options + ) ]; if (!empty($userFunctions)) { @@ -153,9 +255,14 @@ public function render($path, $params, $mustClean = false) $params['view'] = $view; } - $relativePath = str_replace($view->getViewsDir(), '', $path); + $relativePath = str_replace( + $view->getViewsDir(), + '', + $path + ); $content = $this->twig->render($relativePath, $params); + if ($mustClean) { $this->_view->setContent($content); } else { diff --git a/Library/Phalcon/Paginator/Pager.php b/Library/Phalcon/Paginator/Pager.php index 563727755..06de85473 100644 --- a/Library/Phalcon/Paginator/Pager.php +++ b/Library/Phalcon/Paginator/Pager.php @@ -150,7 +150,7 @@ public function getLastPage() public function getLayout() { if (!array_key_exists('layoutClass', $this->options)) { - $this->options['layoutClass'] = 'Phalcon\Paginator\Pager\Layout'; + $this->options['layoutClass'] = \Phalcon\Paginator\Pager\Layout::class; } if (!array_key_exists('urlMask', $this->options)) { @@ -162,11 +162,21 @@ public function getLayout() $rangeLength = $this->getRangeLength(); if (!class_exists($rangeClass)) { - throw new \RuntimeException(sprintf('Unable to find range class "%s"', $rangeClass)); + throw new \RuntimeException( + sprintf( + 'Unable to find range class "%s"', + $rangeClass + ) + ); } if (!class_exists($this->options['layoutClass'])) { - throw new \RuntimeException(sprintf('Unable to find layout "%s"', $this->options['layoutClass'])); + throw new \RuntimeException( + sprintf( + 'Unable to find layout "%s"', + $this->options['layoutClass'] + ) + ); } return new $this->options['layoutClass']( @@ -183,9 +193,13 @@ public function getLayout() */ public function getPagesInRange() { - /** @var \Phalcon\Paginator\Pager\Range $range */ $rangeClass = $this->getRangeClass(); - $range = new $rangeClass($this, $this->getRangeLength()); + + /** @var \Phalcon\Paginator\Pager\Range $range */ + $range = new $rangeClass( + $this, + $this->getRangeLength() + ); return $range->getRange(); } @@ -198,7 +212,9 @@ public function getPagesInRange() public function getIterator() { if (!$this->paginateResult->items instanceof \Iterator) { - return new \ArrayIterator($this->paginateResult->items); + return new \ArrayIterator( + $this->paginateResult->items + ); } return $this->paginateResult->items; @@ -211,7 +227,9 @@ public function getIterator() */ public function count() { - return intval($this->paginateResult->total_items); + return intval( + $this->paginateResult->total_items + ); } /** @@ -222,7 +240,7 @@ public function count() protected function getRangeClass() { if (!array_key_exists('rangeClass', $this->options)) { - $this->options['rangeClass'] = 'Phalcon\Paginator\Pager\Range\Sliding'; + $this->options['rangeClass'] = \Phalcon\Paginator\Pager\Range\Sliding::class; } return $this->options['rangeClass']; diff --git a/Library/Phalcon/Paginator/Pager/Layout.php b/Library/Phalcon/Paginator/Pager/Layout.php index 76c13108a..3322ba491 100644 --- a/Library/Phalcon/Paginator/Pager/Layout.php +++ b/Library/Phalcon/Paginator/Pager/Layout.php @@ -127,7 +127,7 @@ public function addMaskReplacement($oldMask, $newMask, $asValue = false) if (($oldMask = trim($oldMask)) != 'page_number') { $this->maskReplacements[$oldMask] = [ 'newMask' => $newMask, - 'asValue' => ($asValue === false) ? false : true + 'asValue' => ($asValue !== false) ]; } } @@ -140,8 +140,9 @@ public function addMaskReplacement($oldMask, $newMask, $asValue = false) public function removeMaskReplacement($oldMask) { if (isset($this->maskReplacements[$oldMask])) { - $this->maskReplacements[$oldMask] = null; - unset($this->maskReplacements[$oldMask]); + unset( + $this->maskReplacements[$oldMask] + ); } } @@ -216,12 +217,16 @@ protected function parseUrlTemplate(array $options = []) // If given page is the current active one if ($options['page_number'] == $this->pager->getCurrentPage()) { - $str = $this->parseMaskReplacements($this->selectedTemplate); + $str = $this->parseMaskReplacements( + $this->selectedTemplate + ); } // Possible attempt where Selected == Template if ($str == '') { - $str = $this->parseMaskReplacements($this->template); + $str = $this->parseMaskReplacements( + $this->template + ); } return $str; diff --git a/Library/Phalcon/Paginator/Pager/Range.php b/Library/Phalcon/Paginator/Pager/Range.php index 5c86018a0..a0cd0745d 100644 --- a/Library/Phalcon/Paginator/Pager/Range.php +++ b/Library/Phalcon/Paginator/Pager/Range.php @@ -50,7 +50,10 @@ abstract class Range public function __construct(Pager $pager, $chunkLength) { $this->pager = $pager; - $this->chunkLength = abs(intval($chunkLength)); + + $this->chunkLength = abs( + intval($chunkLength) + ); if ($this->chunkLength == 0) { $this->chunkLength = 1; diff --git a/Library/Phalcon/Session/Adapter/Aerospike.php b/Library/Phalcon/Session/Adapter/Aerospike.php index 4871e27ef..8b2561a58 100644 --- a/Library/Phalcon/Session/Adapter/Aerospike.php +++ b/Library/Phalcon/Session/Adapter/Aerospike.php @@ -33,20 +33,25 @@ * * use Phalcon\Session\Adapter\Aerospike as AerospikeSession; * - * $session = new AerospikeSession([ - * 'hosts' => [ - * ['addr' => '127.0.0.1', 'port' => 3000] - * ], - * 'persistent' => true, - * 'namespace' => 'test', - * 'prefix' => 'session_', - * 'lifetime' => 8600, - * 'uniqueId' => '3Hf90KdjQ18', - * 'options' => [ - * \Aerospike::OPT_CONNECT_TIMEOUT => 1250, - * \Aerospike::OPT_WRITE_TIMEOUT => 1500 + * $session = new AerospikeSession( + * [ + * 'hosts' => [ + * [ + * 'addr' => '127.0.0.1', + * 'port' => 3000, + * ], + * ], + * 'persistent' => true, + * 'namespace' => 'test', + * 'prefix' => 'session_', + * 'lifetime' => 8600, + * 'uniqueId' => '3Hf90KdjQ18', + * 'options' => [ + * \Aerospike::OPT_CONNECT_TIMEOUT => 1250, + * \Aerospike::OPT_WRITE_TIMEOUT => 1500, + * ], * ] - * ]); + * ); * * $session->start(); * @@ -59,30 +64,35 @@ class Aerospike extends Adapter implements AdapterInterface { /** * The Aerospike DB + * * @var AerospikeDb */ protected $db; /** * Default Aerospike namespace + * * @var string */ protected $namespace = 'test'; /** * The Aerospike Set for store sessions + * * @var string */ protected $set = 'session'; /** * Key prefix + * * @var string */ protected $prefix = ''; /** * Session lifetime + * * @var int */ protected $lifetime = 8600; @@ -103,6 +113,7 @@ public function __construct(array $options) if (isset($options['namespace'])) { $this->namespace = $options['namespace']; + unset($options['namespace']); } @@ -112,6 +123,7 @@ public function __construct(array $options) if (isset($options['set']) && !empty($options['set'])) { $this->set = $options['set']; + unset($options['set']); } @@ -130,7 +142,11 @@ public function __construct(array $options) } $this->db = new AerospikeDb( - new FrontendData(['lifetime' => $this->lifetime]), + new FrontendData( + [ + 'lifetime' => $this->lifetime, + ] + ), [ 'hosts' => $options['hosts'], 'namespace' => $this->namespace, @@ -138,7 +154,6 @@ public function __construct(array $options) 'prefix' => $this->prefix, 'persistent' => $persistent, 'options' => $opts, - ] ); diff --git a/Library/Phalcon/Session/Adapter/Database.php b/Library/Phalcon/Session/Adapter/Database.php index 1bd8ae366..efe7b8d01 100644 --- a/Library/Phalcon/Session/Adapter/Database.php +++ b/Library/Phalcon/Session/Adapter/Database.php @@ -57,7 +57,9 @@ public function __construct($options = null) unset($options['db']); if (!isset($options['table']) || empty($options['table']) || !is_string($options['table'])) { - throw new Exception("Parameter 'table' is required and it must be a non empty string"); + throw new Exception( + "Parameter 'table' is required and it must be a non empty string" + ); } $columns = ['session_id', 'data', 'created_at', 'modified_at']; @@ -99,6 +101,7 @@ public function open() public function close() { $this->_started = false; + return $this->isStarted(); } diff --git a/Library/Phalcon/Session/Adapter/HandlerSocket.php b/Library/Phalcon/Session/Adapter/HandlerSocket.php index c98b375ba..769117629 100644 --- a/Library/Phalcon/Session/Adapter/HandlerSocket.php +++ b/Library/Phalcon/Session/Adapter/HandlerSocket.php @@ -55,7 +55,7 @@ class HandlerSocket extends Adapter implements AdapterInterface 'host' => self::DEFAULT_HOST, 'port' => self::DEFAULT_PORT, 'dbname' => self::DEFAULT_DBNAME, - 'dbtable' => self::DEFAULT_DBTABLE + 'dbtable' => self::DEFAULT_DBTABLE, ], ]; @@ -160,7 +160,15 @@ public function close() */ public function read($id) { - $retval = $this->hs->executeSingle($this->hsIndex, '=', [$id], 1, 0); + $retval = $this->hs->executeSingle( + $this->hsIndex, + '=', + [ + $id, + ], + 1, + 0 + ); if (!isset($retval[0], $retval[0][2])) { return ''; @@ -187,9 +195,27 @@ public function write($id, $data) } if (empty($this->fields)) { - $this->hs->executeInsert($this->hsIndex, [$id, date('Y-m-d H:i:s'), $data]); + $this->hs->executeInsert( + $this->hsIndex, + [ + $id, + date('Y-m-d H:i:s'), + $data, + ] + ); } else { - $this->hs->executeUpdate($this->hsIndex, '=', [$id], [$id, date('Y-m-d H:i:s'), $data], 1, 0); + $this->hs->executeUpdate( + $this->hsIndex, + '=', + [$id], + [ + $id, + date('Y-m-d H:i:s'), + $data, + ], + 1, + 0 + ); } return true; @@ -203,7 +229,13 @@ public function write($id, $data) */ public function destroy($id) { - $this->hs->executeDelete($this->hsIndex, '=', [$id], 1, 0); + $this->hs->executeDelete( + $this->hsIndex, + '=', + [$id], + 1, + 0 + ); return true; } @@ -216,7 +248,11 @@ public function destroy($id) */ public function gc($maxlifetime) { - $time = date('Y-m-d H:i:s', strtotime("- $maxlifetime seconds")); + $time = date( + 'Y-m-d H:i:s', + strtotime("- $maxlifetime seconds") + ); + $index = $this->hsIndex + 1; $this->hs->openIndex( @@ -227,7 +263,13 @@ public function gc($maxlifetime) '' ); - $this->hs->executeDelete($index, '<', [$time], 1000, 0); + $this->hs->executeDelete( + $index, + '<', + [$time], + 1000, + 0 + ); return true; } @@ -264,11 +306,16 @@ protected function init($options) $this->options = $options; if (!extension_loaded('handlersocket')) { - throw new Exception('The handlersocket extension must be loaded for using session!'); + throw new Exception( + 'The handlersocket extension must be loaded for using session!' + ); } // load handlersocket server - $this->hs = new \HandlerSocket($options['server']['host'], $options['server']['port']); + $this->hs = new \HandlerSocket( + $options['server']['host'], + $options['server']['port'] + ); // open handlersocket index $result = $this->hs->openIndex( @@ -280,7 +327,9 @@ protected function init($options) ); if (!$result) { - throw new Exception('The HandlerSocket database specified in the options does not exist.'); + throw new Exception( + 'The HandlerSocket database specified in the options does not exist.' + ); } } } diff --git a/Library/Phalcon/Session/Adapter/Mongo.php b/Library/Phalcon/Session/Adapter/Mongo.php index bf3663106..5e3824019 100644 --- a/Library/Phalcon/Session/Adapter/Mongo.php +++ b/Library/Phalcon/Session/Adapter/Mongo.php @@ -87,13 +87,18 @@ public function close() */ public function read($sessionId) { - $sessionData = $this->getCollection()->findOne(['_id' => $sessionId]); + $sessionData = $this->getCollection()->findOne( + [ + '_id' => $sessionId, + ] + ); if (!isset($sessionData['data'])) { return ''; } $this->data = $sessionData['data']; + return $sessionData['data']; } @@ -113,7 +118,7 @@ public function write($sessionId, $sessionData) $sessionData = [ '_id' => $sessionId, 'modified' => new \MongoDate(), - 'data' => $sessionData + 'data' => $sessionData, ]; $this->getCollection()->save($sessionData); @@ -132,7 +137,11 @@ public function destroy($sessionId = null) $this->data = null; - $remove = $this->getCollection()->remove(['_id' => $sessionId]); + $remove = $this->getCollection()->remove( + [ + '_id' => $sessionId, + ] + ); return (bool) $remove['ok']; } @@ -144,10 +153,23 @@ public function destroy($sessionId = null) public function gc($maxLifetime) { $minAge = new \DateTime(); - $minAge->sub(new \DateInterval('PT' . $maxLifetime . 'S')); - $minAgeMongo = new \MongoDate($minAge->getTimestamp()); - $query = ['modified' => ['$lte' => $minAgeMongo]]; + $minAge->sub( + new \DateInterval( + 'PT' . $maxLifetime . 'S' + ) + ); + + $minAgeMongo = new \MongoDate( + $minAge->getTimestamp() + ); + + $query = [ + 'modified' => [ + '$lte' => $minAgeMongo, + ], + ]; + $remove = $this->getCollection()->remove($query); return (bool) $remove['ok']; diff --git a/Library/Phalcon/Test/Traits/FunctionalTestCase.php b/Library/Phalcon/Test/Traits/FunctionalTestCase.php index 30aadc58d..09288beeb 100644 --- a/Library/Phalcon/Test/Traits/FunctionalTestCase.php +++ b/Library/Phalcon/Test/Traits/FunctionalTestCase.php @@ -39,6 +39,7 @@ protected function setUpPhalcon() 'dispatcher', function () { $dispatcher = new PhDispatcher(); + $dispatcher->setControllerName('test'); $dispatcher->setActionName('empty'); $dispatcher->setParams([]); @@ -67,6 +68,7 @@ function () { protected function tearDownPhalcon() { $this->di->reset(); + $this->application = null; $_SESSION = []; @@ -85,7 +87,10 @@ protected function tearDownPhalcon() */ protected function dispatch($url) { - $this->di->setShared('response', $this->application->handle($url)); + $this->di->setShared( + 'response', + $this->application->handle($url) + ); } /** @@ -96,7 +101,10 @@ protected function dispatch($url) */ public function assertController($expected) { - $actual = $this->di->getShared('dispatcher')->getControllerName(); + $dispatcher = $this->di->getShared('dispatcher'); + + $actual = $dispatcher->getControllerName(); + if ($actual != $expected) { throw new \PHPUnit\Framework\ExpectationFailedException( sprintf( @@ -118,7 +126,10 @@ public function assertController($expected) */ public function assertAction($expected) { - $actual = $this->di->getShared('dispatcher')->getActionName(); + $dispatcher = $this->di->getShared('dispatcher'); + + $actual = $dispatcher->getActionName(); + if ($actual != $expected) { throw new \PHPUnit\Framework\ExpectationFailedException( sprintf( @@ -128,6 +139,7 @@ public function assertAction($expected) ) ); } + $this->assertEquals($expected, $actual); } @@ -142,8 +154,13 @@ public function assertAction($expected) */ public function assertHeader(array $expected) { + $response = $this->di->getShared('response'); + + $headers = $response->getHeaders(); + foreach ($expected as $expectedField => $expectedValue) { - $actualValue = $this->di->getShared('response')->getHeaders()->get($expectedField); + $actualValue = $headers->get($expectedField); + if ($actualValue != $expectedValue) { throw new \PHPUnit\Framework\ExpectationFailedException( sprintf( @@ -155,6 +172,7 @@ public function assertHeader(array $expected) ) ); } + $this->assertEquals($expectedValue, $actualValue); } } @@ -172,7 +190,11 @@ public function assertResponseCode($expected) $expected = (string) $expected; } - $actualValue = $this->di->getShared('response')->getHeaders()->get('Status'); + $response = $this->di->getShared('response'); + + $headers = $response->getHeaders(); + + $actualValue = $headers->get('Status'); if (empty($actualValue) || stristr($actualValue, $expected) === false) { throw new \PHPUnit\Framework\ExpectationFailedException( @@ -196,10 +218,13 @@ public function assertDispatchIsForwarded() { /* @var $dispatcher \Phalcon\Mvc\Dispatcher */ $dispatcher = $this->di->getShared('dispatcher'); + $actual = $dispatcher->wasForwarded(); if (!$actual) { - throw new \PHPUnit\Framework\ExpectationFailedException('Failed asserting dispatch was forwarded'); + throw new \PHPUnit\Framework\ExpectationFailedException( + 'Failed asserting dispatch was forwarded' + ); } $this->assertTrue($actual); @@ -213,18 +238,26 @@ public function assertDispatchIsForwarded() */ public function assertRedirectTo($location) { - $actualLocation = $this->di->getShared('response')->getHeaders()->get('Location'); + $response = $this->di->getShared('response'); + + $headers = $response->getHeaders(); + + $actualLocation = $headers->get('Location'); if (!$actualLocation) { - throw new \PHPUnit\Framework\ExpectationFailedException('Failed asserting response caused a redirect'); + throw new \PHPUnit\Framework\ExpectationFailedException( + 'Failed asserting response caused a redirect' + ); } if ($actualLocation !== $location) { - throw new \PHPUnit\Framework\ExpectationFailedException(sprintf( - 'Failed asserting response redirects to "%s". It redirects to "%s".', - $location, - $actualLocation - )); + throw new \PHPUnit\Framework\ExpectationFailedException( + sprintf( + 'Failed asserting response redirects to "%s". It redirects to "%s".', + $location, + $actualLocation + ) + ); } $this->assertEquals($location, $actualLocation); @@ -237,7 +270,9 @@ public function assertRedirectTo($location) */ public function getContent() { - return $this->di->getShared('response')->getContent(); + $response = $this->di->getShared('response'); + + return $response->getContent(); } /** @@ -247,6 +282,9 @@ public function getContent() */ public function assertResponseContentContains($string) { - $this->assertContains($string, $this->getContent()); + $this->assertContains( + $string, + $this->getContent() + ); } } diff --git a/Library/Phalcon/Traits/ConfigurableTrait.php b/Library/Phalcon/Traits/ConfigurableTrait.php index 353e98fbc..f4672fd8a 100644 --- a/Library/Phalcon/Traits/ConfigurableTrait.php +++ b/Library/Phalcon/Traits/ConfigurableTrait.php @@ -48,7 +48,9 @@ protected function setParameters($parameters) } if (!is_array($parameters) && !($parameters instanceof Traversable)) { - throw new InvalidArgumentException('The $parameters argument must be either an array or Traversable'); + throw new InvalidArgumentException( + 'The $parameters argument must be either an array or Traversable' + ); } foreach ($parameters as $key => $value) { diff --git a/Library/Phalcon/Traits/EventManagerAwareTrait.php b/Library/Phalcon/Traits/EventManagerAwareTrait.php index 681a6e4bb..b34489de7 100644 --- a/Library/Phalcon/Traits/EventManagerAwareTrait.php +++ b/Library/Phalcon/Traits/EventManagerAwareTrait.php @@ -54,10 +54,12 @@ public function setEventsManager(EventsManager $manager) */ public function getEventsManager() { + $di = Di::getDefault(); + if (!empty($this->eventsManager)) { $manager = $this->eventsManager; - } elseif (Di::getDefault()->has('eventsManager')) { - $manager = Di::getDefault()->get('eventsManager'); + } elseif ($di->has('eventsManager')) { + $manager = $di->get('eventsManager'); } if (isset($manager) && $manager instanceof EventsManager) { diff --git a/Library/Phalcon/Translate/Adapter/CsvMulti.php b/Library/Phalcon/Translate/Adapter/CsvMulti.php index 907b51945..1ceac8ec5 100644 --- a/Library/Phalcon/Translate/Adapter/CsvMulti.php +++ b/Library/Phalcon/Translate/Adapter/CsvMulti.php @@ -11,18 +11,18 @@ class CsvMulti extends Csv implements AdapterInterface, \ArrayAccess /** * @var array */ - private $locales = array(); - + private $locales = []; + /** * @var string */ private $locale = null; - + /** * @var string */ - private $indexes = array(); - + private $indexes = []; + /** * Load translates from file * @@ -38,13 +38,16 @@ private function _load($file, $length, $delimiter, $enclosure) { // @codingStandardsIgnoreEnd $fileHandler = fopen($file, "rb"); - + if (gettype($fileHandler) !== "resource") { - throw new Exception("Error opening translation file '" . $file . "'"); + throw new Exception( + "Error opening translation file '" . $file . "'" + ); } $line = 0; - $locales = array(); + $locales = []; + while ($data = fgetcsv($fileHandler, $length, $delimiter, $enclosure)) { if ($line++ == 0) { // first csv line @@ -56,8 +59,10 @@ private function _load($file, $length, $delimiter, $enclosure) } else { // the first row is the translation index (label) $index = array_shift($data); + // store this index internally $this->indexes[] = $index; + // the first element is removed as well, so the pos is according to the first line foreach ($data as $pos => $translation) { $this->_translate[$this->locales[$pos]][$index] = $translation; @@ -71,6 +76,7 @@ private function _load($file, $length, $delimiter, $enclosure) /** * Sets locale information, according to one from the header row of the source csv * Set it to false for enabling the "no translation mode" + * * * // Set locale to Dutch * $adapter->setLocale('nl_NL'); @@ -79,11 +85,14 @@ private function _load($file, $length, $delimiter, $enclosure) public function setLocale($locale) { if ($locale !== false && !array_key_exists($locale, $this->_translate)) { - throw new Exception("The locale '{$locale}' is not available in the data source."); + throw new Exception( + "The locale '{$locale}' is not available in the data source." + ); + return false; - } else { - return $this->locale = $locale; } + + return $this->locale = $locale; } /** @@ -113,7 +122,11 @@ public function exists($index) if (is_null($this->locale)) { throw new Exception('The locale must have been defined.'); } - return in_array($index, $this->getIndexes()); + + return in_array( + $index, + $this->getIndexes() + ); } /** diff --git a/Library/Phalcon/Translate/Adapter/Database.php b/Library/Phalcon/Translate/Adapter/Database.php index 5126a711f..c5f528e89 100644 --- a/Library/Phalcon/Translate/Adapter/Database.php +++ b/Library/Phalcon/Translate/Adapter/Database.php @@ -88,13 +88,16 @@ public function __construct(array $options) */ public function query($translateKey, $placeholders = null) { - $options = $this->options; - $translation = $options['db']->fetchOne( + $translation = $this->options['db']->fetchOne( $this->stmtSelect, Db::FETCH_ASSOC, - ['language' => $options['language'], 'key_name' => $translateKey] + [ + 'language' => $this->options['language'], + 'key_name' => $translateKey, + ] ); - $value = empty($translation['value']) ? $translateKey : $translation['value']; + + $value = empty($translation['value']) ? $translateKey : $translation['value']; return $this->replacePlaceholders($value, $placeholders); } @@ -121,12 +124,13 @@ public function _($translateKey, $placeholders = null) */ public function exists($translateKey) { - $options = $this->options; - - $result = $options['db']->fetchOne( + $result = $this->options['db']->fetchOne( $this->stmtExists, Db::FETCH_ASSOC, - ['language' => $options['language'], 'key_name' => $translateKey] + [ + 'language' => $this->options['language'], + 'key_name' => $translateKey, + ] ); return !empty($result['count']); @@ -141,10 +145,13 @@ public function exists($translateKey) */ public function add($translateKey, $message) { - $options = $this->options; - $data = ['language' => $options['language'], 'key_name' => $translateKey, 'value' => $message]; + $data = [ + 'language' => $this->options['language'], + 'key_name' => $translateKey, + 'value' => $message, + ]; - return $options['db']->insert($options['table'], array_values($data), array_keys($data)); + return $this->options['db']->insert($this->options['table'], array_values($data), array_keys($data)); } /** @@ -158,10 +165,18 @@ public function update($translateKey, $message) { $options = $this->options; - return $options['db']->update($options['table'], ['value'], [$message], [ - 'conditions' => 'key_name = ? AND language = ?', - 'bind' => ['key' => $translateKey, 'lang' => $options['language']] - ]); + return $options['db']->update( + $options['table'], + ['value'], + [$message], + [ + 'conditions' => 'key_name = ? AND language = ?', + 'bind' => [ + 'key' => $translateKey, + 'lang' => $options['language'], + ] + ] + ); } /** @@ -177,7 +192,10 @@ public function delete($translateKey) return $options['db']->delete( $options['table'], 'key_name = :key AND language = :lang', - ['key' => $translateKey, 'lang' => $options['language']] + [ + 'key' => $translateKey, + 'lang' => $options['language'], + ] ); } diff --git a/Library/Phalcon/Translate/Adapter/Mongo.php b/Library/Phalcon/Translate/Adapter/Mongo.php index bedae69eb..6d05f2119 100644 --- a/Library/Phalcon/Translate/Adapter/Mongo.php +++ b/Library/Phalcon/Translate/Adapter/Mongo.php @@ -97,7 +97,13 @@ protected function getTranslations($translateKey) /** @var CollectionInterface $collection */ $collection = $this->collection; - return $collection::findFirst([['key' => $translateKey]]); + return $collection::findFirst( + [ + [ + 'key' => $translateKey, + ], + ] + ); } /** @@ -147,6 +153,7 @@ public function offsetExists($translateKey) public function offsetSet($translateKey, $message) { $translations = $this->getTranslations($translateKey); + $translations->{$this->language} = $message; return $translations->save(); @@ -172,6 +179,7 @@ public function offsetGet($translateKey) public function offsetUnset($translateKey) { $translations = $this->getTranslations($translateKey); + unset($translations->{$this->language}); return $translations->save(); diff --git a/Library/Phalcon/Translate/Adapter/Redis.php b/Library/Phalcon/Translate/Adapter/Redis.php index 88ff56b6a..81bf72251 100644 --- a/Library/Phalcon/Translate/Adapter/Redis.php +++ b/Library/Phalcon/Translate/Adapter/Redis.php @@ -123,7 +123,10 @@ public function add($translateKey, $message) $this->cache[$key][$index] = $message; - return $this->redis->set($key, serialize($this->cache[$key])); + return $this->redis->set( + $key, + serialize($this->cache[$key]) + ); } /** diff --git a/Library/Phalcon/Translate/Adapter/ResourceBundle.php b/Library/Phalcon/Translate/Adapter/ResourceBundle.php index b2a140224..7d174c1bf 100644 --- a/Library/Phalcon/Translate/Adapter/ResourceBundle.php +++ b/Library/Phalcon/Translate/Adapter/ResourceBundle.php @@ -55,7 +55,12 @@ public function __construct($options) } $this->options = $options; - $this->bundle = new \ResourceBundle($this->options['locale'], $this->options['bundle'], $this->fallback); + + $this->bundle = new \ResourceBundle( + $this->options['locale'], + $this->options['bundle'], + $this->fallback + ); parent::__construct($options); } @@ -86,7 +91,10 @@ public function query($index, $placeholders = null) return $index; } - return $this->replacePlaceholders($this->get($index, $this->bundle), $placeholders); + return $this->replacePlaceholders( + $this->get($index, $this->bundle), + $placeholders + ); } /** diff --git a/Library/Phalcon/Utils/ArrayUtils.php b/Library/Phalcon/Utils/ArrayUtils.php index be8f838d5..7e5ee9b44 100644 --- a/Library/Phalcon/Utils/ArrayUtils.php +++ b/Library/Phalcon/Utils/ArrayUtils.php @@ -43,13 +43,16 @@ class ArrayUtils public function iteratorToArray($iterator, $recursive = true) { if (!is_array($iterator) && !$iterator instanceof Traversable) { - throw new InvalidArgumentException(__METHOD__ . ' must be either an array or Traversable'); + throw new InvalidArgumentException( + __METHOD__ . ' must be either an array or Traversable' + ); } if (!$recursive) { if (is_array($iterator)) { return $iterator; } + return iterator_to_array($iterator); } @@ -58,21 +61,17 @@ public function iteratorToArray($iterator, $recursive = true) } $array = []; + foreach ($iterator as $key => $value) { if (is_scalar($value)) { $array[$key] = $value; - continue; - } - if ($value instanceof Traversable) { + } elseif ($value instanceof Traversable) { $array[$key] = $this->iteratorToArray($value, $recursive); - continue; - } - if (is_array($value)) { + } elseif (is_array($value)) { $array[$key] = $this->iteratorToArray($value, $recursive); - continue; + } else { + $array[$key] = $value; } - - $array[$key] = $value; } return $array; diff --git a/Library/Phalcon/Utils/Slug.php b/Library/Phalcon/Utils/Slug.php index cbb5bb03f..9472e695b 100644 --- a/Library/Phalcon/Utils/Slug.php +++ b/Library/Phalcon/Utils/Slug.php @@ -58,12 +58,21 @@ public static function generate($string, $replace = [], $delimiter = '-') // Better to replace given $replace array as index => value // Example $replace['ı' => 'i', 'İ' => 'i']; if (!empty($replace) && is_array($replace)) { - $string = str_replace(array_keys($replace), array_values($replace), $string); + $string = str_replace( + array_keys($replace), + array_values($replace), + $string + ); } $transliterator = Transliterator::create('Any-Latin; Latin-ASCII'); + $string = $transliterator->transliterate( - mb_convert_encoding(htmlspecialchars_decode($string), 'UTF-8', 'auto') + mb_convert_encoding( + htmlspecialchars_decode($string), + 'UTF-8', + 'auto' + ) ); self::restoreLocale($oldLocale); @@ -77,7 +86,15 @@ public static function generate($string, $replace = [], $delimiter = '-') protected static function restoreLocale($oldLocale) { if ((stripos($oldLocale, '=') > 0)) { - parse_str(str_replace(';', '&', $oldLocale), $loc); + parse_str( + str_replace( + ';', + '&', + $oldLocale + ), + $loc + ); + $oldLocale = array_values($loc); } diff --git a/Library/Phalcon/Validation/Validator/AlphaCompleteValidator.php b/Library/Phalcon/Validation/Validator/AlphaCompleteValidator.php index f569f6f50..9098498b7 100644 --- a/Library/Phalcon/Validation/Validator/AlphaCompleteValidator.php +++ b/Library/Phalcon/Validation/Validator/AlphaCompleteValidator.php @@ -23,13 +23,13 @@ public function validate(\Phalcon\Validation $validator, $attribute) { $value = $validator->getValue($attribute); - $allowPipes = (bool)$this->getOption('allowPipes'); + $allowPipes = (bool) $this->getOption('allowPipes'); $allowPipes = $allowPipes ? '|' : ''; - $allowBlackSlashes = (bool)$this->getOption('allowBackslashes'); + $allowBlackSlashes = (bool) $this->getOption('allowBackslashes'); $allowBlackSlashes = $allowBlackSlashes ? '\\\\' : ''; - $allowUrlChars = (bool)$this->getOption('allowUrlChars'); + $allowUrlChars = (bool) $this->getOption('allowUrlChars'); $allowUrlChars = $allowUrlChars ? '=#' : ''; if (!preg_match('/^([-\p{L}*0-9_+!.,:\/;' . $allowPipes . $allowBlackSlashes . $allowUrlChars @@ -51,28 +51,46 @@ public function validate(\Phalcon\Validation $validator, $attribute) $message = $this->getOption('message', $message); - $validator->appendMessage(new Message($message, $attribute, 'AlphaComplete')); + $validator->appendMessage( + new Message( + $message, + $attribute, + 'AlphaComplete' + ) + ); } - if ($min = (int)$this->getOption('min')) { + if ($min = (int) $this->getOption('min')) { if (strlen($value) < $min) { $messageMin = $this->getOption( 'messageMinimum', 'The value must contain at least ' . $min . ' characters.' ); - $validator->appendMessage(new Message($messageMin, $attribute, 'AlphaComplete')); + $validator->appendMessage( + new Message( + $messageMin, + $attribute, + 'AlphaComplete' + ) + ); } } - if ($max = (int)$this->getOption('max')) { + if ($max = (int) $this->getOption('max')) { if (strlen($value) > $max) { $messageMax = $this->getOption( 'messageMaximum', 'The value can contain maximum ' . $max . ' characters.' ); - $validator->appendMessage(new Message($messageMax, $attribute, 'AlphaComplete')); + $validator->appendMessage( + new Message( + $messageMax, + $attribute, + 'AlphaComplete' + ) + ); } } diff --git a/Library/Phalcon/Validation/Validator/AlphaNamesValidator.php b/Library/Phalcon/Validation/Validator/AlphaNamesValidator.php index 76b91ee56..c63e0b352 100644 --- a/Library/Phalcon/Validation/Validator/AlphaNamesValidator.php +++ b/Library/Phalcon/Validation/Validator/AlphaNamesValidator.php @@ -20,11 +20,11 @@ class AlphaNamesValidator extends Validator implements ValidatorInterface * * @return boolean */ - public function validate(\Phalcon\Validation $validator, $attribute) + public function validate(Validation $validator, $attribute) { $value = $validator->getValue($attribute); - $numbers = (bool)$this->getOption('numbers'); + $numbers = (bool) $this->getOption('numbers'); $numbers = $numbers ? '0-9' : ''; if (!preg_match('/^([-\p{L}' . $numbers . '\'_\s])+$/u', $value)) { @@ -40,7 +40,13 @@ public function validate(\Phalcon\Validation $validator, $attribute) } } - $validator->appendMessage(new Message($message, $attribute, 'AlphaNames')); + $validator->appendMessage( + new Message( + $message, + $attribute, + 'AlphaNames' + ) + ); } if ($min = (int)$this->getOption('min')) { @@ -50,23 +56,35 @@ public function validate(\Phalcon\Validation $validator, $attribute) 'The value must contain at least ' . $min . ' characters.' ); - $validator->appendMessage(new Message($messageMin, $attribute, 'AlphaNames')); + $validator->appendMessage( + new Message( + $messageMin, + $attribute, + 'AlphaNames' + ) + ); } } - if ($max = (int)$this->getOption('max')) { + if ($max = (int) $this->getOption('max')) { if (strlen($value) > $max) { $messageMax = $this->getOption( 'messageMaximum', 'The value can contain maximum ' . $max . ' characters.' ); - $validator->appendMessage(new Message($messageMax, $attribute, 'AlphaNames')); + $validator->appendMessage( + new Message( + $messageMax, + $attribute, + 'AlphaNames' + ) + ); + return false; } } - if (count($validator->getMessages())) { return false; } diff --git a/Library/Phalcon/Validation/Validator/AlphaNumericValidator.php b/Library/Phalcon/Validation/Validator/AlphaNumericValidator.php index 07f5944e2..50c064f4b 100644 --- a/Library/Phalcon/Validation/Validator/AlphaNumericValidator.php +++ b/Library/Phalcon/Validation/Validator/AlphaNumericValidator.php @@ -21,14 +21,14 @@ class AlphaNumericValidator extends Validator implements ValidatorInterface * * @return boolean */ - public function validate(\Phalcon\Validation $validator, $attribute) + public function validate(Validation $validator, $attribute) { $value = $validator->getValue($attribute); - $whiteSpace = (bool)$this->getOption('whiteSpace'); + $whiteSpace = (bool) $this->getOption('whiteSpace'); $whiteSpace = $whiteSpace ? '\s' : ''; - $underscore = (bool)$this->getOption('underscore'); + $underscore = (bool) $this->getOption('underscore'); $underscore = $underscore ? '_' : ''; if (!preg_match('/^([\p{L}0-9' . $whiteSpace . $underscore . '])+$/u', $value)) { @@ -46,7 +46,13 @@ public function validate(\Phalcon\Validation $validator, $attribute) } } - $validator->appendMessage(new Message($message, $attribute, 'AlphaNumeric')); + $validator->appendMessage( + new Message( + $message, + $attribute, + 'AlphaNumeric' + ) + ); } if ($min = (int)$this->getOption('min')) { @@ -56,7 +62,13 @@ public function validate(\Phalcon\Validation $validator, $attribute) 'The value must contain at least ' . $min . ' characters.' ); - $validator->appendMessage(new Message($messageMin, $attribute, 'AlphaNumeric')); + $validator->appendMessage( + new Message( + $messageMin, + $attribute, + 'AlphaNumeric' + ) + ); } } @@ -67,7 +79,13 @@ public function validate(\Phalcon\Validation $validator, $attribute) 'The value can contain maximum ' . $max . ' characters.' ); - $validator->appendMessage(new Message($messageMax, $attribute, 'AlphaNumeric')); + $validator->appendMessage( + new Message( + $messageMax, + $attribute, + 'AlphaNumeric' + ) + ); } } diff --git a/Library/Phalcon/Validation/Validator/ArrayInclusionIn.php b/Library/Phalcon/Validation/Validator/ArrayInclusionIn.php index 4a4407b19..89667ada9 100644 --- a/Library/Phalcon/Validation/Validator/ArrayInclusionIn.php +++ b/Library/Phalcon/Validation/Validator/ArrayInclusionIn.php @@ -25,17 +25,34 @@ public function validate(\Phalcon\Validation $validation, $attribute) $allowEmpty = $this->getOption('allowEmpty'); if ((empty($array) && !$allowEmpty) || empty($domain) || !is_array($array)) { - $validation->appendMessage(new Message('Invalid argument supplied', $attribute)); + $validation->appendMessage( + new Message( + 'Invalid argument supplied', + $attribute + ) + ); + return false; } foreach ($array as $item) { if (!in_array($item, $domain)) { - $message = $this->getOption('message', 'Values provided not exist in domain'); - $validation->appendMessage(new Message($message, $attribute)); + $message = $this->getOption( + 'message', + 'Values provided not exist in domain' + ); + + $validation->appendMessage( + new Message( + $message, + $attribute + ) + ); + return false; } } + return true; } } diff --git a/Library/Phalcon/Validation/Validator/CardNumber.php b/Library/Phalcon/Validation/Validator/CardNumber.php index d31837279..69a31ef5b 100644 --- a/Library/Phalcon/Validation/Validator/CardNumber.php +++ b/Library/Phalcon/Validation/Validator/CardNumber.php @@ -55,7 +55,12 @@ class CardNumber extends Validator */ public function validate(Validation $validation, $attribute) { - $value = preg_replace('/[^\d]/', '', $validation->getValue($attribute)); + $value = preg_replace( + '/[^\d]/', + '', + $validation->getValue($attribute) + ); + $message = ($this->hasOption('message')) ? $this->getOption('message') : 'Credit card number is invalid'; if ($this->hasOption('type')) { @@ -66,20 +71,30 @@ public function validate(Validation $validation, $attribute) $issuer = substr($value, 0, 2); $result = (true === in_array($issuer, [34, 37])); break; + case CardNumber::MASTERCARD: $issuer = substr($value, 0, 2); $result = (true === in_array($issuer, [51, 52, 53, 54, 55])); break; + case CardNumber::VISA: $issuer = $value[0]; $result = ($issuer == 4); break; + default: throw new ValidationException('Incorrect type specifier'); } if (false === $result) { - $validation->appendMessage(new Message($message, $attribute, 'CardNumber')); + $validation->appendMessage( + new Message( + $message, + $attribute, + 'CardNumber' + ) + ); + return false; } } @@ -92,15 +107,24 @@ public function validate(Validation $validation, $attribute) $temp = $value[$i]; } else { $temp = $value[$i] * 2; + if ($temp > 9) { $temp -= 9; } } + $checkSum += $temp; } if (($checkSum % 10) != 0) { - $validation->appendMessage(new Message($message, $attribute, 'CardNumber')); + $validation->appendMessage( + new Message( + $message, + $attribute, + 'CardNumber' + ) + ); + return false; } diff --git a/Library/Phalcon/Validation/Validator/ConfirmationOf.php b/Library/Phalcon/Validation/Validator/ConfirmationOf.php index d015ea917..7ba803868 100644 --- a/Library/Phalcon/Validation/Validator/ConfirmationOf.php +++ b/Library/Phalcon/Validation/Validator/ConfirmationOf.php @@ -70,7 +70,11 @@ public function validate(Validation $validation, $attribute) $message = ($this->hasOption('message') ? $this->getOption('message') : 'Value not confirmed'); $validation->appendMessage( - new Validation\Message($message, $attribute, 'ConfirmationOfValidator') + new Validation\Message( + $message, + $attribute, + 'ConfirmationOfValidator' + ) ); return false; diff --git a/Library/Phalcon/Validation/Validator/Db/Uniqueness.php b/Library/Phalcon/Validation/Validator/Db/Uniqueness.php index 9fe0e035f..b002ff462 100644 --- a/Library/Phalcon/Validation/Validator/Db/Uniqueness.php +++ b/Library/Phalcon/Validation/Validator/Db/Uniqueness.php @@ -50,8 +50,9 @@ * * Exclude option is optional. * - * If second parameter will be null (omitted) than validator will try to get database - * connection from default DI instance with \Phalcon\Di::getDefault()->get('db'); + * If second parameter will be null (omitted) than validator will try to get + * database connection from default DI instance with + * \Phalcon\Di::getDefault()->get('db'); */ class Uniqueness extends Validator @@ -83,26 +84,36 @@ public function __construct(array $options = [], DbConnection $db = null) } if (!$db instanceof DbConnection) { - throw new ValidationException('Validator Uniqueness require connection to database'); + throw new ValidationException( + 'Validator Uniqueness require connection to database' + ); } if (!$this->hasOption('table')) { - throw new ValidationException('Validator require table option to be set'); + throw new ValidationException( + 'Validator require table option to be set' + ); } if (!$this->hasOption('column')) { - throw new ValidationException('Validator require column option to be set'); + throw new ValidationException( + 'Validator require column option to be set' + ); } if ($this->hasOption('exclude')) { $exclude = $this->getOption('exclude'); if (!isset($exclude['column']) || empty($exclude['column'])) { - throw new ValidationException('Validator with "exclude" option require column option to be set'); + throw new ValidationException( + 'Validator with "exclude" option require column option to be set' + ); } if (!isset($exclude['value']) || empty($exclude['value'])) { - throw new ValidationException('Validator with "exclude" option require value option to be set'); + throw new ValidationException( + 'Validator with "exclude" option require value option to be set' + ); } } @@ -118,11 +129,17 @@ public function __construct(array $options = [], DbConnection $db = null) */ public function validate(Validation $validator, $attribute) { - $table = $this->db->escapeIdentifier($this->getOption('table')); - $column = $this->db->escapeIdentifier($this->getOption('column')); + $table = $this->db->escapeIdentifier( + $this->getOption('table') + ); + + $column = $this->db->escapeIdentifier( + $this->getOption('column') + ); if ($this->hasOption('exclude')) { $exclude = $this->getOption('exclude'); + $result = $this->db->fetchOne( sprintf( 'SELECT COUNT(*) AS count FROM %s WHERE %s = ? AND %s != ?', @@ -131,19 +148,38 @@ public function validate(Validation $validator, $attribute) $this->db->escapeIdentifier($exclude['column']) ), Db::FETCH_ASSOC, - [$validator->getValue($attribute), $exclude['value']] + [ + $validator->getValue($attribute), + $exclude['value'], + ] ); } else { $result = $this->db->fetchOne( - sprintf('SELECT COUNT(*) AS count FROM %s WHERE %s = ?', $table, $column), + sprintf( + 'SELECT COUNT(*) AS count FROM %s WHERE %s = ?', + $table, + $column + ), Db::FETCH_ASSOC, - [$validator->getValue($attribute)] + [ + $validator->getValue($attribute), + ] ); } if ($result['count']) { - $message = $this->getOption('message', 'Already taken. Choose another!'); - $validator->appendMessage(new Message($message, $attribute, 'Uniqueness')); + $message = $this->getOption( + 'message', + 'Already taken. Choose another!' + ); + + $validator->appendMessage( + new Message( + $message, + $attribute, + 'Uniqueness' + ) + ); return false; } diff --git a/Library/Phalcon/Validation/Validator/Decimal.php b/Library/Phalcon/Validation/Validator/Decimal.php index 6f6ba589b..2e9bea3a0 100644 --- a/Library/Phalcon/Validation/Validator/Decimal.php +++ b/Library/Phalcon/Validation/Validator/Decimal.php @@ -42,12 +42,15 @@ public function validate(Validation $validation, $attribute) { $value = $validation->getValue($attribute); $field = $this->getOption('label'); + if (empty($field)) { $validation->getLabel($attribute); } if (false === $this->hasOption('places')) { - throw new ValidationException('A number of decimal places must be set'); + throw new ValidationException( + 'A number of decimal places must be set' + ); } if ($this->hasOption('digits')) { @@ -62,10 +65,12 @@ public function validate(Validation $validation, $attribute) $decimal = $this->getOption('point'); } else { // Get the decimal point for the current locale - list($decimal) = array_values(localeconv()); + list($decimal) = array_values( + localeconv() + ); } - $result = (boolean) preg_match( + $result = (bool) preg_match( sprintf( '#^[+-]?[0-9]%s%s[0-9]{%d}$#', $digits, @@ -77,13 +82,23 @@ public function validate(Validation $validation, $attribute) if (!$result) { $message = $this->getOption('message'); - $replacePairs = [':field' => $field]; + + $replacePairs = [ + ':field' => $field, + ]; if (empty($message)) { $message = ':field must contain valid decimal value'; } - $validation->appendMessage(new Message(strtr($message, $replacePairs), $attribute, 'Decimal')); + $validation->appendMessage( + new Message( + strtr($message, $replacePairs), + $attribute, + 'Decimal' + ) + ); + return false; } diff --git a/Library/Phalcon/Validation/Validator/Iban.php b/Library/Phalcon/Validation/Validator/Iban.php index bed6b673d..50938ddda 100644 --- a/Library/Phalcon/Validation/Validator/Iban.php +++ b/Library/Phalcon/Validation/Validator/Iban.php @@ -78,7 +78,7 @@ class Iban extends Validator protected $sepaCountries = [ 'AT', 'BE', 'BG', 'CY', 'CZ', 'DK', 'FO', 'GL', 'EE', 'FI', 'FR', 'DE', 'GI', 'GR', 'HU', 'IS', 'IE', 'IT', 'LV', 'LI', 'LT', 'LU', 'MT', 'MC', - 'NL', 'NO', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'CH', 'GB' + 'NL', 'NO', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'CH', 'GB', ]; /** @@ -227,7 +227,12 @@ public function validate(Validation $validation, $attribute) $code = $this->prepareCode($attribute); $replacePairs = [":field"=> $label]; - $message = $this->prepareMessage($validation, $attribute, "Iban", $messageCode); + $message = $this->prepareMessage( + $validation, + $attribute, + "Iban", + $messageCode + ); $validation->appendMessage( new Message( @@ -237,6 +242,7 @@ public function validate(Validation $validation, $attribute) $code ) ); + return false; } @@ -272,11 +278,10 @@ protected function getErrorMessageCode(Validation $validation, $attribute) } $format = substr($value, 4) . substr($value, 0, 4); + $format = str_replace( - ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', - 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'], - ['10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', - '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35'], + range('A', 'Z'), + range(10, 35), $format ); diff --git a/Library/Phalcon/Validation/Validator/IpValidator.php b/Library/Phalcon/Validation/Validator/IpValidator.php index 349660d20..17b59fe27 100644 --- a/Library/Phalcon/Validation/Validator/IpValidator.php +++ b/Library/Phalcon/Validation/Validator/IpValidator.php @@ -27,7 +27,9 @@ public function validate(Validation $validator, $attribute) 'The IP is not valid' ); - $validator->appendMessage(new Message($message, $attribute, 'Ip')); + $validator->appendMessage( + new Message($message, $attribute, 'Ip') + ); return false; } diff --git a/Library/Phalcon/Validation/Validator/MongoId.php b/Library/Phalcon/Validation/Validator/MongoId.php index 0cbdc637f..59052bf71 100644 --- a/Library/Phalcon/Validation/Validator/MongoId.php +++ b/Library/Phalcon/Validation/Validator/MongoId.php @@ -50,8 +50,16 @@ public function validate(Validation $validation, $attribute) if (!$result) { $message = ($this->hasOption('message')) ? $this->getOption('message') : 'MongoId is not valid'; - $validation->appendMessage(new Message($message, $attribute, 'MongoId')); + + $validation->appendMessage( + new Message( + $message, + $attribute, + 'MongoId' + ) + ); } + return $result; } } diff --git a/Library/Phalcon/Validation/Validator/NumericValidator.php b/Library/Phalcon/Validation/Validator/NumericValidator.php index d0b18cdb8..088d33036 100644 --- a/Library/Phalcon/Validation/Validator/NumericValidator.php +++ b/Library/Phalcon/Validation/Validator/NumericValidator.php @@ -20,14 +20,14 @@ class NumericValidator extends Validator implements ValidatorInterface * * @return boolean */ - public function validate(\Phalcon\Validation $validator, $attribute) + public function validate(Validation $validator, $attribute) { $value = $validator->getValue($attribute); - $allowFloat = (bool)$this->getOption('allowFloat'); + $allowFloat = (bool) $this->getOption('allowFloat'); $allowFloat = $allowFloat ? '.,' : ''; - $allowSign = (bool)$this->getOption('allowSign'); + $allowSign = (bool) $this->getOption('allowSign'); $allowSign = $allowSign ? '[-+]?' : ''; $allowSignMessage = $allowSign ? 'signed' : 'unsigned'; @@ -38,7 +38,13 @@ public function validate(\Phalcon\Validation $validator, $attribute) 'The value must be a valid ' . $allowSignMessage . ' floating number' ); - $validator->appendMessage(new Message($message, $attribute, 'Numeric')); + $validator->appendMessage( + new Message( + $message, + $attribute, + 'Numeric' + ) + ); } } else { if (!preg_match('/^(' . $allowSign . '[0-9])+$/u', $value)) { @@ -47,7 +53,13 @@ public function validate(\Phalcon\Validation $validator, $attribute) 'The value must be a valid ' . $allowSignMessage . ' integer number' ); - $validator->appendMessage(new Message($message, $attribute, 'Numeric')); + $validator->appendMessage( + new Message( + $message, + $attribute, + 'Numeric' + ) + ); } } @@ -58,7 +70,13 @@ public function validate(\Phalcon\Validation $validator, $attribute) 'The value must be at least ' . $min ); - $validator->appendMessage(new Message($messageMin, $attribute, 'Numeric')); + $validator->appendMessage( + new Message( + $messageMin, + $attribute, + 'Numeric' + ) + ); } } @@ -69,7 +87,13 @@ public function validate(\Phalcon\Validation $validator, $attribute) 'The value must be lower than ' . $max ); - $validator->appendMessage(new Message($messageMax, $attribute, 'Numeric')); + $validator->appendMessage( + new Message( + $messageMax, + $attribute, + 'Numeric' + ) + ); } } diff --git a/Library/Phalcon/Validation/Validator/PasswordStrength.php b/Library/Phalcon/Validation/Validator/PasswordStrength.php index 308a7d00a..a5df6b1b6 100644 --- a/Library/Phalcon/Validation/Validator/PasswordStrength.php +++ b/Library/Phalcon/Validation/Validator/PasswordStrength.php @@ -36,7 +36,6 @@ */ class PasswordStrength extends Validation\Validator { - const MIN_VALID_SCORE = 2; /** @@ -64,7 +63,11 @@ public function validate(Validation $validation, $attribute) $message = ($this->hasOption('message') ? $this->getOption('message') : 'Password too weak'); $validation->appendMessage( - new Validation\Message($message, $attribute, 'PasswordStrengthValidator') + new Validation\Message( + $message, + $attribute, + 'PasswordStrengthValidator' + ) ); return false; diff --git a/Library/Phalcon/Validation/Validator/ReCaptcha.php b/Library/Phalcon/Validation/Validator/ReCaptcha.php index 172f87dc2..d7e7d8938 100644 --- a/Library/Phalcon/Validation/Validator/ReCaptcha.php +++ b/Library/Phalcon/Validation/Validator/ReCaptcha.php @@ -40,13 +40,18 @@ * * use Phalcon\Validation\Validator; * - * $validator->add('g-recaptcha-response', new Validator([ - * 'message' => 'The captcha is not valid', - * 'secret' => 'your_site_key', - * 'score' => 0.5, //optional score check for ReCaptcha v3 - * 'ip' => 'optional client ip address override', - * 'action' => 'optional action name to verify for ReCaptcha v3' - * ])); + * $validator->add( + * 'g-recaptcha-response', + * new Validator( + * [ + * 'message' => 'The captcha is not valid', + * 'secret' => 'your_site_key', + * 'score' => 0.5, //optional score check for ReCaptcha v3 + * 'ip' => 'optional client ip address override', + * 'action' => 'optional action name to verify for ReCaptcha v3', + * ], + * ) + * ); * * * @link https://developers.google.com/recaptcha/intro @@ -61,6 +66,7 @@ class ReCaptcha extends Validator /** * Response error code reference + * * @var array $messages */ protected $messages = [ @@ -83,6 +89,7 @@ public function validate(Validation $validation, $attribute) $secret = $this->getOption('secret'); $value = $validation->getValue($attribute); $request = $validation->getDI()->get('request'); + if ($this->hasOption('ip')) { $remoteIp = $this->getOption('ip'); } else { @@ -91,15 +98,24 @@ public function validate(Validation $validation, $attribute) if (!empty($value)) { $curl = curl_init(self::RECAPTCHA_URL); - curl_setopt_array($curl, [ - CURLOPT_RETURNTRANSFER => true, - CURLOPT_POSTFIELDS => [ - 'secret' => $secret, - 'response' => $value, - 'remoteip' => $remoteIp + + curl_setopt_array( + $curl, + [ + CURLOPT_RETURNTRANSFER => true, + CURLOPT_POSTFIELDS => [ + 'secret' => $secret, + 'response' => $value, + 'remoteip' => $remoteIp, + ], ] - ]); - $response = json_decode(curl_exec($curl), true); + ); + + $response = json_decode( + curl_exec($curl), + true + ); + curl_close($curl); } @@ -116,6 +132,7 @@ public function validate(Validation $validation, $attribute) $message = $this->getOption('message'); $replacePairs = [':field', $label]; + if (empty($message) && !empty($response['error-codes'])) { $message = $this->messages[$response['error-codes']]; } @@ -124,7 +141,14 @@ public function validate(Validation $validation, $attribute) $message = $validation->getDefaultMessage('ReCaptcha'); } - $validation->appendMessage(new Message(strtr($message, $replacePairs), $attribute, 'ReCaptcha')); + $validation->appendMessage( + new Message( + strtr($message, $replacePairs), + $attribute, + 'ReCaptcha' + ) + ); + return false; }