diff --git a/.gitignore b/.gitignore index 42ec4541e..dadd0895e 100644 --- a/.gitignore +++ b/.gitignore @@ -11,4 +11,4 @@ codeception.yml tests/aerospike.suite.yml tests/unit.suite.5.yml tests/unit.suite.yml -tests/unit5x.suite.yml \ No newline at end of file +tests/unit5x.suite.yml diff --git a/Library/Phalcon/Acl/Adapter/Database.php b/Library/Phalcon/Acl/Adapter/Database.php index 35a8ddf10..1eab8a038 100644 --- a/Library/Phalcon/Acl/Adapter/Database.php +++ b/Library/Phalcon/Acl/Adapter/Database.php @@ -92,12 +92,24 @@ public function __construct(array $options) $this->connection = $options['db']; - foreach (['roles', 'resources', 'resourcesAccesses', 'accessList', 'rolesInherits'] as $table) { + $tables = [ + 'roles', + 'resources', + 'resourcesAccesses', + 'accessList', + 'rolesInherits', + ]; + + foreach ($tables as $table) { 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->{$table} = $this->connection->escapeIdentifier($options[$table]); + $this->{$table} = $this->connection->escapeIdentifier( + $options[$table] + ); } } @@ -118,33 +130,51 @@ public function __construct(array $options) public function addRole($role, $accessInherits = null) { if (is_string($role)) { - $role = new Role($role, ucwords($role) . ' Role'); + $role = new Role( + $role, + ucwords($role) . ' Role' + ); } if (!$role instanceof RoleInterface) { - throw new Exception('Role must be either an string or implement RoleInterface'); + throw new Exception( + 'Role must be either an string or implement RoleInterface' + ); } $exists = $this->connection->fetchOne( "SELECT COUNT(*) FROM {$this->roles} WHERE name = ?", null, - [$role->getName()] + [ + $role->getName(), + ] ); if (!$exists[0]) { $this->connection->execute( "INSERT INTO {$this->roles} VALUES (?, ?)", - [$role->getName(), $role->getDescription()] + [ + $role->getName(), + $role->getDescription(), + ] ); $this->connection->execute( "INSERT INTO {$this->accessList} VALUES (?, ?, ?, ?)", - [$role->getName(), '*', '*', $this->_defaultAccess] + [ + $role->getName(), + '*', + '*', + $this->_defaultAccess, + ] ); } if ($accessInherits) { - return $this->addInherit($role->getName(), $accessInherits); + return $this->addInherit( + $role->getName(), + $accessInherits + ); } return true; @@ -160,21 +190,37 @@ public function addRole($role, $accessInherits = null) public function addInherit($roleName, $roleToInherit) { $sql = "SELECT COUNT(*) FROM {$this->roles} WHERE name = ?"; - $exists = $this->connection->fetchOne($sql, null, [$roleName]); + + $exists = $this->connection->fetchOne( + $sql, + null, + [ + $roleName, + ] + ); + if (!$exists[0]) { - throw new Exception("Role '{$roleName}' does not exist in the role list"); + throw new Exception( + "Role '{$roleName}' does not exist in the role list" + ); } $exists = $this->connection->fetchOne( "SELECT COUNT(*) FROM {$this->rolesInherits} WHERE roles_name = ? AND roles_inherit = ?", null, - [$roleName, $roleToInherit] + [ + $roleName, + $roleToInherit, + ] ); if (!$exists[0]) { $this->connection->execute( "INSERT INTO {$this->rolesInherits} VALUES (?, ?)", - [$roleName, $roleToInherit] + [ + $roleName, + $roleToInherit, + ] ); } } @@ -190,7 +236,9 @@ public function isRole($roleName) $exists = $this->connection->fetchOne( "SELECT COUNT(*) FROM {$this->roles} WHERE name = ?", null, - [$roleName] + [ + $roleName, + ] ); return (bool) $exists[0]; @@ -207,7 +255,9 @@ public function isResource($resourceName) $exists = $this->connection->fetchOne( "SELECT COUNT(*) FROM {$this->resources} WHERE name = ?", null, - [$resourceName] + [ + $resourceName, + ] ); return (bool) $exists[0]; @@ -238,18 +288,26 @@ public function addResource($resource, $accessList = null) $exists = $this->connection->fetchOne( "SELECT COUNT(*) FROM {$this->resources} WHERE name = ?", null, - [$resource->getName()] + [ + $resource->getName(), + ] ); if (!$exists[0]) { $this->connection->execute( "INSERT INTO {$this->resources} VALUES (?, ?)", - [$resource->getName(), $resource->getDescription()] + [ + $resource->getName(), + $resource->getDescription(), + ] ); } if ($accessList) { - return $this->addResourceAccess($resource->getName(), $accessList); + return $this->addResourceAccess( + $resource->getName(), + $accessList + ); } return true; @@ -266,7 +324,9 @@ public function addResource($resource, $accessList = null) public function addResourceAccess($resourceName, $accessList) { if (!$this->isResource($resourceName)) { - throw new Exception("Resource '{$resourceName}' does not exist in ACL"); + throw new Exception( + "Resource '{$resourceName}' does not exist in ACL" + ); } $sql = "SELECT COUNT(*) FROM {$this->resourcesAccesses} WHERE resources_name = ? AND access_name = ?"; @@ -276,11 +336,22 @@ public function addResourceAccess($resourceName, $accessList) } foreach ($accessList as $accessName) { - $exists = $this->connection->fetchOne($sql, null, [$resourceName, $accessName]); + $exists = $this->connection->fetchOne( + $sql, + null, + [ + $resourceName, + $accessName, + ] + ); + if (!$exists[0]) { $this->connection->execute( 'INSERT INTO ' . $this->resourcesAccesses . ' VALUES (?, ?)', - [$resourceName, $accessName] + [ + $resourceName, + $accessName, + ] ); } } @@ -296,10 +367,19 @@ public function addResourceAccess($resourceName, $accessList) public function getResources() { $resources = []; - $sql = "SELECT * FROM {$this->resources}"; - foreach ($this->connection->fetchAll($sql, Db::FETCH_ASSOC) as $row) { - $resources[] = new Resource($row['name'], $row['description']); + $sql = "SELECT * FROM {$this->resources}"; + + $rows = $this->connection->fetchAll( + $sql, + Db::FETCH_ASSOC + ); + + foreach ($rows as $row) { + $resources[] = new Resource( + $row['name'], + $row['description'] + ); } return $resources; @@ -315,8 +395,16 @@ public function getRoles() $roles = []; $sql = "SELECT * FROM {$this->roles}"; - foreach ($this->connection->fetchAll($sql, Db::FETCH_ASSOC) as $row) { - $roles[] = new Role($row['name'], $row['description']); + $rows = $this->connection->fetchAll( + $sql, + Db::FETCH_ASSOC + ); + + foreach ($rows as $row) { + $roles[] = new Role( + $row['name'], + $row['description'] + ); } return $roles; @@ -402,29 +490,42 @@ public function deny($roleName, $resourceName, $access, $func = null) */ public function isAllowed($role, $resource, $access, array $parameters = null) { - $sql = implode(' ', [ - "SELECT " . $this->connection->escapeIdentifier('allowed') . " FROM {$this->accessList} AS a", - // role_name in: - 'WHERE roles_name IN (', - // given 'role'-parameter - 'SELECT ? ', - // inherited role_names - "UNION SELECT roles_inherit FROM {$this->rolesInherits} WHERE roles_name = ?", - // or 'any' - "UNION SELECT '*'", - ')', - // resources_name should be given one or 'any' - "AND resources_name IN (?, '*')", - // access_name should be given one or 'any' - "AND access_name IN (?, '*')", - // order be the sum of bools for 'literals' before 'any' - "ORDER BY ".$this->connection->escapeIdentifier('allowed')." DESC", - // get only one... - 'LIMIT 1' - ]); + $sql = implode( + ' ', + [ + "SELECT " . $this->connection->escapeIdentifier('allowed') . " FROM {$this->accessList} AS a", + // role_name in: + 'WHERE roles_name IN (', + // given 'role'-parameter + 'SELECT ? ', + // inherited role_names + "UNION SELECT roles_inherit FROM {$this->rolesInherits} WHERE roles_name = ?", + // or 'any' + "UNION SELECT '*'", + ')', + // resources_name should be given one or 'any' + "AND resources_name IN (?, '*')", + // access_name should be given one or 'any' + "AND access_name IN (?, '*')", + // order be the sum of bools for 'literals' before 'any' + "ORDER BY " . $this->connection->escapeIdentifier('allowed') . " DESC", + // get only one... + 'LIMIT 1', + ] + ); // fetch one entry... - $allowed = $this->connection->fetchOne($sql, Db::FETCH_NUM, [$role, $role, $resource, $access]); + $allowed = $this->connection->fetchOne( + $sql, + Db::FETCH_NUM, + [ + $role, + $role, + $resource, + $access, + ] + ); + if (is_array($allowed)) { return (bool) $allowed[0]; } @@ -432,7 +533,6 @@ public function isAllowed($role, $resource, $access, array $parameters = null) /** * Return the default access action */ - return $this->_defaultAccess; } @@ -475,7 +575,16 @@ protected function insertOrUpdateAccess($roleName, $resourceName, $accessName, $ */ if ($resourceName !== '*' && $accessName !== '*') { $sql = "SELECT COUNT(*) FROM {$this->resourcesAccesses} WHERE resources_name = ? AND access_name = ?"; - $exists = $this->connection->fetchOne($sql, null, [$resourceName, $accessName]); + + $exists = $this->connection->fetchOne( + $sql, + null, + [ + $resourceName, + $accessName, + ] + ); + if (!$exists[0]) { throw new Exception( "Access '{$accessName}' does not exist in resource '{$resourceName}' in ACL" @@ -488,14 +597,36 @@ protected function insertOrUpdateAccess($roleName, $resourceName, $accessName, $ */ $sql = "SELECT COUNT(*) FROM {$this->accessList} " . " WHERE roles_name = ? AND resources_name = ? AND access_name = ?"; - $exists = $this->connection->fetchOne($sql, null, [$roleName, $resourceName, $accessName]); + + $exists = $this->connection->fetchOne( + $sql, + null, + [ + $roleName, + $resourceName, + $accessName, + ] + ); + if (!$exists[0]) { $sql = "INSERT INTO {$this->accessList} VALUES (?, ?, ?, ?)"; - $params = [$roleName, $resourceName, $accessName, $action]; + + $params = [ + $roleName, + $resourceName, + $accessName, + $action, + ]; } else { $sql = "UPDATE {$this->accessList} SET allowed = ? " . "WHERE roles_name = ? AND resources_name = ? AND access_name = ?"; - $params = [$action, $roleName, $resourceName, $accessName]; + + $params = [ + $action, + $roleName, + $resourceName, + $accessName, + ]; } $this->connection->execute($sql, $params); @@ -505,10 +636,29 @@ protected function insertOrUpdateAccess($roleName, $resourceName, $accessName, $ */ $sql = "SELECT COUNT(*) FROM {$this->accessList} " . "WHERE roles_name = ? AND resources_name = ? AND access_name = ?"; - $exists = $this->connection->fetchOne($sql, null, [$roleName, $resourceName, '*']); + + $exists = $this->connection->fetchOne( + $sql, + null, + [ + $roleName, + $resourceName, + '*', + ] + ); + if (!$exists[0]) { $sql = "INSERT INTO {$this->accessList} VALUES (?, ?, ?, ?)"; - $this->connection->execute($sql, [$roleName, $resourceName, '*', $this->_defaultAccess]); + + $this->connection->execute( + $sql, + [ + $roleName, + $resourceName, + '*', + $this->_defaultAccess, + ] + ); } return true; @@ -526,7 +676,9 @@ protected function insertOrUpdateAccess($roleName, $resourceName, $accessName, $ protected function allowOrDeny($roleName, $resourceName, $access, $action) { if (!$this->isRole($roleName)) { - throw new Exception("Role '{$roleName}' does not exist in the list"); + throw new Exception( + "Role '{$roleName}' does not exist in the list" + ); } if (!is_array($access)) { @@ -534,7 +686,12 @@ protected function allowOrDeny($roleName, $resourceName, $access, $action) } foreach ($access as $accessName) { - $this->insertOrUpdateAccess($roleName, $resourceName, $accessName, $action); + $this->insertOrUpdateAccess( + $roleName, + $resourceName, + $accessName, + $action + ); } } } diff --git a/Library/Phalcon/Acl/Adapter/Mongo.php b/Library/Phalcon/Acl/Adapter/Mongo.php index b7bc8c077..de991db8b 100644 --- a/Library/Phalcon/Acl/Adapter/Mongo.php +++ b/Library/Phalcon/Acl/Adapter/Mongo.php @@ -94,32 +94,49 @@ public function __construct($options) public function addRole($role, $accessInherits = null) { if (is_string($role)) { - $role = new Role($role, ucwords($role) . ' Role'); + $role = new Role( + $role, + ucwords($role) . ' Role' + ); } if (!$role instanceof RoleInterface) { - throw new Exception('Role must be either an string or implement RoleInterface'); + throw new Exception( + 'Role must be either an string or implement RoleInterface' + ); } $roles = $this->getCollection('roles'); - $exists = $roles->count(['name' => $role->getName()]); + + $exists = $roles->count( + [ + 'name' => $role->getName(), + ] + ); if (!$exists) { - $roles->insert([ - 'name' => $role->getName(), - 'description' => $role->getDescription() - ]); - - $this->getCollection('accessList')->insert([ - 'roles_name' => $role->getName(), - 'resources_name' => '*', - 'access_name' => '*', - 'allowed' => $this->_defaultAccess - ]); + $roles->insert( + [ + 'name' => $role->getName(), + 'description' => $role->getDescription(), + ] + ); + + $this->getCollection('accessList')->insert( + [ + 'roles_name' => $role->getName(), + 'resources_name' => '*', + 'access_name' => '*', + 'allowed' => $this->_defaultAccess, + ] + ); } if ($accessInherits) { - return $this->addInherit($role->getName(), $accessInherits); + return $this->addInherit( + $role->getName(), + $accessInherits + ); } return true; @@ -184,16 +201,26 @@ public function addResource($resource, $accessList = null) $resources = $this->getCollection('resources'); - $exists = $resources->count(['name' => $resource->getName()]); + $exists = $resources->count( + [ + 'name' => $resource->getName(), + ] + ); + if (!$exists) { - $resources->insert([ - 'name' => $resource->getName(), - 'description' => $resource->getDescription() - ]); + $resources->insert( + [ + 'name' => $resource->getName(), + 'description' => $resource->getDescription(), + ] + ); } if ($accessList) { - return $this->addResourceAccess($resource->getName(), $accessList); + return $this->addResourceAccess( + $resource->getName(), + $accessList + ); } return true; @@ -210,7 +237,9 @@ public function addResource($resource, $accessList = null) public function addResourceAccess($resourceName, $accessList) { if (!$this->isResource($resourceName)) { - throw new Exception("Resource '" . $resourceName . "' does not exist in ACL"); + throw new Exception( + "Resource '" . $resourceName . "' does not exist in ACL" + ); } $resourcesAccesses = $this->getCollection('resourcesAccesses'); @@ -220,15 +249,20 @@ public function addResourceAccess($resourceName, $accessList) } foreach ($accessList as $accessName) { - $exists = $resourcesAccesses->count([ - 'resources_name' => $resourceName, - 'access_name' => $accessName - ]); - if (!$exists) { - $resourcesAccesses->insert([ + $exists = $resourcesAccesses->count( + [ 'resources_name' => $resourceName, - 'access_name' => $accessName - ]); + 'access_name' => $accessName, + ] + ); + + if (!$exists) { + $resourcesAccesses->insert( + [ + 'resources_name' => $resourceName, + 'access_name' => $accessName, + ] + ); } } @@ -245,7 +279,10 @@ public function getResources() $resources = []; foreach ($this->getCollection('resources')->find() as $row) { - $resources[] = new Resource($row['name'], $row['description']); + $resources[] = new Resource( + $row['name'], + $row['description'] + ); } return $resources; @@ -261,7 +298,10 @@ public function getRoles() $roles = []; foreach ($this->getCollection('roles')->find() as $row) { - $roles[] = new Role($row['name'], $row['description']); + $roles[] = new Role( + $row['name'], + $row['description'] + ); } return $roles; @@ -351,11 +391,14 @@ public function deny($roleName, $resourceName, $access, $func = null) public function isAllowed($role, $resource, $access, array $parameters = null) { $accessList = $this->getCollection('accessList'); - $access = $accessList->findOne([ - 'roles_name' => $role, - 'resources_name' => $resource, - 'access_name' => $access - ]); + + $access = $accessList->findOne( + [ + 'roles_name' => $role, + 'resources_name' => $resource, + 'access_name' => $access, + ] + ); if (is_array($access)) { return (bool) $access['allowed']; @@ -364,11 +407,13 @@ public function isAllowed($role, $resource, $access, array $parameters = null) /** * Check if there is an common rule for that resource */ - $access = $accessList->findOne([ - 'roles_name' => $role, - 'resources_name' => $resource, - 'access_name' => '*' - ]); + $access = $accessList->findOne( + [ + 'roles_name' => $role, + 'resources_name' => $resource, + 'access_name' => '*', + ] + ); if (is_array($access)) { return (bool) $access['allowed']; @@ -425,10 +470,12 @@ protected function insertOrUpdateAccess($roleName, $resourceName, $accessName, $ /** * Check if the access is valid in the resource */ - $exists = $this->getCollection('resourcesAccesses')->count([ - 'resources_name' => $resourceName, - 'access_name' => $accessName - ]); + $exists = $this->getCollection('resourcesAccesses')->count( + [ + 'resources_name' => $resourceName, + 'access_name' => $accessName, + ] + ); if (!$exists) { throw new Exception( @@ -438,40 +485,49 @@ protected function insertOrUpdateAccess($roleName, $resourceName, $accessName, $ $accessList = $this->getCollection('accessList'); - $access = $accessList->findOne([ - 'roles_name' => $roleName, - 'resources_name' => $resourceName, - 'access_name' => $accessName - ]); - - if (!$access) { - $accessList->insert([ + $access = $accessList->findOne( + [ 'roles_name' => $roleName, 'resources_name' => $resourceName, 'access_name' => $accessName, - 'allowed' => $action - ]); + ] + ); + + if (!$access) { + $accessList->insert( + [ + 'roles_name' => $roleName, + 'resources_name' => $resourceName, + 'access_name' => $accessName, + 'allowed' => $action, + ] + ); } else { $access['allowed'] = $action; + $accessList->save($access); } /** * Update the access '*' in access_list */ - $exists = $accessList->count([ - 'roles_name' => $roleName, - 'resources_name' => $resourceName, - 'access_name' => '*' - ]); - - if (!$exists) { - $accessList->insert([ + $exists = $accessList->count( + [ 'roles_name' => $roleName, 'resources_name' => $resourceName, 'access_name' => '*', - 'allowed' => $this->_defaultAccess - ]); + ] + ); + + if (!$exists) { + $accessList->insert( + [ + 'roles_name' => $roleName, + 'resources_name' => $resourceName, + 'access_name' => '*', + 'allowed' => $this->_defaultAccess, + ] + ); } return true; @@ -489,15 +545,24 @@ protected function insertOrUpdateAccess($roleName, $resourceName, $accessName, $ protected function allowOrDeny($roleName, $resourceName, $access, $action) { if (!$this->isRole($roleName)) { - throw new Exception('Role "' . $roleName . '" does not exist in the list'); + throw new Exception( + 'Role "' . $roleName . '" does not exist in the list' + ); } if (!is_array($access)) { - $access = [$access]; + $access = [ + $access, + ]; } foreach ($access as $accessName) { - $this->insertOrUpdateAccess($roleName, $resourceName, $accessName, $action); + $this->insertOrUpdateAccess( + $roleName, + $resourceName, + $accessName, + $action + ); } } } diff --git a/Library/Phalcon/Acl/Adapter/README.md b/Library/Phalcon/Acl/Adapter/README.md index 2f2559f0c..2e66f7298 100644 --- a/Library/Phalcon/Acl/Adapter/README.md +++ b/Library/Phalcon/Acl/Adapter/README.md @@ -10,17 +10,21 @@ This adapter uses a database to store the ACL list: use Phalcon\Acl\Adapter\Database as AclDb; use Phalcon\Db\Adapter\Pdo\Sqlite; -$connection = new Sqlite(['dbname' => 'sample.db']); +$connection = new Sqlite( + [ + 'dbname' => 'sample.db', + ] +); $acl = AclDb( - [ - 'db' => $connection, - 'roles' => 'roles', - 'rolesInherits' => 'roles_inherits', - 'resources' => 'resources', - 'resourcesAccesses' => 'resources_accesses', - 'accessList' => 'access_list' - ] + [ + 'db' => $connection, + 'roles' => 'roles', + 'rolesInherits' => 'roles_inherits', + 'resources' => 'resources', + 'resourcesAccesses' => 'resources_accesses', + 'accessList' => 'access_list', + ] ); ``` @@ -64,22 +68,33 @@ CREATE TABLE `roles_inherits` ( Using the cache adapter: ```php - // By default the action is deny access -$acl->setDefaultAction(Phalcon\Acl::DENY); +$acl->setDefaultAction( + \Phalcon\Acl::DENY +); // You can add roles/resources/accesses to list or insert them directly in the tables // Add roles -$acl->addRole(new Phalcon\Acl\Role('Admins')); +$acl->addRole( + new \Phalcon\Acl\Role('Admins') +); // Create the resource with its accesses -$acl->addResource('Products', ['insert', 'update', 'delete']); +$acl->addResource( + 'Products', + [ + 'insert', + 'update', + 'delete', + ] +); // Allow Admins to insert products $acl->allow('Admin', 'Products', 'insert'); // Do Admins are allowed to insert Products? -var_dump($acl->isAllowed('Admins', 'Products', 'update')); - +var_dump( + $acl->isAllowed('Admins', 'Products', 'update') +); ``` diff --git a/Library/Phalcon/Acl/Adapter/Redis.php b/Library/Phalcon/Acl/Adapter/Redis.php index 491ed44e3..cf57cb1d8 100644 --- a/Library/Phalcon/Acl/Adapter/Redis.php +++ b/Library/Phalcon/Acl/Adapter/Redis.php @@ -81,18 +81,35 @@ public function getRedis() public function addRole($role, $accessInherits = null) { if (is_string($role)) { - $role = new Role($role, ucwords($role) . ' Role'); + $role = new Role( + $role, + ucwords($role) . ' Role' + ); } if (!$role instanceof RoleInterface) { - throw new Exception('Role must be either an string or implement RoleInterface'); + throw new Exception( + 'Role must be either an string or implement RoleInterface' + ); } - $this->redis->hMset('roles', [$role->getName() => $role->getDescription()]); - $this->redis->sAdd("accessList:$role:*:{$this->getDefaultAction()}}", "*"); + $this->redis->hMset( + 'roles', + [ + $role->getName() => $role->getDescription(), + ] + ); + + $this->redis->sAdd( + "accessList:$role:*:{$this->getDefaultAction()}}", + "*" + ); if ($accessInherits) { - $this->addInherit($role->getName(), $accessInherits); + $this->addInherit( + $role->getName(), + $accessInherits + ); } return true; @@ -132,6 +149,7 @@ public function addInherit($roleName, $roleToInherit) foreach ($roleToInherit as $roleToInherit) { $this->redis->sAdd("rolesInherits:$roleName", $roleToInherit); } + return true; } @@ -165,12 +183,24 @@ public function addInherit($roleName, $roleToInherit) public function addResource($resource, $accessList = null) { if (!is_object($resource)) { - $resource = new Resource($resource, ucwords($resource) . " Resource"); + $resource = new Resource( + $resource, + ucwords($resource) . " Resource" + ); } - $this->redis->hMset("resources", [$resource->getName() => $resource->getDescription()]); + + $this->redis->hMset( + "resources", + [ + $resource->getName() => $resource->getDescription(), + ] + ); if ($accessList) { - return $this->addResourceAccess($resource->getName(), $accessList); + return $this->addResourceAccess( + $resource->getName(), + $accessList + ); } return true; @@ -187,12 +217,17 @@ public function addResource($resource, $accessList = null) public function addResourceAccess($resourceName, $accessList) { if (!$this->isResource($resourceName)) { - throw new Exception("Resource '" . $resourceName . "' does not exist in ACL"); + throw new Exception( + "Resource '" . $resourceName . "' does not exist in ACL" + ); } $accessList = (is_string($accessList)) ? explode(' ', $accessList) : $accessList; foreach ($accessList as $accessName) { - $this->redis->sAdd("resourcesAccesses:$resourceName", $accessName); + $this->redis->sAdd( + "resourcesAccesses:$resourceName", + $accessName + ); } return true; @@ -222,7 +257,10 @@ public function isResource($resourceName) public function isResourceAccess($resource, $access) { - return $this->redis->sIsMember("resourcesAccesses:$resource", $access); + return $this->redis->sIsMember( + "resourcesAccesses:$resource", + $access + ); } /** @@ -280,10 +318,18 @@ public function getResourceAccess($resource) public function dropResourceAccess($resource, $accessList) { if (!is_array($accessList)) { - $accessList = (array)$accessList; + $accessList = (array) $accessList; } + array_unshift($accessList, "resourcesAccesses:$resource"); - call_user_func_array([$this->redis, 'sRem'], $accessList); + + call_user_func_array( + [ + $this->redis, + 'sRem', + ], + $accessList + ); } /** @@ -309,13 +355,28 @@ public function dropResourceAccess($resource, $accessList) public function allow($role, $resource, $access, $func = null) { if ($role !== '*' && $resource !== '*') { - $this->allowOrDeny($role, $resource, $access, Acl::ALLOW); + $this->allowOrDeny( + $role, + $resource, + $access, + Acl::ALLOW + ); } + if ($role === '*' || empty($role)) { - $this->rolePermission($resource, $access, Acl::ALLOW); + $this->rolePermission( + $resource, + $access, + Acl::ALLOW + ); } + if ($resource === '*' || empty($resource)) { - $this->resourcePermission($role, $access, Acl::ALLOW); + $this->resourcePermission( + $role, + $access, + Acl::ALLOW + ); } } @@ -376,11 +437,24 @@ protected function rolePermission($resource, $access, $allowOrDeny) public function deny($role, $resource, $access, $func = null) { if ($role === '*' || empty($role)) { - $this->rolePermission($resource, $access, Acl::DENY); + $this->rolePermission( + $resource, + $access, + Acl::DENY + ); } elseif ($resource === '*' || empty($resource)) { - $this->resourcePermission($role, $access, Acl::DENY); + $this->resourcePermission( + $role, + $access, + Acl::DENY + ); } else { - $this->allowOrDeny($role, $resource, $access, Acl::DENY); + $this->allowOrDeny( + $role, + $resource, + $access, + Acl::DENY + ); } } @@ -408,6 +482,7 @@ public function isAllowed($role, $resource, $access, array $parameters = null) if ($this->redis->exists("rolesInherits:$role")) { $rolesInherits = $this->redis->sMembers("rolesInherits:$role"); + foreach ($rolesInherits as $role) { if ($this->redis->sIsMember("accessList:$role:$resource:" . Acl::ALLOW, $access)) { return Acl::ALLOW; @@ -463,20 +538,36 @@ protected function setAccess($roleName, $resourceName, $accessName, $action) "Access '" . $accessName . "' does not exist in resource '" . $resourceName . "' in ACL" ); } + $this->addResourceAccess($resourceName, $accessName); } - $this->redis->sAdd("accessList:$roleName:$resourceName:$action", $accessName); + + $this->redis->sAdd( + "accessList:$roleName:$resourceName:$action", + $accessName + ); + $accessList = "accessList:$roleName:$resourceName"; // remove first if exists foreach ([1, 2] as $act) { - $this->redis->sRem("$accessList:$act", $accessName); - $this->redis->sRem("$accessList:$act", "*"); + $this->redis->sRem( + "$accessList:$act", + $accessName + ); + + $this->redis->sRem( + "$accessList:$act", + "*" + ); } $this->redis->sAdd("$accessList:$action", $accessName); - $this->redis->sAdd("$accessList:{$this->getDefaultAction()}", "*"); + $this->redis->sAdd( + "$accessList:{$this->getDefaultAction()}", + "*" + ); return true; } @@ -493,15 +584,27 @@ protected function setAccess($roleName, $resourceName, $accessName, $action) protected function allowOrDeny($roleName, $resourceName, $access, $action) { if (!$this->isRole($roleName)) { - throw new Exception('Role "' . $roleName . '" does not exist in the list'); + throw new Exception( + 'Role "' . $roleName . '" does not exist in the list' + ); } + if (!$this->isResource($resourceName)) { - throw new Exception('Resource "' . $resourceName . '" does not exist in the list'); + throw new Exception( + 'Resource "' . $resourceName . '" does not exist in the list' + ); } + $access = ($access === '*' || empty($access)) ? $this->getResourceAccess($resourceName) : $access; + if (is_array($access)) { foreach ($access as $accessName) { - $this->setAccess($roleName, $resourceName, $accessName, $action); + $this->setAccess( + $roleName, + $resourceName, + $accessName, + $action + ); } } else { $this->setAccess($roleName, $resourceName, $access, $action); diff --git a/Library/Phalcon/Acl/Factory/Memory.php b/Library/Phalcon/Acl/Factory/Memory.php index a188fea5a..acf669a86 100644 --- a/Library/Phalcon/Acl/Factory/Memory.php +++ b/Library/Phalcon/Acl/Factory/Memory.php @@ -66,10 +66,15 @@ public function create(Config $config) $defaultAction = $this->config->get('defaultAction'); if (!is_int($defaultAction) && !ctype_digit($defaultAction)) { - throw new Exception('Key "defaultAction" must exist and must be of numeric value.'); + throw new Exception( + 'Key "defaultAction" must exist and must be of numeric value.' + ); } - $this->acl->setDefaultAction((int) $defaultAction); + $this->acl->setDefaultAction( + (int) $defaultAction + ); + $this->addResources(); $this->addRoles(); @@ -85,15 +90,19 @@ public function create(Config $config) protected function addResources() { if (!(array)$this->config->get('resource')) { - throw new Exception('Key "resource" must exist and must be traversable.'); + throw new Exception( + 'Key "resource" must exist and must be traversable.' + ); } // resources foreach ($this->config->get('resource') as $name => $resource) { $actions = (array) $resource->get('actions'); + if (!$actions) { $actions = null; } + $this->acl->addResource( $this->makeResource($name, $resource->description), $actions @@ -111,13 +120,20 @@ protected function addResources() */ protected function addRoles() { - if (!(array)$this->config->get('role')) { - throw new Exception('Key "role" must exist and must be traversable.'); + if (!(array) $this->config->get('role')) { + throw new Exception( + 'Key "role" must exist and must be traversable.' + ); } foreach ($this->config->get('role') as $role => $rules) { - $this->roles[$role] = $this->makeRole($role, $rules->get('description')); + $this->roles[$role] = $this->makeRole( + $role, + $rules->get('description') + ); + $this->addRole($role, $rules); + $this->addAccessRulesToRole($role, $rules); } @@ -143,13 +159,17 @@ protected function addAccessRulesToRole($role, Config $rules) } foreach ($rules as $controller => $actionRules) { - $actions = $this->castAction($actionRules->get('actions')); + $actions = $this->castAction( + $actionRules->get('actions') + ); if (!in_array($method, ['allow', 'deny'])) { - throw new Exception(sprintf( - 'Wrong access method given. Expected "allow" or "deny" but "%s" was set.', - $method - )); + throw new Exception( + sprintf( + 'Wrong access method given. Expected "allow" or "deny" but "%s" was set.', + $method + ) + ); } $this->acl->{$method}($role, $controller, $actions); @@ -199,16 +219,24 @@ protected function addRole($role, Config $rules) if ($rules->get('inherit')) { // role exists? if (!array_key_exists($rules->inherit, $this->roles)) { - throw new Exception(sprintf( - 'Role "%s" cannot inherit non-existent role "%s". - Either such role does not exist or it is set to be inherited before it is actually defined.', - $role, - $rules->inherit - )); + throw new Exception( + sprintf( + 'Role "%s" cannot inherit non-existent role "%s". + Either such role does not exist or it is set to be inherited before it is actually defined.', + $role, + $rules->inherit + ) + ); } - $this->acl->addRole($this->roles[$role], $this->roles[$rules->inherit]); + + $this->acl->addRole( + $this->roles[$role], + $this->roles[$rules->inherit] + ); } else { - $this->acl->addRole($this->roles[$role]); + $this->acl->addRole( + $this->roles[$role] + ); } return $this; diff --git a/Library/Phalcon/Acl/Factory/README.md b/Library/Phalcon/Acl/Factory/README.md index 7575e86be..81f014dce 100644 --- a/Library/Phalcon/Acl/Factory/README.md +++ b/Library/Phalcon/Acl/Factory/README.md @@ -8,7 +8,6 @@ in case `\Phalcon\Config` or one of its adapters is used for configuration. To setup `acl` service in DI `service.php` file using `acl.ini` file: (example of structure and options in ini file can be found in [tests/_fixtures/Acl/acl.ini](tests/_fixtures/Acl/acl.ini) - ```php use Phalcon\Config\Adapter\Ini as ConfigIni; use Phalcon\Acl\Factory\Memory as AclMemory; @@ -18,10 +17,12 @@ $di->setShared( function () { $config = new ConfigIni(APP_PATH . '/config/acl.ini'); $factory = new AclMemory(); - + // returns instance of \Phalcon\Acl\Adapter\Memory // note the [acl] section in ini file - return $factory->create($config->get('acl')); + return $factory->create( + $config->get('acl') + ); } ); ``` @@ -38,7 +39,7 @@ $di->setShared( function () { $config = new Config(APP_PATH . '/config/acl.php'); $factory = new AclMemory(); - + // returns instance of \Phalcon\Acl\Adapter\Memory return $factory->create($config); } diff --git a/Library/Phalcon/Annotations/Adapter/Aerospike.php b/Library/Phalcon/Annotations/Adapter/Aerospike.php index e99ba03ba..91226f1a0 100644 --- a/Library/Phalcon/Annotations/Adapter/Aerospike.php +++ b/Library/Phalcon/Annotations/Adapter/Aerospike.php @@ -104,7 +104,11 @@ public function __construct(array $options = []) parent::__construct($options); $this->aerospike = new BackendAerospike( - new FrontendData(['lifetime' => $this->options['lifetime']]), + new FrontendData( + [ + 'lifetime' => $this->options['lifetime'], + ] + ), [ 'hosts' => $this->options['hosts'], 'namespace' => $this->namespace, diff --git a/Library/Phalcon/Annotations/Adapter/Base.php b/Library/Phalcon/Annotations/Adapter/Base.php index 09086d895..d6829541e 100644 --- a/Library/Phalcon/Annotations/Adapter/Base.php +++ b/Library/Phalcon/Annotations/Adapter/Base.php @@ -80,7 +80,9 @@ public function __construct($options = null) */ public function read($key) { - return $this->getCacheBackend()->get( + $backend = $this->getCacheBackend(); + + return $backend->get( $this->prepareKey($key), $this->options['lifetime'] ); @@ -94,7 +96,9 @@ public function read($key) */ public function write($key, $data) { - $this->getCacheBackend()->save( + $backend = $this->getCacheBackend(); + + $backend->save( $this->prepareKey($key), $data, $this->options['lifetime'] diff --git a/Library/Phalcon/Annotations/Adapter/Memcached.php b/Library/Phalcon/Annotations/Adapter/Memcached.php index 6577adacc..57d8b1e54 100644 --- a/Library/Phalcon/Annotations/Adapter/Memcached.php +++ b/Library/Phalcon/Annotations/Adapter/Memcached.php @@ -101,19 +101,23 @@ protected function getCacheBackend() { if (null === $this->memcached) { $this->memcached = new CacheBackend( - new CacheFrontend(['lifetime' => $this->options['lifetime']]), + new CacheFrontend( + [ + 'lifetime' => $this->options['lifetime'], + ] + ), [ 'servers' => [ [ - 'host' => $this->options['host'], - 'port' => $this->options['port'], - 'weight' => $this->options['weight'] + 'host' => $this->options['host'], + 'port' => $this->options['port'], + 'weight' => $this->options['weight'], ], ], 'client' => [ - MemcachedGeneric::OPT_HASH => MemcachedGeneric::HASH_MD5, - MemcachedGeneric::OPT_PREFIX_KEY => $this->options['prefix'] - ] + MemcachedGeneric::OPT_HASH => MemcachedGeneric::HASH_MD5, + MemcachedGeneric::OPT_PREFIX_KEY => $this->options['prefix'], + ], ] ); } diff --git a/Library/Phalcon/Annotations/Adapter/README.md b/Library/Phalcon/Annotations/Adapter/README.md index 1f33f0a9f..917322409 100644 --- a/Library/Phalcon/Annotations/Adapter/README.md +++ b/Library/Phalcon/Annotations/Adapter/README.md @@ -10,15 +10,20 @@ This adapter uses a `Phalcon\Cache\Backend\Libmemcached` backend to store the ca ```php use Phalcon\Annotations\Adapter\Memcached; -$di->set('annotations', function () { - return new Memcached([ - 'lifetime' => 8600, - 'host' => 'localhost', - 'port' => 11211, - 'weight' => 1, - 'prefix' => 'prefix.', - ]); -}); +$di->set( + 'annotations', + function () { + return new Memcached( + [ + 'lifetime' => 8600, + 'host' => 'localhost', + 'port' => 11211, + 'weight' => 1, + 'prefix' => 'prefix.', + ] + ); + } +); ``` ## Redis @@ -29,14 +34,19 @@ This adapter uses a `Phalcon\Cache\Backend\Redis` backend to store the cached co ```php use Phalcon\Annotations\Adapter\Redis; -$di->set('annotations', function () { - return new Redis([ - 'lifetime' => 8600, - 'host' => 'localhost', - 'port' => 6379, - 'prefix' => 'annotations_', - ]); -}); +$di->set( + 'annotations', + function () { + return new Redis( + [ + 'lifetime' => 8600, + 'host' => 'localhost', + 'port' => 6379, + 'prefix' => 'annotations_', + ] + ); + } +); ``` ## Aerospike @@ -47,19 +57,27 @@ This adapter uses a `Phalcon\Cache\Backend\Aerospike` backend to store the cache ```php use Phalcon\Annotations\Adapter\Aerospike; -$di->set('annotations', function () { - return new Aerospike([ - 'hosts' => [ - ['addr' => '127.0.0.1', 'port' => 3000] - ], - 'persistent' => true, - 'namespace' => 'test', - 'prefix' => 'annotations_', - 'lifetime' => 8600, - 'options' => [ - \Aerospike::OPT_CONNECT_TIMEOUT => 1250, - \Aerospike::OPT_WRITE_TIMEOUT => 1500 - ] - ]); -}); +$di->set( + 'annotations', + function () { + return new Aerospike( + [ + 'hosts' => [ + [ + 'addr' => '127.0.0.1', + 'port' => 3000, + ], + ], + 'persistent' => true, + 'namespace' => 'test', + 'prefix' => 'annotations_', + 'lifetime' => 8600, + 'options' => [ + \Aerospike::OPT_CONNECT_TIMEOUT => 1250, + \Aerospike::OPT_WRITE_TIMEOUT => 1500, + ], + ] + ); + } +); ``` diff --git a/Library/Phalcon/Annotations/Adapter/Redis.php b/Library/Phalcon/Annotations/Adapter/Redis.php index b1a24e55b..966b41b9a 100644 --- a/Library/Phalcon/Annotations/Adapter/Redis.php +++ b/Library/Phalcon/Annotations/Adapter/Redis.php @@ -70,7 +70,11 @@ public function __construct(array $options = []) parent::__construct($options); $this->redis = new BackendRedis( - new FrontendData(['lifetime' => $this->options['lifetime']]), + new FrontendData( + [ + 'lifetime' => $this->options['lifetime'], + ] + ), $options ); } diff --git a/Library/Phalcon/Annotations/Extended/AbstractAdapter.php b/Library/Phalcon/Annotations/Extended/AbstractAdapter.php index ba7afcf23..043e29f69 100644 --- a/Library/Phalcon/Annotations/Extended/AbstractAdapter.php +++ b/Library/Phalcon/Annotations/Extended/AbstractAdapter.php @@ -85,7 +85,10 @@ protected function checkKey($key) { if (!is_string($key)) { throw new Exception( - sprintf('Invalid key type key to retrieve annotations. Expected string but got %s.', gettype($key)) + sprintf( + 'Invalid key type key to retrieve annotations. Expected string but got %s.', + gettype($key) + ) ); } } diff --git a/Library/Phalcon/Annotations/Extended/Adapter/Apc.php b/Library/Phalcon/Annotations/Extended/Adapter/Apc.php index 49982066f..460b62336 100644 --- a/Library/Phalcon/Annotations/Extended/Adapter/Apc.php +++ b/Library/Phalcon/Annotations/Extended/Adapter/Apc.php @@ -112,10 +112,18 @@ public function write($key, Reflection $data) $prefixedKey = $this->getPrefixedIdentifier($key); if (function_exists('apcu_store')) { - return apcu_store($prefixedKey, $data, $this->lifetime); + return apcu_store( + $prefixedKey, + $data, + $this->lifetime + ); } - return apc_store($prefixedKey, $data, $this->lifetime); + return apc_store( + $prefixedKey, + $data, + $this->lifetime + ); } /** @@ -135,15 +143,23 @@ public function flush() $prefixPattern = '#^_PHAN' . preg_quote("{$this->prefix}", '#') . '#'; if (class_exists('\APCuIterator')) { - foreach (new \APCuIterator($prefixPattern) as $item) { - apcu_delete($item['key']); + $iterator = new \APCuIterator($prefixPattern); + + foreach ($iterator as $item) { + apcu_delete( + $item['key'] + ); } return true; } - foreach (new \APCIterator('user', $prefixPattern) as $item) { - apc_delete($item['key']); + $iterator = new \APCIterator('user', $prefixPattern); + + foreach ($iterator as $item) { + apc_delete( + $item['key'] + ); } return true; diff --git a/Library/Phalcon/Annotations/Extended/Adapter/Files.php b/Library/Phalcon/Annotations/Extended/Adapter/Files.php index a22d0ceef..b8d87de6d 100644 --- a/Library/Phalcon/Annotations/Extended/Adapter/Files.php +++ b/Library/Phalcon/Annotations/Extended/Adapter/Files.php @@ -61,7 +61,7 @@ class Files extends AbstractAdapter public function __construct(array $options = []) { if (!isset($options['annotationsDir'])) { - $options['annotationsDir'] =sys_get_temp_dir(); + $options['annotationsDir'] = sys_get_temp_dir(); } parent::__construct($options); @@ -76,6 +76,7 @@ public function __construct(array $options = []) protected function setAnnotationsDir($annotationsDir) { $annotationsDir = (string) $annotationsDir; + $this->annotationsDir = rtrim($annotationsDir, '\\/') . DIRECTORY_SEPARATOR; return $this; @@ -141,12 +142,15 @@ public function write($key, Reflection $reflection) public function flush() { $iterator = new \DirectoryIterator($this->annotationsDir); + foreach ($iterator as $item) { if ($item->isDot() || !$item->isFile() || $item->getExtension() !== 'php') { continue; } - unlink($item->getPathname()); + unlink( + $item->getPathname() + ); } return true; @@ -160,7 +164,17 @@ public function flush() */ protected function getPrefixedIdentifier($key) { - $key = strtolower(str_replace(['\\', '/', ':'], '_', $key)); + $key = strtolower( + str_replace( + [ + '\\', + '/', + ':', + ], + '_', + $key + ) + ); return $this->annotationsDir . preg_replace('#_{2,}#', '_', $key) . '.php'; } diff --git a/Library/Phalcon/Annotations/Extended/Adapter/Memory.php b/Library/Phalcon/Annotations/Extended/Adapter/Memory.php index 63bd07ba9..3198764af 100644 --- a/Library/Phalcon/Annotations/Extended/Adapter/Memory.php +++ b/Library/Phalcon/Annotations/Extended/Adapter/Memory.php @@ -80,7 +80,6 @@ public function write($key, Reflection $reflection) $this->data[$prefixedKey] = $reflection; - return true; } diff --git a/Library/Phalcon/Annotations/Extended/README.md b/Library/Phalcon/Annotations/Extended/README.md index ac7a64f20..62b991cc1 100644 --- a/Library/Phalcon/Annotations/Extended/README.md +++ b/Library/Phalcon/Annotations/Extended/README.md @@ -18,13 +18,18 @@ using either _APCu_ or _APC_ extension. This adapter is suitable for production. ```php use Phalcon\Annotations\Extended\Adapter\Apc; -$di->set('annotations', function () { - return new Apc([ - 'lifetime' => 8600, // Optional - 'statsSey' => '_PHAN', // Optional - 'prefix' => 'app-annotations-', // Optional - ]); -}); +$di->set( + 'annotations', + function () { + return new Apc( + [ + 'lifetime' => 8600, // Optional + 'statsSey' => '_PHAN', // Optional + 'prefix' => 'app-annotations-', // Optional + ] + ); + } +); ``` ## Memory @@ -34,9 +39,12 @@ Stores the parsed annotations in the memory. This adapter is the suitable develo ```php use Phalcon\Annotations\Extended\Adapter\Memory; -$di->set('annotations', function () { - return new Memory(); -}); +$di->set( + 'annotations', + function () { + return new Memory(); + } +); ``` ## Files 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/Avatar/README.md b/Library/Phalcon/Avatar/README.md index 46713b305..c25972781 100644 --- a/Library/Phalcon/Avatar/README.md +++ b/Library/Phalcon/Avatar/README.md @@ -14,17 +14,22 @@ Users must register their email addresses with Gravatar before their avatars wil ```php use Phalcon\Avatar\Gravatar; -$di->setShared('gravatar', function () { - // Get Gravatar instance - $gravatar = new Gravatar([]); - - // Setting default image, maximum size and maximum allowed Gravatar rating - $gravatar->setDefaultImage('retro') - ->setSize(220) - ->setRating(Gravatar::RATING_PG); - - return $gravatar; -}); +$di->setShared( + 'gravatar', + function () { + // Get Gravatar instance + $gravatar = new Gravatar( + [] + ); + + // Setting default image, maximum size and maximum allowed Gravatar rating + $gravatar->setDefaultImage('retro') + ->setSize(220) + ->setRating(Gravatar::RATING_PG); + + return $gravatar; + } +); ``` #### Setup through config @@ -40,13 +45,15 @@ $config = [ 'use_https' => true, ]; +$di->setShared( + 'gravatar', + function () use ($config) { + // Get Gravatar instance + $gravatar = new Gravatar($config); -$di->setShared('gravatar', function () use ($config) { - // Get Gravatar instance - $gravatar = new Gravatar($config); - - return $gravatar; -}); + return $gravatar; + } +); ``` ### Using @@ -156,7 +163,9 @@ By default, the Gravatar rating is `Gravatar::RATING_G`. Example: ```php -$gravatar->setRating(Gravatar::RATING_PG); +$gravatar->setRating( + Gravatar::RATING_PG +); ``` If an invalid maximum rating is specified, this method will throw an exception of class `\InvalidArgumentException`. 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/README.md b/Library/Phalcon/Cache/Backend/README.md index a48dc0c05..7c24b9eda 100644 --- a/Library/Phalcon/Cache/Backend/README.md +++ b/Library/Phalcon/Cache/Backend/README.md @@ -17,22 +17,35 @@ Usage: use Phalcon\Cache\Backend\Aerospike as BackendCache; use Phalcon\Cache\Frontend\Data; -$di->set('cache', function () { - $cache = new BackendCache(new Data(['lifetime' => 3600]), [ - '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 - ] - ]); - - return $cache; -}); +$di->set( + 'cache', + function () { + $cache = new BackendCache( + new Data( + [ + 'lifetime' => 3600, + ] + ), + [ + '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, + ], + ] + ); + + return $cache; + } +); ``` ## Database @@ -44,26 +57,38 @@ use Phalcon\Cache\Backend\Database; use Phalcon\Cache\Frontend\Data; use Phalcon\Db\Adapter\Pdo\Mysql; -$di->set('cache', function() { - // Create a connection - $connection = new Mysql([ - 'host' => 'localhost', - 'username' => 'root', - 'password' => 'secret', - 'dbname' => 'cache_db' - ]); - - // Create a Data frontend and set a default lifetime to 1 hour - $frontend = new Data(['lifetime' => 3600]); - - // Create the cache passing the connection - $cache = new Database($frontend, [ - 'db' => $connection, - 'table' => 'cache_data' - ]); - - return $cache; -}); +$di->set( + 'cache', + function () { + // Create a connection + $connection = new Mysql( + [ + 'host' => 'localhost', + 'username' => 'root', + 'password' => 'secret', + 'dbname' => 'cache_db', + ] + ); + + // Create a Data frontend and set a default lifetime to 1 hour + $frontend = new Data( + [ + 'lifetime' => 3600, + ] + ); + + // Create the cache passing the connection + $cache = new Database( + $frontend, + [ + 'db' => $connection, + 'table' => 'cache_data', + ] + ); + + return $cache; + } +); ``` This adapter uses the following table to store the data: @@ -81,15 +106,15 @@ This adapter uses the following table to store the data: Using the cache adapter: ```php - $time = $this->cache->get('le-time'); + if ($time === null) { $time = date('r'); + $this->cache->save('le-time', $time); } echo $time; - ``` ## Wincache 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/Console/README.md b/Library/Phalcon/Cli/Console/README.md index ccb42213b..487df32ba 100644 --- a/Library/Phalcon/Cli/Console/README.md +++ b/Library/Phalcon/Cli/Console/README.md @@ -51,24 +51,26 @@ Firstly you need to add some important values into the config. ```php use Phalcon\Config; -$config = new Config([ - 'appName' => 'My Console App', - 'version' => '1.0', - - /** - * tasksDir is the absolute path to your tasks directory - * For instance, 'tasksDir' => realpath(dirname(dirname(__FILE__))).'/tasks', - */ - 'tasksDir' => '/path/to/your/project/tasks', - - /** - * annotationsAdapter is the choosen adapter to read annotations. - * Adapter by default: memory - */ - 'annotationsAdapter' => 'memory', - - 'printNewLine' => true -]); +$config = new Config( + [ + 'appName' => 'My Console App', + 'version' => '1.0', + + /** + * tasksDir is the absolute path to your tasks directory + * For instance, 'tasksDir' => realpath(dirname(dirname(__FILE__))).'/tasks', + */ + 'tasksDir' => '/path/to/your/project/tasks', + + /** + * annotationsAdapter is the chosen adapter to read annotations. + * Adapter by default: memory + */ + 'annotationsAdapter' => 'memory', + + 'printNewLine' => true, + ] +); ``` Second you must to create an instance of the DI class and add the created config class under key 'config'. @@ -77,9 +79,13 @@ Second you must to create an instance of the DI class and add the created config use Phalcon\DI\FactoryDefault\Cli as CliDi; $di = new CliDi(); -$di->set('config', function () use ($config) { - return $config; -}); + +$di->set( + 'config', + function () use ($config) { + return $config; + } +); ``` Well, it's time to create an instance of Extended Console Class to handle the calls @@ -88,7 +94,8 @@ Well, it's time to create an instance of Extended Console Class to handle the ca use Phalcon\Cli\Console\Extended as Console; $console = new Console(); -// Seting the above DI + +// Setting the above DI $console->setDI($di); /** @@ -111,6 +118,7 @@ try { $console->handle($arguments); } catch (Exception $e) { echo $e->getMessage(); + exit(255); } ``` @@ -146,7 +154,7 @@ class LsTask extends Task */ public function mainAction() { - echo 'Content list:'.PHP_EOL; + echo 'Content list:' . PHP_EOL; // Code to iterate a directory and show the content } @@ -155,18 +163,21 @@ class LsTask extends Task * @param({'type'='string', 'name'='directory', 'description'='directory to be listed' }) * @param({'type'='string', 'name'='Size unit', 'description'='Unit size to be shown' }) */ - public function hrAction(array $params) { + public function hrAction(array $params) + { $directoryToList = $params[0]; $unitSize = $params[1]; + // Code to iterate a directory and show the content } - + /** * @DoNotCover */ public function secretAction() { - echo 'Secret list:'.PHP_EOL; + echo 'Secret list:' . PHP_EOL; + // ... } } 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/Cli/Environment/README.md b/Library/Phalcon/Cli/Environment/README.md index 075e6d57d..6aaa34432 100644 --- a/Library/Phalcon/Cli/Environment/README.md +++ b/Library/Phalcon/Cli/Environment/README.md @@ -34,6 +34,9 @@ use Phalcon\DiInterface; class Console extends PhConsole implements EnvironmentAwareInterface { + /** + * @var EnvironmentInterface|null + */ protected $environment; public function __construct(DiInterface $di = null) @@ -65,7 +68,9 @@ use MyAwesomeApplication\Console; $application = new Console; -$application->setEnvironment(new Environment); +$application->setEnvironment( + new Environment +); ``` ## Implementing your own Environment 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/Db/Adapter/README.md b/Library/Phalcon/Db/Adapter/README.md index 6112b1e93..48231b460 100644 --- a/Library/Phalcon/Db/Adapter/README.md +++ b/Library/Phalcon/Db/Adapter/README.md @@ -14,23 +14,41 @@ use Phalcon\Cache\Backend\File; use Phalcon\Cache\Frontend\Data; use Phalcon\Db\Adapter\Cacheable\Mysql; -$di->set('db', function() { - /** @var \Phalcon\DiInterface $this */ - $connection = new Mysql([ - 'host' => $this->getShared('config')->database->host, - 'username' => $this->getShared('config')->database->username, - 'password' => $this->getShared('config')->database->password, - 'dbname' => $this->getShared('config')->database->name, - 'options' => [Pdo::ATTR_EMULATE_PREPARES => false] - ]); - - $frontCache = new Data(['lifetime' => 2592000]); - - // File backend settings - $connection->setCache(new File($frontCache, ['cacheDir' => __DIR__ . '/../../var/db/'])); - - return $connection; -}); +$di->set( + 'db', + function () { + /** @var \Phalcon\DiInterface $this */ + $connection = new Mysql( + [ + 'host' => $this->getShared('config')->database->host, + 'username' => $this->getShared('config')->database->username, + 'password' => $this->getShared('config')->database->password, + 'dbname' => $this->getShared('config')->database->name, + 'options' => [ + Pdo::ATTR_EMULATE_PREPARES => false, + ], + ] + ); + + $frontCache = new Data( + [ + 'lifetime' => 2592000, + ] + ); + + // File backend settings + $connection->setCache( + new File( + $frontCache, + [ + 'cacheDir' => __DIR__ . '/../../var/db/', + ] + ) + ); + + return $connection; + } +); ``` ## Pdo\Oracle @@ -40,16 +58,24 @@ Specific functions for the Oracle RDBMS. ```php use Phalcon\Db\Adapter\Pdo\Oracle; -$di->set('db', function() { - /** @var \Phalcon\DiInterface $this */ - $connection = new Oracle([ - 'dbname' => $this->getShared('config')->database->dbname, - 'username' => $this->getShared('config')->database->username, - 'password' => $this->getShared('config')->database->password, - ]); - - return $connection; -}); +$di->set( + 'db', + function () { + /** @var \Phalcon\DiInterface $this */ + + $config = $this->getShared('config'); + + $connection = new Oracle( + [ + 'dbname' => $config->database->dbname, + 'username' => $config->database->username, + 'password' => $config->database->password, + ] + ); + + return $connection; + } +); ``` ## Mongo\Client @@ -61,12 +87,17 @@ This will solve cursor and related records problems on the ODM. ```php use Phalcon\Db\Adapter\Mongo\Client; -$di->setShared('mongo', function() { - /** @var \Phalcon\DiInterface $this */ - $mongo = new Client(); +$di->setShared( + 'mongo', + function () { + /** @var \Phalcon\DiInterface $this */ + $mongo = new Client(); - return $mongo->selectDB($this->getShared('config')->database->dbname); -}); + return $mongo->selectDB( + $this->getShared('config')->database->dbname + ); + } +); ``` ## MongoDB\Client @@ -80,30 +111,39 @@ use Phalcon\Mvc\Collection\Manager; use Phalcon\Db\Adapter\MongoDB\Client; // Initialise the mongo DB connection. -$di->setShared('mongo', function () { - /** @var \Phalcon\DiInterface $this */ - $config = $this->getShared('config'); - - if (!$config->database->mongo->username || !$config->database->mongo->password) { - $dsn = 'mongodb://' . $config->database->mongo->host; - } else { - $dsn = sprintf( - 'mongodb://%s:%s@%s', - $config->database->mongo->username, - $config->database->mongo->password, - $config->database->mongo->host +$di->setShared( + 'mongo', + function () { + /** @var \Phalcon\DiInterface $this */ + + $config = $this->getShared('config'); + + if (!$config->database->mongo->username || !$config->database->mongo->password) { + $dsn = 'mongodb://' . $config->database->mongo->host; + } else { + $dsn = sprintf( + 'mongodb://%s:%s@%s', + $config->database->mongo->username, + $config->database->mongo->password, + $config->database->mongo->host + ); + } + + $mongo = new Client($dsn); + + return $mongo->selectDatabase( + $config->database->mongo->dbname ); } - - $mongo = new Client($dsn); - - return $mongo->selectDatabase($config->database->mongo->dbname); -}); +); // Collection Manager is required for MongoDB -$di->setShared('collectionManager', function () { - return new Manager(); -}); +$di->setShared( + 'collectionManager', + function () { + return new Manager(); + } +); ``` Collection example: @@ -116,7 +156,7 @@ class UserCollection extends MongoCollection public $name; public $email; public $password; - + public function getSource() { return 'users'; diff --git a/Library/Phalcon/Db/Dialect/MysqlExtended.php b/Library/Phalcon/Db/Dialect/MysqlExtended.php index f320bf95d..ebef06f31 100644 --- a/Library/Phalcon/Db/Dialect/MysqlExtended.php +++ b/Library/Phalcon/Db/Dialect/MysqlExtended.php @@ -60,7 +60,27 @@ class MysqlExtended extends Mysql public function getSqlExpression(array $expression, $escapeChar = null, $bindCounts = null) { if ($expression["type"] == 'functionCall') { - switch (strtoupper($expression["name"])) { + $expressionName = strtoupper($expression["name"]); + + switch ($expressionName) { + case 'TIMESTAMPDIFF': + $timeUnit = substr($expression["arguments"][0]['value'], 1, -1); + $allowedTimeUnits = [ + "MICROSECOND", "SECOND", "MINUTE", "HOUR", "DAY", "WEEK", "MONTH", "QUARTER", "YEAR" + ]; + + if (count($expression["arguments"]) != 3) { + throw new Exception($expressionName . ' requires 3 parameters'); + } + + if (!in_array($timeUnit, $allowedTimeUnits)) { + throw new Exception($expressionName . ' unit is not supported'); + } + + return $expressionName . '(' . $timeUnit . ', ' . + $this->getSqlExpression($expression["arguments"][1]) . ', ' . + $this->getSqlExpression($expression["arguments"][2]) . ')'; + case 'DATE_INTERVAL': if (count($expression["arguments"]) != 2) { throw new Exception('DATE_INTERVAL requires 2 parameters'); diff --git a/Library/Phalcon/Db/Dialect/Oracle.php b/Library/Phalcon/Db/Dialect/Oracle.php index e72a349c8..19756d96e 100644 --- a/Library/Phalcon/Db/Dialect/Oracle.php +++ b/Library/Phalcon/Db/Dialect/Oracle.php @@ -53,6 +53,17 @@ class Oracle extends Dialect protected $_escapeChar = ""; // @codingStandardsIgnoreEnd + /** + * Returns a SQL modified with a LOCK IN SHARE MODE clause + * + * @param string $sqlQuery + * @return string + */ + public function sharedLock($sqlQuery) + { + return $sqlQuery . ' LOCK IN SHARE MODE'; + } + /** * Generates the SQL for LIMIT clause. * diff --git a/Library/Phalcon/Db/Dialect/README.md b/Library/Phalcon/Db/Dialect/README.md index 21140664f..2004aa0d2 100644 --- a/Library/Phalcon/Db/Dialect/README.md +++ b/Library/Phalcon/Db/Dialect/README.md @@ -12,15 +12,20 @@ these syntax you can use these functions: use Phalcon\Db\Adapter\Pdo\Mysql; use Phalcon\Db\Dialect\MysqlExtended; -$di->set('db', function() { - return new Mysql([ - 'host' => 'localhost', - 'username' => 'root', - 'password' => 'secret', - 'dbname' => 'enigma', - 'dialectClass' => MysqlExtended::class, - ]); -}); +$di->set( + 'db', + function () { + return new Mysql( + [ + 'host' => 'localhost', + 'username' => 'root', + 'password' => 'secret', + 'dbname' => 'enigma', + 'dialectClass' => MysqlExtended::class, + ] + ); + } +); ``` Usage: @@ -57,12 +62,17 @@ Generates database specific SQL for the Oracle RDBMS. use Phalcon\Db\Adapter\Pdo\Oracle; use Phalcon\Db\Adapter\Pdo\Oracle as Connection; -$di->set('db', function() { - return new Connection([ - 'dbname' => '//localhost/enigma', - 'username' => 'oracle', - 'password' => 'secret', - 'dialectClass' => Oracle::class, - ]); -}); +$di->set( + 'db', + function () { + return new Connection( + [ + 'dbname' => '//localhost/enigma', + 'username' => 'oracle', + 'password' => 'secret', + 'dialectClass' => Oracle::class, + ] + ); + } +); ``` 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/Error/README.md b/Library/Phalcon/Error/README.md index 0876c5127..af6840eae 100644 --- a/Library/Phalcon/Error/README.md +++ b/Library/Phalcon/Error/README.md @@ -11,12 +11,12 @@ use Phalcon\Logger\Adapter\File as FileLogger; use Phalcon\Logger\Formatter\Line as LineFormatter; return [ - 'error' => [ - 'logger' => new FileLogger(ROOT_PATH . '/log/' . APPLICATION_ENV . '.log'), - 'formatter' => new LineFormatter('[%date%][%type%] %message%', 'Y-m-d H:i:s O'), - 'controller' => 'error', - 'action' => 'index', - ] + 'error' => [ + 'logger' => new FileLogger(ROOT_PATH . '/log/' . APPLICATION_ENV . '.log'), + 'formatter' => new LineFormatter('[%date%][%type%] %message%', 'Y-m-d H:i:s O'), + 'controller' => 'error', + 'action' => 'index', + ], ]; ``` @@ -34,18 +34,19 @@ error handler has to be registered. Application must also define constants for a ```php class Application extends \Phalcon\Mvc\Application { - const ENV_PRODUCTION = 'production'; - const ENV_STAGING = 'staging'; - const ENV_TEST = 'test'; - const ENV_DEVELOPMENT = 'development'; - - public function __construct(DiInterface $dependencyInjector = null) - { - $this->_registerAutoloaders(); - ErrorHandler::register(); - - parent::__construct($dependencyInjector); - } + const ENV_PRODUCTION = 'production'; + const ENV_STAGING = 'staging'; + const ENV_TEST = 'test'; + const ENV_DEVELOPMENT = 'development'; + + public function __construct(DiInterface $dependencyInjector = null) + { + $this->_registerAutoloaders(); + + ErrorHandler::register(); + + parent::__construct($dependencyInjector); + } } ``` @@ -54,30 +55,32 @@ In the error controller `\Phalcon\Error\Error` can be retrieved through the disp ```php public function indexAction() { - /** @var \Phalcon\Error\Error $error */ - $error = $this->dispatcher->getParam('error'); - - switch ($error->type()) { - case 404: - $code = 404; - break; - case 403: - $code = 403; - break; - case 401: - $code = 401; - break; - default: - $code = 500; - } - - $this->response->resetHeaders()->setStatusCode($code, null); - - $this->view->setVars([ - 'error' => $error, - 'code' => $code, - 'dev' => APPLICATION_ENV != \Phalcon\Error\Application::ENV_PRODUCTION - ]); + /** @var \Phalcon\Error\Error $error */ + $error = $this->dispatcher->getParam('error'); + + switch ($error->type()) { + case 404: + $code = 404; + break; + case 403: + $code = 403; + break; + case 401: + $code = 401; + break; + default: + $code = 500; + } + + $this->response->resetHeaders()->setStatusCode($code, null); + + $this->view->setVars( + [ + 'error' => $error, + 'code' => $code, + 'dev' => (APPLICATION_ENV != \Phalcon\Error\Application::ENV_PRODUCTION), + ] + ); } ``` @@ -89,9 +92,9 @@ Error message could be displayed to the user this way: message(); ?> -
in file(); ?> on line line(); ?>
- isException()) { ?> -
exception()->getTraceAsString(); ?>
- +
in file(); ?> on line line(); ?>
+ isException()) { ?> +
exception()->getTraceAsString(); ?>
+ ``` 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/Client/README.md b/Library/Phalcon/Http/Client/README.md index 1dadc1377..30ed337b9 100644 --- a/Library/Phalcon/Http/Client/README.md +++ b/Library/Phalcon/Http/Client/README.md @@ -19,27 +19,36 @@ $provider->setBaseUri('http://example.com/api/'); $provider->header->set('Accept', 'application/json'); // GET request to http://example.com/api/me/images?access_token=1234 and return response -$response = $provider->get('me/images', [ - 'access_token' => 1234 -]); +$response = $provider->get( + 'me/images', + [ + 'access_token' => 1234, + ] +); echo $response->body; // POST multipart/form-data request to http://example.com/api/me/images -$response = $provider->post('me/images', [ - 'access_token' => 1234, - 'image' => '@/home/mine/myimage.jpg' -]); +$response = $provider->post( + 'me/images', + [ + 'access_token' => 1234, + 'image' => '@/home/mine/myimage.jpg', + ] +); echo $response->body; echo $response->header->get('Content-Type'); echo $response->header->statusCode; // DELETE request to http://example.com/api/me/images -$response = $provider->delete('me/images', [ - 'access_token' => 1234, - 'image_id' => '321' -]); +$response = $provider->delete( + 'me/images', + [ + 'access_token' => 1234, + 'image_id' => '321', + ] +); echo $response->body; ``` diff --git a/Library/Phalcon/Http/README.md b/Library/Phalcon/Http/README.md index 6c76a0990..98d4c9a17 100644 --- a/Library/Phalcon/Http/README.md +++ b/Library/Phalcon/Http/README.md @@ -4,7 +4,7 @@ Uri utility ## Uri -The utility to parse URI strings. Resolve absolute, relative URN and querystrings. Build new URI from actual object's statement. +The utility to parse URI strings. Resolve absolute, relative URN and query strings. Build new URI from actual object's statement. ### Examples @@ -16,16 +16,17 @@ $uri1 = new Uri('http://phalconphp.com/foo/bar/baz?var1=a&var2=1'); $uri2 = $uri1->resolve('/last'); echo $uri2->build(); // http://phalconphp.com/last?var1=a&var2=1 - $uri3 = $uri1->resolve('last'); echo $uri3->build(); // http://phalconphp.com/foo/bar/baz/last?var1=a&var2=1 -$uri4 = new Uri([ - 'scheme' => 'https', - 'host' => 'admin.example.com', - 'user' => 'john', - 'pass' => 'doe' -]); +$uri4 = new Uri( + [ + 'scheme' => 'https', + 'host' => 'admin.example.com', + 'user' => 'john', + 'pass' => 'doe', + ] +); $uri5 = $uri1->resolve($uri4); echo $uri5->build(); // https://john:doe@admin.example.com/foo/bar/baz?var1=a&var2=1 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/Logger/README.md b/Library/Phalcon/Logger/README.md index 3e751c5e9..de2a0c0c3 100644 --- a/Library/Phalcon/Logger/README.md +++ b/Library/Phalcon/Logger/README.md @@ -10,23 +10,29 @@ Adapter to store logs in a database table: use Phalcon\Db\Adapter\Pdo\Mysql; use Phalcon\Logger\Adapter\Database as DbLogger; -$di->set('logger', function() { - - $connection = new Mysql([ - 'host' => 'localhost', - 'username' => 'root', - 'password' => 'secret', - 'dbname' => 'audit' - ]); - - $logger = new DbLogger('errors', [ - 'db' => $connection, - 'table' => 'logs' - ]); - - return $logger; -}); - +$di->set( + 'logger', + function () { + $connection = new Mysql( + [ + 'host' => 'localhost', + 'username' => 'root', + 'password' => 'secret', + 'dbname' => 'audit', + ] + ); + + $logger = new DbLogger( + 'errors', + [ + 'db' => $connection, + 'table' => 'logs', + ] + ); + + return $logger; + } +); ``` The following table is used to store the logs: @@ -63,15 +69,20 @@ Adapter to send messages by UDP protocol to external server ```php use Phalcon\Logger\Adapter\Udplogger as UdpLogger; -$di->set('logger', function() { - - $logger = new UdpLogger('errors', [ - 'url' => $url, - 'port' => $port - ]); - - return $logger; -}); +$di->set( + 'logger', + function () { + $logger = new UdpLogger( + 'errors', + [ + 'url' => $url, + 'port' => $port, + ] + ); + + return $logger; + } +); ``` ## Multiple file logger @@ -101,33 +112,33 @@ Note that similar-level logs are logged into the same file. The log level groups are defined within the `getTypeString()` method. You may overload this method to fit your needs: ```php - private function getTypeString($type) - { - switch ($type) { - case Logger::EMERGENCY: - case Logger::EMERGENCE: - 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: - default: - // debug, log, custom, special - return 'debug'; - } +private function getTypeString($type) +{ + switch ($type) { + case Logger::EMERGENCY: + case Logger::EMERGENCE: + 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: + default: + // debug, log, custom, special + return 'debug'; } +} ``` Thus, by default both errors and alerts are logged into error.log, and both emergence and critical messages are logged into critical.log, etc. @@ -139,12 +150,15 @@ Optionally, you may pass configuration options to the logger constructor: ```php use Phalcon\Logger\Adapter\File\Multiple as MultipleLogger; -$logger = new MultipleLogger(__DIR__ . '/../logs', [ - // filename prefix to all logs generated by this logger. Defaults to "" - 'prefix' => 'myapp-', - // filename extension to all logs generated by this logger. Defaults to "log" - 'extension' => 'txt' -]); +$logger = new MultipleLogger( + __DIR__ . '/../logs', + [ + // filename prefix to all logs generated by this logger. Defaults to "" + 'prefix' => 'myapp-', + // filename extension to all logs generated by this logger. Defaults to "log" + 'extension' => 'txt', + ] +); ``` diff --git a/Library/Phalcon/Mailer/CHANGELOG.md b/Library/Phalcon/Mailer/CHANGELOG.md index 54d0f1ef9..e966f5f49 100644 --- a/Library/Phalcon/Mailer/CHANGELOG.md +++ b/Library/Phalcon/Mailer/CHANGELOG.md @@ -8,4 +8,4 @@ - In `\Phalcon\Mailer\Message`, creation SwiftMailer of instances moved to the DI ## v1.0.0 (2014-09-14) -- Release of component :) \ No newline at end of file +- Release of component :) 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/Mailer/README.md b/Library/Phalcon/Mailer/README.md index b2aadfbec..c06d23906 100644 --- a/Library/Phalcon/Mailer/README.md +++ b/Library/Phalcon/Mailer/README.md @@ -15,9 +15,9 @@ $config = [ 'username' => 'example@gmail.com', 'password' => 'your_password', 'from' => [ - 'email' => 'example@gmail.com', - 'name' => 'YOUR FROM NAME' - ] + 'email' => 'example@gmail.com', + 'name' => 'YOUR FROM NAME', + ], ]; ``` @@ -29,8 +29,8 @@ $config = [ 'sendmail' => '/usr/sbin/sendmail -bs', 'from' => [ 'email' => 'example@gmail.com', - 'name' => 'YOUR FROM NAME' - ] + 'name' => 'YOUR FROM NAME', + ], ]; ``` @@ -41,8 +41,8 @@ $config = [ 'driver' => 'mail', 'from' => [ 'email' => 'example@gmail.com', - 'name' => 'YOUR FROM NAME' - ] + 'name' => 'YOUR FROM NAME', + ], ]; ``` 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/Behavior/README.md b/Library/Phalcon/Mvc/Model/Behavior/README.md index f9f6268cb..4224930f6 100644 --- a/Library/Phalcon/Mvc/Model/Behavior/README.md +++ b/Library/Phalcon/Mvc/Model/Behavior/README.md @@ -12,12 +12,16 @@ class Categories extends \Phalcon\Mvc\Model { public function initialize() { - $this->addBehavior(new NestedSetBehavior([ - 'rootAttribute' => 'root', - 'leftAttribute' => 'lft', - 'rightAttribute' => 'rgt', - 'levelAttribute' => 'level' - ])); + $this->addBehavior( + new NestedSetBehavior( + [ + 'rootAttribute' => 'root', + 'leftAttribute' => 'lft', + 'rightAttribute' => 'rgt', + 'levelAttribute' => 'level', + ] + ) + ); } } ``` @@ -128,12 +132,24 @@ Result: Mercedes node and Audi node. You can get the whole tree using standard model methods like the following. For single tree per table: ```php -Categories::find(['order' => 'lft']); +Categories::find( + [ + 'order' => 'lft', + ] +); ``` For multiple trees per table: ```php -Categories::find(['root=:root:', 'order'=>'lft', 'bind' => ['root' => $root_id]]); +Categories::find( + [ + 'root=:root:', + 'order' => 'lft', + 'bind' => [ + 'root' => $root_id, + ], + ] +); ``` ### Modifying a tree @@ -278,7 +294,7 @@ $audi = Categories::findFirst(3); $ford = Categories::findFirst(4); $mercedes = Categories::findFirst(5); -foreach([$audi,$ford,$mercedes] as $category) { +foreach ([$audi,$ford,$mercedes] as $category) { $category->moveAsLast($cars); } ``` @@ -405,7 +421,7 @@ public function initialize() new Blameable( [ 'auditClass' => MyAudit::class, - 'auditDetailClass' => MyAuditDetail::class + 'auditDetailClass' => MyAuditDetail::class, ] ) ); @@ -416,6 +432,7 @@ Also by default `Audit` class will look for userName key in session for getting You can change this behavior by: ```php +use Phalcon\DiInterface; use Phalcon\Mvc\Model\Behavior\Blameable; public function initialize() @@ -423,9 +440,9 @@ public function initialize() $this->addBehavior( new Blameable( [ - 'userCallback' => function(Phalcon\DiInterface $di) { + 'userCallback' => function (DiInterface $di) { // your custom code to return user name - } + }, ] ) ); @@ -443,7 +460,7 @@ public function initialize() $this->addBehavior( new Blameable( [ - 'snapshotUpdatingDisabled' => true + 'snapshotUpdatingDisabled' => true, ] ) ); 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/README.md b/Library/Phalcon/Mvc/Model/MetaData/README.md index 44a0f9fca..20e6fcad0 100644 --- a/Library/Phalcon/Mvc/Model/MetaData/README.md +++ b/Library/Phalcon/Mvc/Model/MetaData/README.md @@ -7,9 +7,14 @@ Usage examples of the adapters available here: This adapter uses a Wincache backend to store the cached content: ```php -$di->set('modelsMetadata', function () { - return new \Phalcon\Mvc\Model\MetaData\Wincache([ - 'lifetime' => 8600, - ]); -}); +$di->set( + 'modelsMetadata', + function () { + return new \Phalcon\Mvc\Model\MetaData\Wincache( + [ + 'lifetime' => 8600, + ] + ); + } +); ``` 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/Model/README.md b/Library/Phalcon/Mvc/Model/README.md index 9a1be86df..c79ff793e 100644 --- a/Library/Phalcon/Mvc/Model/README.md +++ b/Library/Phalcon/Mvc/Model/README.md @@ -33,7 +33,13 @@ $robots = Loader::fromResultset(Robot::find(), 'Parts'); # Equivalent to the sec $robots = Robot::with('Parts', 'Foo.Bar'); // And arguments can be passed to the find method -$robots = Robot::with('Parts', 'Foo.Bar', ['limit' => 5]); +$robots = Robot::with( + 'Parts', + 'Foo.Bar', + [ + 'limit' => 5, + ] +); // And constraints $robots = Robot::with( @@ -42,10 +48,10 @@ $robots = Robot::with( 'Foo.Bar' => function (QueryBuilder $builder) { // Limit Bar $builder->limit(5); - } + }, ], [ - 'limit' => 5 + 'limit' => 5, ] ); diff --git a/Library/Phalcon/Mvc/MongoCollection.php b/Library/Phalcon/Mvc/MongoCollection.php index 8ca5703a3..322e591ce 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(); } @@ -614,8 +669,11 @@ public function createIfNotExist(array $criteria) */ 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/README.md b/Library/Phalcon/Mvc/View/Engine/README.md index e30dde550..d9ad6403f 100644 --- a/Library/Phalcon/Mvc/View/Engine/README.md +++ b/Library/Phalcon/Mvc/View/Engine/README.md @@ -7,13 +7,14 @@ Mustache -------- [Mustache](https://github.com/bobthecow/mustache.php) is a logic-less template engine available for many platforms and languages. A PHP implementation is available in -[this Github repository](https://github.com/bobthecow/mustache.php). +[this GitHub repository](https://github.com/bobthecow/mustache.php). You need to manually load the Mustache library before use its engine adapter. Either registering an autoload function or including the relevant file first can achieve this. ```php require "path/to/Mustache/Autoloader.php"; + Mustache_Autoloader::register(); ``` @@ -21,18 +22,22 @@ Register the adapter in the view component: ```php //Setting up the view component -$di->set('view', function() { - - $view = new \Phalcon\Mvc\View(); - - $view->setViewsDir('../app/views/'); - - $view->registerEngines( - ['.mhtml' => 'Phalcon\Mvc\View\Engine\Mustache'] - ); - - return $view; -}); +$di->set( + 'view', + function () { + $view = new \Phalcon\Mvc\View(); + + $view->setViewsDir('../app/views/'); + + $view->registerEngines( + [ + '.mhtml' => 'Phalcon\Mvc\View\Engine\Mustache', + ] + ); + + return $view; + } +); ``` Twig @@ -43,24 +48,29 @@ You need to manually load the Twig library before use its engine adapter. Regist ```php require "path/to/Twig/Autoloader.php"; + Twig_Autoloader::register(); ``` Register the adapter in the view component: ```php // Setting up the view component -$di->set('view', function() { - - $view = new \Phalcon\Mvc\View(); - - $view->setViewsDir('../app/views/'); - - $view->registerEngines( - ['.twig' => 'Phalcon\Mvc\View\Engine\Twig'] - ); - - return $view; -}); +$di->set( + 'view', + function () { + $view = new \Phalcon\Mvc\View(); + + $view->setViewsDir('../app/views/'); + + $view->registerEngines( + [ + '.twig' => 'Phalcon\Mvc\View\Engine\Twig', + ] + ); + + return $view; + } +); ``` or @@ -70,26 +80,31 @@ use Phalcon\Mvc\View; use Phalcon\Mvc\View\Engine\Twig; // Setting up the view component -$di->set('view', function() { - - $view = new View(); - - $view->setViewsDir('../app/views/'); - - $view->registerEngines( - [ - '.twig' => function($view, $di) { - // Setting up Twig Environment Options - $options = ['cache' => '../cache/']; - $twig = new Twig($view, $di, $options); - - return $twig; - } - ] - ); - - return $view; -}); +$di->set( + 'view', + function () { + $view = new View(); + + $view->setViewsDir('../app/views/'); + + $view->registerEngines( + [ + '.twig' => function ($view, $di) { + // Setting up Twig Environment Options + $options = [ + 'cache' => '../cache/', + ]; + + $twig = new Twig($view, $di, $options); + + return $twig; + } + ] + ); + + return $view; + } +); ``` You can also create your own defined functions to extend Twig parsing capabilities by passing a forth parameter to the Twig constructor that consists of an Array of Twig_SimpleFunction elements. This will allow you to extend Twig, or even override default functions, with your own. @@ -100,38 +115,42 @@ use Phalcon\Mvc\View; use Phalcon\Mvc\View\Engine\Twig; // Setting up the view component -$di->set('view', function() { - - $view = new View(); - - $view->setViewsDir('../app/views/'); - - $view->registerEngines( - [ - '.twig' => function($view, $di) { - // Setting up Twig Environment Options - $options = ['cache' => '../cache/']; - - // Adding support for the native PHP chunk_split function - $user_functions = [ - new Twig_SimpleFunction( - 'chunk_split', - function ($string, $len = 76, $end = "\r\n") use ($di) { - return chunk_split($string, $len, $end); - }, - $options - ), - ]; - - $twig = new Twig($view, $di, $options, $user_functions); - - return $twig; - } - ] - ); - - return $view; -}); +$di->set( + 'view', + function () { + $view = new View(); + + $view->setViewsDir('../app/views/'); + + $view->registerEngines( + [ + '.twig' => function ($view, $di) { + // Setting up Twig Environment Options + $options = [ + 'cache' => '../cache/', + ]; + + // Adding support for the native PHP chunk_split function + $userFunctions = [ + new Twig_SimpleFunction( + 'chunk_split', + function ($string, $len = 76, $end = "\r\n") { + return chunk_split($string, $len, $end); + }, + $options + ), + ]; + + $twig = new Twig($view, $di, $options, $userFunctions); + + return $twig; + } + ] + ); + + return $view; + } +); ``` The engine implements "assets" tag in Twig templates: @@ -177,41 +196,49 @@ Register the adapter in the view component: use Phalcon\Mvc\View; // Setting up the view component -$di->set('view', function() { - - $view = new View(); - - $view->setViewsDir('../app/views/'); - - $view->registerEngines( - ['.tpl' => 'Phalcon\Mvc\View\Engine\Smarty'] - ); - - return $view; -}); +$di->set( + 'view', + function () { + $view = new View(); + + $view->setViewsDir('../app/views/'); + + $view->registerEngines( + [ + '.tpl' => \Phalcon\Mvc\View\Engine\Smarty::class, + ] + ); + + return $view; + } +); ``` -Smarty's equivalent to Phalcon's "setVar($key, $value)" function is "assign($key, $value, $nocache = false)" which has a third optional argument. This third argument, when set to true, marks the variable as exempt from caching. This is an essential Smarty feature that other template engines lack, being useful for pages that have portions that are often changing such as the current user who is logged in. If you want to utilize this additional argument, use the incubator SmartyView instead of View which extends View to include this functionality. +Smarty's equivalent to Phalcon's `setVar($key, $value)` function is `assign($key, $value, $nocache = false)` which has a third optional argument. This third argument, when set to true, marks the variable as exempt from caching. This is an essential Smarty feature that other template engines lack, being useful for pages that have portions that are often changing such as the current user who is logged in. If you want to utilize this additional argument, use the incubator SmartyView instead of View which extends View to include this functionality. ```php use Phalcon\Mvc\View\SmartyView; // Setting up the view component -$di->set('view', function() { - - $view = new SmartyView(); - - $view->setViewsDir('../app/views/'); - - $view->registerEngines( - ['.tpl' => 'Phalcon\Mvc\View\Engine\Smarty'] - ); - - return $view; -}); +$di->set( + 'view', + function () { + $view = new SmartyView(); + + $view->setViewsDir('../app/views/'); + + $view->registerEngines( + [ + '.tpl' => \Phalcon\Mvc\View\Engine\Smarty::class, + ] + ); + + return $view; + } +); ``` -You may now use the setVar function you are familiar with in Phalcon with the third, optional argument: +You may now use the `setVar()` method you are familiar with in Phalcon with the third, optional argument: ```php // This variable is exempt from caching @@ -227,35 +254,39 @@ Smarty can be configured to alter its default behavior, the following example ex use Phalcon\Mvc\View; use Phalcon\Mvc\View\Engine\Smarty; -$di->set('view', function() use ($config) { - - $view = new View(); - $view->setViewsDir('../app/views/'); - - $view->registerEngines( - [ - '.html' => function($view, $di) { - - $smarty = new Smarty($view, $di); - - $smarty->setOptions([ - 'template_dir' => $view->getViewsDir(), - 'compile_dir' => '../app/viewscompiled', - 'error_reporting' => error_reporting() ^ E_NOTICE, - 'escape_html' => true, - '_file_perms' => 0666, - '_dir_perms' => 0777, - 'force_compile' => false, - 'compile_check' => true, - 'caching' => false, - 'debugging' => true, - ]); - - return $smarty; - } - ] - ); - - return $view; -}); +$di->set( + 'view', + function () use ($config) { + $view = new View(); + + $view->setViewsDir('../app/views/'); + + $view->registerEngines( + [ + '.html' => function ($view, $di) { + $smarty = new Smarty($view, $di); + + $smarty->setOptions( + [ + 'template_dir' => $view->getViewsDir(), + 'compile_dir' => '../app/viewscompiled', + 'error_reporting' => error_reporting() ^ E_NOTICE, + 'escape_html' => true, + '_file_perms' => 0666, + '_dir_perms' => 0777, + 'force_compile' => false, + 'compile_check' => true, + 'caching' => false, + 'debugging' => true, + ] + ); + + return $smarty; + } + ] + ); + + return $view; + } +); ``` 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/Paginator/README.md b/Library/Phalcon/Paginator/README.md index 75569abe6..7b7b15ce4 100644 --- a/Library/Phalcon/Paginator/README.md +++ b/Library/Phalcon/Paginator/README.md @@ -11,20 +11,24 @@ use Phalcon\Paginator\Pager; class IndexController extends Controller { - public function indexAction() { - $currentPage = abs($this->request->getQuery('page', 'int', 1)); + $currentPage = abs( + $this->request->getQuery('page', 'int', 1) + ); + if ($currentPage == 0) { $currentPage = 1; } $pager = new Pager( - new Paginator([ - 'data' => range(1, 200), - 'limit' => 10, - 'page' => $currentPage, - ]), + new Paginator( + [ + 'data' => range(1, 200), + 'limit' => 10, + 'page' => $currentPage, + ] + ), [ // We will use Bootstrap framework styles 'layoutClass' => 'Phalcon\Paginator\Pager\Layout\Bootstrap', @@ -35,11 +39,13 @@ class IndexController extends Controller // Or something like this // 'urlMask' => sprintf( // '%s?page={%%page_number}', - // $this->url->get([ - // 'for' => 'index:posts', - // 'controller' => 'index', - // 'action' => 'index' - // ]) + // $this->url->get( + // [ + // 'for' => 'index:posts', + // 'controller' => 'index', + // 'action' => 'index', + // ] + // ) // ), ] ); diff --git a/Library/Phalcon/Queue/Beanstalk/README.md b/Library/Phalcon/Queue/Beanstalk/README.md index 082e1283d..8b31b39db 100644 --- a/Library/Phalcon/Queue/Beanstalk/README.md +++ b/Library/Phalcon/Queue/Beanstalk/README.md @@ -19,10 +19,12 @@ class IndexController extends Controller { if ($this->request->isPost()) { // Connect to the queue - $beanstalk = new BeanstalkExtended([ - 'host' => '192.168.0.21', - 'prefix' => 'project-name', - ]); + $beanstalk = new BeanstalkExtended( + [ + 'host' => '192.168.0.21', + 'prefix' => 'project-name', + ] + ); // Save the video info in database and send it to post-process $beanstalk->putInTube('processVideo', 4871); @@ -35,19 +37,20 @@ class IndexController extends Controller public function deleteVideoAction() { // Connect to the queue - $beanstalk = new BeanstalkExtended([ - 'host' => '192.168.0.21', - 'prefix' => 'project-name', - ]); + $beanstalk = new BeanstalkExtended( + [ + 'host' => '192.168.0.21', + 'prefix' => 'project-name', + ] + ); // Send the command to physical unlink to the queue $beanstalk->putInTube('deleteVideo', 4871); } - } ``` -Now handle the queues in console script (e.g.: php app/bin/video.php): +Now handle the queues in console script (e.g.: `php app/bin/video.php`): ```php #!/usr/bin/env php @@ -55,34 +58,45 @@ Now handle the queues in console script (e.g.: php app/bin/video.php): /** * Workers that handles queues related to the videos. */ + use Phalcon\Queue\Beanstalk\Extended as BeanstalkExtended; use Phalcon\Queue\Beanstalk\Job; $host = '192.168.0.21'; -$beanstalk = new BeanstalkExtended([ - 'host' => $host, - 'prefix' => 'project-name', -]); - -$beanstalk->addWorker($host.'processVideo', function (Job $job) { - // Here we should collect the meta information, - // make the screenshots, convert the video to the FLV etc. - $videoId = $job->getBody(); - - // It's very important to send the right exit code! - exit(0); -}); +$beanstalk = new BeanstalkExtended( + [ + 'host' => $host, + 'prefix' => 'project-name', + ] +); + +$beanstalk->addWorker( + $host . 'processVideo', + function (Job $job) { + // Here we should collect the meta information, + // make the screenshots, convert the video to the FLV etc. + $videoId = $job->getBody(); + + // It's very important to send the right exit code! + exit(0); + } +); -$beanstalk->addWorker($host.'deleteVideo', function (Job $job) { - // Here we should collect the meta information, - // make the screenshots, convert the video to the FLV etc. - $videoId = $job->getBody(); +$beanstalk->addWorker( + $host . 'deleteVideo', + function (Job $job) { + // Here we should collect the meta information, + // make the screenshots, convert the video to the FLV etc. + $videoId = $job->getBody(); - unlink('/var/www/data/' . $videoId . '.flv'); + unlink( + '/var/www/data/' . $videoId . '.flv' + ); - exit(0); -}); + exit(0); + } +); // Start processing queues $beanstalk->doWork(); @@ -93,26 +107,35 @@ Simple console script that outputs tubes stats: ```php #!/usr/bin/env php '192.168.0.21', - 'prefix' => $prefix, -]); - -foreach ($beanstalk->getTubes() as $tube) { - if (0 === strpos($tube, $prefix)) { - try { - $stats = $beanstalk->getTubeStats($tube); - printf( - "%s:\n\tready: %d\n\treserved: %d\n", - $tube, - $stats['current-jobs-ready'], - $stats['current-jobs-reserved'] - ); - } catch (\Exception $e) { - } +$beanstalk = new BeanstalkExtended( + [ + 'host' => '192.168.0.21', + 'prefix' => $prefix, + ] +); + +$tubes = $beanstalk->getTubes(); + +foreach ($tubes as $tube) { + if (0 !== strpos($tube, $prefix)) { + continue; + } + + try { + $stats = $beanstalk->getTubeStats($tube); + + printf( + "%s:\n\tready: %d\n\treserved: %d\n", + $tube, + $stats['current-jobs-ready'], + $stats['current-jobs-reserved'] + ); + } catch (\Exception $e) { + // ... } } ``` 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/Session/Adapter/README.md b/Library/Phalcon/Session/Adapter/README.md index 5c83d5d6e..cac887b59 100644 --- a/Library/Phalcon/Session/Adapter/README.md +++ b/Library/Phalcon/Session/Adapter/README.md @@ -16,26 +16,34 @@ Usage: ```php use Phalcon\Session\Adapter\Aerospike as SessionHandler; -$di->set('session', function () { - $session = new SessionHandler([ - '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(); - - return $session; -}); +$di->set( + 'session', + function () { + $session = new SessionHandler( + [ + '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(); + + return $session; + } +); ``` @@ -47,24 +55,31 @@ This adapter uses a database backend to store session data: use Phalcon\Db\Adapter\Pdo\Mysql; use Phalcon\Session\Adapter\Database; -$di->set('session', function() { - // Create a connection - $connection = new Mysql([ - 'host' => 'localhost', - 'username' => 'root', - 'password' => 'secret', - 'dbname' => 'test' - ]); - - $session = new Database([ - 'db' => $connection, - 'table' => 'session_data' - ]); - - $session->start(); - - return $session; -}); +$di->set( + 'session', + function () { + // Create a connection + $connection = new Mysql( + [ + 'host' => 'localhost', + 'username' => 'root', + 'password' => 'secret', + 'dbname' => 'test', + ] + ); + + $session = new Database( + [ + 'db' => $connection, + 'table' => 'session_data', + ] + ); + + $session->start(); + + return $session; + } +); ``` @@ -87,20 +102,24 @@ This adapter uses a Mongo database backend to store session data: ```php use Phalcon\Session\Adapter\Mongo as MongoSession; -$di->set('session', function() { - // Create a connection to mongo - $mongo = new \Mongo(); - - // Passing a collection to the adapter - $session = new MongoSession([ - 'collection' => $mongo->test->session_data - ]); +$di->set( + 'session', + function () { + // Create a connection to mongo + $mongo = new \Mongo(); - $session->start(); + // Passing a collection to the adapter + $session = new MongoSession( + [ + 'collection' => $mongo->test->session_data, + ] + ); - return $session; -}); + $session->start(); + return $session; + } +); ``` ## Redis @@ -111,15 +130,20 @@ You would need a [phpredis][4] extension installed to use it: ```php use Phalcon\Session\Adapter\Redis; -$di->set('session', function() { - $session = new Redis([ - 'path' => 'tcp://127.0.0.1:6379?weight=1' - ]); +$di->set( + 'session', + function () { + $session = new Redis( + [ + 'path' => 'tcp://127.0.0.1:6379?weight=1', + ] + ); - $session->start(); + $session->start(); - return $session; -}); + return $session; + } +); ``` @@ -142,24 +166,28 @@ CREATE TABLE `php_session` ( ```php use Phalcon\Session\Adapter\HandlerSocket; -$di->set('session', function() { - $session = new HandlerSocket([ - 'cookie_path' => '/', - 'cookie_domain' => '', - 'lifetime' => 3600, - 'server' => [ - 'host' => 'localhost', - 'port' => 9999, - 'dbname' => 'session', - 'dbtable' => 'php_session' - ] - ]); - - $session->start(); - - return $session; -}); - +$di->set( + 'session', + function () { + $session = new HandlerSocket( + [ + 'cookie_path' => '/', + 'cookie_domain' => '', + 'lifetime' => 3600, + 'server' => [ + 'host' => 'localhost', + 'port' => 9999, + 'dbname' => 'session', + 'dbtable' => 'php_session', + ], + ] + ); + + $session->start(); + + return $session; + } +); ``` The extension [`handlersocket`][5] is required to use this adapter. 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/Traits/README.md b/Library/Phalcon/Traits/README.md index 6f1722389..8c9813645 100644 --- a/Library/Phalcon/Traits/README.md +++ b/Library/Phalcon/Traits/README.md @@ -20,7 +20,7 @@ class MyAdapter protected $configurable = [ 'host', - 'viewsDir' + 'viewsDir', ]; public function __construct(array $options) diff --git a/Library/Phalcon/Translate/Adapter/Base.php b/Library/Phalcon/Translate/Adapter/Base.php deleted file mode 100644 index 1a1ff3819..000000000 --- a/Library/Phalcon/Translate/Adapter/Base.php +++ /dev/null @@ -1,32 +0,0 @@ - $value) { - $translation = str_replace('%' . $key . '%', $value, $translation); - } - } - - return $translation; - } -} diff --git a/Library/Phalcon/Translate/Adapter/CsvMulti.php b/Library/Phalcon/Translate/Adapter/CsvMulti.php new file mode 100644 index 000000000..1ceac8ec5 --- /dev/null +++ b/Library/Phalcon/Translate/Adapter/CsvMulti.php @@ -0,0 +1,139 @@ + $locale) { + $this->locales[$pos] = $locale; + } + } 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; + } + } + } + + fclose($fileHandler); + } + + /** + * 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'); + * + */ + 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." + ); + + return false; + } + + return $this->locale = $locale; + } + + /** + * Returns the translation related to the given key and the previsouly set locale + */ + public function query($index, $placeholders = null) + { + if (!$this->exists($index)) { + throw new Exception("They key '{$index}' was not found."); + } + + if ($this->locale === false) { + // "no translation mode" + $translation = $index; + } else { + $translation = $this->_translate[$this->locale][$index]; + } + + return $this->replacePlaceholders($translation, $placeholders); + } + + /** + * Check whether is defined a translation key in the internal array + */ + public function exists($index) + { + if (is_null($this->locale)) { + throw new Exception('The locale must have been defined.'); + } + + return in_array( + $index, + $this->getIndexes() + ); + } + + /** + * Returns all the translation keys + */ + public function getIndexes() + { + return $this->indexes; + } +} diff --git a/Library/Phalcon/Translate/Adapter/Database.php b/Library/Phalcon/Translate/Adapter/Database.php index ea3f966dd..c5f528e89 100644 --- a/Library/Phalcon/Translate/Adapter/Database.php +++ b/Library/Phalcon/Translate/Adapter/Database.php @@ -25,7 +25,7 @@ use Phalcon\Translate\AdapterInterface; use Phalcon\Translate\Exception; -class Database extends Base implements AdapterInterface, \ArrayAccess +class Database extends Adapter implements AdapterInterface, \ArrayAccess { /** * @var array @@ -44,13 +44,6 @@ class Database extends Base implements AdapterInterface, \ArrayAccess */ protected $stmtSelect; - /** - * Use ICU MessageFormatter to parse message - * - * @var boolean - */ - protected $useIcuMessageFormatter = false; - /** * Class constructor. * @@ -71,14 +64,6 @@ public function __construct(array $options) throw new Exception("Parameter 'language' is required"); } - if (isset($options['useIcuMessageFormatter'])) { - if (!class_exists('\MessageFormatter')) { - throw new Exception('"MessageFormatter" class is required'); - } - - $this->useIcuMessageFormatter = (boolean) $options['useIcuMessageFormatter']; - } - $this->stmtSelect = sprintf( 'SELECT value FROM %s WHERE language = :language AND key_name = :key_name', $options['table'] @@ -90,6 +75,8 @@ public function __construct(array $options) ); $this->options = $options; + + parent::__construct($options); } /** @@ -101,25 +88,18 @@ 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']; - if (is_array($placeholders) && !empty($placeholders)) { - if (true === $this->useIcuMessageFormatter) { - $value = \MessageFormatter::formatMessage($options['language'], $value, $placeholders); - } else { - foreach ($placeholders as $placeHolderKey => $placeHolderValue) { - $value = str_replace('%' . $placeHolderKey . '%', $placeHolderValue, $value); - } - } - } + $value = empty($translation['value']) ? $translateKey : $translation['value']; - return $value; + return $this->replacePlaceholders($value, $placeholders); } /** @@ -144,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']); @@ -164,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)); } /** @@ -181,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'], + ] + ] + ); } /** @@ -200,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 9bd1e5e13..6d05f2119 100644 --- a/Library/Phalcon/Translate/Adapter/Mongo.php +++ b/Library/Phalcon/Translate/Adapter/Mongo.php @@ -21,6 +21,7 @@ use Phalcon\Translate\Exception; use Phalcon\Mvc\CollectionInterface; +use Phalcon\Translate\Adapter; use Phalcon\Translate\AdapterInterface; /** @@ -33,11 +34,10 @@ * * @package Phalcon\Translate\Adapter */ -class Mongo extends Base implements AdapterInterface, \ArrayAccess +class Mongo extends Adapter implements AdapterInterface, \ArrayAccess { protected $language; protected $collection; - protected $formatter; /** * Mongo constructor. @@ -59,10 +59,8 @@ public function __construct($options) } $this->setLanguage($options['language']); - - if (isset($options['formatter'])) { - $this->setFormatter($options['formatter']); - } + + parent::__construct($options); } /** @@ -86,16 +84,6 @@ protected function setLanguage($language) $this->language = $language; } - /** - * Sets the formatter to use if necessary. - * - * @param \MessageFormatter $formatter Message formatter. - */ - protected function setFormatter(\MessageFormatter $formatter) - { - $this->formatter = $formatter; - } - /** * Gets the translations set. * @@ -109,7 +97,13 @@ protected function getTranslations($translateKey) /** @var CollectionInterface $collection */ $collection = $this->collection; - return $collection::findFirst([['key' => $translateKey]]); + return $collection::findFirst( + [ + [ + 'key' => $translateKey, + ], + ] + ); } /** @@ -132,34 +126,7 @@ public function query($translateKey, $placeholders = null) $translation = $translations->{$this->language}; } - if (!empty($placeholders)) { - return $this->format($translation, $placeholders); - } - - return $translation; - } - - /** - * Formats a translation. - * - * @param string $translation Translated text. - * @param array $placeholders Placeholders to apply. - * - * @return string - */ - protected function format($translation, $placeholders = []) - { - if ($this->formatter) { - $formatter = $this->formatter; - - return $formatter::formatMessage($this->language, $translation, $placeholders); - } - - foreach ($placeholders as $key => $value) { - $translation = str_replace("%$key%", $value, $translation); - } - - return $translation; + return $this->replacePlaceholders($value, $placeholders); } /** @@ -186,6 +153,7 @@ public function offsetExists($translateKey) public function offsetSet($translateKey, $message) { $translations = $this->getTranslations($translateKey); + $translations->{$this->language} = $message; return $translations->save(); @@ -211,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/README.md b/Library/Phalcon/Translate/Adapter/README.md index 83c3609d0..c70bccd4a 100644 --- a/Library/Phalcon/Translate/Adapter/README.md +++ b/Library/Phalcon/Translate/Adapter/README.md @@ -11,14 +11,19 @@ First of all, you need to up your database. To do this, use [DI][1] (in `/public ```php use Phalcon\Db\Adapter\Pdo\Mysql; -$di->set('db', function() { - return new Mysql([ - 'host' => 'localhost', - 'username' => 'root', - 'password' => 123456, - 'dbname' => 'application' - ]); -}); +$di->set( + 'db', + function () { + return new Mysql( + [ + 'host' => 'localhost', + 'username' => 'root', + 'password' => 123456, + 'dbname' => 'application', + ] + ); + } +); ``` Then, you should get the translation through your `controller`. Put this on it: @@ -28,17 +33,18 @@ use Phalcon\Translate\Adapter\Database; class IndexController extends \Phalcon\Mvc\Controller { - protected function _getTranslation() - { - return new Database([ - 'db' => $this->di->get('db'), // Here we're getting the database from DI - 'table' => 'translations', // The table that is storing the translations - 'language' => $this->request->getBestLanguage(), // Now we're getting the best language for the user - 'useIcuMessageFormatter' => true, // Optional, if need formatting message using ICU MessageFormatter - ]); - } - - // ... + protected function _getTranslation() + { + return new Database( + [ + 'db' => $this->di->get('db'), // Here we're getting the database from DI + 'table' => 'translations', // The table that is storing the translations + 'language' => $this->request->getBestLanguage(), // Now we're getting the best language for the user + ] + ); + } + + // ... } ``` @@ -68,15 +74,18 @@ from your database. *This step happens in your controller.* Follow the example: ```php class IndexController extends \Phalcon\Mvc\Controller { - protected function _getTranslation() - { - // ... - } - - public function indexAction() - { - $this->view->setVar('expression', $this->_getTranslation()); - } + protected function _getTranslation() + { + // ... + } + + public function indexAction() + { + $this->view->setVar( + 'expression', + $this->_getTranslation() + ); + } } ``` @@ -84,12 +93,12 @@ Then, just output the`phrase/sentence/word` in your view: ```php - - - - -

_("IndexPage_Hello_World"); ?>

- + + + + +

_("IndexPage_Hello_World"); ?>

+ ``` @@ -98,14 +107,6 @@ Or, if you wish you can use [Volt][2]:

{{ expression._("IndexPage_Hello_World") }}

``` -ICU MessageFormatter Example -```php -// Example plural message with key 'cats' -// Peter has {nbCats, plural, =0{no cat} =1{a cat} other{# cats}} - -$this->_getTranslation()->_('cats', ['nbCats' => rand(0, 10)]); -``` - ## Mongo Implements a Mongo adapter for translations. @@ -117,17 +118,13 @@ use MessageFormatter; use Phalcon\Translate\Adapter\Mongo; use My\Application\Collections\Translate; -$fmt = new MessageFormatter( - "en_US", - "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree" +$translate = new Mongo( + [ + 'collection' => Translate::class, + 'language' => 'en', + ] ); -$translate = new Mongo([ - 'collection' => Translate::class, - 'language' => 'en', - 'formatter' => $fmt, -]); - echo $translate->t('application.title'); ``` @@ -141,14 +138,22 @@ The extension [intl][3] must be installed in PHP. ```php use Phalcon\Translate\Adapter\ResourceBundle; -$translate = new ResourceBundle([ - 'bundle' => '/path/to/bundle', // required - 'locale' => 'en', // required - 'fallback' => false // optional, default - true -]); +$translate = new ResourceBundle( + [ + 'bundle' => '/path/to/bundle', // required + 'locale' => 'en', // required + 'fallback' => false, // optional, default - true + ] +); echo $translate->t('application.title'); -echo $translate->t('application.copyright', ['currentYear' => new \DateTime('now')]); + +echo $translate->t( + 'application.copyright', + [ + 'currentYear' => new \DateTime('now'), + ] +); ``` ResourceBundle source file example @@ -165,3 +170,28 @@ root { [1]: http://docs.phalconphp.com/en/latest/api/Phalcon_DI.html [2]: http://docs.phalconphp.com/en/latest/reference/volt.html [3]: http://php.net/manual/en/book.intl.php + +## MultiCsv + +This adapter extends *Phalcon\Translate\Adapter\Csv* by allowing one csv file for several languages. + +* CSV example (blank spaces added for readability): +```csv +#ignored; en_US; fr_FR; es_ES +label_street; street; rue; calle +label_car; car; voiture; coche +label_home; home; maison; casa +``` +* PHP example : +```php +// the constructor is inherited from Phalcon\Translate\Adapter\Csv +$titles_translater = new Phalcon\Translate\Adapter\MultiCsv( + [ + 'content' => "{$config->langDir}/titles.csv", + ] +); + +$titles_translater->setLocale('es_ES'); + +echo $titles_translater->query('label_home'); // string 'casa' +``` diff --git a/Library/Phalcon/Translate/Adapter/Redis.php b/Library/Phalcon/Translate/Adapter/Redis.php index 0cab6dc7a..81bf72251 100644 --- a/Library/Phalcon/Translate/Adapter/Redis.php +++ b/Library/Phalcon/Translate/Adapter/Redis.php @@ -1,6 +1,7 @@ levels = $options['levels']; } + + parent::__construct($options); } /** @@ -93,9 +96,11 @@ public function query($translateKey, $placeholders = null) $this->loadValueByKey($key); - return isset($this->cache[$key]) && isset($this->cache[$key][$index]) + $value = isset($this->cache[$key]) && isset($this->cache[$key][$index]) ? $this->cache[$key][$index] : $translateKey; + + return $this->replacePlaceholders($value, $placeholders); } /** @@ -118,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 909eaf526..7d174c1bf 100644 --- a/Library/Phalcon/Translate/Adapter/ResourceBundle.php +++ b/Library/Phalcon/Translate/Adapter/ResourceBundle.php @@ -8,7 +8,7 @@ /** * ResourceBundle adapter */ -class ResourceBundle extends Base implements AdapterInterface +class ResourceBundle extends Adapter implements AdapterInterface { /** * @var \ResourceBundle @@ -42,10 +42,6 @@ public function __construct($options) throw new Exception('"ResourceBundle" class is required'); } - if (!class_exists('\MessageFormatter')) { - throw new Exception('"MessageFormatter" class is required'); - } - if (!isset($options['bundle'])) { throw new Exception('"bundle" option is required'); } @@ -59,7 +55,14 @@ 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); } /** @@ -88,13 +91,10 @@ public function query($index, $placeholders = null) return $index; } - $formatter = new \MessageFormatter($this->options['locale'], $this->get($index, $this->bundle)); - - if (null !== $formatter) { - return $formatter->format((array) $placeholders); - } else { - return $index; - } + return $this->replacePlaceholders( + $this->get($index, $this->bundle), + $placeholders + ); } /** diff --git a/Library/Phalcon/Translate/Interpolator/Intl.php b/Library/Phalcon/Translate/Interpolator/Intl.php new file mode 100644 index 000000000..af28f5e33 --- /dev/null +++ b/Library/Phalcon/Translate/Interpolator/Intl.php @@ -0,0 +1,52 @@ +locale = $locale; + } + + /** + * Replaces placeholders by the values passed + * Use the MessageFormatter class, + * See http://php.net/manual/en/class.messageformatter.php + */ + public function replacePlaceholders($translation, $placeholders = null) + { + if (is_array($placeholders) && count($placeholders)) { + try { + // TODO (?) : keep an internal cache of the MessageFormatter objects (key = locale.translation) + $fmt = new MessageFormatter($this->locale, $translation); + } catch (IntlException $e) { + $fmt = null; + } finally { + // for php 7.x the original exception message is "Constructor failed" + // for php 5.6 the constructor returns null, see this wont fix bug https://bugs.php.net/bug.php?id=58631 + // make it a bit more understandable + if (is_null($fmt)) { + throw new Exception( + "Unable to instantiate a MessageFormatter. Check locale and string syntax.", + 0, + isset($e) ? $e : null + ); + } + } + + $translation = $fmt->format($placeholders); + if ($translation === false) { + throw new Exception($fmt->getErrorMessage(), $fmt->getErrorCode()); + } + } + return $translation; + } +} diff --git a/Library/Phalcon/Translate/Interpolator/README.md b/Library/Phalcon/Translate/Interpolator/README.md new file mode 100644 index 000000000..d6dda6118 --- /dev/null +++ b/Library/Phalcon/Translate/Interpolator/README.md @@ -0,0 +1,59 @@ +# Phalcon\Translate\Interpolator + +Usage examples of the interpolators available here: + +## Intl + +It needs the extension [intl](php.net/manual/book.intl.php) to be installed in PHP, and it uses [MessageFormatter](http://php.net/manual/en/class.messageformatter.php) objects in an interpolator interface. +More about the syntax convention can be read on this [formating guide](https://www.sitepoint.com/localization-demystified-understanding-php-intl/) and on the [ICU documentation](http://userguide.icu-project.org/formatparse/messages). + +```php + new Intl('en_US'), // this interpolator must be locale aware + 'content' => [ + 'hi-name' => 'Hello {name}, it\'s {time, number, integer} o\'clock', + ], + ] +); + +$name = 'Henry'; + +// Hello Henry, it's 8 o'clock +$translate->_( + 'hi-name', + [ + 'name' => $name, + 'time' => 8, + ] +); +``` + +```php + new Intl('fr_FR'), // this interpolator must be locale aware + 'content' => [ + 'apples' => "{count, plural, =0{Je n'ai aucune pomme} =1{J'ai une pomme} other{J'ai # pommes}}.", + ], + ] +); + +// thousands separator is " " (blank space) for fr_FR +echo $translate->_( + 'apples', + [ + 'count' => 1000, + ] +); // J'ai 1 000 pommes +``` 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 new file mode 100644 index 000000000..89667ada9 --- /dev/null +++ b/Library/Phalcon/Validation/Validator/ArrayInclusionIn.php @@ -0,0 +1,58 @@ +getValue($attribute); + $domain = $this->getOption('domain'); + $allowEmpty = $this->getOption('allowEmpty'); + + if ((empty($array) && !$allowEmpty) || empty($domain) || !is_array($array)) { + $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 + ) + ); + + 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/README.md b/Library/Phalcon/Validation/Validator/Db/README.md index 568945f67..1b64a9072 100644 --- a/Library/Phalcon/Validation/Validator/Db/README.md +++ b/Library/Phalcon/Validation/Validator/Db/README.md @@ -1,11 +1,15 @@ # Phalcon\Validation\Validator\Db -Usage examples of db validators available here: +Usage examples of DB validators available here: ## Uniqueness ```php -$connection = new \Phalcon\Db\Adapter\Pdo\Sqlite(['dbname' => 'sample.db']); +$connection = new \Phalcon\Db\Adapter\Pdo\Sqlite( + [ + 'dbname' => 'sample.db', + ] +); $uniqueness = new \Phalcon\Validation\Validator\Db\Uniqueness( [ @@ -13,6 +17,6 @@ $uniqueness = new \Phalcon\Validation\Validator\Db\Uniqueness( 'column' => 'login', 'message' => 'already taken', ], - $connection; + $connection ); ``` 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/README.md b/Library/Phalcon/Validation/Validator/README.md index 36461d3d9..251e919f6 100644 --- a/Library/Phalcon/Validation/Validator/README.md +++ b/Library/Phalcon/Validation/Validator/README.md @@ -26,12 +26,16 @@ use Phalcon\Validation\Validator\ReCaptcha; $reCaptcha = new Hidden('g-recaptcha-response'); -$reCaptcha->setLabel('reCAPTCHA')->addValidators([ - new ReCaptcha([ - 'message' => 'The captcha is not valid', - 'secret' => 'your_site_key', - ]), -]); +$reCaptcha->setLabel('reCAPTCHA')->addValidators( + [ + new ReCaptcha( + [ + 'message' => 'The captcha is not valid', + 'secret' => 'your_site_key', + ] + ), + ] +); $this->add($reCaptcha); ``` @@ -50,13 +54,13 @@ The IpValidator validates a valid ip address. ```php $data['ip'] = $this->request->getPost('ip'); -$validation = new Phalcon\Validation(); +$validation = new \Phalcon\Validation(); $validation->add( 'ip', - new MicheleAngioni\PhalconValidators\IpValidator ( + new \MicheleAngioni\PhalconValidators\IpValidator( [ - 'message' => 'The IP is not valid.' // Optional + 'message' => 'The IP is not valid.', // Optional ] ) ); @@ -65,7 +69,6 @@ $messages = $validation->validate($data); if (count($messages)) { // Some error occurred, handle messages - } ``` @@ -83,20 +86,20 @@ Optionally also signed numbers are supported. ```php $data['number'] = $this->request->getPost('number'); -$validation = new Phalcon\Validation(); +$validation = new \Phalcon\Validation(); $validation->add( 'number', - new MicheleAngioni\PhalconValidators\NumericValidator ( + new \MicheleAngioni\PhalconValidators\NumericValidator( [ - 'allowFloat' => true, // Optional, default: false - 'allowSign' => true, // Optional, default: false - 'min' => 2, // Optional - 'min' => 2, // Optional - 'max' => 50, // Optional - 'message' => 'Only numeric (0-9,.) characters are allowed.', // Optional - 'messageMinimum' => 'The value must be at least 2', // Optional - 'messageMaximum' => 'The value must be lower than 50' // Optional + 'allowFloat' => true, // Optional, default: false + 'allowSign' => true, // Optional, default: false + 'min' => 2, // Optional + 'min' => 2, // Optional + 'max' => 50, // Optional + 'message' => 'Only numeric (0-9,.) characters are allowed.', // Optional + 'messageMinimum' => 'The value must be at least 2', // Optional + 'messageMaximum' => 'The value must be lower than 50', // Optional ] ) ); @@ -105,7 +108,6 @@ $messages = $validation->validate($data); if (count($messages)) { // Some error occurred, handle messages - } // Validation succeeded without errors @@ -119,19 +121,19 @@ Minimum and maximum string lengths can be specified. ```php $data['text'] = $this->request->getPost('text'); -$validation = new Phalcon\Validation(); +$validation = new \Phalcon\Validation(); $validation->add( 'text', - new MicheleAngioni\PhalconValidators\AlphaNumericValidator ( + new \MicheleAngioni\PhalconValidators\AlphaNumericValidator( [ - 'whiteSpace' => true, // Optional, default false - 'underscore' => true, // Optional, default false - 'min' => 6, // Optional - 'max' => 30, // Optional - 'message' => 'Validation failed.', // Optional - 'messageMinimum' => 'The value must contain at least 6 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 30 characters.' // Optional + 'whiteSpace' => true, // Optional, default false + 'underscore' => true, // Optional, default false + 'min' => 6, // Optional + 'max' => 30, // Optional + 'message' => 'Validation failed.', // Optional + 'messageMinimum' => 'The value must contain at least 6 characters.', // Optional + 'messageMaximum' => 'The value can contain maximum 30 characters.', // Optional ] ) ); @@ -140,7 +142,6 @@ $messages = $validation->validate($data); if (count($messages)) { // Some error occurred, handle messages - } // Validation succeeded without errors @@ -155,18 +156,18 @@ Minimum and maximum string lengths can be specified. ```php $data['text'] = $this->request->getPost('text'); -$validation = new Phalcon\Validation(); +$validation = new \Phalcon\Validation(); $validation->add( 'text', - new MicheleAngioni\PhalconValidators\AlphaNamesValidator ( + new \MicheleAngioni\PhalconValidators\AlphaNamesValidator( [ - 'numbers' => true, // Optional, default false - 'min' => 6, // Optional - 'max' => 30, // Optional - 'message' => 'Validation failed.', // Optional - 'messageMinimum' => 'The value must contain at least 6 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 30 characters.' // Optional + 'numbers' => true, // Optional, default false + 'min' => 6, // Optional + 'max' => 30, // Optional + 'message' => 'Validation failed.', // Optional + 'messageMinimum' => 'The value must contain at least 6 characters.', // Optional + 'messageMaximum' => 'The value can contain maximum 30 characters.', // Optional ] ) ); @@ -175,7 +176,6 @@ $messages = $validation->validate($data); if (count($messages)) { // Some error occurred, handle messages - } // Validation succeeded without errors @@ -190,20 +190,20 @@ Minimum and maximum string lengths can be specified. ```php $data['text'] = $this->request->getPost('text'); -$validation = new Phalcon\Validation(); +$validation = new \Phalcon\Validation(); $validation->add( 'text', - new MicheleAngioni\PhalconValidators\AlphaCompleteValidator ( + new \MicheleAngioni\PhalconValidators\AlphaCompleteValidator( [ - 'allowBackslashes' => true, // Optional - 'allowPipes' => true, // Optional - 'allowUrlChars' => true, // Optional - 'min' => 6, // Optional - 'max' => 30, // Optional - 'message' => 'Validation failed.', // Optional - 'messageMinimum' => 'The value must contain at least 6 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 30 characters.' // Optional + 'allowBackslashes' => true, // Optional + 'allowPipes' => true, // Optional + 'allowUrlChars' => true, // Optional + 'min' => 6, // Optional + 'max' => 30, // Optional + 'message' => 'Validation failed.', // Optional + 'messageMinimum' => 'The value must contain at least 6 characters.', // Optional + 'messageMaximum' => 'The value can contain maximum 30 characters.', // Optional ] ) ); @@ -212,7 +212,6 @@ $messages = $validation->validate($data); if (count($messages)) { // Some error occurred, handle messages - } // Validation succeeded without errors diff --git a/Library/Phalcon/Validation/Validator/ReCaptcha.php b/Library/Phalcon/Validation/Validator/ReCaptcha.php index 3cf5fc9a6..d7e7d8938 100644 --- a/Library/Phalcon/Validation/Validator/ReCaptcha.php +++ b/Library/Phalcon/Validation/Validator/ReCaptcha.php @@ -40,10 +40,18 @@ * * use Phalcon\Validation\Validator; * - * $validator->add('g-recaptcha-response', new Validator([ - * 'message' => 'The captcha is not valid', - * 'secret' => 'your_site_key' - * ])); + * $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 @@ -58,6 +66,7 @@ class ReCaptcha extends Validator /** * Response error code reference + * * @var array $messages */ protected $messages = [ @@ -80,23 +89,42 @@ public function validate(Validation $validation, $attribute) $secret = $this->getOption('secret'); $value = $validation->getValue($attribute); $request = $validation->getDI()->get('request'); - $remoteIp = $request->getClientAddress(false); + + if ($this->hasOption('ip')) { + $remoteIp = $this->getOption('ip'); + } else { + $remoteIp = $request->getClientAddress(false); + } 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); } - if (empty($response['success'])) { + if (empty($response['success']) + || ($this->hasOption('score') + && $this->getOption('score') > $response['score']) + || ($this->hasOption('action') + && $this->getOption('action') !== $response['action']) + ) { $label = $this->getOption('label'); if (empty($label)) { $label = $validation->getLabel($attribute); @@ -104,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']]; } @@ -112,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; } diff --git a/README.md b/README.md index d3b3a516a..360ea6aca 100644 --- a/README.md +++ b/README.md @@ -71,9 +71,11 @@ to load classes from the incubator repository: $loader = new Phalcon\Loader(); -$loader->registerNamespaces([ - 'Phalcon' => '/path/to/incubator/Library/Phalcon/' -]); +$loader->registerNamespaces( + [ + 'Phalcon' => '/path/to/incubator/Library/Phalcon/', + ] +); $loader->register(); ``` diff --git a/composer.json b/composer.json index 94301ee8d..fd6040263 100644 --- a/composer.json +++ b/composer.json @@ -37,7 +37,7 @@ "phpdocumentor/reflection-docblock": "2.0.4", "phpunit/phpunit": "^4.8", "squizlabs/php_codesniffer": "^2.9", - "codeception/codeception": "2.3.6", + "codeception/codeception": "^2.5", "codeception/mockery-module": "0.2.2", "codeception/aerospike-module": "^1.0", "codeception/specify": "^0.4", diff --git a/tests/_bootstrap.php b/tests/_bootstrap.php index 6f68e8997..96f62c5f5 100644 --- a/tests/_bootstrap.php +++ b/tests/_bootstrap.php @@ -1,8 +1,8 @@ load(); +(new Dotenv\Dotenv(realpath(__DIR__)))->load(); require_once '_support/functions.php'; @@ -24,13 +24,33 @@ clearstatcache(); -$root = realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR; +$root = realpath(__DIR__) . DIRECTORY_SEPARATOR; define('TESTS_PATH', $root); -define('PROJECT_PATH', dirname(TESTS_PATH) . DIRECTORY_SEPARATOR); -define('PATH_DATA', $root . '_data' . DIRECTORY_SEPARATOR); -define('PATH_CACHE', $root . '_cache' . DIRECTORY_SEPARATOR); -define('PATH_OUTPUT', $root . '_output' . DIRECTORY_SEPARATOR); -define('INCUBATOR_FIXTURES', $root . '_fixtures' . DIRECTORY_SEPARATOR); + +define( + 'PROJECT_PATH', + dirname(TESTS_PATH) . DIRECTORY_SEPARATOR +); + +define( + 'PATH_DATA', + $root . '_data' . DIRECTORY_SEPARATOR +); + +define( + 'PATH_CACHE', + $root . '_cache' . DIRECTORY_SEPARATOR +); + +define( + 'PATH_OUTPUT', + $root . '_output' . DIRECTORY_SEPARATOR +); + +define( + 'INCUBATOR_FIXTURES', + $root . '_fixtures' . DIRECTORY_SEPARATOR +); unset($root); diff --git a/tests/_data/assets/translation/csv/names.csv b/tests/_data/assets/translation/csv/names.csv new file mode 100644 index 000000000..f8853f67e --- /dev/null +++ b/tests/_data/assets/translation/csv/names.csv @@ -0,0 +1,4 @@ +;en_US;fr_FR;es_ES +label_street;street;rue;calle +label_car;car;voiture;coche +label_home;home;maison;casa \ No newline at end of file diff --git a/tests/_data/dump.sql b/tests/_data/dump.sql index 093d74c28..cac64de41 100644 --- a/tests/_data/dump.sql +++ b/tests/_data/dump.sql @@ -1290,3 +1290,17 @@ CREATE TABLE `sessions` ( created_at INT, modified_at INT )ENGINE=InnoDB DEFAULT CHARSET=utf8; + +DROP TABLE if EXISTS `translations`; +CREATE TABLE `translations` ( + `id` INT(11) NOT NULL AUTO_INCREMENT, + `language` VARCHAR(5) NOT NULL COLLATE 'utf8_bin', + `key_name` VARCHAR(48) NOT NULL COLLATE 'utf8_bin', + `value` TEXT NOT NULL COLLATE 'utf8_bin', + PRIMARY KEY (`id`) +)ENGINE=InnoDB DEFAULT CHARSET=utf8; + +INSERT INTO `translations` (`language`,`key_name`,`value`) VALUES + ('en_US','hello','Hello!'), + ('fr_FR','hello','Salut!'), + ('es_ES','hello','¡Hola!'); diff --git a/tests/aerospike/Annotations/Adapter/AerospikeTest.php b/tests/aerospike/Annotations/Adapter/AerospikeTest.php index c77c1a363..3d7a7a58e 100644 --- a/tests/aerospike/Annotations/Adapter/AerospikeTest.php +++ b/tests/aerospike/Annotations/Adapter/AerospikeTest.php @@ -47,17 +47,26 @@ protected function _before() public function testHasAerospikeProperty() { - $this->assertClassHasAttribute('aerospike', Aerospike::class); + $this->assertClassHasAttribute( + 'aerospike', + Aerospike::class + ); } public function testHasNamespaceProperty() { - $this->assertClassHasAttribute('namespace', Aerospike::class); + $this->assertClassHasAttribute( + 'namespace', + Aerospike::class + ); } public function testHasSetProperty() { - $this->assertClassHasAttribute('set', Aerospike::class); + $this->assertClassHasAttribute( + 'set', + Aerospike::class + ); } /** @@ -67,10 +76,18 @@ public function testHasSetProperty() */ public function testShouldReadAndWriteToAerospikeWithoutPrefix($key, $data) { - $object = new Aerospike(['hosts' => $this->getHostConfig()]); + $object = new Aerospike( + [ + 'hosts' => $this->getHostConfig(), + ] + ); + $object->write($key, $data); - $this->assertEquals($data, $object->read($key)); + $this->assertEquals( + $data, + $object->read($key) + ); } /** @@ -80,33 +97,78 @@ public function testShouldReadAndWriteToAerospikeWithoutPrefix($key, $data) */ public function testShouldReadAndWriteToAerospikeWithPrefix($key, $data) { - $object = new Aerospike(['hosts' => $this->getHostConfig(), 'prefix' => 'test_']); + $object = new Aerospike( + [ + 'hosts' => $this->getHostConfig(), + 'prefix' => 'test_', + ] + ); + $object->write($key, $data); - $this->assertEquals($data, $object->read($key)); + $this->assertEquals( + $data, + $object->read($key) + ); } public function testShouldGetCacheBackendThroughGetter() { - $object = new Aerospike(['hosts' => $this->getHostConfig()]); + $object = new Aerospike( + [ + 'hosts' => $this->getHostConfig(), + ] + ); + + $reflectedMethod = new ReflectionMethod( + get_class($object), + 'getCacheBackend' + ); - $reflectedMethod = new ReflectionMethod(get_class($object), 'getCacheBackend'); $reflectedMethod->setAccessible(true); - $this->assertInstanceOf(CacheBackend::class, $reflectedMethod->invoke($object)); + + $this->assertInstanceOf( + CacheBackend::class, + $reflectedMethod->invoke($object) + ); } public function testShouldGetCacheBackendThroughReflectionSetter() { - $object = new Aerospike(['hosts' => $this->getHostConfig()]); - $mock = $this->getMock(CacheBackend::class, [], [], '', false); + $object = new Aerospike( + [ + 'hosts' => $this->getHostConfig(), + ] + ); + + $mock = $this->getMock( + CacheBackend::class, + [], + [], + '', + false + ); + + $reflectedProperty = new ReflectionProperty( + get_class($object), + 'aerospike' + ); - $reflectedProperty = new ReflectionProperty(get_class($object), 'aerospike'); $reflectedProperty->setAccessible(true); + $reflectedProperty->setValue($object, $mock); - $reflectedMethod = new ReflectionMethod(get_class($object), 'getCacheBackend'); + $reflectedMethod = new ReflectionMethod( + get_class($object), + 'getCacheBackend' + ); + $reflectedMethod->setAccessible(true); - $this->assertInstanceOf(CacheBackend::class, $reflectedMethod->invoke($object)); + + $this->assertInstanceOf( + CacheBackend::class, + $reflectedMethod->invoke($object) + ); } /** @@ -115,11 +177,23 @@ public function testShouldGetCacheBackendThroughReflectionSetter() */ public function testShouldPrepareKey($key) { - $object = new Aerospike(['hosts' => $this->getHostConfig()]); - $reflectedMethod = new ReflectionMethod(get_class($object), 'prepareKey'); + $object = new Aerospike( + [ + 'hosts' => $this->getHostConfig(), + ] + ); + + $reflectedMethod = new ReflectionMethod( + get_class($object), + 'prepareKey' + ); + $reflectedMethod->setAccessible(true); - $this->assertEquals($key, $reflectedMethod->invoke($object, $key)); + $this->assertEquals( + $key, + $reflectedMethod->invoke($object, $key) + ); } /** @@ -130,10 +204,18 @@ public function testShouldPrepareKey($key) public function testShouldCreateAerospikeAdapterInstanceAndSetOptions($options, $expected) { $object = new Aerospike($options); - $reflectedProperty = new ReflectionProperty(get_class($object), 'options'); + + $reflectedProperty = new ReflectionProperty( + get_class($object), + 'options' + ); + $reflectedProperty->setAccessible(true); - $this->assertEquals($expected, $reflectedProperty->getValue($object)); + $this->assertEquals( + $expected, + $reflectedProperty->getValue($object) + ); } /** @@ -142,7 +224,10 @@ public function testShouldCreateAerospikeAdapterInstanceAndSetOptions($options, */ public function testShouldCatchExceptionWhenInvalidParamsPassed($options) { - $this->setExpectedException(Exception::class, 'No hosts given in options'); + $this->setExpectedException( + Exception::class, + 'No hosts given in options' + ); new Aerospike($options); } @@ -150,7 +235,17 @@ public function testShouldCatchExceptionWhenInvalidParamsPassed($options) public function providerReadWrite() { // This key is needed in order not to break your real data - $key = hash('sha256', json_encode([__CLASS__, __METHOD__, __FILE__, __LINE__])); + $key = hash( + 'sha256', + json_encode( + [ + __CLASS__, + __METHOD__, + __FILE__, + __LINE__, + ] + ) + ); return [ 'string' => [$key . '_test1', 'data1'], @@ -168,7 +263,7 @@ public function providerKey() return [ ['key1'], [1], - ['_key1'] + ['_key1'], ]; } @@ -195,124 +290,135 @@ public function providerConstructor() return [ //$this->getConfig() [ [ - 'hosts' => $this->getHostConfig(), - 'lifetime' => 23 + 'hosts' => $this->getHostConfig(), + 'lifetime' => 23, ], [ - 'hosts' => $this->getHostConfig(), - 'lifetime' => 23, - 'prefix' => '', + 'hosts' => $this->getHostConfig(), + 'lifetime' => 23, + 'prefix' => '', 'persistent' => false, - 'options' => [] - ] + 'options' => [], + ], ], + [ [ - 'hosts' => $this->getHostConfig(), + 'hosts' => $this->getHostConfig(), 'lifetime' => 23, - 'options' => [ + 'options' => [ 1 => 1250, 3 => 1500 ] ], [ - 'hosts' => $this->getHostConfig(), - 'lifetime' => 23, - 'prefix' => '', + 'hosts' => $this->getHostConfig(), + 'lifetime' => 23, + 'prefix' => '', 'persistent' => false, - 'options' => [ + 'options' => [ 1 => 1250, - 3 => 1500 - ] - ] + 3 => 1500, + ], + ], ], + [ [ - 'hosts' => $this->getHostConfig(), - 'lifetime' => 23, - 'persistent' => true + 'hosts' => $this->getHostConfig(), + 'lifetime' => 23, + 'persistent' => true, ], [ - 'hosts' => $this->getHostConfig(), - 'lifetime' => 23, - 'prefix' => '', + 'hosts' => $this->getHostConfig(), + 'lifetime' => 23, + 'prefix' => '', 'persistent' => true, - 'options' => [], - ] + 'options' => [], + ], ], + [ [ - 'hosts' => $this->getHostConfig(), - 'prefix' => 'test_' + 'hosts' => $this->getHostConfig(), + 'prefix' => 'test_', ], [ - 'hosts' => $this->getHostConfig(), - 'lifetime' => 8600, - 'prefix' => 'test_', + 'hosts' => $this->getHostConfig(), + 'lifetime' => 8600, + 'prefix' => 'test_', 'persistent' => false, - 'options' => [], - ] + 'options' => [], + ], ], + [ [ - 'hosts' => $this->getHostConfig(), - 'randomValue' => 'test_' + 'hosts' => $this->getHostConfig(), + 'randomValue' => 'test_', ], [ - 'hosts' => $this->getHostConfig(), + 'hosts' => $this->getHostConfig(), 'randomValue' => 'test_', - 'lifetime' => 8600, - 'prefix' => '', - 'persistent' => false, - 'options' => [], - ] + 'lifetime' => 8600, + 'prefix' => '', + 'persistent' => false, + 'options' => [], + ], ], + [ [ 'hosts' => $this->getHostConfig(), - 123 => 'test_' + 123 => 'test_' ], [ - 'hosts' => $this->getHostConfig(), - 123 => 'test_', - 'lifetime' => 8600, - 'prefix' => '', + 'hosts' => $this->getHostConfig(), + 123 => 'test_', + 'lifetime' => 8600, + 'prefix' => '', 'persistent' => false, - 'options' => [], - ] + 'options' => [], + ], ], + [ [ - 'hosts' => $this->getHostConfig(), + 'hosts' => $this->getHostConfig(), 'lifetime' => 24, - 'prefix' => 'test_', + 'prefix' => 'test_', ], [ - 'hosts' => $this->getHostConfig(), - 'lifetime' => 24, - 'prefix' => 'test_', + 'hosts' => $this->getHostConfig(), + 'lifetime' => 24, + 'prefix' => 'test_', 'persistent' => false, - 'options' => [], - ] + 'options' => [], + ], ], + [ [ 'hosts' => $this->getHostConfig(), ], [ - 'hosts' => $this->getHostConfig(), - 'lifetime' => 8600, - 'prefix' => '', + 'hosts' => $this->getHostConfig(), + 'lifetime' => 8600, + 'prefix' => '', 'persistent' => false, - 'options' => [], - ] + 'options' => [], + ], ], - ]; } private function getHostConfig() { - return [['addr' => env('TEST_AS_HOST', '127.0.0.1'), 'port' => (int)env('TEST_AS_PORT', 3000)]]; + return [ + [ + 'addr' => env('TEST_AS_HOST', '127.0.0.1'), + 'port' => (int) env('TEST_AS_PORT', 3000), + ] + ]; } } diff --git a/tests/aerospike/Cache/Backend/AerospikeTest.php b/tests/aerospike/Cache/Backend/AerospikeTest.php index 853c5ede6..e9ccba362 100644 --- a/tests/aerospike/Cache/Backend/AerospikeTest.php +++ b/tests/aerospike/Cache/Backend/AerospikeTest.php @@ -48,7 +48,10 @@ protected function _before() public function testShouldGetAerospikeInstance() { - $this->assertInstanceOf(\Aerospike::class, $this->getAdapter()->getDb()); + $this->assertInstanceOf( + \Aerospike::class, + $this->getAdapter()->getDb() + ); } /** @@ -63,27 +66,55 @@ public function testShouldThrowExceptionIfCacheIsNotStarted() public function testShouldIncrementValue() { $cache = $this->getAdapter(); + $this->tester->haveInAerospike('increment', 1); - $this->assertEquals(2, $cache->increment('increment')); - $this->assertEquals(4, $cache->increment('increment', 2)); - $this->assertEquals(14, $cache->increment('increment', 10)); + $this->assertEquals( + 2, + $cache->increment('increment') + ); + + $this->assertEquals( + 4, + $cache->increment('increment', 2) + ); + + $this->assertEquals( + 14, + $cache->increment('increment', 10) + ); } public function testShouldDecrementValue() { $cache = $this->getAdapter(); + $this->tester->haveInAerospike('decrement', 100); - $this->assertEquals(99, $cache->decrement('decrement')); - $this->assertEquals(97, $cache->decrement('decrement', 2)); - $this->assertEquals(87, $cache->decrement('decrement', 10)); + $this->assertEquals( + 99, + $cache->decrement('decrement') + ); + + $this->assertEquals( + 97, + $cache->decrement('decrement', 2) + ); + + $this->assertEquals( + 87, + $cache->decrement('decrement', 10) + ); } public function testShouldGetKeys() { $cache = $this->getAdapter(null); - $this->assertEquals(0, count($cache->queryKeys())); + + $this->assertCount( + 0, + $cache->queryKeys() + ); $cache->save('a', 1, 10); $cache->save('long-key', 'long-val', 10); @@ -92,8 +123,21 @@ public function testShouldGetKeys() $keys = $cache->queryKeys(); sort($keys); - $this->assertEquals(['a', 'bcd', 'long-key'], $keys); - $this->assertEquals(['long-key'], $cache->queryKeys('long')); + $this->assertEquals( + [ + 'a', + 'bcd', + 'long-key', + ], + $keys + ); + + $this->assertEquals( + [ + 'long-key', + ], + $cache->queryKeys('long') + ); } public function testShouldFlushAllData() @@ -101,6 +145,7 @@ public function testShouldFlushAllData() $cache = $this->getAdapter(); $data = "sure, nothing interesting"; + $cache->save('test-data-flush', $data); $cache->save('test-data-flush2', $data); @@ -115,11 +160,15 @@ public function testShouldSaveData() $cache = $this->getAdapter(); $data = [1, 2, 3, 4, 5]; + $cache->save('test-data', $data); + $this->tester->seeInAerospike('test-data', $data); $data = "sure, nothing interesting"; + $cache->save('test-data', $data); + $this->tester->seeInAerospike('test-data', $data); } @@ -128,9 +177,12 @@ public function testShouldDeleteData() $cache = $this->getAdapter(20); $data = rand(0, 99); + $this->tester->haveInAerospike('test-data', $data); - $this->assertTrue($cache->delete('test-data')); + $this->assertTrue( + $cache->delete('test-data') + ); $this->tester->dontSeeInAerospike('test-data'); } @@ -139,42 +191,73 @@ public function testShouldUseOutputFrontend() { $time = date('H:i:s'); - $frontCache = new CacheOutput(['lifetime' => 10]); - $cache = new CacheAerospike($frontCache, $this->getConfig()); + $frontCache = new CacheOutput( + [ + 'lifetime' => 10, + ] + ); + + $cache = new CacheAerospike( + $frontCache, + $this->getConfig() + ); ob_start(); $content = $cache->start('test-output'); + $this->assertNull($content); echo $time; $obContent = ob_get_contents(); + $cache->save(null, null, null, true); ob_end_clean(); $this->assertEquals($time, $obContent); - $this->assertEquals($time, $cache->get('test-output')); + + $this->assertEquals( + $time, + $cache->get('test-output') + ); $content = $cache->start('test-output'); $this->assertEquals($content, $obContent); - $this->assertEquals($content, $cache->get('test-output')); + + $this->assertEquals( + $content, + $cache->get('test-output') + ); $keys = $cache->queryKeys(); - $this->assertEquals([0 => 'test-output'], $keys); + + $this->assertEquals( + [ + 0 => 'test-output', + ], + $keys + ); } private function getAdapter($lifetime = 20) { if ($lifetime) { - $frontCache = new CacheData(['lifetime' => $lifetime]); + $frontCache = new CacheData( + [ + 'lifetime' => $lifetime, + ] + ); } else { $frontCache = new CacheData(); } - $cache = new CacheAerospike($frontCache, $this->getConfig()); + $cache = new CacheAerospike( + $frontCache, + $this->getConfig() + ); return $cache; } @@ -183,11 +266,14 @@ private function getConfig() { return [ 'hosts' => [ - ['addr' => env('TEST_AS_HOST', '127.0.0.1'), 'port' => (int)env('TEST_AS_PORT', 3000)] + [ + 'addr' => env('TEST_AS_HOST', '127.0.0.1'), + 'port' => (int) env('TEST_AS_PORT', 3000), + ], ], 'persistent' => false, // important 'namespace' => 'test', - 'prefix' => '' + 'prefix' => '', ]; } } diff --git a/tests/aerospike/Session/Adapter/AerospikeTest.php b/tests/aerospike/Session/Adapter/AerospikeTest.php index af9ca686a..bd9f8e898 100644 --- a/tests/aerospike/Session/Adapter/AerospikeTest.php +++ b/tests/aerospike/Session/Adapter/AerospikeTest.php @@ -45,11 +45,13 @@ protected function _before() $this->markTestSkipped('The Aerospike module is not available.'); } - $this->getModule('Aerospike')->_reconfigure([ - 'set' => $this->set, - 'addr' => env('TEST_AS_HOST', '127.0.0.1'), - 'port' => (int)env('TEST_AS_PORT', 3000) - ]); + $this->getModule('Aerospike')->_reconfigure( + [ + 'set' => $this->set, + 'addr' => env('TEST_AS_HOST', '127.0.0.1'), + 'port' => (int) env('TEST_AS_PORT', 3000), + ] + ); } /** @@ -65,22 +67,31 @@ protected function _after() public function testShouldWriteSession() { $sessionId = 'abcdef123458'; - $session = new SessionHandler($this->getConfig()); + + $session = new SessionHandler( + $this->getConfig() + ); $data = [ - 321 => microtime(true), - 'def' => '678', - 'xyz' => 'zyx' - ]; + 321 => microtime(true), + 'def' => '678', + 'xyz' => 'zyx', + ]; + + $this->assertTrue( + $session->write($sessionId, $data) + ); - $this->assertTrue($session->write($sessionId, $data)); $this->tester->seeInAerospike($sessionId, $data); } public function testShouldReadSession() { $sessionId = 'some_session_key'; - $session = new SessionHandler($this->getConfig()); + + $session = new SessionHandler( + $this->getConfig() + ); $data = [ 321 => microtime(true), @@ -89,24 +100,33 @@ public function testShouldReadSession() ]; $this->tester->haveInAerospike($sessionId, $data); + $this->keys[] = $sessionId; - $this->assertEquals($data, $session->read($sessionId)); + $this->assertEquals( + $data, + $session->read($sessionId) + ); } public function testShouldDestroySession() { $sessionId = 'abcdef123457'; - $session = new SessionHandler($this->getConfig()); + + $session = new SessionHandler( + $this->getConfig() + ); $data = [ - 'abc' => 345, - 'def' => ['foo' => 'bar'], - 'zyx' => 'xyz' - ]; + 'abc' => 345, + 'def' => ['foo' => 'bar'], + 'zyx' => 'xyz', + ]; $this->tester->haveInAerospike($sessionId, $data); + $session->destroy($sessionId); + $this->tester->dontSeeInAerospike($sessionId); } @@ -115,14 +135,20 @@ private function cleanup() $aerospike = new Aerospike( [ 'hosts' => [ - ['addr' => env('TEST_AS_HOST', '127.0.0.1'), 'port' => (int)env('TEST_AS_PORT', 3000)] - ] + [ + 'addr' => env('TEST_AS_HOST', '127.0.0.1'), + 'port' => (int) env('TEST_AS_PORT', 3000), + ], + ], ], false ); foreach ($this->keys as $i => $key) { - $aerospike->remove($this->buildKey($aerospike, $key)); + $aerospike->remove( + $this->buildKey($aerospike, $key) + ); + unset($this->keys[$i]); } } @@ -140,7 +166,10 @@ private function getConfig() { return [ 'hosts' => [ - ['addr' => env('TEST_AS_HOST', '127.0.0.1'), 'port' => (int)env('TEST_AS_PORT', 3000)] + [ + 'addr' => env('TEST_AS_HOST', '127.0.0.1'), + 'port' => (int) env('TEST_AS_PORT', 3000), + ], ], 'persistent' => false, 'namespace' => $this->ns, @@ -148,10 +177,10 @@ private function getConfig() 'prefix' => '', 'lifetime' => 10, 'uniqueId' => 'some-unique-id', - 'options' => [ + 'options' => [ \Aerospike::OPT_CONNECT_TIMEOUT => 1250, - \Aerospike::OPT_WRITE_TIMEOUT => 1500 - ] + \Aerospike::OPT_WRITE_TIMEOUT => 1500, + ], ]; } } diff --git a/tests/unit/Acl/Adapter/DatabaseTest.php b/tests/unit/Acl/Adapter/DatabaseTest.php index db8f80f44..1f28a883b 100644 --- a/tests/unit/Acl/Adapter/DatabaseTest.php +++ b/tests/unit/Acl/Adapter/DatabaseTest.php @@ -27,25 +27,38 @@ */ class DatabaseTest extends Test { - const ADAPTER_CLASS = 'Phalcon\Acl\Adapter\Database'; + const ADAPTER_CLASS = Database::class; protected function getConnection() { - return new Sqlite(['dbname' => 'tests/_output/sample.db']); + return new Sqlite( + [ + 'dbname' => 'tests/_output/sample.db', + ] + ); } protected function assertProtectedPropertyEquals($propertyName, $tableName, DbAdapter $connection, Database $adapter) { - $property = new ReflectionProperty(self::ADAPTER_CLASS, $propertyName); + $property = new ReflectionProperty( + self::ADAPTER_CLASS, + $propertyName + ); + $property->setAccessible(true); - $this->assertEquals($connection->escapeIdentifier($tableName), $property->getValue($adapter)); + + $this->assertEquals( + $connection->escapeIdentifier($tableName), + $property->getValue($adapter) + ); } /** + * @param array $options + * * @dataProvider incorrectDbProvider * @expectedException \Phalcon\Acl\Exception * @expectedExceptionMessage Parameter "db" is required and it must be an instance of Phalcon\Acl\AdapterInterface - * @param array $options */ public function testShouldThrowExceptionIfDbIsMissingOrInvalid($options) { @@ -67,9 +80,10 @@ public function incorrectDbProvider() } /** - * @dataProvider incorrectOptionsProvider * @param string $expected * @param array $options + * + * @dataProvider incorrectOptionsProvider */ public function testShouldThrowExceptionWhenOptionsIsInvalid($expected, $options) { @@ -121,16 +135,25 @@ public function testShouldCreateAdapterInstance() 'rolesInherits' => 'roles_inherits', 'resources' => 'resources', 'resourcesAccesses' => 'resources_accesses', - 'accessList' => 'access_list' + 'accessList' => 'access_list', ]; $adapter = new Database($options); - $this->assertInstanceOf(self::ADAPTER_CLASS, $adapter); + + $this->assertInstanceOf( + self::ADAPTER_CLASS, + $adapter + ); unset($options['db']); foreach ($options as $property => $tableName) { - $this->assertProtectedPropertyEquals($property, $tableName, $connection, $adapter); + $this->assertProtectedPropertyEquals( + $property, + $tableName, + $connection, + $adapter + ); } } } diff --git a/tests/unit/Acl/Factory/MemoryTest.php b/tests/unit/Acl/Factory/MemoryTest.php index 7471bb7d4..048b84b96 100644 --- a/tests/unit/Acl/Factory/MemoryTest.php +++ b/tests/unit/Acl/Factory/MemoryTest.php @@ -30,21 +30,41 @@ class MemoryTest extends Test { public function testFactoryShouldCreateMemoryAclObjectFromAclConfigurationWithAllOptions() { - $config = new Ini(INCUBATOR_FIXTURES . 'Acl/acl.ini'); + $config = new Ini( + INCUBATOR_FIXTURES . 'Acl/acl.ini' + ); + $factory = new MemoryFactory(); - $acl = $factory->create($config->get('acl')); - $this->assertInstanceOf('Phalcon\Acl\Adapter\Memory', $acl); + $acl = $factory->create( + $config->get('acl') + ); + + $this->assertInstanceOf( + MemoryAdapter::class, + $acl + ); + $this->assertAclIsConfiguredAsExpected($acl, $config); } public function testFactoryShouldWorkIfCreatedFromConfigPHPArray() { - $config = new Config(include INCUBATOR_FIXTURES . 'Acl/acl.php'); + $config = new Config( + include INCUBATOR_FIXTURES . 'Acl/acl.php' + ); + $factory = new MemoryFactory(); - $acl = $factory->create($config->get('acl')); - $this->assertInstanceOf('Phalcon\Acl\Adapter\Memory', $acl); + $acl = $factory->create( + $config->get('acl') + ); + + $this->assertInstanceOf( + MemoryAdapter::class, + $acl + ); + $this->assertAclIsConfiguredAsExpected($acl, $config); } @@ -54,10 +74,17 @@ public function testFactoryShouldWorkIfCreatedFromConfigPHPArray() */ public function testFactoryShouldThrowExceptionIfDefaultActionIsMissing() { - $config = new Ini(INCUBATOR_FIXTURES . 'Acl/acl.ini'); + $config = new Ini( + INCUBATOR_FIXTURES . 'Acl/acl.ini' + ); + unset($config->acl->defaultAction); + $factory = new MemoryFactory(); - $factory->create($config->get('acl')); + + $factory->create( + $config->get('acl') + ); } /** @@ -66,10 +93,17 @@ public function testFactoryShouldThrowExceptionIfDefaultActionIsMissing() */ public function testFactoryShouldThrowExceptionIfResourceOptionIsMissing() { - $config = new Ini(INCUBATOR_FIXTURES . 'Acl/acl.ini'); + $config = new Ini( + INCUBATOR_FIXTURES . 'Acl/acl.ini' + ); + unset($config->acl->resource); + $factory = new MemoryFactory(); - $factory->create($config->get('acl')); + + $factory->create( + $config->get('acl') + ); } /** @@ -78,11 +112,23 @@ public function testFactoryShouldThrowExceptionIfResourceOptionIsMissing() */ public function testFactoryShouldThrowExceptionIfActionsKeyIsMissing() { - $config = new Ini(INCUBATOR_FIXTURES . 'Acl/acl.ini'); - unset($config->acl->resource->index->actions); - unset($config->acl->role->guest->allow->index->actions[0]); + $config = new Ini( + INCUBATOR_FIXTURES . 'Acl/acl.ini' + ); + + unset( + $config->acl->resource->index->actions + ); + + unset( + $config->acl->role->guest->allow->index->actions[0] + ); + $factory = new MemoryFactory(); - $factory->create($config->get('acl')); + + $factory->create( + $config->get('acl') + ); } /** @@ -91,10 +137,17 @@ public function testFactoryShouldThrowExceptionIfActionsKeyIsMissing() */ public function testFactoryShouldThrowExceptionIfRoleKeyIsMissing() { - $config = new Ini(INCUBATOR_FIXTURES . 'Acl/acl.ini'); + $config = new Ini( + INCUBATOR_FIXTURES . 'Acl/acl.ini' + ); + unset($config->acl->role); + $factory = new MemoryFactory(); - $factory->create($config->get('acl')); + + $factory->create( + $config->get('acl') + ); } /** @@ -103,10 +156,25 @@ public function testFactoryShouldThrowExceptionIfRoleKeyIsMissing() */ public function testFactoryShouldThrowExceptionIfWrongMethodIsSet() { - $config = new Ini(INCUBATOR_FIXTURES . 'Acl/acl.ini'); - $config->acl->role->user->wrongmethod = new Config(['test' => ['actions' => ['test']]]); + $config = new Ini( + INCUBATOR_FIXTURES . 'Acl/acl.ini' + ); + + $config->acl->role->user->wrongmethod = new Config( + [ + 'test' => [ + 'actions' => [ + 'test', + ], + ], + ] + ); + $factory = new MemoryFactory(); - $factory->create($config->get('acl')); + + $factory->create( + $config->get('acl') + ); } /** @@ -119,10 +187,23 @@ public function testFactoryShouldThrowExceptionIfWrongMethodIsSet() */ public function testFactoryShouldThrowExceptionIfWrongNoActionIsSet($action) { - $config = new Ini(INCUBATOR_FIXTURES . 'Acl/acl.ini'); - $config->acl->role->user->wrongmethod = new Config(['test' => ['actions' => $action]]); + $config = new Ini( + INCUBATOR_FIXTURES . 'Acl/acl.ini' + ); + + $config->acl->role->user->wrongmethod = new Config( + [ + 'test' => [ + 'actions' => $action, + ], + ] + ); + $factory = new MemoryFactory(); - $factory->create($config->get('acl')); + + $factory->create( + $config->get('acl') + ); } public function invalidActionProvider() @@ -133,7 +214,10 @@ public function invalidActionProvider() 'null' => [null], 'bool' => [false], 'object' => [new \stdClass], - 'callable' => [function () {}], + 'callable' => [ + function () { + }, + ], ]; } @@ -144,44 +228,111 @@ public function invalidActionProvider() */ public function testFactoryShouldThrowExceptionIfNonExistentInheritRoleIsSet() { - $config = new Ini(INCUBATOR_FIXTURES . 'Acl/acl.ini'); + $config = new Ini( + INCUBATOR_FIXTURES . 'Acl/acl.ini' + ); + $config->acl->role->user->inherit = 'nonexistentrole'; + $factory = new MemoryFactory(); - $factory->create($config->get('acl')); + + $factory->create( + $config->get('acl') + ); } protected function assertAclIsConfiguredAsExpected(MemoryAdapter $acl, Config $config) { // assert default action - $this->assertEquals(Acl::DENY, $acl->getDefaultAction()); + $this->assertEquals( + Acl::DENY, + $acl->getDefaultAction() + ); + + // assert resources $resources = $acl->getResources(); + $this->assertInternalType('array', $resources); + $indexResource = $resources[0]; $testResource = $resources[1]; - $this->assertEquals('index', $indexResource->getName()); - $this->assertEquals('test', $testResource->getName()); - $this->assertEquals($config->acl->resource->index->description, $indexResource->getDescription()); - $this->assertEquals($config->acl->resource->test->description, $testResource->getDescription()); + + $this->assertEquals( + 'index', + $indexResource->getName() + ); + + $this->assertEquals( + 'test', + $testResource->getName() + ); + + $this->assertEquals( + $config->acl->resource->index->description, + $indexResource->getDescription() + ); + + $this->assertEquals( + $config->acl->resource->test->description, + $testResource->getDescription() + ); + + // assert roles $roles = $acl->getRoles(); - $this->assertInternalType('array', $roles); + + $this->assertInternalType( + 'array', + $roles + ); + $guestRole = $roles[0]; $userRole = $roles[1]; - $this->assertEquals('guest', $guestRole->getName()); - $this->assertEquals('user', $userRole->getName()); - $this->assertEquals($config->acl->role->guest->description, $guestRole->getDescription()); - $this->assertEquals($config->acl->role->user->description, $userRole->getDescription()); + + $this->assertEquals( + 'guest', + $guestRole->getName() + ); + + $this->assertEquals( + 'user', + $userRole->getName() + ); + + $this->assertEquals( + $config->acl->role->guest->description, + $guestRole->getDescription() + ); + + $this->assertEquals( + $config->acl->role->user->description, + $userRole->getDescription() + ); + + // assert guest rules - $this->assertTrue($acl->isAllowed('guest', 'index', 'index')); - $this->assertFalse($acl->isAllowed('guest', 'test', 'index')); + $this->assertTrue( + $acl->isAllowed('guest', 'index', 'index') + ); + + $this->assertFalse( + $acl->isAllowed('guest', 'test', 'index') + ); + + // assert user rules // inherited from guest - $this->assertTrue($acl->isAllowed('user', 'index', 'index')); - $this->assertTrue($acl->isAllowed('user', 'test', 'index')); + $this->assertTrue( + $acl->isAllowed('user', 'index', 'index') + ); + + $this->assertTrue( + $acl->isAllowed('user', 'test', 'index') + ); } } diff --git a/tests/unit/Annotations/Adapter/BaseTest.php b/tests/unit/Annotations/Adapter/BaseTest.php index 63ddacb10..3504ced0c 100644 --- a/tests/unit/Annotations/Adapter/BaseTest.php +++ b/tests/unit/Annotations/Adapter/BaseTest.php @@ -31,7 +31,9 @@ protected function getObject($options) { return $this->getMockForAbstractClass( Base::class, - ['options' => $options], + [ + 'options' => $options, + ], '', true, true, @@ -51,12 +53,21 @@ public function testWriteAnnotations($key, $data) $mock = $this->getObject(null); $mock->expects($this->once())->method('prepareKey')->willReturn($key); - $cacheBackend = new CacheBackend(new CacheFrontend(['lifetime' => 86400])); + $cacheBackend = new CacheBackend( + new CacheFrontend( + [ + 'lifetime' => 86400, + ] + ) + ); $mock->expects($this->once())->method('getCacheBackend')->willReturn($cacheBackend); $mock->write($key, $data, 86400); - $this->assertEquals($data, $cacheBackend->get($key)); + $this->assertEquals( + $data, + $cacheBackend->get($key) + ); } /** @@ -67,14 +78,25 @@ public function testWriteAnnotations($key, $data) public function testReadAnnotations($key, $data) { $mock = $this->getObject(null); + $mock->expects($this->once())->method('prepareKey')->willReturn($key); - $cacheBackend = new CacheBackend(new CacheFrontend(['lifetime' => 86400])); + $cacheBackend = new CacheBackend( + new CacheFrontend( + [ + 'lifetime' => 86400, + ] + ) + ); + $cacheBackend->save($key, $data, 86400); $mock->expects($this->once())->method('getCacheBackend')->willReturn($cacheBackend); - $this->assertEquals($data, $mock->read($key)); + $this->assertEquals( + $data, + $mock->read($key) + ); } /** @@ -85,46 +107,142 @@ public function testReadAnnotations($key, $data) public function testConstructor($options, $expected) { $mock = $this->getObject($options); - $reflectedProperty = new ReflectionProperty(get_class($mock), 'options'); + + $reflectedProperty = new ReflectionProperty( + get_class($mock), + 'options' + ); + $reflectedProperty->setAccessible(true); - $this->assertEquals($expected, $reflectedProperty->getValue($mock)); + + $this->assertEquals( + $expected, + $reflectedProperty->getValue($mock) + ); } public function testHasDefaultLifetime() { - $this->assertClassHasStaticAttribute('defaultLifetime', Base::class); + $this->assertClassHasStaticAttribute( + 'defaultLifetime', + Base::class + ); } public function testHasDefaultPrefix() { - $this->assertClassHasStaticAttribute('defaultPrefix', Base::class); + $this->assertClassHasStaticAttribute( + 'defaultPrefix', + Base::class + ); } public function testHasOptions() { - $this->assertClassHasAttribute('options', Base::class); + $this->assertClassHasAttribute( + 'options', + Base::class + ); } public function providerReadWrite() { return [ - ['test1', 'data1'], - ['test1', (object) ['key' => 'value']], - ['test1', ['key' => 'value']], - ['test1', null] + [ + 'test1', + 'data1', + ], + + [ + 'test1', + (object) ['key' => 'value'], + ], + + [ + 'test1', + [ + 'key' => 'value', + ], + ], + + [ + 'test1', + null, + ], ]; } public function providerConstructor() { return [ - [['lifetime' => 23], ['lifetime' => 23, 'prefix' => '']], - [['prefix' => 'test_'], ['lifetime' => 8600, 'prefix' => 'test_']], - [['randomValue' => 'test_'], ['randomValue' => 'test_', 'lifetime' => 8600, 'prefix' => '']], - [[123 => 'test_'], [123 => 'test_', 'lifetime' => 8600, 'prefix' => '']], - [['lifetime' => 24, 'prefix' => 'test_'], ['lifetime' => 24, 'prefix' => 'test_']], - [[], ['lifetime' => 8600, 'prefix' => '']], - [null, ['lifetime' => 8600, 'prefix' => '']] + [ + [ + 'lifetime' => 23, + ], + [ + 'lifetime' => 23, + 'prefix' => '', + ], + ], + + [ + [ + 'prefix' => 'test_', + ], + [ + 'lifetime' => 8600, + 'prefix' => 'test_', + ], + ], + + [ + [ + 'randomValue' => 'test_', + ], + [ + 'randomValue' => 'test_', + 'lifetime' => 8600, + 'prefix' => '', + ], + ], + + [ + [ + 123 => 'test_', + ], + [ + 123 => 'test_', + 'lifetime' => 8600, + 'prefix' => '', + ], + ], + + [ + [ + 'lifetime' => 24, + 'prefix' => 'test_', + ], + [ + 'lifetime' => 24, + 'prefix' => 'test_', + ], + ], + + [ + [], + [ + 'lifetime' => 8600, + 'prefix' => '', + ], + ], + + [ + null, + [ + 'lifetime' => 8600, + 'prefix' => '', + ], + ], ]; } } diff --git a/tests/unit/Annotations/Adapter/MemcachedTest.php b/tests/unit/Annotations/Adapter/MemcachedTest.php index d6d246326..01c9be9e1 100644 --- a/tests/unit/Annotations/Adapter/MemcachedTest.php +++ b/tests/unit/Annotations/Adapter/MemcachedTest.php @@ -43,22 +43,36 @@ protected function _before() */ public function testShouldCatchExceptionWhenNoHostGivenInOptions() { - new Memcached(['lifetime' => 23, 'prefix' => '']); + new Memcached( + [ + 'lifetime' => 23, + 'prefix' => '', + ] + ); } public function testHasDefaultPort() { - $this->assertClassHasStaticAttribute('defaultPort', Memcached::class); + $this->assertClassHasStaticAttribute( + 'defaultPort', + Memcached::class + ); } public function testHasDefaultWeight() { - $this->assertClassHasStaticAttribute('defaultWeight', Memcached::class); + $this->assertClassHasStaticAttribute( + 'defaultWeight', + Memcached::class + ); } public function testHasMemcached() { - $this->assertClassHasAttribute('memcached', Memcached::class); + $this->assertClassHasAttribute( + 'memcached', + Memcached::class + ); } /** @@ -68,10 +82,18 @@ public function testHasMemcached() */ public function testShouldReadAndWriteToMemcachedWithoutPrefix($key, $data) { - $object = new Memcached(['host' => env('TEST_MC_HOST', '127.0.0.1')]); + $object = new Memcached( + [ + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + ] + ); + $object->write($key, $data); - $this->assertEquals($data, $object->read($key)); + $this->assertEquals( + $data, + $object->read($key) + ); } /** @@ -81,33 +103,67 @@ public function testShouldReadAndWriteToMemcachedWithoutPrefix($key, $data) */ public function testShouldReadAndWriteToMemcachedWithPrefix($key, $data) { - $object = new Memcached(['host' => env('TEST_MC_HOST', '127.0.0.1'), 'prefix' => 'test_']); + $object = new Memcached( + [ + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + 'prefix' => 'test_', + ] + ); + $object->write($key, $data); - $this->assertEquals($data, $object->read($key)); + $this->assertEquals( + $data, + $object->read($key) + ); } public function testShouldGetCacheBackendThroughGetter() { - $object = new Memcached(['host' => env('TEST_MC_HOST', '127.0.0.1')]); + $object = new Memcached( + [ + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + ] + ); + + $reflectedMethod = new ReflectionMethod( + get_class($object), + 'getCacheBackend' + ); - $reflectedMethod = new ReflectionMethod(get_class($object), 'getCacheBackend'); $reflectedMethod->setAccessible(true); - $this->assertInstanceOf(Libmemcached::class, $reflectedMethod->invoke($object)); + + $this->assertInstanceOf( + Libmemcached::class, + $reflectedMethod->invoke($object) + ); } public function testShouldGetCacheBackendThroughReflectionSetter() { - $object = new Memcached(['host' => env('TEST_MC_HOST', '127.0.0.1')]); + $object = new Memcached( + [ + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + ] + ); + $mock = $this->getMockBuilder(Libmemcached::class) ->disableOriginalConstructor() ->getMock(); $this->tester->setProtectedProperty($object, 'memcached', $mock); - $reflectedMethod = new ReflectionMethod(get_class($object), 'getCacheBackend'); + $reflectedMethod = new ReflectionMethod( + get_class($object), + 'getCacheBackend' + ); + $reflectedMethod->setAccessible(true); - $this->assertInstanceOf(Libmemcached::class, $reflectedMethod->invoke($object)); + + $this->assertInstanceOf( + Libmemcached::class, + $reflectedMethod->invoke($object) + ); } /** @@ -116,11 +172,23 @@ public function testShouldGetCacheBackendThroughReflectionSetter() */ public function testShouldPrepareKey($key) { - $object = new Memcached(['host' => env('TEST_MC_HOST', '127.0.0.1')]); - $reflectedMethod = new ReflectionMethod(get_class($object), 'prepareKey'); + $object = new Memcached( + [ + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + ] + ); + + $reflectedMethod = new ReflectionMethod( + get_class($object), + 'prepareKey' + ); + $reflectedMethod->setAccessible(true); - $this->assertEquals($key, $reflectedMethod->invoke($object, $key)); + $this->assertEquals( + $key, + $reflectedMethod->invoke($object, $key) + ); } /** @@ -132,20 +200,54 @@ public function testShouldCreateMemcachedAdapterInstanceAndSetOptions($options, { $object = new Memcached($options); - $this->assertEquals($expected, $this->tester->getProtectedProperty($object, 'options')); + $this->assertEquals( + $expected, + $this->tester->getProtectedProperty($object, 'options') + ); } public function providerReadWrite() { // This key is needed in order not to break your real data - $key = hash('sha256', json_encode([__CLASS__, __METHOD__, __FILE__, __LINE__])); + $key = hash( + 'sha256', + json_encode( + [ + __CLASS__, + __METHOD__, + __FILE__, + __LINE__, + ] + ) + ); return [ - [$key . '_test1', 'data1'], - [$key . '_test1', (object) ['key' => 'value']], - [$key . '_test1', ['key' => 'value']], - [$key . '_test1', null], - [$key . '_test1', new stdClass()], + [ + $key . '_test1', + 'data1', + ], + + [ + $key . '_test1', + (object) ['key' => 'value'], + ], + + [ + $key . '_test1', + [ + 'key' => 'value', + ], + ], + + [ + $key . '_test1', + null, + ], + + [ + $key . '_test1', + new stdClass(), + ], ]; } @@ -154,7 +256,7 @@ public function providerKey() return [ ['key1'], [1], - ['_key1'] + ['_key1'], ]; } @@ -163,133 +265,141 @@ public function providerConstructor() return [ [ [ - 'host' => env('TEST_MC_HOST', '127.0.0.1'), - 'port' => env('TEST_MC_PORT', 11211), - 'weight' => 1, - 'lifetime' => 23 + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + 'port' => env('TEST_MC_PORT', 11211), + 'weight' => 1, + 'lifetime' => 23, ], [ - 'host' => env('TEST_MC_HOST', '127.0.0.1'), - 'port' => env('TEST_MC_PORT', 11211), - 'weight' => 1, + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + 'port' => env('TEST_MC_PORT', 11211), + 'weight' => 1, 'lifetime' => 23, - 'prefix' => '' - ] + 'prefix' => '', + ], ], + [ [ - 'host' => env('TEST_MC_HOST', '127.0.0.1'), - 'port' => env('TEST_MC_PORT', 11211), + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + 'port' => env('TEST_MC_PORT', 11211), 'weight' => 1, - 'prefix' => 'test_' + 'prefix' => 'test_', ], [ - 'host' => env('TEST_MC_HOST', '127.0.0.1'), - 'port' => env('TEST_MC_PORT', 11211), - 'weight' => 1, + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + 'port' => env('TEST_MC_PORT', 11211), + 'weight' => 1, 'lifetime' => 8600, - 'prefix' => 'test_' - ] + 'prefix' => 'test_', + ], ], + [ [ - 'host' => env('TEST_MC_HOST', '127.0.0.1'), - 'port' => env('TEST_MC_PORT', 11211), - 'weight' => 1, - 'randomValue' => 'test_' + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + 'port' => env('TEST_MC_PORT', 11211), + 'weight' => 1, + 'randomValue' => 'test_', ], [ - 'host' => env('TEST_MC_HOST', '127.0.0.1'), - 'port' => env('TEST_MC_PORT', 11211), - 'weight' => 1, + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + 'port' => env('TEST_MC_PORT', 11211), + 'weight' => 1, 'randomValue' => 'test_', - 'lifetime' => 8600, - 'prefix' => '' - ] + 'lifetime' => 8600, + 'prefix' => '', + ], ], + [ [ - 'host' => env('TEST_MC_HOST', '127.0.0.1'), - 'port' => env('TEST_MC_PORT', 11211), + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + 'port' => env('TEST_MC_PORT', 11211), 'weight' => 1, - 123 => 'test_' + 123 => 'test_' ], [ - 'host' => env('TEST_MC_HOST', '127.0.0.1'), - 'port' => env('TEST_MC_PORT', 11211), - 'weight' => 1, - 123 => 'test_', + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + 'port' => env('TEST_MC_PORT', 11211), + 'weight' => 1, + 123 => 'test_', 'lifetime' => 8600, - 'prefix' => '' - ] + 'prefix' => '', + ], ], + [ [ - 'host' => env('TEST_MC_HOST', '127.0.0.1'), - 'port' => env('TEST_MC_PORT', 11211), - 'weight' => 1, + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + 'port' => env('TEST_MC_PORT', 11211), + 'weight' => 1, 'lifetime' => 24, - 'prefix' => 'test_' + 'prefix' => 'test_', ], [ - 'host' => env('TEST_MC_HOST', '127.0.0.1'), - 'port' => env('TEST_MC_PORT', 11211), - 'weight' => 1, + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + 'port' => env('TEST_MC_PORT', 11211), + 'weight' => 1, 'lifetime' => 24, - 'prefix' => 'test_' - ] + 'prefix' => 'test_', + ], ], + [ [ - 'host' => env('TEST_MC_HOST', '127.0.0.1'), - 'port' => env('TEST_MC_PORT', 11211), - 'weight' => 1 + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + 'port' => env('TEST_MC_PORT', 11211), + 'weight' => 1, ], [ - 'host' => env('TEST_MC_HOST', '127.0.0.1'), - 'port' => env('TEST_MC_PORT', 11211), - 'weight' => 1, + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + 'port' => env('TEST_MC_PORT', 11211), + 'weight' => 1, 'lifetime' => 8600, - 'prefix' => '' - ] + 'prefix' => '', + ], ], + [ [ - 'host' => env('TEST_MC_HOST', '127.0.0.1'), - 'weight' => 1 + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + 'weight' => 1, ], [ - 'host' => env('TEST_MC_HOST', '127.0.0.1'), - 'port' => env('TEST_MC_PORT', 11211), - 'weight' => 1, + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + 'port' => env('TEST_MC_PORT', 11211), + 'weight' => 1, 'lifetime' => 8600, - 'prefix' => '' - ] + 'prefix' => '', + ], ], + [ [ 'host' => env('TEST_MC_HOST', '127.0.0.1'), 'port' => env('TEST_MC_PORT', 11211), ], [ - 'host' => env('TEST_MC_HOST', '127.0.0.1'), - 'port' => env('TEST_MC_PORT', 11211), - 'weight' => 1, + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + 'port' => env('TEST_MC_PORT', 11211), + 'weight' => 1, 'lifetime' => 8600, - 'prefix' => '' - ] + 'prefix' => '', + ], ], + [ [ 'host' => env('TEST_MC_HOST', '127.0.0.1'), ], [ - 'host' => env('TEST_MC_HOST', '127.0.0.1'), - 'port' => env('TEST_MC_PORT', 11211), - 'weight' => 1, + 'host' => env('TEST_MC_HOST', '127.0.0.1'), + 'port' => env('TEST_MC_PORT', 11211), + 'weight' => 1, 'lifetime' => 8600, - 'prefix' => '' - ] + 'prefix' => '', + ], ], ]; } diff --git a/tests/unit/Annotations/Adapter/RedisTest.php b/tests/unit/Annotations/Adapter/RedisTest.php index a2071bb81..6c5610f7e 100644 --- a/tests/unit/Annotations/Adapter/RedisTest.php +++ b/tests/unit/Annotations/Adapter/RedisTest.php @@ -39,7 +39,10 @@ protected function _before() public function testHasRedis() { - $this->assertClassHasAttribute('redis', Redis::class); + $this->assertClassHasAttribute( + 'redis', + Redis::class + ); } /** @@ -49,10 +52,18 @@ public function testHasRedis() */ public function testShouldReadAndWriteToRedisWithoutPrefix($key, $data) { - $object = new Redis(['host' => env('TEST_RS_HOST', 11211)]); + $object = new Redis( + [ + 'host' => env('TEST_RS_HOST', 11211), + ] + ); + $object->write($key, $data); - $this->assertEquals($data, $object->read($key)); + $this->assertEquals( + $data, + $object->read($key) + ); } /** @@ -62,33 +73,77 @@ public function testShouldReadAndWriteToRedisWithoutPrefix($key, $data) */ public function testShouldReadAndWriteToRedisWithPrefix($key, $data) { - $object = new Redis(['host' => env('TEST_RS_HOST', 11211), 'prefix' => 'test_']); + $object = new Redis( + [ + 'host' => env('TEST_RS_HOST', 11211), + 'prefix' => 'test_', + ] + ); + $object->write($key, $data); - $this->assertEquals($data, $object->read($key)); + $this->assertEquals( + $data, + $object->read($key) + ); } public function testShouldGetCacheBackendThroughGetter() { - $object = new Redis(['host' => env('TEST_RS_HOST', 11211)]); + $object = new Redis( + [ + 'host' => env('TEST_RS_HOST', 11211), + ] + ); + + $reflectedMethod = new ReflectionMethod( + get_class($object), + 'getCacheBackend' + ); - $reflectedMethod = new ReflectionMethod(get_class($object), 'getCacheBackend'); $reflectedMethod->setAccessible(true); - $this->assertInstanceOf(CacheBackend::class, $reflectedMethod->invoke($object)); + + $this->assertInstanceOf( + CacheBackend::class, + $reflectedMethod->invoke($object) + ); } public function testShouldGetCacheBackendThroughReflectionSetter() { - $object = new Redis(['host' => env('TEST_RS_HOST', 11211)]); - $mock = $this->getMock(CacheBackend::class, [], [], '', false); + $object = new Redis( + [ + 'host' => env('TEST_RS_HOST', 11211), + ] + ); + + $mock = $this->getMock( + CacheBackend::class, + [], + [], + '', + false + ); + + $reflectedProperty = new ReflectionProperty( + get_class($object), + 'redis' + ); - $reflectedProperty = new ReflectionProperty(get_class($object), 'redis'); $reflectedProperty->setAccessible(true); $reflectedProperty->setValue($object, $mock); - $reflectedMethod = new ReflectionMethod(get_class($object), 'getCacheBackend'); + $reflectedMethod = new ReflectionMethod( + get_class($object), + 'getCacheBackend' + ); + $reflectedMethod->setAccessible(true); - $this->assertInstanceOf(CacheBackend::class, $reflectedMethod->invoke($object)); + + $this->assertInstanceOf( + CacheBackend::class, + $reflectedMethod->invoke($object) + ); } /** @@ -97,11 +152,23 @@ public function testShouldGetCacheBackendThroughReflectionSetter() */ public function testShouldPrepareKey($key) { - $object = new Redis(['host' => env('TEST_RS_HOST', 11211)]); - $reflectedMethod = new ReflectionMethod(get_class($object), 'prepareKey'); + $object = new Redis( + [ + 'host' => env('TEST_RS_HOST', 11211), + ] + ); + + $reflectedMethod = new ReflectionMethod( + get_class($object), + 'prepareKey' + ); + $reflectedMethod->setAccessible(true); - $this->assertEquals($key, $reflectedMethod->invoke($object, $key)); + $this->assertEquals( + $key, + $reflectedMethod->invoke($object, $key) + ); } /** @@ -112,25 +179,72 @@ public function testShouldPrepareKey($key) public function testShouldCreateRedisAdapterInstanceAndSetOptions($options, $expected) { $object = new Redis($options); - $reflectedProperty = new ReflectionProperty(get_class($object), 'options'); + + $reflectedProperty = new ReflectionProperty( + get_class($object), + 'options' + ); + $reflectedProperty->setAccessible(true); - $this->assertEquals($expected, $reflectedProperty->getValue($object)); + $this->assertEquals( + $expected, + $reflectedProperty->getValue($object) + ); } public function providerReadWrite() { // This key is needed in order not to break your real data - $key = hash('sha256', json_encode([__CLASS__, __METHOD__, __FILE__, __LINE__])); + $key = hash( + 'sha256', + json_encode( + [ + __CLASS__, + __METHOD__, + __FILE__, + __LINE__, + ] + ) + ); return [ - 'string' => [$key . '_test1', 'data1'], - 'object' => [$key . '_test1', (object) ['key' => 'value']], - 'array' => [$key . '_test1', ['key' => 'value']], - 'null' => [$key . '_test1', null], - 'int' => [$key . '_test1', PHP_INT_MAX], - 'float' => [$key . '_test1', 3.14], - 'class' => [$key . '_test1', new \stdClass()], + 'string' => [ + $key . '_test1', + 'data1', + ], + + 'object' => [ + $key . '_test1', + (object) ['key' => 'value'], + ], + + 'array' => [ + $key . '_test1', + [ + 'key' => 'value' + ], + ], + + 'null' => [ + $key . '_test1', + null, + ], + + 'int' => [ + $key . '_test1', + PHP_INT_MAX, + ], + + 'float' => [ + $key . '_test1', + 3.14, + ], + + 'class' => [ + $key . '_test1', + new \stdClass(), + ], ]; } @@ -139,7 +253,7 @@ public function providerKey() return [ ['key1'], [1], - ['_key1'] + ['_key1'], ]; } @@ -148,127 +262,135 @@ public function providerConstructor() return [ [ [ - 'host' => env('TEST_RS_HOST', 11211), - 'port' => env('TEST_RS_PORT', 6379), - 'lifetime' => 23 + 'host' => env('TEST_RS_HOST', 11211), + 'port' => env('TEST_RS_PORT', 6379), + 'lifetime' => 23, ], [ - 'host' => env('TEST_RS_HOST', 11211), - 'port' => env('TEST_RS_PORT', 6379), - 'lifetime' => 23, - 'prefix' => '', - 'persistent' => false - ] + 'host' => env('TEST_RS_HOST', 11211), + 'port' => env('TEST_RS_PORT', 6379), + 'lifetime' => 23, + 'prefix' => '', + 'persistent' => false, + ], ], + [ [ - 'host' => env('TEST_RS_HOST', 11211), - 'port' => env('TEST_RS_PORT', 6379), - 'lifetime' => 23, - 'persistent' => true + 'host' => env('TEST_RS_HOST', 11211), + 'port' => env('TEST_RS_PORT', 6379), + 'lifetime' => 23, + 'persistent' => true, ], [ - 'host' => env('TEST_RS_HOST', 11211), - 'port' => env('TEST_RS_PORT', 6379), - 'lifetime' => 23, - 'prefix' => '', - 'persistent' => true - ] + 'host' => env('TEST_RS_HOST', 11211), + 'port' => env('TEST_RS_PORT', 6379), + 'lifetime' => 23, + 'prefix' => '', + 'persistent' => true, + ], ], + [ [ - 'host' => env('TEST_RS_HOST', 11211), - 'port' => env('TEST_RS_PORT', 6379), - 'prefix' => 'test_' + 'host' => env('TEST_RS_HOST', 11211), + 'port' => env('TEST_RS_PORT', 6379), + 'prefix' => 'test_', ], [ - 'host' => env('TEST_RS_HOST', 11211), - 'port' => env('TEST_RS_PORT', 6379), - 'lifetime' => 8600, - 'prefix' => 'test_', - 'persistent' => false - ] + 'host' => env('TEST_RS_HOST', 11211), + 'port' => env('TEST_RS_PORT', 6379), + 'lifetime' => 8600, + 'prefix' => 'test_', + 'persistent' => false, + ], ], + [ [ - 'host' => env('TEST_RS_HOST', 11211), - 'port' => env('TEST_RS_PORT', 6379), - 'randomValue' => 'test_' + 'host' => env('TEST_RS_HOST', 11211), + 'port' => env('TEST_RS_PORT', 6379), + 'randomValue' => 'test_', ], [ - 'host' => env('TEST_RS_HOST', 11211), - 'port' => env('TEST_RS_PORT', 6379), + 'host' => env('TEST_RS_HOST', 11211), + 'port' => env('TEST_RS_PORT', 6379), 'randomValue' => 'test_', - 'lifetime' => 8600, - 'prefix' => '', - 'persistent' => false - ] + 'lifetime' => 8600, + 'prefix' => '', + 'persistent' => false, + ], ], + [ [ 'host' => env('TEST_RS_HOST', 11211), 'port' => env('TEST_RS_PORT', 6379), - 123 => 'test_' + 123 => 'test_', ], [ - 'host' => env('TEST_RS_HOST', 11211), - 'port' => env('TEST_RS_PORT', 6379), - 123 => 'test_', - 'lifetime' => 8600, - 'prefix' => '', - 'persistent' => false - ] + 'host' => env('TEST_RS_HOST', 11211), + 'port' => env('TEST_RS_PORT', 6379), + 123 => 'test_', + 'lifetime' => 8600, + 'prefix' => '', + 'persistent' => false, + ], ], + [ [ - 'host' => env('TEST_RS_HOST', 11211), - 'port' => env('TEST_RS_PORT', 6379), + 'host' => env('TEST_RS_HOST', 11211), + 'port' => env('TEST_RS_PORT', 6379), 'lifetime' => 24, - 'prefix' => 'test_', + 'prefix' => 'test_', ], [ - 'host' => env('TEST_RS_HOST', 11211), - 'port' => env('TEST_RS_PORT', 6379), - 'lifetime' => 24, - 'prefix' => 'test_', - 'persistent' => false - ] + 'host' => env('TEST_RS_HOST', 11211), + 'port' => env('TEST_RS_PORT', 6379), + 'lifetime' => 24, + 'prefix' => 'test_', + 'persistent' => false, + ], ], + [ [ 'host' => env('TEST_RS_HOST', 11211), 'port' => env('TEST_RS_PORT', 6379), ], [ - 'host' => env('TEST_RS_HOST', 11211), - 'port' => env('TEST_RS_PORT', 6379), - 'lifetime' => 8600, - 'prefix' => '', - 'persistent' => false - ] + 'host' => env('TEST_RS_HOST', 11211), + 'port' => env('TEST_RS_PORT', 6379), + 'lifetime' => 8600, + 'prefix' => '', + 'persistent' => false, + ], ], + [ [ 'host' => env('TEST_RS_HOST', 11211), ], [ - 'host' => env('TEST_RS_HOST', 11211), - 'port' => env('TEST_RS_PORT', 6379), - 'lifetime' => 8600, - 'prefix' => '', - 'persistent' => false - ] + 'host' => env('TEST_RS_HOST', 11211), + 'port' => env('TEST_RS_PORT', 6379), + 'lifetime' => 8600, + 'prefix' => '', + 'persistent' => false, + ], ], + [ [ ], [ - 'host' => '127.0.0.1', - 'port' => env('TEST_RS_PORT', 6379), - 'lifetime' => 8600, - 'prefix' => '', - 'persistent' => false - ] + 'host' => '127.0.0.1', + 'port' => env('TEST_RS_PORT', 6379), + 'lifetime' => 8600, + 'prefix' => '', + 'persistent' => false, + ], ], ]; } diff --git a/tests/unit/Annotations/Extended/Adapter/ApcTest.php b/tests/unit/Annotations/Extended/Adapter/ApcTest.php index 87009fd33..ede33290a 100644 --- a/tests/unit/Annotations/Extended/Adapter/ApcTest.php +++ b/tests/unit/Annotations/Extended/Adapter/ApcTest.php @@ -19,11 +19,15 @@ protected function _before() } if (!ini_get('apc.enabled') || (PHP_SAPI === 'cli' && !ini_get('apc.enable_cli'))) { - $this->markTestSkipped('Warning: apc.enable_cli must be set to "On"'); + $this->markTestSkipped( + 'Warning: apc.enable_cli must be set to "On"' + ); } if (extension_loaded('apcu') && version_compare(phpversion('apcu'), '5.1.6', '=')) { - $this->markTestSkipped('Warning: APCu v5.1.6 was broken. See: https://github.com/krakjoe/apcu/issues/203'); + $this->markTestSkipped( + 'Warning: APCu v5.1.6 was broken. See: https://github.com/krakjoe/apcu/issues/203' + ); } } @@ -31,90 +35,200 @@ protected function _before() public function shouldReadFromApcWithoutAnyAdditionalParameter() { $reflection = $this->getReflection(); + $annotations = new Apc(); - $this->tester->haveInApc('_PHAN' . 'read-1', $reflection); - $this->assertEquals($reflection, $annotations->read('read-1')); + $this->tester->haveInApc( + '_PHAN' . 'read-1', + $reflection + ); + + $this->assertEquals( + $reflection, + $annotations->read('read-1') + ); } /** @test */ public function shouldReadFromApcWithPrefix() { $reflection = $this->getReflection(); - $annotations = new Apc(['prefix' => 'prefix-']); - $this->tester->haveInApc('_PHAN' . 'prefix-read-2', $reflection); - $this->assertEquals($reflection, $annotations->read('read-2')); + $annotations = new Apc( + [ + 'prefix' => 'prefix-', + ] + ); + + $this->tester->haveInApc( + '_PHAN' . 'prefix-read-2', + $reflection + ); + + $this->assertEquals( + $reflection, + $annotations->read('read-2') + ); } /** @test */ public function shouldWriteToTheApcWithoutAnyAdditionalParameter() { $reflection = $this->getReflection(); + $annotations = new Apc(); - $this->assertTrue($annotations->write('write-1', $reflection)); - $this->assertEquals($reflection, $this->tester->grabValueFromApc('_PHAN' . 'write-1')); + $this->assertTrue( + $annotations->write('write-1', $reflection) + ); + + $this->assertEquals( + $reflection, + $this->tester->grabValueFromApc( + '_PHAN' . 'write-1' + ) + ); } /** @test */ public function shouldWriteToTheApcWithPrefix() { $reflection = $this->getReflection(); - $annotations = new Apc(['prefix' => 'prefix-']); - $this->assertTrue($annotations->write('write-2', $reflection)); - $this->assertEquals($reflection, $this->tester->grabValueFromApc('_PHAN' . 'prefix-write-2')); + $annotations = new Apc( + [ + 'prefix' => 'prefix-', + ] + ); + + $this->assertTrue( + $annotations->write('write-2', $reflection) + ); + + $this->assertEquals( + $reflection, + $this->tester->grabValueFromApc( + '_PHAN' . 'prefix-write-2' + ) + ); } /** @test */ public function shouldFlushTheApcStorageWithoutAnyAdditionalParameter() { $reflection = $this->getReflection(); + $annotations = new Apc(); - $this->tester->haveInApc('_PHAN' . 'flush-1', $reflection); - $this->tester->haveInApc('_ANOTHER' . 'flush-1', $reflection); + $this->tester->haveInApc( + '_PHAN' . 'flush-1', + $reflection + ); + + $this->tester->haveInApc( + '_ANOTHER' . 'flush-1', + $reflection + ); + + $this->assertTrue( + $annotations->flush() + ); + + $this->tester->dontSeeInApc( + '_PHAN' . 'flush-1' + ); - $this->assertTrue($annotations->flush()); - $this->tester->dontSeeInApc('_PHAN' . 'flush-1'); - $this->tester->seeInApc('_ANOTHER' . 'flush-1', $reflection); + $this->tester->seeInApc( + '_ANOTHER' . 'flush-1', + $reflection + ); } /** @test */ public function shouldFlushTheApcStorageWithPrefix() { $reflection = $this->getReflection(); - $annotations = new Apc(['prefix' => 'prefix-']); - $this->tester->haveInApc('_PHAN' . 'prefix-flush-2', $reflection); - $this->tester->haveInApc('_ANOTHER' . 'prefix-flush-2', $reflection); + $annotations = new Apc( + [ + 'prefix' => 'prefix-', + ] + ); + + $this->tester->haveInApc( + '_PHAN' . 'prefix-flush-2', + $reflection + ); + + $this->tester->haveInApc( + '_ANOTHER' . 'prefix-flush-2', + $reflection + ); + + $this->assertTrue( + $annotations->flush() + ); - $this->assertTrue($annotations->flush()); - $this->tester->dontSeeInApc('_PHAN' . 'prefix-flush-2'); - $this->tester->seeInApc('_ANOTHER' . 'prefix-flush-2', $reflection); + $this->tester->dontSeeInApc( + '_PHAN' . 'prefix-flush-2' + ); + + $this->tester->seeInApc( + '_ANOTHER' . 'prefix-flush-2', + $reflection + ); } /** @test */ public function shouldReadAndWriteFromApcWithoutAnyAdditionalParameter() { $reflection = $this->getReflection(); + $annotations = new Apc(); - $this->assertTrue($annotations->write('read-write-1', $reflection)); - $this->assertEquals($reflection, $annotations->read('read-write-1')); - $this->assertEquals($reflection, $this->tester->grabValueFromApc('_PHAN' . 'read-write-1')); + $this->assertTrue( + $annotations->write('read-write-1', $reflection) + ); + + $this->assertEquals( + $reflection, + $annotations->read('read-write-1') + ); + + $this->assertEquals( + $reflection, + $this->tester->grabValueFromApc( + '_PHAN' . 'read-write-1' + ) + ); } /** @test */ public function shouldReadAndWriteFromApcWithPrefix() { $reflection = $this->getReflection(); - $annotations = new Apc(['prefix' => 'prefix-']); - $this->assertTrue($annotations->write('read-write-2', $reflection)); - $this->assertEquals($reflection, $annotations->read('read-write-2')); - $this->assertEquals($reflection, $this->tester->grabValueFromApc('_PHAN' . 'prefix-read-write-2')); + $annotations = new Apc( + [ + 'prefix' => 'prefix-', + ] + ); + + $this->assertTrue( + $annotations->write('read-write-2', $reflection) + ); + + $this->assertEquals( + $reflection, + $annotations->read('read-write-2') + ); + + $this->assertEquals( + $reflection, + $this->tester->grabValueFromApc( + '_PHAN' . 'prefix-read-write-2' + ) + ); } /** @@ -128,16 +242,29 @@ public function shouldReadAndWriteFromApcWithPrefix() public function shouldGetValueFromApcByUsingPrefixedIdentifier($key, $prefix, $statsKey, $expected) { if ($statsKey === null) { - $options = ['prefix' => $prefix]; + $options = [ + 'prefix' => $prefix, + ]; } else { - $options = ['prefix' => $prefix, 'statsKey' => $statsKey]; + $options = [ + 'prefix' => $prefix, + 'statsKey' => $statsKey, + ]; } $annotations = new Apc($options); - $reflectedMethod = new ReflectionMethod(get_class($annotations), 'getPrefixedIdentifier'); + + $reflectedMethod = new ReflectionMethod( + get_class($annotations), + 'getPrefixedIdentifier' + ); + $reflectedMethod->setAccessible(true); - $this->assertEquals($expected, $reflectedMethod->invoke($annotations, $key)); + $this->assertEquals( + $expected, + $reflectedMethod->invoke($annotations, $key) + ); } public function providerKey() @@ -158,12 +285,14 @@ public function providerKey() protected function getReflection() { - return Reflection::__set_state([ - '_reflectionData' => [ - 'class' => [], - 'methods' => [], - 'properties' => [], + return Reflection::__set_state( + [ + '_reflectionData' => [ + 'class' => [], + 'methods' => [], + 'properties' => [], + ] ] - ]); + ); } } diff --git a/tests/unit/Annotations/Extended/Adapter/FilesTest.php b/tests/unit/Annotations/Extended/Adapter/FilesTest.php index 5c3e3b792..224c83461 100644 --- a/tests/unit/Annotations/Extended/Adapter/FilesTest.php +++ b/tests/unit/Annotations/Extended/Adapter/FilesTest.php @@ -12,11 +12,22 @@ class FilesTest extends Test public function shouldReadFromFileDirectoryWithoutAnyAdditionalParameter() { $reflection = $this->getReflection(); + $annotations = new Files(); - $this->tester->amInPath(sys_get_temp_dir()); - $this->tester->writeToFile('read-1.php', 'assertEquals($reflection, $annotations->read('read-1')); + $this->tester->amInPath( + sys_get_temp_dir() + ); + + $this->tester->writeToFile( + 'read-1.php', + 'assertEquals( + $reflection, + $annotations->read('read-1') + ); $this->tester->deleteFile('read-1.php'); } @@ -25,11 +36,26 @@ public function shouldReadFromFileDirectoryWithoutAnyAdditionalParameter() public function shouldReadFromFileDirectoryWithAnnotationsDir() { $reflection = $this->getReflection(); - $annotations = new Files(['annotationsDir' => codecept_output_dir()]); - $this->tester->amInPath(codecept_output_dir()); - $this->tester->writeToFile('read-2.php', 'assertEquals($reflection, $annotations->read('read-2')); + $annotations = new Files( + [ + 'annotationsDir' => codecept_output_dir(), + ] + ); + + $this->tester->amInPath( + codecept_output_dir() + ); + + $this->tester->writeToFile( + 'read-2.php', + 'assertEquals( + $reflection, + $annotations->read('read-2') + ); $this->tester->deleteFile('read-2.php'); } @@ -38,13 +64,25 @@ public function shouldReadFromFileDirectoryWithAnnotationsDir() public function shouldWriteToTheFileDirectoryWithoutAnyAdditionalParameter() { $reflection = $this->getReflection(); + $annotations = new Files(); - $this->assertTrue($annotations->write('write-1', $reflection)); + $this->assertTrue( + $annotations->write( + 'write-1', + $reflection + ) + ); + + $this->tester->amInPath( + sys_get_temp_dir() + ); - $this->tester->amInPath(sys_get_temp_dir()); $this->tester->seeFileFound('write-1.php'); - $this->tester->seeFileContentsEqual('tester->seeFileContentsEqual( + 'tester->deleteFile('write-1.php'); } @@ -53,13 +91,26 @@ public function shouldWriteToTheFileDirectoryWithoutAnyAdditionalParameter() public function shouldWriteToTheFileDirectoryWithAnnotationsDir() { $reflection = $this->getReflection(); - $annotations = new Files(['annotationsDir' => codecept_output_dir()]); - $this->assertTrue($annotations->write('write-2', $reflection)); + $annotations = new Files( + [ + 'annotationsDir' => codecept_output_dir(), + ] + ); + + $this->assertTrue( + $annotations->write('write-2', $reflection) + ); + + $this->tester->amInPath( + codecept_output_dir() + ); - $this->tester->amInPath(codecept_output_dir()); $this->tester->seeFileFound('write-2.php'); - $this->tester->seeFileContentsEqual('tester->seeFileContentsEqual( + 'tester->deleteFile('write-2.php'); } @@ -68,13 +119,26 @@ public function shouldWriteToTheFileDirectoryWithAnnotationsDir() public function shouldFlushTheFileDirectoryStorageWithoutAnyAdditionalParameter() { $reflection = $this->getReflection(); + $annotations = new Files(); - $this->tester->amInPath(sys_get_temp_dir()); - $this->tester->writeToFile('flush-1.php', 'tester->writeToFile('flush-2.php', 'tester->amInPath( + sys_get_temp_dir() + ); + + $this->tester->writeToFile( + 'flush-1.php', + 'assertTrue($annotations->flush()); + $this->tester->writeToFile( + 'flush-2.php', + 'assertTrue( + $annotations->flush() + ); $this->tester->dontSeeFileFound('flush-1.php'); $this->tester->dontSeeFileFound('flush-2.php'); @@ -84,13 +148,30 @@ public function shouldFlushTheFileDirectoryStorageWithoutAnyAdditionalParameter( public function shouldFlushTheFileDirectoryStorageWithAnnotationsDir() { $reflection = $this->getReflection(); - $annotations = new Files(['annotationsDir' => codecept_output_dir()]); - $this->tester->amInPath(codecept_output_dir()); - $this->tester->writeToFile('flush-3.php', 'tester->writeToFile('flush-4.php', ' codecept_output_dir(), + ] + ); + + $this->tester->amInPath( + codecept_output_dir() + ); + + $this->tester->writeToFile( + 'flush-3.php', + 'tester->writeToFile( + 'flush-4.php', + 'assertTrue($annotations->flush()); + $this->assertTrue( + $annotations->flush() + ); $this->tester->dontSeeFileFound('flush-3.php'); $this->tester->dontSeeFileFound('flush-4.php'); @@ -100,13 +181,28 @@ public function shouldFlushTheFileDirectoryStorageWithAnnotationsDir() public function shouldReadAndWriteFromFileDirectoryWithoutAnyAdditionalParameter() { $reflection = $this->getReflection(); + $annotations = new Files(); - $this->assertTrue($annotations->write('read-write-1', $reflection)); - $this->assertEquals($reflection, $annotations->read('read-write-1')); + $this->assertTrue( + $annotations->write( + 'read-write-1', + $reflection + ) + ); + + $this->assertEquals( + $reflection, + $annotations->read('read-write-1') + ); - $this->tester->amInPath(sys_get_temp_dir()); - $this->tester->seeFileContentsEqual('tester->amInPath( + sys_get_temp_dir() + ); + + $this->tester->seeFileContentsEqual( + 'tester->deleteFile('read-write-1.php'); } @@ -115,13 +211,29 @@ public function shouldReadAndWriteFromFileDirectoryWithoutAnyAdditionalParameter public function shouldReadAndWriteFromFileDirectoryWithAnnotationsDir() { $reflection = $this->getReflection(); - $annotations = new Files(['annotationsDir' => codecept_output_dir()]); - $this->assertTrue($annotations->write('read-write-2', $reflection)); - $this->assertEquals($reflection, $annotations->read('read-write-2')); + $annotations = new Files( + [ + 'annotationsDir' => codecept_output_dir(), + ] + ); + + $this->assertTrue( + $annotations->write('read-write-2', $reflection) + ); + + $this->assertEquals( + $reflection, + $annotations->read('read-write-2') + ); + + $this->tester->amInPath( + codecept_output_dir() + ); - $this->tester->amInPath(codecept_output_dir()); - $this->tester->seeFileContentsEqual('tester->seeFileContentsEqual( + 'tester->deleteFile('read-write-2.php'); } @@ -129,12 +241,14 @@ public function shouldReadAndWriteFromFileDirectoryWithAnnotationsDir() protected function getReflection() { - return Reflection::__set_state([ - '_reflectionData' => [ - 'class' => [], - 'methods' => [], - 'properties' => [], + return Reflection::__set_state( + [ + '_reflectionData' => [ + 'class' => [], + 'methods' => [], + 'properties' => [], + ], ] - ]); + ); } } diff --git a/tests/unit/Annotations/Extended/Adapter/MemoryTest.php b/tests/unit/Annotations/Extended/Adapter/MemoryTest.php index fe6c3d3e5..13e32da14 100644 --- a/tests/unit/Annotations/Extended/Adapter/MemoryTest.php +++ b/tests/unit/Annotations/Extended/Adapter/MemoryTest.php @@ -14,31 +14,55 @@ class MemoryTest extends Test public function shouldReadFromMemoryWithoutAnyAdditionalParameter() { $reflection = $this->getReflection(); + $annotations = new Memory(); - $this->haveInMemory($annotations, 'read-1', $reflection); - $this->assertEquals($reflection, $annotations->read('read-1')); + $this->haveInMemory( + $annotations, + 'read-1', + $reflection + ); + + $this->assertEquals( + $reflection, + $annotations->read('read-1') + ); } /** @test */ public function shouldWriteToTheMemoryWithoutAnyAdditionalParameter() { $reflection = $this->getReflection(); + $annotations = new Memory(); - $this->assertTrue($annotations->write('write-1', $reflection)); - $this->assertEquals($reflection, $this->grabValueFromMemory($annotations, 'write-1')); + $this->assertTrue( + $annotations->write('write-1', $reflection) + ); + + $this->assertEquals( + $reflection, + $this->grabValueFromMemory($annotations, 'write-1') + ); } /** @test */ public function shouldFlushTheMemoryStorageWithoutAnyAdditionalParameter() { $reflection = $this->getReflection(); + $annotations = new Memory(); - $this->haveInMemory($annotations, 'flush-1', $reflection); + $this->haveInMemory( + $annotations, + 'flush-1', + $reflection + ); + + $this->assertTrue( + $annotations->flush() + ); - $this->assertTrue($annotations->flush()); $this->dontSeeInMemory($annotations, 'flush-1'); } @@ -46,11 +70,22 @@ public function shouldFlushTheMemoryStorageWithoutAnyAdditionalParameter() public function shouldReadAndWriteFromMemoryWithoutAnyAdditionalParameter() { $reflection = $this->getReflection(); + $annotations = new Memory(); - $this->assertTrue($annotations->write('read-write-1', $reflection)); - $this->assertEquals($reflection, $annotations->read('read-write-1')); - $this->assertEquals($reflection, $this->grabValueFromMemory($annotations, 'read-write-1')); + $this->assertTrue( + $annotations->write('read-write-1', $reflection) + ); + + $this->assertEquals( + $reflection, + $annotations->read('read-write-1') + ); + + $this->assertEquals( + $reflection, + $this->grabValueFromMemory($annotations, 'read-write-1') + ); } /** @@ -62,10 +97,18 @@ public function shouldReadAndWriteFromMemoryWithoutAnyAdditionalParameter() public function shouldGetValueFromMemoryByUsingPrefixedIdentifier($key, $expected) { $annotations = new Memory(); - $reflectedMethod = new ReflectionMethod(get_class($annotations), 'getPrefixedIdentifier'); + + $reflectedMethod = new ReflectionMethod( + get_class($annotations), + 'getPrefixedIdentifier' + ); + $reflectedMethod->setAccessible(true); - $this->assertEquals($expected, $reflectedMethod->invoke($annotations, $key)); + $this->assertEquals( + $expected, + $reflectedMethod->invoke($annotations, $key) + ); } public function providerKey() @@ -80,18 +123,24 @@ public function providerKey() protected function getReflection() { - return Reflection::__set_state([ - '_reflectionData' => [ - 'class' => [], - 'methods' => [], - 'properties' => [], + return Reflection::__set_state( + [ + '_reflectionData' => [ + 'class' => [], + 'methods' => [], + 'properties' => [], + ], ] - ]); + ); } protected function haveInMemory($object, $key, $value) { - $reflectedProperty = new ReflectionProperty(get_class($object), 'data'); + $reflectedProperty = new ReflectionProperty( + get_class($object), + 'data' + ); + $reflectedProperty->setAccessible(true); $data = $reflectedProperty->getValue($object); @@ -102,7 +151,11 @@ protected function haveInMemory($object, $key, $value) protected function grabValueFromMemory($object, $key) { - $reflectedProperty = new ReflectionProperty(get_class($object), 'data'); + $reflectedProperty = new ReflectionProperty( + get_class($object), + 'data' + ); + $reflectedProperty->setAccessible(true); $data = $reflectedProperty->getValue($object); @@ -112,7 +165,11 @@ protected function grabValueFromMemory($object, $key) protected function dontSeeInMemory($object, $key, $value = false) { - $reflectedProperty = new ReflectionProperty(get_class($object), 'data'); + $reflectedProperty = new ReflectionProperty( + get_class($object), + 'data' + ); + $reflectedProperty->setAccessible(true); $data = $reflectedProperty->getValue($object); @@ -120,7 +177,10 @@ protected function dontSeeInMemory($object, $key, $value = false) if ($value === false) { $this->assertArrayNotHasKey($key, $data); } else { - $this->assertSame($value, $data[$key]); + $this->assertSame( + $value, + $data[$key] + ); } } } diff --git a/tests/unit/Avatar/GravatarTest.php b/tests/unit/Avatar/GravatarTest.php index e45c40c12..bdfdf9596 100644 --- a/tests/unit/Avatar/GravatarTest.php +++ b/tests/unit/Avatar/GravatarTest.php @@ -46,44 +46,89 @@ public function incorrectConfigProvider() 'object' => [new \stdClass()], 'float' => [microtime(true)], 'int' => [PHP_INT_MAX], - 'callable' => [function () {}], - 'resource' => [tmpfile()], + 'callable' => [ + function () { + }, + ], + 'resource' => [ + tmpfile(), + ], ]; } public function testShouldUseConfigInstance() { - $gravatar = new Gravatar(new Config([])); - $this->assertInstanceOf('Phalcon\Avatar\Gravatar', $gravatar); + $gravatar = new Gravatar( + new Config( + [] + ) + ); + + $this->assertInstanceOf( + Gravatar::class, + $gravatar + ); } public function testShouldUseArrayAsConfig() { - $gravatar = new Gravatar([]); - $this->assertInstanceOf('Phalcon\Avatar\Gravatar', $gravatar); + $gravatar = new Gravatar( + [] + ); + + $this->assertInstanceOf( + Gravatar::class, + $gravatar + ); } public function testShouldSetUseDefaultValues() { $gravatar = new Gravatar([]); - $this->assertEquals(Gravatar::RATING_G, $gravatar->getRating()); - $this->assertEquals(80, $gravatar->getSize()); - $this->assertNotTrue($gravatar->isUseSecureURL()); + $this->assertEquals( + Gravatar::RATING_G, + $gravatar->getRating() + ); + + $this->assertEquals( + 80, + $gravatar->getSize() + ); + + $this->assertNotTrue( + $gravatar->isUseSecureURL() + ); } public function testShouldSetOptionsThroughConfig() { - $gravatar = new Gravatar([ - 'default_image' => 'retro', - 'rating' => 'x', - 'size' => 60, - 'use_https' => true - ]); - - $this->assertEquals('retro', $gravatar->getDefaultImage()); - $this->assertEquals(Gravatar::RATING_X, $gravatar->getRating()); - $this->assertEquals(60, $gravatar->getSize()); - $this->assertTrue($gravatar->isUseSecureURL()); + $gravatar = new Gravatar( + [ + 'default_image' => 'retro', + 'rating' => 'x', + 'size' => 60, + 'use_https' => true, + ] + ); + + $this->assertEquals( + 'retro', + $gravatar->getDefaultImage() + ); + + $this->assertEquals( + Gravatar::RATING_X, + $gravatar->getRating() + ); + + $this->assertEquals( + 60, + $gravatar->getSize() + ); + + $this->assertTrue( + $gravatar->isUseSecureURL() + ); } } diff --git a/tests/unit/Cache/Backend/DatabaseTest.php b/tests/unit/Cache/Backend/DatabaseTest.php index 0e7fafc05..31445c019 100644 --- a/tests/unit/Cache/Backend/DatabaseTest.php +++ b/tests/unit/Cache/Backend/DatabaseTest.php @@ -37,7 +37,10 @@ class DatabaseTest extends Test */ public function testShouldThrowExceptionIfDbIsMissingOrInvalid($options) { - new CacheBackend(new CacheFrontend, $options); + new CacheBackend( + new CacheFrontend, + $options + ); } public function incorrectDbProvider() @@ -72,7 +75,12 @@ public function testNotPrefixed() protected function getBackend($prefix = '') { - $frontend = new CacheFrontend(['lifetime' => 10]); + $frontend = new CacheFrontend( + [ + 'lifetime' => 10, + ] + ); + $connection = new DbAdapter( [ 'host' => env('TEST_DB_HOST', '127.0.0.1'), @@ -84,32 +92,61 @@ protected function getBackend($prefix = '') ] ); - return new CacheBackend($frontend, [ - 'db' => $connection, - 'table' => 'cache_data', - 'prefix' => $prefix, - ]); + return new CacheBackend( + $frontend, + [ + 'db' => $connection, + 'table' => 'cache_data', + 'prefix' => $prefix, + ] + ); } protected function runTests(CacheBackend $backend, $lifetime = null) { $backend->save($this->key, $this->data, $lifetime); - $this->assertTrue($backend->exists($this->key)); - $this->assertEquals($this->data, $backend->get($this->key)); + $this->assertTrue( + $backend->exists($this->key) + ); + + $this->assertEquals( + $this->data, + $backend->get($this->key) + ); + $this->assertNotEmpty($backend->queryKeys()); $this->assertNotEmpty($backend->queryKeys('DB_')); - $this->assertTrue($backend->delete($this->key)); - $this->assertFalse($backend->delete($this->key)); + + + + $this->assertTrue( + $backend->delete($this->key) + ); + + $this->assertFalse( + $backend->delete($this->key) + ); + + if (null !== $lifetime) { $backend->save($this->key, $this->data, $lifetime); - $this->assertTrue($backend->exists($this->key, $lifetime)); - $this->assertEquals($this->data, $backend->get($this->key, $lifetime)); + $this->assertTrue( + $backend->exists($this->key, $lifetime) + ); + + $this->assertEquals( + $this->data, + $backend->get($this->key, $lifetime) + ); $backend->save($this->key, $this->data, -$lifetime); - $this->assertFalse($backend->exists($this->key, -$lifetime)); + + $this->assertFalse( + $backend->exists($this->key, -$lifetime) + ); } } } diff --git a/tests/unit/Cache/Backend/NullCacheTest.php b/tests/unit/Cache/Backend/NullCacheTest.php index 27a15da4d..ed2374d39 100644 --- a/tests/unit/Cache/Backend/NullCacheTest.php +++ b/tests/unit/Cache/Backend/NullCacheTest.php @@ -29,107 +29,200 @@ public function testStartShouldAlwaysReturnTrue() { $nullCache = new NullCache(); - $this->assertTrue($nullCache->start('fooBar')); - $this->assertTrue($nullCache->start('fooBar'), 1000); + $this->assertTrue( + $nullCache->start('fooBar') + ); + + $this->assertTrue( + $nullCache->start('fooBar'), + 1000 + ); } public function testFrontendShouldBeNone() { $nullCache = new NullCache(); - $this->assertInstanceOf(NoneFrontend::class, $nullCache->getFrontend()); + $this->assertInstanceOf( + NoneFrontend::class, + $nullCache->getFrontend() + ); } public function testGetOptionsShouldReturnEmptyArray() { $nullCache = new NullCache(); - $this->assertEquals([], $nullCache->getOptions()); + $this->assertEquals( + [], + $nullCache->getOptions() + ); } public function testCacheShouldAlwaysBeFresh() { $nullCache = new NullCache(); - $this->assertTrue($nullCache->isFresh()); + $this->assertTrue( + $nullCache->isFresh() + ); } public function testCacheShouldAlwaysBeStarted() { $nullCache = new NullCache(); - $this->assertTrue($nullCache->isStarted()); + $this->assertTrue( + $nullCache->isStarted() + ); $nullCache->start('fooBar'); - $this->assertTrue($nullCache->isStarted()); + + $this->assertTrue( + $nullCache->isStarted() + ); $nullCache->stop(); - $this->assertTrue($nullCache->isStarted()); + + $this->assertTrue( + $nullCache->isStarted() + ); } public function testLastKeyShouldBeEmpty() { $nullCache = new NullCache(); - $this->assertEquals('', $nullCache->getLastKey()); + $this->assertEquals( + '', + $nullCache->getLastKey() + ); } public function testGetSomethingFromCacheShouldAlwaysReturnNull() { $nullCache = new NullCache(); - $this->assertEquals(null, $nullCache->get('fooBar')); - $this->assertEquals(null, $nullCache->get('fooBar', 1000)); - $this->assertEquals(null, $nullCache->get('fooBar', 0)); + $this->assertEquals( + null, + $nullCache->get('fooBar') + ); + + $this->assertEquals( + null, + $nullCache->get('fooBar', 1000) + ); + + $this->assertEquals( + null, + $nullCache->get('fooBar', 0) + ); $nullCache->save('fooBar', 'baz', 1000); - $this->assertEquals(null, $nullCache->get('fooBar')); - $this->assertEquals(null, $nullCache->get('fooBar', 1000)); - $this->assertEquals(null, $nullCache->get('fooBar', 0)); + + $this->assertEquals( + null, + $nullCache->get('fooBar') + ); + + $this->assertEquals( + null, + $nullCache->get('fooBar', 1000) + ); + + $this->assertEquals( + null, + $nullCache->get('fooBar', 0) + ); } public function testSaveSomethingToCacheShouldAlwaysReturnTrue() { $nullCache = new NullCache(); - $this->assertTrue($nullCache->save('fooBar', null)); - $this->assertTrue($nullCache->save('fooBar', 'baz')); - $this->assertTrue($nullCache->save('fooBar', 'baz', 1000)); - $this->assertTrue($nullCache->save('fooBar', 'baz', 1000, true)); - $this->assertTrue($nullCache->save('fooBar', 'baz', 1000, false)); + $this->assertTrue( + $nullCache->save('fooBar', null) + ); + + $this->assertTrue( + $nullCache->save('fooBar', 'baz') + ); + + $this->assertTrue( + $nullCache->save('fooBar', 'baz', 1000) + ); + + $this->assertTrue( + $nullCache->save('fooBar', 'baz', 1000, true) + ); + + $this->assertTrue( + $nullCache->save('fooBar', 'baz', 1000, false) + ); } public function testDeleteSomethingFromCacheShouldAlwaysReturnTrue() { $nullCache = new NullCache(); - $this->assertTrue($nullCache->delete('fooBar')); - $this->assertFalse($nullCache->exists('fooBar')); + $this->assertTrue( + $nullCache->delete('fooBar') + ); + + $this->assertFalse( + $nullCache->exists('fooBar') + ); $randomKey = 'randomKey' . uniqid('NullCache', true); - $this->assertTrue($nullCache->delete($randomKey)); - $this->assertFalse($nullCache->exists($randomKey)); + + $this->assertTrue( + $nullCache->delete($randomKey) + ); + + $this->assertFalse( + $nullCache->exists($randomKey) + ); } public function testQueryKeysShouldReturnEmptyArray() { $nullCache = new NullCache(); - $this->assertEquals([], $nullCache->queryKeys()); - $this->assertEquals([], $nullCache->queryKeys('fooBar')); + $this->assertEquals( + [], + $nullCache->queryKeys() + ); + + $this->assertEquals( + [], + $nullCache->queryKeys('fooBar') + ); } public function testNoKeyWillEverExistsInTheCache() { $nullCache = new NullCache(); - $this->assertFalse($nullCache->exists('fooBar')); + $this->assertFalse( + $nullCache->exists('fooBar') + ); + + $this->assertTrue( + $nullCache->save('fooBar', 'baz') + ); - $this->assertTrue($nullCache->save('fooBar', 'baz')); - $this->assertFalse($nullCache->exists('fooBar')); + $this->assertFalse( + $nullCache->exists('fooBar') + ); $randomKey = 'randomKey' . uniqid('NullCache', true); - $this->assertTrue($nullCache->save('fooBar', $randomKey)); - $this->assertFalse($nullCache->exists($randomKey)); + + $this->assertTrue( + $nullCache->save('fooBar', $randomKey) + ); + + $this->assertFalse( + $nullCache->exists($randomKey) + ); } } diff --git a/tests/unit/Config/Adapter/XmlTest.php b/tests/unit/Config/Adapter/XmlTest.php index ff6bc2478..c3786af07 100644 --- a/tests/unit/Config/Adapter/XmlTest.php +++ b/tests/unit/Config/Adapter/XmlTest.php @@ -62,7 +62,9 @@ function () { ], ]; - $config = new Xml(PATH_DATA . 'config/config.xml'); + $config = new Xml( + PATH_DATA . 'config/config.xml' + ); expect($config->toArray())->equals($expected); } diff --git a/tests/unit/Config/LoaderTest.php b/tests/unit/Config/LoaderTest.php index 22da0ff2e..24618a5c2 100644 --- a/tests/unit/Config/LoaderTest.php +++ b/tests/unit/Config/LoaderTest.php @@ -27,45 +27,105 @@ class LoaderTest extends Test public function testLoadPhpFileConfig() { $file = INCUBATOR_FIXTURES . 'Config/config.php'; + $config = ConfigLoader::load($file); - $this->assertTrue(is_object($config)); - $this->assertInstanceOf('Phalcon\Config\Adapter\Php', $config); - $this->assertInstanceOf('Phalcon\Config', $config); - $this->assertEquals('bar', $config->phalcon->foo); + $this->assertTrue( + is_object($config) + ); + + $this->assertInstanceOf( + 'Phalcon\Config\Adapter\Php', + $config + ); + + $this->assertInstanceOf( + 'Phalcon\Config', + $config + ); + + $this->assertEquals( + 'bar', + $config->phalcon->foo + ); } public function testLoadPhp5FileConfig() { $file = INCUBATOR_FIXTURES . 'Config/config.php5'; + $config = ConfigLoader::load($file); - $this->assertTrue(is_object($config)); - $this->assertInstanceOf('Phalcon\Config\Adapter\Php', $config); - $this->assertInstanceOf('Phalcon\Config', $config); - $this->assertEquals('bar', $config->phalcon->foo); + $this->assertTrue( + is_object($config) + ); + + $this->assertInstanceOf( + \Phalcon\Config\Adapter\Php::class, + $config + ); + + $this->assertInstanceOf( + \Phalcon\Config::class, + $config + ); + + $this->assertEquals( + 'bar', + $config->phalcon->foo + ); } public function testLoadIncFileConfig() { $file = INCUBATOR_FIXTURES . 'Config/config.inc'; + $config = ConfigLoader::load($file); - $this->assertTrue(is_object($config)); - $this->assertInstanceOf('Phalcon\Config\Adapter\Php', $config); - $this->assertInstanceOf('Phalcon\Config', $config); - $this->assertEquals('bar', $config->phalcon->foo); + $this->assertTrue( + is_object($config) + ); + + $this->assertInstanceOf( + \Phalcon\Config\Adapter\Php::class, + $config + ); + + $this->assertInstanceOf( + \Phalcon\Config::class, + $config + ); + + $this->assertEquals( + 'bar', + $config->phalcon->foo + ); } public function testLoadIniFileConfig() { $file = INCUBATOR_FIXTURES . 'Config/config.ini'; + $config = ConfigLoader::load($file); - $this->assertTrue(is_object($config)); - $this->assertInstanceOf('Phalcon\Config\Adapter\Ini', $config); - $this->assertInstanceOf('Phalcon\Config', $config); - $this->assertEquals('bar', $config->phalcon->foo); + $this->assertTrue( + is_object($config) + ); + + $this->assertInstanceOf( + \Phalcon\Config\Adapter\Ini::class, + $config + ); + + $this->assertInstanceOf( + \Phalcon\Config::class, + $config + ); + + $this->assertEquals( + 'bar', + $config->phalcon->foo + ); } /** @@ -74,12 +134,27 @@ public function testLoadIniFileConfig() public function testLoadJsonFileConfig() { $file = INCUBATOR_FIXTURES . 'Config/config.json'; + $config = ConfigLoader::load($file); - $this->assertTrue(is_object($config)); - $this->assertInstanceOf('Phalcon\Config\Adapter\Json', $config); - $this->assertInstanceOf('Phalcon\Config', $config); - $this->assertEquals('bar', $config->phalcon->foo); + $this->assertTrue( + is_object($config) + ); + + $this->assertInstanceOf( + \Phalcon\Config\Adapter\Json::class, + $config + ); + + $this->assertInstanceOf( + \Phalcon\Config::class, + $config + ); + + $this->assertEquals( + 'bar', + $config->phalcon->foo + ); } /** @@ -88,12 +163,27 @@ public function testLoadJsonFileConfig() public function testLoadYamlFileConfig() { $file = INCUBATOR_FIXTURES . 'Config/config.yaml'; + $config = ConfigLoader::load($file); - $this->assertTrue(is_object($config)); - $this->assertInstanceOf('Phalcon\Config\Adapter\Yaml', $config); - $this->assertInstanceOf('Phalcon\Config', $config); - $this->assertEquals('bar', $config->phalcon->foo); + $this->assertTrue( + is_object($config) + ); + + $this->assertInstanceOf( + \Phalcon\Config\Adapter\Yaml::class, + $config + ); + + $this->assertInstanceOf( + \Phalcon\Config::class, + $config + ); + + $this->assertEquals( + 'bar', + $config->phalcon->foo + ); } /** @@ -102,12 +192,27 @@ public function testLoadYamlFileConfig() public function testLoadYmlFileConfig() { $file = INCUBATOR_FIXTURES . 'Config/config.yml'; + $config = ConfigLoader::load($file); - $this->assertTrue(is_object($config)); - $this->assertInstanceOf('Phalcon\Config\Adapter\Yaml', $config); - $this->assertInstanceOf('Phalcon\Config', $config); - $this->assertEquals('bar', $config->phalcon->foo); + $this->assertTrue( + is_object($config) + ); + + $this->assertInstanceOf( + \Phalcon\Config\Adapter\Yaml::class, + $config + ); + + $this->assertInstanceOf( + \Phalcon\Config::class, + $config + ); + + $this->assertEquals( + 'bar', + $config->phalcon->foo + ); } /** @@ -117,6 +222,7 @@ public function testLoadYmlFileConfig() public function testLoadWrongFilePath() { $file = INCUBATOR_FIXTURES . 'Config/config.jason'; + ConfigLoader::load($file); } @@ -127,6 +233,7 @@ public function testLoadWrongFilePath() public function testLoadUnsupportedConfigFile() { $file = INCUBATOR_FIXTURES . 'Config/config.txt'; + ConfigLoader::load($file); } } diff --git a/tests/unit/Db/Adapter/FactoryTest.php b/tests/unit/Db/Adapter/FactoryTest.php index 1c4de95c3..74b946fd5 100644 --- a/tests/unit/Db/Adapter/FactoryTest.php +++ b/tests/unit/Db/Adapter/FactoryTest.php @@ -47,22 +47,54 @@ protected function _before() public function testLoadMysqlAdapter() { $this->testable['adapter'] = 'mysql'; + $adapter = AdaptersFactory::load($this->testable); - $this->assertTrue(is_object($adapter)); - $this->assertInstanceOf('Phalcon\Db\Adapter\Pdo\Mysql', $adapter); - $this->assertInstanceOf('Phalcon\Db\Adapter\Pdo', $adapter); - $this->assertInstanceOf('Phalcon\Db\Adapter', $adapter); + + $this->assertTrue( + is_object($adapter) + ); + + $this->assertInstanceOf( + \Phalcon\Db\Adapter\Pdo\Mysql::class, + $adapter + ); + + $this->assertInstanceOf( + \Phalcon\Db\Adapter\Pdo::class, + $adapter + ); + + $this->assertInstanceOf( + \Phalcon\Db\Adapter::class, + $adapter + ); } public function testLoadSqliteAdapter() { $this->testable['adapter'] = 'sqlite'; $this->testable['dbname'] = INCUBATOR_FIXTURES . 'Db/sqlite.db'; + $adapter = AdaptersFactory::load($this->testable); - $this->assertTrue(is_object($adapter)); - $this->assertInstanceOf('Phalcon\Db\Adapter\Pdo\Sqlite', $adapter); - $this->assertInstanceOf('Phalcon\Db\Adapter\Pdo', $adapter); - $this->assertInstanceOf('Phalcon\Db\Adapter', $adapter); + + $this->assertTrue( + is_object($adapter) + ); + + $this->assertInstanceOf( + \Phalcon\Db\Adapter\Pdo\Sqlite::class, + $adapter + ); + + $this->assertInstanceOf( + \Phalcon\Db\Adapter\Pdo::class, + $adapter + ); + + $this->assertInstanceOf( + \Phalcon\Db\Adapter::class, + $adapter + ); } /** @@ -72,6 +104,7 @@ public function testLoadSqliteAdapter() public function testMissingConfigKeyAdapter() { unset($this->testable['adapter']); + AdaptersFactory::load($this->testable); } @@ -91,6 +124,7 @@ public function testEmptyConfigKeyAdapter() public function testLoadUnsupportedAdapter() { $this->testable['adapter'] = 'drizzle'; + AdaptersFactory::load($this->testable); } } diff --git a/tests/unit/Db/Dialect/OracleTest.php b/tests/unit/Db/Dialect/OracleTest.php index a9c58cb78..03fa3991f 100644 --- a/tests/unit/Db/Dialect/OracleTest.php +++ b/tests/unit/Db/Dialect/OracleTest.php @@ -39,6 +39,9 @@ public function testDescribeColumnsForSchemaWithDots() "TC.OWNER = 'DATABASE.NAME.WITH.DOTS' ORDER BY TC.COLUMN_ID" ]; - $this->assertEquals(join('', $expected), $sql); + $this->assertEquals( + join('', $expected), + $sql + ); } } diff --git a/tests/unit/Http/Client/HeaderTest.php b/tests/unit/Http/Client/HeaderTest.php index a5f63be12..aa562d386 100644 --- a/tests/unit/Http/Client/HeaderTest.php +++ b/tests/unit/Http/Client/HeaderTest.php @@ -31,23 +31,36 @@ public function testHeaderParsedCorrectlyBothWithAndWithoutMessage() $testData = [ $stringHeaderWithMessage => [ - "statusCode" => 200, + "statusCode" => 200, "statusMessage" => "OK", - "status" => "HTTP/1.1 200 OK", + "status" => "HTTP/1.1 200 OK", ], $stringHeaderNoMessage => [ - "statusCode" => 550, + "statusCode" => 550, "statusMessage" => "", - "status" => "HTTP/1.1 550", + "status" => "HTTP/1.1 550", ], ]; foreach ($testData as $stringHeader => $expected) { $header = new Header(); + $header->parse($stringHeader); - $this->assertEquals($header->statusCode, $expected["statusCode"]); - $this->assertEquals($header->statusMessage, $expected["statusMessage"]); - $this->assertEquals($header->status, $expected["status"]); + + $this->assertEquals( + $expected["statusCode"], + $header->statusCode + ); + + $this->assertEquals( + $expected["statusMessage"], + $header->statusMessage + ); + + $this->assertEquals( + $expected["status"], + $header->status + ); } } } diff --git a/tests/unit/Legacy/CryptTest.php b/tests/unit/Legacy/CryptTest.php index 3e1d418ca..f27e6148a 100644 --- a/tests/unit/Legacy/CryptTest.php +++ b/tests/unit/Legacy/CryptTest.php @@ -30,6 +30,7 @@ class CryptTest extends Test public function _before() { parent::_before(); + if (!extension_loaded('mcrypt')) { $this->markTestSkipped('Warning: mcrypt extension is not loaded'); } @@ -48,15 +49,18 @@ public function testCryptConstants() "Crypt constants are not correct", function ($const, $expected) { expect($const)->equals($expected); - }, ['examples' => [ - [Crypt::PADDING_DEFAULT, 0], - [Crypt::PADDING_ANSI_X_923, 1], - [Crypt::PADDING_PKCS7, 2], - [Crypt::PADDING_ISO_10126, 3], - [Crypt::PADDING_ISO_IEC_7816_4, 4], - [Crypt::PADDING_ZERO, 5], - [Crypt::PADDING_SPACE, 6], - ]] + }, + [ + 'examples' => [ + [Crypt::PADDING_DEFAULT, 0], + [Crypt::PADDING_ANSI_X_923, 1], + [Crypt::PADDING_PKCS7, 2], + [Crypt::PADDING_ISO_10126, 3], + [Crypt::PADDING_ISO_IEC_7816_4, 4], + [Crypt::PADDING_ZERO, 5], + [Crypt::PADDING_SPACE, 6], + ], + ] ); } @@ -76,10 +80,11 @@ function ($key, $test) { MCRYPT_MODE_CBC, MCRYPT_MODE_CFB, MCRYPT_MODE_OFB, - MCRYPT_MODE_NOFB + MCRYPT_MODE_NOFB, ]; $crypt = new Crypt(); + foreach ($modes as $mode) { $crypt->setMode($mode); $crypt->setKey(substr($key, 0, 16)); @@ -90,13 +95,17 @@ function ($key, $test) { $encryption = $crypt->encrypt($test, substr($key, 0, 16)); expect(rtrim($crypt->decrypt($encryption, substr($key, 0, 16)), "\0"))->equals($test); } - }, ['examples' => [ - [md5(uniqid()), str_repeat('x', mt_rand(1, 255))], - [time().time(), str_shuffle(join('', range('a', 'z')))], - ['le$ki12432543543543543', null], - ]] + }, + [ + 'examples' => [ + [md5(uniqid()), str_repeat('x', mt_rand(1, 255))], + [time().time(), str_shuffle(join('', range('a', 'z')))], + ['le$ki12432543543543543', null], + ], + ] ); } + /** * Tests the padding * @@ -121,6 +130,7 @@ function () { } $crypt = new Crypt(); + $crypt->setCipher(MCRYPT_RIJNDAEL_256) ->setKey(substr($key, 0, 16)); @@ -139,6 +149,7 @@ function () { } ); } + /** * Tests the encryption base 64 * @@ -151,7 +162,9 @@ public function testCryptEncryptBase64() "encryption base 64does not return correct results", function () { $crypt = new Crypt(); + $crypt->setPadding(Crypt::PADDING_ANSI_X_923); + $key = substr('phalcon notice 13123123', 0, 16); $expected = 'https://github.com/phalcon/cphalcon/issues?state=open'; diff --git a/tests/unit/Mvc/Collection/Helpers/UniquenessTrait.php b/tests/unit/Mvc/Collection/Helpers/UniquenessTrait.php index 97b479c5a..ed22cfa51 100644 --- a/tests/unit/Mvc/Collection/Helpers/UniquenessTrait.php +++ b/tests/unit/Mvc/Collection/Helpers/UniquenessTrait.php @@ -12,14 +12,20 @@ trait UniquenessTrait private function testSingleField(UnitTester $I) { $validation = new Validation(); + $validation->add('type', new Uniqueness()); + $messages = $validation->validate(null, $this->robot); + $I->assertCount(0, $messages); $I->assertTrue($this->robot->save()); + $messages = $validation->validate(null, $this->robot); $I->assertCount(0, $messages); + $messages = $validation->validate(null, $this->anotherRobot); $I->assertCount(0, $messages); + $messages = $validation->validate(null, $this->deletedRobot); $I->assertCount(1, $messages); } @@ -33,23 +39,30 @@ private function testSingleFieldConvert(UnitTester $I) [ 'convert' => function (array $values) { $values['type'] = 'hydraulic'; // mechanical -> hydraulic + return $values; }, ] ) ); + $messages = $validation->validate(null, $this->deletedRobot); + $I->assertCount(0, $messages); } private function testSingleFieldWithNull(UnitTester $I) { $validation = new Validation(); + $validation->add('deleted', new Uniqueness()); + $messages = $validation->validate(null, $this->robot); $I->assertCount(0, $messages); + $messages = $validation->validate(null, $this->anotherRobot); $I->assertCount(1, $messages); + $messages = $validation->validate(null, $this->deletedRobot); $I->assertCount(0, $messages); } @@ -57,11 +70,15 @@ private function testSingleFieldWithNull(UnitTester $I) private function testMultipleFields(UnitTester $I) { $validation = new Validation(); + $validation->add(['name', 'type'], new Uniqueness()); + $messages = $validation->validate(null, $this->robot); $I->assertCount(0, $messages); + $messages = $validation->validate(null, $this->anotherRobot); $I->assertCount(0, $messages); + $messages = $validation->validate(null, $this->deletedRobot); $I->assertCount(1, $messages); } @@ -69,17 +86,20 @@ private function testMultipleFields(UnitTester $I) private function testMultipleFieldsConvert(UnitTester $I) { $validation = new Validation(); + $validation->add( ['name', 'type'], new Uniqueness( [ 'convert' => function (array $values) { $values['type'] = 'hydraulic'; // mechanical -> hydraulic + return $values; }, ] ) ); + $messages = $validation->validate(null, $this->deletedRobot); $I->assertCount(0, $messages); } @@ -87,7 +107,15 @@ private function testMultipleFieldsConvert(UnitTester $I) private function testMultipleFieldsWithNull(UnitTester $I) { $validation = new Validation(); - $validation->add(['type', 'deleted'], new Uniqueness()); + + $validation->add( + [ + 'type', + 'deleted', + ], + new Uniqueness() + ); + $messages = $validation->validate(null, $this->robot); $I->assertCount(0, $messages); $messages = $validation->validate(null, $this->anotherRobot); @@ -103,6 +131,7 @@ private function testMultipleFieldsWithNull(UnitTester $I) private function testExceptSingleFieldSingleExcept(UnitTester $I) { $validation = new Validation(); + $validation->add( 'year', new Uniqueness( @@ -111,6 +140,7 @@ private function testExceptSingleFieldSingleExcept(UnitTester $I) ] ) ); + $messages = $validation->validate(null, $this->robot); $I->assertCount(0, $messages); $I->assertTrue($this->anotherRobot->save()); @@ -121,6 +151,7 @@ private function testExceptSingleFieldSingleExcept(UnitTester $I) private function testExceptSingleFieldMultipleExcept(UnitTester $I) { $validation = new Validation(); + $validation->add( 'year', new Uniqueness( @@ -129,6 +160,7 @@ private function testExceptSingleFieldMultipleExcept(UnitTester $I) ] ) ); + $messages = $validation->validate(null, $this->robot); $I->assertCount(0, $messages); $messages = $validation->validate(null, $this->anotherRobot); @@ -138,6 +170,7 @@ private function testExceptSingleFieldMultipleExcept(UnitTester $I) private function testExceptMultipleFieldSingleExcept(UnitTester $I) { $validation = new Validation(); + $validation->add( ['type', 'year'], new Uniqueness( @@ -149,6 +182,7 @@ private function testExceptMultipleFieldSingleExcept(UnitTester $I) ] ) ); + $messages = $validation->validate(null, $this->deletedRobot); $I->assertCount(0, $messages); $this->deletedRobot->type = 'mechanical'; @@ -162,6 +196,7 @@ private function testExceptMultipleFieldSingleExcept(UnitTester $I) private function testExceptMultipleFieldMultipleExcept(UnitTester $I) { $validation = new Validation(); + $validation->add( ['year', 'type'], new Uniqueness( @@ -173,8 +208,10 @@ private function testExceptMultipleFieldMultipleExcept(UnitTester $I) ] ) ); + $messages = $validation->validate(null, $this->robot); $I->assertCount(0, $messages); + $messages = $validation->validate(null, $this->anotherRobot); $I->assertCount(0, $messages); } @@ -182,6 +219,7 @@ private function testExceptMultipleFieldMultipleExcept(UnitTester $I) private function testConvertArrayReturnsArray(UnitTester $I) { $validation = new Validation(); + $validation->add( 'type', new Uniqueness( @@ -194,11 +232,13 @@ private function testConvertArrayReturnsArray(UnitTester $I) ] ) ); + try { $validation->validate(null, $this->robot); + $I->assertTrue(false); } catch (\Exception $e) { $I->assertTrue(true); } } -} \ No newline at end of file +} diff --git a/tests/unit/Mvc/Model/Behavior/BlameableTest.php b/tests/unit/Mvc/Model/Behavior/BlameableTest.php index 5f4ab179b..f0e7e2a65 100644 --- a/tests/unit/Mvc/Model/Behavior/BlameableTest.php +++ b/tests/unit/Mvc/Model/Behavior/BlameableTest.php @@ -106,17 +106,23 @@ public function testCreate() public function testUpdate() { $robots = Robots::findFirst(); + $robots->type = 'hydraulic'; + $this->assertTrue($robots->update()); + $audit = Audit::findFirst(2); + $this->assertNotEmpty($audit); $this->assertEquals(Robots::class, $audit->model_name); $this->assertNotEmpty($audit->primary_key); $this->assertEquals($audit->primary_key[0], $robots->id); $this->assertEquals('U', $audit->type); $this->assertEquals('127.0.0.1', $audit->ipaddress); + /** @var AuditDetail[]|Resultset $details */ $details = $audit->details->toArray(); + $this->assertEquals( [ [ diff --git a/tests/unit/Mvc/Model/Behavior/Helper.php b/tests/unit/Mvc/Model/Behavior/Helper.php index c7031c449..a1a2830d0 100644 --- a/tests/unit/Mvc/Model/Behavior/Helper.php +++ b/tests/unit/Mvc/Model/Behavior/Helper.php @@ -91,7 +91,11 @@ protected function _after() protected function getProperty($propertyName, NestedSetBehavior $behavior) { - $property = new ReflectionProperty(get_class($behavior), $propertyName); + $property = new ReflectionProperty( + get_class($behavior), + $propertyName + ); + $property->setAccessible(true); return $property->getValue($behavior); @@ -129,7 +133,11 @@ protected function prettifyRoots($multipleTrees = true) $order = 'lft'; } - $categories = CategoriesManyRoots::find(['order' => $order]); + $categories = CategoriesManyRoots::find( + [ + 'order' => $order, + ] + ); $result = []; foreach ($categories as $category) { @@ -155,7 +163,12 @@ protected function checkIntegrity($rootId = null) /** @var \Phalcon\Db\Result\Pdo $check1 */ $check1 = $connection->query($sql); - $this->assertEquals(['cnt' => '0'], $check1->fetch(\PDO::FETCH_ASSOC)); + $this->assertEquals( + [ + 'cnt' => '0', + ], + $check1->fetch(\PDO::FETCH_ASSOC) + ); $sql = "SELECT COUNT(*) cnt, MIN(lft) min, MAX(rgt) max FROM categories"; diff --git a/tests/unit/Mvc/Model/Behavior/NestedSetTest.php b/tests/unit/Mvc/Model/Behavior/NestedSetTest.php index ba0dffc1d..114d6bf89 100644 --- a/tests/unit/Mvc/Model/Behavior/NestedSetTest.php +++ b/tests/unit/Mvc/Model/Behavior/NestedSetTest.php @@ -100,7 +100,12 @@ function () { $category1->name = 'Mobile Phones'; $category1->saveNode(); - $I->seeInDatabase(CategoriesManyRoots::$table, ['name' => 'Mobile Phones']); + $I->seeInDatabase( + CategoriesManyRoots::$table, + [ + 'name' => 'Mobile Phones', + ] + ); $category1 = CategoriesManyRoots::findFirst(); @@ -113,7 +118,12 @@ function () { $category2->name = 'Cars'; $category2->saveNode(); - $I->seeInDatabase(CategoriesManyRoots::$table, ['name' => 'Cars']); + $I->seeInDatabase( + CategoriesManyRoots::$table, + [ + 'name' => 'Cars', + ] + ); $category2 = CategoriesManyRoots::findFirst(2); @@ -126,7 +136,12 @@ function () { $category3->name = 'Computers'; $category3->saveNode(); - $I->seeInDatabase(CategoriesManyRoots::$table, ['name' => 'Computers']); + $I->seeInDatabase( + CategoriesManyRoots::$table, + [ + 'name' => 'Computers', + ] + ); $category3 = CategoriesManyRoots::findFirst(3); @@ -162,10 +177,11 @@ function () { $category = new CategoriesOneRoot(); $category->name = 'Computers'; $category->saveNode(); - }, [ + }, + [ 'throws' => [ 'Phalcon\Mvc\Model\Exception', - 'Cannot create more than one root in single root mode.' + 'Cannot create more than one root in single root mode.', ] ] ); @@ -429,9 +445,10 @@ function () { */ public function testShouldDeleteNode() { - $this->createTree(); + $samsung = CategoriesManyRoots::findFirst(2); + $actual = $samsung->deleteNode(); $this->assertTrue($actual); diff --git a/tests/unit/Mvc/Model/Behavior/Stubs/Categories.php b/tests/unit/Mvc/Model/Behavior/Stubs/Categories.php index 6b896c5fe..adc4157c2 100644 --- a/tests/unit/Mvc/Model/Behavior/Stubs/Categories.php +++ b/tests/unit/Mvc/Model/Behavior/Stubs/Categories.php @@ -65,8 +65,13 @@ class CategoriesManyRoots extends Model public function initialize() { $this->setSource(self::$table); - $this->addBehavior(new NestedSetBehavior([ - 'hasManyRoots' => true, - ])); + + $this->addBehavior( + new NestedSetBehavior( + [ + 'hasManyRoots' => true, + ] + ) + ); } } diff --git a/tests/unit/Mvc/Model/EagerLoading/EagerLoadingTest.php b/tests/unit/Mvc/Model/EagerLoading/EagerLoadingTest.php index c9ee63a90..32f1250e0 100644 --- a/tests/unit/Mvc/Model/EagerLoading/EagerLoadingTest.php +++ b/tests/unit/Mvc/Model/EagerLoading/EagerLoadingTest.php @@ -114,15 +114,20 @@ public function testManyEagerLoadsAndConstraints() ); $this->assertEquals( - array_sum(array_map(function ($o) { - $c = 0; + array_sum( + array_map( + function ($o) { + $c = 0; - foreach ($o->robots as $r) { - $c += count($r->bugs); - } + foreach ($o->robots as $r) { + $c += count($r->bugs); + } - return $c; - }, $manufacturers)), + return $c; + }, + $manufacturers + ) + ), 2 ); @@ -134,15 +139,24 @@ public function testManyEagerLoadsAndConstraints() ], [ 'limit' => 5, - 'order' => 'id ASC' + 'order' => 'id ASC', ] ); $this->assertEquals( - array_sum(array_map(function ($o) { - return count($o->robots); - }, $manufacturers)), - Robot::count(['manufacturer_id < 6']) + array_sum( + array_map( + function ($o) { + return count($o->robots); + }, + $manufacturers + ) + ), + Robot::count( + [ + 'manufacturer_id < 6', + ] + ) ); $robots = []; @@ -152,9 +166,14 @@ public function testManyEagerLoadsAndConstraints() } $this->assertEquals( - array_sum(array_map(function ($o) { - return count($o->bugs); - }, $robots)), + array_sum( + array_map( + function ($o) { + return count($o->bugs); + }, + $robots + ) + ), 0 ); } @@ -166,7 +185,10 @@ public function testManyEagerLoadsAndConstraints() */ public function testShouldThrowRuntimeExceptionIfTheRelationIsNotDefinedOrSupported($args) { - $reflection = new ReflectionClass('Phalcon\Mvc\Model\EagerLoading\Loader'); + $reflection = new ReflectionClass( + 'Phalcon\Mvc\Model\EagerLoading\Loader' + ); + $reflection->newInstanceArgs([Robot::findFirst(), $args])->execute(); } @@ -178,7 +200,10 @@ public function testShouldThrowRuntimeExceptionIfTheRelationIsNotDefinedOrSuppor */ public function testShouldThrowInvalidArgumentExceptionIfLoaderSubjectIsNotValid($args) { - $reflection = new ReflectionClass('Phalcon\Mvc\Model\EagerLoading\Loader'); + $reflection = new ReflectionClass( + 'Phalcon\Mvc\Model\EagerLoading\Loader' + ); + $reflection->newInstance($args); } @@ -190,7 +215,13 @@ public function testShouldThrowInvalidArgumentExceptionIfLoaderSubjectIsNotValid */ public function testShouldThrowLogicExceptionIfTheEntityWillBeIncomplete($method, $args) { - call_user_func_array(['Phalcon\Test\Mvc\Model\EagerLoading\Stubs\Robot', $method], $args); + call_user_func_array( + [ + 'Phalcon\Test\Mvc\Model\EagerLoading\Stubs\Robot', + $method + ], + $args + ); } /** @@ -200,14 +231,38 @@ public function testShouldThrowLogicExceptionIfTheEntityWillBeIncomplete($method */ public function testShouldThrowBadMethodCallExceptionIfArgumentsWereNotProvided($method) { - call_user_func(['Phalcon\Test\Mvc\Model\EagerLoading\Stubs\Robot', $method]); + call_user_func( + [ + 'Phalcon\Test\Mvc\Model\EagerLoading\Stubs\Robot', + $method + ] + ); } public function testShouldUseEagerLoadingAndGetModelByUsingMethods() { - $this->assertTrue(is_array(Robot::with('Parts'))); - $this->assertTrue(is_object(Robot::findFirstById(1)->load('Parts'))); - $this->assertTrue(is_object(Robot::findFirstWith('Parts', ['id = 1']))); + $this->assertTrue( + is_array( + Robot::with('Parts') + ) + ); + + $this->assertTrue( + is_object( + Robot::findFirstById(1)->load('Parts') + ) + ); + + $this->assertTrue( + is_object( + Robot::findFirstWith( + 'Parts', + [ + 'id = 1', + ] + ) + ) + ); } public function testShouldUseEagerLoadingAndDetectHasManyToMany() @@ -244,7 +299,10 @@ public function testShouldUseEagerLoadingAndDetectHasMany() $rawly = Manufacturer::findFirstById(1); $rawly->robots; - $eagerly = Loader::fromModel(Manufacturer::findFirstById(1), 'Robots'); + $eagerly = Loader::fromModel( + Manufacturer::findFirstById(1), + 'Robots' + ); $this->assertTrue(property_exists($eagerly, 'robots')); $this->assertTrue(is_array($eagerly->robots)); @@ -275,31 +333,54 @@ public function testShouldUseEagerLoadingAndDetectHasOne() $eagerly = Loader::fromModel(Robot::findFirstById(1), 'Purpose'); - $this->assertTrue(property_exists($eagerly, 'purpose')); - $this->assertInstanceOf('Phalcon\Test\Mvc\Model\EagerLoading\Stubs\Purpose', $eagerly->purpose); - $this->assertEquals($rawly->purpose->readAttribute('id'), $eagerly->purpose->readAttribute('id')); + $this->assertTrue( + property_exists($eagerly, 'purpose') + ); + + $this->assertInstanceOf( + 'Phalcon\Test\Mvc\Model\EagerLoading\Stubs\Purpose', + $eagerly->purpose + ); + + $this->assertEquals( + $rawly->purpose->readAttribute('id'), + $eagerly->purpose->readAttribute('id') + ); } public function testShouldUseEagerLoadingAndDetectBelongsToDeep() { $rawly = Manufacturer::findFirstById(1); - $rawly->robots = $this->resultSetToEagerLoadingEquivalent($rawly->robots); + + $rawly->robots = $this->resultSetToEagerLoadingEquivalent( + $rawly->robots + ); foreach ($rawly->robots as $robot) { $robot->parent; } - $eagerly = Loader::fromModel(Manufacturer::findFirstById(1), 'Robots.Parent'); + $eagerly = Loader::fromModel( + Manufacturer::findFirstById(1), + 'Robots.Parent' + ); $this->assertTrue(property_exists($eagerly->robots[0], 'parent')); $this->assertNull($eagerly->robots[0]->parent); - $this->assertInstanceOf('Phalcon\Test\Mvc\Model\EagerLoading\Stubs\Robot', $eagerly->robots[2]->parent); + + $this->assertInstanceOf( + 'Phalcon\Test\Mvc\Model\EagerLoading\Stubs\Robot', + $eagerly->robots[2]->parent + ); $getIds = function ($obj) { return property_exists($obj, 'parent') && isset($obj->parent) ? $obj->parent->readAttribute('id') : null; }; - $this->assertEquals(array_map($getIds, $eagerly->robots), array_map($getIds, $rawly->robots)); + $this->assertEquals( + array_map($getIds, $eagerly->robots), + array_map($getIds, $rawly->robots) + ); } public function testBelongsTo() @@ -310,8 +391,16 @@ public function testBelongsTo() $eagerly = Loader::fromModel(Bug::findFirstById(1), 'Robot'); $this->assertTrue(property_exists($eagerly, 'robot')); - $this->assertInstanceOf('Phalcon\Test\Mvc\Model\EagerLoading\Stubs\Robot', $eagerly->robot); - $this->assertEquals($rawly->robot->readAttribute('id'), $eagerly->robot->readAttribute('id')); + + $this->assertInstanceOf( + 'Phalcon\Test\Mvc\Model\EagerLoading\Stubs\Robot', + $eagerly->robot + ); + + $this->assertEquals( + $rawly->robot->readAttribute('id'), + $eagerly->robot->readAttribute('id') + ); // Reverse $rawly = Robot::findFirstById(2); @@ -320,33 +409,67 @@ public function testBelongsTo() $eagerly = Loader::fromModel(Robot::findFirstById(2), 'Bugs'); $this->assertTrue(property_exists($eagerly, 'bugs')); - $this->assertContainsOnlyInstancesOf('Phalcon\Test\Mvc\Model\EagerLoading\Stubs\Bug', $eagerly->bugs); + + $this->assertContainsOnlyInstancesOf( + 'Phalcon\Test\Mvc\Model\EagerLoading\Stubs\Bug', + $eagerly->bugs + ); $getIds = function ($obj) { return $obj->readAttribute('id'); }; - $this->assertEquals(array_map($getIds, $rawly->bugs), array_map($getIds, $eagerly->bugs)); - $this->assertEmpty(Loader::fromModel(Robot::findFirstById(1), 'Bugs')->bugs); + $this->assertEquals( + array_map($getIds, $rawly->bugs), + array_map($getIds, $eagerly->bugs) + ); + + $this->assertEmpty( + Loader::fromModel(Robot::findFirstById(1), 'Bugs')->bugs + ); // Test from multiple - $rawly = $this->resultSetToEagerLoadingEquivalent(Bug::find(['limit' => 10])); + $rawly = $this->resultSetToEagerLoadingEquivalent( + Bug::find( + [ + 'limit' => 10, + ] + ) + ); + foreach ($rawly as $bug) { $bug->robot; } - $eagerly = Loader::fromResultset(Bug::find(array ('limit' => 10)), 'Robot'); + $eagerly = Loader::fromResultset( + Bug::find( + [ + 'limit' => 10, + ] + ), + 'Robot' + ); $this->assertTrue(is_array($eagerly)); - $this->assertTrue(array_reduce($eagerly, function ($res, $bug) { - return $res && property_exists($bug, 'robot'); - }, true)); + + $this->assertTrue( + array_reduce( + $eagerly, + function ($res, $bug) { + return $res && property_exists($bug, 'robot'); + }, + true + ) + ); $getIds = function ($obj) { return property_exists($obj, 'robot') && isset($obj->robot) ? $obj->robot->readAttribute('id') : null; }; - $this->assertEquals(array_map($getIds, $rawly), array_map($getIds, $eagerly)); + $this->assertEquals( + array_map($getIds, $rawly), + array_map($getIds, $eagerly) + ); } public function providerWithoutArguments() diff --git a/tests/unit/Mvc/Model/MetaData/BaseTest.php b/tests/unit/Mvc/Model/MetaData/BaseTest.php index 2ffe868fd..744c6b4ce 100644 --- a/tests/unit/Mvc/Model/MetaData/BaseTest.php +++ b/tests/unit/Mvc/Model/MetaData/BaseTest.php @@ -28,13 +28,19 @@ public function testBaseMetaDataAdapterImplementsMetaDataInterface() { $mock = Mockery::mock('Phalcon\Mvc\Model\MetaData\Base'); - $this->assertInstanceOf('Phalcon\Mvc\Model\MetaDataInterface', $mock); + $this->assertInstanceOf( + 'Phalcon\Mvc\Model\MetaDataInterface', + $mock + ); } public function testWincacheMetaDataAdapterImplementsMetaDataInterface() { $mock = Mockery::mock('Phalcon\Mvc\Model\MetaData\Wincache'); - $this->assertInstanceOf('Phalcon\Mvc\Model\MetaDataInterface', $mock); + $this->assertInstanceOf( + 'Phalcon\Mvc\Model\MetaDataInterface', + $mock + ); } } diff --git a/tests/unit/Mvc/MongoCollectionTest.php b/tests/unit/Mvc/MongoCollectionTest.php index 44dcd358a..3177f6802 100755 --- a/tests/unit/Mvc/MongoCollectionTest.php +++ b/tests/unit/Mvc/MongoCollectionTest.php @@ -42,7 +42,7 @@ protected function _before() $this->markTestSkipped('mongodb extension not loaded'); } - $this->di->set('mongo', function() { + $this->di->set('mongo', function () { $dsn = 'mongodb://' . env('TEST_MONGODB_HOST', '127.0.0.1') . ':' . env('TEST_MONGODB_PORT', 27017); $mongo = new Client($dsn); @@ -54,7 +54,7 @@ protected function _before() public function testCollectionsSave() { - $car = new Cars(); + $car = new Cars(); $car->manufacturer = 'Mclaren'; $car->model = '650S'; $car->rank = 1; diff --git a/tests/unit/Paginator/PagerTest.php b/tests/unit/Paginator/PagerTest.php index 443363654..c6dd60883 100644 --- a/tests/unit/Paginator/PagerTest.php +++ b/tests/unit/Paginator/PagerTest.php @@ -41,13 +41,18 @@ public function testCreatingPagerObjectWithoutOptionsShouldConstructObject() ->andReturn(null); $pager = new Pager($mock); - $this->assertInstanceOf('Phalcon\Paginator\Pager', $pager); + + $this->assertInstanceOf( + Pager::class, + $pager + ); } public function testCallingGetPagesInRangeMethodWithDefaultOptionsShouldReturnExpectedArray() { // stub paginate $paginate = new stdClass(); + $paginate->total_pages = 20; $paginate->current = 5; $paginate->last = 20; @@ -63,18 +68,23 @@ public function testCallingGetPagesInRangeMethodWithDefaultOptionsShouldReturnEx ->andReturn(null); $pager = new Pager($mock); + $this->assertEquals( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], $pager->getPagesInRange() ); - $this->assertEquals(null, $pager->getLimit()); + $this->assertEquals( + null, + $pager->getLimit() + ); } public function testCallingGetPagesInRangeMethodWithSliderOnEndShouldReturnExpectedArray() { // stub paginate $paginate = new stdClass(); + $paginate->total_pages = 20; $paginate->current = 20; $paginate->last = 20; @@ -89,7 +99,13 @@ public function testCallingGetPagesInRangeMethodWithSliderOnEndShouldReturnExpec ->once() ->andReturn(null); - $pager = new Pager($mock, ['rangeLength' => 5]); + $pager = new Pager( + $mock, + [ + 'rangeLength' => 5, + ] + ); + $this->assertEquals( [16, 17, 18, 19, 20], $pager->getPagesInRange() @@ -100,6 +116,7 @@ public function testCallingGetPagesInRangeMethodWithSliderOnStartShouldReturnExp { // stub paginate $paginate = new stdClass(); + $paginate->total_pages = 20; $paginate->current = 1; $paginate->last = 20; @@ -114,7 +131,13 @@ public function testCallingGetPagesInRangeMethodWithSliderOnStartShouldReturnExp ->once() ->andReturn(null); - $pager = new Pager($mock, ['rangeLength' => 5]); + $pager = new Pager( + $mock, + [ + 'rangeLength' => 5, + ] + ); + $this->assertEquals( [1, 2, 3, 4, 5], $pager->getPagesInRange() @@ -125,6 +148,7 @@ public function testGetLayoutMethodShouldReturnObjectOfLayoutType() { // stub paginate $paginate = new stdClass(); + $paginate->total_pages = 20; $paginate->current = 1; $paginate->last = 20; @@ -139,15 +163,25 @@ public function testGetLayoutMethodShouldReturnObjectOfLayoutType() ->once() ->andReturn(null); - $pager = new Pager($mock, ['rangeLength' => 5, 'urlMask' => 'xxx']); + $pager = new Pager( + $mock, + [ + 'rangeLength' => 5, + 'urlMask' => 'xxx', + ] + ); - $this->assertInstanceOf('Phalcon\Paginator\Pager\Layout', $pager->getLayout()); + $this->assertInstanceOf( + \Phalcon\Paginator\Pager\Layout::class, + $pager->getLayout() + ); } public function testPagerGetterMethodsShouldReturnExpectedValues() { // stub paginate $paginate = new stdClass(); + $paginate->total_pages = 20; $paginate->current = 10; $paginate->last = 20; @@ -167,15 +201,47 @@ public function testPagerGetterMethodsShouldReturnExpectedValues() ->once() ->andReturn(null); - $pager = new Pager($mock, ['rangeLength' => 5, 'urlMask' => 'xxx']); + $pager = new Pager( + $mock, + [ + 'rangeLength' => 5, + 'urlMask' => 'xxx', + ] + ); - $this->assertEquals($paginate->current, $pager->getCurrentPage()); - $this->assertEquals($paginate->total_items, $pager->count()); - $this->assertEquals(1, $pager->getFirstPage()); - $this->assertTrue($pager->haveToPaginate()); - $this->assertEquals($paginate->before, $pager->getPreviousPage()); - $this->assertEquals($paginate->next, $pager->getNextPage()); - $this->assertInstanceOf('Iterator', $pager->getIterator()); + $this->assertEquals( + $paginate->current, + $pager->getCurrentPage() + ); + + $this->assertEquals( + $paginate->total_items, + $pager->count() + ); + + $this->assertEquals( + 1, + $pager->getFirstPage() + ); + + $this->assertTrue( + $pager->haveToPaginate() + ); + + $this->assertEquals( + $paginate->before, + $pager->getPreviousPage() + ); + + $this->assertEquals( + $paginate->next, + $pager->getNextPage() + ); + + $this->assertInstanceOf( + \Iterator::class, + $pager->getIterator() + ); } public function testPagerGetIteratorMethodWillCreateIteratorIfArrayIsPassed() @@ -196,9 +262,18 @@ public function testPagerGetIteratorMethodWillCreateIteratorIfArrayIsPassed() ->once() ->andReturn(null); - $pager = new Pager($mock, ['rangeLength' => 5, 'urlMask' => 'xxx']); + $pager = new Pager( + $mock, + [ + 'rangeLength' => 5, + 'urlMask' => 'xxx', + ] + ); - $this->assertInstanceOf('Iterator', $pager->getIterator()); + $this->assertInstanceOf( + 'Iterator', + $pager->getIterator() + ); } /** @@ -234,6 +309,7 @@ public function testGetLayoutMethodShouldWithInvalidRangeClassShouldThrowExcepti { // stub paginate $paginate = new stdClass(); + $paginate->total_pages = 20; $paginate->current = 1; @@ -251,8 +327,8 @@ public function testGetLayoutMethodShouldWithInvalidRangeClassShouldThrowExcepti $mock, [ 'rangeLength' => 5, - 'rangeClass' => 'UnknownRangeClass', - 'urlMask' => 'xxx', + 'rangeClass' => 'UnknownRangeClass', + 'urlMask' => 'xxx', ] ); @@ -267,6 +343,7 @@ public function testGetLayoutMethodShouldWithInvalidLayoutClassShouldThrowExcept { // stub paginate $paginate = new stdClass(); + $paginate->total_pages = 20; $paginate->current = 1; @@ -285,9 +362,10 @@ public function testGetLayoutMethodShouldWithInvalidLayoutClassShouldThrowExcept [ 'rangeLength' => 5, 'layoutClass' => 'UnknownLayoutClass', - 'urlMask' => 'xxx', + 'urlMask' => 'xxx', ] ); + $pager->getLayout(); } } diff --git a/tests/unit/Queue/Beanstalk/ExtendedTest.php b/tests/unit/Queue/Beanstalk/ExtendedTest.php index 9e568eb0b..ab897a03c 100644 --- a/tests/unit/Queue/Beanstalk/ExtendedTest.php +++ b/tests/unit/Queue/Beanstalk/ExtendedTest.php @@ -41,35 +41,55 @@ class ExtendedTest extends Test */ protected function _before() { - $this->client = new Extended([ - 'host' => env('TEST_BT_HOST', 6379), - 'port' => env('TEST_BT_PORT', 11300), - 'prefix' => 'PHPUnit_', - ]); + $this->client = new Extended( + [ + 'host' => env('TEST_BT_HOST', 6379), + 'port' => env('TEST_BT_PORT', 11300), + 'prefix' => 'PHPUnit_', + ] + ); if (!$this->client->connect()) { - $this->markTestSkipped(sprintf( - 'Need a running beanstalkd server at %s:%d', - env('TEST_BT_HOST', 6379), - env('TEST_BT_PORT', 11300) - )); + $this->markTestSkipped( + sprintf( + 'Need a running beanstalkd server at %s:%d', + env('TEST_BT_HOST', 6379), + env('TEST_BT_PORT', 11300) + ) + ); } - $this->shmKey = round(microtime(true) * 1000); + $this->shmKey = round( + microtime(true) * 1000 + ); } public function testShouldPutAndReserve() { - $jobId = $this->client->putInTube(self::TUBE_NAME, 'testPutInTube'); + $jobId = $this->client->putInTube( + self::TUBE_NAME, + 'testPutInTube' + ); $this->assertNotEquals(false, $jobId); $job = $this->client->reserveFromTube(self::TUBE_NAME); $this->assertNotEmpty($job); - $this->assertInstanceOf(Job::class, $job); - $this->assertEquals($jobId, $job->getId()); - $this->assertTrue($job->delete()); + + $this->assertInstanceOf( + Job::class, + $job + ); + + $this->assertEquals( + $jobId, + $job->getId() + ); + + $this->assertTrue( + $job->delete() + ); } /** @@ -92,7 +112,9 @@ public function testShouldGetTubes() $job = $this->client->reserve(0.1); if ($job) { - $this->assertTrue($job->delete()); + $this->assertTrue( + $job->delete() + ); } else { $isRunning = false; } @@ -135,27 +157,41 @@ public function testShouldDoWork() $that = $this; - $fork->call(function () use ($expected, $that) { - foreach ($expected as $tube => $value) { - $that->client->addWorker($tube, function (Job $job) { - // Store string "test-tube-%JOB_BODY%" in a shared memory - $memory = shmop_open($this->shmKey, 'c', 0644, $this->shmLimit); - $output = trim(shmop_read($memory, 0, $this->shmLimit)); - $output .= sprintf("\ntest-tube-%s", $job->getBody()); - - shmop_write($memory, $output, 0); - shmop_close($memory); + $fork->call( + function () use ($expected, $that) { + foreach ($expected as $tube => $value) { + $that->client->addWorker( + $tube, + function (Job $job) { + // Store string "test-tube-%JOB_BODY%" in a shared memory + $memory = shmop_open($this->shmKey, 'c', 0644, $this->shmLimit); + + $output = trim(shmop_read($memory, 0, $this->shmLimit)); + $output .= sprintf( + "\ntest-tube-%s", + $job->getBody() + ); + + shmop_write($memory, $output, 0); + shmop_close($memory); + + throw new \RuntimeException( + 'Forced exception to stop worker' + ); + } + ); + + $that->assertNotEquals( + false, + $that->client->putInTube($tube, $value) + ); + } - throw new \RuntimeException('Forced exception to stop worker'); - }); + $that->client->doWork(); - $that->assertNotEquals(false, $that->client->putInTube($tube, $value)); + exit(0); } - - $that->client->doWork(); - - exit(0); - }); + ); $reflectionFork = new \ReflectionClass($fork); $reflectionThreads = $reflectionFork->getProperty('threads'); @@ -174,7 +210,10 @@ public function testShouldDoWork() $this->assertNotEmpty($output); - $actual = explode("\n", trim($output)); + $actual = explode( + "\n", + trim($output) + ); $this->assertEquals( count($expected), diff --git a/tests/unit/Session/Adapter/DatabaseTest.php b/tests/unit/Session/Adapter/DatabaseTest.php index 9a4f38d10..6a243d8c6 100644 --- a/tests/unit/Session/Adapter/DatabaseTest.php +++ b/tests/unit/Session/Adapter/DatabaseTest.php @@ -54,15 +54,17 @@ protected function _before() 'password' => env('TEST_DB_PASSWD', 'secret'), 'dbname' => env('TEST_DB_NAME', 'incubator'), 'charset' => env('TEST_DB_CHARSET', 'utf8'), - 'port' => env('TEST_DB_PORT', 3306) + 'port' => env('TEST_DB_PORT', 3306), ] ); - $this->session = new Database([ - 'db' => $this->connection, - 'table' => 'sessions', - 'lifetime' => 3600 - ]); + $this->session = new Database( + [ + 'db' => $this->connection, + 'table' => 'sessions', + 'lifetime' => 3600, + ] + ); } /** @@ -75,8 +77,11 @@ protected function _before() public function shouldWorkSessionAdapter() { $this->session->start(); + $sessionID = $this->session->getId(); + $this->session->set('customer_id', 'somekey'); + $this->specify( "Method set() hasn't worked", function ($data, $expected) { @@ -84,22 +89,41 @@ function ($data, $expected) { }, [ 'examples' => [ - [$_SESSION['customer_id'], 'somekey'] + [ + $this->session->get('customer_id'), + 'somekey', + ], ] ] ); + + session_start(); + $this->session->write( + $sessionID, + session_encode() + ); - $this->session->write($sessionID, session_encode()); - $this->tester->seeInDatabase(ModelSession::$table, ['session_id' => $sessionID]); - $this->tester->seeInDatabase(ModelSession::$table, ['data' => 'customer_id|s:7:"somekey";']); - $this->session->remove('customer_id'); + $this->tester->seeInDatabase( + ModelSession::$table, + [ + 'session_id' => $sessionID, + ] + ); + $this->tester->seeInDatabase( + ModelSession::$table, + [ + 'data' => 'customer_id|s:7:"somekey";', + ] + ); + + $this->session->remove('customer_id'); $sessionData = $this->session->read($sessionID); - session_start(); - session_decode($sessionData); + session_decode($sessionData); + $this->specify( "Method read() hasn't worked", function ($data, $expected) { @@ -107,23 +131,61 @@ function ($data, $expected) { }, [ 'examples' => [ - [$_SESSION['customer_id'], 'somekey'] + [ + $this->session->get('customer_id'), + 'somekey', + ], ] ] ); $this->session->set('customer_id', 'somekey'); $this->session->set('customer_id2', 'somekey2'); - $this->session->write($sessionID, session_encode()); - $this->tester->seeInDatabase(ModelSession::$table, ['session_id' => $sessionID]); - $this->tester->seeInDatabase(ModelSession::$table, ['data' => 'customer_id|s:7:"somekey";customer_id2|s:8:"somekey2";']); + + $this->session->write( + $sessionID, + session_encode() + ); + + $this->tester->seeInDatabase( + ModelSession::$table, + [ + 'session_id' => $sessionID, + ] + ); + + $this->tester->seeInDatabase( + ModelSession::$table, + [ + 'data' => 'customer_id|s:7:"somekey";customer_id2|s:8:"somekey2";', + ] + ); + $this->session->remove('customer_id'); $this->session->remove('customer_id2'); $sessionData = $this->session->read($sessionID); + session_start(); - session_decode($sessionData); + session_decode($sessionData); + + $session = $this->session; + $this->specify( + "Method read() hasn't worked", + function ($data, $expected) use ($session) { + expect($data)->equals($expected); + }, + [ + 'examples' => [ + [ + $this->session->get('customer_id'), + 'somekey', + ], + ], + ] + ); + $this->specify( "Method update() hasn't worked", function ($data, $expected) { @@ -131,13 +193,27 @@ function ($data, $expected) { }, [ 'examples' => [ - [$_SESSION['customer_id'], 'somekey'], - [$_SESSION['customer_id2'], 'somekey2'] - ] + [ + $this->session->get('customer_id'), + 'somekey', + ], + [ + $this->session->get('customer_id2'), + 'somekey2', + ], + ], ] ); - $this->connection->execute($this->getWrittenSessionData($sessionID)); - $this->tester->dontSeeInDatabase(ModelSession::$table, ['session_id' => $sessionID]); + $this->connection->execute( + $this->getWrittenSessionData($sessionID) + ); + + $this->tester->dontSeeInDatabase( + ModelSession::$table, + [ + 'session_id' => $sessionID, + ] + ); } } diff --git a/tests/unit/Test/Codeception/FunctionalTestCaseTest.php b/tests/unit/Test/Codeception/FunctionalTestCaseTest.php index 260ab582b..0029097f3 100644 --- a/tests/unit/Test/Codeception/FunctionalTestCaseTest.php +++ b/tests/unit/Test/Codeception/FunctionalTestCaseTest.php @@ -50,7 +50,13 @@ public function testUsesTrait() $testSubject->setUp(); - $reflectionProperty = new \ReflectionProperty(FunctionalTestCase::class, 'di'); + + + $reflectionProperty = new \ReflectionProperty( + FunctionalTestCase::class, + 'di' + ); + $reflectionProperty->setAccessible(true); $this->assertInstanceOf( diff --git a/tests/unit/Test/Codeception/ModelTestCaseTest.php b/tests/unit/Test/Codeception/ModelTestCaseTest.php index efdf4909e..957997b80 100644 --- a/tests/unit/Test/Codeception/ModelTestCaseTest.php +++ b/tests/unit/Test/Codeception/ModelTestCaseTest.php @@ -50,7 +50,13 @@ public function testUsesTrait() $testSubject->setUp(); - $reflectionProperty = new \ReflectionProperty(ModelTestCase::class, 'di'); + + + $reflectionProperty = new \ReflectionProperty( + ModelTestCase::class, + 'di' + ); + $reflectionProperty->setAccessible(true); $this->assertInstanceOf( diff --git a/tests/unit/Test/Codeception/UnitTestCaseTest.php b/tests/unit/Test/Codeception/UnitTestCaseTest.php index 0a5f233fa..342da0114 100644 --- a/tests/unit/Test/Codeception/UnitTestCaseTest.php +++ b/tests/unit/Test/Codeception/UnitTestCaseTest.php @@ -49,9 +49,18 @@ public function testUsesTrait() $testSubject->setUp(); - $reflectionProperty = new \ReflectionProperty(UnitTestCase::class, 'di'); + + + $reflectionProperty = new \ReflectionProperty( + UnitTestCase::class, + 'di' + ); + $reflectionProperty->setAccessible(true); - $this->assertInstanceOf(DiInterface::class, $reflectionProperty->getValue($testSubject)); + $this->assertInstanceOf( + DiInterface::class, + $reflectionProperty->getValue($testSubject) + ); } } diff --git a/tests/unit/Test/FunctionalTestCaseTest.php b/tests/unit/Test/FunctionalTestCaseTest.php index 925b5b722..c8598d852 100644 --- a/tests/unit/Test/FunctionalTestCaseTest.php +++ b/tests/unit/Test/FunctionalTestCaseTest.php @@ -34,6 +34,9 @@ public function testUnitPlaceholder() ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->assertInstanceOf(PHPUnitTestCase::class, $testSubject); + $this->assertInstanceOf( + PHPUnitTestCase::class, + $testSubject + ); } } diff --git a/tests/unit/Test/ModelTestCaseTest.php b/tests/unit/Test/ModelTestCaseTest.php index 3f461cda1..888175f93 100644 --- a/tests/unit/Test/ModelTestCaseTest.php +++ b/tests/unit/Test/ModelTestCaseTest.php @@ -34,6 +34,9 @@ public function testUnitPlaceholder() ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->assertInstanceOf(PHPUnitTestCase::class, $testSubject); + $this->assertInstanceOf( + PHPUnitTestCase::class, + $testSubject + ); } } diff --git a/tests/unit/Test/PHPUnit/FunctionalTestCaseTest.php b/tests/unit/Test/PHPUnit/FunctionalTestCaseTest.php index 90c02a13a..d5e43d04a 100644 --- a/tests/unit/Test/PHPUnit/FunctionalTestCaseTest.php +++ b/tests/unit/Test/PHPUnit/FunctionalTestCaseTest.php @@ -32,7 +32,13 @@ public function testUsesTrait() $testSubject->setUp(); - $reflectionProperty = new \ReflectionProperty(FunctionalTestCase::class, 'di'); + + + $reflectionProperty = new \ReflectionProperty( + FunctionalTestCase::class, + 'di' + ); + $reflectionProperty->setAccessible(true); $this->assertInstanceOf( diff --git a/tests/unit/Test/PHPUnit/ModelTestCaseTest.php b/tests/unit/Test/PHPUnit/ModelTestCaseTest.php index d8f1c4e9b..ff7116a78 100644 --- a/tests/unit/Test/PHPUnit/ModelTestCaseTest.php +++ b/tests/unit/Test/PHPUnit/ModelTestCaseTest.php @@ -32,7 +32,13 @@ public function testUsesTrait() $testSubject->setUp(); - $reflectionProperty = new \ReflectionProperty(ModelTestCase::class, 'di'); + + + $reflectionProperty = new \ReflectionProperty( + ModelTestCase::class, + 'di' + ); + $reflectionProperty->setAccessible(true); $this->assertInstanceOf( diff --git a/tests/unit/Test/PHPUnit/UnitTestCaseTest.php b/tests/unit/Test/PHPUnit/UnitTestCaseTest.php index 0920bd528..725c1bd5d 100644 --- a/tests/unit/Test/PHPUnit/UnitTestCaseTest.php +++ b/tests/unit/Test/PHPUnit/UnitTestCaseTest.php @@ -32,9 +32,18 @@ public function testUsesTrait() $testSubject->setUp(); - $reflectionProperty = new \ReflectionProperty(UnitTestCase::class, 'di'); + + + $reflectionProperty = new \ReflectionProperty( + UnitTestCase::class, + 'di' + ); + $reflectionProperty->setAccessible(true); - $this->assertInstanceOf(DiInterface::class, $reflectionProperty->getValue($testSubject)); + $this->assertInstanceOf( + DiInterface::class, + $reflectionProperty->getValue($testSubject) + ); } } diff --git a/tests/unit/Test/Traits/ModelTestCaseTest.php b/tests/unit/Test/Traits/ModelTestCaseTest.php index 38c428d29..7c373f1d0 100644 --- a/tests/unit/Test/Traits/ModelTestCaseTest.php +++ b/tests/unit/Test/Traits/ModelTestCaseTest.php @@ -31,7 +31,9 @@ class ModelTestCaseTest extends ModelTest public function _before() { - $this->testSubject = $this->di->get(ModelTest::class); + $this->testSubject = $this->di->get( + ModelTest::class + ); } public function testDbWithDb() @@ -56,10 +58,19 @@ public function testDbWithDb() $this->testSubject->setDI($this->di); - $reflectionMethod = new \ReflectionMethod(ModelTest::class, 'setDb'); + + + $reflectionMethod = new \ReflectionMethod( + ModelTest::class, + 'setDb' + ); + $reflectionMethod->setAccessible(true); - $this->assertSame($mockDb, $reflectionMethod->invoke($this->testSubject)); + $this->assertSame( + $mockDb, + $reflectionMethod->invoke($this->testSubject) + ); } public function testDbWithoutConfig() @@ -91,9 +102,15 @@ public function testDbWithoutConfig() $this->testSubject->setDI($this->di); - $reflectionMethod = new \ReflectionMethod(ModelTest::class, 'setDb'); + + + $reflectionMethod = new \ReflectionMethod( + ModelTest::class, + 'setDb' + ); + $reflectionMethod->setAccessible(true); $reflectionMethod->invoke($this->testSubject); } -} \ No newline at end of file +} diff --git a/tests/unit/Test/Traits/ResultSetTest.php b/tests/unit/Test/Traits/ResultSetTest.php index fbd9545a4..618ba76e3 100644 --- a/tests/unit/Test/Traits/ResultSetTest.php +++ b/tests/unit/Test/Traits/ResultSetTest.php @@ -30,11 +30,13 @@ class ResultSetTest extends Test /** @var \Phalcon\Test\Traits\ResultSet */ protected $testSubject = null; - public function setUp() { + public function setUp() + { $this->testSubject = $this; } - public function testCanMockResultSet() { + public function testCanMockResultSet() + { $mockModel = $this->getMockBuilder(Model::class) ->setMockClassName('ClassA') ->disableOriginalConstructor() @@ -60,21 +62,36 @@ public function testCanMockResultSet() { $mockResultSet = $this->testSubject->mockResultSet($mockData); //Testing Count - $this->assertEquals(3, $mockResultSet->count()); + $this->assertEquals( + 3, + $mockResultSet->count() + ); //Testing Rewind/Valid/Current/Key/Next - foreach($mockResultSet as $currentKey => $testModel) { - $this->assertSame($mockData[$currentKey], $testModel); + foreach ($mockResultSet as $currentKey => $testModel) { + $this->assertSame( + $mockData[$currentKey], + $testModel + ); } //Testing getFirst - $this->assertSame($mockModel, $mockResultSet->getFirst()); + $this->assertSame( + $mockModel, + $mockResultSet->getFirst() + ); //Testing getLast - $this->assertSame($mockThirdModel, $mockResultSet->getLast()); + $this->assertSame( + $mockThirdModel, + $mockResultSet->getLast() + ); //Testing toArray - $this->assertSame($mockData, $mockResultSet->toArray()); + $this->assertSame( + $mockData, + $mockResultSet->toArray() + ); } public function testCanMockEmptyResultSet() @@ -82,14 +99,30 @@ public function testCanMockEmptyResultSet() /** @var \Phalcon\Mvc\Model\Resultset $mockResultSet */ $mockResultSet = $this->testSubject->mockResultset([]); - $this->assertEquals(0, $mockResultSet->count()); - $this->assertFalse($mockResultSet->getFirst()); - $this->assertFalse($mockResultSet->getLast()); + $this->assertEquals( + 0, + $mockResultSet->count() + ); + + $this->assertFalse( + $mockResultSet->getFirst() + ); + + $this->assertFalse( + $mockResultSet->getLast() + ); } public function testCanUseOtherResultSetClasses() { - $mockResultset = $this->mockResultset([], Simple::class); - $this->assertInstanceOf(Simple::class, $mockResultset); + $mockResultset = $this->mockResultset( + [], + Simple::class + ); + + $this->assertInstanceOf( + Simple::class, + $mockResultset + ); } } diff --git a/tests/unit/Test/Traits/UnitTestCaseTest.php b/tests/unit/Test/Traits/UnitTestCaseTest.php index 076592498..931eec6c1 100644 --- a/tests/unit/Test/Traits/UnitTestCaseTest.php +++ b/tests/unit/Test/Traits/UnitTestCaseTest.php @@ -30,9 +30,7 @@ class UnitTestCaseTest extends Unit public function _before() { - $this->testSubject = $this->getMockBuilder( - UnitTestCase::class - )->getMockForTrait(); + $this->testSubject = $this->getMockBuilder(UnitTestCase::class)->getMockForTrait(); } public function testConfig() @@ -46,7 +44,14 @@ public function testConfig() $this->di->set('config', $mockConfig); - $this->assertSame($this->testSubject, $this->testSubject->setConfig($mockConfig)); - $this->assertSame($mockConfig, $this->testSubject->getConfig()); + $this->assertSame( + $this->testSubject, + $this->testSubject->setConfig($mockConfig) + ); + + $this->assertSame( + $mockConfig, + $this->testSubject->getConfig() + ); } -} \ No newline at end of file +} diff --git a/tests/unit/Test/UnitTestCaseTest.php b/tests/unit/Test/UnitTestCaseTest.php index f3b8dc3e5..d540e22e9 100644 --- a/tests/unit/Test/UnitTestCaseTest.php +++ b/tests/unit/Test/UnitTestCaseTest.php @@ -34,6 +34,9 @@ public function testUnitPlaceholder() ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->assertInstanceOf(PHPUnitTestCase::class, $testSubject); + $this->assertInstanceOf( + PHPUnitTestCase::class, + $testSubject + ); } } diff --git a/tests/unit/Translate/Adapter/CsvMulti/Base.php b/tests/unit/Translate/Adapter/CsvMulti/Base.php new file mode 100644 index 000000000..bbdf1b0f7 --- /dev/null +++ b/tests/unit/Translate/Adapter/CsvMulti/Base.php @@ -0,0 +1,26 @@ + $content, + ]; + + $this->adapter = new CsvMulti($params); + } + + public function _after() + { + $this->adapter = null; + } +} diff --git a/tests/unit/Translate/Adapter/CsvMulti/ExistsCest.php b/tests/unit/Translate/Adapter/CsvMulti/ExistsCest.php new file mode 100644 index 000000000..df9101a0f --- /dev/null +++ b/tests/unit/Translate/Adapter/CsvMulti/ExistsCest.php @@ -0,0 +1,60 @@ +wantToTest( + 'Translate\Adapter\CsvMulti - exists cannot work without a locale having been set' + ); + + $I->expectThrowable( + new Exception('The locale must have been defined.'), + function () { + $this->adapter->exists('label_street'); + } + ); + } + + public function translateAdapterExistsItDoesnt(UnitTester $I) + { + $I->wantToTest('Translate\Adapter\CsvMulti - exists returns false'); + + $this->adapter->setLocale('en_US'); + + $I->assertFalse( + $this->adapter->exists('label_cat') + ); + } + + public function translateAdapterExistsItDoes(UnitTester $I) + { + $I->wantToTest('Translate\Adapter\CsvMulti - exists returns true'); + + $this->adapter->setLocale('en_US'); + + $I->assertTrue( + $this->adapter->exists('label_street') + ); + + $I->assertTrue( + $this->adapter->exists('label_car') + ); + + $I->assertTrue( + $this->adapter->exists('label_home') + ); + } +} diff --git a/tests/unit/Translate/Adapter/CsvMulti/GetIndexCest.php b/tests/unit/Translate/Adapter/CsvMulti/GetIndexCest.php new file mode 100644 index 000000000..84e72cb44 --- /dev/null +++ b/tests/unit/Translate/Adapter/CsvMulti/GetIndexCest.php @@ -0,0 +1,33 @@ +wantToTest( + 'Translate\Adapter\CsvMulti - getIndexes returns the indexes' + ); + + $this->adapter->setLocale('en_US'); + + $I->assertEquals( + [ + 'label_street', + 'label_car', + 'label_home', + ], + $this->adapter->getIndexes() + ); + } +} diff --git a/tests/unit/Translate/Adapter/CsvMulti/QueryCest.php b/tests/unit/Translate/Adapter/CsvMulti/QueryCest.php new file mode 100644 index 000000000..b67533a0b --- /dev/null +++ b/tests/unit/Translate/Adapter/CsvMulti/QueryCest.php @@ -0,0 +1,114 @@ +wantToTest( + 'Translate\Adapter\CsvMulti - query returns the key when locale is false' + ); + + $this->adapter->setLocale(false); + + $I->assertEquals( + 'label_street', + $this->adapter->query('label_street') + ); + + $I->assertEquals( + 'label_street', + $this->adapter->query('label_street', 'placeholder_for_street') + ); + } + + public function queryDoesTranslate(UnitTester $I) + { + $I->wantToTest( + 'Translate\Adapter\CsvMulti - query returns the translated string matching the index' + ); + + + + $this->adapter->setLocale('en_US'); + + $I->assertEquals( + 'street', + $this->adapter->query('label_street') + ); + + $I->assertEquals( + 'car', + $this->adapter->query('label_car') + ); + + $I->assertEquals( + 'home', + $this->adapter->query('label_home') + ); + + + + $this->adapter->setLocale('fr_FR'); + + $I->assertEquals( + 'rue', + $this->adapter->query('label_street') + ); + + $I->assertEquals( + 'voiture', + $this->adapter->query('label_car') + ); + + $I->assertEquals( + 'maison', + $this->adapter->query('label_home') + ); + + + $this->adapter->setLocale('es_ES'); + + $I->assertEquals( + 'calle', + $this->adapter->query('label_street') + ); + + $I->assertEquals( + 'coche', + $this->adapter->query('label_car') + ); + + $I->assertEquals( + 'casa', + $this->adapter->query('label_home') + ); + } + + public function queryKeyDoesntExist(UnitTester $I) + { + $I->wantToTest( + 'Translate\Adapter\CsvMulti - query raises an exception when the key doesn\'t match' + ); + + $I->expectThrowable( + new Exception("They key 'label_unexists' was not found."), + function () { + $this->adapter->setLocale('en_US'); + + $this->adapter->query('label_unexists'); + } + ); + } +} diff --git a/tests/unit/Translate/Adapter/DatabaseCest.php b/tests/unit/Translate/Adapter/DatabaseCest.php new file mode 100644 index 000000000..b5849ace5 --- /dev/null +++ b/tests/unit/Translate/Adapter/DatabaseCest.php @@ -0,0 +1,127 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ + +namespace Phalcon\Test\Unit\Translate\Adapter; + +use UnitTester; +use Phalcon\Di; +use Phalcon\Mvc\Model\Metadata\Memory; +use Phalcon\Mvc\Model\Manager; +use Phalcon\Db\Adapter\Pdo\Mysql; +use Phalcon\Translate\Adapter\Database; + +class DatabaseCest +{ + /** + * @var DiInterface + */ + private $previousDependencyInjector; + + /** + * @var Array + */ + private $config = null; + + /** + * executed before each test + */ + public function _before(UnitTester $I) + { + $this->previousDependencyInjector = Di::getDefault(); + + $di = new Di(); + + $di->setShared('modelsMetadata', new Memory()); + $di->setShared('modelsManager', new Manager()); + + $di->setShared( + 'db', + function () { + return new Mysql( + [ + 'host' => env('TEST_DB_HOST', '127.0.0.1'), + 'username' => env('TEST_DB_USER', 'incubator'), + 'password' => env('TEST_DB_PASSWD', 'secret'), + 'dbname' => env('TEST_DB_NAME', 'incubator'), + 'charset' => env('TEST_DB_CHARSET', 'utf8'), + 'port' => env('TEST_DB_PORT', 3306), + ] + ); + } + ); + + if ($this->previousDependencyInjector instanceof DiInterface) { + Di::setDefault($di); + } + + $this->config = [ + 'en' => [ + 'db' => $di->get('db'), // Here we're getting the database from DI + 'table' => 'translations', // The table that is storing the translations + 'language' => 'en_US', // Now we're getting the best language for the user]; + ], + 'fr' => [ + 'db' => $di->get('db'), // Here we're getting the database from DI + 'table' => 'translations', // The table that is storing the translations + 'language' => 'fr_FR', // Now we're getting the best language for the user]; + ], + 'es' => [ + 'db' => $di->get('db'), // Here we're getting the database from DI + 'table' => 'translations', // The table that is storing the translations + 'language' => 'es_ES', // Now we're getting the best language for the user]; + ], + ]; + } + + /** + * executed after each test + */ + protected function _after() + { + if ($this->previousDependencyInjector instanceof DiInterface) { + Di::setDefault( + $this->previousDependencyInjector + ); + } else { + Di::reset(); + } + } + + public function testEnTranslate(UnitTester $I) + { + $params = $this->config['en']; + $translator = new Database($params); + + $expect = 'Hello!'; + $actual = $translator->query('hello'); + $I->assertEquals($expect, $actual); + } + + public function testFrTranslate(UnitTester $I) + { + $params = $this->config['fr']; + $translator = new Database($params); + + $expect = 'Salut!'; + $actual = $translator->query('hello'); + $I->assertEquals($expect, $actual); + } + + public function testEsTranslate(UnitTester $I) + { + $params = $this->config['es']; + $translator = new Database($params); + + $expect = '¡Hola!'; + $actual = $translator->query('hello'); + $I->assertEquals($expect, $actual); + } +} diff --git a/tests/unit/Translate/Interpolator/Intl/ReplacePlaceholdersCest.php b/tests/unit/Translate/Interpolator/Intl/ReplacePlaceholdersCest.php new file mode 100644 index 000000000..dfa9f7947 --- /dev/null +++ b/tests/unit/Translate/Interpolator/Intl/ReplacePlaceholdersCest.php @@ -0,0 +1,150 @@ +wantToTest('Translate\Interpolator\Intl - replacePlaceholders()'); + + $interpolator = new Intl('en_US'); + + $stringFrom = 'I have {number_apples, plural, =0{no apples} =1{one apple} other{# apples}} and my name is {name}.'; + + $I->assertEquals( + 'I have no apples and my name is John.', + $interpolator->replacePlaceholders( + $stringFrom, + [ + 'number_apples' => 0, + 'name' => 'John', + ] + ) + ); + $I->assertEquals( + 'I have one apple and my name is Richard.', + $interpolator->replacePlaceholders( + $stringFrom, + [ + 'number_apples' => 1, + 'name' => 'Richard', + ] + ) + ); + + // thousands separator is "," for en_US + $I->assertEquals( + 'I have 1,000 apples and my name is John.', + $interpolator->replacePlaceholders( + $stringFrom, + [ + 'number_apples' => 1000, + 'name' => 'John', + ] + ) + ); + + // thousands separator is usually " " (blank space) for fr_FR + // depending on system settings it can also be an unbreakable-space + // retrieve it through NumberFormatter API + $numberformatter = new NumberFormatter( + 'fr_FR', + NumberFormatter::PATTERN_DECIMAL + ); + + $thousand_separator = $numberformatter->getSymbol( + NumberFormatter::GROUPING_SEPARATOR_SYMBOL + ); + + unset($numberformatter); + + $interpolator = new Intl('fr_FR'); + $stringFrom = "{number_apples, plural, =0{Je n'ai aucune pomme} =1{J'ai une pomme} other{J'ai # pommes}} et mon nom est {name}."; + + $I->assertEquals( + "J'ai 1{$thousand_separator}000 pommes et mon nom est John.", + $interpolator->replacePlaceholders( + $stringFrom, + [ + 'number_apples' => 1000, + 'name' => 'John', + ] + ) + ); + } + + /** + * Tests Phalcon\Translate\Interpolator\Intl::replacePlaceholders() + * + * @param UnitTester $I + * + * @since 2019-03-07 + */ + public function translateInterpolatorIntlReplacePlaceholdersBadString(UnitTester $I) + { + $I->wantToTest( + 'Translate\Interpolator\Intl - replacePlaceholders() throws an exception when fails to create a MessageFormatter' + ); + + $I->expectThrowable( + new Exception("Unable to instantiate a MessageFormatter. Check locale and string syntax."), + function () { + $interpolator = new Intl('en_US'); + $stringFrom = 'My name is {name, incorrect}.'; + + $interpolator->replacePlaceholders( + $stringFrom, + [ + 'whatever', + ] + ); + } + ); + } + + /** + * Tests Phalcon\Translate\Interpolator\Intl::replacePlaceholders() + * + * @param UnitTester $I + * + * @since 2019-03-07 + */ + public function translateInterpolatorIntlReplacePlaceholdersBadPlaceholders(UnitTester $I) + { + $I->wantToTest( + 'Translate\Interpolator\Intl - replacePlaceholders() throws an exception when placeholders data is illegal' + ); + + $I->expectThrowable( + new Exception("No strategy to convert the value given for the argument with key '0' is available: U_ILLEGAL_ARGUMENT_ERROR", 1), + function () { + $interpolator = new Intl('en_US'); + $stringFrom = 'My name is {name}.'; + + // [[]] is an illegal argument + $interpolator->replacePlaceholders( + $stringFrom, + [ + [], + ] + ); + } + ); + } +} diff --git a/tests/unit/Utils/SlugTest.php b/tests/unit/Utils/SlugTest.php index fcae84b61..f25e7787e 100644 --- a/tests/unit/Utils/SlugTest.php +++ b/tests/unit/Utils/SlugTest.php @@ -64,67 +64,67 @@ public function providerStrings() "Mess'd up --text-- just (to) stress/test/ ?our! " . "`little` \\clean\\ url fun.ction!?-->", [], "-", - 'mess-d-up-text-just-to-stress-test-our-little-clean-url-fun-ction' + 'mess-d-up-text-just-to-stress-test-our-little-clean-url-fun-ction', ], [ "Perchè l'erba è verde?", "'", "-", - 'perche-l-erba-e-verde' + 'perche-l-erba-e-verde', ], // Italian [ "Peux-tu m'aider s'il te plaît?", "'", "-", - 'peux-tu-m-aider-s-il-te-plait' + 'peux-tu-m-aider-s-il-te-plait', ], // French [ "Tänk efter nu – förr'n vi föser dig bort", "-", "-", - 'tank-efter-nu-forr-n-vi-foser-dig-bort' + 'tank-efter-nu-forr-n-vi-foser-dig-bort', ], // Swedish [ "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝßàáâãäåæçèéêëìíîïñòóôõöùúûüýÿ", [], '-', - 'aaaaaaaeceeeeiiiinooooouuuuyssaaaaaaaeceeeeiiiinooooouuuuyy' + 'aaaaaaaeceeeeiiiinooooouuuuyssaaaaaaaeceeeeiiiinooooouuuuyy', ], [ "Custom`delimiter*example", ['*' => " replace "], "-", - 'custom-delimiter-replace-example' + 'custom-delimiter-replace-example', ], [ "My+Last_Crazy|delimiter/example", '', ' ', - 'my last crazy delimiter example' + 'my last crazy delimiter example', ], [ "What does it mean yapılır in Turkish", ['ı' => 'i'], "-", - "what-does-it-mean-yapilir-in-turkish" + "what-does-it-mean-yapilir-in-turkish", ], // Turkish [ 'Àà Ââ Ææ Ää Çç Éé Èè Êê Ëë Îî Ïï Ôô Œœ Öö Ùù Ûû Üü Ÿÿ', [], '-', - 'aa-aa-aeae-aa-cc-ee-ee-ee-ee-ii-ii-oo-oeoe-oo-uu-uu-uu-yy' + 'aa-aa-aeae-aa-cc-ee-ee-ee-ee-ii-ii-oo-oeoe-oo-uu-uu-uu-yy', ], [ 'а б в г д е ё ж з и й к л м н о п р с т у ф х ц ч ш щ ъ ы ь э ю я', [], '-', - 'a-b-v-g-d-e-e-z-z-i-j-k-l-m-n-o-p-r-s-t-u-f-h-c-c-s-s-y-e-u-a' + 'a-b-v-g-d-e-e-z-z-i-j-k-l-m-n-o-p-r-s-t-u-f-h-c-c-s-s-y-e-u-a', ], // Russian [ 'Keramik og stentøj Populære kategorier', [], '-', - 'keramik-og-stentoj-populaere-kategorier' + 'keramik-og-stentoj-populaere-kategorier', ], // Danish ]; } diff --git a/tests/unit/Validation/Validator/AlphaCompleteValidatorTest.php b/tests/unit/Validation/Validator/AlphaCompleteValidatorTest.php index 4424d7119..ff0741371 100644 --- a/tests/unit/Validation/Validator/AlphaCompleteValidatorTest.php +++ b/tests/unit/Validation/Validator/AlphaCompleteValidatorTest.php @@ -34,19 +34,23 @@ public function testAlphaCompleteValidatorOk() $validation->add( 'text', - new AlphaCompleteValidator ( + new AlphaCompleteValidator( [ - 'min' => 5, // Optional - 'max' => 100, // Optional - 'message' => 'Validation failed.', // Optional + 'min' => 5, // Optional + 'max' => 100, // Optional + 'message' => 'Validation failed.', // Optional 'messageMinimum' => 'The value must contain at least 5 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 100 characters.' // Optional + 'messageMaximum' => 'The value can contain maximum 100 characters.', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(0, count($messages)); + + $this->assertCount( + 0, + $messages + ); } public function testAlphaCompleteValidatorOkWithPipe() @@ -57,20 +61,24 @@ public function testAlphaCompleteValidatorOkWithPipe() $validation->add( 'text', - new AlphaCompleteValidator ( + new AlphaCompleteValidator( [ - 'allowPipes' => true, // Optional - 'min' => 5, // Optional - 'max' => 100, // Optional - 'message' => 'Validation failed.', // Optional + 'allowPipes' => true, // Optional + 'min' => 5, // Optional + 'max' => 100, // Optional + 'message' => 'Validation failed.', // Optional 'messageMinimum' => 'The value must contain at least 5 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 100 characters.' // Optional + 'messageMaximum' => 'The value can contain maximum 100 characters.', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(0, count($messages)); + + $this->assertCount( + 0, + $messages + ); } public function testAlphaCompleteValidatorOkWithBackslackesh() @@ -81,20 +89,24 @@ public function testAlphaCompleteValidatorOkWithBackslackesh() $validation->add( 'text', - new AlphaCompleteValidator ( + new AlphaCompleteValidator( [ - 'allowBackslashes' => true, // Optional - 'min' => 5, // Optional - 'max' => 100, // Optional - 'message' => 'Validation failed.', // Optional - 'messageMinimum' => 'The value must contain at least 5 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 100 characters.' // Optional + 'allowBackslashes' => true, // Optional + 'min' => 5, // Optional + 'max' => 100, // Optional + 'message' => 'Validation failed.', // Optional + 'messageMinimum' => 'The value must contain at least 5 characters.', // Optional + 'messageMaximum' => 'The value can contain maximum 100 characters.', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(0, count($messages)); + + $this->assertCount( + 0, + $messages + ); } public function testAlphaCompleteValidatorOkWithUrlChars() @@ -105,21 +117,25 @@ public function testAlphaCompleteValidatorOkWithUrlChars() $validation->add( 'text', - new AlphaCompleteValidator ( + new AlphaCompleteValidator( [ - 'allowPipes' => true, // Optional - 'allowUrlChars' => true, // Optional - 'min' => 5, // Optional - 'max' => 100, // Optional - 'message' => 'Validation failed.', // Optional + 'allowPipes' => true, // Optional + 'allowUrlChars' => true, // Optional + 'min' => 5, // Optional + 'max' => 100, // Optional + 'message' => 'Validation failed.', // Optional 'messageMinimum' => 'The value must contain at least 5 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 100 characters.' // Optional + 'messageMaximum' => 'The value can contain maximum 100 characters.', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(0, count($messages)); + + $this->assertCount( + 0, + $messages + ); } public function testAlphaCompleteValidatorFailingSymbols() @@ -130,11 +146,11 @@ public function testAlphaCompleteValidatorFailingSymbols() $validation->add( 'text', - new AlphaCompleteValidator ( + new AlphaCompleteValidator( [ - 'min' => 5, // Optional - 'max' => 100, // Optional - 'message' => 'Validation failed.', // Optional + 'min' => 5, // Optional + 'max' => 100, // Optional + 'message' => 'Validation failed.', // Optional 'messageMinimum' => 'The value must contain at least 5 characters.', // Optional 'messageMaximum' => 'The value can contain maximum 100 characters.' // Optional ] @@ -142,7 +158,11 @@ public function testAlphaCompleteValidatorFailingSymbols() ); $messages = $validation->validate($data); - $this->assertEquals(1, count($messages)); + + $this->assertCount( + 1, + $messages + ); } public function testAlphaCompleteValidatorFailingUrlCharsEquals() @@ -153,19 +173,23 @@ public function testAlphaCompleteValidatorFailingUrlCharsEquals() $validation->add( 'text', - new AlphaCompleteValidator ( + new AlphaCompleteValidator( [ - 'min' => 5, // Optional - 'max' => 100, // Optional - 'message' => 'Validation failed.', // Optional + 'min' => 5, // Optional + 'max' => 100, // Optional + 'message' => 'Validation failed.', // Optional 'messageMinimum' => 'The value must contain at least 5 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 100 characters.' // Optional + 'messageMaximum' => 'The value can contain maximum 100 characters.', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(1, count($messages)); + + $this->assertCount( + 1, + $messages + ); } public function testAlphaCompleteValidatorFailingUrlCharsHashtag() @@ -176,19 +200,23 @@ public function testAlphaCompleteValidatorFailingUrlCharsHashtag() $validation->add( 'text', - new AlphaCompleteValidator ( + new AlphaCompleteValidator( [ - 'min' => 5, // Optional - 'max' => 100, // Optional - 'message' => 'Validation failed.', // Optional + 'min' => 5, // Optional + 'max' => 100, // Optional + 'message' => 'Validation failed.', // Optional 'messageMinimum' => 'The value must contain at least 5 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 100 characters.' // Optional + 'messageMaximum' => 'The value can contain maximum 100 characters.', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(1, count($messages)); + + $this->assertCount( + 1, + $messages + ); } public function testAlphaCompleteValidatorFailingPipe() @@ -199,19 +227,23 @@ public function testAlphaCompleteValidatorFailingPipe() $validation->add( 'text', - new AlphaCompleteValidator ( + new AlphaCompleteValidator( [ - 'min' => 5, // Optional - 'max' => 100, // Optional - 'message' => 'Validation failed.', // Optional + 'min' => 5, // Optional + 'max' => 100, // Optional + 'message' => 'Validation failed.', // Optional 'messageMinimum' => 'The value must contain at least 5 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 100 characters.' // Optional + 'messageMaximum' => 'The value can contain maximum 100 characters.', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(1, count($messages)); + + $this->assertCount( + 1, + $messages + ); } public function testAlphaCompleteValidatorFailingLength() @@ -222,18 +254,22 @@ public function testAlphaCompleteValidatorFailingLength() $validation->add( 'text', - new AlphaCompleteValidator ( + new AlphaCompleteValidator( [ - 'min' => 5, // Optional - 'max' => 10, // Optional - 'message' => 'Validation failed.', // Optional + 'min' => 5, // Optional + 'max' => 10, // Optional + 'message' => 'Validation failed.', // Optional 'messageMinimum' => 'The value must contain at least 5 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 10 characters.' // Optional + 'messageMaximum' => 'The value can contain maximum 10 characters.', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(1, count($messages)); + + $this->assertCount( + 1, + $messages + ); } } diff --git a/tests/unit/Validation/Validator/AlphaNamesValidatorTest.php b/tests/unit/Validation/Validator/AlphaNamesValidatorTest.php index 3832c9584..5fb22dc17 100644 --- a/tests/unit/Validation/Validator/AlphaNamesValidatorTest.php +++ b/tests/unit/Validation/Validator/AlphaNamesValidatorTest.php @@ -33,20 +33,24 @@ public function testNamesValidatorOk() $validation->add( 'text', - new AlphaNamesValidator ( + new AlphaNamesValidator( [ - 'numbers' => true, // Optional, default false - 'min' => 5, // Optional - 'max' => 100, // Optional - 'message' => 'Validation failed.', // Optional + 'numbers' => true, // Optional, default false + 'min' => 5, // Optional + 'max' => 100, // Optional + 'message' => 'Validation failed.', // Optional 'messageMinimum' => 'The value must contain at least 5 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 100 characters.' // Optional + 'messageMaximum' => 'The value can contain maximum 100 characters.', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(0, count($messages)); + + $this->assertCount( + 0, + $messages + ); } public function testNamesValidatorOkNumbers() @@ -57,20 +61,24 @@ public function testNamesValidatorOkNumbers() $validation->add( 'text', - new AlphaNamesValidator ( + new AlphaNamesValidator( [ - 'numbers' => true, // Optional, default false - 'min' => 5, // Optional - 'max' => 100, // Optional - 'message' => 'Validation failed.', // Optional + 'numbers' => true, // Optional, default false + 'min' => 5, // Optional + 'max' => 100, // Optional + 'message' => 'Validation failed.', // Optional 'messageMinimum' => 'The value must contain at least 5 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 100 characters.' // Optional + 'messageMaximum' => 'The value can contain maximum 100 characters.', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(0, count($messages)); + + $this->assertCount( + 0, + $messages + ); } public function testNamesValidatorFailingNumbers() @@ -81,20 +89,24 @@ public function testNamesValidatorFailingNumbers() $validation->add( 'text', - new AlphaNamesValidator ( + new AlphaNamesValidator( [ - 'numbers' => false, // Optional, default false - 'min' => 5, // Optional - 'max' => 100, // Optional - 'message' => 'Validation failed.', // Optional + 'numbers' => false, // Optional, default false + 'min' => 5, // Optional + 'max' => 100, // Optional + 'message' => 'Validation failed.', // Optional 'messageMinimum' => 'The value must contain at least 5 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 100 characters.' // Optional + 'messageMaximum' => 'The value can contain maximum 100 characters.', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(1, count($messages)); + + $this->assertCount( + 1, + $messages + ); } public function testNamesValidatorFailingLengthAndNumbers() @@ -105,20 +117,24 @@ public function testNamesValidatorFailingLengthAndNumbers() $validation->add( 'text', - new AlphaNamesValidator ( + new AlphaNamesValidator( [ - 'numbers' => false, // Optional, default false - 'min' => 5, // Optional - 'max' => 10, // Optional - 'message' => 'Validation failed.', // Optional + 'numbers' => false, // Optional, default false + 'min' => 5, // Optional + 'max' => 10, // Optional + 'message' => 'Validation failed.', // Optional 'messageMinimum' => 'The value must contain at least 5 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 100 characters.' // Optional + 'messageMaximum' => 'The value can contain maximum 100 characters.', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(2, count($messages)); + + $this->assertCount( + 2, + $messages + ); } public function testNamesValidatorFailingLengthAndBackslash() @@ -129,20 +145,24 @@ public function testNamesValidatorFailingLengthAndBackslash() $validation->add( 'text', - new AlphaNamesValidator ( + new AlphaNamesValidator( [ - 'numbers' => true, // Optional, default false - 'min' => 5, // Optional - 'max' => 10, // Optional - 'message' => 'Validation failed.', // Optional + 'numbers' => true, // Optional, default false + 'min' => 5, // Optional + 'max' => 10, // Optional + 'message' => 'Validation failed.', // Optional 'messageMinimum' => 'The value must contain at least 5 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 100 characters.' // Optional + 'messageMaximum' => 'The value can contain maximum 100 characters.', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(2, count($messages)); + + $this->assertCount( + 2, + $messages + ); } public function testNamesValidatorFailingLenghtAndSymbols() @@ -153,19 +173,23 @@ public function testNamesValidatorFailingLenghtAndSymbols() $validation->add( 'text', - new AlphaNamesValidator ( + new AlphaNamesValidator( [ - 'numbers' => true, // Optional, default false - 'min' => 5, // Optional - 'max' => 10, // Optional - 'message' => 'Validation failed.', // Optional + 'numbers' => true, // Optional, default false + 'min' => 5, // Optional + 'max' => 10, // Optional + 'message' => 'Validation failed.', // Optional 'messageMinimum' => 'The value must contain at least 5 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 100 characters.' // Optional + 'messageMaximum' => 'The value can contain maximum 100 characters.', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(2, count($messages)); + + $this->assertCount( + 2, + $messages + ); } } diff --git a/tests/unit/Validation/Validator/AlphaNumericValidatorTest.php b/tests/unit/Validation/Validator/AlphaNumericValidatorTest.php index d9bcbed51..d4d4744e6 100644 --- a/tests/unit/Validation/Validator/AlphaNumericValidatorTest.php +++ b/tests/unit/Validation/Validator/AlphaNumericValidatorTest.php @@ -33,21 +33,25 @@ public function testAlphaNumericValidatorOk() $validation->add( 'text', - new AlphaNumericValidator ( + new AlphaNumericValidator( [ - 'whiteSpace' => true, // Optional, default false - 'underscore' => true, // Optional, default false - 'min' => 5, // Optional - 'max' => 100, // Optional - 'message' => 'Validation failed.', // Optional + 'whiteSpace' => true, // Optional, default false + 'underscore' => true, // Optional, default false + 'min' => 5, // Optional + 'max' => 100, // Optional + 'message' => 'Validation failed.', // Optional 'messageMinimum' => 'The value must contain at least 5 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 100 characters.' // Optional + 'messageMaximum' => 'The value can contain maximum 100 characters.', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(0, count($messages)); + + $this->assertCount( + 0, + $messages + ); } public function testAlphaNumericValidatorFailingWhiteSpace() @@ -58,21 +62,25 @@ public function testAlphaNumericValidatorFailingWhiteSpace() $validation->add( 'text', - new AlphaNumericValidator ( + new AlphaNumericValidator( [ - 'whiteSpace' => false, // Optional, default false - 'underscore' => true, // Optional, default false - 'min' => 5, // Optional - 'max' => 100, // Optional - 'message' => 'Validation failed.', // Optional + 'whiteSpace' => false, // Optional, default false + 'underscore' => true, // Optional, default false + 'min' => 5, // Optional + 'max' => 100, // Optional + 'message' => 'Validation failed.', // Optional 'messageMinimum' => 'The value must contain at least 5 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 100 characters.' // Optional + 'messageMaximum' => 'The value can contain maximum 100 characters.', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(1, count($messages)); + + $this->assertCount( + 1, + $messages + ); } public function testAlphaNumericValidatorFailingUnderscope() @@ -83,21 +91,25 @@ public function testAlphaNumericValidatorFailingUnderscope() $validation->add( 'text', - new AlphaNumericValidator ( + new AlphaNumericValidator( [ - 'whiteSpace' => true, // Optional, default false - 'underscore' => false, // Optional, default false - 'min' => 5, // Optional - 'max' => 100, // Optional - 'message' => 'Validation failed.', // Optional + 'whiteSpace' => true, // Optional, default false + 'underscore' => false, // Optional, default false + 'min' => 5, // Optional + 'max' => 100, // Optional + 'message' => 'Validation failed.', // Optional 'messageMinimum' => 'The value must contain at least 5 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 100 characters.' // Optional + 'messageMaximum' => 'The value can contain maximum 100 characters.', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(1, count($messages)); + + $this->assertCount( + 1, + $messages + ); } public function testAlphaNumericValidatorFailingLengthAndUnderscore() @@ -108,20 +120,24 @@ public function testAlphaNumericValidatorFailingLengthAndUnderscore() $validation->add( 'text', - new AlphaNumericValidator ( + new AlphaNumericValidator( [ - 'whiteSpace' => true, // Optional, default false - 'underscore' => false, // Optional, default false - 'min' => 5, // Optional - 'max' => 10, // Optional - 'message' => 'Validation failed.', // Optional + 'whiteSpace' => true, // Optional, default false + 'underscore' => false, // Optional, default false + 'min' => 5, // Optional + 'max' => 10, // Optional + 'message' => 'Validation failed.', // Optional 'messageMinimum' => 'The value must contain at least 5 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 100 characters.' // Optional + 'messageMaximum' => 'The value can contain maximum 100 characters.', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(2, count($messages)); + + $this->assertCount( + 2, + $messages + ); } } diff --git a/tests/unit/Validation/Validator/ArrayInclusionInTest.php b/tests/unit/Validation/Validator/ArrayInclusionInTest.php new file mode 100644 index 000000000..948972697 --- /dev/null +++ b/tests/unit/Validation/Validator/ArrayInclusionInTest.php @@ -0,0 +1,123 @@ +add( + 'field', + new ArrayInclusionIn( + [ + 'domain' => $this->domain, + 'allowEmpty' => false, + ] + ) + ); + + $messages = $validation->validate( + [ + 'field' => $values, + ] + ); + + $this->assertCount( + 0, + $messages + ); + } + + public function testArrayInclusionInWithInvalidInput() + { + $values = ['A', 'E']; + + $validation = new Validation(); + + $validation->add( + 'field', + new ArrayInclusionIn( + [ + 'domain' => $this->domain, + 'allowEmpty' => false, + ] + ) + ); + + $messages = $validation->validate( + [ + 'field' => $values, + ] + ); + + $this->assertCount( + 1, + $messages + ); + } + + public function testArrayInclusionInWithInvalidArgument() + { + $values = 'A'; + + $validation = new Validation(); + + $validation->add( + 'field', + new ArrayInclusionIn( + [ + 'domain' => $this->domain, + 'allowEmpty' => false, + ] + ) + ); + + $messages = $validation->validate( + [ + 'field' => $values, + ] + ); + + $this->assertCount( + 1, + $messages + ); + } + + public function testArrayInclusionInWithAllowEmptyTrue() + { + $values = null; + + $validation = new Validation(); + + $validation->add( + 'field', + new ArrayInclusionIn( + [ + 'domain' => $this->domain, + 'allowEmpty' => true, + ] + ) + ); + + $messages = $validation->validate( + [ + 'field' => $values, + ] + ); + + $this->assertCount( + 0, + $messages + ); + } +} diff --git a/tests/unit/Validation/Validator/CardNumberTest.php b/tests/unit/Validation/Validator/CardNumberTest.php index 7953aa27e..7967cb239 100644 --- a/tests/unit/Validation/Validator/CardNumberTest.php +++ b/tests/unit/Validation/Validator/CardNumberTest.php @@ -36,13 +36,31 @@ public function testShouldValidateCardNumberForModel($type, $cardnumber, $willRe $validation = new Validation(); if ($type) { - $validation->add('creditcard', new CardNumber(['type' => $type])); + $validation->add( + 'creditcard', + new CardNumber( + [ + 'type' => $type, + ] + ) + ); } else { - $validation->add('creditcard', new CardNumber()); + $validation->add( + 'creditcard', + new CardNumber() + ); } - $messages = $validation->validate(['creditcard' => $cardnumber]); - $this->assertNotEquals($willReturn, $messages->valid()); + $messages = $validation->validate( + [ + 'creditcard' => $cardnumber, + ] + ); + + $this->assertNotEquals( + $willReturn, + $messages->valid() + ); } public function providerCards() diff --git a/tests/unit/Validation/Validator/ConfirmationOfTest.php b/tests/unit/Validation/Validator/ConfirmationOfTest.php index 96b164641..6b0e59428 100644 --- a/tests/unit/Validation/Validator/ConfirmationOfTest.php +++ b/tests/unit/Validation/Validator/ConfirmationOfTest.php @@ -28,55 +28,116 @@ class ConfirmationOfTest extends Test public function testValidateExceptionWithoutOrigField() { $validation = Stub::make('Phalcon\Validation'); + $validator = new ConfirmationOf(); + $this->setExpectedException('Phalcon\Validation\Exception'); + $validator->validate($validation, 'confirmation'); } public function testValidateSameAsOrig() { - $validation = Stub::make('Phalcon\Validation', array('getValue' => 'value')); - $validator = new ConfirmationOf(array( - 'origField' => 'original' - )); - $this->assertTrue($validator->validate($validation, 'confirmation')); + $validation = Stub::make( + 'Phalcon\Validation', + [ + 'getValue' => 'value', + ] + ); + + $validator = new ConfirmationOf( + [ + 'origField' => 'original', + ] + ); + + $this->assertTrue( + $validator->validate($validation, 'confirmation') + ); } public function testValidateNotSameAsOrig() { - $validation = Stub::make('Phalcon\Validation', array('getValue' => Stub::consecutive('val1', 'val2'), 'appendMessage' => true)); - $validator = new ConfirmationOf(array( - 'origField' => 'original' - )); - $this->assertFalse($validator->validate($validation, 'confirmation')); + $validation = Stub::make( + 'Phalcon\Validation', + [ + 'getValue' => Stub::consecutive('val1', 'val2'), + 'appendMessage' => true, + ] + ); + + $validator = new ConfirmationOf( + [ + 'origField' => 'original', + ] + ); + + $this->assertFalse( + $validator->validate($validation, 'confirmation') + ); } public function testValidateAllowEmpty() { - $validation = Stub::make('Phalcon\Validation', array('getValue' => Stub::consecutive('', 'val2'))); - $validator = new ConfirmationOf(array( - 'origField' => 'original', - 'allowEmpty' => true - )); - $this->assertTrue($validator->validate($validation, 'confirmation')); + $validation = Stub::make( + 'Phalcon\Validation', + [ + 'getValue' => Stub::consecutive('', 'val2'), + ] + ); + + $validator = new ConfirmationOf( + [ + 'origField' => 'original', + 'allowEmpty' => true, + ] + ); + + $this->assertTrue( + $validator->validate($validation, 'confirmation') + ); } public function testValidateNotAllowEmpty() { - $validation = Stub::make('Phalcon\Validation', array('getValue' => Stub::consecutive('', 'val2'), 'appendMessage' => true)); - $validator = new ConfirmationOf(array( - 'origField' => 'original', - 'allowEmpty' => false - )); - $this->assertFalse($validator->validate($validation, 'confirmation')); + $validation = Stub::make( + 'Phalcon\Validation', + [ + 'getValue' => Stub::consecutive('', 'val2'), + 'appendMessage' => true, + ] + ); + + $validator = new ConfirmationOf( + [ + 'origField' => 'original', + 'allowEmpty' => false, + ] + ); + + $this->assertFalse( + $validator->validate($validation, 'confirmation') + ); } public function testValidateInvalidValue() { - $validation = Stub::make('Phalcon\Validation', array('getValue' => array('value', 'value'), 'appendMessage' => true)); - $validator = new ConfirmationOf(array( - 'origField' => 'original' - )); - $this->assertFalse($validator->validate($validation, 'confirmation')); + $validation = Stub::make( + 'Phalcon\Validation', + [ + 'getValue' => ['value', 'value'], + 'appendMessage' => true, + ] + ); + + $validator = new ConfirmationOf( + [ + 'origField' => 'original', + ] + ); + + $this->assertFalse( + $validator->validate($validation, 'confirmation') + ); } } diff --git a/tests/unit/Validation/Validator/Db/UniquenessTest.php b/tests/unit/Validation/Validator/Db/UniquenessTest.php index 1ed1460ea..8056f3ec5 100644 --- a/tests/unit/Validation/Validator/Db/UniquenessTest.php +++ b/tests/unit/Validation/Validator/Db/UniquenessTest.php @@ -44,20 +44,23 @@ private function getDbStub() { codecept_debug('getDbStub'); return Stub::makeEmpty( - 'Phalcon\Db\Adapter\Pdo', + \Phalcon\Db\Adapter\Pdo::class, [ 'fetchOne' => function ($sql, $fetchMode, $params) { - if ( - $sql !== 'SELECT COUNT(*) AS count FROM "users" WHERE "login" = ? AND "id" != ?' && + if ($sql !== 'SELECT COUNT(*) AS count FROM "users" WHERE "login" = ? AND "id" != ?' && $sql !== 'SELECT COUNT(*) AS count FROM "users" WHERE "login" = ?' ) { return null; } if ($params[0] == 'login_taken') { - return ['count' => 1]; + return [ + 'count' => 1, + ]; } else { - return ['count' => 0]; + return [ + 'count' => 0, + ]; } }, 'escapeIdentifier' => function ($identifier) { @@ -74,7 +77,7 @@ private function getDbStub() public function testShouldCatchExceptionWhenValidateUniquenessWithoutDbAndDefaultDI() { $uniquenessOptions = [ - 'table' => 'users', + 'table' => 'users', 'column' => 'login', ]; @@ -87,15 +90,23 @@ public function testShouldCatchExceptionWhenValidateUniquenessWithoutDbAndDefaul */ public function testShouldCatchExceptionWhenValidateUniquenessWithoutColumnOption() { - new Uniqueness(['table' => 'users'], $this->getDbStub()); + new Uniqueness( + [ + 'table' => 'users', + ], + $this->getDbStub() + ); } public function testAvailableUniquenessWithDefaultDI() { - $this->di->set('db', $this->getDbStub()); + $this->di->set( + 'db', + $this->getDbStub() + ); $uniquenessOptions = [ - 'table' => 'users', + 'table' => 'users', 'column' => 'login', ]; @@ -103,39 +114,64 @@ public function testAvailableUniquenessWithDefaultDI() $this->validation->add('login', $uniqueness); - $messages = $this->validation->validate(['login' => 'login_free']); + $messages = $this->validation->validate( + [ + 'login' => 'login_free', + ] + ); + $this->assertCount(0, $messages); } public function testShouldValidateAvailableUniqueness() { $uniquenessOptions = [ - 'table' => 'users', + 'table' => 'users', 'column' => 'login', ]; - $uniqueness = new Uniqueness($uniquenessOptions, $this->getDbStub()); + $uniqueness = new Uniqueness( + $uniquenessOptions, + $this->getDbStub() + ); $this->validation->add('login', $uniqueness); - $messages = $this->validation->validate(['login' => 'login_free']); + $messages = $this->validation->validate( + [ + 'login' => 'login_free', + ] + ); + $this->assertCount(0, $messages); } public function testAlreadyTakenUniquenessWithDefaultMessage() { $uniquenessOptions = [ - 'table' => 'users', + 'table' => 'users', 'column' => 'login', ]; - $uniqueness = new Uniqueness($uniquenessOptions, $this->getDbStub()); + $uniqueness = new Uniqueness( + $uniquenessOptions, + $this->getDbStub() + ); $this->validation->add('login', $uniqueness); - $messages = $this->validation->validate(['login' => 'login_taken']); + + $messages = $this->validation->validate( + [ + 'login' => 'login_taken', + ] + ); $this->assertCount(1, $messages); - $this->assertEquals('Already taken. Choose another!', $messages[0]); + + $this->assertEquals( + 'Already taken. Choose another!', + $messages[0] + ); } public function testAlreadyTakenUniquenessWithCustomMessage() @@ -146,11 +182,24 @@ public function testAlreadyTakenUniquenessWithCustomMessage() 'message' => 'Login already taken.' ]; - $uniqueness = new Uniqueness($uniquenessOptions, $this->getDbStub()); + $uniqueness = new Uniqueness( + $uniquenessOptions, + $this->getDbStub() + ); + $this->validation->add('login', $uniqueness); - $messages = $this->validation->validate(['login' => 'login_taken']); + + $messages = $this->validation->validate( + [ + 'login' => 'login_taken', + ] + ); $this->assertCount(1, $messages); - $this->assertEquals('Login already taken.', $messages[0]); + + $this->assertEquals( + 'Login already taken.', + $messages[0] + ); } } diff --git a/tests/unit/Validation/Validator/DecimalTest.php b/tests/unit/Validation/Validator/DecimalTest.php index 839dde2dd..ce47fafed 100644 --- a/tests/unit/Validation/Validator/DecimalTest.php +++ b/tests/unit/Validation/Validator/DecimalTest.php @@ -33,59 +33,121 @@ public function testShouldCatchExceptionWhenMissedPlacesInDecimalValidation() { $validation = new Validation(); - $validation->add('number', new Decimal([ - 'digit' => 3, - 'point' => ',', - 'message' => 'Price must contain valid decimal value', - ])); + $validation->add( + 'number', + new Decimal( + [ + 'digit' => 3, + 'point' => ',', + 'message' => 'Price must contain valid decimal value', + ] + ) + ); - $validation->validate(['number' => '1233.22']); + $validation->validate( + [ + 'number' => '1233.22', + ] + ); } public function testShouldValidateUsingPlacesInDecimalValidation() { $validation = new Validation(); - $validation->add('number', new Decimal([ - 'places' => 2, - 'message' => 'Price must contain valid decimal value', - ])); + $validation->add( + 'number', + new Decimal( + [ + 'places' => 2, + 'message' => 'Price must contain valid decimal value', + ] + ) + ); - $messages = $validation->validate(['number' => '2.1']); - $this->assertEquals(1, $messages->count()); - $this->assertEquals('Price must contain valid decimal value', $messages[0]->getMessage()); - $this->assertEquals('Decimal', $messages[0]->getType()); + $messages = $validation->validate( + [ + 'number' => '2.1', + ] + ); - $messages = $validation->validate(['number' => '8.67']); - $this->assertEquals(0, $messages->count()); + $this->assertEquals( + 1, + $messages->count() + ); + + $this->assertEquals( + 'Price must contain valid decimal value', + $messages[0]->getMessage() + ); + + $this->assertEquals( + 'Decimal', + $messages[0]->getType() + ); + + $messages = $validation->validate( + [ + 'number' => '8.67', + ] + ); + + $this->assertEquals( + 0, + $messages->count() + ); } public function testShouldValidateUsingDigitsInDecimalValidation() { $validation = new Validation(); - $validation->add('number1', new Decimal([ - 'places' => 2, - 'digits' => 2, - 'label' => 'Magic number #1', - 'message' => ':field must contain valid decimal value', - ])); - - $validation->add('number2', new Decimal([ - 'places' => 2, - 'digits' => 1, - 'label' => 'Magic number #2', - 'message' => ':field must contain valid decimal value', - ])); - - $validation->validate([ - 'number1' => '9.99', - 'number2' => '6.99' - ]); + $validation->add( + 'number1', + new Decimal( + [ + 'places' => 2, + 'digits' => 2, + 'label' => 'Magic number #1', + 'message' => ':field must contain valid decimal value', + ] + ) + ); + + $validation->add( + 'number2', + new Decimal( + [ + 'places' => 2, + 'digits' => 1, + 'label' => 'Magic number #2', + 'message' => ':field must contain valid decimal value', + ] + ) + ); + + $validation->validate( + [ + 'number1' => '9.99', + 'number2' => '6.99', + ] + ); $messages = $validation->getMessages(); - $this->assertEquals(1, $messages->count()); - $this->assertEquals('Magic number #1 must contain valid decimal value', $messages[0]->getMessage()); - $this->assertEquals('Decimal', $messages[0]->getType()); + + $this->assertEquals( + 1, + $messages->count() + ); + + $this->assertEquals( + 'Magic number #1 must contain valid decimal value', + $messages[0]->getMessage() + ); + + $this->assertEquals( + 'Decimal', + $messages[0]->getType() + ); } } diff --git a/tests/unit/Validation/Validator/IbanTest.php b/tests/unit/Validation/Validator/IbanTest.php index 6d0dd56e1..92fcc359d 100644 --- a/tests/unit/Validation/Validator/IbanTest.php +++ b/tests/unit/Validation/Validator/IbanTest.php @@ -40,18 +40,24 @@ class IbanTest extends Test public function shouldValidateIbanCodeWithSetCountryCode($countryCode, $code) { $validation = new Validation(); + $validation->add( 'test', new Iban() ); $validators = $validation->getValidators(); + $validator = $validators[0]; $validator = $validator[1]; $validator->setCountryCode($countryCode); - $messages = $validation->validate(['test' => $code]); + $messages = $validation->validate( + [ + 'test' => $code, + ] + ); $this->assertCount( 0, @@ -82,7 +88,11 @@ public function shouldValidateIbanCodeWithoutCountryCode($countryCode, $code) $iban ); - $messages = $validation->validate(['test' => $code]); + $messages = $validation->validate( + [ + 'test' => $code, + ] + ); $this->assertCount( 0, @@ -106,14 +116,21 @@ public function shouldValidateIbanCodeWithoutCountryCode($countryCode, $code) public function shouldValidateIbanCodeWithCountryCode($countryCode, $code) { $validation = new Validation(); + $validation->add( 'test', - new Iban([ - 'country_code' => $countryCode, - ]) + new Iban( + [ + 'country_code' => $countryCode, + ] + ) ); - $messages = $validation->validate(['test' => $code]); + $messages = $validation->validate( + [ + 'test' => $code, + ] + ); $this->assertCount( 0, @@ -139,18 +156,25 @@ public function shouldValidateIbanCodeWithCountryCode($countryCode, $code) public function shouldCatchErrorMessage($countryCode, $code, $message, $messageType) { $validation = new Validation(); - $iban = new Iban([ - 'country_code' => $countryCode, - $messageType => $message, - 'allow_non_sepa' => false, - ]); + + $iban = new Iban( + [ + 'country_code' => $countryCode, + $messageType => $message, + 'allow_non_sepa' => false, + ] + ); $validation->add( 'test', $iban ); - $messages = $validation->validate(['test' => $code]); + $messages = $validation->validate( + [ + 'test' => $code, + ] + ); foreach ($messages as $messageReturn) { $this->assertEquals( diff --git a/tests/unit/Validation/Validator/IpValidatorTest.php b/tests/unit/Validation/Validator/IpValidatorTest.php index af54d6296..203f05a20 100644 --- a/tests/unit/Validation/Validator/IpValidatorTest.php +++ b/tests/unit/Validation/Validator/IpValidatorTest.php @@ -32,15 +32,19 @@ public function testIpValidatorOk() $validation->add( 'ip', - new \Phalcon\Validation\Validator\IpValidator ( + new \Phalcon\Validation\Validator\IpValidator( [ - 'message' => 'The IP is not valid.' + 'message' => 'The IP is not valid.', ] ) ); $messages = $validation->validate($data); - $this->assertEquals(0, count($messages)); + + $this->assertCount( + 0, + $messages + ); } public function testIpValidatorFailing() @@ -51,14 +55,18 @@ public function testIpValidatorFailing() $validation->add( 'ip', - new \Phalcon\Validation\Validator\IpValidator ( + new \Phalcon\Validation\Validator\IpValidator( [ - 'message' => 'The IP is not valid.' + 'message' => 'The IP is not valid.', ] ) ); $messages = $validation->validate($data); - $this->assertEquals(1, count($messages)); + + $this->assertCount( + 1, + $messages + ); } } diff --git a/tests/unit/Validation/Validator/NumericValidatorTest.php b/tests/unit/Validation/Validator/NumericValidatorTest.php index ad81b0089..d21e953eb 100644 --- a/tests/unit/Validation/Validator/NumericValidatorTest.php +++ b/tests/unit/Validation/Validator/NumericValidatorTest.php @@ -33,19 +33,23 @@ public function testNumericValidatorOk() $validation->add( 'number', - new NumericValidator ( + new NumericValidator( [ - 'min' => 1, // Optional - 'max' => 2000000000, // Optional - 'message' => 'Only numeric (0-9) characters are allowed.', // Optional - 'messageMinimum' => 'The value must be at least 1', // Optional - 'messageMaximum' => 'The value must be lower than 12345678900' // Optional + 'min' => 1, // Optional + 'max' => 2000000000, // Optional + 'message' => 'Only numeric (0-9) characters are allowed.', // Optional + 'messageMinimum' => 'The value must be at least 1', // Optional + 'messageMaximum' => 'The value must be lower than 12345678900', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(0, count($messages)); + + $this->assertCount( + 0, + $messages + ); } public function testNumericValidatorOkSign() @@ -56,20 +60,24 @@ public function testNumericValidatorOkSign() $validation->add( 'number', - new NumericValidator ( + new NumericValidator( [ - 'allowSign' => true, // Optional, default false - 'min' => -20, // Optional - 'max' => 2000000000, // Optional - 'message' => 'Only numeric (0-9) characters are allowed.', // Optional - 'messageMinimum' => 'The value must be at least 1', // Optional - 'messageMaximum' => 'The value must be lower than 12345678900' // Optional + 'allowSign' => true, // Optional, default false + 'min' => -20, // Optional + 'max' => 2000000000, // Optional + 'message' => 'Only numeric (0-9) characters are allowed.', // Optional + 'messageMinimum' => 'The value must be at least 1', // Optional + 'messageMaximum' => 'The value must be lower than 12345678900', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(0, count($messages)); + + $this->assertCount( + 0, + $messages + ); } public function testNumericValidatorFailingSign() @@ -80,19 +88,23 @@ public function testNumericValidatorFailingSign() $validation->add( 'number', - new NumericValidator ( + new NumericValidator( [ - 'min' => 2, // Optional - 'max' => 10 , // Optional - 'message' => 'Only numeric (0-9) characters are allowed.', // Optional - 'messageMinimum' => 'The value must be at least 2', // Optional - 'messageMaximum' => 'The value must be lower than 10' // Optional + 'min' => 2, // Optional + 'max' => 10, // Optional + 'message' => 'Only numeric (0-9) characters are allowed.', // Optional + 'messageMinimum' => 'The value must be at least 2', // Optional + 'messageMaximum' => 'The value must be lower than 10', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(1, count($messages)); + + $this->assertCount( + 1, + $messages + ); } public function testNumericValidatorFailingMax() @@ -103,19 +115,23 @@ public function testNumericValidatorFailingMax() $validation->add( 'number', - new NumericValidator ( + new NumericValidator( [ - 'min' => 2, // Optional - 'max' => 10 , // Optional - 'message' => 'Only numeric (0-9) characters are allowed.', // Optional - 'messageMinimum' => 'The value must be at least 2', // Optional - 'messageMaximum' => 'The value must be lower than 10' // Optional + 'min' => 2, // Optional + 'max' => 10, // Optional + 'message' => 'Only numeric (0-9) characters are allowed.', // Optional + 'messageMinimum' => 'The value must be at least 2', // Optional + 'messageMaximum' => 'The value must be lower than 10' // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(1, count($messages)); + + $this->assertCount( + 1, + $messages + ); } public function testNumericValidatorFailingMin() @@ -126,19 +142,23 @@ public function testNumericValidatorFailingMin() $validation->add( 'number', - new NumericValidator ( + new NumericValidator( [ - 'min' => 2, // Optional - 'max' => 10 , // Optional - 'message' => 'Only numeric (0-9) characters are allowed.', // Optional - 'messageMinimum' => 'The value must be at least 2', // Optional - 'messageMaximum' => 'The value must be lower than 10' // Optional + 'min' => 2, // Optional + 'max' => 10, // Optional + 'message' => 'Only numeric (0-9) characters are allowed.', // Optional + 'messageMinimum' => 'The value must be at least 2', // Optional + 'messageMaximum' => 'The value must be lower than 10', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(1, count($messages)); + + $this->assertCount( + 1, + $messages + ); } public function testNumericValidatorFailingComma() @@ -149,19 +169,23 @@ public function testNumericValidatorFailingComma() $validation->add( 'number', - new NumericValidator ( + new NumericValidator( [ - 'min' => 2, // Optional - 'max' => 10 , // Optional - 'message' => 'Only numeric (0-9) characters are allowed.', // Optional - 'messageMinimum' => 'The value must be at least 2', // Optional - 'messageMaximum' => 'The value must be lower than 10' // Optional + 'min' => 2, // Optional + 'max' => 10, // Optional + 'message' => 'Only numeric (0-9) characters are allowed.', // Optional + 'messageMinimum' => 'The value must be at least 2', // Optional + 'messageMaximum' => 'The value must be lower than 10', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(1, count($messages)); + + $this->assertCount( + 1, + $messages + ); } public function testNumericValidatorFloatOk() @@ -172,20 +196,24 @@ public function testNumericValidatorFloatOk() $validation->add( 'number', - new NumericValidator ( + new NumericValidator( [ - 'allowFloat' => true, // Optional, default: false - 'min' => 2, // Optional - 'max' => 10 , // Optional - 'message' => 'Only numeric (0-9) characters are allowed.', // Optional - 'messageMinimum' => 'The value must be at least 2', // Optional - 'messageMaximum' => 'The value must be lower than 10' // Optional + 'allowFloat' => true, // Optional, default: false + 'min' => 2, // Optional + 'max' => 10, // Optional + 'message' => 'Only numeric (0-9) characters are allowed.', // Optional + 'messageMinimum' => 'The value must be at least 2', // Optional + 'messageMaximum' => 'The value must be lower than 10', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(0, count($messages)); + + $this->assertCount( + 0, + $messages + ); } public function testNumericValidatorFloatOkSignPlus() @@ -196,20 +224,24 @@ public function testNumericValidatorFloatOkSignPlus() $validation->add( 'number', - new NumericValidator ( + new NumericValidator( [ - 'allowSign' => true, // Optional, default: false - 'allowFloat' => true, // Optional, default: false - 'max' => 10 , // Optional - 'message' => 'Only numeric (0-9) characters are allowed.', // Optional - 'messageMinimum' => 'The value must be at least 2', // Optional - 'messageMaximum' => 'The value must be lower than 10' // Optional + 'allowSign' => true, // Optional, default: false + 'allowFloat' => true, // Optional, default: false + 'max' => 10, // Optional + 'message' => 'Only numeric (0-9) characters are allowed.', // Optional + 'messageMinimum' => 'The value must be at least 2', // Optional + 'messageMaximum' => 'The value must be lower than 10', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(0, count($messages)); + + $this->assertCount( + 0, + $messages + ); } public function testNumericValidatorFloatOkSignMenus() @@ -220,20 +252,24 @@ public function testNumericValidatorFloatOkSignMenus() $validation->add( 'number', - new NumericValidator ( + new NumericValidator( [ - 'allowSign' => true, // Optional, default: false - 'allowFloat' => true, // Optional, default: false - 'max' => 10 , // Optional - 'message' => 'Only numeric (0-9) characters are allowed.', // Optional - 'messageMinimum' => 'The value must be at least 2', // Optional - 'messageMaximum' => 'The value must be lower than 10' // Optional + 'allowSign' => true, // Optional, default: false + 'allowFloat' => true, // Optional, default: false + 'max' => 10, // Optional + 'message' => 'Only numeric (0-9) characters are allowed.', // Optional + 'messageMinimum' => 'The value must be at least 2', // Optional + 'messageMaximum' => 'The value must be lower than 10', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(0, count($messages)); + + $this->assertCount( + 0, + $messages + ); } public function testNumericValidatorFloatFailing() @@ -244,20 +280,24 @@ public function testNumericValidatorFloatFailing() $validation->add( 'number', - new NumericValidator ( + new NumericValidator( [ - 'allowFloat' => true, // Optional, default: false - 'min' => 2, // Optional - 'max' => 10 , // Optional - 'message' => 'Only numeric (0-9) characters are allowed.', // Optional - 'messageMinimum' => 'The value must be at least 2', // Optional - 'messageMaximum' => 'The value must be lower than 10' // Optional + 'allowFloat' => true, // Optional, default: false + 'min' => 2, // Optional + 'max' => 10, // Optional + 'message' => 'Only numeric (0-9) characters are allowed.', // Optional + 'messageMinimum' => 'The value must be at least 2', // Optional + 'messageMaximum' => 'The value must be lower than 10', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(1, count($messages)); + + $this->assertCount( + 1, + $messages + ); } public function testNumericValidatorFloatFailingSign() @@ -268,19 +308,23 @@ public function testNumericValidatorFloatFailingSign() $validation->add( 'number', - new NumericValidator ( + new NumericValidator( [ - 'allowFloat' => true, // Optional, default: false - 'min' => 2, // Optional - 'max' => 10 , // Optional - 'message' => 'Only numeric (0-9) characters are allowed.', // Optional - 'messageMinimum' => 'The value must be at least 2', // Optional - 'messageMaximum' => 'The value must be lower than 10' // Optional + 'allowFloat' => true, // Optional, default: false + 'min' => 2, // Optional + 'max' => 10, // Optional + 'message' => 'Only numeric (0-9) characters are allowed.', // Optional + 'messageMinimum' => 'The value must be at least 2', // Optional + 'messageMaximum' => 'The value must be lower than 10', // Optional ] ) ); $messages = $validation->validate($data); - $this->assertEquals(2, count($messages)); + + $this->assertCount( + 2, + $messages + ); } } diff --git a/tests/unit/Validation/Validator/PasswordStrengthTest.php b/tests/unit/Validation/Validator/PasswordStrengthTest.php index 3e5be2f44..a7e191274 100644 --- a/tests/unit/Validation/Validator/PasswordStrengthTest.php +++ b/tests/unit/Validation/Validator/PasswordStrengthTest.php @@ -34,7 +34,13 @@ public function testValidateWeakOnDefaultScore() ->willReturn('Weak1'); $validator = new PasswordStrength(); - $this->assertTrue($validator->validate($validation, 'password')); + + $this->assertTrue( + $validator->validate( + $validation, + 'password' + ) + ); } public function testValidateVeryWeakOnDefaultScore() @@ -50,7 +56,13 @@ public function testValidateVeryWeakOnDefaultScore() ->willReturn(true); $validator = new PasswordStrength(); - $this->assertFalse($validator->validate($validation, 'password')); + + $this->assertFalse( + $validator->validate( + $validation, + 'password' + ) + ); } public function testValidateMediumOnScore3() @@ -61,8 +73,18 @@ public function testValidateMediumOnScore3() ->method('getValue') ->willReturn('Medium99'); - $validator = new PasswordStrength(['minScore' => 3]); - $this->assertTrue($validator->validate($validation, 'password')); + $validator = new PasswordStrength( + [ + 'minScore' => 3, + ] + ); + + $this->assertTrue( + $validator->validate( + $validation, + 'password' + ) + ); } public function testValidateWeakOnScore3() @@ -77,8 +99,18 @@ public function testValidateWeakOnScore3() ->method('appendMessage') ->willReturn(true); - $validator = new PasswordStrength(['minScore' => 3]); - $this->assertFalse($validator->validate($validation, 'password')); + $validator = new PasswordStrength( + [ + 'minScore' => 3, + ] + ); + + $this->assertFalse( + $validator->validate( + $validation, + 'password' + ) + ); } public function testValidateAllowEmpty() @@ -89,8 +121,18 @@ public function testValidateAllowEmpty() ->method('getValue') ->willReturn(''); - $validator = new PasswordStrength(['allowEmpty' => true]); - $this->assertTrue($validator->validate($validation, 'password')); + $validator = new PasswordStrength( + [ + 'allowEmpty' => true, + ] + ); + + $this->assertTrue( + $validator->validate( + $validation, + 'password' + ) + ); } public function testValidateNotAllowEmpty() @@ -105,8 +147,18 @@ public function testValidateNotAllowEmpty() ->method('appendMessage') ->willReturn(true); - $validator = new PasswordStrength(['allowEmpty' => false]); - $this->assertFalse($validator->validate($validation, 'password')); + $validator = new PasswordStrength( + [ + 'allowEmpty' => false, + ] + ); + + $this->assertFalse( + $validator->validate( + $validation, + 'password' + ) + ); } public function testValidateInvalidValue() @@ -122,7 +174,13 @@ public function testValidateInvalidValue() ->willReturn(true); $validator = new PasswordStrength(); - $this->assertFalse($validator->validate($validation, 'password')); + + $this->assertFalse( + $validator->validate( + $validation, + 'password' + ) + ); } public function testValidateMediumOnScore4() @@ -137,8 +195,18 @@ public function testValidateMediumOnScore4() ->method('appendMessage') ->willReturn(true); - $validator = new PasswordStrength(['minScore' => 4]); - $this->assertFalse($validator->validate($validation, 'password')); + $validator = new PasswordStrength( + [ + 'minScore' => 4, + ] + ); + + $this->assertFalse( + $validator->validate( + $validation, + 'password' + ) + ); } public function testValidateStrongOnScore4() @@ -149,8 +217,18 @@ public function testValidateStrongOnScore4() ->method('getValue') ->willReturn('Strong-9'); - $validator = new PasswordStrength(['minScore' => 4]); - $this->assertTrue($validator->validate($validation, 'password')); + $validator = new PasswordStrength( + [ + 'minScore' => 4, + ] + ); + + $this->assertTrue( + $validator->validate( + $validation, + 'password' + ) + ); } protected function getValidationMock() diff --git a/tests/unit5x/Validation/Validator/MongoIdTest.php b/tests/unit5x/Validation/Validator/MongoIdTest.php index 2fac435e5..12b9b9f47 100644 --- a/tests/unit5x/Validation/Validator/MongoIdTest.php +++ b/tests/unit5x/Validation/Validator/MongoIdTest.php @@ -80,43 +80,99 @@ protected function _after() public function testInvalidMongoIdValue() { + $array = [ + 'id' => 123, + ]; + + $this->validation->add( + 'id', + $this->testable + ); - $array = ['id' => 123]; - $this->validation->add('id', $this->testable); $messages = $this->validation->validate($array); - $this->assertEquals(1, count($messages)); - $this->assertEquals('MongoId is not valid', $messages[0]->getMessage()); - $this->assertEquals('MongoId', $messages[0]->getType()); + $this->assertCount( + 1, + $messages + ); + + $this->assertEquals( + 'MongoId is not valid', + $messages[0]->getMessage() + ); + + $this->assertEquals( + 'MongoId', + $messages[0]->getType() + ); } public function testValidMongoIdValue() { - $array = ['id' => '561824e063e702bc1900002a']; - $this->validation->add('id', $this->testable); + $array = [ + 'id' => '561824e063e702bc1900002a', + ]; + + $this->validation->add( + 'id', + $this->testable + ); + $messages = $this->validation->validate($array); - $this->assertEquals(0, count($messages)); + $this->assertCount( + 0, + $messages + ); } public function testEmptyMongoIdValue() { - $array = ['id' => '']; - $this->validation->add('id', $this->testable); + $array = [ + 'id' => '', + ]; + + $this->validation->add( + 'id', + $this->testable + ); + $messages = $this->validation->validate($array); - $this->assertEquals(1, count($messages)); - $this->assertEquals('MongoId is not valid', $messages[0]->getMessage()); - $this->assertEquals('MongoId', $messages[0]->getType()); + $this->assertCount( + 1, + $messages + ); + + $this->assertEquals( + 'MongoId is not valid', + $messages[0]->getMessage() + ); + + $this->assertEquals( + 'MongoId', + $messages[0]->getType() + ); } public function testEmptyMongoIdValueWithAllowEmptyOption() { - $array = ['id' => '']; + $array = [ + 'id' => '', + ]; + $this->testable->setOption('allowEmpty', true); - $this->validation->add('id', $this->testable); + + $this->validation->add( + 'id', + $this->testable + ); + $messages = $this->validation->validate($array); - $this->assertEquals(0, count($messages)); + $this->assertCount( + 0, + $messages + ); } }