diff --git a/composer.json b/composer.json index 1fbb9fcf43..1607de5b15 100644 --- a/composer.json +++ b/composer.json @@ -1,16 +1,16 @@ { "name": "mobtitude/zendframework1", - "description": "Zend Framework 1 fork compatible with PHP 7.2 by Mobtitude", + "description": "Zend Framework 1 fork compatible with PHP 8.1 by Mobtitude", "type": "library", "keywords": [ "framework", "zf1", - "php-7.2" + "php-8.1" ], "homepage": "https://github.com/mobtitude/zendframework1", "license": "BSD-3-Clause", "require": { - "php": ">=5.2.2" + "php": "^8.1" }, "autoload": { "psr-0": { @@ -29,6 +29,7 @@ } }, "require-dev": { + "rector/rector": "^0.12.17", "phpunit/phpunit": "3.7.*", "phpunit/dbunit": "1.3.*" }, diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000000..451e0638f9 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,14 @@ +version: '3' +services: + php-qa: + image: psfoundation/code-quality + working_dir: /project + volumes: + - ./:/project + - ~/.ssh:/root/.ssh + builder: + image: psfoundation/webapp-builder:1.0.13-php8.1 + working_dir: /project + volumes: + - ./:/project + - ~/.ssh:/root/.ssh diff --git a/library/Zend/Acl.php b/library/Zend/Acl.php index a5d169f56a..8052641a71 100644 --- a/library/Zend/Acl.php +++ b/library/Zend/Acl.php @@ -223,11 +223,7 @@ public function removeRole($role) { $this->_getRoleRegistry()->remove($role); - if ($role instanceof Zend_Acl_Role_Interface) { - $roleId = $role->getRoleId(); - } else { - $roleId = $role; - } + $roleId = $role instanceof Zend_Acl_Role_Interface ? $role->getRoleId() : $role; foreach ($this->_rules['allResources']['byRoleId'] as $roleIdCurrent => $rules) { if ($roleId === $roleIdCurrent) { @@ -302,11 +298,7 @@ public function addResource($resource, $parent = null) if (null !== $parent) { try { - if ($parent instanceof Zend_Acl_Resource_Interface) { - $resourceParentId = $parent->getResourceId(); - } else { - $resourceParentId = $parent; - } + $resourceParentId = $parent instanceof Zend_Acl_Resource_Interface ? $parent->getResourceId() : $parent; $resourceParent = $this->get($resourceParentId); } catch (Zend_Acl_Exception $e) { require_once 'Zend/Acl/Exception.php'; @@ -354,11 +346,7 @@ public function add(Zend_Acl_Resource_Interface $resource, $parent = null) */ public function get($resource) { - if ($resource instanceof Zend_Acl_Resource_Interface) { - $resourceId = $resource->getResourceId(); - } else { - $resourceId = (string) $resource; - } + $resourceId = $resource instanceof Zend_Acl_Resource_Interface ? $resource->getResourceId() : (string) $resource; if (!$this->has($resource)) { require_once 'Zend/Acl/Exception.php'; @@ -378,11 +366,7 @@ public function get($resource) */ public function has($resource) { - if ($resource instanceof Zend_Acl_Resource_Interface) { - $resourceId = $resource->getResourceId(); - } else { - $resourceId = (string) $resource; - } + $resourceId = $resource instanceof Zend_Acl_Resource_Interface ? $resource->getResourceId() : (string) $resource; return isset($this->_resources[$resourceId]); } @@ -416,7 +400,7 @@ public function inherits($resource, $inherit, $onlyParent = false) $parentId = $this->_resources[$resourceId]['parent']->getResourceId(); if ($inheritId === $parentId) { return true; - } else if ($onlyParent) { + } elseif ($onlyParent) { return false; } } else { @@ -480,7 +464,7 @@ public function remove($resource) */ public function removeAll() { - foreach ($this->_resources as $resourceId => $resource) { + foreach (array_keys($this->_resources) as $resourceId) { foreach ($this->_rules['byResourceId'] as $resourceIdCurrent => $rules) { if ($resourceId === $resourceIdCurrent) { unset($this->_rules['byResourceId'][$resourceIdCurrent]); @@ -617,17 +601,13 @@ public function setRule($operation, $type, $roles = null, $resources = null, $pr // ensure that all specified Roles exist; normalize input to array of Role objects or null if (!is_array($roles)) { $roles = array($roles); - } else if (0 === count($roles)) { + } elseif ([] === $roles) { $roles = array(null); } $rolesTemp = $roles; $roles = array(); foreach ($rolesTemp as $role) { - if (null !== $role) { - $roles[] = $this->_getRoleRegistry()->get($role); - } else { - $roles[] = null; - } + $roles[] = null !== $role ? $this->_getRoleRegistry()->get($role) : null; } unset($rolesTemp); @@ -635,17 +615,13 @@ public function setRule($operation, $type, $roles = null, $resources = null, $pr if ($resources !== null) { if (!is_array($resources)) { $resources = array($resources); - } else if (0 === count($resources)) { + } elseif ([] === $resources) { $resources = array(null); } $resourcesTemp = $resources; $resources = array(); foreach ($resourcesTemp as $resource) { - if (null !== $resource) { - $resources[] = $this->get($resource); - } else { - $resources[] = null; - } + $resources[] = null !== $resource ? $this->get($resource) : null; } unset($resourcesTemp, $resource); } else { @@ -659,7 +635,7 @@ public function setRule($operation, $type, $roles = null, $resources = null, $pr // normalize privileges to array if (null === $privileges) { $privileges = array(); - } else if (!is_array($privileges)) { + } elseif (!is_array($privileges)) { $privileges = array($privileges); } @@ -672,7 +648,7 @@ public function setRule($operation, $type, $roles = null, $resources = null, $pr foreach ($resources as $resource) { foreach ($roles as $role) { $rules =& $this->_getRules($resource, $role, true); - if (0 === count($privileges)) { + if ([] === $privileges) { $rules['allPrivileges']['type'] = $type; $rules['allPrivileges']['assert'] = $assert; if (!isset($rules['byPrivilegeId'])) { @@ -690,7 +666,7 @@ public function setRule($operation, $type, $roles = null, $resources = null, $pr // this block will apply to all resources in a global rule foreach ($roles as $role) { $rules =& $this->_getRules(null, $role, true); - if (0 === count($privileges)) { + if ([] === $privileges) { $rules['allPrivileges']['type'] = $type; $rules['allPrivileges']['assert'] = $assert; } else { @@ -713,7 +689,7 @@ public function setRule($operation, $type, $roles = null, $resources = null, $pr if (null === $rules) { continue; } - if (0 === count($privileges)) { + if ([] === $privileges) { if (null === $resource && null === $role) { if ($type === $rules['allPrivileges']['type']) { $rules = array( @@ -756,7 +732,7 @@ public function setRule($operation, $type, $roles = null, $resources = null, $pr if (null === $rules) { continue; } - if (0 === count($privileges)) { + if ([] === $privileges) { if (null === $role) { if ($type === $rules['allPrivileges']['type']) { $rules = array( @@ -853,7 +829,7 @@ public function isAllowed($role = null, $resource = null, $privilege = null) // query on all privileges do { // depth-first search on $role if it is not 'allRoles' pseudo-parent - if (null !== $role && null !== ($result = $this->_roleDFSAllPrivileges($role, $resource, $privilege))) { + if (null !== $role && null !== ($result = $this->_roleDFSAllPrivileges($role, $resource))) { return $result; } @@ -885,7 +861,7 @@ public function isAllowed($role = null, $resource = null, $privilege = null) // look for rule on 'allRoles' pseudo-parent if (null !== ($ruleType = $this->_getRuleType($resource, null, $privilege))) { return self::TYPE_ALLOW === $ruleType; - } else if (null !== ($ruleTypeAllPrivileges = $this->_getRuleType($resource, null, null))) { + } elseif (null !== ($ruleTypeAllPrivileges = $this->_getRuleType($resource, null, null))) { return self::TYPE_ALLOW === $ruleTypeAllPrivileges; } @@ -935,10 +911,8 @@ protected function _roleDFSAllPrivileges(Zend_Acl_Role_Interface $role, Zend_Acl } while (null !== ($role = array_pop($dfs['stack']))) { - if (!isset($dfs['visited'][$role->getRoleId()])) { - if (null !== ($result = $this->_roleDFSVisitAllPrivileges($role, $resource, $dfs))) { - return $result; - } + if (!isset($dfs['visited'][$role->getRoleId()]) && null !== ($result = $this->_roleDFSVisitAllPrivileges($role, $resource, $dfs))) { + return $result; } } @@ -1023,10 +997,8 @@ protected function _roleDFSOnePrivilege(Zend_Acl_Role_Interface $role, Zend_Acl_ } while (null !== ($role = array_pop($dfs['stack']))) { - if (!isset($dfs['visited'][$role->getRoleId()])) { - if (null !== ($result = $this->_roleDFSVisitOnePrivilege($role, $resource, $privilege, $dfs))) { - return $result; - } + if (!isset($dfs['visited'][$role->getRoleId()]) && null !== ($result = $this->_roleDFSVisitOnePrivilege($role, $resource, $privilege, $dfs))) { + return $result; } } @@ -1069,7 +1041,7 @@ protected function _roleDFSVisitOnePrivilege(Zend_Acl_Role_Interface $role, Zend if (null !== ($ruleTypeOnePrivilege = $this->_getRuleType($resource, $role, $privilege))) { return self::TYPE_ALLOW === $ruleTypeOnePrivilege; - } else if (null !== ($ruleTypeAllPrivileges = $this->_getRuleType($resource, $role, null))) { + } elseif (null !== ($ruleTypeAllPrivileges = $this->_getRuleType($resource, $role, null))) { return self::TYPE_ALLOW === $ruleTypeAllPrivileges; } @@ -1117,7 +1089,7 @@ protected function _getRuleType(Zend_Acl_Resource_Interface $resource = null, Ze } else { return null; } - } else if (!isset($rules['byPrivilegeId'][$privilege])) { + } elseif (!isset($rules['byPrivilegeId'][$privilege])) { return null; } else { $rule = $rules['byPrivilegeId'][$privilege]; @@ -1136,9 +1108,9 @@ protected function _getRuleType(Zend_Acl_Resource_Interface $resource = null, Ze if (null === $rule['assert'] || $assertionValue) { return $rule['type']; - } else if (null !== $resource || null !== $role || null !== $privilege) { + } elseif (null !== $resource || null !== $role || null !== $privilege) { return null; - } else if (self::TYPE_ALLOW === $rule['type']) { + } elseif (self::TYPE_ALLOW === $rule['type']) { return self::TYPE_DENY; } else { return self::TYPE_ALLOW; diff --git a/library/Zend/Acl/Role/Registry.php b/library/Zend/Acl/Role/Registry.php index d9d57f3379..e3ec45c199 100644 --- a/library/Zend/Acl/Role/Registry.php +++ b/library/Zend/Acl/Role/Registry.php @@ -84,11 +84,7 @@ public function add(Zend_Acl_Role_Interface $role, $parents = null) require_once 'Zend/Acl/Role/Registry/Exception.php'; foreach ($parents as $parent) { try { - if ($parent instanceof Zend_Acl_Role_Interface) { - $roleParentId = $parent->getRoleId(); - } else { - $roleParentId = $parent; - } + $roleParentId = $parent instanceof Zend_Acl_Role_Interface ? $parent->getRoleId() : $parent; $roleParent = $this->get($roleParentId); } catch (Zend_Acl_Role_Registry_Exception $e) { throw new Zend_Acl_Role_Registry_Exception("Parent Role id '$roleParentId' does not exist", 0, $e); @@ -118,11 +114,7 @@ public function add(Zend_Acl_Role_Interface $role, $parents = null) */ public function get($role) { - if ($role instanceof Zend_Acl_Role_Interface) { - $roleId = $role->getRoleId(); - } else { - $roleId = (string) $role; - } + $roleId = $role instanceof Zend_Acl_Role_Interface ? $role->getRoleId() : (string) $role; if (!$this->has($role)) { /** @@ -145,11 +137,7 @@ public function get($role) */ public function has($role) { - if ($role instanceof Zend_Acl_Role_Interface) { - $roleId = $role->getRoleId(); - } else { - $roleId = (string) $role; - } + $roleId = $role instanceof Zend_Acl_Role_Interface ? $role->getRoleId() : (string) $role; return isset($this->_roles[$roleId]); } diff --git a/library/Zend/Amf/Parse/Amf0/Deserializer.php b/library/Zend/Amf/Parse/Amf0/Deserializer.php index 6d8fa7f55d..a8e5090e02 100644 --- a/library/Zend/Amf/Parse/Amf0/Deserializer.php +++ b/library/Zend/Amf/Parse/Amf0/Deserializer.php @@ -238,8 +238,7 @@ public function readDate() $offset = $this->_stream->readInt(); require_once 'Zend/Date.php'; - $date = new Zend_Date($timestamp); - return $date; + return new Zend_Date($timestamp); } /** @@ -272,7 +271,7 @@ public function readTypedObject() $returnObject = new $loader(); $properties = get_object_vars($this->readObject()); foreach($properties as $key=>$value) { - if($key) { + if($key !== '' && $key !== '0') { $returnObject->$key = $value; } } diff --git a/library/Zend/Amf/Parse/Amf0/Serializer.php b/library/Zend/Amf/Parse/Amf0/Serializer.php index 0a578c1291..e5e6fb3fd2 100644 --- a/library/Zend/Amf/Parse/Amf0/Serializer.php +++ b/library/Zend/Amf/Parse/Amf0/Serializer.php @@ -157,14 +157,14 @@ public function writeTypeMarker(&$data, $markerType = null, $dataByVal = false) $i = 0; foreach (array_keys($data) as $key) { // check if it contains non-integer keys - if (!is_numeric($key) || intval($key) != $key) { + if (!is_numeric($key) || (int) $key != $key) { $markerType = Zend_Amf_Constants::AMF0_OBJECT; break; // check if it is a sparse indexed array - } else if ($key != $i) { - $markerType = Zend_Amf_Constants::AMF0_MIXEDARRAY; - break; - } + } elseif ($key != $i) { + $markerType = Zend_Amf_Constants::AMF0_MIXEDARRAY; + break; + } $i++; } // Dealing with a standard numeric array @@ -337,7 +337,7 @@ protected function getClassName($object) $className = Zend_Amf_Parse_TypeLoader::getMappedClassName(get_class($object)); break; // Check to see if the user has defined an explicit Action Script type. - case isset($object->_explicitType): + case property_exists($object, '_explicitType') && $object->_explicitType !== null: $className = $object->_explicitType; break; // Check if user has defined a method for accessing the Action Script type diff --git a/library/Zend/Amf/Parse/Amf3/Deserializer.php b/library/Zend/Amf/Parse/Amf3/Deserializer.php index 9bcc272af3..20d9e74056 100644 --- a/library/Zend/Amf/Parse/Amf3/Deserializer.php +++ b/library/Zend/Amf/Parse/Amf3/Deserializer.php @@ -183,7 +183,7 @@ public function readString() //Check if this is a reference string if (($stringReference & 0x01) == 0) { // reference string - $stringReference = $stringReference >> 1; + $stringReference >>= 1; if ($stringReference >= count($this->_referenceStrings)) { require_once 'Zend/Amf/Exception.php'; throw new Zend_Amf_Exception('Undefined string reference: ' . $stringReference); @@ -193,7 +193,7 @@ public function readString() } $length = $stringReference >> 1; - if ($length) { + if ($length !== 0) { $string = $this->_stream->readBytes($length); $this->_referenceStrings[] = $string; } else { @@ -217,7 +217,7 @@ public function readDate() { $dateReference = $this->readInteger(); if (($dateReference & 0x01) == 0) { - $dateReference = $dateReference >> 1; + $dateReference >>= 1; if ($dateReference>=count($this->_referenceObjects)) { require_once 'Zend/Amf/Exception.php'; throw new Zend_Amf_Exception('Undefined date reference: ' . $dateReference); @@ -244,7 +244,7 @@ public function readArray() { $arrayReference = $this->readInteger(); if (($arrayReference & 0x01)==0){ - $arrayReference = $arrayReference >> 1; + $arrayReference >>= 1; if ($arrayReference>=count($this->_referenceObjects)) { require_once 'Zend/Amf/Exception.php'; throw new Zend_Amf_Exception('Unknow array reference: ' . $arrayReference); @@ -263,7 +263,7 @@ public function readArray() $key = $this->readString(); } - $arrayReference = $arrayReference >>1; + $arrayReference >>= 1; //We have a dense array for ($i=0; $i < $arrayReference; $i++) { @@ -283,7 +283,7 @@ public function readObject() { $traitsInfo = $this->readInteger(); $storedObject = ($traitsInfo & 0x01)==0; - $traitsInfo = $traitsInfo >> 1; + $traitsInfo >>= 1; // Check if the Object is in the stored Objects reference table if ($storedObject) { @@ -296,7 +296,7 @@ public function readObject() } else { // Check if the Object is in the stored Definitions reference table $storedClass = ($traitsInfo & 0x01) == 0; - $traitsInfo = $traitsInfo >> 1; + $traitsInfo >>= 1; if ($storedClass) { $ref = $traitsInfo; if (!isset($this->_referenceDefinitions[$ref])) { @@ -313,23 +313,19 @@ public function readObject() $className = $this->readString(); $encoding = $traitsInfo & 0x03; $propertyNames = array(); - $traitsInfo = $traitsInfo >> 2; + $traitsInfo >>= 2; } // We now have the object traits defined in variables. Time to go to work: if (!$className) { // No class name generic object $returnObject = new stdClass(); + } elseif ($loader = Zend_Amf_Parse_TypeLoader::loadType($className)) { + $returnObject = new $loader(); } else { - // Defined object - // Typed object lookup against registered classname maps - if ($loader = Zend_Amf_Parse_TypeLoader::loadType($className)) { - $returnObject = new $loader(); - } else { - //user defined typed object - require_once 'Zend/Amf/Exception.php'; - throw new Zend_Amf_Exception('Typed object not found: '. $className . ' '); - } + //user defined typed object + require_once 'Zend/Amf/Exception.php'; + throw new Zend_Amf_Exception('Typed object not found: '. $className . ' '); } // Add the Object to the reference table @@ -365,7 +361,7 @@ public function readObject() $propertyNames[] = $property; $properties[$property] = $this->readTypeMarker(); } - } while ($property !=""); + } while ($property != ""); break; default: // basic property list object. @@ -399,7 +395,7 @@ public function readObject() } if ($returnObject instanceof Zend_Amf_Value_Messaging_ArrayCollection) { - if (isset($returnObject->externalizedData)) { + if (property_exists($returnObject, 'externalizedData') && $returnObject->externalizedData !== null) { $returnObject = $returnObject->externalizedData; } else { $returnObject = get_object_vars($returnObject); diff --git a/library/Zend/Amf/Parse/Amf3/Serializer.php b/library/Zend/Amf/Parse/Amf3/Serializer.php index 3ce47b7f7c..ada3cc7692 100644 --- a/library/Zend/Amf/Parse/Amf3/Serializer.php +++ b/library/Zend/Amf/Parse/Amf3/Serializer.php @@ -132,11 +132,7 @@ public function writeTypeMarker(&$data, $markerType = null, $dataByVal = false) $markerType = Zend_Amf_Constants::AMF3_NULL; break; case (is_bool($data)): - if ($data){ - $markerType = Zend_Amf_Constants::AMF3_BOOLEAN_TRUE; - } else { - $markerType = Zend_Amf_Constants::AMF3_BOOLEAN_FALSE; - } + $markerType = $data ? Zend_Amf_Constants::AMF3_BOOLEAN_TRUE : Zend_Amf_Constants::AMF3_BOOLEAN_FALSE; break; case (is_int($data)): if (($data > 0xFFFFFFF) || ($data < -268435456)) { @@ -158,9 +154,9 @@ public function writeTypeMarker(&$data, $markerType = null, $dataByVal = false) // Handle object types. if (($data instanceof DateTime) || ($data instanceof Zend_Date)) { $markerType = Zend_Amf_Constants::AMF3_DATE; - } else if ($data instanceof Zend_Amf_Value_ByteArray) { + } elseif ($data instanceof Zend_Amf_Value_ByteArray) { $markerType = Zend_Amf_Constants::AMF3_BYTEARRAY; - } else if (($data instanceof DOMDocument) || ($data instanceof SimpleXMLElement)) { + } elseif (($data instanceof DOMDocument) || ($data instanceof SimpleXMLElement)) { $markerType = Zend_Amf_Constants::AMF3_XMLSTRING; } else { $markerType = Zend_Amf_Constants::AMF3_OBJECT; @@ -231,7 +227,7 @@ protected function writeBinaryString(&$string){ public function writeString(&$string) { $len = $this->_mbStringFunctionsOverloaded ? mb_strlen($string, '8bit') : strlen($string); - if(!$len){ + if($len === 0){ $this->writeInteger(0x01); return $this; } @@ -264,7 +260,7 @@ public function writeByteArray(&$data) if (is_string($data)) { //nothing to do - } else if ($data instanceof Zend_Amf_Value_ByteArray) { + } elseif ($data instanceof Zend_Amf_Value_ByteArray) { $data = $data->getData(); } else { require_once 'Zend/Amf/Exception.php'; @@ -288,11 +284,11 @@ public function writeXml($xml) return $this; } - if(is_string($xml)) { + if (is_string($xml)) { //nothing to do - } else if ($xml instanceof DOMDocument) { + } elseif ($xml instanceof DOMDocument) { $xml = $xml->saveXml(); - } else if ($xml instanceof SimpleXMLElement) { + } elseif ($xml instanceof SimpleXMLElement) { $xml = $xml->asXML(); } else { require_once 'Zend/Amf/Exception.php'; @@ -424,7 +420,7 @@ public function writeObject($object) break; // Check to see if the user has defined an explicit Action Script type. - case isset($object->_explicitType): + case property_exists($object, '_explicitType') && $object->_explicitType !== null: $className = $object->_explicitType; break; diff --git a/library/Zend/Amf/Parse/TypeLoader.php b/library/Zend/Amf/Parse/TypeLoader.php index 40003b5779..e550884b13 100644 --- a/library/Zend/Amf/Parse/TypeLoader.php +++ b/library/Zend/Amf/Parse/TypeLoader.php @@ -94,7 +94,7 @@ final class Zend_Amf_Parse_TypeLoader public static function loadType($className) { $class = self::getMappedClassName($className); - if(!$class) { + if($class === '' || $class === '0') { $class = str_replace('.', '_', $className); } if (!class_exists($class)) { @@ -206,7 +206,7 @@ public static function handleResource($resource) try { while(is_resource($resource)) { $resclass = self::getResourceParser($resource); - if(!$resclass) { + if($resclass === '' || $resclass === '0') { require_once 'Zend/Amf/Exception.php'; throw new Zend_Amf_Exception('Can not serialize resource type: '. get_resource_type($resource)); } diff --git a/library/Zend/Amf/Request.php b/library/Zend/Amf/Request.php index c5da936ef0..6fcbae9b24 100644 --- a/library/Zend/Amf/Request.php +++ b/library/Zend/Amf/Request.php @@ -153,9 +153,7 @@ public function readHeader() require_once 'Zend/Amf/Exception.php'; throw new Zend_Amf_Exception('Unable to parse ' . $name . ' header data: ' . $e->getMessage() . ' '. $e->getLine(), 0, $e); } - - $header = new Zend_Amf_Value_MessageHeader($name, $mustRead, $data, $length); - return $header; + return new Zend_Amf_Value_MessageHeader($name, $mustRead, $data, $length); } /** @@ -190,9 +188,7 @@ public function readBody() // set the encoding so we return our message in AMF3 $this->_objectEncoding = Zend_Amf_Constants::AMF3_OBJECT_ENCODING; } - - $body = new Zend_Amf_Value_MessageBody($targetURI, $responseURI, $data); - return $body; + return new Zend_Amf_Value_MessageBody($targetURI, $responseURI, $data); } /** diff --git a/library/Zend/Amf/Response/Http.php b/library/Zend/Amf/Response/Http.php index e4a52937e5..b022f0d7eb 100644 --- a/library/Zend/Amf/Response/Http.php +++ b/library/Zend/Amf/Response/Http.php @@ -63,11 +63,7 @@ protected function isIeOverSsl() } $ua = $_SERVER['HTTP_USER_AGENT']; - if (!preg_match('/; MSIE \d+\.\d+;/', (string) $ua)) { - // Not MicroSoft Internet Explorer - return false; - } - - return true; + // Not MicroSoft Internet Explorer + return (bool) preg_match('/; MSIE \d+\.\d+;/', (string) $ua); } } diff --git a/library/Zend/Amf/Server.php b/library/Zend/Amf/Server.php index 68bca7899e..be0d049f5d 100644 --- a/library/Zend/Amf/Server.php +++ b/library/Zend/Amf/Server.php @@ -258,15 +258,13 @@ protected function _checkAcl($object, $function) } $auth = Zend_Auth::getInstance(); - if($auth->hasIdentity()) { + if ($auth->hasIdentity()) { $role = $auth->getIdentity()->role; + } elseif ($this->_acl->hasRole(Zend_Amf_Constants::GUEST_ROLE)) { + $role = Zend_Amf_Constants::GUEST_ROLE; } else { - if($this->_acl->hasRole(Zend_Amf_Constants::GUEST_ROLE)) { - $role = Zend_Amf_Constants::GUEST_ROLE; - } else { - require_once 'Zend/Amf/Server/Exception.php'; - throw new Zend_Amf_Server_Exception("Unauthenticated access not allowed"); - } + require_once 'Zend/Amf/Server/Exception.php'; + throw new Zend_Amf_Server_Exception("Unauthenticated access not allowed"); } if($this->_acl->isAllowed($role, $class, $function)) { return true; @@ -301,10 +299,8 @@ protected function getLoader() */ protected function _dispatch($method, $params = null, $source = null) { - if($source) { - if(($mapped = Zend_Amf_Parse_TypeLoader::getMappedClassName($source)) !== false) { - $source = $mapped; - } + if($source && ($mapped = Zend_Amf_Parse_TypeLoader::getMappedClassName($source)) !== false) { + $source = $mapped; } $qualifiedName = empty($source) ? $method : $source . '.' . $method; @@ -477,7 +473,7 @@ protected function _handleAuth( $userid, $password) // authentication failed, good bye require_once 'Zend/Amf/Server/Exception.php'; throw new Zend_Amf_Server_Exception( - "Authentication failed: " . join("\n", + "Authentication failed: " . implode("\n", $result->getMessages()), $result->getCode()); } @@ -507,8 +503,8 @@ protected function _handle(Zend_Amf_Request $request) $error = false; $headers = $request->getAmfHeaders(); if (isset($headers[Zend_Amf_Constants::CREDENTIALS_HEADER]) - && isset($headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->userid) - && isset($headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->password) + && (property_exists($headers[Zend_Amf_Constants::CREDENTIALS_HEADER], 'userid') && $headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->userid !== null) + && (property_exists($headers[Zend_Amf_Constants::CREDENTIALS_HEADER], 'password') && $headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->password !== null) ) { try { if ($this->_handleAuth( @@ -561,7 +557,7 @@ protected function _handle(Zend_Amf_Request $request) // Split the target string into its values. $source = substr($targetURI, 0, strrpos($targetURI, '.')); - if ($source) { + if ($source !== '' && $source !== '0') { // Break off method name from namespace into source $method = substr(strrchr($targetURI, '.'), 1); $return = $this->_dispatch($method, $body->getData(), $source); @@ -588,7 +584,7 @@ protected function _handle(Zend_Amf_Request $request) // Split the target string into its values. $source = substr($targetURI, 0, strrpos($targetURI, '.')); - if ($source) { + if ($source !== '' && $source !== '0') { // Break off method name from namespace into source $method = substr(strrchr($targetURI, '.'), 1); $return = $this->_dispatch($method, $body->getData(), $source); @@ -614,12 +610,8 @@ protected function _handle(Zend_Amf_Request $request) if($this->isSession()) { $currentID = session_id(); $joint = "?"; - if(isset($_SERVER['QUERY_STRING'])) { - if(!strpos($_SERVER['QUERY_STRING'], $currentID) !== FALSE) { - if(strrpos($_SERVER['QUERY_STRING'], "?") !== FALSE) { - $joint = "&"; - } - } + if(isset($_SERVER['QUERY_STRING']) && !strpos($_SERVER['QUERY_STRING'], $currentID) && strrpos($_SERVER['QUERY_STRING'], "?") !== FALSE) { + $joint = "&"; } // create a new AMF message header with the session id as a variable. @@ -641,16 +633,14 @@ protected function _handle(Zend_Amf_Request $request) public function handle($request = null) { // Check if request was passed otherwise get it from the server - if ($request === null || !$request instanceof Zend_Amf_Request) { + if (!$request instanceof \Zend_Amf_Request || !$request instanceof Zend_Amf_Request) { $request = $this->getRequest(); } else { $this->setRequest($request); } - if ($this->isSession()) { - // Check if a session is being sent from the amf call - if (isset($_COOKIE[$this->_sessionName])) { - session_id($_COOKIE[$this->_sessionName]); - } + // Check if a session is being sent from the amf call + if ($this->isSession() && isset($_COOKIE[$this->_sessionName])) { + session_id($_COOKIE[$this->_sessionName]); } // Check for errors that may have happend in deserialization of Request. diff --git a/library/Zend/Amf/Value/MessageBody.php b/library/Zend/Amf/Value/MessageBody.php index 59cacba52b..b8bc05672f 100644 --- a/library/Zend/Amf/Value/MessageBody.php +++ b/library/Zend/Amf/Value/MessageBody.php @@ -176,7 +176,7 @@ public function setReplyMethod($methodName) if (!preg_match('#^[/?]#', $methodName)) { $this->_targetUri = rtrim($this->_targetUri, '/') . '/'; } - $this->_targetUri = $this->_targetUri . $methodName; + $this->_targetUri .= $methodName; return $this; } } diff --git a/library/Zend/Application.php b/library/Zend/Application.php index 5ddee7ddaa..1f4498d531 100644 --- a/library/Zend/Application.php +++ b/library/Zend/Application.php @@ -89,8 +89,7 @@ public function __construct($environment, $options = null, $suppressNotFoundWarn $options = $options->toArray(); } elseif (!is_array($options)) { throw new Zend_Application_Exception( - 'Invalid options provided; must be location of config file,' - . ' a config object, or an array' + 'Invalid options provided; must be location of config file, a config object, or an array' ); } @@ -166,9 +165,9 @@ public function setOptions(array $options) $autoloader = $this->getAutoloader(); if (method_exists($autoloader, 'setZfPath')) { $zfPath = $options['autoloaderzfpath']; - $zfVersion = !empty($options['autoloaderzfversion']) - ? $options['autoloaderzfversion'] - : 'latest'; + $zfVersion = empty($options['autoloaderzfversion']) + ? 'latest' + : $options['autoloaderzfversion']; $autoloader->setZfPath($zfPath, $zfVersion); } } @@ -341,8 +340,7 @@ public function setBootstrap($path, $class = null) if (!$this->_bootstrap instanceof Zend_Application_Bootstrap_Bootstrapper) { throw new Zend_Application_Exception( - 'Bootstrap class does not implement' - . ' Zend_Application_Bootstrap_Bootstrapper' + 'Bootstrap class does not implement Zend_Application_Bootstrap_Bootstrapper' ); } @@ -422,8 +420,7 @@ protected function _loadConfig($file) $config = include $file; if (!is_array($config)) { throw new Zend_Application_Exception( - 'Invalid configuration file provided; PHP file does not' - . ' return array value' + 'Invalid configuration file provided; PHP file does not return array value' ); } return $config; diff --git a/library/Zend/Application/Bootstrap/BootstrapAbstract.php b/library/Zend/Application/Bootstrap/BootstrapAbstract.php index 444fe0ca85..e15cdd414c 100644 --- a/library/Zend/Application/Bootstrap/BootstrapAbstract.php +++ b/library/Zend/Application/Bootstrap/BootstrapAbstract.php @@ -719,7 +719,7 @@ protected function _loadPluginResource($resource, $options) $options['bootstrap'] = $this; $className = $this->getPluginLoader()->load(strtolower($resource), false); - if (!$className) { + if ($className === '' || $className === '0') { return false; } @@ -727,7 +727,7 @@ protected function _loadPluginResource($resource, $options) unset($this->_pluginResources[$resource]); - if (isset($instance->_explicitType)) { + if (property_exists($instance, '_explicitType') && $instance->_explicitType !== null) { $resource = $instance->_explicitType; } $resource = strtolower($resource); @@ -764,7 +764,7 @@ protected function _markRun($resource) */ protected function _resolvePluginResourceName($resource) { - if (isset($resource->_explicitType)) { + if (property_exists($resource, '_explicitType') && $resource->_explicitType !== null) { $pluginName = $resource->_explicitType; } else { $className = get_class($resource); @@ -778,7 +778,6 @@ protected function _resolvePluginResourceName($resource) } } } - $pluginName = strtolower($pluginName); - return $pluginName; + return strtolower($pluginName); } } diff --git a/library/Zend/Application/Module/Bootstrap.php b/library/Zend/Application/Module/Bootstrap.php index 1373891cc4..f3752c6d2f 100644 --- a/library/Zend/Application/Module/Bootstrap.php +++ b/library/Zend/Application/Module/Bootstrap.php @@ -115,11 +115,7 @@ public function getModuleName() { if (empty($this->_moduleName)) { $class = get_class($this); - if (preg_match('/^([a-z][a-z0-9]*)_/i', $class, $matches)) { - $prefix = $matches[1]; - } else { - $prefix = $class; - } + $prefix = preg_match('/^([a-z][a-z0-9]*)_/i', $class, $matches) ? $matches[1] : $class; $this->_moduleName = $prefix; } return $this->_moduleName; diff --git a/library/Zend/Application/Resource/Db.php b/library/Zend/Application/Resource/Db.php index 4c7c720e5c..e4dfa90040 100644 --- a/library/Zend/Application/Resource/Db.php +++ b/library/Zend/Application/Resource/Db.php @@ -185,7 +185,7 @@ public function setDefaultMetadataCache($cache) $metadataCache = $cacheManager->getCache($cache); } } - } else if ($cache instanceof Zend_Cache_Core) { + } elseif ($cache instanceof Zend_Cache_Core) { $metadataCache = $cache; } diff --git a/library/Zend/Application/Resource/Mail.php b/library/Zend/Application/Resource/Mail.php index fc9036a81f..694261a878 100644 --- a/library/Zend/Application/Resource/Mail.php +++ b/library/Zend/Application/Resource/Mail.php @@ -133,8 +133,7 @@ protected function _setupTransport($options) case 'Zend_Mail_Transport_Smtp': if (!isset($options['host'])) { throw new Zend_Application_Resource_Exception( - 'A host is necessary for smtp transport,' - . ' but none was given' + 'A host is necessary for smtp transport, but none was given' ); } diff --git a/library/Zend/Application/Resource/Modules.php b/library/Zend/Application/Resource/Modules.php index 6106cfcad1..51e7ffb3c1 100644 --- a/library/Zend/Application/Resource/Modules.php +++ b/library/Zend/Application/Resource/Modules.php @@ -152,7 +152,6 @@ protected function _formatModuleName($name) $name = strtolower($name); $name = str_replace(array('-', '.'), ' ', $name); $name = ucwords($name); - $name = str_replace(' ', '', $name); - return $name; + return str_replace(' ', '', $name); } } diff --git a/library/Zend/Application/Resource/Multidb.php b/library/Zend/Application/Resource/Multidb.php index a7a8c30d48..dc47945c84 100644 --- a/library/Zend/Application/Resource/Multidb.php +++ b/library/Zend/Application/Resource/Multidb.php @@ -197,7 +197,7 @@ protected function _setDefaultMetadataCache($cache) $metadataCache = $cacheManager->getCache($cache); } } - } else if ($cache instanceof Zend_Cache_Core) { + } elseif ($cache instanceof Zend_Cache_Core) { $metadataCache = $cache; } diff --git a/library/Zend/Application/Resource/ResourceAbstract.php b/library/Zend/Application/Resource/ResourceAbstract.php index 1f400eb9fb..4f266bb812 100644 --- a/library/Zend/Application/Resource/ResourceAbstract.php +++ b/library/Zend/Application/Resource/ResourceAbstract.php @@ -70,7 +70,7 @@ public function __construct($options = null) { if (is_array($options)) { $this->setOptions($options); - } else if ($options instanceof Zend_Config) { + } elseif ($options instanceof Zend_Config) { $this->setOptions($options->toArray()); } } diff --git a/library/Zend/Application/Resource/Session.php b/library/Zend/Application/Resource/Session.php index 9519fc7a42..35e666737d 100644 --- a/library/Zend/Application/Resource/Session.php +++ b/library/Zend/Application/Resource/Session.php @@ -108,7 +108,7 @@ public function init() unset($options['savehandler']); } - if (count($options) > 0) { + if ($options !== []) { Zend_Session::setOptions($options); } diff --git a/library/Zend/Application/Resource/Translate.php b/library/Zend/Application/Resource/Translate.php index 5d9fc23d3c..db7648dc69 100644 --- a/library/Zend/Application/Resource/Translate.php +++ b/library/Zend/Application/Resource/Translate.php @@ -70,7 +70,7 @@ public function getTranslate() if (!isset($options['content']) && !isset($options['data'])) { require_once 'Zend/Application/Resource/Exception.php'; throw new Zend_Application_Resource_Exception('No translation source data provided.'); - } else if (array_key_exists('content', $options) && array_key_exists('data', $options)) { + } elseif (array_key_exists('content', $options) && array_key_exists('data', $options)) { require_once 'Zend/Application/Resource/Exception.php'; throw new Zend_Application_Resource_Exception( 'Conflict on translation source data: choose only one key between content and data.' @@ -86,10 +86,8 @@ public function getTranslate() unset($options['data']); } - if (isset($options['log'])) { - if (is_array($options['log'])) { - $options['log'] = Zend_Log::factory($options['log']); - } + if (isset($options['log']) && is_array($options['log'])) { + $options['log'] = Zend_Log::factory($options['log']); } if (isset($options['options'])) { diff --git a/library/Zend/Auth/Adapter/DbTable.php b/library/Zend/Auth/Adapter/DbTable.php index a7f75d23ab..483d2642d1 100644 --- a/library/Zend/Auth/Adapter/DbTable.php +++ b/library/Zend/Auth/Adapter/DbTable.php @@ -275,8 +275,8 @@ public function setCredential($credential) */ public function setAmbiguityIdentity($flag) { - if (is_integer($flag)) { - $this->_ambiguityIdentity = (1 === $flag ? true : false); + if (is_int($flag)) { + $this->_ambiguityIdentity = (1 === $flag); } elseif (is_bool($flag)) { $this->_ambiguityIdentity = $flag; } @@ -371,7 +371,7 @@ public function authenticate() return $authResult; } - if (true === $this->getAmbiguityIdentity()) { + if ($this->getAmbiguityIdentity()) { $validIdentities = array (); $zendAuthCredentialMatchColumn = $this->_zendDb->foldCase('zend_auth_credential_match'); foreach ($resultIdentities as $identity) { @@ -381,9 +381,7 @@ public function authenticate() } $resultIdentities = $validIdentities; } - - $authResult = $this->_authenticateValidateResult(array_shift($resultIdentities)); - return $authResult; + return $this->_authenticateValidateResult(array_shift($resultIdentities)); } /** @@ -507,7 +505,7 @@ protected function _authenticateValidateResultSet(array $resultIdentities) $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND; $this->_authenticateResultInfo['messages'][] = 'A record with the supplied identity could not be found.'; return $this->_authenticateCreateAuthResult(); - } elseif (count($resultIdentities) > 1 && false === $this->getAmbiguityIdentity()) { + } elseif (count($resultIdentities) > 1 && !$this->getAmbiguityIdentity()) { $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS; $this->_authenticateResultInfo['messages'][] = 'More than one record matches the supplied identity.'; return $this->_authenticateCreateAuthResult(); diff --git a/library/Zend/Auth/Adapter/Http.php b/library/Zend/Auth/Adapter/Http.php index 9ffebcad75..69cf53b435 100644 --- a/library/Zend/Auth/Adapter/Http.php +++ b/library/Zend/Auth/Adapter/Http.php @@ -234,18 +234,13 @@ public function __construct(array $config) * @see Zend_Auth_Adapter_Exception */ require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception('Config key \'nonce_timeout\' is required, and must be an ' - . 'integer'); + throw new Zend_Auth_Adapter_Exception('Config key \'nonce_timeout\' is required, and must be an integer'); } else { $this->_nonceTimeout = (int) $config['nonce_timeout']; } // We use the opaque value unless explicitly told not to - if (isset($config['use_opaque']) && false == (bool) $config['use_opaque']) { - $this->_useOpaque = false; - } else { - $this->_useOpaque = true; - } + $this->_useOpaque = isset($config['use_opaque']) && false == (bool) $config['use_opaque'] ? false : true; if (isset($config['algorithm']) && in_array($config['algorithm'], $this->_supportedAlgos)) { $this->_algo = $config['algorithm']; @@ -368,15 +363,10 @@ public function authenticate() * @see Zend_Auth_Adapter_Exception */ require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception('Request and Response objects must be set before calling ' - . 'authenticate()'); + throw new Zend_Auth_Adapter_Exception('Request and Response objects must be set before calling authenticate()'); } - if ($this->_imaProxy) { - $getHeader = 'Proxy-Authorization'; - } else { - $getHeader = 'Authorization'; - } + $getHeader = $this->_imaProxy ? 'Proxy-Authorization' : 'Authorization'; $authHeader = $this->_request->getHeader($getHeader); if (!$authHeader) { @@ -478,14 +468,12 @@ protected function _basicHeader() */ protected function _digestHeader() { - $wwwauth = 'Digest realm="' . $this->_realm . '", ' + return 'Digest realm="' . $this->_realm . '", ' . 'domain="' . $this->_domains . '", ' . 'nonce="' . $this->_calcNonce() . '", ' . ($this->_useOpaque ? 'opaque="' . $this->_calcOpaque() . '", ' : '') . 'algorithm="' . $this->_algo . '", ' . 'qop="' . implode(',', $this->_supportedQops) . '"'; - - return $wwwauth; } /** @@ -509,14 +497,13 @@ protected function _basicAuth($header) * @see Zend_Auth_Adapter_Exception */ require_once 'Zend/Auth/Adapter/Exception.php'; - throw new Zend_Auth_Adapter_Exception('A basicResolver object must be set before doing Basic ' - . 'authentication'); + throw new Zend_Auth_Adapter_Exception('A basicResolver object must be set before doing Basic authentication'); } // Decode the Authorization header $auth = substr($header, strlen('Basic ')); $auth = base64_decode($auth); - if (!$auth) { + if ($auth === '' || $auth === '0') { /** * @see Zend_Auth_Adapter_Exception */ @@ -664,9 +651,7 @@ protected function _calcNonce() // nonce will change on its own, and effectively log the user out. This // would be surprising if the user just logged in. $timeout = ceil(time() / $this->_nonceTimeout) * $this->_nonceTimeout; - - $nonce = hash('md5', $timeout . ':' . $this->_request->getServer('HTTP_USER_AGENT') . ':' . __CLASS__); - return $nonce; + return hash('md5', $timeout . ':' . $this->_request->getServer('HTTP_USER_AGENT') . ':' . __CLASS__); } /** @@ -745,7 +730,7 @@ protected function _parseDigestAuth($header) return false; } else { // Make sure the path portion of both URIs is the same - if ($rUri['path'] != $cUri['path']) { + if ($rUri['path'] !== $cUri['path']) { return false; } // Section 3.2.2.5 seems to suggest that the value of the URI diff --git a/library/Zend/Auth/Adapter/Http/Resolver/File.php b/library/Zend/Auth/Adapter/Http/Resolver/File.php index 8f8b64ce30..481b3a992f 100644 --- a/library/Zend/Auth/Adapter/Http/Resolver/File.php +++ b/library/Zend/Auth/Adapter/Http/Resolver/File.php @@ -117,13 +117,12 @@ public function resolve($username, $realm) */ require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php'; throw new Zend_Auth_Adapter_Http_Resolver_Exception('Username is required'); - } else if (!ctype_print($username) || strpos($username, ':') !== false) { + } elseif (!ctype_print($username) || strpos($username, ':') !== false) { /** * @see Zend_Auth_Adapter_Http_Resolver_Exception */ require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php'; - throw new Zend_Auth_Adapter_Http_Resolver_Exception('Username must consist only of printable characters, ' - . 'excluding the colon'); + throw new Zend_Auth_Adapter_Http_Resolver_Exception('Username must consist only of printable characters, excluding the colon'); } if (empty($realm)) { /** @@ -131,13 +130,12 @@ public function resolve($username, $realm) */ require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php'; throw new Zend_Auth_Adapter_Http_Resolver_Exception('Realm is required'); - } else if (!ctype_print($realm) || strpos($realm, ':') !== false) { + } elseif (!ctype_print($realm) || strpos($realm, ':') !== false) { /** * @see Zend_Auth_Adapter_Http_Resolver_Exception */ require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php'; - throw new Zend_Auth_Adapter_Http_Resolver_Exception('Realm must consist only of printable characters, ' - . 'excluding the colon.'); + throw new Zend_Auth_Adapter_Http_Resolver_Exception('Realm must consist only of printable characters, excluding the colon.'); } // Open file, read through looking for matching credentials diff --git a/library/Zend/Auth/Adapter/Ldap.php b/library/Zend/Auth/Adapter/Ldap.php index 1e8ea055ae..c914c4c172 100644 --- a/library/Zend/Auth/Adapter/Ldap.php +++ b/library/Zend/Auth/Adapter/Ldap.php @@ -255,12 +255,12 @@ public function authenticate() $username = $this->_username; $password = $this->_password; - if (!$username) { + if ($username === '' || $username === '0') { $code = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND; $messages[0] = 'A username is required'; return new Zend_Auth_Result($code, '', $messages); } - if (!$password) { + if ($password === '' || $password === '0') { /* A password is required because some servers will * treat an empty password as an anonymous bind. */ @@ -333,7 +333,7 @@ public function authenticate() $messages[0] = ''; $messages[1] = ''; $messages[] = "$canonicalName authentication successful"; - if ($requireRebind === true) { + if ($requireRebind) { // rebinding with authenticated user $ldap->bind($dn, $password); } @@ -353,21 +353,21 @@ public function authenticate() $err = $zle->getCode(); if ($err == Zend_Ldap_Exception::LDAP_X_DOMAIN_MISMATCH) { - /* This error indicates that the domain supplied in the - * username did not match the domains in the server options - * and therefore we should just skip to the next set of - * server options. - */ - continue; - } else if ($err == Zend_Ldap_Exception::LDAP_NO_SUCH_OBJECT) { - $code = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND; - $messages[0] = "Account not found: $username"; - $failedAuthorities[$dname] = $zle->getMessage(); - } else if ($err == Zend_Ldap_Exception::LDAP_INVALID_CREDENTIALS) { - $code = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID; - $messages[0] = 'Invalid credentials'; - $failedAuthorities[$dname] = $zle->getMessage(); - } else { + /* This error indicates that the domain supplied in the + * username did not match the domains in the server options + * and therefore we should just skip to the next set of + * server options. + */ + continue; + } elseif ($err == Zend_Ldap_Exception::LDAP_NO_SUCH_OBJECT) { + $code = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND; + $messages[0] = "Account not found: $username"; + $failedAuthorities[$dname] = $zle->getMessage(); + } elseif ($err == Zend_Ldap_Exception::LDAP_INVALID_CREDENTIALS) { + $code = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID; + $messages[0] = 'Invalid credentials'; + $failedAuthorities[$dname] = $zle->getMessage(); + } else { $line = $zle->getLine(); $messages[] = $zle->getFile() . "($line): " . $zle->getMessage(); $messages[] = preg_replace( @@ -446,11 +446,7 @@ protected function _checkGroupMembership(Zend_Ldap $ldap, $canonicalName, $dn, a return true; } - if ($adapterOptions['memberIsDn'] === false) { - $user = $canonicalName; - } else { - $user = $dn; - } + $user = $adapterOptions['memberIsDn'] === false ? $canonicalName : $dn; /** * @see Zend_Ldap_Filter @@ -485,7 +481,7 @@ protected function _checkGroupMembership(Zend_Ldap $ldap, $canonicalName, $dn, a */ public function getAccountObject(array $returnAttribs = array(), array $omitAttribs = array()) { - if (!$this->_authenticatedDn) { + if ($this->_authenticatedDn === '' || $this->_authenticatedDn === '0') { return false; } @@ -522,7 +518,7 @@ private function _optionsToString(array $options) foreach ($options as $key => $val) { if ($key === 'password') $val = '*****'; - if ($str) + if ($str !== '' && $str !== '0') $str .= ','; $str .= $key . '=' . $val; } diff --git a/library/Zend/Auth/Adapter/OpenId.php b/library/Zend/Auth/Adapter/OpenId.php index 9b886bba05..cf6f4733c3 100644 --- a/library/Zend/Auth/Adapter/OpenId.php +++ b/library/Zend/Auth/Adapter/OpenId.php @@ -246,17 +246,15 @@ public function authenticate() { $id, array("Authentication failed", $consumer->getError())); } - } else { - if (!$consumer->check($id, - $this->_returnTo, - $this->_root, - $this->_extensions, - $this->_response)) { - return new Zend_Auth_Result( - Zend_Auth_Result::FAILURE, - $id, - array("Authentication failed", $consumer->getError())); - } + } elseif (!$consumer->check($id, + $this->_returnTo, + $this->_root, + $this->_extensions, + $this->_response)) { + return new Zend_Auth_Result( + Zend_Auth_Result::FAILURE, + $id, + array("Authentication failed", $consumer->getError())); } } else { $params = (isset($_SERVER['REQUEST_METHOD']) && diff --git a/library/Zend/Auth/Result.php b/library/Zend/Auth/Result.php index 6f81a9a9e1..28e596edd9 100644 --- a/library/Zend/Auth/Result.php +++ b/library/Zend/Auth/Result.php @@ -110,7 +110,7 @@ public function __construct($code, $identity, array $messages = array()) */ public function isValid() { - return ($this->_code > 0) ? true : false; + return $this->_code > 0; } /** diff --git a/library/Zend/Auth/Storage/Session.php b/library/Zend/Auth/Storage/Session.php index c3680f6faf..9abde003f4 100644 --- a/library/Zend/Auth/Storage/Session.php +++ b/library/Zend/Auth/Storage/Session.php @@ -113,7 +113,7 @@ public function getMember() */ public function isEmpty() { - return !isset($this->_session->{$this->_member}); + return !(property_exists($this->_session, '_member') && $this->_session->{$this->_member} !== null); } /** diff --git a/library/Zend/Barcode.php b/library/Zend/Barcode.php index 6f7c386bc9..8f924afb77 100644 --- a/library/Zend/Barcode.php +++ b/library/Zend/Barcode.php @@ -66,20 +66,16 @@ public static function factory( * barcode name and separate config object. */ if ($barcode instanceof Zend_Config) { - if (isset($barcode->rendererParams)) { + if (property_exists($barcode, 'rendererParams') && $barcode->rendererParams !== null) { $rendererConfig = $barcode->rendererParams->toArray(); } - if (isset($barcode->renderer)) { + if (property_exists($barcode, 'renderer') && $barcode->renderer !== null) { $renderer = (string) $barcode->renderer; } - if (isset($barcode->barcodeParams)) { + if (property_exists($barcode, 'barcodeParams') && $barcode->barcodeParams !== null) { $barcodeConfig = $barcode->barcodeParams->toArray(); } - if (isset($barcode->barcode)) { - $barcode = (string) $barcode->barcode; - } else { - $barcode = null; - } + $barcode = property_exists($barcode, 'barcode') && $barcode->barcode !== null ? (string) $barcode->barcode : null; } try { @@ -119,14 +115,10 @@ public static function makeBarcode($barcode, $barcodeConfig = array()) * barcode name and separate config object. */ if ($barcode instanceof Zend_Config) { - if (isset($barcode->barcodeParams) && $barcode->barcodeParams instanceof Zend_Config) { + if (property_exists($barcode, 'barcodeParams') && $barcode->barcodeParams !== null && $barcode->barcodeParams instanceof Zend_Config) { $barcodeConfig = $barcode->barcodeParams->toArray(); } - if (isset($barcode->barcode)) { - $barcode = (string) $barcode->barcode; - } else { - $barcode = null; - } + $barcode = property_exists($barcode, 'barcode') && $barcode->barcode !== null ? (string) $barcode->barcode : null; } if ($barcodeConfig instanceof Zend_Config) { $barcodeConfig = $barcodeConfig->toArray(); @@ -218,10 +210,10 @@ public static function makeRenderer($renderer = 'image', $rendererConfig = array * barcode name and separate config object. */ if ($renderer instanceof Zend_Config) { - if (isset($renderer->rendererParams)) { + if (property_exists($renderer, 'rendererParams') && $renderer->rendererParams !== null) { $rendererConfig = $renderer->rendererParams->toArray(); } - if (isset($renderer->renderer)) { + if (property_exists($renderer, 'renderer') && $renderer->renderer !== null) { $renderer = (string) $renderer->renderer; } } diff --git a/library/Zend/Barcode/Object/Code128.php b/library/Zend/Barcode/Object/Code128.php index 6292296ea2..507e94eff8 100644 --- a/library/Zend/Barcode/Object/Code128.php +++ b/library/Zend/Barcode/Object/Code128.php @@ -197,8 +197,7 @@ protected function _calculateBarcodeWidth() $encodedData = $convertedChars * $characterLength; // ...except the STOP character (13) $encodedData += $characterLength + 2 * $this->_barThinWidth * $this->_factor; - $width = $quietZone + $encodedData + $quietZone; - return $width; + return $quietZone + $encodedData + $quietZone; } /** @@ -266,7 +265,7 @@ protected static function _isDigit($string, $pos, $length = 2) protected function _convertToBarcodeChars($string) { $string = (string) $string; - if (!strlen($string)) { + if ($string === '') { return array(); } @@ -298,7 +297,7 @@ protected function _convertToBarcodeChars($string) $result[] = $code; $currentCharset = 'C'; } - } else if (in_array($char, $this->_charSets['B']) && $currentCharset != 'B' + } elseif (in_array($char, $this->_charSets['B']) && $currentCharset != 'B' && !(in_array($char, $this->_charSets['A']) && $currentCharset == 'A')) { /** * Switch to B as B contains the char and B is not the current charset. @@ -310,7 +309,7 @@ protected function _convertToBarcodeChars($string) } $result[] = $code; $currentCharset = 'B'; - } else if (array_key_exists($char, $this->_charSets['A']) && $currentCharset != 'A' + } elseif (array_key_exists($char, $this->_charSets['A']) && $currentCharset != 'A' && !(array_key_exists($char, $this->_charSets['B']) && $currentCharset == 'B')) { /** * Switch to C as C contains the char and C is not the current charset. @@ -375,9 +374,7 @@ public function getChecksum($text) $sum += ($k++) * $char; } - $checksum = $sum % 103; - - return $checksum; + return $sum % 103; } /** diff --git a/library/Zend/Barcode/Object/Code25.php b/library/Zend/Barcode/Object/Code25.php index c55a4c5c04..f148b8a3f6 100644 --- a/library/Zend/Barcode/Object/Code25.php +++ b/library/Zend/Barcode/Object/Code25.php @@ -104,7 +104,7 @@ protected function _prepareBarcode() $barcodeChar = str_split($this->_codingMap[$char]); foreach ($barcodeChar as $c) { /* visible, width, top, length */ - $width = $c ? $this->_barThickWidth : $this->_barThinWidth; + $width = $c !== '' && $c !== '0' ? $this->_barThickWidth : $this->_barThinWidth; $barcodeTable[] = array(1 , $width , 0 , 1); $barcodeTable[] = array(0 , $this->_barThinWidth); } @@ -132,12 +132,10 @@ public function getChecksum($text) $checksum = 0; for ($i = strlen($text); $i > 0; $i --) { - $checksum += intval($text[$i - 1]) * $factor; + $checksum += (int) $text[$i - 1] * $factor; $factor = 4 - $factor; } - $checksum = (10 - ($checksum % 10)) % 10; - - return $checksum; + return (10 - ($checksum % 10)) % 10; } } diff --git a/library/Zend/Barcode/Object/Code25interleaved.php b/library/Zend/Barcode/Object/Code25interleaved.php index 8b606ceaaf..b54a42c01a 100644 --- a/library/Zend/Barcode/Object/Code25interleaved.php +++ b/library/Zend/Barcode/Object/Code25interleaved.php @@ -110,14 +110,14 @@ protected function _prepareBarcode() // Interleave for ($ibar = 0; $ibar < 5; $ibar ++) { // Draws char1 bar (fore color) - $barWidth = (substr($this->_codingMap[$char1], $ibar, 1)) + $barWidth = (substr($this->_codingMap[$char1], $ibar, 1) !== '' && substr($this->_codingMap[$char1], $ibar, 1) !== '0') ? $this->_barThickWidth : $this->_barThinWidth; $barcodeTable[] = array(1, $barWidth, 0, 1); // Left space corresponding to char2 (background color) - $barWidth = (substr($this->_codingMap[$char2], $ibar, 1)) + $barWidth = (substr($this->_codingMap[$char2], $ibar, 1) !== '' && substr($this->_codingMap[$char2], $ibar, 1) !== '0') ? $this->_barThickWidth : $this->_barThinWidth; $barcodeTable[] = array(0, $barWidth, 0 , 1); diff --git a/library/Zend/Barcode/Object/Code39.php b/library/Zend/Barcode/Object/Code39.php index ca4403d8cf..63f022ea06 100644 --- a/library/Zend/Barcode/Object/Code39.php +++ b/library/Zend/Barcode/Object/Code39.php @@ -159,7 +159,7 @@ protected function _prepareBarcode() $visible = true; foreach ($barcodeChar as $c) { /* visible, width, top, length */ - $width = $c ? $this->_barThickWidth : $this->_barThinWidth; + $width = $c !== '' && $c !== '0' ? $this->_barThickWidth : $this->_barThinWidth; $barcodeTable[] = array((int) $visible, $width, 0, 1); $visible = ! $visible; } diff --git a/library/Zend/Barcode/Object/Ean13.php b/library/Zend/Barcode/Object/Ean13.php index dfeb6782e7..a5ee19e7a1 100644 --- a/library/Zend/Barcode/Object/Ean13.php +++ b/library/Zend/Barcode/Object/Ean13.php @@ -166,13 +166,11 @@ public function getChecksum($text) $checksum = 0; for ($i = strlen($text); $i > 0; $i --) { - $checksum += intval($text[$i - 1]) * $factor; + $checksum += (int) $text[$i - 1] * $factor; $factor = 4 - $factor; } - $checksum = (10 - ($checksum % 10)) % 10; - - return $checksum; + return (10 - ($checksum % 10)) % 10; } /** @@ -181,7 +179,7 @@ public function getChecksum($text) */ protected function _drawText() { - if (get_class($this) == 'Zend_Barcode_Object_Ean13') { + if (get_class($this) === 'Zend_Barcode_Object_Ean13') { $this->_drawEan13Text(); } else { parent::_drawText(); diff --git a/library/Zend/Barcode/Object/Ean5.php b/library/Zend/Barcode/Object/Ean5.php index 1f074ba077..a3e060a756 100644 --- a/library/Zend/Barcode/Object/Ean5.php +++ b/library/Zend/Barcode/Object/Ean5.php @@ -124,7 +124,7 @@ public function getChecksum($text) $checksum = 0; for ($i = 0 ; $i < $this->_barcodeLength; $i ++) { - $checksum += intval($text[$i]) * ($i % 2 ? 9 : 3); + $checksum += (int) $text[$i] * ($i % 2 !== 0 ? 9 : 3); } return ($checksum % 10); diff --git a/library/Zend/Barcode/Object/Identcode.php b/library/Zend/Barcode/Object/Identcode.php index cbb8f3ea35..a0fd17e305 100644 --- a/library/Zend/Barcode/Object/Identcode.php +++ b/library/Zend/Barcode/Object/Identcode.php @@ -57,7 +57,7 @@ protected function _getDefaultOptions() */ public function getTextToDisplay() { - return preg_replace('/([0-9]{2})([0-9]{3})([0-9]{3})([0-9]{3})([0-9])/', + return preg_replace('/(\d{2})(\d{3})(\d{3})(\d{3})(\d)/', '$1.$2 $3.$4 $5', $this->getText()); } @@ -84,11 +84,9 @@ public function getChecksum($text) $checksum = 0; for ($i = strlen($text); $i > 0; $i --) { - $checksum += intval($text[$i - 1]) * (($i % 2) ? 4 : 9); + $checksum += (int) $text[$i - 1] * (($i % 2 !== 0) ? 4 : 9); } - $checksum = (10 - ($checksum % 10)) % 10; - - return $checksum; + return (10 - ($checksum % 10)) % 10; } } diff --git a/library/Zend/Barcode/Object/Leitcode.php b/library/Zend/Barcode/Object/Leitcode.php index 8646b97b25..69d7c6a23a 100644 --- a/library/Zend/Barcode/Object/Leitcode.php +++ b/library/Zend/Barcode/Object/Leitcode.php @@ -57,7 +57,7 @@ protected function _getDefaultOptions() */ public function getTextToDisplay() { - return preg_replace('/([0-9]{5})([0-9]{3})([0-9]{3})([0-9]{2})([0-9])/', + return preg_replace('/(\d{5})(\d{3})(\d{3})(\d{2})(\d)/', '$1.$2.$3.$4 $5', $this->getText()); } diff --git a/library/Zend/Barcode/Object/ObjectAbstract.php b/library/Zend/Barcode/Object/ObjectAbstract.php index 1285a0c3b8..083aaddca7 100644 --- a/library/Zend/Barcode/Object/ObjectAbstract.php +++ b/library/Zend/Barcode/Object/ObjectAbstract.php @@ -342,13 +342,13 @@ public function getType() */ public function setBarHeight($value) { - if (intval($value) <= 0) { + if ((int) $value <= 0) { require_once 'Zend/Barcode/Object/Exception.php'; throw new Zend_Barcode_Object_Exception( 'Bar height must be greater than 0' ); } - $this->_barHeight = intval($value); + $this->_barHeight = (int) $value; return $this; } @@ -371,13 +371,13 @@ public function getBarHeight() */ public function setBarThinWidth($value) { - if (intval($value) <= 0) { + if ((int) $value <= 0) { require_once 'Zend/Barcode/Object/Exception.php'; throw new Zend_Barcode_Object_Exception( 'Bar width must be greater than 0' ); } - $this->_barThinWidth = intval($value); + $this->_barThinWidth = (int) $value; return $this; } @@ -400,13 +400,13 @@ public function getBarThinWidth() */ public function setBarThickWidth($value) { - if (intval($value) <= 0) { + if ((int) $value <= 0) { require_once 'Zend/Barcode/Object/Exception.php'; throw new Zend_Barcode_Object_Exception( 'Bar width must be greater than 0' ); } - $this->_barThickWidth = intval($value); + $this->_barThickWidth = (int) $value; return $this; } @@ -424,7 +424,7 @@ public function getBarThickWidth() * Set factor applying to * thinBarWidth - thickBarWidth - barHeight - fontSize * - * @param int|float|string|bool $value + * @param scalar $value * @return $this * @throws Zend_Barcode_Object_Exception */ @@ -463,7 +463,7 @@ public function setForeColor($value) if (preg_match('`\#[0-9A-F]{6}`', $value)) { $this->_foreColor = hexdec($value); } elseif (is_numeric($value) && $value >= 0 && $value <= 16777125) { - $this->_foreColor = intval($value); + $this->_foreColor = (int) $value; } else { require_once 'Zend/Barcode/Object/Exception.php'; throw new Zend_Barcode_Object_Exception( @@ -495,7 +495,7 @@ public function setBackgroundColor($value) if (preg_match('`\#[0-9A-F]{6}`', (string) $value)) { $this->_backgroundColor = hexdec($value); } elseif (is_numeric($value) && $value >= 0 && $value <= 16777125) { - $this->_backgroundColor = intval($value); + $this->_backgroundColor = (int) $value; } else { require_once 'Zend/Barcode/Object/Exception.php'; throw new Zend_Barcode_Object_Exception( @@ -576,7 +576,7 @@ public function setReverseColor() /** * Set orientation of barcode and text * - * @param int|float|string|bool $value + * @param scalar $value * @return $this * @throws Zend_Barcode_Object_Exception */ @@ -639,10 +639,8 @@ protected function _addLeadingZeros($text, $withoutChecksum = false) if (strlen($text) < $length) { $text = str_repeat('0', $length - strlen($text)) . $text; } - } else { - if ($this->_barcodeLength == 'even') { - $text = ((strlen($text) - $omitChecksum) % 2 ? '0' . $text : $text); - } + } elseif ($this->_barcodeLength == 'even') { + $text = ((strlen($text) - $omitChecksum) % 2 !== 0 ? '0' . $text : $text); } } return $text; @@ -988,7 +986,7 @@ protected function _checkText($value = null) if ($value === null) { $value = $this->_text; } - if (!strlen($value)) { + if ((string) $value === '') { require_once 'Zend/Barcode/Object/Exception.php'; throw new Zend_Barcode_Object_Exception( 'A text must be provide to Barcode before drawing' @@ -1205,8 +1203,8 @@ protected function _rotate($x1, $y1) + $this->getOffsetTop(); return array( - intval($x2), - intval($y2) + (int) $x2, + (int) $y2 ); } diff --git a/library/Zend/Barcode/Object/Postnet.php b/library/Zend/Barcode/Object/Postnet.php index ddf4caa1c4..4364669da7 100644 --- a/library/Zend/Barcode/Object/Postnet.php +++ b/library/Zend/Barcode/Object/Postnet.php @@ -130,7 +130,6 @@ public function getChecksum($text) { $this->_checkText($text); $sum = array_sum(str_split($text)); - $checksum = (10 - ($sum % 10)) % 10; - return $checksum; + return (10 - ($sum % 10)) % 10; } } diff --git a/library/Zend/Barcode/Object/Royalmail.php b/library/Zend/Barcode/Object/Royalmail.php index 8d7bdd239c..d700abcbf0 100644 --- a/library/Zend/Barcode/Object/Royalmail.php +++ b/library/Zend/Barcode/Object/Royalmail.php @@ -126,7 +126,7 @@ protected function _prepareBarcode() foreach ($textTable as $char) { $bars = str_split($this->_codingMap[$char]); foreach ($bars as $b) { - $barcodeTable[] = array(1 , $this->_barThinWidth , ($b > 1 ? 3/8 : 0) , ($b % 2 ? 5/8 : 1)); + $barcodeTable[] = array(1 , $this->_barThinWidth , ($b > 1 ? 3/8 : 0) , ($b % 2 !== 0 ? 5/8 : 1)); $barcodeTable[] = array(0 , $this->_barThinWidth , 0 , 1); } } diff --git a/library/Zend/Barcode/Renderer/Image.php b/library/Zend/Barcode/Renderer/Image.php index d73b098b11..9ec9e1a5e1 100644 --- a/library/Zend/Barcode/Renderer/Image.php +++ b/library/Zend/Barcode/Renderer/Image.php @@ -98,13 +98,13 @@ public function __construct($options = null) */ public function setHeight($value) { - if (!is_numeric($value) || intval($value) < 0) { + if (!is_numeric($value) || (int) $value < 0) { require_once 'Zend/Barcode/Renderer/Exception.php'; throw new Zend_Barcode_Renderer_Exception( 'Image height must be greater than or equals 0' ); } - $this->_userHeight = intval($value); + $this->_userHeight = (int) $value; return $this; } @@ -127,13 +127,13 @@ public function getHeight() */ public function setWidth($value) { - if (!is_numeric($value) || intval($value) < 0) { + if (!is_numeric($value) || (int) $value < 0) { require_once 'Zend/Barcode/Renderer/Exception.php'; throw new Zend_Barcode_Renderer_Exception( 'Image width must be greater than or equals 0' ); } - $this->_userWidth = intval($value); + $this->_userWidth = (int) $value; return $this; } @@ -301,17 +301,15 @@ protected function _checkDimensions() 'Barcode is define outside the image (height)' ); } - } else { - if ($this->_userHeight) { - $height = $this->_barcode->getHeight(true); - if ($this->_userHeight < $height) { - require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception(sprintf( - "Barcode is define outside the image (calculated: '%d', provided: '%d')", - $height, - $this->_userHeight - )); - } + } elseif ($this->_userHeight !== 0) { + $height = $this->_barcode->getHeight(true); + if ($this->_userHeight < $height) { + require_once 'Zend/Barcode/Renderer/Exception.php'; + throw new Zend_Barcode_Renderer_Exception(sprintf( + "Barcode is define outside the image (calculated: '%d', provided: '%d')", + $height, + $this->_userHeight + )); } } if ($this->_resource !== null) { @@ -321,17 +319,15 @@ protected function _checkDimensions() 'Barcode is define outside the image (width)' ); } - } else { - if ($this->_userWidth) { - $width = $this->_barcode->getWidth(true); - if ($this->_userWidth < $width) { - require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception(sprintf( - "Barcode is define outside the image (calculated: '%d', provided: '%d')", - $width, - $this->_userWidth - )); - } + } elseif ($this->_userWidth !== 0) { + $width = $this->_barcode->getWidth(true); + if ($this->_userWidth < $width) { + require_once 'Zend/Barcode/Renderer/Exception.php'; + throw new Zend_Barcode_Renderer_Exception(sprintf( + "Barcode is define outside the image (calculated: '%d', provided: '%d')", + $width, + $this->_userWidth + )); } } } diff --git a/library/Zend/Barcode/Renderer/Pdf.php b/library/Zend/Barcode/Renderer/Pdf.php index 6341d7829c..6ed82a8e29 100644 --- a/library/Zend/Barcode/Renderer/Pdf.php +++ b/library/Zend/Barcode/Renderer/Pdf.php @@ -78,9 +78,9 @@ public function setResource($pdf, $page = 0) } $this->_resource = $pdf; - $this->_page = intval($page); + $this->_page = (int) $page; - if (!count($this->_resource->pages)) { + if ($this->_resource->pages === []) { $this->_page = 0; $this->_resource->pages[] = new Zend_Pdf_Page( Zend_Pdf_Page::SIZE_A4 @@ -140,11 +140,11 @@ protected function _drawPolygon($points, $color, $filled = true) $y[] = $page->getHeight() - $point[1] * $this->_moduleSize - $this->_topOffset; } if (count($y) == 4) { - if ($x[0] != $x[3] && $y[0] == $y[3]) { + if ($x[0] !== $x[3] && $y[0] === $y[3]) { $y[0] -= ($this->_moduleSize / 2); $y[3] -= ($this->_moduleSize / 2); } - if ($x[1] != $x[2] && $y[1] == $y[2]) { + if ($x[1] !== $x[2] && $y[1] === $y[2]) { $y[1] += ($this->_moduleSize / 2); $y[2] += ($this->_moduleSize / 2); } @@ -239,7 +239,6 @@ public function widthForStringUsingFontSize($text, $font, $fontSize) } $glyphs = $font->glyphNumbersForCharacters($characters); $widths = $font->widthsForGlyphs($glyphs); - $stringWidth = (array_sum($widths) / $font->getUnitsPerEm()) * $fontSize; - return $stringWidth; + return (array_sum($widths) / $font->getUnitsPerEm()) * $fontSize; } } diff --git a/library/Zend/Barcode/Renderer/RendererAbstract.php b/library/Zend/Barcode/Renderer/RendererAbstract.php index 2bbe16b5aa..51ffc995e2 100644 --- a/library/Zend/Barcode/Renderer/RendererAbstract.php +++ b/library/Zend/Barcode/Renderer/RendererAbstract.php @@ -174,13 +174,13 @@ public function getType() */ public function setTopOffset($value) { - if (!is_numeric($value) || intval($value) < 0) { + if (!is_numeric($value) || (int) $value < 0) { require_once 'Zend/Barcode/Renderer/Exception.php'; throw new Zend_Barcode_Renderer_Exception( 'Vertical position must be greater than or equals 0' ); } - $this->_topOffset = intval($value); + $this->_topOffset = (int) $value; return $this; } @@ -201,13 +201,13 @@ public function getTopOffset() */ public function setLeftOffset($value) { - if (!is_numeric($value) || intval($value) < 0) { + if (!is_numeric($value) || (int) $value < 0) { require_once 'Zend/Barcode/Renderer/Exception.php'; throw new Zend_Barcode_Renderer_Exception( 'Horizontal position must be greater than or equals 0' ); } - $this->_leftOffset = intval($value); + $this->_leftOffset = (int) $value; return $this; } @@ -393,7 +393,7 @@ protected function _checkBarcodeObject() protected function _adjustPosition($supportHeight, $supportWidth) { $barcodeHeight = $this->_barcode->getHeight(true) * $this->_moduleSize; - if ($barcodeHeight != $supportHeight && $this->_topOffset == 0) { + if ($barcodeHeight !== $supportHeight && $this->_topOffset == 0) { switch ($this->_verticalPosition) { case 'middle': $this->_topOffset = floor( @@ -409,7 +409,7 @@ protected function _adjustPosition($supportHeight, $supportWidth) } } $barcodeWidth = $this->_barcode->getWidth(true) * $this->_moduleSize; - if ($barcodeWidth != $supportWidth && $this->_leftOffset == 0) { + if ($barcodeWidth !== $supportWidth && $this->_leftOffset == 0) { switch ($this->_horizontalPosition) { case 'center': $this->_leftOffset = floor( diff --git a/library/Zend/Barcode/Renderer/Svg.php b/library/Zend/Barcode/Renderer/Svg.php index 4bb94d750d..ff03658914 100644 --- a/library/Zend/Barcode/Renderer/Svg.php +++ b/library/Zend/Barcode/Renderer/Svg.php @@ -67,13 +67,13 @@ class Zend_Barcode_Renderer_Svg extends Zend_Barcode_Renderer_RendererAbstract */ public function setHeight($value) { - if (!is_numeric($value) || intval($value) < 0) { + if (!is_numeric($value) || (int) $value < 0) { require_once 'Zend/Barcode/Renderer/Exception.php'; throw new Zend_Barcode_Renderer_Exception( 'Svg height must be greater than or equals 0' ); } - $this->_userHeight = intval($value); + $this->_userHeight = (int) $value; return $this; } @@ -96,13 +96,13 @@ public function getHeight() */ public function setWidth($value) { - if (!is_numeric($value) || intval($value) < 0) { + if (!is_numeric($value) || (int) $value < 0) { require_once 'Zend/Barcode/Renderer/Exception.php'; throw new Zend_Barcode_Renderer_Exception( 'Svg width must be greater than or equals 0' ); } - $this->_userWidth = intval($value); + $this->_userWidth = (int) $value; return $this; } @@ -252,17 +252,15 @@ protected function _checkDimensions() 'Barcode is define outside the image (height)' ); } - } else { - if ($this->_userHeight) { - $height = $this->_barcode->getHeight(true); - if ($this->_userHeight < $height) { - require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception(sprintf( - "Barcode is define outside the image (calculated: '%d', provided: '%d')", - $height, - $this->_userHeight - )); - } + } elseif ($this->_userHeight !== 0) { + $height = $this->_barcode->getHeight(true); + if ($this->_userHeight < $height) { + require_once 'Zend/Barcode/Renderer/Exception.php'; + throw new Zend_Barcode_Renderer_Exception(sprintf( + "Barcode is define outside the image (calculated: '%d', provided: '%d')", + $height, + $this->_userHeight + )); } } if ($this->_resource !== null) { @@ -274,17 +272,15 @@ protected function _checkDimensions() 'Barcode is define outside the image (width)' ); } - } else { - if ($this->_userWidth) { - $width = (float) $this->_barcode->getWidth(true); - if ($this->_userWidth < $width) { - require_once 'Zend/Barcode/Renderer/Exception.php'; - throw new Zend_Barcode_Renderer_Exception(sprintf( - "Barcode is define outside the image (calculated: '%d', provided: '%d')", - $width, - $this->_userWidth - )); - } + } elseif ($this->_userWidth !== 0) { + $width = (float) $this->_barcode->getWidth(true); + if ($this->_userWidth < $width) { + require_once 'Zend/Barcode/Renderer/Exception.php'; + throw new Zend_Barcode_Renderer_Exception(sprintf( + "Barcode is define outside the image (calculated: '%d', provided: '%d')", + $width, + $this->_userWidth + )); } } } diff --git a/library/Zend/Cache.php b/library/Zend/Cache.php index dc818f30e5..4294449cda 100644 --- a/library/Zend/Cache.php +++ b/library/Zend/Cache.php @@ -92,21 +92,17 @@ public static function factory($frontend, $backend, $frontendOptions = array(), { if (is_string($backend)) { $backendObject = self::_makeBackend($backend, $backendOptions, $customBackendNaming, $autoload); + } elseif ((is_object($backend)) && (in_array('Zend_Cache_Backend_Interface', class_implements($backend)))) { + $backendObject = $backend; } else { - if ((is_object($backend)) && (in_array('Zend_Cache_Backend_Interface', class_implements($backend)))) { - $backendObject = $backend; - } else { - self::throwException('backend must be a backend name (string) or an object which implements Zend_Cache_Backend_Interface'); - } + self::throwException('backend must be a backend name (string) or an object which implements Zend_Cache_Backend_Interface'); } if (is_string($frontend)) { $frontendObject = self::_makeFrontend($frontend, $frontendOptions, $customFrontendNaming, $autoload); + } elseif (is_object($frontend)) { + $frontendObject = $frontend; } else { - if (is_object($frontend)) { - $frontendObject = $frontend; - } else { - self::throwException('frontend must be a frontend name (string) or an object'); - } + self::throwException('frontend must be a frontend name (string) or an object'); } $frontendObject->setBackend($backendObject); return $frontendObject; @@ -136,12 +132,7 @@ public static function _makeBackend($backend, $backendOptions, $customBackendNam if (!preg_match('~^[\w\\\\]+$~D', $backend)) { Zend_Cache::throwException("Invalid backend name [$backend]"); } - if (!$customBackendNaming) { - // we use this boolean to avoid an API break - $backendClass = 'Zend_Cache_Backend_' . $backend; - } else { - $backendClass = $backend; - } + $backendClass = $customBackendNaming ? $backend : 'Zend_Cache_Backend_' . $backend; if (!$autoload) { $file = str_replace('_', DIRECTORY_SEPARATOR, $backendClass) . '.php'; if (!(self::_isReadable($file))) { @@ -178,12 +169,7 @@ public static function _makeFrontend($frontend, $frontendOptions = array(), $cus if (!preg_match('~^[\w\\\\]+$~D', $frontend)) { Zend_Cache::throwException("Invalid frontend name [$frontend]"); } - if (!$customFrontendNaming) { - // we use this boolean to avoid an API break - $frontendClass = 'Zend_Cache_Frontend_' . $frontend; - } else { - $frontendClass = $frontend; - } + $frontendClass = $customFrontendNaming ? $frontend : 'Zend_Cache_Frontend_' . $frontend; if (!$autoload) { $file = str_replace('_', DIRECTORY_SEPARATOR, $frontendClass) . '.php'; if (!(self::_isReadable($file))) { diff --git a/library/Zend/Cache/Backend.php b/library/Zend/Cache/Backend.php index 3d99e0939c..d581be91d9 100644 --- a/library/Zend/Cache/Backend.php +++ b/library/Zend/Cache/Backend.php @@ -175,11 +175,7 @@ public function getTmpDir() foreach (array($_ENV, $_SERVER) as $tab) { foreach (array('TMPDIR', 'TEMP', 'TMP', 'windir', 'SystemRoot') as $key) { if (isset($tab[$key]) && is_string($tab[$key])) { - if (($key == 'windir') or ($key == 'SystemRoot')) { - $dir = realpath($tab[$key] . '\\temp'); - } else { - $dir = realpath($tab[$key]); - } + $dir = ($key == 'windir' || $key == 'SystemRoot') ? realpath($tab[$key] . '\\temp') : realpath($tab[$key]); if ($this->_isGoodTmpDir($dir)) { return $dir; } @@ -225,12 +221,7 @@ public function getTmpDir() */ protected function _isGoodTmpDir($dir) { - if (is_readable($dir)) { - if (is_writable($dir)) { - return true; - } - } - return false; + return is_readable($dir) && is_writable($dir); } /** diff --git a/library/Zend/Cache/Backend/Apc.php b/library/Zend/Cache/Backend/Apc.php index 5a09becdcf..d205816f89 100644 --- a/library/Zend/Cache/Backend/Apc.php +++ b/library/Zend/Cache/Backend/Apc.php @@ -110,7 +110,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) { $lifetime = $this->getLifetime($specificLifetime); $result = apc_store($id, array($data, time(), $lifetime), $lifetime); - if (count($tags) > 0) { + if ($tags !== []) { $this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND); } return $result; diff --git a/library/Zend/Cache/Backend/File.php b/library/Zend/Cache/Backend/File.php index 581da22113..debcf8ede6 100644 --- a/library/Zend/Cache/Backend/File.php +++ b/library/Zend/Cache/Backend/File.php @@ -129,10 +129,8 @@ public function __construct(array $options = array()) } else { $this->setCacheDir(self::getTmpDir() . DIRECTORY_SEPARATOR, false); } - if (isset($this->_options['file_name_prefix'])) { // particular case for this option - if (!preg_match('~^[a-zA-Z0-9_]+$~D', (string) $this->_options['file_name_prefix'])) { - Zend_Cache::throwException('Invalid file_name_prefix : must use only [a-zA-Z0-9_]'); - } + // particular case for this option + if (isset($this->_options['file_name_prefix']) && !preg_match('~^\w+$~D', (string) $this->_options['file_name_prefix'])) { Zend_Cache::throwException('Invalid file_name_prefix : must use only [a-zA-Z0-9_]'); } if ($this->_options['metadatas_array_max_size'] < 10) { Zend_Cache::throwException('Invalid metadatas_array_max_size, must be > 10'); @@ -253,11 +251,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) return false; } } - if ($this->_options['read_control']) { - $hash = $this->_hash($data, $this->_options['read_control_type']); - } else { - $hash = ''; - } + $hash = $this->_options['read_control'] ? $this->_hash($data, $this->_options['read_control_type']) : ''; $metadatas = array( 'hash' => $hash, 'mtime' => time(), @@ -269,8 +263,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) $this->_log('Zend_Cache_Backend_File::save() / error on saving metadata'); return false; } - $res = $this->_filePutContents($file, $data); - return $res; + return $this->_filePutContents($file, $data); } /** @@ -440,11 +433,7 @@ public function touch($id, $extraLifetime) 'expire' => $metadatas['expire'] + $extraLifetime, 'tags' => $metadatas['tags'] ); - $res = $this->_setMetadatas($id, $newMetadatas); - if (!$res) { - return false; - } - return true; + return $this->_setMetadatas($id, $newMetadatas); } /** @@ -568,11 +557,10 @@ protected function _loadMetadatas($id) { $file = $this->_metadatasFile($id); $result = $this->_fileGetContents($file); - if (!$result) { + if ($result === '' || $result === '0') { return false; } - $tmp = @unserialize($result); - return $tmp; + return @unserialize($result); } /** @@ -585,11 +573,7 @@ protected function _loadMetadatas($id) protected function _saveMetadatas($id, $metadatas) { $file = $this->_metadatasFile($id); - $result = $this->_filePutContents($file, serialize($metadatas)); - if (!$result) { - return false; - } - return true; + return $this->_filePutContents($file, serialize($metadatas)); } /** @@ -741,7 +725,7 @@ protected function _clean($dir, $mode = Zend_Cache::CLEANING_MODE_ALL, $tags = a break; } } - if ((is_dir($file)) and ($this->_options['hashed_directory_level']>0)) { + if (is_dir($file) && $this->_options['hashed_directory_level']>0) { // Recursive call $result = $this->_clean($file . DIRECTORY_SEPARATOR, $mode, $tags) && $result; if ($mode == Zend_Cache::CLEANING_MODE_ALL) { @@ -832,7 +816,7 @@ protected function _get($dir, $mode, $tags = array()) break; } } - if ((is_dir($file)) and ($this->_options['hashed_directory_level']>0)) { + if (is_dir($file) && $this->_options['hashed_directory_level']>0) { // Recursive call $recursiveRs = $this->_get($file . DIRECTORY_SEPARATOR, $mode, $tags); if ($recursiveRs === false) { @@ -892,8 +876,7 @@ protected function _hash($data, $controlType) protected function _idToFileName($id) { $prefix = $this->_options['file_name_prefix']; - $result = $prefix . '---' . $id; - return $result; + return $prefix . '---' . $id; } /** @@ -1013,7 +996,7 @@ protected function _filePutContents($file, $string) fseek($f, 0); ftruncate($f, 0); $tmp = @fwrite($f, $string); - if (!($tmp === FALSE)) { + if ($tmp !== FALSE) { $result = true; } @fclose($f); diff --git a/library/Zend/Cache/Backend/Libmemcached.php b/library/Zend/Cache/Backend/Libmemcached.php index 623e75776c..48b308745f 100644 --- a/library/Zend/Cache/Backend/Libmemcached.php +++ b/library/Zend/Cache/Backend/Libmemcached.php @@ -132,10 +132,8 @@ public function __construct(array $options = array()) $this->_log("Unknown memcached client option '{$name}' ({$optConst})"); } } - if (null !== $optId) { - if (!$this->_memcache->setOption($optId, $value)) { - $this->_log("Setting memcached client option '{$optId}' failed"); - } + if (null !== $optId && !$this->_memcache->setOption($optId, $value)) { + $this->_log("Setting memcached client option '{$optId}' failed"); } } @@ -209,7 +207,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) $this->_log("Memcached::set() failed: [{$rsCode}] {$rsMsg}"); } - if (count($tags) > 0) { + if ($tags !== []) { $this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_LIBMEMCACHED_BACKEND); } diff --git a/library/Zend/Cache/Backend/Memcached.php b/library/Zend/Cache/Backend/Memcached.php index 9cb9916dd8..76994774f4 100644 --- a/library/Zend/Cache/Backend/Memcached.php +++ b/library/Zend/Cache/Backend/Memcached.php @@ -214,16 +214,12 @@ public function test($id) public function save($data, $id, $tags = array(), $specificLifetime = false) { $lifetime = $this->getLifetime($specificLifetime); - if ($this->_options['compression']) { - $flag = MEMCACHE_COMPRESSED; - } else { - $flag = 0; - } + $flag = $this->_options['compression'] ? MEMCACHE_COMPRESSED : 0; // ZF-8856: using set because add needs a second request if item already exists $result = @$this->_memcache->set($id, array($data, time(), $lifetime), $flag, $lifetime); - if (count($tags) > 0) { + if ($tags !== []) { $this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_MEMCACHED_BACKEND); } @@ -452,11 +448,7 @@ public function getMetadatas($id) */ public function touch($id, $extraLifetime) { - if ($this->_options['compression']) { - $flag = MEMCACHE_COMPRESSED; - } else { - $flag = 0; - } + $flag = $this->_options['compression'] ? MEMCACHE_COMPRESSED : 0; $tmp = $this->_memcache->get($id); if (is_array($tmp)) { $data = $tmp[0]; diff --git a/library/Zend/Cache/Backend/Sqlite.php b/library/Zend/Cache/Backend/Sqlite.php index bac31c08ce..8c61ed7b80 100644 --- a/library/Zend/Cache/Backend/Sqlite.php +++ b/library/Zend/Cache/Backend/Sqlite.php @@ -119,7 +119,7 @@ public function load($id, $doNotTestCacheValidity = false) } $result = $this->_query($sql); $row = @sqlite_fetch_array($result); - if ($row) { + if ($row !== []) { return $row['content']; } return false; @@ -137,7 +137,7 @@ public function test($id) $sql = "SELECT lastModified FROM cache WHERE id='$id' AND (expire=0 OR expire>" . time() . ')'; $result = $this->_query($sql); $row = @sqlite_fetch_array($result); - if ($row) { + if ($row !== []) { return ((int) $row['lastModified']); } return false; @@ -162,11 +162,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) $lifetime = $this->getLifetime($specificLifetime); $data = @sqlite_escape_string($data); $mktime = time(); - if ($lifetime === null) { - $expire = 0; - } else { - $expire = $mktime + $lifetime; - } + $expire = $lifetime === null ? 0 : $mktime + $lifetime; $this->_query("DELETE FROM cache WHERE id='$id'"); $sql = "INSERT INTO cache (id, content, lastModified, expire) VALUES ('$id', '$data', $mktime, $expire)"; $res = $this->_query($sql); @@ -285,9 +281,7 @@ public function getIdsMatchingTags($tags = array()) } } $result = array(); - foreach ($ids as $id) { - $result[] = $id; - } + $result = $ids; return $result; } @@ -354,9 +348,7 @@ public function getIdsMatchingAnyTags($tags = array()) } } $result = array(); - foreach ($ids as $id) { - $result[] = $id; - } + $result = $ids; return $result; } @@ -581,10 +573,10 @@ private function _checkStructureVersion() $result = $this->_query("SELECT num FROM version"); if (!$result) return false; $row = @sqlite_fetch_array($result); - if (!$row) { + if ($row === []) { return false; } - if (((int) $row['num']) != 1) { + if ((int) $row['num'] != 1) { // old cache structure $this->_log('Zend_Cache_Backend_Sqlite::_checkStructureVersion() : old cache structure version detected => the cache is going to be dropped'); return false; diff --git a/library/Zend/Cache/Backend/Static.php b/library/Zend/Cache/Backend/Static.php index 70e0286eef..b6a95a253b 100644 --- a/library/Zend/Cache/Backend/Static.php +++ b/library/Zend/Cache/Backend/Static.php @@ -137,11 +137,7 @@ public function getOption($name) */ public function load($id, $doNotTestCacheValidity = false) { - if (($id = (string)$id) === '') { - $id = $this->_detectId(); - } else { - $id = $this->_decodeId($id); - } + $id = ($id = (string)$id) === '' ? $this->_detectId() : $this->_decodeId($id); if (!$this->_verifyPath($id)) { Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path'); } @@ -156,8 +152,7 @@ public function load($id, $doNotTestCacheValidity = false) $pathName = $this->_options['public_dir'] . dirname($id); $file = rtrim($pathName, '/') . '/' . $fileName . $this->_options['file_extension']; if (file_exists($file)) { - $content = file_get_contents($file); - return $content; + return file_get_contents($file); } return false; @@ -188,16 +183,9 @@ public function test($id) $pathName = $this->_options['public_dir'] . dirname($id); // Switch extension if needed - if (isset($this->_tagged[$id])) { - $extension = $this->_tagged[$id]['extension']; - } else { - $extension = $this->_options['file_extension']; - } + $extension = isset($this->_tagged[$id]) ? $this->_tagged[$id]['extension'] : $this->_options['file_extension']; $file = $pathName . '/' . $fileName . $extension; - if (file_exists($file)) { - return true; - } - return false; + return file_exists($file); } /** @@ -225,11 +213,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) } clearstatcache(); - if (($id = (string)$id) === '') { - $id = $this->_detectId(); - } else { - $id = $this->_decodeId($id); - } + $id = ($id = (string)$id) === '' ? $this->_detectId() : $this->_decodeId($id); $fileName = basename($id); if ($fileName === '') { @@ -317,11 +301,7 @@ public function remove($id) } elseif (!$this->_tagged) { return false; } - if (isset($this->_tagged[$id])) { - $extension = $this->_tagged[$id]['extension']; - } else { - $extension = $this->_options['file_extension']; - } + $extension = isset($this->_tagged[$id]) ? $this->_tagged[$id]['extension'] : $this->_options['file_extension']; if ($fileName === '') { $fileName = $this->_options['index_filename']; } @@ -359,10 +339,8 @@ public function removeRecursively($id) } if (is_dir($directory)) { foreach (new DirectoryIterator($directory) as $file) { - if (true === $file->isFile()) { - if (false === unlink($file->getPathName())) { - return false; - } + if ($file->isFile() && !unlink($file->getPathName())) { + return false; } } } @@ -560,7 +538,7 @@ protected static function _validateIdOrTag($string) */ protected function _octdec($val) { - if (is_string($val) && decoct(octdec($val)) == $val) { + if (is_string($val) && decoct(octdec($val)) === $val) { return octdec($val); } return $val; diff --git a/library/Zend/Cache/Backend/Test.php b/library/Zend/Cache/Backend/Test.php index d94e973441..b468a36740 100644 --- a/library/Zend/Cache/Backend/Test.php +++ b/library/Zend/Cache/Backend/Test.php @@ -167,10 +167,7 @@ public function test($id) public function save($data, $id, $tags = array(), $specificLifetime = false) { $this->_addLog('save', array($data, $id, $tags)); - if (substr($id,-5)=='false') { - return false; - } - return true; + return !(substr($id,-5)=='false'); } /** @@ -185,10 +182,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) public function remove($id) { $this->_addLog('remove', array($id)); - if (substr($id,-5)=='false') { - return false; - } - return true; + return !(substr($id,-5)=='false'); } /** @@ -212,10 +206,7 @@ public function remove($id) public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) { $this->_addLog('clean', array($mode, $tags)); - if ($mode=='false') { - return false; - } - return true; + return !($mode=='false'); } /** @@ -410,7 +401,7 @@ private function _addLog($methodName, $args) 'methodName' => $methodName, 'args' => $args ); - $this->_index = $this->_index + 1; + $this->_index += 1; } } diff --git a/library/Zend/Cache/Backend/TwoLevels.php b/library/Zend/Cache/Backend/TwoLevels.php index 135ff6ad8d..5ee3517245 100644 --- a/library/Zend/Cache/Backend/TwoLevels.php +++ b/library/Zend/Cache/Backend/TwoLevels.php @@ -205,7 +205,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false, $pr $boolSlow = $this->_slowBackend->save($preparedData, $id, $tags, $lifetime); } else { $boolSlow = $this->_slowBackend->save($preparedData, $id, $tags, $lifetime); - if ($boolSlow === true) { + if ($boolSlow) { $boolFast = $this->_fastBackend->remove($id); if (!$boolFast && !$this->_fastBackend->test($id)) { // some backends return false on remove() even if the key never existed. (and it won't if fast is full) @@ -492,14 +492,7 @@ private function _prepareData($data, $lifetime, $priority) */ private function _getFastLifetime($lifetime, $priority, $maxLifetime = null) { - if ($lifetime <= 0) { - // if no lifetime, we have an infinite lifetime - // we need to use arbitrary lifetimes - $fastLifetime = (int) (2592000 / (11 - $priority)); - } else { - // prevent computed infinite lifetime (0) by ceil - $fastLifetime = (int) ceil($lifetime / (11 - $priority)); - } + $fastLifetime = $lifetime <= 0 ? (int) (2592000 / (11 - $priority)) : (int) ceil($lifetime / (11 - $priority)); if ($maxLifetime >= 0 && $fastLifetime > $maxLifetime) { return $maxLifetime; @@ -535,12 +528,8 @@ private function _getFastFillingPercentage($mode) $this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage(); } } - } else { - // mode loading - // we compute the percentage only if it's not available in cache - if ($this->_fastBackendFillingPercentage === null) { - $this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage(); - } + } elseif ($this->_fastBackendFillingPercentage === null) { + $this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage(); } return $this->_fastBackendFillingPercentage; } diff --git a/library/Zend/Cache/Backend/WinCache.php b/library/Zend/Cache/Backend/WinCache.php index 06843fa39a..dc4637f9e2 100644 --- a/library/Zend/Cache/Backend/WinCache.php +++ b/library/Zend/Cache/Backend/WinCache.php @@ -110,7 +110,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) { $lifetime = $this->getLifetime($specificLifetime); $result = wincache_ucache_set($id, array($data, time(), $lifetime), $lifetime); - if (count($tags) > 0) { + if ($tags !== []) { $this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_WINCACHE_BACKEND); } return $result; diff --git a/library/Zend/Cache/Backend/Xcache.php b/library/Zend/Cache/Backend/Xcache.php index 4bc077fc92..5d23e88d7d 100644 --- a/library/Zend/Cache/Backend/Xcache.php +++ b/library/Zend/Cache/Backend/Xcache.php @@ -132,7 +132,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) { $lifetime = $this->getLifetime($specificLifetime); $result = xcache_set($id, array($data, time()), $lifetime); - if (count($tags) > 0) { + if ($tags !== []) { $this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_XCACHE_BACKEND); } return $result; diff --git a/library/Zend/Cache/Backend/ZendPlatform.php b/library/Zend/Cache/Backend/ZendPlatform.php index 31e9a7a22a..4237c017b8 100644 --- a/library/Zend/Cache/Backend/ZendPlatform.php +++ b/library/Zend/Cache/Backend/ZendPlatform.php @@ -86,11 +86,7 @@ public function __construct(array $options = array()) public function load($id, $doNotTestCacheValidity = false) { // doNotTestCacheValidity implemented by giving zero lifetime to the cache - if ($doNotTestCacheValidity) { - $lifetime = 0; - } else { - $lifetime = $this->_directives['lifetime']; - } + $lifetime = $doNotTestCacheValidity ? 0 : $this->_directives['lifetime']; $res = output_cache_get($id, $lifetime); if($res) { return $res[0]; @@ -129,7 +125,7 @@ public function test($id) */ public function save($data, $id, $tags = array(), $specificLifetime = false) { - if (!($specificLifetime === false)) { + if ($specificLifetime !== false) { $this->_log("Zend_Cache_Backend_ZendPlatform::save() : non false specifc lifetime is unsuported for this backend"); } @@ -198,11 +194,7 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) $idlist = null; foreach ($tags as $tag) { $next_idlist = output_cache_get(self::TAGS_PREFIX.$tag, $this->_directives['lifetime']); - if ($idlist) { - $idlist = array_intersect_assoc($idlist, $next_idlist); - } else { - $idlist = $next_idlist; - } + $idlist = $idlist ? array_intersect_assoc($idlist, $next_idlist) : $next_idlist; if (count($idlist) == 0) { // if ID list is already empty - we may skip checking other IDs $idlist = null; @@ -224,11 +216,7 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) $idlist = null; foreach ($tags as $tag) { $next_idlist = output_cache_get(self::TAGS_PREFIX.$tag, $this->_directives['lifetime']); - if ($idlist) { - $idlist = array_merge_recursive($idlist, $next_idlist); - } else { - $idlist = $next_idlist; - } + $idlist = $idlist ? array_merge_recursive($idlist, $next_idlist) : $next_idlist; if (count($idlist) == 0) { // if ID list is already empty - we may skip checking other IDs $idlist = null; @@ -271,17 +259,10 @@ private function _clean($dir, $mode) $file = $d->path . $file; if (is_dir($file)) { $result = ($this->_clean($file .'/', $mode)) && ($result); - } else { - if ($mode == Zend_Cache::CLEANING_MODE_ALL) { - $result = ($this->_remove($file)) && ($result); - } else if ($mode == Zend_Cache::CLEANING_MODE_OLD) { - // Files older than lifetime get deleted from cache - if ($this->_directives['lifetime'] !== null) { - if ((time() - @filemtime($file)) > $this->_directives['lifetime']) { - $result = ($this->_remove($file)) && ($result); - } - } - } + } elseif ($mode == Zend_Cache::CLEANING_MODE_ALL) { + $result = ($this->_remove($file)) && ($result); + } elseif ($mode == Zend_Cache::CLEANING_MODE_OLD && $this->_directives['lifetime'] !== null && (time() - @filemtime($file)) > $this->_directives['lifetime']) { + $result = ($this->_remove($file)) && ($result); } } $d->close(); diff --git a/library/Zend/Cache/Backend/ZendServer.php b/library/Zend/Cache/Backend/ZendServer.php index ededaf5a9b..9c14f64217 100755 --- a/library/Zend/Cache/Backend/ZendServer.php +++ b/library/Zend/Cache/Backend/ZendServer.php @@ -146,7 +146,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) 'expire' => $this->_expireTime($lifetime), ); - if (count($tags) > 0) { + if ($tags !== []) { $this->_log('Zend_Cache_Backend_ZendServer::save() : tags are unsupported by the ZendServer backends'); } diff --git a/library/Zend/Cache/Backend/ZendServer/Disk.php b/library/Zend/Cache/Backend/ZendServer/Disk.php index 54914fefff..d16fb833f6 100755 --- a/library/Zend/Cache/Backend/ZendServer/Disk.php +++ b/library/Zend/Cache/Backend/ZendServer/Disk.php @@ -60,9 +60,9 @@ public function __construct(array $options = array()) */ protected function _store($data, $id, $timeToLive) { - if (zend_disk_cache_store($this->_options['namespace'] . '::' . $id, + if (!zend_disk_cache_store($this->_options['namespace'] . '::' . $id, $data, - $timeToLive) === false) { + $timeToLive)) { $this->_log('Store operation failed.'); return false; } diff --git a/library/Zend/Cache/Backend/ZendServer/ShMem.php b/library/Zend/Cache/Backend/ZendServer/ShMem.php index 83086dcd4e..ab1cb56545 100755 --- a/library/Zend/Cache/Backend/ZendServer/ShMem.php +++ b/library/Zend/Cache/Backend/ZendServer/ShMem.php @@ -60,9 +60,9 @@ public function __construct(array $options = array()) */ protected function _store($data, $id, $timeToLive) { - if (zend_shm_cache_store($this->_options['namespace'] . '::' . $id, + if (!zend_shm_cache_store($this->_options['namespace'] . '::' . $id, $data, - $timeToLive) === false) { + $timeToLive)) { $this->_log('Store operation failed.'); return false; } diff --git a/library/Zend/Cache/Core.php b/library/Zend/Cache/Core.php index 8c9d7070bc..34f21ad16d 100644 --- a/library/Zend/Cache/Core.php +++ b/library/Zend/Cache/Core.php @@ -140,8 +140,7 @@ public function __construct($options = array()) $options = $options->toArray(); } if (!is_array($options)) { - Zend_Cache::throwException("Options passed were not an array" - . " or Zend_Config instance."); + Zend_Cache::throwException('Options passed were not an array or Zend_Config instance.'); } foreach ($options as $name => $value) { $this->setOption($name, $value); @@ -350,20 +349,14 @@ public function save($data, $id = null, $tags = array(), $specificLifetime = fal if (!$this->_options['caching']) { return true; } - if ($id === null) { - $id = $this->_lastId; - } else { - $id = $this->_id($id); - } + $id = $id === null ? $this->_lastId : $this->_id($id); $this->_validateIdOrTag($id); $this->_validateTagsArray($tags); if ($this->_options['automatic_serialization']) { // we need to serialize datas before storing them $data = serialize($data); - } else { - if (!is_string($data)) { - Zend_Cache::throwException("Datas must be string or set automatic_serialization = true"); - } + } elseif (!is_string($data)) { + Zend_Cache::throwException("Datas must be string or set automatic_serialization = true"); } // automatic cleaning @@ -402,7 +395,7 @@ public function save($data, $id = null, $tags = array(), $specificLifetime = fal if ($this->_options['write_control']) { $data2 = $this->_backend->load($id, true); - if ($data!=$data2) { + if ($data != $data2) { $this->_log("Zend_Cache_Core::save(): write control of item '{$id}' failed -> removing it", 4); $this->_backend->remove($id); return false; @@ -675,7 +668,7 @@ protected function _validateIdOrTag($string) if (substr($string, 0, 9) == 'internal-') { Zend_Cache::throwException('"internal-*" ids or tags are reserved'); } - if (!preg_match('~^[a-zA-Z0-9_]+$~D', $string)) { + if (!preg_match('~^\w+$~D', $string)) { Zend_Cache::throwException("Invalid id or tag '$string' : must use only [a-zA-Z0-9_]"); } } @@ -739,7 +732,7 @@ protected function _log($message, $priority = 4) if (!$this->_options['logging']) { return; } - if (!(isset($this->_options['logger']) || $this->_options['logger'] instanceof Zend_Log)) { + if (!isset($this->_options['logger']) && !$this->_options['logger'] instanceof Zend_Log) { Zend_Cache::throwException('Logging is enabled but logger is not set'); } $logger = $this->_options['logger']; diff --git a/library/Zend/Cache/Frontend/Capture.php b/library/Zend/Cache/Frontend/Capture.php index 32ecc237ee..fece40e5f4 100644 --- a/library/Zend/Cache/Frontend/Capture.php +++ b/library/Zend/Cache/Frontend/Capture.php @@ -59,7 +59,9 @@ public function start($id, array $tags, $extension = null) { $this->_tags = $tags; $this->_extension = $extension; - ob_start(array($this, '_flush')); + ob_start(function (string $data) : string { + return $this->_flush($data); + }); ob_implicit_flush(false); $this->_idStack[] = $id; return false; diff --git a/library/Zend/Cache/Frontend/File.php b/library/Zend/Cache/Frontend/File.php index e5017c631c..7da051603e 100644 --- a/library/Zend/Cache/Frontend/File.php +++ b/library/Zend/Cache/Frontend/File.php @@ -110,11 +110,7 @@ public function setMasterFiles(array $masterFiles) clearstatcache(); $i = 0; foreach ($masterFiles as $masterFile) { - if (file_exists($masterFile)) { - $mtime = filemtime($masterFile); - } else { - $mtime = false; - } + $mtime = file_exists($masterFile) ? filemtime($masterFile) : false; if (!$this->_specificOptions['ignore_missing_master_files'] && !$mtime) { Zend_Cache::throwException('Unable to read master_file : ' . $masterFile); @@ -157,7 +153,7 @@ public function setOption($name, $value) { if ($name == 'master_file') { $this->setMasterFile($value); - } else if ($name == 'master_files') { + } elseif ($name == 'master_files') { $this->setMasterFiles($value); } else { parent::setOption($name, $value); @@ -196,20 +192,16 @@ public function test($id) if ($this->_specificOptions['master_files_mode'] == self::MODE_AND) { // MODE_AND foreach($this->_masterFile_mtimes as $masterFileMTime) { - if ($masterFileMTime) { - if ($lastModified > $masterFileMTime) { - return $lastModified; - } + if ($masterFileMTime && $lastModified > $masterFileMTime) { + return $lastModified; } } } else { // MODE_OR $res = true; foreach($this->_masterFile_mtimes as $masterFileMTime) { - if ($masterFileMTime) { - if ($lastModified <= $masterFileMTime) { - return false; - } + if ($masterFileMTime && $lastModified <= $masterFileMTime) { + return false; } } return $lastModified; diff --git a/library/Zend/Cache/Frontend/Function.php b/library/Zend/Cache/Frontend/Function.php index 8af521bda6..6d70f73aac 100644 --- a/library/Zend/Cache/Frontend/Function.php +++ b/library/Zend/Cache/Frontend/Function.php @@ -161,7 +161,7 @@ public function makeId($callback, array $args = array()) // generate a unique id for arguments $argsStr = ''; - if ($args) { + if ($args !== []) { try { $argsStr = @serialize(array_values($args)); } catch (Exception $e) { diff --git a/library/Zend/Cache/Frontend/Page.php b/library/Zend/Cache/Frontend/Page.php index 9239476f34..d6393ab5fe 100644 --- a/library/Zend/Cache/Frontend/Page.php +++ b/library/Zend/Cache/Frontend/Page.php @@ -145,10 +145,8 @@ public function __construct(array $options = array()) $this->setOption($name, $value); } } - if (isset($this->_specificOptions['http_conditional'])) { - if ($this->_specificOptions['http_conditional']) { - Zend_Cache::throwException('http_conditional is not implemented for the moment !'); - } + if (isset($this->_specificOptions['http_conditional']) && $this->_specificOptions['http_conditional']) { + Zend_Cache::throwException('http_conditional is not implemented for the moment !'); } $this->setOption('automatic_serialization', true); } @@ -195,10 +193,8 @@ protected function _setContentTypeMemorization($value) if (!$found) { $this->_specificOptions['memorize_headers'][] = 'Content-Type'; } - } else { - if ($found) { - unset($this->_specificOptions['memorize_headers'][$found]); - } + } elseif ($found) { + unset($this->_specificOptions['memorize_headers'][$found]); } } @@ -260,7 +256,7 @@ public function start($id = false, $doNotDie = false) if (!($this->_activeOptions['cache'])) { return false; } - if (!$id) { + if ($id === '' || $id === '0') { $id = $this->_makeId(); if (!$id) { return false; @@ -286,7 +282,9 @@ public function start($id = false, $doNotDie = false) } die(); } - ob_start(array($this, '_flush')); + ob_start(function (string $data) : string { + return $this->_flush($data); + }); ob_implicit_flush(false); return false; } @@ -318,7 +316,7 @@ public function _flush($data) foreach ($headersList as $headerSent) { $tmp = explode(':', (string) $headerSent); $headerSentName = trim(array_shift($tmp)); - if (strtolower($headerName) == strtolower($headerSentName)) { + if (strtolower($headerName) === strtolower($headerSentName)) { $headerSentValue = trim(implode(':', $tmp)); $storedHeaders[] = array($headerSentName, $headerSentValue); } @@ -347,7 +345,7 @@ protected function _makeId() if ($tmp2===false) { return false; } - $tmp = $tmp . $tmp2; + $tmp .= $tmp2; } return md5($tmp); } @@ -370,18 +368,10 @@ protected function _makePartialId($arrayName, $bool1, $bool2) $var = $_POST; break; case 'Session': - if (isset($_SESSION)) { - $var = $_SESSION; - } else { - $var = null; - } + $var = isset($_SESSION) ? $_SESSION : null; break; case 'Cookie': - if (isset($_COOKIE)) { - $var = $_COOKIE; - } else { - $var = null; - } + $var = isset($_COOKIE) ? $_COOKIE : null; break; case 'Files': $var = $_FILES; diff --git a/library/Zend/Cache/Manager.php b/library/Zend/Cache/Manager.php index 330ea954e8..02f87cd5f7 100644 --- a/library/Zend/Cache/Manager.php +++ b/library/Zend/Cache/Manager.php @@ -133,12 +133,8 @@ public function setCache($name, Zend_Cache_Core $cache) */ public function hasCache($name) { - if (isset($this->_caches[$name]) - || $this->hasCacheTemplate($name) - ) { - return true; - } - return false; + return isset($this->_caches[$name]) + || $this->hasCacheTemplate($name); } /** @@ -184,7 +180,7 @@ public function getCache($name) public function getCaches() { $caches = $this->_caches; - foreach ($this->_optionTemplates as $name => $tmp) { + foreach (array_keys($this->_optionTemplates) as $name) { if (!isset($caches[$name])) { $caches[$name] = $this->getCache($name); } @@ -207,8 +203,7 @@ public function setCacheTemplate($name, $options) $options = $options->toArray(); } elseif (!is_array($options)) { require_once 'Zend/Cache/Exception.php'; - throw new Zend_Cache_Exception('Options passed must be in' - . ' an associative array or instance of Zend_Config'); + throw new Zend_Cache_Exception('Options passed must be in an associative array or instance of Zend_Config'); } $this->_optionTemplates[$name] = $options; return $this; @@ -222,10 +217,7 @@ public function setCacheTemplate($name, $options) */ public function hasCacheTemplate($name) { - if (isset($this->_optionTemplates[$name])) { - return true; - } - return false; + return isset($this->_optionTemplates[$name]); } /** @@ -257,8 +249,7 @@ public function setTemplateOptions($name, $options) $options = $options->toArray(); } elseif (!is_array($options)) { require_once 'Zend/Cache/Exception.php'; - throw new Zend_Cache_Exception('Options passed must be in' - . ' an associative array or instance of Zend_Config'); + throw new Zend_Cache_Exception('Options passed must be in an associative array or instance of Zend_Config'); } if (!isset($this->_optionTemplates[$name])) { throw new Zend_Cache_Exception('A cache configuration template' diff --git a/library/Zend/Captcha/Base.php b/library/Zend/Captcha/Base.php index 69b2d21a66..6966e96a17 100644 --- a/library/Zend/Captcha/Base.php +++ b/library/Zend/Captcha/Base.php @@ -96,7 +96,7 @@ public function __construct($options = null) // Set options if (is_array($options)) { $this->setOptions($options); - } else if ($options instanceof Zend_Config) { + } elseif ($options instanceof Zend_Config) { $this->setConfig($options); } } diff --git a/library/Zend/Captcha/Image.php b/library/Zend/Captcha/Image.php index acc761b95d..5ecd385d7b 100644 --- a/library/Zend/Captcha/Image.php +++ b/library/Zend/Captcha/Image.php @@ -595,13 +595,9 @@ protected function _gc() } $suffixLength = strlen($this->_suffix); foreach (new DirectoryIterator($imgdir) as $file) { - if (!$file->isDot() && !$file->isDir()) { - if (file_exists($file->getPathname()) && $file->getMTime() < $expire) { - // only deletes files ending with $this->_suffix - if (substr($file->getFilename(), -($suffixLength)) == $this->_suffix) { - unlink($file->getPathname()); - } - } + // only deletes files ending with $this->_suffix + if (!$file->isDot() && !$file->isDir() && (file_exists($file->getPathname()) && $file->getMTime() < $expire) && substr($file->getFilename(), -($suffixLength)) === $this->_suffix) { + unlink($file->getPathname()); } } } diff --git a/library/Zend/Captcha/Word.php b/library/Zend/Captcha/Word.php index 80d8aecb57..1504d4cef8 100644 --- a/library/Zend/Captcha/Word.php +++ b/library/Zend/Captcha/Word.php @@ -261,7 +261,7 @@ public function setUseNumbers($_useNumbers) */ public function getSession() { - if (!isset($this->_session) || (null === $this->_session)) { + if (!($this->_session !== null) || (null === $this->_session)) { $id = $this->getId(); if (!class_exists($this->_sessionClass)) { require_once 'Zend/Loader.php'; @@ -331,7 +331,7 @@ protected function _generateWord() $totIndexCon = count($consonants) - 1; $totIndexVow = count($vowels) - 1; - for ($i=0; $i < $wordLen; $i = $i + 2) { + for ($i=0; $i < $wordLen; $i += 2) { // generate word with mix of vowels and consonants $consonant = $consonants[Zend_Crypt_Math::randInteger(0, $totIndexCon, true)]; $vowel = $vowels[Zend_Crypt_Math::randInteger(0, $totIndexVow, true)]; diff --git a/library/Zend/Cloud/DocumentService/Adapter/SimpleDb.php b/library/Zend/Cloud/DocumentService/Adapter/SimpleDb.php index 0bf4d6d0a5..2957f54b59 100644 --- a/library/Zend/Cloud/DocumentService/Adapter/SimpleDb.php +++ b/library/Zend/Cloud/DocumentService/Adapter/SimpleDb.php @@ -160,8 +160,7 @@ public function listCollections($options = null) public function listDocuments($collectionName, array $options = null) { $query = $this->select('*')->from($collectionName); - $items = $this->query($collectionName, $query, $options); - return $items; + return $this->query($collectionName, $query, $options); } /** diff --git a/library/Zend/Cloud/DocumentService/Adapter/WindowsAzure.php b/library/Zend/Cloud/DocumentService/Adapter/WindowsAzure.php index 75126dd6ed..707bc4e009 100755 --- a/library/Zend/Cloud/DocumentService/Adapter/WindowsAzure.php +++ b/library/Zend/Cloud/DocumentService/Adapter/WindowsAzure.php @@ -107,11 +107,7 @@ public function __construct($options = array()) } // Build Zend_Service_WindowsAzure_Storage_Blob instance - if (!isset($options[self::HOST])) { - $host = self::DEFAULT_HOST; - } else { - $host = $options[self::HOST]; - } + $host = isset($options[self::HOST]) ? $options[self::HOST] : self::DEFAULT_HOST; if (! isset($options[self::ACCOUNT_NAME])) { throw new Zend_Cloud_DocumentService_Exception('No Windows Azure account name provided.'); @@ -360,7 +356,7 @@ public function updateDocument($collectionName, $documentId, $fieldset = null, $ $fieldset = $fieldset->getFields(); } - $this->_validateCompositeKey($documentId, $collectionName); + $this->_validateCompositeKey($documentId); $this->_validateFields($fieldset); try { $entity = new Zend_Service_WindowsAzure_Storage_DynamicTableEntity($documentId[0], $documentId[1]); @@ -525,7 +521,7 @@ protected function _resolveAttributes(Zend_Service_WindowsAzure_Storage_TableEnt */ protected function _validateKey($key) { - if (preg_match('@[/#?' . preg_quote('\\') . ']@', $key)) { + if (preg_match('@[/#?' . preg_quote('\\', '@') . ']@', $key)) { throw new Zend_Cloud_DocumentService_Exception('Invalid partition or row key provided; must not contain /, \\, #, or ? characters'); } } diff --git a/library/Zend/Cloud/DocumentService/Query.php b/library/Zend/Cloud/DocumentService/Query.php index 24ac3a5135..061aaed755 100644 --- a/library/Zend/Cloud/DocumentService/Query.php +++ b/library/Zend/Cloud/DocumentService/Query.php @@ -146,7 +146,7 @@ public function whereId($value) */ public function limit($limit) { - if ($limit != (int) $limit) { + if ($limit !== (int) $limit) { require_once 'Zend/Cloud/DocumentService/Exception.php'; throw new Zend_Cloud_DocumentService_Exception("LIMIT argument must be an integer"); } diff --git a/library/Zend/Cloud/Infrastructure/Adapter/AbstractAdapter.php b/library/Zend/Cloud/Infrastructure/Adapter/AbstractAdapter.php index ecdef16eb1..bcbe1c89f8 100644 --- a/library/Zend/Cloud/Infrastructure/Adapter/AbstractAdapter.php +++ b/library/Zend/Cloud/Infrastructure/Adapter/AbstractAdapter.php @@ -78,7 +78,7 @@ public function waitStatusInstance($id, $status, $timeout = self::TIMEOUT_STATUS } $num = 0; - while (($num<$timeout) && ($this->statusInstance($id) != $status)) { + while (($num<$timeout) && ($this->statusInstance($id) !== $status)) { sleep(self::TIME_STEP_STATUS_CHANGE); $num += self::TIME_STEP_STATUS_CHANGE; } @@ -147,11 +147,7 @@ public function deployInstance($id, $params, $cmd) $output = stream_get_contents($stream); $error = stream_get_contents($errorStream); - if (empty($error)) { - $result[$command] = $output; - } else { - $result[$command] = $error; - } + $result[$command] = empty($error) ? $output : $error; } } else { $stream = ssh2_exec($conn, $cmd); @@ -164,11 +160,7 @@ public function deployInstance($id, $params, $cmd) $output = stream_get_contents($stream); $error = stream_get_contents($errorStream); - if (empty($error)) { - $result = $output; - } else { - $result = $error; - } + $result = empty($error) ? $output : $error; } return $result; } diff --git a/library/Zend/Cloud/Infrastructure/Adapter/Ec2.php b/library/Zend/Cloud/Infrastructure/Adapter/Ec2.php index 48fdac5835..bfbb12e9e9 100644 --- a/library/Zend/Cloud/Infrastructure/Adapter/Ec2.php +++ b/library/Zend/Cloud/Infrastructure/Adapter/Ec2.php @@ -27,6 +27,7 @@ */ class Zend_Cloud_Infrastructure_Adapter_Ec2 extends Zend_Cloud_Infrastructure_Adapter_AbstractAdapter { + public bool $error; /** * AWS constants */ @@ -333,7 +334,7 @@ public function destroyInstance($id) */ public function imagesInstance() { - if (!isset($this->ec2Image)) { + if (!($this->ec2Image !== null)) { $this->ec2Image = new Zend_Service_Amazon_Ec2_Image($this->accessKey, $this->accessSecret, $this->region); } @@ -370,7 +371,7 @@ public function imagesInstance() */ public function zonesInstance() { - if (!isset($this->ec2Zone)) { + if (!($this->ec2Zone !== null)) { $this->ec2Zone = new Zend_Service_Amazon_Ec2_Availabilityzones($this->accessKey,$this->accessSecret,$this->region); } $this->adapterResult = $this->ec2Zone->describe(); @@ -425,7 +426,7 @@ public function monitorInstance($id, $metric, $options = null) )); } - if (!isset($this->ec2Monitor)) { + if (!($this->ec2Monitor !== null)) { $this->ec2Monitor = new Zend_Service_Amazon_Ec2_CloudWatch($this->accessKey, $this->accessSecret, $this->region); } diff --git a/library/Zend/Cloud/Infrastructure/ImageList.php b/library/Zend/Cloud/Infrastructure/ImageList.php index 21e3a89bf0..1ce3e3dfd9 100644 --- a/library/Zend/Cloud/Infrastructure/ImageList.php +++ b/library/Zend/Cloud/Infrastructure/ImageList.php @@ -150,10 +150,7 @@ public function rewind() public function valid() { $numItems = $this->count(); - if ($numItems > 0 && $this->iteratorKey < $numItems) { - return true; - } - return false; + return $numItems > 0 && $this->iteratorKey < $numItems; } /** diff --git a/library/Zend/Cloud/Infrastructure/InstanceList.php b/library/Zend/Cloud/Infrastructure/InstanceList.php index 02ff7b2856..633e0c76ca 100644 --- a/library/Zend/Cloud/Infrastructure/InstanceList.php +++ b/library/Zend/Cloud/Infrastructure/InstanceList.php @@ -151,10 +151,7 @@ public function rewind() public function valid() { $numItems = $this->count(); - if ($numItems > 0 && $this->iteratorKey < $numItems) { - return true; - } - return false; + return $numItems > 0 && $this->iteratorKey < $numItems; } /** diff --git a/library/Zend/Cloud/QueueService/Adapter/WindowsAzure.php b/library/Zend/Cloud/QueueService/Adapter/WindowsAzure.php index 656dddb6b6..7998fed366 100755 --- a/library/Zend/Cloud/QueueService/Adapter/WindowsAzure.php +++ b/library/Zend/Cloud/QueueService/Adapter/WindowsAzure.php @@ -84,11 +84,7 @@ public function __construct($options = array()) } // Build Zend_Service_WindowsAzure_Storage_Blob instance - if (!isset($options[self::HOST])) { - $host = self::DEFAULT_HOST; - } else { - $host = $options[self::HOST]; - } + $host = isset($options[self::HOST]) ? $options[self::HOST] : self::DEFAULT_HOST; if (! isset($options[self::ACCOUNT_NAME])) { throw new Zend_Cloud_Storage_Exception('No Windows Azure account name provided.'); } @@ -256,11 +252,7 @@ public function receiveMessages($queueId, $max = 1, $options = null) if ($queueId instanceof Zend_Service_WindowsAzure_Storage_QueueInstance) { $queueId = $queueId->Name; } - if (isset($options[self::VISIBILITY_TIMEOUT])) { - $visibility = $options[self::VISIBILITY_TIMEOUT]; - } else { - $visibility = self::DEFAULT_TIMEOUT; - } + $visibility = isset($options[self::VISIBILITY_TIMEOUT]) ? $options[self::VISIBILITY_TIMEOUT] : self::DEFAULT_TIMEOUT; return $this->_makeMessages($this->_storageClient->getMessages($queueId, $max, $visibility, false)); } catch (Zend_Service_WindowsAzure_Exception $e) { throw new Zend_Cloud_QueueService_Exception('Error on recieving messages: '.$e->getMessage(), $e->getCode(), $e); diff --git a/library/Zend/Cloud/StorageService/Adapter/Rackspace.php b/library/Zend/Cloud/StorageService/Adapter/Rackspace.php index 02980d0c36..8e63546ec9 100644 --- a/library/Zend/Cloud/StorageService/Adapter/Rackspace.php +++ b/library/Zend/Cloud/StorageService/Adapter/Rackspace.php @@ -91,7 +91,7 @@ function __construct($options = array()) public function fetchItem($path, $options = null) { $item = $this->_rackspace->getObject($this->_container,$path, $options); - if (!$this->_rackspace->isSuccessful() && ($this->_rackspace->getErrorCode()!='404')) { + if (!$this->_rackspace->isSuccessful() && ($this->_rackspace->getErrorCode() != '404')) { throw new Zend_Cloud_StorageService_Exception('Error on fetch: '.$this->_rackspace->getErrorMsg()); } if (!empty($item)) { @@ -163,13 +163,13 @@ public function moveItem($sourcePath, $destinationPath, $options = null) try { $this->copyItem($sourcePath, $destinationPath, $options); } catch (Zend_Service_Rackspace_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on move: '.$e->getMessage()); + throw new Zend_Cloud_StorageService_Exception('Error on move: '.$e->getMessage(), $e->getCode(), $e); } try { $this->deleteItem($sourcePath); } catch (Zend_Service_Rackspace_Exception $e) { $this->deleteItem($destinationPath); - throw new Zend_Cloud_StorageService_Exception('Error on move: '.$e->getMessage()); + throw new Zend_Cloud_StorageService_Exception('Error on move: '.$e->getMessage(), $e->getCode(), $e); } } @@ -247,19 +247,19 @@ public function deleteMetadata($path, $metadata = null, $options = null) try { $this->storeMetadata($path, $newMetadata); } catch (Zend_Service_Rackspace_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on delete metadata: '.$e->getMessage()); + throw new Zend_Cloud_StorageService_Exception('Error on delete metadata: '.$e->getMessage(), $e->getCode(), $e); } } else { try { $oldMetadata = $this->fetchMetadata($path); } catch (Zend_Service_Rackspace_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on delete metadata: '.$e->getMessage()); + throw new Zend_Cloud_StorageService_Exception('Error on delete metadata: '.$e->getMessage(), $e->getCode(), $e); } $newMetadata = array_diff_assoc($oldMetadata, $metadata); try { $this->storeMetadata($path, $newMetadata); } catch (Zend_Service_Rackspace_Exception $e) { - throw new Zend_Cloud_StorageService_Exception('Error on delete metadata: '.$e->getMessage()); + throw new Zend_Cloud_StorageService_Exception('Error on delete metadata: '.$e->getMessage(), $e->getCode(), $e); } } } diff --git a/library/Zend/Cloud/StorageService/Adapter/S3.php b/library/Zend/Cloud/StorageService/Adapter/S3.php index 05ec1405d4..c828e93e61 100644 --- a/library/Zend/Cloud/StorageService/Adapter/S3.php +++ b/library/Zend/Cloud/StorageService/Adapter/S3.php @@ -304,7 +304,7 @@ protected function _getFullPath($path, $options) { if (isset($options[self::BUCKET_NAME])) { $bucket = $options[self::BUCKET_NAME]; - } else if (isset($this->_defaultBucketName)) { + } elseif ($this->_defaultBucketName !== null) { $bucket = $this->_defaultBucketName; } else { require_once 'Zend/Cloud/StorageService/Exception.php'; diff --git a/library/Zend/Cloud/StorageService/Adapter/WindowsAzure.php b/library/Zend/Cloud/StorageService/Adapter/WindowsAzure.php index 618f463c24..01fa14d390 100644 --- a/library/Zend/Cloud/StorageService/Adapter/WindowsAzure.php +++ b/library/Zend/Cloud/StorageService/Adapter/WindowsAzure.php @@ -86,11 +86,7 @@ public function __construct($options = array()) } // Build Zend_Service_WindowsAzure_Storage_Blob instance - if (!isset($options[self::HOST])) { - $host = self::DEFAULT_HOST; - } else { - $host = $options[self::HOST]; - } + $host = isset($options[self::HOST]) ? $options[self::HOST] : self::DEFAULT_HOST; if (!isset($options[self::ACCOUNT_NAME])) { throw new Zend_Cloud_StorageService_Exception('No Windows Azure account name provided.'); diff --git a/library/Zend/CodeGenerator/Php/Abstract.php b/library/Zend/CodeGenerator/Php/Abstract.php index fc4e4bfd05..85c01271dd 100644 --- a/library/Zend/CodeGenerator/Php/Abstract.php +++ b/library/Zend/CodeGenerator/Php/Abstract.php @@ -58,7 +58,7 @@ abstract class Zend_CodeGenerator_Php_Abstract extends Zend_CodeGenerator_Abstra */ public function setSourceDirty($isSourceDirty = true) { - $this->_isSourceDirty = ($isSourceDirty) ? true : false; + $this->_isSourceDirty = $isSourceDirty; return $this; } diff --git a/library/Zend/CodeGenerator/Php/Class.php b/library/Zend/CodeGenerator/Php/Class.php index 02d5210172..4381c3c306 100644 --- a/library/Zend/CodeGenerator/Php/Class.php +++ b/library/Zend/CodeGenerator/Php/Class.php @@ -210,7 +210,7 @@ public function getName() */ public function setAbstract($isAbstract) { - $this->_isAbstract = ($isAbstract) ? true : false; + $this->_isAbstract = $isAbstract; return $this; } @@ -599,9 +599,7 @@ public function generate() } } - $output .= self::LINE_FEED . '}' . self::LINE_FEED; - - return $output; + return $output . (self::LINE_FEED . '}' . self::LINE_FEED); } /** diff --git a/library/Zend/CodeGenerator/Php/Docblock.php b/library/Zend/CodeGenerator/Php/Docblock.php index fe5ecfd96a..c97aebd5e6 100644 --- a/library/Zend/CodeGenerator/Php/Docblock.php +++ b/library/Zend/CodeGenerator/Php/Docblock.php @@ -213,15 +213,13 @@ protected function _docCommentize($content) foreach ($lines as $line) { $output .= $indent . ' *'; - if ($line) { + if ($line !== '' && $line !== '0') { $output .= " $line"; } $output .= self::LINE_FEED; } $output = rtrim($output, ' *' . self::LINE_FEED) . self::LINE_FEED; - - $output .= $indent . ' */' . self::LINE_FEED; - return $output; + return $output . ($indent . ' */' . self::LINE_FEED); } } diff --git a/library/Zend/CodeGenerator/Php/Docblock/Tag.php b/library/Zend/CodeGenerator/Php/Docblock/Tag.php index bfb6c3a5df..a7ae36af71 100644 --- a/library/Zend/CodeGenerator/Php/Docblock/Tag.php +++ b/library/Zend/CodeGenerator/Php/Docblock/Tag.php @@ -112,9 +112,7 @@ public static function factory($tagName) } catch (Zend_Loader_Exception $exception) { $tagClass = 'Zend_CodeGenerator_Php_Docblock_Tag'; } - - $tag = new $tagClass(array('name' => $tagName)); - return $tag; + return new $tagClass(array('name' => $tagName)); } /** @@ -169,7 +167,7 @@ public function getDescription() public function generate() { $tag = '@' . $this->_name; - if ($this->_description) { + if ($this->_description !== '' && $this->_description !== '0') { $tag .= ' ' . $this->_description; } return $tag; diff --git a/library/Zend/CodeGenerator/Php/Docblock/Tag/License.php b/library/Zend/CodeGenerator/Php/Docblock/Tag/License.php index 9642e6df5e..f09f0d7f5e 100644 --- a/library/Zend/CodeGenerator/Php/Docblock/Tag/License.php +++ b/library/Zend/CodeGenerator/Php/Docblock/Tag/License.php @@ -91,8 +91,7 @@ public function getUrl() */ public function generate() { - $output = '@license ' . $this->_url . ' ' . $this->_description . self::LINE_FEED; - return $output; + return '@license ' . $this->_url . ' ' . $this->_description . self::LINE_FEED; } } diff --git a/library/Zend/CodeGenerator/Php/Docblock/Tag/Param.php b/library/Zend/CodeGenerator/Php/Docblock/Tag/Param.php index 64ff2f72e0..11effdfcb5 100644 --- a/library/Zend/CodeGenerator/Php/Docblock/Tag/Param.php +++ b/library/Zend/CodeGenerator/Php/Docblock/Tag/Param.php @@ -118,11 +118,10 @@ public function getParamName() */ public function generate() { - $output = '@param ' - . (($this->_datatype != null) ? $this->_datatype : 'unknown') + return '@param ' + . (($this->_datatype != null) ? $this->_datatype : 'unknown') . (($this->_paramName != null) ? ' $' . $this->_paramName : '') . (($this->_description != null) ? ' ' . $this->_description : ''); - return $output; } } diff --git a/library/Zend/CodeGenerator/Php/Docblock/Tag/Return.php b/library/Zend/CodeGenerator/Php/Docblock/Tag/Return.php index 60dcf30041..e0bb55fd1a 100644 --- a/library/Zend/CodeGenerator/Php/Docblock/Tag/Return.php +++ b/library/Zend/CodeGenerator/Php/Docblock/Tag/Return.php @@ -91,8 +91,7 @@ public function getDatatype() */ public function generate() { - $output = '@return ' . $this->_datatype . ' ' . $this->_description; - return $output; + return '@return ' . $this->_datatype . ' ' . $this->_description; } } diff --git a/library/Zend/CodeGenerator/Php/File.php b/library/Zend/CodeGenerator/Php/File.php index cfea53dbe4..3346d58db2 100644 --- a/library/Zend/CodeGenerator/Php/File.php +++ b/library/Zend/CodeGenerator/Php/File.php @@ -109,11 +109,9 @@ public static function fromReflectedFileName($filePath, $usePreviousCodeGenerato { $realpath = realpath($filePath); - if ($realpath === false) { - if ( ($realpath = Zend_Reflection_File::findRealpathInIncludePath($filePath)) === false) { - require_once 'Zend/CodeGenerator/Php/Exception.php'; - throw new Zend_CodeGenerator_Php_Exception('No file for ' . $realpath . ' was found.'); - } + if ($realpath === false && ($realpath = Zend_Reflection_File::findRealpathInIncludePath($filePath)) === false) { + require_once 'Zend/CodeGenerator/Php/Exception.php'; + throw new Zend_CodeGenerator_Php_Exception('No file for ' . $realpath . ' was found.'); } if ($usePreviousCodeGeneratorIfItExists && isset(self::$_fileCodeGenerators[$realpath])) { @@ -156,7 +154,8 @@ public static function fromReflection(Zend_Reflection_File $reflectionFile) $bodyLines = explode("\n", $body); $bodyReturn = array(); - for ($lineNum = 1; $lineNum <= count($bodyLines); $lineNum++) { + $bodyLinesCount = count($bodyLines); + for ($lineNum = 1; $lineNum <= $bodyLinesCount; $lineNum++) { if ($lineNum == $classStartLine) { $bodyReturn[] = str_replace('?', $class->getName(), self::$_markerClass); //'/* Zend_CodeGenerator_Php_File-ClassMarker: {' . $class->getName() . '} */'; $lineNum = $classEndLine; @@ -174,8 +173,9 @@ public static function fromReflection(Zend_Reflection_File $reflectionFile) $bodyLines = explode("\n", $body); $bodyReturn = array(); - for ($lineNum = 1; $lineNum <= count($bodyLines); $lineNum++) { - if ($lineNum == $docblock->getStartLine()) { + $bodyLinesCount = count($bodyLines); + for ($lineNum = 1; $lineNum <= $bodyLinesCount; $lineNum++) { + if ($lineNum === $docblock->getStartLine()) { $bodyReturn[] = str_replace('?', $class->getName(), self::$_markerDocblock); //'/* Zend_CodeGenerator_Php_File-ClassMarker: {' . $class->getName() . '} */'; $lineNum = $docblock->getEndLine(); } else { @@ -381,7 +381,7 @@ public function isSourceDirty() */ public function generate() { - if ($this->isSourceDirty() === false) { + if (!$this->isSourceDirty()) { return $this->_sourceContent; } diff --git a/library/Zend/CodeGenerator/Php/Member/Abstract.php b/library/Zend/CodeGenerator/Php/Member/Abstract.php index 4875242a6b..1731867b43 100644 --- a/library/Zend/CodeGenerator/Php/Member/Abstract.php +++ b/library/Zend/CodeGenerator/Php/Member/Abstract.php @@ -118,7 +118,7 @@ public function getDocblock() */ public function setAbstract($isAbstract) { - $this->_isAbstract = ($isAbstract) ? true : false; + $this->_isAbstract = $isAbstract; return $this; } @@ -139,7 +139,7 @@ public function isAbstract() */ public function setFinal($isFinal) { - $this->_isFinal = ($isFinal) ? true : false; + $this->_isFinal = $isFinal; return $this; } @@ -161,7 +161,7 @@ public function isFinal() */ public function setStatic($isStatic) { - $this->_isStatic = ($isStatic) ? true : false; + $this->_isStatic = $isStatic; return $this; } diff --git a/library/Zend/CodeGenerator/Php/Method.php b/library/Zend/CodeGenerator/Php/Method.php index 26c498bb5c..ae4eeba495 100644 --- a/library/Zend/CodeGenerator/Php/Method.php +++ b/library/Zend/CodeGenerator/Php/Method.php @@ -110,7 +110,7 @@ public static function fromReflection(Zend_Reflection_Method $reflectionMethod) */ public function setFinal($isFinal) { - $this->_isFinal = ($isFinal) ? true : false; + $this->_isFinal = $isFinal; return $this; } @@ -225,13 +225,11 @@ public function generate() $output .= ' ' . str_replace(self::LINE_FEED, self::LINE_FEED . $indent . $indent, trim($this->_body)) . self::LINE_FEED; - } elseif ($this->_body) { + } elseif ($this->_body !== '' && $this->_body !== '0') { $output .= $this->_body . self::LINE_FEED; } - $output .= $indent . '}' . self::LINE_FEED; - - return $output; + return $output . ($indent . '}' . self::LINE_FEED); } } diff --git a/library/Zend/CodeGenerator/Php/Parameter.php b/library/Zend/CodeGenerator/Php/Parameter.php index ce62706e5a..646aef2d30 100644 --- a/library/Zend/CodeGenerator/Php/Parameter.php +++ b/library/Zend/CodeGenerator/Php/Parameter.php @@ -147,12 +147,12 @@ public function getName() */ public function setDefaultValue($defaultValue) { - if($defaultValue === null) { + if ($defaultValue === null) { $this->_defaultValue = new Zend_CodeGenerator_Php_Parameter_DefaultValue("null"); - } else if(is_array($defaultValue)) { + } elseif (is_array($defaultValue)) { $defaultValue = str_replace(array("\r", "\n"), "", var_export($defaultValue, true)); $this->_defaultValue = new Zend_CodeGenerator_Php_Parameter_DefaultValue($defaultValue); - } else if(is_bool($defaultValue)) { + } elseif (is_bool($defaultValue)) { if($defaultValue == true) { $this->_defaultValue = new Zend_CodeGenerator_Php_Parameter_DefaultValue("true"); } else { @@ -223,11 +223,11 @@ public function generate() { $output = ''; - if ($this->_type) { + if ($this->_type !== '' && $this->_type !== '0') { $output .= $this->_type . ' '; } - if($this->_passedByReference === true) { + if($this->_passedByReference) { $output .= '&'; } @@ -237,7 +237,7 @@ public function generate() $output .= ' = '; if (is_string($this->_defaultValue)) { $output .= '\'' . $this->_defaultValue . '\''; - } else if($this->_defaultValue instanceof Zend_CodeGenerator_Php_Parameter_DefaultValue) { + } elseif ($this->_defaultValue instanceof Zend_CodeGenerator_Php_Parameter_DefaultValue) { $output .= (string)$this->_defaultValue; } else { $output .= $this->_defaultValue; diff --git a/library/Zend/CodeGenerator/Php/Property.php b/library/Zend/CodeGenerator/Php/Property.php index af5408f91d..a28f47c5e5 100644 --- a/library/Zend/CodeGenerator/Php/Property.php +++ b/library/Zend/CodeGenerator/Php/Property.php @@ -105,7 +105,7 @@ public function setConst($const) */ public function isConst() { - return ($this->_isConst) ? true : false; + return $this->_isConst; } /** diff --git a/library/Zend/CodeGenerator/Php/Property/DefaultValue.php b/library/Zend/CodeGenerator/Php/Property/DefaultValue.php index 1eeed9576f..6a59533d44 100644 --- a/library/Zend/CodeGenerator/Php/Property/DefaultValue.php +++ b/library/Zend/CodeGenerator/Php/Property/DefaultValue.php @@ -92,11 +92,7 @@ protected function _init() */ public function isValidConstantType() { - if ($this->_type == self::TYPE_AUTO) { - $type = $this->_getAutoDeterminedType($this->_value); - } else { - $type = $this->_type; - } + $type = $this->_type == self::TYPE_AUTO ? $this->_getAutoDeterminedType($this->_value) : $this->_type; // valid types for constants $scalarTypes = array( @@ -318,8 +314,6 @@ public function generate() ); } - $output .= ';'; - - return $output; + return $output . ';'; } } diff --git a/library/Zend/Config.php b/library/Zend/Config.php index a39a1f2255..85dafcff18 100644 --- a/library/Zend/Config.php +++ b/library/Zend/Config.php @@ -109,11 +109,7 @@ public function __construct(array $array, $allowModifications = false) $this->_index = 0; $this->_data = array(); foreach ($array as $key => $value) { - if (is_array($value)) { - $this->_data[$key] = new self($value, $this->_allowModifications); - } else { - $this->_data[$key] = $value; - } + $this->_data[$key] = is_array($value) ? new self($value, $this->_allowModifications) : $value; } $this->_count = count($this->_data); } @@ -157,11 +153,7 @@ public function __get($name) public function __set($name, $value) { if ($this->_allowModifications) { - if (is_array($value)) { - $this->_data[$name] = new self($value, true); - } else { - $this->_data[$name] = $value; - } + $this->_data[$name] = is_array($value) ? new self($value, true) : $value; $this->_count = count($this->_data); } else { /** @see Zend_Config_Exception */ @@ -180,11 +172,7 @@ public function __clone() { $array = array(); foreach ($this->_data as $key => $value) { - if ($value instanceof Zend_Config) { - $array[$key] = clone $value; - } else { - $array[$key] = $value; - } + $array[$key] = $value instanceof Zend_Config ? clone $value : $value; } $this->_data = $array; } @@ -199,11 +187,7 @@ public function toArray() $array = array(); $data = $this->_data; foreach ($data as $key => $value) { - if ($value instanceof Zend_Config) { - $array[$key] = $value->toArray(); - } else { - $array[$key] = $value; - } + $array[$key] = $value instanceof Zend_Config ? $value->toArray() : $value; } return $array; } @@ -245,7 +229,7 @@ public function __unset($name) * * @return int */ - public function count() + public function count(): int { return $this->_count; } @@ -255,7 +239,7 @@ public function count() * * @return mixed */ - public function current() + public function current(): mixed { $this->_skipNextIteration = false; return current($this->_data); @@ -266,7 +250,7 @@ public function current() * * @return mixed */ - public function key() + public function key(): mixed { return key($this->_data); } @@ -275,7 +259,7 @@ public function key() * Defined by Iterator interface * */ - public function next() + public function next(): void { if ($this->_skipNextIteration) { $this->_skipNextIteration = false; @@ -289,7 +273,7 @@ public function next() * Defined by Iterator interface * */ - public function rewind() + public function rewind(): void { $this->_skipNextIteration = false; reset($this->_data); @@ -301,7 +285,7 @@ public function rewind() * * @return boolean */ - public function valid() + public function valid(): bool { return $this->_index < $this->_count; } @@ -348,11 +332,7 @@ public function merge(Zend_Config $merge) $this->$key = $item; } } else { - if($item instanceof Zend_Config) { - $this->$key = new Zend_Config($item->toArray(), !$this->readOnly()); - } else { - $this->$key = $item; - } + $this->$key = $item instanceof Zend_Config ? new Zend_Config($item->toArray(), !$this->readOnly()) : $item; } } @@ -406,7 +386,7 @@ public function setExtend($extendingSection, $extendedSection = null) { if ($extendedSection === null && isset($this->_extends[$extendingSection])) { unset($this->_extends[$extendingSection]); - } else if ($extendedSection !== null) { + } elseif ($extendedSection !== null) { $this->_extends[$extendingSection] = $extendedSection; } } @@ -467,12 +447,10 @@ protected function _arrayMergeRecursive($firstArray, $secondArray) foreach ($secondArray as $key => $value) { if (isset($firstArray[$key])) { $firstArray[$key] = $this->_arrayMergeRecursive($firstArray[$key], $value); + } elseif ($key === 0) { + $firstArray= array(0=>$this->_arrayMergeRecursive($firstArray, $value)); } else { - if($key === 0) { - $firstArray= array(0=>$this->_arrayMergeRecursive($firstArray, $value)); - } else { - $firstArray[$key] = $value; - } + $firstArray[$key] = $value; } } } else { diff --git a/library/Zend/Config/Ini.php b/library/Zend/Config/Ini.php index cc9fffa99d..8786755868 100644 --- a/library/Zend/Config/Ini.php +++ b/library/Zend/Config/Ini.php @@ -169,7 +169,9 @@ public function __construct($filename, $section = null, $options = false) */ protected function _parseIniFile($filename) { - set_error_handler(array($this, '_loadFileErrorHandler')); + set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline) { + return $this->_loadFileErrorHandler($errno, $errstr, $errfile, $errline); + }); $iniArray = parse_ini_file($filename, true); // Warnings and errors are suppressed restore_error_handler(); diff --git a/library/Zend/Config/Json.php b/library/Zend/Config/Json.php index 2c31fdc014..a38766f194 100755 --- a/library/Zend/Config/Json.php +++ b/library/Zend/Config/Json.php @@ -110,7 +110,9 @@ public function __construct($json, $section = null, $options = false) } } - set_error_handler(array($this, '_loadFileErrorHandler')); // Warnings and errors are suppressed + set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline) { + return $this->_loadFileErrorHandler($errno, $errstr, $errfile, $errline); + }); // Warnings and errors are suppressed if ($json[0] != '{') { $json = file_get_contents($json); } @@ -133,7 +135,7 @@ public function __construct($json, $section = null, $options = false) } catch (Zend_Json_Exception $e) { // decode failed require_once 'Zend/Config/Exception.php'; - throw new Zend_Config_Exception("Error parsing JSON data"); + throw new Zend_Config_Exception("Error parsing JSON data", $e->getCode(), $e); } if ($section === null) { @@ -205,9 +207,7 @@ protected function _processExtends(array $data, $section, array $config = array( unset($thisSection[self::EXTENDS_NAME]); } - $config = $this->_arrayMergeRecursive($config, $thisSection); - - return $config; + return $this->_arrayMergeRecursive($config, $thisSection); } /** diff --git a/library/Zend/Config/Writer/Array.php b/library/Zend/Config/Writer/Array.php index 50c260e0cf..b88d5479aa 100644 --- a/library/Zend/Config/Writer/Array.php +++ b/library/Zend/Config/Writer/Array.php @@ -47,9 +47,7 @@ public function render() $data = array($sectionName => $data); } - $arrayString = "_config->getExtends(); $sectionName = $this->_config->getSectionName(); - if($this->_renderWithoutSections == true) { + if ($this->_renderWithoutSections == true) { $iniString .= $this->_addBranch($this->_config); - } else if (is_string($sectionName)) { + } elseif (is_string($sectionName)) { $iniString .= '[' . $sectionName . ']' . "\n" . $this->_addBranch($this->_config) . "\n"; @@ -148,7 +148,7 @@ protected function _addBranch(Zend_Config $config, $parents = array()) */ protected function _prepareValue($value) { - if (is_integer($value) || is_float($value)) { + if (is_int($value) || is_float($value)) { return $value; } elseif (is_bool($value)) { return ($value ? 'true' : 'false'); diff --git a/library/Zend/Config/Writer/Xml.php b/library/Zend/Config/Writer/Xml.php index c73564b219..b3b3aed763 100644 --- a/library/Zend/Config/Writer/Xml.php +++ b/library/Zend/Config/Writer/Xml.php @@ -72,9 +72,7 @@ public function render() $dom = dom_import_simplexml($xml)->ownerDocument; $dom->formatOutput = true; - $xmlString = $dom->saveXML(); - - return $xmlString; + return $dom->saveXML(); } /** @@ -100,7 +98,7 @@ protected function _addBranch(Zend_Config $config, SimpleXMLElement $xml, Simple } else { $branchType = 'string'; } - } else if ($branchType !== (is_numeric($key) ? 'numeric' : 'string')) { + } elseif ($branchType !== (is_numeric($key) ? 'numeric' : 'string')) { require_once 'Zend/Config/Exception.php'; throw new Zend_Config_Exception('Mixing of string and numeric keys is not allowed'); } @@ -113,14 +111,11 @@ protected function _addBranch(Zend_Config $config, SimpleXMLElement $xml, Simple } else { $parent->addChild($branchName, (string) $value); } + } elseif ($value instanceof Zend_Config) { + $child = $xml->addChild($key); + $this->_addBranch($value, $child, $xml); } else { - if ($value instanceof Zend_Config) { - $child = $xml->addChild($key); - - $this->_addBranch($value, $child, $xml); - } else { - $xml->addChild($key, (string) $value); - } + $xml->addChild($key, (string) $value); } } } diff --git a/library/Zend/Config/Writer/Yaml.php b/library/Zend/Config/Writer/Yaml.php index 4d2b1fed44..6ccb04cd19 100755 --- a/library/Zend/Config/Writer/Yaml.php +++ b/library/Zend/Config/Writer/Yaml.php @@ -132,11 +132,7 @@ protected static function _encodeYaml($indent, $data) $numeric = is_numeric(key($data)); foreach($data as $key => $value) { - if(is_array($value)) { - $encoded = "\n".self::_encodeYaml($indent+1, $value); - } else { - $encoded = (string)$value."\n"; - } + $encoded = is_array($value) ? "\n".self::_encodeYaml($indent+1, $value) : (string)$value."\n"; $result .= str_repeat(" ", $indent).($numeric?"- ":"$key: ").$encoded; } return $result; diff --git a/library/Zend/Config/Xml.php b/library/Zend/Config/Xml.php index 4425a8b705..d05116ffa3 100644 --- a/library/Zend/Config/Xml.php +++ b/library/Zend/Config/Xml.php @@ -100,7 +100,9 @@ public function __construct($xml, $section = null, $options = false) } } - set_error_handler(array($this, '_loadFileErrorHandler')); // Warnings and errors are suppressed + set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline) { + return $this->_loadFileErrorHandler($errno, $errstr, $errfile, $errline); + }); // Warnings and errors are suppressed if (strstr($xml, 'getMessage() - ); + throw new Zend_Config_Exception($e->getMessage(), $e->getCode(), $e); } } @@ -131,9 +131,8 @@ public function __construct($xml, $section = null, $options = false) foreach ($config as $sectionName => $sectionData) { $dataArray[$sectionName] = $this->_processExtends($config, $sectionName); } - parent::__construct($dataArray, $allowModifications); - } else if (is_array($section)) { + } elseif (is_array($section)) { $dataArray = array(); foreach ($section as $sectionName) { if (!isset($config->$sectionName)) { @@ -143,7 +142,6 @@ public function __construct($xml, $section = null, $options = false) $dataArray = array_merge($this->_processExtends($config, $sectionName), $dataArray); } - parent::__construct($dataArray, $allowModifications); } else { if (!isset($config->$section)) { @@ -192,9 +190,7 @@ protected function _processExtends(SimpleXMLElement $element, $section, array $c } } - $config = $this->_arrayMergeRecursive($config, $this->_toArray($thisSection)); - - return $config; + return $this->_arrayMergeRecursive($config, $this->_toArray($thisSection)); } /** @@ -282,13 +278,9 @@ protected function _toArray(SimpleXMLElement $xmlObject) foreach ($xmlObject->children() as $key => $value) { if (count($value->children()) > 0 || count($value->children(self::XML_NAMESPACE)) > 0) { $value = $this->_toArray($value); - } else if (count($value->attributes()) > 0) { + } elseif (count($value->attributes()) > 0) { $attributes = $value->attributes(); - if (isset($attributes['value'])) { - $value = (string) $attributes['value']; - } else { - $value = $this->_toArray($value); - } + $value = isset($attributes['value']) ? (string) $attributes['value'] : $this->_toArray($value); } else { $value = (string) $value; } @@ -303,7 +295,7 @@ protected function _toArray(SimpleXMLElement $xmlObject) $config[$key] = $value; } } - } else if (!isset($xmlObject['extends']) && !isset($nsAttributes['extends']) && (count($config) === 0)) { + } elseif (!isset($xmlObject['extends']) && !isset($nsAttributes['extends']) && ($config === [])) { // Object has no children nor attributes and doesn't use the extends // attribute: it's a string $config = (string) $xmlObject; diff --git a/library/Zend/Config/Yaml.php b/library/Zend/Config/Yaml.php index 8a1a1f2123..4f71401e8b 100755 --- a/library/Zend/Config/Yaml.php +++ b/library/Zend/Config/Yaml.php @@ -165,7 +165,9 @@ public function __construct($yaml, $section = null, $options = false) } // Suppress warnings and errors while loading file - set_error_handler(array($this, '_loadFileErrorHandler')); + set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline) { + return $this->_loadFileErrorHandler($errno, $errstr, $errfile, $errline); + }); $yaml = file_get_contents($yaml); restore_error_handler(); @@ -258,9 +260,7 @@ protected function _processExtends(array $data, $section, array $config = array( unset($thisSection[self::EXTENDS_NAME]); } - $config = $this->_arrayMergeRecursive($config, $thisSection); - - return $config; + return $this->_arrayMergeRecursive($config, $thisSection); } /** @@ -318,14 +318,14 @@ protected static function _decodeYaml($currentIndent, &$lines) if (preg_match("/(?!-)([\w\-]+):\s*(.*)/", $line, $m)) { // key: value - if (strlen((string) $m[2])) { + if (strlen((string) $m[2]) !== 0) { // simple key: value $value = preg_replace("/#.*$/", "", $m[2]); $value = self::_parseValue($value); } else { // key: and then values on new lines $value = self::_decodeYaml($currentIndent + 1, $lines); - if (is_array($value) && !count($value)) { + if (is_array($value) && $value === []) { $value = ""; } } diff --git a/library/Zend/Console/Getopt.php b/library/Zend/Console/Getopt.php index 75bc7c54af..20ddf414ab 100644 --- a/library/Zend/Console/Getopt.php +++ b/library/Zend/Console/Getopt.php @@ -506,9 +506,8 @@ public function toJson() * @see Zend_Json */ require_once 'Zend/Json.php'; - $json = Zend_Json::encode($j); - return $json; + return Zend_Json::encode($j); } /** @@ -530,8 +529,7 @@ public function toXml() } $optionsNode->appendChild($optionNode); } - $xml = $doc->saveXML(); - return $xml; + return $doc->saveXML(); } /** @@ -698,7 +696,7 @@ public function setHelp($helpMap) */ public function parse() { - if ($this->_parsed === true) { + if ($this->_parsed) { return; } $argv = $this->_argv; @@ -714,9 +712,9 @@ public function parse() } if (substr($argv[0], 0, 2) == '--') { $this->_parseLongOption($argv); - } else if (substr($argv[0], 0, 1) == '-' && ('-' != $argv[0] || count($argv) >1)) { + } elseif (substr($argv[0], 0, 1) == '-' && ('-' != $argv[0] || count($argv) >1)) { $this->_parseShortOptionCluster($argv); - } else if($this->_getoptConfig[self::CONFIG_PARSEALL]) { + } elseif ($this->_getoptConfig[self::CONFIG_PARSEALL]) { $this->_remainingArgs[] = array_shift($argv); } else { /* @@ -740,9 +738,9 @@ public function checkRequiredArguments() if ($rule['param'] === 'required') { $defined = false; foreach ($rule['alias'] as $alias) { - $defined = $defined === true ? true : array_key_exists($alias, $this->_options); + $defined = $defined ? true : array_key_exists($alias, $this->_options); } - if ($defined === false) { + if (!$defined) { require_once 'Zend/Console/Getopt/Exception.php'; throw new Zend_Console_Getopt_Exception( 'Option "$alias" requires a parameter.', diff --git a/library/Zend/Controller/Action.php b/library/Zend/Controller/Action.php index 9508e74711..05b93ccab7 100644 --- a/library/Zend/Controller/Action.php +++ b/library/Zend/Controller/Action.php @@ -167,7 +167,7 @@ public function initView() } require_once 'Zend/View/Interface.php'; - if (isset($this->view) && ($this->view instanceof Zend_View_Interface)) { + if ($this->view !== null && ($this->view instanceof Zend_View_Interface)) { return $this->view; } @@ -562,7 +562,7 @@ public function run(Zend_Controller_Request_Abstract $request = null, Zend_Contr if (empty($action)) { $action = 'index'; } - $action = $action . 'Action'; + $action .= 'Action'; $request->setDispatched(true); $this->dispatch($action); diff --git a/library/Zend/Controller/Action/Helper/ActionStack.php b/library/Zend/Controller/Action/Helper/ActionStack.php index e22e8b8e7e..a68e1ad21e 100644 --- a/library/Zend/Controller/Action/Helper/ActionStack.php +++ b/library/Zend/Controller/Action/Helper/ActionStack.php @@ -100,7 +100,7 @@ public function actionToStack($action, $controller = null, $module = null, array $request = $this->getRequest(); - if ($request instanceof Zend_Controller_Request_Abstract === false){ + if (!$request instanceof Zend_Controller_Request_Abstract){ /** * @see Zend_Controller_Action_Exception */ diff --git a/library/Zend/Controller/Action/Helper/AutoCompleteScriptaculous.php b/library/Zend/Controller/Action/Helper/AutoCompleteScriptaculous.php index 098aed8b10..c5fbd77825 100644 --- a/library/Zend/Controller/Action/Helper/AutoCompleteScriptaculous.php +++ b/library/Zend/Controller/Action/Helper/AutoCompleteScriptaculous.php @@ -45,11 +45,7 @@ class Zend_Controller_Action_Helper_AutoCompleteScriptaculous extends Zend_Contr */ public function validateData($data) { - if (!is_array($data) && !is_scalar($data)) { - return false; - } - - return true; + return !(!is_array($data) && !is_scalar($data)); } /** diff --git a/library/Zend/Controller/Action/Helper/ContextSwitch.php b/library/Zend/Controller/Action/Helper/ContextSwitch.php index fe9114bc6e..33d761e92a 100644 --- a/library/Zend/Controller/Action/Helper/ContextSwitch.php +++ b/library/Zend/Controller/Action/Helper/ContextSwitch.php @@ -260,11 +260,8 @@ public function initContext($format = null) // Return if invalid context parameter provided and no format or invalid // format provided - if (!$this->hasContext($context)) { - if (empty($format) || !$this->hasContext($format)) { - - return; - } + if (!$this->hasContext($context) && (empty($format) || !$this->hasContext($format))) { + return; } // Use provided format if passed @@ -453,11 +450,7 @@ public function setSuffix($context, $suffix, $prependViewRendererSuffix = true) if (isset($suffix['prependViewRendererSuffix'])) { $prependViewRendererSuffix = $suffix['prependViewRendererSuffix']; } - if (isset($suffix['suffix'])) { - $suffix = $suffix['suffix']; - } else { - $suffix = ''; - } + $suffix = isset($suffix['suffix']) ? $suffix['suffix'] : ''; } $suffix = (string) $suffix; @@ -516,7 +509,7 @@ public function hasContext($context, $throwException = false) break; } } - if (false === $error) { + if (!$error) { return true; } $context = $error; @@ -746,14 +739,12 @@ public function setCallback($context, $trigger, $callback) $this->hasContext($context, true); $trigger = $this->_validateTrigger($trigger); - if (!is_string($callback)) { - if (!is_array($callback) || (2 != count($callback))) { - /** - * @see Zend_Controller_Action_Exception - */ - require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception('Invalid callback specified'); - } + if (!is_string($callback) && (!is_array($callback) || (2 != count($callback)))) { + /** + * @see Zend_Controller_Action_Exception + */ + require_once 'Zend/Controller/Action/Exception.php'; + throw new Zend_Controller_Action_Exception('Invalid callback specified'); } $this->_contexts[$context]['callbacks'][$trigger] = $callback; @@ -924,7 +915,7 @@ public function getDefaultContext() */ public function setAutoDisableLayout($flag) { - $this->_disableLayout = ($flag) ? true : false; + $this->_disableLayout = $flag; return $this; } @@ -1078,21 +1069,19 @@ public function getCurrentContext() public function postDispatch() { $context = $this->getCurrentContext(); - if (null !== $context) { - if (null !== ($callback = $this->getCallback($context, self::TRIGGER_POST))) { - if (is_string($callback) && method_exists($this, $callback)) { - $this->$callback(); - } elseif (is_string($callback) && function_exists($callback)) { - $callback(); - } elseif (is_array($callback)) { - call_user_func($callback); - } else { - /** - * @see Zend_Controller_Action_Exception - */ - require_once 'Zend/Controller/Action/Exception.php'; - throw new Zend_Controller_Action_Exception(sprintf('Invalid postDispatch context callback registered for context "%s"', $context)); - } + if (null !== $context && null !== ($callback = $this->getCallback($context, self::TRIGGER_POST))) { + if (is_string($callback) && method_exists($this, $callback)) { + $this->$callback(); + } elseif (is_string($callback) && function_exists($callback)) { + $callback(); + } elseif (is_array($callback)) { + call_user_func($callback); + } else { + /** + * @see Zend_Controller_Action_Exception + */ + require_once 'Zend/Controller/Action/Exception.php'; + throw new Zend_Controller_Action_Exception(sprintf('Invalid postDispatch context callback registered for context "%s"', $context)); } } } diff --git a/library/Zend/Controller/Action/Helper/FlashMessenger.php b/library/Zend/Controller/Action/Helper/FlashMessenger.php index 57fe9ecdee..5881b65294 100644 --- a/library/Zend/Controller/Action/Helper/FlashMessenger.php +++ b/library/Zend/Controller/Action/Helper/FlashMessenger.php @@ -82,7 +82,7 @@ public function __construct() self::$_session = new Zend_Session_Namespace($this->getName()); foreach (self::$_session as $namespace => $messages) { self::$_messages[$namespace] = $messages; - unset(self::$_session->{$namespace}); + unset(self::$_session->getNamespace()); } } } @@ -146,7 +146,7 @@ public function addMessage($message, $namespace = null) $namespace = $this->getNamespace(); } - if (self::$_messageAdded === false) { + if (!self::$_messageAdded) { self::$_session->setExpirationHops(1, null, true); } diff --git a/library/Zend/Controller/Action/Helper/Redirector.php b/library/Zend/Controller/Action/Helper/Redirector.php index bf95772981..c25717633a 100644 --- a/library/Zend/Controller/Action/Helper/Redirector.php +++ b/library/Zend/Controller/Action/Helper/Redirector.php @@ -130,7 +130,7 @@ public function getExit() */ public function setExit($flag) { - $this->_exit = ($flag) ? true : false; + $this->_exit = $flag; return $this; } @@ -153,7 +153,7 @@ public function getPrependBase() */ public function setPrependBase($flag) { - $this->_prependBase = ($flag) ? true : false; + $this->_prependBase = $flag; return $this; } @@ -176,7 +176,7 @@ public function getCloseSessionOnExit() */ public function setCloseSessionOnExit($flag) { - $this->_closeSessionOnExit = ($flag) ? true : false; + $this->_closeSessionOnExit = $flag; return $this; } @@ -198,7 +198,7 @@ public function getUseAbsoluteUri() */ public function setUseAbsoluteUri($flag = true) { - $this->_useAbsoluteUri = ($flag) ? true : false; + $this->_useAbsoluteUri = $flag; return $this; } @@ -214,11 +214,9 @@ protected function _redirect($url) $proto = (isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!=="off") ? 'https' : 'http'; $port = (isset($_SERVER['SERVER_PORT'])?$_SERVER['SERVER_PORT']:80); $uri = $proto . '://' . $host; - if ((('http' == $proto) && (80 != $port)) || (('https' == $proto) && (443 != $port))) { - // do not append if HTTP_HOST already contains port - if (strrchr($host, ':') === false) { - $uri .= ':' . $port; - } + // do not append if HTTP_HOST already contains port + if (((('http' == $proto) && (80 != $port)) || (('https' == $proto) && (443 != $port))) && strrchr($host, ':') === false) { + $uri .= ':' . $port; } $url = $uri . '/' . ltrim($url, '/'); } @@ -248,11 +246,7 @@ protected function _prependBase($url) $request = $this->getRequest(); if ($request instanceof Zend_Controller_Request_Http) { $base = rtrim($request->getBaseUrl(), '/'); - if (!empty($base) && ('/' != $base)) { - $url = $base . '/' . ltrim($url, '/'); - } else { - $url = '/' . ltrim($url, '/'); - } + $url = !empty($base) && ('/' != $base) ? $base . '/' . ltrim($url, '/') : '/' . ltrim($url, '/'); } } @@ -283,7 +277,7 @@ public function setGotoSimple($action, $controller = null, $module = null, array $module = $curModule; } - if ($module == $dispatcher->getDefaultModule()) { + if ($module === $dispatcher->getDefaultModule()) { $module = ''; } @@ -352,10 +346,10 @@ public function setGotoUrl($url, array $options = array()) if (null !== $options) { if (isset($options['exit'])) { - $this->setExit(($options['exit']) ? true : false); + $this->setExit((bool) $options['exit']); } if (isset($options['prependBase'])) { - $this->setPrependBase(($options['prependBase']) ? true : false); + $this->setPrependBase((bool) $options['prependBase']); } if (isset($options['code'])) { $this->setCode($options['code']); @@ -519,13 +513,19 @@ public function __call($method, $args) { $method = strtolower($method); if ('goto' == $method) { - return call_user_func_array(array($this, 'gotoSimple'), $args); + return call_user_func_array(function (string $action, ?string $controller = \null, ?string $module = \null, array $params = array()) : void { + $this->gotoSimple($action, $controller, $module, $params); + }, $args); } if ('setgoto' == $method) { - return call_user_func_array(array($this, 'setGotoSimple'), $args); + return call_user_func_array(function (string $action, ?string $controller = \null, ?string $module = \null, array $params = array()) : void { + $this->setGotoSimple($action, $controller, $module, $params); + }, $args); } if ('gotoandexit' == $method) { - return call_user_func_array(array($this, 'gotoSimpleAndExit'), $args); + return call_user_func_array(function ($action, $controller = \null, $module = \null, array $params = array()) : void { + $this->gotoSimpleAndExit($action, $controller, $module, $params); + }, $args); } require_once 'Zend/Controller/Action/Exception.php'; diff --git a/library/Zend/Controller/Action/Helper/Url.php b/library/Zend/Controller/Action/Helper/Url.php index 7b8c69ac12..4119e41731 100644 --- a/library/Zend/Controller/Action/Helper/Url.php +++ b/library/Zend/Controller/Action/Helper/Url.php @@ -59,7 +59,7 @@ public function simple($action, $controller = null, $module = null, array $param } $url = $controller . '/' . $action; - if ($module != $this->getFrontController()->getDispatcher()->getDefaultModule()) { + if ($module !== $this->getFrontController()->getDispatcher()->getDefaultModule()) { $url = $module . '/' . $url; } @@ -76,9 +76,7 @@ public function simple($action, $controller = null, $module = null, array $param $url .= '/' . $paramString; } - $url = '/' . ltrim($url, '/'); - - return $url; + return '/' . ltrim($url, '/'); } /** diff --git a/library/Zend/Controller/Action/Helper/ViewRenderer.php b/library/Zend/Controller/Action/Helper/ViewRenderer.php index a66c12a466..4d81708d36 100644 --- a/library/Zend/Controller/Action/Helper/ViewRenderer.php +++ b/library/Zend/Controller/Action/Helper/ViewRenderer.php @@ -197,7 +197,7 @@ public function __construct(Zend_View_Interface $view = null, array $options = a */ public function __clone() { - if (isset($this->view) && $this->view instanceof Zend_View_Interface) { + if ($this->view !== null && $this->view instanceof Zend_View_Interface) { $this->view = clone $this->view; } @@ -362,9 +362,7 @@ protected function _generateDefaultPrefix() return $default; } - $prefix = substr($class, 0, strpos($class, '_')) . '_View'; - - return $prefix; + return substr($class, 0, strpos($class, '_')) . '_View'; } /** @@ -389,9 +387,7 @@ protected function _getBasePath() 'controller' => $request->getControllerName(), 'action' => $dispatcher->formatActionName($request->getActionName()) ); - - $path = $inflector->filter($parts); - return $path; + return $inflector->filter($parts); } /** @@ -410,7 +406,7 @@ protected function _setOptions(array $options) case 'noController': case 'noRender': $property = '_' . $key; - $this->{$property} = ($value) ? true : false; + $this->{$property} = (bool) $value; break; case 'responseSegment': case 'scriptAction': @@ -647,7 +643,7 @@ public function getViewScript($action = null, array $vars = array()) */ public function setNeverRender($flag = true) { - $this->_neverRender = ($flag) ? true : false; + $this->_neverRender = $flag; return $this; } @@ -669,7 +665,7 @@ public function getNeverRender() */ public function setNoRender($flag = true) { - $this->_noRender = ($flag) ? true : false; + $this->_noRender = $flag; return $this; } @@ -713,11 +709,7 @@ public function getScriptAction() */ public function setResponseSegment($name) { - if (null === $name) { - $this->_responseSegment = null; - } else { - $this->_responseSegment = (string) $name; - } + $this->_responseSegment = null === $name ? null : (string) $name; return $this; } @@ -740,7 +732,7 @@ public function getResponseSegment() */ public function setNoController($flag = true) { - $this->_noController = ($flag) ? true : false; + $this->_noController = $flag; return $this; } @@ -762,7 +754,7 @@ public function getNoController() */ public function setNeverController($flag = true) { - $this->_neverController = ($flag) ? true : false; + $this->_neverController = $flag; return $this; } @@ -857,7 +849,7 @@ protected function _translateSpec(array $vars = array()) // Format action name $action = $dispatcher->formatActionName($request->getActionName()); - $params = compact('module', 'controller', 'action'); + $params = ['module' => $module, 'controller' => $controller, 'action' => $action]; foreach ($vars as $key => $value) { switch ($key) { case 'module': diff --git a/library/Zend/Controller/Action/HelperBroker/PriorityStack.php b/library/Zend/Controller/Action/HelperBroker/PriorityStack.php index d510b74ee5..ff9bdc0179 100644 --- a/library/Zend/Controller/Action/HelperBroker/PriorityStack.php +++ b/library/Zend/Controller/Action/HelperBroker/PriorityStack.php @@ -88,7 +88,7 @@ public function push(Zend_Controller_Action_Helper_Abstract $helper) * * @return array */ - public function getIterator() + public function getIterator(): Traversable { return new ArrayObject($this->_helpersByPriority); } @@ -99,7 +99,7 @@ public function getIterator() * @param int|string $priorityOrHelperName * @return Zend_Controller_Action_HelperBroker_PriorityStack */ - public function offsetExists($priorityOrHelperName) + public function offsetExists($priorityOrHelperName): bool { if (is_string($priorityOrHelperName)) { return array_key_exists($priorityOrHelperName, $this->_helpersByNameRef); @@ -114,7 +114,7 @@ public function offsetExists($priorityOrHelperName) * @param int|string $priorityOrHelperName * @return Zend_Controller_Action_HelperBroker_PriorityStack */ - public function offsetGet($priorityOrHelperName) + public function offsetGet($priorityOrHelperName): mixed { if (!$this->offsetExists($priorityOrHelperName)) { require_once 'Zend/Controller/Action/Exception.php'; @@ -135,6 +135,7 @@ public function offsetGet($priorityOrHelperName) * @param Zend_Controller_Action_Helper_Abstract $helper * @return Zend_Controller_Action_HelperBroker_PriorityStack */ + #[\ReturnTypeWillChange] public function offsetSet($priority, $helper) { $priority = (int) $priority; @@ -158,7 +159,7 @@ public function offsetSet($priority, $helper) $this->_helpersByPriority[$priority] = $helper; $this->_helpersByNameRef[$helper->getName()] = $helper; - if ($priority == ($nextFreeDefault = $this->getNextFreeHigherPriority($this->_nextDefaultPriority))) { + if ($priority === ($nextFreeDefault = $this->getNextFreeHigherPriority($this->_nextDefaultPriority))) { $this->_nextDefaultPriority = $nextFreeDefault; } @@ -172,6 +173,7 @@ public function offsetSet($priority, $helper) * @param int|string $priorityOrHelperName Priority integer or the helper name * @return Zend_Controller_Action_HelperBroker_PriorityStack */ + #[\ReturnTypeWillChange] public function offsetUnset($priorityOrHelperName) { if (!$this->offsetExists($priorityOrHelperName)) { @@ -198,7 +200,7 @@ public function offsetUnset($priorityOrHelperName) * * @return int */ - public function count() + public function count(): int { return count($this->_helpersByPriority); } @@ -216,9 +218,7 @@ public function getNextFreeHigherPriority($indexPriority = null) $indexPriority = $this->_nextDefaultPriority; } - $priorities = array_keys($this->_helpersByPriority); - - while (in_array($indexPriority, $priorities)) { + while (array_key_exists($indexPriority, $this->_helpersByPriority)) { $indexPriority++; } @@ -238,9 +238,7 @@ public function getNextFreeLowerPriority($indexPriority = null) $indexPriority = $this->_nextDefaultPriority; } - $priorities = array_keys($this->_helpersByPriority); - - while (in_array($indexPriority, $priorities)) { + while (array_key_exists($indexPriority, $this->_helpersByPriority)) { $indexPriority--; } diff --git a/library/Zend/Controller/Dispatcher/Abstract.php b/library/Zend/Controller/Dispatcher/Abstract.php index 2bfe1be2be..833906c1fd 100644 --- a/library/Zend/Controller/Dispatcher/Abstract.php +++ b/library/Zend/Controller/Dispatcher/Abstract.php @@ -230,11 +230,7 @@ public function setPathDelimiter($spec) protected function _formatName($unformatted, $isAction = false) { // preserve directories - if (!$isAction) { - $segments = explode($this->getPathDelimiter(), $unformatted); - } else { - $segments = (array) $unformatted; - } + $segments = $isAction ? (array) $unformatted : explode($this->getPathDelimiter(), $unformatted); foreach ($segments as $key => $segment) { $segment = str_replace($this->getWordDelimiter(), ' ', strtolower($segment)); diff --git a/library/Zend/Controller/Dispatcher/Standard.php b/library/Zend/Controller/Dispatcher/Standard.php index 492056e42a..de6ab1dc3e 100644 --- a/library/Zend/Controller/Dispatcher/Standard.php +++ b/library/Zend/Controller/Dispatcher/Standard.php @@ -157,7 +157,7 @@ public function removeControllerDirectory($module) */ public function formatModuleName($unformatted) { - if (($this->_defaultModule == $unformatted) && !$this->getParam('prefixDefaultModule')) { + if (($this->_defaultModule === $unformatted) && !$this->getParam('prefixDefaultModule')) { return $unformatted; } @@ -207,7 +207,7 @@ public function isDispatchable(Zend_Controller_Request_Abstract $request) } $finalClass = $className; - if (($this->_defaultModule != $this->_curModule) + if (($this->_defaultModule !== $this->_curModule) || $this->getParam('prefixDefaultModule')) { $finalClass = $this->formatClassName($this->_curModule, $className); @@ -263,7 +263,7 @@ public function dispatch(Zend_Controller_Request_Abstract $request, Zend_Control * class name to do the class->file mapping, but the full class name to insantiate the controller */ $moduleClassName = $className; - if (($this->_defaultModule != $this->_curModule) + if (($this->_defaultModule !== $this->_curModule) || $this->getParam('prefixDefaultModule')) { $moduleClassName = $this->formatClassName($this->_curModule, $className); @@ -341,7 +341,7 @@ public function dispatch(Zend_Controller_Request_Abstract $request, Zend_Control public function loadClass($className) { $finalClass = $className; - if (($this->_defaultModule != $this->_curModule) + if (($this->_defaultModule !== $this->_curModule) || $this->getParam('prefixDefaultModule')) { $finalClass = $this->formatClassName($this->_curModule, $className); @@ -422,7 +422,7 @@ public function isValidModule($module) $module = strtolower($module); $controllerDir = $this->getControllerDirectory(); foreach (array_keys($controllerDir) as $moduleName) { - if ($module == strtolower($moduleName)) { + if ($module === strtolower($moduleName)) { return true; } } diff --git a/library/Zend/Controller/Front.php b/library/Zend/Controller/Front.php index 3ca4c78b1d..25e5464766 100644 --- a/library/Zend/Controller/Front.php +++ b/library/Zend/Controller/Front.php @@ -859,10 +859,8 @@ public function dispatch(Zend_Controller_Request_Abstract $request = null, Zend_ /** * Set base URL of request object, if available */ - if (is_callable(array($this->_request, 'setBaseUrl'))) { - if (null !== $this->_baseUrl) { - $this->_request->setBaseUrl($this->_baseUrl); - } + if (is_callable(array($this->_request, 'setBaseUrl')) && null !== $this->_baseUrl) { + $this->_request->setBaseUrl($this->_baseUrl); } /** diff --git a/library/Zend/Controller/Plugin/ActionStack.php b/library/Zend/Controller/Plugin/ActionStack.php index 12c62de112..18d306d128 100644 --- a/library/Zend/Controller/Plugin/ActionStack.php +++ b/library/Zend/Controller/Plugin/ActionStack.php @@ -163,8 +163,7 @@ public function getClearRequestParams() public function getStack() { $registry = $this->getRegistry(); - $stack = $registry[$this->getRegistryKey()]; - return $stack; + return $registry[$this->getRegistryKey()]; } /** @@ -189,7 +188,7 @@ protected function _saveStack(array $stack) public function pushStack(Zend_Controller_Request_Abstract $next) { $stack = $this->getStack(); - array_push($stack, $next); + $stack[] = $next; return $this->_saveStack($stack); } @@ -214,7 +213,7 @@ public function popStack() } $action = $next->getActionName(); if (empty($action)) { - return $this->popStack($stack); + return $this->popStack(); } $request = $this->getRequest(); diff --git a/library/Zend/Controller/Plugin/Broker.php b/library/Zend/Controller/Plugin/Broker.php index 1214583eb3..a4efec1611 100644 --- a/library/Zend/Controller/Plugin/Broker.php +++ b/library/Zend/Controller/Plugin/Broker.php @@ -50,14 +50,14 @@ class Zend_Controller_Plugin_Broker extends Zend_Controller_Plugin_Abstract */ public function registerPlugin(Zend_Controller_Plugin_Abstract $plugin, $stackIndex = null) { - if (false !== array_search($plugin, $this->_plugins, true)) { + if (in_array($plugin, $this->_plugins, true)) { require_once 'Zend/Controller/Exception.php'; throw new Zend_Controller_Exception('Plugin already registered'); } $stackIndex = (int) $stackIndex; - if ($stackIndex) { + if ($stackIndex !== 0) { if (isset($this->_plugins[$stackIndex])) { require_once 'Zend/Controller/Exception.php'; throw new Zend_Controller_Exception('Plugin with stackIndex "' . $stackIndex . '" already registered'); diff --git a/library/Zend/Controller/Plugin/ErrorHandler.php b/library/Zend/Controller/Plugin/ErrorHandler.php index 42da1633c6..d12b4fe3c1 100644 --- a/library/Zend/Controller/Plugin/ErrorHandler.php +++ b/library/Zend/Controller/Plugin/ErrorHandler.php @@ -262,21 +262,13 @@ protected function _handleError(Zend_Controller_Request_Abstract $request) $error->exception = $exception; switch ($exceptionType) { case 'Zend_Controller_Router_Exception': - if (404 == $exception->getCode()) { - $error->type = self::EXCEPTION_NO_ROUTE; - } else { - $error->type = self::EXCEPTION_OTHER; - } + $error->type = 404 == $exception->getCode() ? self::EXCEPTION_NO_ROUTE : self::EXCEPTION_OTHER; break; case 'Zend_Controller_Dispatcher_Exception': $error->type = self::EXCEPTION_NO_CONTROLLER; break; case 'Zend_Controller_Action_Exception': - if (404 == $exception->getCode()) { - $error->type = self::EXCEPTION_NO_ACTION; - } else { - $error->type = self::EXCEPTION_OTHER; - } + $error->type = 404 == $exception->getCode() ? self::EXCEPTION_NO_ACTION : self::EXCEPTION_OTHER; break; default: $error->type = self::EXCEPTION_OTHER; diff --git a/library/Zend/Controller/Request/Abstract.php b/library/Zend/Controller/Request/Abstract.php index d57238f46b..79efb7db8f 100644 --- a/library/Zend/Controller/Request/Abstract.php +++ b/library/Zend/Controller/Request/Abstract.php @@ -310,7 +310,7 @@ public function getParams() */ public function setParams(array $array) { - $this->_params = $this->_params + (array) $array; + $this->_params += (array) $array; foreach ($array as $key => $value) { if (null === $value) { @@ -340,7 +340,7 @@ public function clearParams() */ public function setDispatched($flag = true) { - $this->_dispatched = $flag ? true : false; + $this->_dispatched = $flag; return $this; } diff --git a/library/Zend/Controller/Request/Apache404.php b/library/Zend/Controller/Request/Apache404.php index 3c4dd7ac48..5d096813a1 100644 --- a/library/Zend/Controller/Request/Apache404.php +++ b/library/Zend/Controller/Request/Apache404.php @@ -65,10 +65,8 @@ public function setRequestUri($requestUri = null) } } elseif (!is_string($requestUri)) { return $this; - } else { - if (false !== ($pos = strpos($requestUri, '?'))) { - $parseUriGetVars = substr($requestUri, $pos + 1); - } + } elseif (false !== ($pos = strpos($requestUri, '?'))) { + $parseUriGetVars = substr($requestUri, $pos + 1); } if ($parseUriGetVars) { diff --git a/library/Zend/Controller/Request/Http.php b/library/Zend/Controller/Request/Http.php index 7ccb20cd74..0c2e820852 100644 --- a/library/Zend/Controller/Request/Http.php +++ b/library/Zend/Controller/Request/Http.php @@ -421,14 +421,11 @@ public function setRequestUri($requestUri = null) } } elseif (!is_string($requestUri)) { return $this; - } else { - // Set GET items, if available - if (false !== ($pos = strpos($requestUri, '?'))) { - // Get key => value pairs and set $_GET - $query = substr($requestUri, $pos + 1); - parse_str($query, $vars); - $this->setQuery($vars); - } + } elseif (false !== ($pos = strpos($requestUri, '?'))) { + // Get key => value pairs and set $_GET + $query = substr($requestUri, $pos + 1); + parse_str($query, $vars); + $this->setQuery($vars); } $this->_requestUri = $requestUri; @@ -577,11 +574,7 @@ public function setBasePath($basePath = null) return $this; } - if (basename($baseUrl) === $filename) { - $basePath = dirname($baseUrl); - } else { - $basePath = $baseUrl; - } + $basePath = basename($baseUrl) === $filename ? dirname($baseUrl) : $baseUrl; } if (substr(PHP_OS, 0, 3) === 'WIN') { @@ -840,11 +833,7 @@ public function getMethod() */ public function isPost() { - if ('POST' == $this->getMethod()) { - return true; - } - - return false; + return 'POST' == $this->getMethod(); } /** @@ -854,11 +843,7 @@ public function isPost() */ public function isGet() { - if ('GET' == $this->getMethod()) { - return true; - } - - return false; + return 'GET' == $this->getMethod(); } /** @@ -868,11 +853,7 @@ public function isGet() */ public function isPut() { - if ('PUT' == $this->getMethod()) { - return true; - } - - return false; + return 'PUT' == $this->getMethod(); } /** @@ -882,11 +863,7 @@ public function isPut() */ public function isDelete() { - if ('DELETE' == $this->getMethod()) { - return true; - } - - return false; + return 'DELETE' == $this->getMethod(); } /** @@ -896,11 +873,7 @@ public function isDelete() */ public function isHead() { - if ('HEAD' == $this->getMethod()) { - return true; - } - - return false; + return 'HEAD' == $this->getMethod(); } /** @@ -910,11 +883,7 @@ public function isHead() */ public function isOptions() { - if ('OPTIONS' == $this->getMethod()) { - return true; - } - - return false; + return 'OPTIONS' == $this->getMethod(); } /** @@ -924,11 +893,7 @@ public function isOptions() */ public function isPatch() { - if ('PATCH' == $this->getMethod()) { - return true; - } - - return false; + return 'PATCH' == $this->getMethod(); } /** @@ -951,7 +916,7 @@ public function isXmlHttpRequest() public function isFlashRequest() { $header = strtolower($this->getHeader('USER_AGENT')); - return (strstr($header, ' flash')) ? true : false; + return (bool) strstr($header, ' flash'); } /** @@ -974,11 +939,7 @@ public function getRawBody() if (null === $this->_rawBody) { $body = file_get_contents('php://input'); - if (strlen(trim($body)) > 0) { - $this->_rawBody = $body; - } else { - $this->_rawBody = false; - } + $this->_rawBody = strlen(trim($body)) > 0 ? $body : false; } return $this->_rawBody; } @@ -1024,7 +985,7 @@ public function getHeader($header) } $header = strtolower($header); foreach ($headers as $key => $value) { - if (strtolower($key) == $header) { + if (strtolower($key) === $header) { return $value; } } @@ -1083,7 +1044,7 @@ public function getClientIp($checkProxy = true) { if ($checkProxy && $this->getServer('HTTP_CLIENT_IP') != null) { $ip = $this->getServer('HTTP_CLIENT_IP'); - } else if ($checkProxy && $this->getServer('HTTP_X_FORWARDED_FOR') != null) { + } elseif ($checkProxy && $this->getServer('HTTP_X_FORWARDED_FOR') != null) { $ip = $this->getServer('HTTP_X_FORWARDED_FOR'); } else { $ip = $this->getServer('REMOTE_ADDR'); diff --git a/library/Zend/Controller/Request/HttpTestCase.php b/library/Zend/Controller/Request/HttpTestCase.php index 58b9bd3936..d5fb134f61 100644 --- a/library/Zend/Controller/Request/HttpTestCase.php +++ b/library/Zend/Controller/Request/HttpTestCase.php @@ -271,7 +271,6 @@ public function getRequestUri() protected function _normalizeHeaderName($name) { $name = strtoupper((string) $name); - $name = str_replace('-', '_', $name); - return $name; + return str_replace('-', '_', $name); } } diff --git a/library/Zend/Controller/Request/Simple.php b/library/Zend/Controller/Request/Simple.php index 74e4b0c4a1..b4cd07f9cf 100644 --- a/library/Zend/Controller/Request/Simple.php +++ b/library/Zend/Controller/Request/Simple.php @@ -47,7 +47,7 @@ public function __construct($action = null, $controller = null, $module = null, $this->setModuleName($module); } - if ($params) { + if ($params !== []) { $this->setParams($params); } } diff --git a/library/Zend/Controller/Response/Abstract.php b/library/Zend/Controller/Response/Abstract.php index 9fcc22693e..971be26580 100644 --- a/library/Zend/Controller/Response/Abstract.php +++ b/library/Zend/Controller/Response/Abstract.php @@ -95,8 +95,7 @@ protected function _normalizeHeader($name) { $filtered = str_replace(array('-', '_'), ' ', (string) $name); $filtered = ucwords(strtolower($filtered)); - $filtered = str_replace(' ', '-', $filtered); - return $filtered; + return str_replace(' ', '-', $filtered); } /** @@ -192,7 +191,7 @@ public function clearHeaders() */ public function clearHeader($name) { - if (! count($this->_headers)) { + if ($this->_headers === []) { return $this; } @@ -252,7 +251,7 @@ public function clearRawHeaders() */ public function clearRawHeader($headerRaw) { - if (! count($this->_headersRaw)) { + if ($this->_headersRaw === []) { return $this; } @@ -288,11 +287,7 @@ public function setHttpResponseCode($code) throw new Zend_Controller_Response_Exception('Invalid HTTP response code'); } - if ((300 <= $code) && (307 >= $code)) { - $this->_isRedirect = true; - } else { - $this->_isRedirect = false; - } + $this->_isRedirect = (300 <= $code) && (307 >= $code); $this->_httpResponseCode = $code; return $this; @@ -339,7 +334,7 @@ public function sendHeaders() // Only check if we can send headers if we have headers to send if (count($this->_headersRaw) || count($this->_headers) || (200 != $this->_httpResponseCode)) { $this->canSendHeaders(true); - } elseif (200 == $this->_httpResponseCode) { + } elseif (200 === $this->_httpResponseCode) { // Haven't changed the response code, and we have no headers return $this; } @@ -459,11 +454,11 @@ public function clearBody($name = null) */ public function getBody($spec = false) { - if (false === $spec) { + if (!$spec) { ob_start(); $this->outputBody(); return ob_get_clean(); - } elseif (true === $spec) { + } elseif ($spec) { return $this->_body; } elseif (is_string($spec) && isset($this->_body[$spec])) { return $this->_body[$spec]; @@ -566,7 +561,7 @@ public function insert($name, $content, $parent = null, $before = false) $this->_body = $ins + $this->_body; } elseif ($loc >= (count($this->_body))) { // If location of key is maximal, we're appending - $this->_body = $this->_body + $ins; + $this->_body += $ins; } else { // Otherwise, insert at location specified $pre = array_slice($this->_body, 0, $loc); @@ -751,7 +746,7 @@ public function getExceptionByCode($code) public function renderExceptions($flag = null) { if (null !== $flag) { - $this->_renderExceptions = $flag ? true : false; + $this->_renderExceptions = $flag; } return $this->_renderExceptions; diff --git a/library/Zend/Controller/Response/HttpTestCase.php b/library/Zend/Controller/Response/HttpTestCase.php index 768dbfd311..f5712ddeed 100644 --- a/library/Zend/Controller/Response/HttpTestCase.php +++ b/library/Zend/Controller/Response/HttpTestCase.php @@ -41,9 +41,7 @@ class Zend_Controller_Response_HttpTestCase extends Zend_Controller_Response_Htt public function sendHeaders() { $headers = array(); - foreach ($this->_headersRaw as $header) { - $headers[] = $header; - } + $headers = $this->_headersRaw; foreach ($this->_headers as $header) { $name = $header['name']; $key = strtolower($name); diff --git a/library/Zend/Controller/Router/Rewrite.php b/library/Zend/Controller/Router/Rewrite.php index 83909f8a87..7e3f2bcbcf 100644 --- a/library/Zend/Controller/Router/Rewrite.php +++ b/library/Zend/Controller/Router/Rewrite.php @@ -180,11 +180,7 @@ public function addConfig(Zend_Config $config, $section = null) throw new Zend_Controller_Router_Exception("No chain defined"); } - if ($info->chain instanceof Zend_Config) { - $childRouteNames = $info->chain; - } else { - $childRouteNames = explode(',', (string) $info->chain); - } + $childRouteNames = $info->chain instanceof Zend_Config ? $info->chain : explode(',', (string) $info->chain); foreach ($childRouteNames as $childRouteName) { $childRoute = $this->getRoute(trim($childRouteName)); @@ -401,11 +397,7 @@ public function route(Zend_Controller_Request_Abstract $request) } // TODO: Should be an interface method. Hack for 1.0 BC - if (!method_exists($route, 'getVersion') || $route->getVersion() == 1) { - $match = $request->getPathInfo(); - } else { - $match = $request; - } + $match = !method_exists($route, 'getVersion') || $route->getVersion() == 1 ? $request->getPathInfo() : $request; if ($params = $route->match($match)) { $this->_setRequestParams($request, $params); diff --git a/library/Zend/Controller/Router/Route.php b/library/Zend/Controller/Router/Route.php index 404340bf88..52f50192ad 100644 --- a/library/Zend/Controller/Router/Route.php +++ b/library/Zend/Controller/Router/Route.php @@ -392,11 +392,7 @@ public function assemble($data = array(), $reset = false, $encode = false, $part } } elseif ($part != '*') { if ($this->_isTranslated && substr($part, 0, 1) === '@') { - if (substr($part, 1, 1) !== '@') { - $url[$key] = $translator->translate(substr($part, 1), $locale); - } else { - $url[$key] = substr($part, 1); - } + $url[$key] = substr($part, 1, 1) !== '@' ? $translator->translate(substr($part, 1), $locale) : substr($part, 1); } else { if (substr($part, 0, 2) === '@@') { $part = substr($part, 1); @@ -523,19 +519,17 @@ public function getTranslator() { if ($this->_translator !== null) { return $this->_translator; + } elseif (($translator = self::getDefaultTranslator()) !== null) { + return $translator; } else { - if (($translator = self::getDefaultTranslator()) !== null) { - return $translator; - } else { - try { - $translator = Zend_Registry::get('Zend_Translate'); - } catch (Zend_Exception $e) { - $translator = null; - } + try { + $translator = Zend_Registry::get('Zend_Translate'); + } catch (Zend_Exception $e) { + $translator = null; + } - if ($translator instanceof Zend_Translate) { - return $translator; - } + if ($translator instanceof Zend_Translate) { + return $translator; } } @@ -582,24 +576,6 @@ public function setLocale($locale) */ public function getLocale() { - if ($this->_locale !== null) { - return $this->_locale; - } else { - if (($locale = self::getDefaultLocale()) !== null) { - return $locale; - } else { - try { - $locale = Zend_Registry::get('Zend_Locale'); - } catch (Zend_Exception $e) { - $locale = null; - } - - if ($locale !== null) { - return $locale; - } - } - } - - return null; + return $this->_locale; } } diff --git a/library/Zend/Controller/Router/Route/Chain.php b/library/Zend/Controller/Router/Route/Chain.php index e05910dff1..f5bf71ade2 100644 --- a/library/Zend/Controller/Router/Route/Chain.php +++ b/library/Zend/Controller/Router/Route/Chain.php @@ -34,6 +34,7 @@ class Zend_Controller_Router_Route_Chain extends Zend_Controller_Router_Route_Abstract { + public ?\Zend_Controller_Request_Abstract $_request; /** * Routes * diff --git a/library/Zend/Controller/Router/Route/Hostname.php b/library/Zend/Controller/Router/Route/Hostname.php index 21cbe1d659..934796995f 100644 --- a/library/Zend/Controller/Router/Route/Hostname.php +++ b/library/Zend/Controller/Router/Route/Hostname.php @@ -133,7 +133,7 @@ public function setRequest(Zend_Controller_Request_Abstract $request = null) */ public function getRequest() { - if ($this->_request === null) { + if (!$this->_request instanceof \Zend_Controller_Request_Abstract) { require_once 'Zend/Controller/Front.php'; $this->_request = Zend_Controller_Front::getInstance()->getRequest(); } @@ -151,7 +151,7 @@ public static function getInstance(Zend_Config $config) { $reqs = ($config->reqs instanceof Zend_Config) ? $config->reqs->toArray() : array(); $defs = ($config->defaults instanceof Zend_Config) ? $config->defaults->toArray() : array(); - $scheme = (isset($config->scheme)) ? $config->scheme : null; + $scheme = (property_exists($config, 'scheme') && $config->scheme !== null) ? $config->scheme : null; return new self($config->route, $defs, $reqs, $scheme); } @@ -175,7 +175,7 @@ public function __construct($route, $defaults = array(), $reqs = array(), $schem if ($route != '') { foreach (explode('.', $route) as $pos => $part) { - if (substr($part, 0, 1) == $this->_hostVariable) { + if (substr($part, 0, 1) === $this->_hostVariable) { $name = substr($part, 1); $this->_parts[$pos] = (isset($reqs[$name]) ? $reqs[$name] : $this->_defaultRegex); $this->_variables[$pos] = $name; @@ -331,16 +331,10 @@ public function assemble($data = array(), $reset = false, $encode = false, $part $scheme = $this->_scheme; } else { $request = $this->getRequest(); - if ($request instanceof Zend_Controller_Request_Http) { - $scheme = $request->getScheme(); - } else { - $scheme = 'http'; - } + $scheme = $request instanceof Zend_Controller_Request_Http ? $request->getScheme() : 'http'; } - $url = $scheme . '://' . $url; - - return $url; + return $scheme . '://' . $url; } /** diff --git a/library/Zend/Controller/Router/Route/Module.php b/library/Zend/Controller/Router/Route/Module.php index 581a89b1bc..5ff51dbda0 100644 --- a/library/Zend/Controller/Router/Route/Module.php +++ b/library/Zend/Controller/Router/Route/Module.php @@ -197,8 +197,8 @@ public function match($path, $partial = false) $values[$this->_actionKey] = array_shift($path); } - if ($numSegs = count($path)) { - for ($i = 0; $i < $numSegs; $i = $i + 2) { + if (($numSegs = count($path)) !== 0) { + for ($i = 0; $i < $numSegs; $i += 2) { $key = urldecode($path[$i]); $val = isset($path[$i + 1]) ? urldecode($path[$i + 1]) : null; $params[$key] = (isset($params[$key]) ? (array_merge((array)$params[$key], array($val))) : $val); @@ -230,7 +230,7 @@ public function assemble($data = array(), $reset = false, $encode = true, $parti $this->_setRequestKeys(); } - $params = (!$reset) ? $this->_values : array(); + $params = ($reset) ? array() : $this->_values; foreach ($data as $key => $value) { if ($value !== null) { @@ -244,10 +244,8 @@ public function assemble($data = array(), $reset = false, $encode = true, $parti $url = ''; - if ($this->_moduleValid || array_key_exists($this->_moduleKey, $data)) { - if ($params[$this->_moduleKey] != $this->_defaults[$this->_moduleKey]) { - $module = $params[$this->_moduleKey]; - } + if (($this->_moduleValid || array_key_exists($this->_moduleKey, $data)) && $params[$this->_moduleKey] != $this->_defaults[$this->_moduleKey]) { + $module = $params[$this->_moduleKey]; } unset($params[$this->_moduleKey]); diff --git a/library/Zend/Controller/Router/Route/Regex.php b/library/Zend/Controller/Router/Route/Regex.php index e012357d7b..4323ea58b9 100644 --- a/library/Zend/Controller/Router/Route/Regex.php +++ b/library/Zend/Controller/Router/Route/Regex.php @@ -79,7 +79,7 @@ public static function getInstance(Zend_Config $config) { $defs = ($config->defaults instanceof Zend_Config) ? $config->defaults->toArray() : array(); $map = ($config->map instanceof Zend_Config) ? $config->map->toArray() : array(); - $reverse = (isset($config->reverse)) ? $config->reverse : null; + $reverse = (property_exists($config, 'reverse') && $config->reverse !== null) ? $config->reverse : null; return new self($config->route, $defs, $map, $reverse); } @@ -147,9 +147,8 @@ public function match($path, $partial = false) $values = $this->_getMappedValues($values); $defaults = $this->_getMappedValues($this->_defaults, false, true); - $return = $values + $defaults; - return $return; + return $values + $defaults; } /** @@ -185,11 +184,7 @@ protected function _getMappedValues($values, $reversed = false, $preserve = fals } elseif ($reversed) { $index = $key; if (!is_int($key)) { - if (array_key_exists($key, $this->_map)) { - $index = $this->_map[$key]; - } else { - $index = array_search($key, $this->_map, true); - } + $index = array_key_exists($key, $this->_map) ? $this->_map[$key] : array_search($key, $this->_map, true); } if (false !== $index) { $return[$index] = $values[$key]; @@ -289,11 +284,7 @@ public function getVariables() $variables = array(); foreach ($this->_map as $key => $value) { - if (is_numeric($key)) { - $variables[] = $value; - } else { - $variables[] = $key; - } + $variables[] = is_numeric($key) ? $value : $key; } return $variables; diff --git a/library/Zend/Controller/Router/Route/Static.php b/library/Zend/Controller/Router/Route/Static.php index 2acf62b4b3..fcbd93889f 100644 --- a/library/Zend/Controller/Router/Route/Static.php +++ b/library/Zend/Controller/Router/Route/Static.php @@ -102,10 +102,8 @@ public function match($path, $partial = false) return $this->_defaults; } - } else { - if (trim($path, self::URI_DELIMITER) == $this->_route) { - return $this->_defaults; - } + } elseif (trim($path, self::URI_DELIMITER) == $this->_route) { + return $this->_defaults; } return false; diff --git a/library/Zend/Crypt.php b/library/Zend/Crypt.php index 0ceeac71e3..fb86d52545 100644 --- a/library/Zend/Crypt.php +++ b/library/Zend/Crypt.php @@ -86,8 +86,7 @@ public static function hash($algorithm, $data, $binaryOutput = false) } self::_detectHashSupport($algorithm); $supportedMethod = '_digest' . ucfirst(self::$_type); - $result = self::$supportedMethod($algorithm, $data, $binaryOutput); - return $result; + return self::$supportedMethod($algorithm, $data, $binaryOutput); } /** diff --git a/library/Zend/Crypt/DiffieHellman.php b/library/Zend/Crypt/DiffieHellman.php index 03463a59a5..c96ee098b0 100644 --- a/library/Zend/Crypt/DiffieHellman.php +++ b/library/Zend/Crypt/DiffieHellman.php @@ -121,7 +121,7 @@ public function __construct($prime, $generator, $privateKey = null, $privateKeyT */ public function generateKeys() { - if (function_exists('openssl_dh_compute_key') && self::$useOpenssl !== false) { + if (function_exists('openssl_dh_compute_key') && self::$useOpenssl) { $details = array(); $details['p'] = $this->getPrime(); $details['g'] = $this->getGenerator(); @@ -209,7 +209,7 @@ public function computeSecretKey($publicKey, $type = self::NUMBER, $output = sel require_once('Zend/Crypt/DiffieHellman/Exception.php'); throw new Zend_Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number'); } - if (function_exists('openssl_dh_compute_key') && self::$useOpenssl !== false) { + if (function_exists('openssl_dh_compute_key') && self::$useOpenssl) { $this->_secretKey = openssl_dh_compute_key($publicKey, $this->getPublicKey()); } else { $this->_secretKey = $this->_math->powmod($publicKey, $this->getPrivateKey(), $this->getPrime()); @@ -226,7 +226,7 @@ public function computeSecretKey($publicKey, $type = self::NUMBER, $output = sel */ public function getSharedSecretKey($type = self::NUMBER) { - if (!isset($this->_secretKey)) { + if (!($this->_secretKey !== null)) { require_once('Zend/Crypt/DiffieHellman/Exception.php'); throw new Zend_Crypt_DiffieHellman_Exception('A secret key has not yet been computed; call computeSecretKey()'); } @@ -263,7 +263,7 @@ public function setPrime($number) */ public function getPrime() { - if (!isset($this->_prime)) { + if (!($this->_prime !== null)) { require_once('Zend/Crypt/DiffieHellman/Exception.php'); throw new Zend_Crypt_DiffieHellman_Exception('No prime number has been set'); } @@ -295,7 +295,7 @@ public function setGenerator($number) */ public function getGenerator() { - if (!isset($this->_generator)) { + if (!($this->_generator !== null)) { require_once('Zend/Crypt/DiffieHellman/Exception.php'); throw new Zend_Crypt_DiffieHellman_Exception('No generator number has been set'); } @@ -349,7 +349,7 @@ public function getPrivateKey($type = self::NUMBER) */ public function hasPrivateKey() { - return isset($this->_privateKey); + return $this->_privateKey !== null; } /** @@ -381,8 +381,7 @@ public function setBigIntegerMath($extension = null) */ protected function _generatePrivateKey() { - $rand = $this->_math->rand($this->getGenerator(), $this->getPrime()); - return $rand; + return $this->_math->rand($this->getGenerator(), $this->getPrime()); } } diff --git a/library/Zend/Crypt/Hmac.php b/library/Zend/Crypt/Hmac.php index b11eb4d749..4ff711915a 100644 --- a/library/Zend/Crypt/Hmac.php +++ b/library/Zend/Crypt/Hmac.php @@ -125,11 +125,11 @@ protected static function _setHashAlgorithm($hash) $hashSupported = true; } - if ($hashSupported === false && function_exists('mhash') && in_array($hash, self::$_supportedAlgosMhash)) { + if (!$hashSupported && function_exists('mhash') && in_array($hash, self::$_supportedAlgosMhash)) { $hashSupported = true; } - if ($hashSupported === false) { + if (!$hashSupported) { require_once 'Zend/Crypt/Hmac/Exception.php'; throw new Zend_Crypt_Hmac_Exception('hash algorithm provided is not supported on this PHP installation; please enable the hash or mhash extensions'); } diff --git a/library/Zend/Crypt/Math.php b/library/Zend/Crypt/Math.php index 6c8687a893..844d78c0c2 100644 --- a/library/Zend/Crypt/Math.php +++ b/library/Zend/Crypt/Math.php @@ -60,8 +60,7 @@ public function rand($minimum, $maximum) for ($i = 1; $i < $i2; $i++) { $rand .= mt_rand(0, 9); } - $rand .= mt_rand(0, 9); - return $rand; + return $rand . mt_rand(0, 9); } /** @@ -92,7 +91,7 @@ public static function randBytes($length, $strong = false) return fread($frandom, $length); } } - if (true === $strong) { + if ($strong) { require_once 'Zend/Crypt/Exception.php'; throw new Zend_Crypt_Exception( 'This PHP environment doesn\'t support secure random number generation. ' . diff --git a/library/Zend/Crypt/Math/BigInteger/Gmp.php b/library/Zend/Crypt/Math/BigInteger/Gmp.php index 33196edc2a..bcacae1e0a 100644 --- a/library/Zend/Crypt/Math/BigInteger/Gmp.php +++ b/library/Zend/Crypt/Math/BigInteger/Gmp.php @@ -195,11 +195,10 @@ public function integerToBinary($operand) $bigInt = gmp_strval($operand, 16); if (strlen($bigInt) % 2 != 0) { $bigInt = '0' . $bigInt; - } else if ($bigInt[0] > '7') { + } elseif ($bigInt[0] > '7') { $bigInt = '00' . $bigInt; } - $return = pack("H*", $bigInt); - return $return; + return pack("H*", $bigInt); } /** diff --git a/library/Zend/Crypt/Rsa.php b/library/Zend/Crypt/Rsa.php index 84e6e76848..4c42b0b482 100644 --- a/library/Zend/Crypt/Rsa.php +++ b/library/Zend/Crypt/Rsa.php @@ -155,10 +155,9 @@ public function verifySignature($data, $signature, $format = null) if ($format == self::BASE64) { $signature = base64_decode($signature); } - $result = openssl_verify($data, $signature, + return openssl_verify($data, $signature, $this->getPublicKey()->getOpensslKeyResource(), $this->getHashAlgorithm()); - return $result; } /** @@ -231,11 +230,10 @@ public function generateKeys(array $configargs = null) $privateKey = new Zend_Crypt_Rsa_Key_Private($private, $passPhrase); $details = openssl_pkey_get_details($resource); $publicKey = new Zend_Crypt_Rsa_Key_Public($details['key']); - $return = new ArrayObject(array( + return new ArrayObject(array( 'privateKey'=>$privateKey, 'publicKey'=>$publicKey ), ArrayObject::ARRAY_AS_PROPS); - return $return; } /** diff --git a/library/Zend/Crypt/Rsa/Key.php b/library/Zend/Crypt/Rsa/Key.php index fafde02f57..23815d8e0d 100644 --- a/library/Zend/Crypt/Rsa/Key.php +++ b/library/Zend/Crypt/Rsa/Key.php @@ -28,6 +28,7 @@ */ class Zend_Crypt_Rsa_Key implements Countable { + public $_certificateString; /** * @var string */ diff --git a/library/Zend/Currency.php b/library/Zend/Currency.php index d8b1dcda8c..68df473fd1 100644 --- a/library/Zend/Currency.php +++ b/library/Zend/Currency.php @@ -99,7 +99,7 @@ public function __construct($options = null, $locale = null) if (is_array($options)) { $this->setLocale($locale); $this->setFormat($options); - } else if (Zend_Locale::isLocale($options, false, false)) { + } elseif (Zend_Locale::isLocale($options, false, false)) { $this->setLocale($options); $options = $locale; } else { @@ -119,7 +119,7 @@ public function __construct($options = null, $locale = null) $this->_options['symbol'] = self::getSymbol($options, $this->_options['locale']); } - if (($this->_options['currency'] === null) and ($this->_options['name'] === null)) { + if ($this->_options['currency'] === null && $this->_options['name'] === null) { require_once 'Zend/Currency/Exception.php'; throw new Zend_Currency_Exception("Currency '$options' not found"); } @@ -129,7 +129,7 @@ public function __construct($options = null, $locale = null) || (!is_array($calloptions) && $this->_options['display'] == self::NO_SYMBOL)) { if (!empty($this->_options['symbol'])) { $this->_options['display'] = self::USE_SYMBOL; - } else if (!empty($this->_options['currency'])) { + } elseif (!empty($this->_options['currency'])) { $this->_options['display'] = self::USE_SHORTNAME; } } @@ -146,11 +146,7 @@ public function __construct($options = null, $locale = null) public function toCurrency($value = null, array $options = array()) { if ($value === null) { - if (is_array($options) && isset($options['value'])) { - $value = $options['value']; - } else { - $value = $this->_options['value']; - } + $value = is_array($options) && isset($options['value']) ? $options['value'] : $this->_options['value']; } if (is_array($value)) { @@ -161,7 +157,7 @@ public function toCurrency($value = null, array $options = array()) } // Validate the passed number - if (!(isset($value)) or (is_numeric($value) === false)) { + if (!(isset($value)) || !is_numeric($value)) { require_once 'Zend/Currency/Exception.php'; throw new Zend_Currency_Exception("Value '$value' has to be numeric"); } @@ -183,7 +179,7 @@ public function toCurrency($value = null, array $options = array()) $locale = $options['locale']; if (empty($format)) { $format = Zend_Locale_Data::getContent($locale, 'currencynumber'); - } else if (Zend_Locale::isLocale($format, true, false)) { + } elseif (Zend_Locale::isLocale($format, true, false)) { $locale = $format; $format = Zend_Locale_Data::getContent($format, 'currencynumber'); } @@ -201,20 +197,16 @@ public function toCurrency($value = null, array $options = array()) $space = ' '; } - if ($options['position'] == self::LEFT) { - $value = '¤' . $space . $value; - } else { - $value = $value . $space . '¤'; - } + $value = $options['position'] == self::LEFT ? '¤' . $space . $value : $value . $space . '¤'; } // Localize the number digits - if (empty($options['script']) === false) { + if (!empty($options['script'])) { $value = Zend_Locale_Format::convertNumerals($value, 'Latn', $options['script']); } // Get the sign to be placed next to the number - if (is_numeric($options['display']) === false) { + if (!is_numeric($options['display'])) { $sign = $options['display']; } else { switch($options['display']) { @@ -236,9 +228,7 @@ public function toCurrency($value = null, array $options = array()) break; } } - - $value = str_replace('¤', $sign, $value); - return $value; + return str_replace('¤', $sign, $value); } /** @@ -304,15 +294,14 @@ public function setFormat(array $options = array()) private function _checkParams($currency = null, $locale = null) { // Manage the params - if ((empty($locale)) and (!empty($currency)) and - (Zend_Locale::isLocale($currency, true, false))) { + if (empty($locale) && !empty($currency) && Zend_Locale::isLocale($currency, true, false)) { $locale = $currency; $currency = null; } // Validate the locale and get the country short name $country = null; - if ((Zend_Locale::isLocale($locale, true, false)) and (strlen((string) $locale) > 4)) { + if (Zend_Locale::isLocale($locale, true, false) && strlen((string) $locale) > 4) { $country = substr($locale, (strpos($locale, '_') + 1)); } else { require_once 'Zend/Currency/Exception.php'; @@ -321,11 +310,7 @@ private function _checkParams($currency = null, $locale = null) // Get the available currencies for this country $data = Zend_Locale_Data::getContent($locale, 'currencytoregion', $country); - if ((empty($currency) === false) and (empty($data) === false)) { - $abbreviation = $currency; - } else { - $abbreviation = $data; - } + $abbreviation = (!empty($currency) && !empty($data)) ? $currency : $data; return array('locale' => $locale, 'currency' => $currency, 'name' => $abbreviation, 'country' => $country); } @@ -340,7 +325,7 @@ private function _checkParams($currency = null, $locale = null) */ public function getSymbol($currency = null, $locale = null) { - if (($currency === null) and ($locale === null)) { + if ($currency === null && $locale === null) { return $this->_options['symbol']; } @@ -348,11 +333,11 @@ public function getSymbol($currency = null, $locale = null) // Get the symbol $symbol = Zend_Locale_Data::getContent($params['locale'], 'currencysymbol', $params['currency']); - if (empty($symbol) === true) { + if (empty($symbol)) { $symbol = Zend_Locale_Data::getContent($params['locale'], 'currencysymbol', $params['name']); } - if (empty($symbol) === true) { + if (empty($symbol)) { return null; } @@ -368,14 +353,14 @@ public function getSymbol($currency = null, $locale = null) */ public function getShortName($currency = null, $locale = null) { - if (($currency === null) and ($locale === null)) { + if ($currency === null && $locale === null) { return $this->_options['currency']; } $params = self::_checkParams($currency, $locale); // Get the shortname - if (empty($params['currency']) === true) { + if (empty($params['currency'])) { return $params['name']; } @@ -403,7 +388,7 @@ public function getShortName($currency = null, $locale = null) */ public function getName($currency = null, $locale = null) { - if (($currency === null) and ($locale === null)) { + if ($currency === null && $locale === null) { return $this->_options['name']; } @@ -411,11 +396,11 @@ public function getName($currency = null, $locale = null) // Get the name $name = Zend_Locale_Data::getContent($params['locale'], 'nametocurrency', $params['currency']); - if (empty($name) === true) { + if (empty($name)) { $name = Zend_Locale_Data::getContent($params['locale'], 'nametocurrency', $params['name']); } - if (empty($name) === true) { + if (empty($name)) { return null; } @@ -435,15 +420,13 @@ public function getRegionList($currency = null) $currency = $this->_options['currency']; } - if (empty($currency) === true) { + if (empty($currency)) { require_once 'Zend/Currency/Exception.php'; throw new Zend_Currency_Exception('No currency defined'); } $data = Zend_Locale_Data::getContent($this->_options['locale'], 'regiontocurrency', $currency); - - $result = explode(' ', $data); - return $result; + return explode(' ', $data); } /** @@ -456,16 +439,12 @@ public function getRegionList($currency = null) */ public function getCurrencyList($region = null) { - if (empty($region) === true) { - if (strlen((string) $this->_options['locale']) > 4) { - $region = substr($this->_options['locale'], (strpos($this->_options['locale'], '_') + 1)); - } + if (empty($region) && strlen((string) $this->_options['locale']) > 4) { + $region = substr($this->_options['locale'], (strpos($this->_options['locale'], '_') + 1)); } $data = Zend_Locale_Data::getContent($this->_options['locale'], 'currencytoregion', $region); - - $result = explode(' ', $data); - return $result; + return explode(' ', $data); } /** @@ -537,7 +516,7 @@ public static function removeCache() */ public static function clearCache($tag = null) { - Zend_Locale_Data::clearCache($tag); + Zend_Locale_Data::clearCache(); } /** @@ -562,7 +541,7 @@ public function setLocale($locale = null) } } catch (Zend_Locale_Exception $e) { require_once 'Zend/Currency/Exception.php'; - throw new Zend_Currency_Exception($e->getMessage()); + throw new Zend_Currency_Exception($e->getMessage(), $e->getCode(), $e); } // Get currency details @@ -689,7 +668,7 @@ public function compare($value, $currency = null) $value = $this->_options['value'] - $value; if ($value < 0) { return -1; - } else if ($value > 0) { + } elseif ($value > 0) { return 1; } @@ -706,11 +685,7 @@ public function compare($value, $currency = null) public function equals($value, $currency = null) { $value = $this->_exchangeCurrency($value, $currency); - if ($this->_options['value'] == $value) { - return true; - } - - return false; + return $this->_options['value'] == $value; } /** @@ -723,11 +698,7 @@ public function equals($value, $currency = null) public function isMore($value, $currency = null) { $value = $this->_exchangeCurrency($value, $currency); - if ($this->_options['value'] > $value) { - return true; - } - - return false; + return $this->_options['value'] > $value; } /** @@ -740,11 +711,7 @@ public function isMore($value, $currency = null) public function isLess($value, $currency = null) { $value = $this->_exchangeCurrency($value, $currency); - if ($this->_options['value'] < $value) { - return true; - } - - return false; + return $this->_options['value'] < $value; } @@ -774,9 +741,7 @@ protected function _exchangeCurrency($value, $currency) $rate = $service->getRate($currency, $this->getShortName()); } - - $value *= $rate; - return $value; + return $value * $rate; } /** @@ -832,21 +797,19 @@ public function setService($service) */ protected function _checkOptions(array $options = array()) { - if (count($options) === 0) { + if ($options === []) { return $this->_options; } foreach ($options as $name => $value) { $name = strtolower($name); - if ($name !== 'format') { - if (gettype($value) === 'string') { - $value = strtolower($value); - } + if ($name !== 'format' && gettype($value) === 'string') { + $value = strtolower($value); } switch($name) { case 'position': - if (($value !== self::STANDARD) and ($value !== self::RIGHT) and ($value !== self::LEFT)) { + if ($value !== self::STANDARD && $value !== self::RIGHT && $value !== self::LEFT) { require_once 'Zend/Currency/Exception.php'; throw new Zend_Currency_Exception("Unknown position '" . $value . "'"); } @@ -854,19 +817,16 @@ protected function _checkOptions(array $options = array()) break; case 'format': - if ((empty($value) === false) and (Zend_Locale::isLocale($value, null, false) === false)) { - if (!is_string($value) || (strpos($value, '0') === false)) { - require_once 'Zend/Currency/Exception.php'; - throw new Zend_Currency_Exception("'" . - ((gettype($value) === 'object') ? get_class($value) : $value) - . "' is no format token"); - } + if ((!empty($value) && !Zend_Locale::isLocale($value, null, false)) && (!is_string($value) || (strpos($value, '0') === false))) { + require_once 'Zend/Currency/Exception.php'; + throw new Zend_Currency_Exception("'" . + ((gettype($value) === 'object') ? get_class($value) : $value) + . "' is no format token"); } break; case 'display': - if (is_numeric($value) and ($value !== self::NO_SYMBOL) and ($value !== self::USE_SYMBOL) and - ($value !== self::USE_SHORTNAME) and ($value !== self::USE_NAME)) { + if (is_numeric($value) && $value !== self::NO_SYMBOL && $value !== self::USE_SYMBOL && $value !== self::USE_SHORTNAME && $value !== self::USE_NAME) { require_once 'Zend/Currency/Exception.php'; throw new Zend_Currency_Exception("Unknown display '$value'"); } @@ -877,7 +837,7 @@ protected function _checkOptions(array $options = array()) $value = -1; } - if (($value < -1) or ($value > 30)) { + if ($value < -1 || $value > 30) { require_once 'Zend/Currency/Exception.php'; throw new Zend_Currency_Exception("'$value' precision has to be between -1 and 30."); } @@ -888,7 +848,7 @@ protected function _checkOptions(array $options = array()) Zend_Locale_Format::convertNumerals(0, $options['script']); } catch (Zend_Locale_Exception $e) { require_once 'Zend/Currency/Exception.php'; - throw new Zend_Currency_Exception($e->getMessage()); + throw new Zend_Currency_Exception($e->getMessage(), $e->getCode(), $e); } break; diff --git a/library/Zend/Date.php b/library/Zend/Date.php index 101d96929d..ce1467bbb5 100644 --- a/library/Zend/Date.php +++ b/library/Zend/Date.php @@ -136,8 +136,7 @@ class Zend_Date extends Zend_Date_DateObject */ public function __construct($date = null, $part = null, $locale = null) { - if (is_object($date) and !($date instanceof Zend_TimeSync_Protocol) and - !($date instanceof Zend_Date)) { + if (is_object($date) && !($date instanceof Zend_TimeSync_Protocol) && !($date instanceof Zend_Date)) { if ($locale instanceof Zend_Locale) { $locale = $date; $date = null; @@ -147,12 +146,11 @@ public function __construct($date = null, $part = null, $locale = null) } } - if (($date !== null) and !is_array($date) and !($date instanceof Zend_TimeSync_Protocol) and - !($date instanceof Zend_Date) and !defined($date) and Zend_Locale::isLocale($date, true, false)) { + if ($date !== null && !is_array($date) && !($date instanceof Zend_TimeSync_Protocol) && !($date instanceof Zend_Date) && !defined($date) && Zend_Locale::isLocale($date, true, false)) { $locale = $date; $date = null; $part = null; - } else if (($part !== null) and !defined($part) and Zend_Locale::isLocale($part, true, false)) { + } elseif ($part !== null && !defined($part) && Zend_Locale::isLocale($part, true, false)) { $locale = $part; $part = null; } @@ -166,7 +164,7 @@ public function __construct($date = null, $part = null, $locale = null) if ($date === null) { if ($part === null) { $date = time(); - } else if ($part !== self::TIMESTAMP) { + } elseif ($part !== self::TIMESTAMP) { $date = self::now($locale); $date = $date->get($part); } @@ -176,7 +174,7 @@ public function __construct($date = null, $part = null, $locale = null) $date = $date->getInfo(); $date = $this->_getTime($date['offset']); $part = null; - } else if (parent::$_defaultOffset != 0) { + } elseif (parent::$_defaultOffset != 0) { $date = $this->_getTime(parent::$_defaultOffset); } @@ -191,13 +189,13 @@ public function __construct($date = null, $part = null, $locale = null) } // set datepart - if (($part !== null && $part !== self::TIMESTAMP) or (!is_numeric($date))) { + if ($part !== null && $part !== self::TIMESTAMP || !is_numeric($date)) { // switch off dst handling for value setting $this->setUnixTimestamp($this->getGmtOffset()); $this->set($date, $part, $this->_locale); // DST fix - if (is_array($date) === true) { + if (is_array($date)) { if (!isset($date['hour'])) { $date['hour'] = 0; } @@ -331,7 +329,7 @@ private function _timestamp($calc, $stamp) } if (is_array($stamp)) { - if (isset($stamp['timestamp']) === true) { + if (isset($stamp['timestamp'])) { $stamp = $stamp['timestamp']; } else { require_once 'Zend/Date/Exception.php'; @@ -339,11 +337,7 @@ private function _timestamp($calc, $stamp) } } - if ($calc === 'set') { - $return = $this->setUnixTimestamp($stamp); - } else { - $return = $this->_calcdetail($calc, $stamp, self::TIMESTAMP, null); - } + $return = $calc === 'set' ? $this->setUnixTimestamp($stamp) : $this->_calcdetail($calc, $stamp, self::TIMESTAMP, null); if ($calc != 'cmp') { return $this; } @@ -447,8 +441,7 @@ public function toString($format = null, $type = null, $locale = null) $format = null; } - if (($type !== null) and ($type != 'php') and ($type != 'iso') and - Zend_Locale::isLocale($type, null, false)) { + if ($type !== null && $type != 'php' && $type != 'iso' && Zend_Locale::isLocale($type, null, false)) { $locale = $type; $type = null; } @@ -459,7 +452,7 @@ public function toString($format = null, $type = null, $locale = null) if ($format === null) { $format = Zend_Locale_Format::getDateFormat($locale) . ' ' . Zend_Locale_Format::getTimeFormat($locale); - } else if (((self::$_options['format_type'] == 'php') && ($type === null)) or ($type == 'php')) { + } elseif ((self::$_options['format_type'] == 'php') && ($type === null) || $type == 'php') { $format = Zend_Locale_Format::convertPhpToIsoFormat($format); } @@ -487,7 +480,7 @@ public function toValue($part = null) { $result = $this->get($part); if (is_numeric($result)) { - return intval("$result"); + return (int) "$result"; } else { return false; } @@ -539,7 +532,7 @@ public function get($part = null, $locale = null) if ($part === null) { $part = self::TIMESTAMP; - } else if (self::$_options['format_type'] == 'php') { + } elseif (self::$_options['format_type'] == 'php') { $part = Zend_Locale_Format::convertPhpToIsoFormat($part); } @@ -560,9 +553,9 @@ private function _toToken($part, $locale) { $orig = ''; for ($i = 0; isset($part[$i]); ++$i) { if ($part[$i] == "'") { - $comment = $comment ? false : true; + $comment = !$comment; if (isset($part[$i+1]) && ($part[$i+1] == "'")) { - $comment = $comment ? false : true; + $comment = !$comment; $format .= "\\'"; ++$i; } @@ -576,7 +569,7 @@ private function _toToken($part, $locale) { $orig = ''; } else { $orig .= $part[$i]; - if (!isset($part[$i+1]) || (isset($orig[0]) && ($orig[0] != $part[$i+1]))) { + if (!isset($part[$i+1]) || (isset($orig[0]) && ($orig[0] !== $part[$i+1]))) { $format .= $this->_parseIsoToDate($orig, $locale); $orig = ''; } @@ -1047,7 +1040,7 @@ public static function getFullYear($value) if ($value >= 0) { if ($value < 70) { $value += 2000; - } else if ($value < 100) { + } elseif ($value < 100) { $value += 1900; } } @@ -1147,7 +1140,7 @@ public function compare($date, $part = self::TIMESTAMP, $locale = null) if ($compare > 0) { return 1; - } else if ($compare < 0) { + } elseif ($compare < 0) { return -1; } return 0; @@ -1201,7 +1194,7 @@ public function getTimezoneFromString($zone) } preg_match('/([+-]\d{2}):{0,1}\d{2}/', $zone, $match); - if (!empty($match) and ($match[count($match) - 1] <= 14) and ($match[count($match) - 1] >= -12)) { + if (!empty($match) && $match[count($match) - 1] <= 14 && $match[count($match) - 1] >= -12) { $zone = "Etc/GMT"; $zone .= ($match[count($match) - 1] < 0) ? "+" : "-"; $zone .= (int) abs($match[count($match) - 1]); @@ -1210,7 +1203,7 @@ public function getTimezoneFromString($zone) preg_match('/([[:alpha:]\/_]{3,30})(?!.*([[:alpha:]\/]{3,30}))/', $zone, $match); try { - if (!empty($match) and (!is_int($match[count($match) - 1]))) { + if (!empty($match) && !is_int($match[count($match) - 1])) { $oldzone = $this->getTimezone(); $this->setTimezone($match[count($match) - 1]); $result = $this->getTimezone(); @@ -1260,12 +1253,12 @@ private function _assign($calc, $date, $comp = 0, $dst = false) } // dst-correction if 'fix_dst' = true and dst !== false but only for non UTC and non GMT - if ((self::$_options['fix_dst'] === true) and ($dst !== false) and ($this->_dst === true)) { + if (self::$_options['fix_dst'] === true && $dst !== false && $this->_dst === true) { $hour = $this->toString(self::HOUR, 'iso'); if ($hour != $dst) { - if (($dst == ($hour + 1)) or ($dst == ($hour - 23))) { + if ($dst == ($hour + 1) || $dst == ($hour - 23)) { $value += 3600; - } else if (($dst == ($hour - 1)) or ($dst == ($hour + 23))) { + } elseif ($dst == ($hour - 1) || $dst == ($hour + 23)) { $value -= 3600; } $this->setUnixTimestamp($value); @@ -1315,13 +1308,13 @@ private function _calculate($calc, $date, $part, $locale) $date = $date->toString($part, 'iso', $locale); } - if (is_array($date) === true) { - if (empty($part) === false) { + if (is_array($date)) { + if (!empty($part)) { switch($part) { // Fall through case self::DAY: case self::DAY_SHORT: - if (isset($date['day']) === true) { + if (isset($date['day'])) { $date = $date['day']; } break; @@ -1332,13 +1325,13 @@ private function _calculate($calc, $date, $part, $locale) case self::WEEKDAY_DIGIT: case self::WEEKDAY_NARROW: case self::WEEKDAY_NAME: - if (isset($date['weekday']) === true) { + if (isset($date['weekday'])) { $date = $date['weekday']; $part = self::WEEKDAY_DIGIT; } break; case self::DAY_OF_YEAR: - if (isset($date['day_of_year']) === true) { + if (isset($date['day_of_year'])) { $date = $date['day_of_year']; } break; @@ -1348,7 +1341,7 @@ private function _calculate($calc, $date, $part, $locale) case self::MONTH_NAME: case self::MONTH_NAME_SHORT: case self::MONTH_NAME_NARROW: - if (isset($date['month']) === true) { + if (isset($date['month'])) { $date = $date['month']; } break; @@ -1357,7 +1350,7 @@ private function _calculate($calc, $date, $part, $locale) case self::YEAR_SHORT: case self::YEAR_8601: case self::YEAR_SHORT_8601: - if (isset($date['year']) === true) { + if (isset($date['year'])) { $date = $date['year']; } break; @@ -1366,43 +1359,43 @@ private function _calculate($calc, $date, $part, $locale) case self::HOUR_AM: case self::HOUR_SHORT: case self::HOUR_SHORT_AM: - if (isset($date['hour']) === true) { + if (isset($date['hour'])) { $date = $date['hour']; } break; // Fall through case self::MINUTE: case self::MINUTE_SHORT: - if (isset($date['minute']) === true) { + if (isset($date['minute'])) { $date = $date['minute']; } break; // Fall through case self::SECOND: case self::SECOND_SHORT: - if (isset($date['second']) === true) { + if (isset($date['second'])) { $date = $date['second']; } break; // Fall through case self::TIMEZONE: case self::TIMEZONE_NAME: - if (isset($date['timezone']) === true) { + if (isset($date['timezone'])) { $date = $date['timezone']; } break; case self::TIMESTAMP: - if (isset($date['timestamp']) === true) { + if (isset($date['timestamp'])) { $date = $date['timestamp']; } break; case self::WEEK: - if (isset($date['week']) === true) { + if (isset($date['week'])) { $date = $date['week']; } break; case self::TIMEZONE_SECS: - if (isset($date['gmtsecs']) === true) { + if (isset($date['gmtsecs'])) { $date = $date['gmtsecs']; } break; @@ -1413,27 +1406,27 @@ private function _calculate($calc, $date, $part, $locale) } } else { $hours = 0; - if (isset($date['hour']) === true) { + if (isset($date['hour'])) { $hours = $date['hour']; } $minutes = 0; - if (isset($date['minute']) === true) { + if (isset($date['minute'])) { $minutes = $date['minute']; } $seconds = 0; - if (isset($date['second']) === true) { + if (isset($date['second'])) { $seconds = $date['second']; } $months = 0; - if (isset($date['month']) === true) { + if (isset($date['month'])) { $months = $date['month']; } $days = 0; - if (isset($date['day']) === true) { + if (isset($date['day'])) { $days = $date['day']; } $years = 0; - if (isset($date['year']) === true) { + if (isset($date['year'])) { $years = $date['year']; } return $this->_assign($calc, $this->mktime($hours, $minutes, $seconds, $months, $days, $years, true), @@ -1447,8 +1440,8 @@ private function _calculate($calc, $date, $part, $locale) // day formats case self::DAY: if (is_numeric($date)) { - return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + intval($date), 1970, true), - $this->mktime(0, 0, 0, 1, 1 + intval($day), 1970, true), $hour); + return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + (int) $date, 1970, true), + $this->mktime(0, 0, 0, 1, 1 + (int) $day, 1970, true), $hour); } require_once 'Zend/Date/Exception.php'; @@ -1461,7 +1454,7 @@ private function _calculate($calc, $date, $part, $locale) $cnt = 0; foreach ($daylist as $key => $value) { - if (strtoupper(iconv_substr($value, 0, 3, 'UTF-8')) == strtoupper($date)) { + if (strtoupper(iconv_substr($value, 0, 3, 'UTF-8')) === strtoupper($date)) { $found = $cnt; break; } @@ -1481,8 +1474,8 @@ private function _calculate($calc, $date, $part, $locale) case self::DAY_SHORT: if (is_numeric($date)) { - return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + intval($date), 1970, true), - $this->mktime(0, 0, 0, 1, 1 + intval($day), 1970, true), $hour); + return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + (int) $date, 1970, true), + $this->mktime(0, 0, 0, 1, 1 + (int) $day, 1970, true), $hour); } require_once 'Zend/Date/Exception.php'; @@ -1495,7 +1488,7 @@ private function _calculate($calc, $date, $part, $locale) $cnt = 0; foreach ($daylist as $key => $value) { - if (strtoupper($value) == strtoupper($date)) { + if (strtoupper($value) === strtoupper($date)) { $found = $cnt; break; } @@ -1515,8 +1508,8 @@ private function _calculate($calc, $date, $part, $locale) case self::WEEKDAY_8601: $weekday = (int) $this->toString(self::WEEKDAY_8601, 'iso', $locale); - if ((intval($date) > 0) and (intval($date) < 8)) { - return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + intval($date), 1970, true), + if ((int) $date > 0 && (int) $date < 8) { + return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + (int) $date, 1970, true), $this->mktime(0, 0, 0, 1, 1 + $weekday, 1970, true), $hour); } @@ -1532,7 +1525,7 @@ private function _calculate($calc, $date, $part, $locale) case self::WEEKDAY_DIGIT: $weekday = (int) $this->toString(self::WEEKDAY_DIGIT, 'iso', $locale); - if (is_numeric($date) and (intval($date) >= 0) and (intval($date) < 7)) { + if (is_numeric($date) && (int) $date >= 0 && (int) $date < 7) { return $this->_assign($calc, $this->mktime(0, 0, 0, 1, 1 + $date, 1970, true), $this->mktime(0, 0, 0, 1, 1 + $weekday, 1970, true), $hour); } @@ -1563,7 +1556,7 @@ private function _calculate($calc, $date, $part, $locale) $weekday = (int) $this->toString(self::WEEKDAY_DIGIT, 'iso', $locale); $cnt = 0; foreach ($daylist as $key => $value) { - if (strtoupper(iconv_substr($value, 0, 1, 'UTF-8')) == strtoupper($date)) { + if (strtoupper(iconv_substr($value, 0, 1, 'UTF-8')) === strtoupper($date)) { $found = $cnt; break; } @@ -1586,7 +1579,7 @@ private function _calculate($calc, $date, $part, $locale) $weekday = (int) $this->toString(self::WEEKDAY_DIGIT, 'iso', $locale); $cnt = 0; foreach ($daylist as $key => $value) { - if (strtoupper($value) == strtoupper($date)) { + if (strtoupper($value) === strtoupper($date)) { $found = $cnt; break; } @@ -1621,7 +1614,7 @@ private function _calculate($calc, $date, $part, $locale) $monthlist = Zend_Locale_Data::getList($locale, 'month'); $cnt = 0; foreach ($monthlist as $key => $value) { - if (strtoupper($value) == strtoupper($date)) { + if (strtoupper($value) === strtoupper($date)) { $found = $key; break; } @@ -1641,7 +1634,7 @@ private function _calculate($calc, $date, $part, $locale) $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); } } - } else if ($calc == 'sub') { + } elseif ($calc == 'sub') { $date = $month - $found; $calc = 'set'; if (self::$_options['extend_month'] == false) { @@ -1672,7 +1665,7 @@ private function _calculate($calc, $date, $part, $locale) $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); } } - } else if ($calc == 'sub') { + } elseif ($calc == 'sub') { $date = $month - $date; $calc = 'set'; if (self::$_options['extend_month'] == false) { @@ -1694,7 +1687,7 @@ private function _calculate($calc, $date, $part, $locale) $monthlist = Zend_Locale_Data::getList($locale, 'month', array('gregorian', 'format', 'abbreviated')); $cnt = 0; foreach ($monthlist as $key => $value) { - if (strtoupper($value) == strtoupper($date)) { + if (strtoupper($value) === strtoupper($date)) { $found = $key; break; } @@ -1714,7 +1707,7 @@ private function _calculate($calc, $date, $part, $locale) $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); } } - } else if ($calc == 'sub') { + } elseif ($calc == 'sub') { $date = $month - $found; $calc = 'set'; if (self::$_options['extend_month'] === false) { @@ -1734,7 +1727,7 @@ private function _calculate($calc, $date, $part, $locale) break; case self::MONTH_SHORT: - if (is_numeric($date) === true) { + if (is_numeric($date)) { $fixday = 0; if ($calc === 'add') { $date += $month; @@ -1745,7 +1738,7 @@ private function _calculate($calc, $date, $part, $locale) $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); } } - } else if ($calc === 'sub') { + } elseif ($calc === 'sub') { $date = $month - $date; $calc = 'set'; if (self::$_options['extend_month'] === false) { @@ -1793,7 +1786,7 @@ private function _calculate($calc, $date, $part, $locale) $fixday = ($parts['mday'] < $day) ? -$parts['mday'] : ($parts['mday'] - $day); } } - } else if ($calc === 'sub') { + } elseif ($calc === 'sub') { $date = $month - $found; $calc = 'set'; if (self::$_options['extend_month'] === false) { @@ -1823,12 +1816,12 @@ private function _calculate($calc, $date, $part, $locale) if ($calc === 'add') { $date += $year; $calc = 'set'; - } else if ($calc === 'sub') { + } elseif ($calc === 'sub') { $date = $year - $date; $calc = 'set'; } - return $this->_assign($calc, $this->mktime(0, 0, 0, $month, $day, intval($date), true), + return $this->_assign($calc, $this->mktime(0, 0, 0, $month, $day, (int) $date, true), $this->mktime(0, 0, 0, $month, $day, $year, true), false); } @@ -1841,12 +1834,12 @@ private function _calculate($calc, $date, $part, $locale) if ($calc === 'add') { $date += $year; $calc = 'set'; - } else if ($calc === 'sub') { + } elseif ($calc === 'sub') { $date = $year - $date; $calc = 'set'; } - return $this->_assign($calc, $this->mktime(0, 0, 0, $month, $day, intval($date), true), + return $this->_assign($calc, $this->mktime(0, 0, 0, $month, $day, (int) $date, true), $this->mktime(0, 0, 0, $month, $day, $year, true), false); } @@ -1856,14 +1849,14 @@ private function _calculate($calc, $date, $part, $locale) case self::YEAR_SHORT: if (is_numeric($date)) { - $date = intval($date); + $date = (int) $date; if (($calc == 'set') || ($calc == 'cmp')) { $date = self::getFullYear($date); } if ($calc === 'add') { $date += $year; $calc = 'set'; - } else if ($calc === 'sub') { + } elseif ($calc === 'sub') { $date = $year - $date; $calc = 'set'; } @@ -1878,14 +1871,14 @@ private function _calculate($calc, $date, $part, $locale) case self::YEAR_SHORT_8601: if (is_numeric($date)) { - $date = intval($date); + $date = (int) $date; if (($calc === 'set') || ($calc === 'cmp')) { $date = self::getFullYear($date); } if ($calc === 'add') { $date += $year; $calc = 'set'; - } else if ($calc === 'sub') { + } elseif ($calc === 'sub') { $date = $year - $date; $calc = 'set'; } @@ -1906,11 +1899,11 @@ private function _calculate($calc, $date, $part, $locale) case self::SWATCH: if (is_numeric($date)) { - $rest = intval($date); + $rest = (int) $date; $hours = floor($rest * 24 / 1000); - $rest = $rest - ($hours * 1000 / 24); + $rest -= $hours * 1000 / 24; $minutes = floor($rest * 1440 / 1000); - $rest = $rest - ($minutes * 1000 / 1440); + $rest -= $minutes * 1000 / 1440; $seconds = floor($rest * 86400 / 1000); return $this->_assign($calc, $this->mktime($hours, $minutes, $seconds, 1, 1, 1970, true), $this->mktime($hour, $minute, $second, 1, 1, 1970, true), false); @@ -1922,7 +1915,7 @@ private function _calculate($calc, $date, $part, $locale) case self::HOUR_SHORT_AM: if (is_numeric($date)) { - return $this->_assign($calc, $this->mktime(intval($date), 0, 0, 1, 1, 1970, true), + return $this->_assign($calc, $this->mktime((int) $date, 0, 0, 1, 1, 1970, true), $this->mktime($hour, 0, 0, 1, 1, 1970, true), false); } @@ -1932,7 +1925,7 @@ private function _calculate($calc, $date, $part, $locale) case self::HOUR_SHORT: if (is_numeric($date)) { - return $this->_assign($calc, $this->mktime(intval($date), 0, 0, 1, 1, 1970, true), + return $this->_assign($calc, $this->mktime((int) $date, 0, 0, 1, 1, 1970, true), $this->mktime($hour, 0, 0, 1, 1, 1970, true), false); } @@ -1942,7 +1935,7 @@ private function _calculate($calc, $date, $part, $locale) case self::HOUR_AM: if (is_numeric($date)) { - return $this->_assign($calc, $this->mktime(intval($date), 0, 0, 1, 1, 1970, true), + return $this->_assign($calc, $this->mktime((int) $date, 0, 0, 1, 1, 1970, true), $this->mktime($hour, 0, 0, 1, 1, 1970, true), false); } @@ -1952,7 +1945,7 @@ private function _calculate($calc, $date, $part, $locale) case self::HOUR: if (is_numeric($date)) { - return $this->_assign($calc, $this->mktime(intval($date), 0, 0, 1, 1, 1970, true), + return $this->_assign($calc, $this->mktime((int) $date, 0, 0, 1, 1, 1970, true), $this->mktime($hour, 0, 0, 1, 1, 1970, true), false); } @@ -1962,7 +1955,7 @@ private function _calculate($calc, $date, $part, $locale) case self::MINUTE: if (is_numeric($date)) { - return $this->_assign($calc, $this->mktime(0, intval($date), 0, 1, 1, 1970, true), + return $this->_assign($calc, $this->mktime(0, (int) $date, 0, 1, 1, 1970, true), $this->mktime(0, $minute, 0, 1, 1, 1970, true), false); } @@ -1972,7 +1965,7 @@ private function _calculate($calc, $date, $part, $locale) case self::SECOND: if (is_numeric($date)) { - return $this->_assign($calc, $this->mktime(0, 0, intval($date), 1, 1, 1970, true), + return $this->_assign($calc, $this->mktime(0, 0, (int) $date, 1, 1, 1970, true), $this->mktime(0, 0, $second, 1, 1, 1970, true), false); } @@ -2003,7 +1996,7 @@ private function _calculate($calc, $date, $part, $locale) case self::MINUTE_SHORT: if (is_numeric($date)) { - return $this->_assign($calc, $this->mktime(0, intval($date), 0, 1, 1, 1970, true), + return $this->_assign($calc, $this->mktime(0, (int) $date, 0, 1, 1, 1970, true), $this->mktime(0, $minute, 0, 1, 1, 1970, true), false); } @@ -2013,7 +2006,7 @@ private function _calculate($calc, $date, $part, $locale) case self::SECOND_SHORT: if (is_numeric($date)) { - return $this->_assign($calc, $this->mktime(0, 0, intval($date), 1, 1, 1970, true), + return $this->_assign($calc, $this->mktime(0, 0, (int) $date, 1, 1, 1970, true), $this->mktime(0, 0, $second, 1, 1, 1970, true), false); } @@ -2079,7 +2072,7 @@ private function _calculate($calc, $date, $part, $locale) if (empty($timematch)) { preg_match('/[T,\s]{0,1}(\d{2})(\d{2})/', (string) $tmpdate, $timematch); } - if (empty($datematch) and empty($timematch)) { + if (empty($datematch) && empty($timematch)) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("unsupported ISO8601 format ($date)", 0, null, $date); } @@ -2094,7 +2087,7 @@ private function _calculate($calc, $date, $part, $locale) $datematch[1] = 1970; $datematch[2] = 1; $datematch[3] = 1; - } else if (iconv_strlen($datematch[1], 'UTF-8') == 2) { + } elseif (iconv_strlen($datematch[1], 'UTF-8') == 2) { $datematch[1] = self::getFullYear($datematch[1]); } if (empty($timematch)) { @@ -2119,9 +2112,7 @@ private function _calculate($calc, $date, $part, $locale) break; case self::RFC_2822: - $result = preg_match('/^\w{3},\s(\d{1,2})\s(\w{3})\s(\d{4})\s' - . '(\d{2}):(\d{2}):{0,1}(\d{0,2})\s([+-]' - . '{1}\d{4}|\w{1,20})$/', (string) $date, $match); + $result = preg_match('/^\w{3},\s(\d{1,2})\s(\w{3})\s(\d{4})\s(\d{2}):(\d{2}):{0,1}(\d{0,2})\s([+-]{1}\d{4}|\w{1,20})$/', (string) $date, $match); if (!$result) { require_once 'Zend/Date/Exception.php'; @@ -2639,7 +2630,7 @@ private function _calculate($calc, $date, $part, $locale) } $parsed = Zend_Locale_Format::getDate($date, array('date_format' => $part, 'locale' => $locale, 'fix_date' => true, 'format_type' => 'iso')); - if ((strpos(strtoupper($part), 'YY') !== false) and (strpos(strtoupper($part), 'YYYY') === false)) { + if (strpos(strtoupper($part), 'YY') !== false && strpos(strtoupper($part), 'YYYY') === false) { $parsed['year'] = self::getFullYear($parsed['year']); } @@ -2696,12 +2687,7 @@ private function _calculate($calc, $date, $part, $locale) public function equals($date, $part = self::TIMESTAMP, $locale = null) { $result = $this->compare($date, $part, $locale); - - if ($result == 0) { - return true; - } - - return false; + return $result == 0; } /** @@ -2718,12 +2704,7 @@ public function equals($date, $part = self::TIMESTAMP, $locale = null) public function isEarlier($date, $part = null, $locale = null) { $result = $this->compare($date, $part, $locale); - - if ($result == -1) { - return true; - } - - return false; + return $result == -1; } /** @@ -2741,12 +2722,7 @@ public function isEarlier($date, $part = null, $locale = null) public function isLater($date, $part = null, $locale = null) { $result = $this->compare($date, $part, $locale); - - if ($result == 1) { - return true; - } - - return false; + return $result == 1; } /** @@ -2759,11 +2735,7 @@ public function isLater($date, $part = null, $locale = null) */ public function getTime($locale = null) { - if (self::$_options['format_type'] == 'php') { - $format = 'H:i:s'; - } else { - $format = self::TIME_MEDIUM; - } + $format = self::$_options['format_type'] == 'php' ? 'H:i:s' : self::TIME_MEDIUM; return $this->copyPart($format, $locale); } @@ -2790,8 +2762,7 @@ private function _time($calc, $time, $format, $locale) $time = $time->toString('HH:mm:ss', 'iso'); } else { if (is_array($time)) { - if ((isset($time['hour']) === true) or (isset($time['minute']) === true) or - (isset($time['second']) === true)) { + if (isset($time['hour']) || isset($time['minute']) || isset($time['second'])) { $parsed = $time; } else { require_once 'Zend/Date/Exception.php'; @@ -2952,8 +2923,7 @@ private function _date($calc, $date, $format, $locale) $date = $date->toString('d.M.y', 'iso'); } else { if (is_array($date)) { - if ((isset($date['year']) === true) or (isset($date['month']) === true) or - (isset($date['day']) === true)) { + if (isset($date['year']) || isset($date['month']) || isset($date['day'])) { $parsed = $date; } else { require_once 'Zend/Date/Exception.php'; @@ -2969,7 +2939,7 @@ private function _date($calc, $date, $format, $locale) } $parsed = Zend_Locale_Format::getDate($date, array('date_format' => $format, 'locale' => $locale, 'format_type' => 'iso')); - if ((strpos(strtoupper($format), 'YY') !== false) and (strpos(strtoupper($format), 'YYYY') === false)) { + if (strpos(strtoupper($format), 'YY') !== false && strpos(strtoupper($format), 'YYYY') === false) { $parsed['year'] = self::getFullYear($parsed['year']); } } catch (Zend_Locale_Exception $e) { @@ -3167,11 +3137,7 @@ public function compareIso($date, $locale = null) */ public function getArpa($locale = null) { - if (self::$_options['format_type'] == 'php') { - $format = 'D\, d M y H\:i\:s O'; - } else { - $format = self::RFC_822; - } + $format = self::$_options['format_type'] == 'php' ? 'D\, d M y H\:i\:s O' : self::RFC_822; return $this->toString($format, 'iso', $locale); } @@ -3256,15 +3222,15 @@ public function compareArpa($date, $locale = null) */ private function _checkLocation($location) { - if (!isset($location['longitude']) or !isset($location['latitude'])) { + if (!isset($location['longitude']) || !isset($location['latitude'])) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('Location must include \'longitude\' and \'latitude\'', 0, null, $location); } - if (($location['longitude'] > 180) or ($location['longitude'] < -180)) { + if ($location['longitude'] > 180 || $location['longitude'] < -180) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('Longitude must be between -180 and 180', 0, null, $location); } - if (($location['latitude'] > 90) or ($location['latitude'] < -90)) { + if ($location['latitude'] > 90 || $location['latitude'] < -90) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception('Latitude must be between -90 and 90', 0, null, $location); } @@ -3384,7 +3350,7 @@ public static function checkLeapYear($year) } if (is_array($year)) { - if (isset($year['year']) === true) { + if (isset($year['year'])) { $year = $year['year']; } else { require_once 'Zend/Date/Exception.php'; @@ -3421,7 +3387,7 @@ public function isToday() { $today = $this->date('Ymd', $this->_getTime()); $day = $this->date('Ymd', $this->getUnixTimestamp()); - return ($today == $day); + return ($today === $day); } @@ -3436,7 +3402,7 @@ public function isYesterday() // adjusts for leap days and DST changes that are timezone specific $yesterday = $this->date('Ymd', $this->mktime(0, 0, 0, $month, $day -1, $year)); $day = $this->date('Ymd', $this->getUnixTimestamp()); - return $day == $yesterday; + return $day === $yesterday; } @@ -3451,7 +3417,7 @@ public function isTomorrow() // adjusts for leap days and DST changes that are timezone specific $tomorrow = $this->date('Ymd', $this->mktime(0, 0, 0, $month, $day +1, $year)); $day = $this->date('Ymd', $this->getUnixTimestamp()); - return $day == $tomorrow; + return $day === $tomorrow; } /** @@ -3530,7 +3496,7 @@ private function _calcvalue($calc, $value, $type, $parameter, $locale) if ($value instanceof Zend_Date) { // extract value from object $value = $value->toString($parameter, 'iso', $locale); - } else if (!is_array($value) && !is_numeric($value) && ($type != 'iso') && ($type != 'arpa')) { + } elseif (!is_array($value) && !is_numeric($value) && ($type != 'iso') && ($type != 'arpa')) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid $type ($value) operand", 0, null, $value); } @@ -3552,11 +3518,7 @@ private function _calcvalue($calc, $value, $type, $parameter, $locale) */ public function getYear($locale = null) { - if (self::$_options['format_type'] == 'php') { - $format = 'Y'; - } else { - $format = self::YEAR; - } + $format = self::$_options['format_type'] == 'php' ? 'Y' : self::YEAR; return $this->copyPart($format, $locale); } @@ -3644,11 +3606,7 @@ public function compareYear($year, $locale = null) */ public function getMonth($locale = null) { - if (self::$_options['format_type'] == 'php') { - $format = 'm'; - } else { - $format = self::MONTH; - } + $format = self::$_options['format_type'] == 'php' ? 'm' : self::MONTH; return $this->copyPart($format, $locale); } @@ -3677,43 +3635,41 @@ private function _month($calc, $month, $locale) if ($month instanceof Zend_Date) { // extract month from object $found = $month->toString(self::MONTH_SHORT, 'iso', $locale); + } elseif (is_numeric($month)) { + $found = $month; + } elseif (is_array($month)) { + if (isset($month['month'])) { + $month = $month['month']; + } else { + require_once 'Zend/Date/Exception.php'; + throw new Zend_Date_Exception("no month given in array"); + } } else { - if (is_numeric($month)) { - $found = $month; - } else if (is_array($month)) { - if (isset($month['month']) === true) { - $month = $month['month']; - } else { - require_once 'Zend/Date/Exception.php'; - throw new Zend_Date_Exception("no month given in array"); + $monthlist = Zend_Locale_Data::getList($locale, 'month'); + $monthlist2 = Zend_Locale_Data::getList($locale, 'month', array('gregorian', 'format', 'abbreviated')); + + $monthlist = array_merge($monthlist, $monthlist2); + $found = 0; + $cnt = 0; + foreach ($monthlist as $key => $value) { + if (strtoupper($value) === strtoupper($month)) { + $found = ($key % 12) + 1; + break; } - } else { - $monthlist = Zend_Locale_Data::getList($locale, 'month'); - $monthlist2 = Zend_Locale_Data::getList($locale, 'month', array('gregorian', 'format', 'abbreviated')); - - $monthlist = array_merge($monthlist, $monthlist2); - $found = 0; - $cnt = 0; - foreach ($monthlist as $key => $value) { - if (strtoupper($value) == strtoupper($month)) { - $found = ($key % 12) + 1; + ++$cnt; + } + if ($found == 0) { + foreach ($monthlist2 as $key => $value) { + if (strtoupper(iconv_substr($value, 0, 1, 'UTF-8')) === strtoupper($month)) { + $found = $key + 1; break; } ++$cnt; } - if ($found == 0) { - foreach ($monthlist2 as $key => $value) { - if (strtoupper(iconv_substr($value, 0, 1, 'UTF-8')) == strtoupper($month)) { - $found = $key + 1; - break; - } - ++$cnt; - } - } - if ($found == 0) { - require_once 'Zend/Date/Exception.php'; - throw new Zend_Date_Exception("unknown month name ($month)", 0, null, $month); - } + } + if ($found == 0) { + require_once 'Zend/Date/Exception.php'; + throw new Zend_Date_Exception("unknown month name ($month)", 0, null, $month); } } $return = $this->_calcdetail($calc, $found, self::MONTH_SHORT, $locale); @@ -3835,8 +3791,8 @@ private function _day($calc, $day, $locale) if (is_numeric($day)) { $type = self::DAY_SHORT; - } else if (is_array($day)) { - if (isset($day['day']) === true) { + } elseif (is_array($day)) { + if (isset($day['day'])) { $day = $day['day']; $type = self::WEEKDAY; } else { @@ -3949,11 +3905,7 @@ public function compareDay($day, $locale = null) */ public function getWeekday($locale = null) { - if (self::$_options['format_type'] == 'php') { - $format = 'l'; - } else { - $format = self::WEEKDAY; - } + $format = self::$_options['format_type'] == 'php' ? 'l' : self::WEEKDAY; return $this->copyPart($format, $locale); } @@ -3985,8 +3937,8 @@ private function _weekday($calc, $weekday, $locale) if (is_numeric($weekday)) { $type = self::WEEKDAY_8601; - } else if (is_array($weekday)) { - if (isset($weekday['weekday']) === true) { + } elseif (is_array($weekday)) { + if (isset($weekday['weekday'])) { $weekday = $weekday['weekday']; $type = self::WEEKDAY; } else { @@ -4100,11 +4052,7 @@ public function compareWeekday($weekday, $locale = null) */ public function getDayOfYear($locale = null) { - if (self::$_options['format_type'] == 'php') { - $format = 'D'; - } else { - $format = self::DAY_OF_YEAR; - } + $format = self::$_options['format_type'] == 'php' ? 'D' : self::DAY_OF_YEAR; return $this->copyPart($format, $locale); } @@ -4266,11 +4214,7 @@ public function compareHour($hour, $locale = null) */ public function getMinute($locale = null) { - if (self::$_options['format_type'] == 'php') { - $format = 'i'; - } else { - $format = self::MINUTE; - } + $format = self::$_options['format_type'] == 'php' ? 'i' : self::MINUTE; return $this->copyPart($format, $locale); } @@ -4352,11 +4296,7 @@ public function compareMinute($minute, $locale = null) */ public function getSecond($locale = null) { - if (self::$_options['format_type'] == 'php') { - $format = 's'; - } else { - $format = self::SECOND; - } + $format = self::$_options['format_type'] == 'php' ? 's' : self::SECOND; return $this->copyPart($format, $locale); } @@ -4449,7 +4389,7 @@ public function getFractionalPrecision() */ public function setFractionalPrecision($precision) { - if (!intval($precision) or ($precision < 0) or ($precision > 9)) { + if (!(int) $precision || $precision < 0 || $precision > 9) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("precision ($precision) must be a positive integer less than 10", 0, null, $precision); } @@ -4488,9 +4428,9 @@ public function setMilliSecond($milli = null, $precision = null) { if ($milli === null) { list($milli, $time) = explode(" ", microtime()); - $milli = intval($milli); + $milli = (int) $milli; $precision = 6; - } else if (!is_numeric($milli)) { + } elseif (!is_numeric($milli)) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid milli second ($milli) operand", 0, null, $milli); } @@ -4521,8 +4461,8 @@ public function addMilliSecond($milli = null, $precision = null) { if ($milli === null) { list($milli, $time) = explode(" ", microtime()); - $milli = intval($milli); - } else if (!is_numeric($milli)) { + $milli = (int) $milli; + } elseif (!is_numeric($milli)) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid milli second ($milli) operand", 0, null, $milli); } @@ -4543,7 +4483,7 @@ public function addMilliSecond($milli = null, $precision = null) } if ($this->_precision > $precision) { - $milli = $milli * pow(10, $this->_precision - $precision); + $milli *= pow(10, $this->_precision - $precision); } elseif ($this->_precision < $precision) { $milli = round($milli / pow(10, $precision - $this->_precision)); } @@ -4600,15 +4540,15 @@ public function compareMilliSecond($milli = null, $precision = null) { if ($milli === null) { list($milli, $time) = explode(" ", microtime()); - $milli = intval($milli); - } else if (is_numeric($milli) === false) { + $milli = (int) $milli; + } elseif (!is_numeric($milli)) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("invalid milli second ($milli) operand", 0, null, $milli); } if ($precision === null) { $precision = strlen((string) $milli); - } else if (!is_int($precision) || $precision < 1 || $precision > 9) { + } elseif (!is_int($precision) || $precision < 1 || $precision > 9) { require_once 'Zend/Date/Exception.php'; throw new Zend_Date_Exception("precision ($precision) must be a positive integer less than 10", 0, null, $precision); } @@ -4631,7 +4571,7 @@ public function compareMilliSecond($milli = null, $precision = null) $comp = $this->_fractional - $milli; if ($comp < 0) { return -1; - } else if ($comp > 0) { + } elseif ($comp > 0) { return 1; } return 0; @@ -4646,11 +4586,7 @@ public function compareMilliSecond($milli = null, $precision = null) */ public function getWeek($locale = null) { - if (self::$_options['format_type'] == 'php') { - $format = 'W'; - } else { - $format = self::WEEK; - } + $format = self::$_options['format_type'] == 'php' ? 'W' : self::WEEK; return $this->copyPart($format, $locale); } @@ -4777,7 +4713,7 @@ public static function isDate($date, $format = null, $locale = null) if ($format === null) { $format = Zend_Locale_Format::getDateFormat($locale); - } else if ((self::$_options['format_type'] == 'php') && !defined($format)) { + } elseif ((self::$_options['format_type'] == 'php') && !defined($format)) { $format = Zend_Locale_Format::convertPhpToIsoFormat($format); } @@ -4795,68 +4731,62 @@ public static function isDate($date, $format = null, $locale = null) $parsed = $date; } - if (((strpos($format, 'Y') !== false) or (strpos($format, 'y') !== false)) and - (!isset($parsed['year']))) { + if ((strpos($format, 'Y') !== false || strpos($format, 'y') !== false) && !isset($parsed['year'])) { // Year expected but not found return false; } - if ((strpos($format, 'M') !== false) and (!isset($parsed['month']))) { + if (strpos($format, 'M') !== false && !isset($parsed['month'])) { // Month expected but not found return false; } - if ((strpos($format, 'd') !== false) and (!isset($parsed['day']))) { + if (strpos($format, 'd') !== false && !isset($parsed['day'])) { // Day expected but not found return false; } - if (((strpos($format, 'H') !== false) or (strpos($format, 'h') !== false)) and - (!isset($parsed['hour']))) { + if ((strpos($format, 'H') !== false || strpos($format, 'h') !== false) && !isset($parsed['hour'])) { // Hour expected but not found return false; } - if ((strpos($format, 'm') !== false) and (!isset($parsed['minute']))) { + if (strpos($format, 'm') !== false && !isset($parsed['minute'])) { // Minute expected but not found return false; } - if ((strpos($format, 's') !== false) and (!isset($parsed['second']))) { + if (strpos($format, 's') !== false && !isset($parsed['second'])) { // Second expected but not found return false; } // Set not given dateparts - if (isset($parsed['hour']) === false) { + if (!isset($parsed['hour'])) { $parsed['hour'] = 12; } - if (isset($parsed['minute']) === false) { + if (!isset($parsed['minute'])) { $parsed['minute'] = 0; } - if (isset($parsed['second']) === false) { + if (!isset($parsed['second'])) { $parsed['second'] = 0; } - if (isset($parsed['month']) === false) { + if (!isset($parsed['month'])) { $parsed['month'] = 1; } - if (isset($parsed['day']) === false) { + if (!isset($parsed['day'])) { $parsed['day'] = 1; } - if (isset($parsed['year']) === false) { + if (!isset($parsed['year'])) { $parsed['year'] = 1970; } - if (self::isYearLeapYear($parsed['year'])) { - $parsed['year'] = 1972; - } else { - $parsed['year'] = 1971; - } + $parsed['year'] = self::isYearLeapYear($parsed['year']) ? 1972 : 1971; $date = new self($parsed, null, $locale); $timestamp = $date->mktime($parsed['hour'], $parsed['minute'], $parsed['second'], diff --git a/library/Zend/Date/DateObject.php b/library/Zend/Date/DateObject.php index a5842bde68..7db27071bd 100644 --- a/library/Zend/Date/DateObject.php +++ b/library/Zend/Date/DateObject.php @@ -82,7 +82,7 @@ protected function setUnixTimestamp($timestamp = null) if (is_numeric($timestamp)) { $this->_unixTimestamp = $timestamp; - } else if ($timestamp === null) { + } elseif ($timestamp === null) { $this->_unixTimestamp = time(); } else { require_once 'Zend/Date/Exception.php'; @@ -101,7 +101,7 @@ protected function setUnixTimestamp($timestamp = null) */ protected function getUnixTimestamp() { - if ($this->_unixTimestamp === intval($this->_unixTimestamp)) { + if ($this->_unixTimestamp === (int) $this->_unixTimestamp) { return (int) $this->_unixTimestamp; } else { return (string) $this->_unixTimestamp; @@ -146,12 +146,12 @@ protected function _getTime($sync = null) protected function mktime($hour, $minute, $second, $month, $day, $year, $gmt = false) { // complete date but in 32bit timestamp - use PHP internal - if ((1901 < $year) and ($year < 2038)) { + if (1901 < $year && $year < 2038) { $oldzone = @date_default_timezone_get(); // Timezone also includes DST settings, therefor substracting the GMT offset is not enough // We have to set the correct timezone to get the right value - if (($this->_timezone != $oldzone) and ($gmt === false)) { + if ($this->_timezone != $oldzone && !$gmt) { date_default_timezone_set($this->_timezone); } $result = ($gmt) ? @gmmktime($hour, $minute, $second, $month, $day, $year) @@ -161,7 +161,7 @@ protected function mktime($hour, $minute, $second, $month, $day, $year, $gmt = f return $result; } - if ($gmt !== true) { + if (!$gmt) { $second += $this->_offset; } @@ -173,9 +173,9 @@ protected function mktime($hour, $minute, $second, $month, $day, $year, $gmt = f } // date to integer - $day = intval($day); - $month = intval($month); - $year = intval($year); + $day = (int) $day; + $month = (int) $month; + $year = (int) $year; // correct months > 12 and months < 1 if ($month > 12) { @@ -200,7 +200,7 @@ protected function mktime($hour, $minute, $second, $month, $day, $year, $gmt = f if ($count < $year) { $date += 365; - if ($leapyear === true) { + if ($leapyear) { $date++; } @@ -208,7 +208,7 @@ protected function mktime($hour, $minute, $second, $month, $day, $year, $gmt = f for ($mcount = 0; $mcount < ($month - 1); $mcount++) { $date += self::$_monthTable[$mcount]; - if (($leapyear === true) and ($mcount == 1)) { + if ($leapyear && $mcount == 1) { $date++; } @@ -229,13 +229,13 @@ protected function mktime($hour, $minute, $second, $month, $day, $year, $gmt = f if ($count > $year) { $date += 365; - if ($leapyear === true) + if ($leapyear) $date++; } else { for ($mcount = 11; $mcount > ($month - 1); $mcount--) { $date += self::$_monthTable[$mcount]; - if (($leapyear === true) and ($mcount == 2)) { + if ($leapyear && $mcount == 2) { $date++; } @@ -249,7 +249,7 @@ protected function mktime($hour, $minute, $second, $month, $day, $year, $gmt = f // gregorian correction for 5.Oct.1582 if ($date < -12220185600) { $date += 864000; - } else if ($date < -12219321600) { + } elseif ($date < -12219321600) { $date = -12219321600; } } @@ -274,14 +274,14 @@ protected function mktime($hour, $minute, $second, $month, $day, $year, $gmt = f protected static function isYearLeapYear($year) { // all leapyears can be divided through 4 - if (($year % 4) != 0) { + if ($year % 4 != 0) { return false; } // all leapyears can be divided through 400 if ($year % 400 == 0) { return true; - } else if (($year > 1582) and ($year % 100 == 0)) { + } elseif ($year > 1582 && $year % 100 == 0) { return false; } @@ -335,7 +335,7 @@ protected function date($format, $timestamp = null, $gmt = false) } // check on false or null alone fails - if (empty($gmt) and empty($jump)) { + if (empty($gmt) && empty($jump)) { $tempstamp = $timestamp; if ($tempstamp > 0) { while (abs($tempstamp) > 0x7FFFFFFF) { @@ -360,7 +360,7 @@ protected function date($format, $timestamp = null, $gmt = false) } } - if (($timestamp < 0) and ($gmt !== true)) { + if ($timestamp < 0 && !$gmt) { $timestamp -= $this->_offset; } @@ -399,9 +399,9 @@ protected function date($format, $timestamp = null, $gmt = false) case 'S': // english suffix for day of month, st nd rd th if (($date['mday'] % 10) == 1) { $output .= 'st'; - } else if ((($date['mday'] % 10) == 2) and ($date['mday'] != 12)) { + } elseif (($date['mday'] % 10) == 2 && $date['mday'] != 12) { $output .= 'nd'; - } else if (($date['mday'] % 10) == 3) { + } elseif (($date['mday'] % 10) == 3) { $output .= 'rd'; } else { $output .= 'th'; @@ -452,7 +452,7 @@ protected function date($format, $timestamp = null, $gmt = false) case 'o': // ISO 8601 year number $week = $this->weekNumber($date['year'], $date['mon'], $date['mday']); - if (($week > 50) and ($date['mon'] == 1)) { + if ($week > 50 && $date['mon'] == 1) { $output .= ($date['year'] - 1); } else { $output .= $date['year']; @@ -479,7 +479,7 @@ protected function date($format, $timestamp = null, $gmt = false) case 'B': // swatch internet time $dayseconds = ($date['hours'] * 3600) + ($date['minutes'] * 60) + $date['seconds']; - if ($gmt === true) { + if ($gmt) { $dayseconds += 3600; } $output .= (int) (($dayseconds % 86400) / 86.4); @@ -489,11 +489,7 @@ protected function date($format, $timestamp = null, $gmt = false) if ($date['hours'] > 12) { $hour = $date['hours'] - 12; } else { - if ($date['hours'] == 0) { - $hour = '12'; - } else { - $hour = $date['hours']; - } + $hour = $date['hours'] == 0 ? '12' : $date['hours']; } $output .= $hour; break; @@ -506,11 +502,7 @@ protected function date($format, $timestamp = null, $gmt = false) if ($date['hours'] > 12) { $hour = $date['hours'] - 12; } else { - if ($date['hours'] == 0) { - $hour = '12'; - } else { - $hour = $date['hours']; - } + $hour = $date['hours'] == 0 ? '12' : $date['hours']; } $output .= (($hour < 10) ? '0'.$hour : $hour); break; @@ -530,7 +522,7 @@ protected function date($format, $timestamp = null, $gmt = false) // timezone formats case 'e': // timezone identifier - if ($gmt === true) { + if ($gmt) { $output .= gmdate('e', mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], 2000)); } else { @@ -540,7 +532,7 @@ protected function date($format, $timestamp = null, $gmt = false) break; case 'I': // daylight saving time or not - if ($gmt === true) { + if ($gmt) { $output .= gmdate('I', mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], 2000)); } else { @@ -550,18 +542,18 @@ protected function date($format, $timestamp = null, $gmt = false) break; case 'O': // difference to GMT in hours - $gmtstr = ($gmt === true) ? 0 : $this->getGmtOffset(); + $gmtstr = ($gmt) ? 0 : $this->getGmtOffset(); $output .= sprintf('%s%04d', ($gmtstr <= 0) ? '+' : '-', abs($gmtstr) / 36); break; case 'P': // difference to GMT with colon - $gmtstr = ($gmt === true) ? 0 : $this->getGmtOffset(); + $gmtstr = ($gmt) ? 0 : $this->getGmtOffset(); $gmtstr = sprintf('%s%04d', ($gmtstr <= 0) ? '+' : '-', abs($gmtstr) / 36); $output = $output . substr($gmtstr, 0, 3) . ':' . substr($gmtstr, 3); break; case 'T': // timezone settings - if ($gmt === true) { + if ($gmt) { $output .= gmdate('T', mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], 2000)); } else { @@ -571,7 +563,7 @@ protected function date($format, $timestamp = null, $gmt = false) break; case 'Z': // timezone offset in seconds - $output .= ($gmt === true) ? 0 : -$this->getGmtOffset(); + $output .= ($gmt) ? 0 : -$this->getGmtOffset(); break; @@ -635,13 +627,13 @@ protected function date($format, $timestamp = null, $gmt = false) */ protected static function dayOfWeek($year, $month, $day) { - if ((1901 < $year) and ($year < 2038)) { + if (1901 < $year && $year < 2038) { return (int) date('w', mktime(0, 0, 0, $month, $day, $year)); } // gregorian correction $correction = 0; - if (($year < 1582) or (($year == 1582) and (($month < 10) or (($month == 10) && ($day < 15))))) { + if ($year < 1582 || $year == 1582 && ($month < 10 || ($month == 10) && ($day < 15))) { $correction = 3; } @@ -726,7 +718,7 @@ protected function getDateParts($timestamp = null, $fast = null) $timestamp += 31536000; $leapyear = self::isYearLeapYear($i); - if ($leapyear === true) { + if ($leapyear) { $timestamp += 86400; } @@ -744,14 +736,14 @@ protected function getDateParts($timestamp = null, $fast = null) $day = $timestamp; $timestamp += self::$_monthTable[$i] * 86400; - if (($leapyear === true) and ($i == 1)) { + if ($leapyear && $i == 1) { $timestamp += 86400; } if ($timestamp >= 0) { $month = $i; $numday = self::$_monthTable[$i]; - if (($leapyear === true) and ($i == 1)) { + if ($leapyear && $i == 1) { ++$numday; } break; @@ -771,7 +763,7 @@ protected function getDateParts($timestamp = null, $fast = null) $timestamp -= 31536000; $leapyear = self::isYearLeapYear($i); - if ($leapyear === true) { + if ($leapyear) { $timestamp -= 86400; } @@ -789,14 +781,14 @@ protected function getDateParts($timestamp = null, $fast = null) $day = $timestamp; $timestamp -= self::$_monthTable[$i] * 86400; - if (($leapyear === true) and ($i == 1)) { + if ($leapyear && $i == 1) { $timestamp -= 86400; } if ($timestamp < 0) { $month = $i; $numday = self::$_monthTable[$i]; - if (($leapyear === true) and ($i == 1)) { + if ($leapyear && $i == 1) { ++$numday; } break; @@ -805,7 +797,7 @@ protected function getDateParts($timestamp = null, $fast = null) $timestamp = $day; $numberdays = ceil(($timestamp + 1) / 86400); - $timestamp = $timestamp - ($numberdays - 1) * 86400; + $timestamp -= ($numberdays - 1) * 86400; $hours = floor($timestamp / 3600); } @@ -866,23 +858,21 @@ protected function getDateParts($timestamp = null, $fast = null) */ protected function weekNumber($year, $month, $day) { - if ((1901 < $year) and ($year < 2038)) { + if (1901 < $year && $year < 2038) { return (int) date('W', mktime(0, 0, 0, $month, $day, $year)); } $dayofweek = self::dayOfWeek($year, $month, $day); $firstday = self::dayOfWeek($year, 1, 1); - if (($month == 1) and (($firstday < 1) or ($firstday > 4)) and ($day < 4)) { + if ($month == 1 && ($firstday < 1 || $firstday > 4) && $day < 4) { $firstday = self::dayOfWeek($year - 1, 1, 1); $month = 12; $day = 31; - - } else if (($month == 12) and ((self::dayOfWeek($year + 1, 1, 1) < 5) and - (self::dayOfWeek($year + 1, 1, 1) > 0))) { + } elseif ($month == 12 && (self::dayOfWeek($year + 1, 1, 1) < 5 && self::dayOfWeek($year + 1, 1, 1) > 0)) { return 1; } - return intval (((self::dayOfWeek($year, 1, 1) < 5) and (self::dayOfWeek($year, 1, 1) > 0)) + + return (int) ((self::dayOfWeek($year, 1, 1) < 5 && self::dayOfWeek($year, 1, 1) > 0) + 4 * ($month - 1) + (2 * ($month - 1) + ($day - 1) + $firstday - $dayofweek + 6) * 36 / 256); } @@ -945,7 +935,7 @@ protected function calcSun($location, $horizon, $rise = false) // get quadrant $solLongitude = $this->_range($solLongitude, $fullCircle); - if (($solLongitude / $quarterCircle) - intval($solLongitude / $quarterCircle) == 0) { + if (($solLongitude / $quarterCircle) - (int) ($solLongitude / $quarterCircle) == 0) { $solLongitude += 4.84814E-6; } @@ -956,7 +946,7 @@ protected function calcSun($location, $horizon, $rise = false) // adjust quadrant if ($solLongitude > $threeQuarterCircle) { $solAscension += $fullCircle; - } else if ($solLongitude > $quarterCircle) { + } elseif ($solLongitude > $quarterCircle) { $solAscension += $halfCircle; } @@ -991,15 +981,15 @@ protected function calcSun($location, $horizon, $rise = false) $universalTime *= 24 / $fullCircle; // convert to time - $hour = intval($universalTime); + $hour = (int) $universalTime; $universalTime = ($universalTime - $hour) * 60; - $min = intval($universalTime); + $min = (int) $universalTime; $universalTime = ($universalTime - $min) * 60; - $sec = intval($universalTime); + $sec = (int) $universalTime; return $this->mktime($hour, $min, $sec, $this->date('m', $this->_unixTimestamp), $this->date('j', $this->_unixTimestamp), $this->date('Y', $this->_unixTimestamp), - -1, true); + -1); } /** @@ -1019,25 +1009,19 @@ public function setTimezone($zone = null) } // throw an error on false input, but only if the new date extension is available - if (function_exists('timezone_open')) { - if (!@timezone_open($zone)) { - require_once 'Zend/Date/Exception.php'; - throw new Zend_Date_Exception("timezone ($zone) is not a known timezone", 0, null, $zone); - } + if (function_exists('timezone_open') && !@timezone_open($zone)) { + require_once 'Zend/Date/Exception.php'; + throw new Zend_Date_Exception("timezone ($zone) is not a known timezone", 0, null, $zone); } // this can generate an error if the date extension is not available and a false timezone is given $result = @date_default_timezone_set($zone); - if ($result === true) { + if ($result) { $this->_offset = mktime(0, 0, 0, 1, 2, 1970) - gmmktime(0, 0, 0, 1, 2, 1970); $this->_timezone = $zone; } date_default_timezone_set($oldzone); - if (($zone == 'UTC') or ($zone == 'GMT')) { - $this->_dst = false; - } else { - $this->_dst = true; - } + $this->_dst = ($zone == 'UTC' || $zone == 'GMT') ? false : true; return $this; } @@ -1065,7 +1049,7 @@ public function getGmtOffset() $date = $this->getDateParts($this->getUnixTimestamp(), true); $zone = @date_default_timezone_get(); $result = @date_default_timezone_set($this->_timezone); - if ($result === true) { + if ($result) { $offset = $this->mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], $date['year'], false) - $this->mktime($date['hours'], $date['minutes'], $date['seconds'], diff --git a/library/Zend/Db.php b/library/Zend/Db.php index 40f26dbae1..3ac335f62f 100644 --- a/library/Zend/Db.php +++ b/library/Zend/Db.php @@ -207,14 +207,10 @@ public static function factory($adapter, $config = array()) * adapter name and separate config object. */ if ($adapter instanceof Zend_Config) { - if (isset($adapter->params)) { + if (property_exists($adapter, 'params') && $adapter->params !== null) { $config = $adapter->params->toArray(); } - if (isset($adapter->adapter)) { - $adapter = (string) $adapter->adapter; - } else { - $adapter = null; - } + $adapter = property_exists($adapter, 'adapter') && $adapter->adapter !== null ? (string) $adapter->adapter : null; } /* diff --git a/library/Zend/Db/Adapter/Abstract.php b/library/Zend/Db/Adapter/Abstract.php index 9f857c6a54..ecaa8b0ef2 100644 --- a/library/Zend/Db/Adapter/Abstract.php +++ b/library/Zend/Db/Adapter/Abstract.php @@ -199,12 +199,10 @@ public function __construct($config) $options[$key] = $value; } } - if (array_key_exists('driver_options', $config)) { - if (!empty($config['driver_options'])) { - // can't use array_merge() because keys might be integers - foreach ((array) $config['driver_options'] as $key => $value) { - $driverOptions[$key] = $value; - } + if (array_key_exists('driver_options', $config) && !empty($config['driver_options'])) { + // can't use array_merge() because keys might be integers + foreach ((array) $config['driver_options'] as $key => $value) { + $driverOptions[$key] = $value; } } @@ -364,7 +362,7 @@ public function setProfiler($profiler) if ($profilerIsObject = is_object($profiler)) { if ($profiler instanceof Zend_Db_Profiler) { $profilerInstance = $profiler; - } else if ($profiler instanceof Zend_Config) { + } elseif ($profiler instanceof Zend_Config) { $profiler = $profiler->toArray(); } else { /** @@ -386,7 +384,7 @@ public function setProfiler($profiler) if (isset($profiler['instance'])) { $profilerInstance = $profiler['instance']; } - } else if (!$profilerIsObject) { + } elseif (!$profilerIsObject) { $enabled = (bool) $profiler; } @@ -545,21 +543,17 @@ public function insert($table, array $bind) if ($val instanceof Zend_Db_Expr) { $vals[] = $val->__toString(); unset($bind[$col]); + } elseif ($this->supportsParameters('positional')) { + $vals[] = '?'; + } elseif ($this->supportsParameters('named')) { + unset($bind[$col]); + $bind[':col'.$i] = $val; + $vals[] = ':col'.$i; + $i++; } else { - if ($this->supportsParameters('positional')) { - $vals[] = '?'; - } else { - if ($this->supportsParameters('named')) { - unset($bind[$col]); - $bind[':col'.$i] = $val; - $vals[] = ':col'.$i; - $i++; - } else { - /** @see Zend_Db_Adapter_Exception */ - require_once 'Zend/Db/Adapter/Exception.php'; - throw new Zend_Db_Adapter_Exception(get_class($this) ." doesn't support positional or named binding"); - } - } + /** @see Zend_Db_Adapter_Exception */ + require_once 'Zend/Db/Adapter/Exception.php'; + throw new Zend_Db_Adapter_Exception(get_class($this) ." doesn't support positional or named binding"); } } @@ -574,8 +568,7 @@ public function insert($table, array $bind) $bind = array_values($bind); } $stmt = $this->query($sql, $bind); - $result = $stmt->rowCount(); - return $result; + return $stmt->rowCount(); } /** @@ -599,21 +592,17 @@ public function update($table, array $bind, $where = '') if ($val instanceof Zend_Db_Expr) { $val = $val->__toString(); unset($bind[$col]); + } elseif ($this->supportsParameters('positional')) { + $val = '?'; + } elseif ($this->supportsParameters('named')) { + unset($bind[$col]); + $bind[':col'.$i] = $val; + $val = ':col'.$i; + $i++; } else { - if ($this->supportsParameters('positional')) { - $val = '?'; - } else { - if ($this->supportsParameters('named')) { - unset($bind[$col]); - $bind[':col'.$i] = $val; - $val = ':col'.$i; - $i++; - } else { - /** @see Zend_Db_Adapter_Exception */ - require_once 'Zend/Db/Adapter/Exception.php'; - throw new Zend_Db_Adapter_Exception(get_class($this) ." doesn't support positional or named binding"); - } - } + /** @see Zend_Db_Adapter_Exception */ + require_once 'Zend/Db/Adapter/Exception.php'; + throw new Zend_Db_Adapter_Exception(get_class($this) ." doesn't support positional or named binding"); } $set[] = $this->quoteIdentifier($col, true) . ' = ' . $val; } @@ -626,18 +615,12 @@ public function update($table, array $bind, $where = '') $sql = "UPDATE " . $this->quoteIdentifier($table, true) . ' SET ' . implode(', ', $set) - . (($where) ? " WHERE $where" : ''); - + . (($where !== '' && $where !== '0') ? " WHERE $where" : ''); /** * Execute the statement and return the number of affected rows */ - if ($this->supportsParameters('positional')) { - $stmt = $this->query($sql, array_values($bind)); - } else { - $stmt = $this->query($sql, $bind); - } - $result = $stmt->rowCount(); - return $result; + $stmt = $this->supportsParameters('positional') ? $this->query($sql, array_values($bind)) : $this->query($sql, $bind); + return $stmt->rowCount(); } /** @@ -656,14 +639,13 @@ public function delete($table, $where = '') */ $sql = "DELETE FROM " . $this->quoteIdentifier($table, true) - . (($where) ? " WHERE $where" : ''); + . (($where !== '' && $where !== '0') ? " WHERE $where" : ''); /** * Execute the statement and return the number of affected rows */ $stmt = $this->query($sql); - $result = $stmt->rowCount(); - return $result; + return $stmt->rowCount(); } /** @@ -695,9 +677,7 @@ protected function _whereExpr($where) } $term = '(' . $term . ')'; } - - $where = implode(' AND ', $where); - return $where; + return implode(' AND ', $where); } /** @@ -735,8 +715,7 @@ public function fetchAll($sql, $bind = array(), $fetchMode = null) $fetchMode = $this->_fetchMode; } $stmt = $this->query($sql, $bind); - $result = $stmt->fetchAll($fetchMode); - return $result; + return $stmt->fetchAll($fetchMode); } /** @@ -754,8 +733,7 @@ public function fetchRow($sql, $bind = array(), $fetchMode = null) $fetchMode = $this->_fetchMode; } $stmt = $this->query($sql, $bind); - $result = $stmt->fetch($fetchMode); - return $result; + return $stmt->fetch($fetchMode); } /** @@ -792,8 +770,7 @@ public function fetchAssoc($sql, $bind = array()) public function fetchCol($sql, $bind = array()) { $stmt = $this->query($sql, $bind); - $result = $stmt->fetchAll(Zend_Db::FETCH_COLUMN, 0); - return $result; + return $stmt->fetchAll(Zend_Db::FETCH_COLUMN, 0); } /** @@ -826,8 +803,7 @@ public function fetchPairs($sql, $bind = array()) public function fetchOne($sql, $bind = array()) { $stmt = $this->query($sql, $bind); - $result = $stmt->fetchColumn(0); - return $result; + return $stmt->fetchColumn(0); } /** @@ -879,7 +855,7 @@ public function quote($value, $type = null) $quotedValue = '0'; switch ($this->_numericDataTypes[$type]) { case Zend_Db::INT_TYPE: // 32-bit integer - $quotedValue = (string) intval($value); + $quotedValue = (string) (int) $value; break; case Zend_Db::BIGINT_TYPE: // 64-bit integer // ANSI SQL-style hex literals (e.g. x'[\dA-F]+') @@ -1009,11 +985,7 @@ protected function _quoteIdentifierAs($ident, $alias = null, $auto = false, $as if (is_array($ident)) { $segments = array(); foreach ($ident as $segment) { - if ($segment instanceof Zend_Db_Expr) { - $segments[] = $segment->__toString(); - } else { - $segments[] = $this->_quoteIdentifier($segment, $auto); - } + $segments[] = $segment instanceof Zend_Db_Expr ? $segment->__toString() : $this->_quoteIdentifier($segment, $auto); } if ($alias !== null && end($ident) == $alias) { $alias = null; @@ -1038,7 +1010,7 @@ protected function _quoteIdentifierAs($ident, $alias = null, $auto = false, $as */ protected function _quoteIdentifier($value, $auto=false) { - if ($auto === false || $this->_autoQuoteIdentifiers === true) { + if (!$auto || $this->_autoQuoteIdentifiers) { $q = $this->getQuoteIdentifierSymbol(); return ($q . str_replace("$q", "$q$q", $value) . $q); } diff --git a/library/Zend/Db/Adapter/Db2.php b/library/Zend/Db/Adapter/Db2.php index dac2b1b7b9..fdeaa62d05 100644 --- a/library/Zend/Db/Adapter/Db2.php +++ b/library/Zend/Db/Adapter/Db2.php @@ -132,13 +132,7 @@ protected function _connect() } $this->_determineI5(); - if ($this->_config['persistent']) { - // use persistent connection - $conn_func_name = 'db2_pconnect'; - } else { - // use "normal" connection - $conn_func_name = 'db2_connect'; - } + $conn_func_name = $this->_config['persistent'] ? 'db2_pconnect' : 'db2_connect'; if (!isset($this->_config['driver_options']['autocommit'])) { // set execution mode @@ -303,11 +297,8 @@ public function getQuoteIdentifierSymbol() $info = db2_server_info($this->_connection); if ($info) { $identQuote = $info->IDENTIFIER_QUOTE_CHAR; - } else { - // db2_server_info() does not return result on some i5 OS version - if ($this->_isI5) { - $identQuote ="'"; - } + } elseif ($this->_isI5) { + $identQuote ="'"; } return $identQuote; } @@ -328,11 +319,7 @@ public function listTables($schema = null) $tables = array(); if (!$this->_isI5) { - if ($schema) { - $stmt = db2_tables($this->_connection, null, $schema); - } else { - $stmt = db2_tables($this->_connection); - } + $stmt = $schema ? db2_tables($this->_connection, null, $schema) : db2_tables($this->_connection); while ($row = db2_fetch_assoc($stmt)) { $tables[] = $row['TABLE_NAME']; } @@ -454,7 +441,9 @@ public function describeTable($tableName, $schemaName = null) $colseq = 11; foreach ($result as $key => $row) { - list ($primary, $primaryPosition, $identity) = array(false, null, false); + $primary = false; + $primaryPosition = null; + $identity = false; if ($row[$tabconstType] == 'P') { $primary = true; $primaryPosition = $row[$colseq]; @@ -472,7 +461,7 @@ public function describeTable($tableName, $schemaName = null) 'SCHEMA_NAME' => $this->foldCase($row[$tabschema]), 'TABLE_NAME' => $this->foldCase($row[$tabname]), 'COLUMN_NAME' => $this->foldCase($row[$colname]), - 'COLUMN_POSITION' => (!$this->_isI5) ? $row[$colno]+1 : $row[$colno], + 'COLUMN_POSITION' => ($this->_isI5) ? $row[$colno] : $row[$colno]+1, 'DATA_TYPE' => $row[$typename], 'DEFAULT' => $row[$default], 'NULLABLE' => (bool) ($row[$nulls] == 'Y'), @@ -662,7 +651,7 @@ public function setFetchMode($mode) */ public function limit($sql, $count, $offset = 0) { - $count = intval($count); + $count = (int) $count; if ($count <= 0) { /** * @see Zend_Db_Adapter_Db2_Exception @@ -671,7 +660,7 @@ public function limit($sql, $count, $offset = 0) throw new Zend_Db_Adapter_Db2_Exception("LIMIT argument count=$count is not valid"); } - $offset = intval($offset); + $offset = (int) $offset; if ($offset < 0) { /** * @see Zend_Db_Adapter_Db2_Exception @@ -681,8 +670,7 @@ public function limit($sql, $count, $offset = 0) } if ($offset == 0) { - $limit_sql = $sql . " FETCH FIRST $count ROWS ONLY"; - return $limit_sql; + return $sql . " FETCH FIRST $count ROWS ONLY"; } /** @@ -710,12 +698,8 @@ public function limit($sql, $count, $offset = 0) */ public function supportsParameters($type) { - if ($type == 'positional') { - return true; - } - // if its 'named' or anything else - return false; + return $type == 'positional'; } /** @@ -761,16 +745,11 @@ public function isI5() protected function _determineI5() { // first us the compiled flag. - $this->_isI5 = (php_uname('s') == 'OS400') ? true : false; + $this->_isI5 = php_uname('s') == 'OS400'; // if this is set, then us it if (isset($this->_config['os'])){ - if (strtolower($this->_config['os']) === 'i5') { - $this->_isI5 = true; - } else { - // any other value passed in, its null - $this->_isI5 = false; - } + $this->_isI5 = strtolower($this->_config['os']) === 'i5'; } } @@ -819,8 +798,7 @@ protected function _i5LastInsertId($objectName = null, $idType = null) if ($objectName === null) { $sql = 'SELECT IDENTITY_VAL_LOCAL() AS VAL FROM QSYS2.QSQPTABL'; - $value = $this->fetchOne($sql); - return $value; + return $this->fetchOne($sql); } if (strtoupper($idType) === 'S'){ diff --git a/library/Zend/Db/Adapter/Mysqli.php b/library/Zend/Db/Adapter/Mysqli.php index a82d478362..acf67a5d82 100644 --- a/library/Zend/Db/Adapter/Mysqli.php +++ b/library/Zend/Db/Adapter/Mysqli.php @@ -225,15 +225,15 @@ public function describeTable($tableName, $schemaName = null) if (preg_match('/^((?:var)?char)\((\d+)\)/', (string) $row['Type'], $matches)) { $row['Type'] = $matches[1]; $row['Length'] = $matches[2]; - } else if (preg_match('/^decimal\((\d+),(\d+)\)/', (string) $row['Type'], $matches)) { + } elseif (preg_match('/^decimal\((\d+),(\d+)\)/', (string) $row['Type'], $matches)) { $row['Type'] = 'decimal'; $row['Precision'] = $matches[1]; $row['Scale'] = $matches[2]; - } else if (preg_match('/^float\((\d+),(\d+)\)/', (string) $row['Type'], $matches)) { + } elseif (preg_match('/^float\((\d+),(\d+)\)/', (string) $row['Type'], $matches)) { $row['Type'] = 'float'; $row['Precision'] = $matches[1]; $row['Scale'] = $matches[2]; - } else if (preg_match('/^((?:big|medium|small|tiny)?int)\((\d+)\)/', (string) $row['Type'], $matches)) { + } elseif (preg_match('/^((?:big|medium|small|tiny)?int)\((\d+)\)/', (string) $row['Type'], $matches)) { $row['Type'] = $matches[1]; /** * The optional argument of a MySQL int type is not precision @@ -243,11 +243,7 @@ public function describeTable($tableName, $schemaName = null) if (strtoupper($row['Key']) == 'PRI') { $row['Primary'] = true; $row['PrimaryPosition'] = $p; - if ($row['Extra'] == 'auto_increment') { - $row['Identity'] = true; - } else { - $row['Identity'] = false; - } + $row['Identity'] = $row['Extra'] == 'auto_increment'; ++$p; } $desc[$this->foldCase($row['Field'])] = array( @@ -291,17 +287,9 @@ protected function _connect() throw new Zend_Db_Adapter_Mysqli_Exception('The Mysqli extension is required for this adapter but the extension is not loaded'); } - if (isset($this->_config['port'])) { - $port = (integer) $this->_config['port']; - } else { - $port = null; - } + $port = isset($this->_config['port']) ? (integer) $this->_config['port'] : null; - if (isset($this->_config['socket'])) { - $socket = $this->_config['socket']; - } else { - $socket = null; - } + $socket = isset($this->_config['socket']) ? $this->_config['socket'] : null; $this->_connection = mysqli_init(); @@ -330,7 +318,7 @@ protected function _connect() $socket ); - if ($_isConnected === false || mysqli_connect_errno()) { + if (!$_isConnected || mysqli_connect_errno()) { $this->closeConnection(); /** @@ -496,7 +484,7 @@ public function setFetchMode($mode) */ public function limit($sql, $count, $offset = 0) { - $count = intval($count); + $count = (int) $count; if ($count <= 0) { /** * @see Zend_Db_Adapter_Mysqli_Exception @@ -505,7 +493,7 @@ public function limit($sql, $count, $offset = 0) throw new Zend_Db_Adapter_Mysqli_Exception("LIMIT argument count=$count is not valid"); } - $offset = intval($offset); + $offset = (int) $offset; if ($offset < 0) { /** * @see Zend_Db_Adapter_Mysqli_Exception diff --git a/library/Zend/Db/Adapter/Oracle.php b/library/Zend/Db/Adapter/Oracle.php index a03968a3ff..38eb14f12b 100644 --- a/library/Zend/Db/Adapter/Oracle.php +++ b/library/Zend/Db/Adapter/Oracle.php @@ -258,8 +258,7 @@ public function lastSequenceId($sequenceName) { $this->_connect(); $sql = 'SELECT '.$this->quoteIdentifier($sequenceName, true).'.CURRVAL FROM dual'; - $value = $this->fetchOne($sql); - return $value; + return $this->fetchOne($sql); } /** @@ -274,8 +273,7 @@ public function nextSequenceId($sequenceName) { $this->_connect(); $sql = 'SELECT '.$this->quoteIdentifier($sequenceName, true).'.NEXTVAL FROM dual'; - $value = $this->fetchOne($sql); - return $value; + return $this->fetchOne($sql); } /** @@ -318,8 +316,7 @@ public function lastInsertId($tableName = null, $primaryKey = null) public function listTables() { $this->_connect(); - $data = $this->fetchCol('SELECT table_name FROM all_tables'); - return $data; + return $this->fetchCol('SELECT table_name FROM all_tables'); } /** @@ -417,7 +414,9 @@ public function describeTable($tableName, $schemaName = null) $desc = array(); foreach ($result as $key => $row) { - list ($primary, $primaryPosition, $identity) = array(false, null, false); + $primary = false; + $primaryPosition = null; + $identity = false; if ($row[$constraint_type] == 'P') { $primary = true; $primaryPosition = $row[$position]; @@ -538,7 +537,7 @@ public function setFetchMode($mode) */ public function limit($sql, $count, $offset = 0) { - $count = intval($count); + $count = (int) $count; if ($count <= 0) { /** * @see Zend_Db_Adapter_Oracle_Exception @@ -547,7 +546,7 @@ public function limit($sql, $count, $offset = 0) throw new Zend_Db_Adapter_Oracle_Exception("LIMIT argument count=$count is not valid"); } - $offset = intval($offset); + $offset = (int) $offset; if ($offset < 0) { /** * @see Zend_Db_Adapter_Oracle_Exception @@ -631,7 +630,7 @@ public function getServerVersion() $version = oci_server_version($this->_connection); if ($version !== false) { $matches = null; - if (preg_match('/((?:[0-9]{1,2}\.){1,3}[0-9]{1,2})/', $version, $matches)) { + if (preg_match('/((?:\d{1,2}\.){1,3}\d{1,2})/', $version, $matches)) { return $matches[1]; } else { return null; diff --git a/library/Zend/Db/Adapter/Oracle/Exception.php b/library/Zend/Db/Adapter/Oracle/Exception.php index bf19dd8096..b9d7f9b8e0 100644 --- a/library/Zend/Db/Adapter/Oracle/Exception.php +++ b/library/Zend/Db/Adapter/Oracle/Exception.php @@ -41,16 +41,16 @@ class Zend_Db_Adapter_Oracle_Exception extends Zend_Db_Adapter_Exception function __construct($error = null, $code = 0) { if (is_array($error)) { - if (!isset($error['offset'])) { - $this->message = $error['code'] .' '. $error['message']; - } else { - $this->message = $error['code'] .' '. $error['message']." " - . substr($error['sqltext'], 0, $error['offset']) - . "*" - . substr($error['sqltext'], $error['offset']); - } - $this->code = $error['code']; - } else if (is_string($error)) { + if (!isset($error['offset'])) { + $this->message = $error['code'] .' '. $error['message']; + } else { + $this->message = $error['code'] .' '. $error['message']." " + . substr($error['sqltext'], 0, $error['offset']) + . "*" + . substr($error['sqltext'], $error['offset']); + } + $this->code = $error['code']; + } elseif (is_string($error)) { $this->message = $error; } if (!$this->code && $code) { diff --git a/library/Zend/Db/Adapter/Pdo/Abstract.php b/library/Zend/Db/Adapter/Pdo/Abstract.php index 4db0a5df17..3db3d548f8 100644 --- a/library/Zend/Db/Adapter/Pdo/Abstract.php +++ b/library/Zend/Db/Adapter/Pdo/Abstract.php @@ -45,6 +45,7 @@ abstract class Zend_Db_Adapter_Pdo_Abstract extends Zend_Db_Adapter_Abstract { + protected $_pdoType; /** * Default class name for a DB statement. * @@ -391,7 +392,7 @@ public function getServerVersion() return null; } $matches = null; - if (preg_match('/((?:[0-9]{1,2}\.){1,3}[0-9]{1,2})/', (string) $version, $matches)) { + if (preg_match('/((?:\d{1,2}\.){1,3}\d{1,2})/', (string) $version, $matches)) { return $matches[1]; } else { return null; diff --git a/library/Zend/Db/Adapter/Pdo/Ibm.php b/library/Zend/Db/Adapter/Pdo/Ibm.php index 2f9c5c8e17..e82dfa6f70 100644 --- a/library/Zend/Db/Adapter/Pdo/Ibm.php +++ b/library/Zend/Db/Adapter/Pdo/Ibm.php @@ -259,11 +259,7 @@ public function insert($table, array $bind) $this->_connect(); $newbind = array(); if (is_array($bind)) { - foreach ($bind as $name => $value) { - if($value !== null) { - $newbind[$name] = $value; - } - } + $newbind = array_filter($bind, fn($value) => $value !== null); } return parent::insert($table, $newbind); @@ -304,9 +300,7 @@ public function lastInsertId($tableName = null, $primaryKey = null) return $this->lastSequenceId($sequenceName); } - $id = $this->getConnection()->lastInsertId(); - - return $id; + return $this->getConnection()->lastInsertId(); } /** @@ -344,9 +338,9 @@ public function getServerVersion() try { $stmt = $this->query('SELECT service_level, fixpack_num FROM TABLE (sysproc.env_get_inst_info()) as INSTANCEINFO'); $result = $stmt->fetchAll(Zend_Db::FETCH_NUM); - if (count($result)) { + if ($result !== []) { $matches = null; - if (preg_match('/((?:[0-9]{1,2}\.){1,3}[0-9]{1,2})/', (string) $result[0][0], $matches)) { + if (preg_match('/((?:\d{1,2}\.){1,3}\d{1,2})/', (string) $result[0][0], $matches)) { return $matches[1]; } else { return null; diff --git a/library/Zend/Db/Adapter/Pdo/Ibm/Db2.php b/library/Zend/Db/Adapter/Pdo/Ibm/Db2.php index a58746d69c..6375a1fcab 100644 --- a/library/Zend/Db/Adapter/Pdo/Ibm/Db2.php +++ b/library/Zend/Db/Adapter/Pdo/Ibm/Db2.php @@ -62,8 +62,7 @@ public function __construct($adapter) */ public function listTables() { - $sql = "SELECT tabname " - . "FROM SYSCAT.TABLES "; + $sql = 'SELECT tabname FROM SYSCAT.TABLES '; return $this->_adapter->fetchCol($sql); } @@ -120,7 +119,9 @@ public function describeTable($tableName, $schemaName = null) $colseq = 11; foreach ($result as $key => $row) { - list ($primary, $primaryPosition, $identity) = array(false, null, false); + $primary = false; + $primaryPosition = null; + $identity = false; if ($row[$tabconstype] == 'P') { $primary = true; $primaryPosition = $row[$colseq]; @@ -165,13 +166,13 @@ public function describeTable($tableName, $schemaName = null) */ public function limit($sql, $count, $offset = 0) { - $count = intval($count); + $count = (int) $count; if ($count < 0) { /** @see Zend_Db_Adapter_Exception */ require_once 'Zend/Db/Adapter/Exception.php'; throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid"); } else { - $offset = intval($offset); + $offset = (int) $offset; if ($offset < 0) { /** @see Zend_Db_Adapter_Exception */ require_once 'Zend/Db/Adapter/Exception.php'; @@ -179,8 +180,7 @@ public function limit($sql, $count, $offset = 0) } if ($offset == 0 && $count > 0) { - $limit_sql = $sql . " FETCH FIRST $count ROWS ONLY"; - return $limit_sql; + return $sql . " FETCH FIRST $count ROWS ONLY"; } /** * DB2 does not implement the LIMIT clause as some RDBMS do. @@ -209,8 +209,7 @@ public function limit($sql, $count, $offset = 0) public function lastSequenceId($sequenceName) { $sql = 'SELECT PREVVAL FOR '.$this->_adapter->quoteIdentifier($sequenceName).' AS VAL FROM SYSIBM.SYSDUMMY1'; - $value = $this->_adapter->fetchOne($sql); - return $value; + return $this->_adapter->fetchOne($sql); } /** @@ -222,7 +221,6 @@ public function lastSequenceId($sequenceName) public function nextSequenceId($sequenceName) { $sql = 'SELECT NEXTVAL FOR '.$this->_adapter->quoteIdentifier($sequenceName).' AS VAL FROM SYSIBM.SYSDUMMY1'; - $value = $this->_adapter->fetchOne($sql); - return $value; + return $this->_adapter->fetchOne($sql); } } diff --git a/library/Zend/Db/Adapter/Pdo/Ibm/Ids.php b/library/Zend/Db/Adapter/Pdo/Ibm/Ids.php index 4d4b689f0a..60fe80518b 100644 --- a/library/Zend/Db/Adapter/Pdo/Ibm/Ids.php +++ b/library/Zend/Db/Adapter/Pdo/Ibm/Ids.php @@ -62,8 +62,7 @@ public function __construct($adapter) */ public function listTables() { - $sql = "SELECT tabname " - . "FROM systables "; + $sql = 'SELECT tabname FROM systables '; return $this->_adapter->fetchCol($sql); } @@ -189,7 +188,7 @@ protected function _getDataType($typeNo) ); if ($typeNo - 256 >= 0) { - $typeNo = $typeNo - 256; + $typeNo -= 256; } return $typemap[$typeNo]; @@ -219,7 +218,7 @@ protected function _getPrimaryInfo($tabid) // this should return only 1 row // unless there is no primary key, // in which case, the empty array is returned - if ($results) { + if ($results !== []) { $row = $results[0]; } else { return $cols; @@ -247,16 +246,16 @@ protected function _getPrimaryInfo($tabid) */ public function limit($sql, $count, $offset = 0) { - $count = intval($count); + $count = (int) $count; if ($count < 0) { /** @see Zend_Db_Adapter_Exception */ require_once 'Zend/Db/Adapter/Exception.php'; throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid"); - } else if ($count == 0) { - $limit_sql = str_ireplace("SELECT", "SELECT * FROM (SELECT", $sql); - $limit_sql .= ") WHERE 0 = 1"; + } elseif ($count == 0) { + $limit_sql = str_ireplace("SELECT", "SELECT * FROM (SELECT", $sql); + $limit_sql .= ") WHERE 0 = 1"; } else { - $offset = intval($offset); + $offset = (int) $offset; if ($offset < 0) { /** @see Zend_Db_Adapter_Exception */ require_once 'Zend/Db/Adapter/Exception.php'; @@ -281,8 +280,7 @@ public function lastSequenceId($sequenceName) { $sql = 'SELECT '.$this->_adapter->quoteIdentifier($sequenceName).'.CURRVAL FROM ' .'systables WHERE tabid = 1'; - $value = $this->_adapter->fetchOne($sql); - return $value; + return $this->_adapter->fetchOne($sql); } /** @@ -295,7 +293,6 @@ public function nextSequenceId($sequenceName) { $sql = 'SELECT '.$this->_adapter->quoteIdentifier($sequenceName).'.NEXTVAL FROM ' .'systables WHERE tabid = 1'; - $value = $this->_adapter->fetchOne($sql); - return $value; + return $this->_adapter->fetchOne($sql); } } diff --git a/library/Zend/Db/Adapter/Pdo/Mssql.php b/library/Zend/Db/Adapter/Pdo/Mssql.php index 7f1dfdd3bf..68430b74b7 100644 --- a/library/Zend/Db/Adapter/Pdo/Mssql.php +++ b/library/Zend/Db/Adapter/Pdo/Mssql.php @@ -121,9 +121,7 @@ protected function _dsn() foreach ($dsn as $key => $val) { $dsn[$key] = "$key=$val"; } - - $dsn = $this->_pdoType . ':' . implode(';', $dsn); - return $dsn; + return $this->_pdoType . ':' . implode(';', $dsn); } /** @@ -220,11 +218,9 @@ public function listTables() */ public function describeTable($tableName, $schemaName = null) { - if ($schemaName != null) { - if (strpos($schemaName, '.') !== false) { - $result = explode('.', $schemaName); - $schemaName = $result[1]; - } + if ($schemaName != null && strpos($schemaName, '.') !== false) { + $result = explode('.', $schemaName); + $schemaName = $result[1]; } /** * Discover metadata information about this table. @@ -277,11 +273,7 @@ public function describeTable($tableName, $schemaName = null) } $isPrimary = array_key_exists($row[$column_name], $primaryKeyColumn); - if ($isPrimary) { - $primaryPosition = $primaryKeyColumn[$row[$column_name]]; - } else { - $primaryPosition = null; - } + $primaryPosition = $isPrimary ? $primaryKeyColumn[$row[$column_name]] : null; $desc[$this->foldCase($row[$column_name])] = array( 'SCHEMA_NAME' => null, // @todo @@ -316,14 +308,14 @@ public function describeTable($tableName, $schemaName = null) */ public function limit($sql, $count, $offset = 0) { - $count = intval($count); + $count = (int) $count; if ($count <= 0) { /** @see Zend_Db_Adapter_Exception */ require_once 'Zend/Db/Adapter/Exception.php'; throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid"); } - $offset = intval($offset); + $offset = (int) $offset; if ($offset < 0) { /** @see Zend_Db_Adapter_Exception */ require_once 'Zend/Db/Adapter/Exception.php'; @@ -412,7 +404,7 @@ public function getServerVersion() try { $stmt = $this->query("SELECT CAST(SERVERPROPERTY('productversion') AS VARCHAR)"); $result = $stmt->fetchAll(Zend_Db::FETCH_NUM); - if (count($result)) { + if ($result !== []) { return $result[0][0]; } return null; diff --git a/library/Zend/Db/Adapter/Pdo/Mysql.php b/library/Zend/Db/Adapter/Pdo/Mysql.php index 51c5c2eb60..ff498a6b20 100644 --- a/library/Zend/Db/Adapter/Pdo/Mysql.php +++ b/library/Zend/Db/Adapter/Pdo/Mysql.php @@ -184,23 +184,28 @@ public function describeTable($tableName, $schemaName = null) $i = 1; $p = 1; foreach ($result as $row) { - list($length, $scale, $precision, $unsigned, $primary, $primaryPosition, $identity) - = array(null, null, null, null, false, null, false); + $length = null; + $scale = null; + $precision = null; + $unsigned = null; + $primary = false; + $primaryPosition = null; + $identity = false; if (preg_match('/unsigned/', (string) $row[$type])) { $unsigned = true; } if (preg_match('/^((?:var)?char)\((\d+)\)/', (string) $row[$type], $matches)) { $row[$type] = $matches[1]; $length = $matches[2]; - } else if (preg_match('/^decimal\((\d+),(\d+)\)/', (string) $row[$type], $matches)) { + } elseif (preg_match('/^decimal\((\d+),(\d+)\)/', (string) $row[$type], $matches)) { $row[$type] = 'decimal'; $precision = $matches[1]; $scale = $matches[2]; - } else if (preg_match('/^float\((\d+),(\d+)\)/', (string) $row[$type], $matches)) { + } elseif (preg_match('/^float\((\d+),(\d+)\)/', (string) $row[$type], $matches)) { $row[$type] = 'float'; $precision = $matches[1]; $scale = $matches[2]; - } else if (preg_match('/^((?:big|medium|small|tiny)?int)\((\d+)\)/', (string) $row[$type], $matches)) { + } elseif (preg_match('/^((?:big|medium|small|tiny)?int)\((\d+)\)/', (string) $row[$type], $matches)) { $row[$type] = $matches[1]; // The optional argument of a MySQL int type is not precision // or length; it is only a hint for display width. @@ -208,11 +213,7 @@ public function describeTable($tableName, $schemaName = null) if (strtoupper($row[$key]) == 'PRI') { $primary = true; $primaryPosition = $p; - if ($row[$extra] == 'auto_increment') { - $identity = true; - } else { - $identity = false; - } + $identity = $row[$extra] == 'auto_increment'; ++$p; } $desc[$this->foldCase($row[$field])] = array( @@ -247,14 +248,14 @@ public function describeTable($tableName, $schemaName = null) */ public function limit($sql, $count, $offset = 0) { - $count = intval($count); + $count = (int) $count; if ($count <= 0) { /** @see Zend_Db_Adapter_Exception */ require_once 'Zend/Db/Adapter/Exception.php'; throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid"); } - $offset = intval($offset); + $offset = (int) $offset; if ($offset < 0) { /** @see Zend_Db_Adapter_Exception */ require_once 'Zend/Db/Adapter/Exception.php'; diff --git a/library/Zend/Db/Adapter/Pdo/Oci.php b/library/Zend/Db/Adapter/Pdo/Oci.php index 893e1dc6cd..619430b956 100644 --- a/library/Zend/Db/Adapter/Pdo/Oci.php +++ b/library/Zend/Db/Adapter/Pdo/Oci.php @@ -143,8 +143,7 @@ public function quoteTableAs($ident, $alias = null, $auto = false) */ public function listTables() { - $data = $this->fetchCol('SELECT table_name FROM all_tables'); - return $data; + return $this->fetchCol('SELECT table_name FROM all_tables'); } /** @@ -242,7 +241,9 @@ public function describeTable($tableName, $schemaName = null) $desc = array(); foreach ($result as $key => $row) { - list ($primary, $primaryPosition, $identity) = array(false, null, false); + $primary = false; + $primaryPosition = null; + $identity = false; if ($row[$constraint_type] == 'P') { $primary = true; $primaryPosition = $row[$position]; @@ -282,8 +283,7 @@ public function describeTable($tableName, $schemaName = null) public function lastSequenceId($sequenceName) { $this->_connect(); - $value = $this->fetchOne('SELECT '.$this->quoteIdentifier($sequenceName, true).'.CURRVAL FROM dual'); - return $value; + return $this->fetchOne('SELECT '.$this->quoteIdentifier($sequenceName, true).'.CURRVAL FROM dual'); } /** @@ -297,8 +297,7 @@ public function lastSequenceId($sequenceName) public function nextSequenceId($sequenceName) { $this->_connect(); - $value = $this->fetchOne('SELECT '.$this->quoteIdentifier($sequenceName, true).'.NEXTVAL FROM dual'); - return $value; + return $this->fetchOne('SELECT '.$this->quoteIdentifier($sequenceName, true).'.NEXTVAL FROM dual'); } /** @@ -344,14 +343,14 @@ public function lastInsertId($tableName = null, $primaryKey = null) */ public function limit($sql, $count, $offset = 0) { - $count = intval($count); + $count = (int) $count; if ($count <= 0) { /** @see Zend_Db_Adapter_Exception */ require_once 'Zend/Db/Adapter/Exception.php'; throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid"); } - $offset = intval($offset); + $offset = (int) $offset; if ($offset < 0) { /** @see Zend_Db_Adapter_Exception */ require_once 'Zend/Db/Adapter/Exception.php'; diff --git a/library/Zend/Db/Adapter/Pdo/Pgsql.php b/library/Zend/Db/Adapter/Pdo/Pgsql.php index 5a96fd830a..5fad0fa399 100644 --- a/library/Zend/Db/Adapter/Pdo/Pgsql.php +++ b/library/Zend/Db/Adapter/Pdo/Pgsql.php @@ -207,7 +207,9 @@ public function describeTable($tableName, $schemaName = null) $defaultValue = $matches[1]; } } - list($primary, $primaryPosition, $identity) = array(false, null, false); + $primary = false; + $primaryPosition = null; + $identity = false; if ($row[$contype] == 'p') { $primary = true; $primaryPosition = array_search($row[$attnum], explode(',', (string) $row[$conkey])) + 1; @@ -244,7 +246,7 @@ public function describeTable($tableName, $schemaName = null) */ public function limit($sql, $count, $offset = 0) { - $count = intval($count); + $count = (int) $count; if ($count <= 0) { /** * @see Zend_Db_Adapter_Exception @@ -253,7 +255,7 @@ public function limit($sql, $count, $offset = 0) throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid"); } - $offset = intval($offset); + $offset = (int) $offset; if ($offset < 0) { /** * @see Zend_Db_Adapter_Exception @@ -282,10 +284,9 @@ public function lastSequenceId($sequenceName) { $this->_connect(); $sequenceName = str_replace($this->getQuoteIdentifierSymbol(), '', (string) $sequenceName); - $value = $this->fetchOne("SELECT CURRVAL(" + return $this->fetchOne("SELECT CURRVAL(" . $this->quote($this->quoteIdentifier($sequenceName, true)) . ")"); - return $value; } /** @@ -300,10 +301,9 @@ public function nextSequenceId($sequenceName) { $this->_connect(); $sequenceName = str_replace($this->getQuoteIdentifierSymbol(), '', (string) $sequenceName); - $value = $this->fetchOne("SELECT NEXTVAL(" + return $this->fetchOne("SELECT NEXTVAL(" . $this->quote($this->quoteIdentifier($sequenceName, true)) . ")"); - return $value; } /** diff --git a/library/Zend/Db/Adapter/Pdo/Sqlite.php b/library/Zend/Db/Adapter/Pdo/Sqlite.php index 5c342b6eb1..ed09cfc020 100644 --- a/library/Zend/Db/Adapter/Pdo/Sqlite.php +++ b/library/Zend/Db/Adapter/Pdo/Sqlite.php @@ -223,12 +223,16 @@ public function describeTable($tableName, $schemaName = null) $p = 1; foreach ($result as $key => $row) { - list($length, $scale, $precision, $primary, $primaryPosition, $identity) = - array(null, null, null, false, null, false); + $length = null; + $scale = null; + $precision = null; + $primary = false; + $primaryPosition = null; + $identity = false; if (preg_match('/^((?:var)?char)\((\d+)\)/i', (string) $row[$type], $matches)) { $row[$type] = $matches[1]; $length = $matches[2]; - } else if (preg_match('/^decimal\((\d+),(\d+)\)/i', (string) $row[$type], $matches)) { + } elseif (preg_match('/^decimal\((\d+),(\d+)\)/i', (string) $row[$type], $matches)) { $row[$type] = 'DECIMAL'; $precision = $matches[1]; $scale = $matches[2]; @@ -272,14 +276,14 @@ public function describeTable($tableName, $schemaName = null) */ public function limit($sql, $count, $offset = 0) { - $count = intval($count); + $count = (int) $count; if ($count <= 0) { /** @see Zend_Db_Adapter_Exception */ require_once 'Zend/Db/Adapter/Exception.php'; throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid"); } - $offset = intval($offset); + $offset = (int) $offset; if ($offset < 0) { /** @see Zend_Db_Adapter_Exception */ require_once 'Zend/Db/Adapter/Exception.php'; diff --git a/library/Zend/Db/Adapter/Sqlsrv.php b/library/Zend/Db/Adapter/Sqlsrv.php index 0b25241707..9286e9d023 100644 --- a/library/Zend/Db/Adapter/Sqlsrv.php +++ b/library/Zend/Db/Adapter/Sqlsrv.php @@ -149,11 +149,7 @@ protected function _connect() // A value may be a constant. if (is_string($value)) { $constantName = strtoupper($value); - if (defined($constantName)) { - $connectionInfo[$option] = constant($constantName); - } else { - $connectionInfo[$option] = $value; - } + $connectionInfo[$option] = defined($constantName) ? constant($constantName) : $value; } } } @@ -491,11 +487,7 @@ public function describeTable($tableName, $schemaName = null) } $isPrimary = array_key_exists($row[$column_name], $primaryKeyColumn); - if ($isPrimary) { - $primaryPosition = $primaryKeyColumn[$row[$column_name]]; - } else { - $primaryPosition = null; - } + $primaryPosition = $isPrimary ? $primaryKeyColumn[$row[$column_name]] : null; $desc[$this->foldCase($row[$column_name])] = array( 'SCHEMA_NAME' => null, // @todo @@ -600,13 +592,13 @@ public function setFetchMode($mode) */ public function limit($sql, $count, $offset = 0) { - $count = intval($count); + $count = (int) $count; if ($count <= 0) { require_once 'Zend/Db/Adapter/Exception.php'; throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid"); } - $offset = intval($offset); + $offset = (int) $offset; if ($offset < 0) { /** @see Zend_Db_Adapter_Exception */ require_once 'Zend/Db/Adapter/Exception.php'; @@ -618,11 +610,7 @@ public function limit($sql, $count, $offset = 0) } else { $orderby = stristr($sql, 'ORDER BY'); - if (!$orderby) { - $over = 'ORDER BY (SELECT 0)'; - } else { - $over = preg_replace('/\"[^,]*\".\"([^,]*)\"/i', '"inner_tbl"."$1"', $orderby); - } + $over = $orderby ? preg_replace('/\"[^,]*\".\"([^,]*)\"/i', '"inner_tbl"."$1"', $orderby) : 'ORDER BY (SELECT 0)'; // Remove ORDER BY clause from $sql $sql = preg_replace('/\s+ORDER BY(.*)/', '', $sql); @@ -652,12 +640,8 @@ public function limit($sql, $count, $offset = 0) */ public function supportsParameters($type) { - if ($type == 'positional') { - return true; - } - // if its 'named' or anything else - return false; + return $type == 'positional'; } /** diff --git a/library/Zend/Db/Profiler.php b/library/Zend/Db/Profiler.php index b5114bc32f..059a000c9d 100644 --- a/library/Zend/Db/Profiler.php +++ b/library/Zend/Db/Profiler.php @@ -162,11 +162,7 @@ public function getEnabled() */ public function setFilterElapsedSecs($minimumSeconds = null) { - if (null === $minimumSeconds) { - $this->_filterElapsedSecs = null; - } else { - $this->_filterElapsedSecs = (integer) $minimumSeconds; - } + $this->_filterElapsedSecs = null === $minimumSeconds ? null : (integer) $minimumSeconds; return $this; } @@ -384,11 +380,7 @@ public function getQueryProfiles($queryType = null, $showUnfinished = false) { $queryProfiles = array(); foreach ($this->_queryProfiles as $key => $qp) { - if ($queryType === null) { - $condition = true; - } else { - $condition = ($qp->getQueryType() & $queryType); - } + $condition = $queryType === null ? true : $qp->getQueryType() & $queryType; if (($qp->hasEnded() || $showUnfinished) && $condition) { $queryProfiles[$key] = $qp; @@ -415,11 +407,7 @@ public function getTotalElapsedSecs($queryType = null) { $elapsedSecs = 0; foreach ($this->_queryProfiles as $key => $qp) { - if (null === $queryType) { - $condition = true; - } else { - $condition = ($qp->getQueryType() & $queryType); - } + $condition = null === $queryType ? true : $qp->getQueryType() & $queryType; if (($qp->hasEnded()) && $condition) { $elapsedSecs += $qp->getElapsedSecs(); } diff --git a/library/Zend/Db/Profiler/Firebug.php b/library/Zend/Db/Profiler/Firebug.php index 5d543f32a5..8425b339a4 100644 --- a/library/Zend/Db/Profiler/Firebug.php +++ b/library/Zend/Db/Profiler/Firebug.php @@ -90,7 +90,6 @@ public function setEnabled($enable) parent::setEnabled($enable); if ($this->getEnabled()) { - if (!$this->_message) { $this->_message = new Zend_Wildfire_Plugin_FirePhp_TableMessage($this->_label); $this->_message->setBuffered(true); @@ -99,14 +98,9 @@ public function setEnabled($enable) $this->_message->setOption('includeLineNumbers', false); Zend_Wildfire_Plugin_FirePhp::getInstance()->send($this->_message); } - - } else { - - if ($this->_message) { - $this->_message->setDestroy(true); - $this->_message = null; - } - + } elseif ($this->_message) { + $this->_message->setDestroy(true); + $this->_message = null; } return $this; diff --git a/library/Zend/Db/Select.php b/library/Zend/Db/Select.php index 1c33c04ab1..8b30552425 100644 --- a/library/Zend/Db/Select.php +++ b/library/Zend/Db/Select.php @@ -559,11 +559,7 @@ public function having($cond, $value = null, $type = null) $cond = $this->_adapter->quoteInto($cond, $value, $type); } - if ($this->_parts[self::HAVING]) { - $this->_parts[self::HAVING][] = self::SQL_AND . " ($cond)"; - } else { - $this->_parts[self::HAVING][] = "($cond)"; - } + $this->_parts[self::HAVING][] = $this->_parts[self::HAVING] ? self::SQL_AND . " ($cond)" : "($cond)"; return $this; } @@ -586,11 +582,7 @@ public function orHaving($cond, $value = null, $type = null) $cond = $this->_adapter->quoteInto($cond, $value, $type); } - if ($this->_parts[self::HAVING]) { - $this->_parts[self::HAVING][] = self::SQL_OR . " ($cond)"; - } else { - $this->_parts[self::HAVING][] = "($cond)"; - } + $this->_parts[self::HAVING][] = $this->_parts[self::HAVING] ? self::SQL_OR . " ($cond)" : "($cond)"; return $this; } @@ -786,7 +778,7 @@ protected function _join($type, $name, $cond, $cols, $schema = null) throw new Zend_Db_Select_Exception("Invalid join type '$type'"); } - if (count($this->_parts[self::UNION])) { + if (count($this->_parts[self::UNION]) > 0) { require_once 'Zend/Db/Select/Exception.php'; throw new Zend_Db_Select_Exception("Invalid use of table with " . self::SQL_UNION); } @@ -979,7 +971,7 @@ protected function _tableCols($correlationName, $cols, $afterCorrelationName = n $columnValues[] = array($currentCorrelationName, $col, is_string($alias) ? $alias : null); } - if ($columnValues) { + if ($columnValues !== []) { // should we attempt to prepend or insert these values? if ($afterCorrelationName === true || is_string($afterCorrelationName)) { @@ -1001,12 +993,12 @@ protected function _tableCols($correlationName, $cols, $afterCorrelationName = n // apply current values to current stack foreach ($columnValues as $columnValue) { - array_push($this->_parts[self::COLUMNS], $columnValue); + $this->_parts[self::COLUMNS][] = $columnValue; } // finish ensuring that all previous values are applied (if they exist) while ($tmpColumns) { - array_push($this->_parts[self::COLUMNS], array_shift($tmpColumns)); + $this->_parts[self::COLUMNS][] = array_shift($tmpColumns); } } } @@ -1022,7 +1014,7 @@ protected function _tableCols($correlationName, $cols, $afterCorrelationName = n */ protected function _where($condition, $value = null, $type = null, $bool = true) { - if (count($this->_parts[self::UNION])) { + if (count($this->_parts[self::UNION]) > 0) { require_once 'Zend/Db/Select/Exception.php'; throw new Zend_Db_Select_Exception("Invalid use of where clause with " . self::SQL_UNION); } @@ -1033,11 +1025,7 @@ protected function _where($condition, $value = null, $type = null, $bool = true) $cond = ""; if ($this->_parts[self::WHERE]) { - if ($bool === true) { - $cond = self::SQL_AND . ' '; - } else { - $cond = self::SQL_OR . ' '; - } + $cond = $bool ? self::SQL_AND . ' ' : self::SQL_OR . ' '; } return $cond . "($condition)"; @@ -1100,7 +1088,7 @@ protected function _renderDistinct($sql) */ protected function _renderColumns($sql) { - if (!count($this->_parts[self::COLUMNS])) { + if (count($this->_parts[self::COLUMNS]) === 0) { return null; } @@ -1259,12 +1247,12 @@ protected function _renderOrder($sql) $order = array(); foreach ($this->_parts[self::ORDER] as $term) { if (is_array($term)) { - if(is_numeric($term[0]) && strval(intval($term[0])) == $term[0]) { + if(is_numeric($term[0]) && strval((int) $term[0]) == $term[0]) { $order[] = (int)trim($term[0]) . ' ' . $term[1]; } else { $order[] = $this->_adapter->quoteIdentifier($term[0], true) . ' ' . $term[1]; } - } elseif (is_numeric($term) && strval(intval($term)) == $term) { + } elseif (is_numeric($term) && strval((int) $term) == $term) { $order[] = (int)trim($term); } else { $order[] = $this->_adapter->quoteIdentifier($term, true); @@ -1342,7 +1330,7 @@ public function __call($method, array $args) */ if (preg_match('/^join([a-zA-Z]*?)Using$/', $method, $matches)) { $type = strtolower($matches[1]); - if ($type) { + if ($type !== '' && $type !== '0') { $type .= ' join'; if (!in_array($type, self::$_joinTypes)) { require_once 'Zend/Db/Select/Exception.php'; @@ -1356,7 +1344,9 @@ public function __call($method, array $args) $type = self::INNER_JOIN; } array_unshift($args, $type); - return call_user_func_array(array($this, '_joinUsing'), $args); + return call_user_func_array(function ($type, $name, $cond, $cols = '*', $schema = \null) : \Zend_Db_Select { + return $this->_joinUsing($type, $name, $cond, $cols, $schema); + }, $args); } require_once 'Zend/Db/Select/Exception.php'; diff --git a/library/Zend/Db/Statement.php b/library/Zend/Db/Statement.php index be5e2d5912..671ef04d3b 100644 --- a/library/Zend/Db/Statement.php +++ b/library/Zend/Db/Statement.php @@ -137,28 +137,26 @@ protected function _parseParameters($sql) $sql = $this->_stripQuoted($sql); // split into text and params - $this->_sqlSplit = preg_split('/(\?|\:[a-zA-Z0-9_]+)/', + $this->_sqlSplit = preg_split('/(\?|\:\w+)/', $sql, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY); // map params $this->_sqlParam = array(); foreach ($this->_sqlSplit as $key => $val) { if ($val == '?') { - if ($this->_adapter->supportsParameters('positional') === false) { + if (!$this->_adapter->supportsParameters('positional')) { /** * @see Zend_Db_Statement_Exception */ require_once 'Zend/Db/Statement/Exception.php'; throw new Zend_Db_Statement_Exception("Invalid bind-variable position '$val'"); } - } else if ($val[0] == ':') { - if ($this->_adapter->supportsParameters('named') === false) { - /** - * @see Zend_Db_Statement_Exception - */ - require_once 'Zend/Db/Statement/Exception.php'; - throw new Zend_Db_Statement_Exception("Invalid bind-variable name '$val'"); - } + } elseif ($val[0] == ':' && !$this->_adapter->supportsParameters('named')) { + /** + * @see Zend_Db_Statement_Exception + */ + require_once 'Zend/Db/Statement/Exception.php'; + throw new Zend_Db_Statement_Exception("Invalid bind-variable name '$val'"); } $this->_sqlParam[] = $val; } @@ -253,11 +251,11 @@ public function bindParam($parameter, &$variable, $type = null, $length = null, if ($intval >= 1 || $intval <= count($this->_sqlParam)) { $position = $intval; } - } else if ($this->_adapter->supportsParameters('named')) { + } elseif ($this->_adapter->supportsParameters('named')) { if ($parameter[0] != ':') { $parameter = ':' . $parameter; } - if (in_array($parameter, $this->_sqlParam) !== false) { + if (in_array($parameter, $this->_sqlParam)) { $position = $parameter; } } @@ -318,7 +316,7 @@ public function execute(array $params = null) } else { $qp->bindParams($this->_bindParam); } - $qp->start($this->_queryId); + $qp->start(); $retval = $this->_execute($params); diff --git a/library/Zend/Db/Statement/Db2.php b/library/Zend/Db/Statement/Db2.php index c23a9f3a95..5edc9d315b 100644 --- a/library/Zend/Db/Statement/Db2.php +++ b/library/Zend/Db/Statement/Db2.php @@ -90,11 +90,7 @@ public function _bindParam($parameter, &$variable, $type = null, $length = null, $type = DB2_PARAM_IN; } - if (isset($options['data-type'])) { - $datatype = $options['data-type']; - } else { - $datatype = DB2_CHAR; - } + $datatype = isset($options['data-type']) ? $options['data-type'] : DB2_CHAR; if (!db2_bind_param($this->_stmt, $parameter, "variable", $type, $datatype)) { /** @@ -198,13 +194,9 @@ public function _execute(array $params = null) } $retval = true; - if ($params !== null) { - $retval = @db2_execute($this->_stmt, $params); - } else { - $retval = @db2_execute($this->_stmt); - } + $retval = $params !== null ? @db2_execute($this->_stmt, $params) : @db2_execute($this->_stmt); - if ($retval === false) { + if (!$retval) { /** * @see Zend_Db_Statement_Db2_Exception */ @@ -215,7 +207,7 @@ public function _execute(array $params = null) } $this->_keys = array(); - if ($field_num = $this->columnCount()) { + if (($field_num = $this->columnCount()) !== 0) { for ($i = 0; $i < $field_num; $i++) { $name = db2_field_name($this->_stmt, $i); $this->_keys[] = $name; @@ -289,8 +281,7 @@ public function fetch($style = null, $cursor = null, $offset = null) */ public function fetchObject($class = 'stdClass', array $config = array()) { - $obj = $this->fetch(Zend_Db::FETCH_OBJ); - return $obj; + return $this->fetch(Zend_Db::FETCH_OBJ); } /** diff --git a/library/Zend/Db/Statement/Mysqli.php b/library/Zend/Db/Statement/Mysqli.php index fecd67f92d..8707526f2c 100644 --- a/library/Zend/Db/Statement/Mysqli.php +++ b/library/Zend/Db/Statement/Mysqli.php @@ -135,7 +135,7 @@ public function closeCursor() */ public function columnCount() { - if (isset($this->_meta) && $this->_meta) { + if ($this->_meta !== null && $this->_meta) { return $this->_meta->field_count; } return 0; @@ -192,7 +192,7 @@ public function _execute(array $params = null) $params = $this->_bindParam; } // send $params as input parameters to the statement - if ($params) { + if ($params !== []) { array_unshift($params, str_repeat('s', count($params))); $stmtParams = array(); foreach ($params as $k => &$value) { @@ -291,9 +291,7 @@ public function fetch($style = null, $cursor = null, $offset = null) // dereference the result values, otherwise things like fetchAll() // return the same values for every entry (because of the reference). $values = array(); - foreach ($this->_values as $key => $val) { - $values[] = $val; - } + $values = $this->_values; $row = false; switch ($style) { diff --git a/library/Zend/Db/Statement/Oracle.php b/library/Zend/Db/Statement/Oracle.php index a157a8a439..9a1acc0c47 100644 --- a/library/Zend/Db/Statement/Oracle.php +++ b/library/Zend/Db/Statement/Oracle.php @@ -121,7 +121,7 @@ protected function _bindParam($parameter, &$variable, $type = null, $length = nu } $retval = @oci_bind_by_name($this->_stmt, $parameter, $variable, $length, $type); - if ($retval === false) { + if (!$retval) { /** * @see Zend_Db_Adapter_Oracle_Exception */ @@ -255,7 +255,7 @@ public function _execute(array $params = null) } $retval = @oci_execute($this->_stmt, $this->_adapter->_getExecuteMode()); - if ($retval === false) { + if (!$retval) { /** * @see Zend_Db_Adapter_Oracle_Exception */ @@ -264,7 +264,7 @@ public function _execute(array $params = null) } $this->_keys = Array(); - if ($field_num = oci_num_fields($this->_stmt)) { + if (($field_num = oci_num_fields($this->_stmt)) !== 0) { for ($i = 1; $i <= $field_num; $i++) { $name = oci_field_name($this->_stmt, $i); $this->_keys[] = $name; @@ -394,7 +394,7 @@ public function fetchAll($style = null, $col = 0) case Zend_Db::FETCH_OBJ: break; case Zend_Db::FETCH_COLUMN: - $flags = $flags &~ OCI_FETCHSTATEMENT_BY_ROW; + $flags &= ~ OCI_FETCHSTATEMENT_BY_ROW; $flags |= OCI_FETCHSTATEMENT_BY_COLUMN; $flags |= OCI_NUM; break; @@ -414,7 +414,7 @@ public function fetchAll($style = null, $col = 0) $result = Array(); if ($flags != OCI_FETCHSTATEMENT_BY_ROW) { /* not Zend_Db::FETCH_OBJ */ - if (! ($rows = oci_fetch_all($this->_stmt, $result, 0, -1, $flags) )) { + if (($rows = oci_fetch_all($this->_stmt, $result, 0, -1, $flags)) === 0) { if ($error = oci_error($this->_stmt)) { /** * @see Zend_Db_Adapter_Oracle_Exception @@ -422,7 +422,7 @@ public function fetchAll($style = null, $col = 0) require_once 'Zend/Db/Statement/Oracle/Exception.php'; throw new Zend_Db_Statement_Oracle_Exception($error); } - if (!$rows) { + if ($rows === 0) { return array(); } } diff --git a/library/Zend/Db/Statement/Pdo.php b/library/Zend/Db/Statement/Pdo.php index b11bc6c7b1..7f999ac44b 100644 --- a/library/Zend/Db/Statement/Pdo.php +++ b/library/Zend/Db/Statement/Pdo.php @@ -105,7 +105,7 @@ protected function _bindParam($parameter, &$variable, $type = null, $length = nu $type = PDO::PARAM_BOOL; } elseif ($variable === null) { $type = PDO::PARAM_NULL; - } elseif (is_integer($variable)) { + } elseif (is_int($variable)) { $type = PDO::PARAM_INT; } else { $type = PDO::PARAM_STR; @@ -245,7 +245,7 @@ public function _execute(array $params = null) * @return mixed Array, object, or scalar depending on fetch mode. * @throws Zend_Db_Statement_Exception */ - public function fetch($style = null, $cursor = null, $offset = null) + public function fetch($style = null, $cursor = PDO::FETCH_ORI_NEXT, $offset = 0) { if ($style === null) { $style = $this->_fetchMode; @@ -263,6 +263,7 @@ public function fetch($style = null, $cursor = null, $offset = null) * * @return IteratorIterator */ + #[\ReturnTypeWillChange] public function getIterator() { return new IteratorIterator($this->_stmt); diff --git a/library/Zend/Db/Table.php b/library/Zend/Db/Table.php index 6f676439de..25bdc04c90 100644 --- a/library/Zend/Db/Table.php +++ b/library/Zend/Db/Table.php @@ -62,15 +62,12 @@ public function __construct($config = array(), $definition = null) E_USER_NOTICE ); $config = array(self::ADAPTER => $config); + } elseif ($definition instanceof Zend_Db_Table_Definition + && $definition->hasTableConfig($config)) { + // this will have DEFINITION_CONFIG_NAME & DEFINITION + $config = $definition->getTableConfig($config); } else { - // process this as table with or without a definition - if ($definition instanceof Zend_Db_Table_Definition - && $definition->hasTableConfig($config)) { - // this will have DEFINITION_CONFIG_NAME & DEFINITION - $config = $definition->getTableConfig($config); - } else { - $config = array(self::NAME => $config); - } + $config = array(self::NAME => $config); } } diff --git a/library/Zend/Db/Table/Abstract.php b/library/Zend/Db/Table/Abstract.php index 66aa60545a..6212ea152a 100644 --- a/library/Zend/Db/Table/Abstract.php +++ b/library/Zend/Db/Table/Abstract.php @@ -262,7 +262,7 @@ public function __construct($config = array()) $config = array(self::ADAPTER => $config); } - if ($config) { + if ($config !== []) { $this->setOptions($config); } @@ -773,7 +773,7 @@ protected function _setupTableName() { if (! $this->_name) { $this->_name = get_class($this); - } else if (strpos($this->_name, '.')) { + } elseif (strpos($this->_name, '.')) { list($this->_schema, $this->_name) = explode('.', $this->_name); } } @@ -789,7 +789,7 @@ protected function _setupTableName() */ protected function _setupMetadata() { - if ($this->metadataCacheInClass() && (count($this->_metadata) > 0)) { + if ($this->metadataCacheInClass() && ($this->_metadata !== [])) { return true; } @@ -888,9 +888,9 @@ protected function _setupPrimaryKey() require_once 'Zend/Db/Table/Exception.php'; throw new Zend_Db_Table_Exception("A table must have a primary key, but none was found for table '{$this->_name}'"); } - } else if (!is_array($this->_primary)) { + } elseif (!is_array($this->_primary)) { $this->_primary = array(1 => $this->_primary); - } else if (isset($this->_primary[0])) { + } elseif (isset($this->_primary[0])) { array_unshift($this->_primary, null); unset($this->_primary[0]); } @@ -939,11 +939,7 @@ protected function _getReferenceMapNormalized() // normalize COLUMNS and REF_COLUMNS to arrays case self::COLUMNS: case self::REF_COLUMNS: - if (!is_array($value)) { - $referenceMapNormalized[$rule][$key] = array($value); - } else { - $referenceMapNormalized[$rule][$key] = $value; - } + $referenceMapNormalized[$rule][$key] = is_array($value) ? $value : array($value); break; // other values are copied as-is @@ -1050,13 +1046,12 @@ public function insert(array $data) * position of the data. The following values are considered empty: * null, false, true, '', array() */ - if (array_key_exists($pkIdentity, $data)) { - if ($data[$pkIdentity] === null // null - || $data[$pkIdentity] === '' // empty string - || is_bool($data[$pkIdentity]) // boolean - || (is_array($data[$pkIdentity]) && empty($data[$pkIdentity]))) { // empty array - unset($data[$pkIdentity]); - } + if (array_key_exists($pkIdentity, $data) && ($data[$pkIdentity] === null // null + || $data[$pkIdentity] === '' // empty string + || is_bool($data[$pkIdentity]) // boolean + || ($data[$pkIdentity] === []))) { + // empty array + unset($data[$pkIdentity]); } /** @@ -1151,7 +1146,8 @@ public function _cascadeUpdate($parentTableClassname, array $oldPrimaryKey, arra case self::CASCADE: $newRefs = array(); $where = array(); - for ($i = 0; $i < count($map[self::COLUMNS]); ++$i) { + $itemsCount = count($map[self::COLUMNS]); + for ($i = 0; $i < $itemsCount; ++$i) { $col = $this->_db->foldCase($map[self::COLUMNS][$i]); $refCol = $this->_db->foldCase($map[self::REF_COLUMNS][$i]); if (array_key_exists($refCol, $newPrimaryKey)) { @@ -1230,7 +1226,8 @@ public function _cascadeDelete($parentTableClassname, array $primaryKey) // CASCADE or CASCADE_RECURSE if (in_array($map[self::ON_DELETE], array(self::CASCADE, self::CASCADE_RECURSE))) { - for ($i = 0; $i < count($map[self::COLUMNS]); ++$i) { + $itemsCount = count($map[self::COLUMNS]); + for ($i = 0; $i < $itemsCount; ++$i) { $col = $this->_db->foldCase($map[self::COLUMNS][$i]); $refCol = $this->_db->foldCase($map[self::REF_COLUMNS][$i]); $type = $this->_metadata[$col]['DATA_TYPE']; @@ -1285,10 +1282,9 @@ public function _cascadeDelete($parentTableClassname, array $primaryKey) * @return Zend_Db_Table_Rowset_Abstract Row(s) matching the criteria. * @throws Zend_Db_Table_Exception */ - public function find() + public function find(...$args) { $this->_setupPrimaryKey(); - $args = func_get_args(); $keyNames = array_values((array) $this->_primary); if (count($args) < count($keyNames)) { @@ -1313,7 +1309,7 @@ public function find() } if ($numberTerms == 0) { $numberTerms = $keyValuesCount; - } else if ($keyValuesCount != $numberTerms) { + } elseif ($keyValuesCount != $numberTerms) { require_once 'Zend/Db/Table/Exception.php'; throw new Zend_Db_Table_Exception("Missing value(s) for the primary key"); } @@ -1327,7 +1323,7 @@ public function find() } $whereClause = null; - if (count($whereList)) { + if ($whereList !== []) { $whereOrTerms = array(); $tableName = $this->_db->quoteTableAs($this->_name, null, true); foreach ($whereList as $keyValueSets) { @@ -1492,7 +1488,7 @@ public function createRow(array $data = array(), $defaultSource = null) if ($defaultSource == self::DEFAULT_DB) { foreach ($this->_metadata as $metadataName => $metadata) { if (($metadata['DEFAULT'] != null) && - ($metadata['NULLABLE'] !== true || ($metadata['NULLABLE'] === true && isset($this->_defaultValues[$metadataName]) && $this->_defaultValues[$metadataName] === true)) && + ($metadata['NULLABLE'] !== true || ($metadata['NULLABLE'] && isset($this->_defaultValues[$metadataName]) && $this->_defaultValues[$metadataName] === true)) && (!(isset($this->_defaultValues[$metadataName]) && $this->_defaultValues[$metadataName] === false))) { $defaults[$metadataName] = $metadata['DEFAULT']; } @@ -1575,8 +1571,7 @@ protected function _order(Zend_Db_Table_Select $select, $order) protected function _fetch(Zend_Db_Table_Select $select) { $stmt = $this->_db->query($select); - $data = $stmt->fetchAll(Zend_Db::FETCH_ASSOC); - return $data; + return $stmt->fetchAll(Zend_Db::FETCH_ASSOC); } /** diff --git a/library/Zend/Db/Table/Row/Abstract.php b/library/Zend/Db/Table/Row/Abstract.php index 0ae6f8d028..38c3960e30 100644 --- a/library/Zend/Db/Table/Row/Abstract.php +++ b/library/Zend/Db/Table/Row/Abstract.php @@ -450,7 +450,7 @@ protected function _doInsert() /** * A read-only row cannot be saved. */ - if ($this->_readOnly === true) { + if ($this->_readOnly) { require_once 'Zend/Db/Table/Row/Exception.php'; throw new Zend_Db_Table_Row_Exception('This row has been marked read-only'); } @@ -508,7 +508,7 @@ protected function _doUpdate() /** * A read-only row cannot be saved. */ - if ($this->_readOnly === true) { + if ($this->_readOnly) { require_once 'Zend/Db/Table/Row/Exception.php'; throw new Zend_Db_Table_Row_Exception('This row has been marked read-only'); } @@ -539,7 +539,7 @@ protected function _doUpdate() * Execute cascading updates against dependent tables. * Do this only if primary key value(s) were changed. */ - if (count($pkDiffData) > 0) { + if ($pkDiffData !== []) { $depTables = $this->_getTable()->getDependentTables(); if (!empty($depTables)) { $pkNew = $this->_getPrimaryKey(true); @@ -557,7 +557,7 @@ protected function _doUpdate() * Use the $diffData variable, so the UPDATE statement * includes SET terms only for data values that changed. */ - if (count($diffData) > 0) { + if ($diffData !== []) { $this->_getTable()->update($diffData, $where); } @@ -597,7 +597,7 @@ public function delete() /** * A read-only row cannot be deleted. */ - if ($this->_readOnly === true) { + if ($this->_readOnly) { require_once 'Zend/Db/Table/Row/Exception.php'; throw new Zend_Db_Table_Row_Exception('This row has been marked read-only'); } @@ -712,12 +712,8 @@ protected function _getPrimaryKey($useDirty = true) } $primary = array_flip($this->_primary); - if ($useDirty) { - $array = array_intersect_key($this->_data, $primary); - } else { - $array = array_intersect_key($this->_cleanData, $primary); - } - if (count($primary) != count($array)) { + $array = $useDirty ? array_intersect_key($this->_data, $primary) : array_intersect_key($this->_cleanData, $primary); + if (count($primary) !== count($array)) { require_once 'Zend/Db/Table/Row/Exception.php'; throw new Zend_Db_Table_Row_Exception("The specified Table '$this->_tableClass' does not have the same primary key as the Row"); } @@ -770,7 +766,7 @@ protected function _refresh() $where = $this->_getWhereQuery(); $row = $this->_getTable()->fetchRow($where); - if (null === $row) { + if (!$row instanceof \Zend_Db_Table_Row_Abstract) { require_once 'Zend/Db/Table/Row/Exception.php'; throw new Zend_Db_Table_Row_Exception('Cannot refresh row as parent is missing'); } @@ -852,7 +848,7 @@ protected function _postDelete() */ protected function _prepareReference(Zend_Db_Table_Abstract $dependentTable, Zend_Db_Table_Abstract $parentTable, $ruleKey) { - $parentTableName = (get_class($parentTable) === 'Zend_Db_Table') ? $parentTable->getDefinitionConfigName() : get_class($parentTable); + $parentTableName = ($parentTable instanceof \Zend_Db_Table) ? $parentTable->getDefinitionConfigName() : get_class($parentTable); $map = $dependentTable->getReference($parentTableName, $ruleKey); if (!isset($map[Zend_Db_Table_Abstract::REF_COLUMNS])) { @@ -906,8 +902,9 @@ public function findDependentRowset($dependentTable, $ruleKey = null, Zend_Db_Ta } $map = $this->_prepareReference($dependentTable, $this->_getTable(), $ruleKey); + $itemsCount = count($map[Zend_Db_Table_Abstract::COLUMNS]); - for ($i = 0; $i < count($map[Zend_Db_Table_Abstract::COLUMNS]); ++$i) { + for ($i = 0; $i < $itemsCount; ++$i) { $parentColumnName = $db->foldCase($map[Zend_Db_Table_Abstract::REF_COLUMNS][$i]); $value = $this->_data[$parentColumnName]; // Use adapter from dependent table to ensure correct query construction @@ -962,9 +959,10 @@ public function findParentRow($parentTable, $ruleKey = null, Zend_Db_Table_Selec } $map = $this->_prepareReference($this->_getTable(), $parentTable, $ruleKey); + $itemsCount = count($map[Zend_Db_Table_Abstract::COLUMNS]); // iterate the map, creating the proper wheres - for ($i = 0; $i < count($map[Zend_Db_Table_Abstract::COLUMNS]); ++$i) { + for ($i = 0; $i < $itemsCount; ++$i) { $dependentColumnName = $db->foldCase($map[Zend_Db_Table_Abstract::COLUMNS][$i]); $value = $this->_data[$dependentColumnName]; // Use adapter from parent table to ensure correct query construction @@ -1059,8 +1057,9 @@ public function findManyToManyRowset($matchTable, $intersectionTable, $callerRef $matchSchema = isset($matchInfo['schema']) ? $matchInfo['schema'] : null; $matchMap = $this->_prepareReference($intersectionTable, $matchTable, $matchRefRule); + $itemsCount = count($matchMap[Zend_Db_Table_Abstract::COLUMNS]); - for ($i = 0; $i < count($matchMap[Zend_Db_Table_Abstract::COLUMNS]); ++$i) { + for ($i = 0; $i < $itemsCount; ++$i) { $interCol = $interDb->quoteIdentifier('i' . '.' . $matchMap[Zend_Db_Table_Abstract::COLUMNS][$i], true); $matchCol = $interDb->quoteIdentifier('m' . '.' . $matchMap[Zend_Db_Table_Abstract::REF_COLUMNS][$i], true); $joinCond[] = "$interCol = $matchCol"; @@ -1072,8 +1071,9 @@ public function findManyToManyRowset($matchTable, $intersectionTable, $callerRef ->setIntegrityCheck(false); $callerMap = $this->_prepareReference($intersectionTable, $this->_getTable(), $callerRefRule); + $itemsCount = count($callerMap[Zend_Db_Table_Abstract::COLUMNS]); - for ($i = 0; $i < count($callerMap[Zend_Db_Table_Abstract::COLUMNS]); ++$i) { + for ($i = 0; $i < $itemsCount; ++$i) { $callerColumnName = $db->foldCase($callerMap[Zend_Db_Table_Abstract::REF_COLUMNS][$i]); $value = $this->_data[$callerColumnName]; $interColumnName = $interDb->foldCase($callerMap[Zend_Db_Table_Abstract::COLUMNS][$i]); @@ -1103,8 +1103,7 @@ public function findManyToManyRowset($matchTable, $intersectionTable, $callerRef throw new Zend_Db_Table_Row_Exception($e->getMessage(), $e->getCode(), $e); } } - $rowset = new $rowsetClass($config); - return $rowset; + return new $rowsetClass($config); } /** @@ -1120,11 +1119,7 @@ public function __call($method, array $args) { $matches = array(); - if (count($args) && $args[0] instanceof Zend_Db_Table_Select) { - $select = $args[0]; - } else { - $select = null; - } + $select = count($args) && $args[0] instanceof Zend_Db_Table_Select ? $args[0] : null; /** * Recognize methods for Has-Many cases: diff --git a/library/Zend/Db/Table/Rowset/Abstract.php b/library/Zend/Db/Table/Rowset/Abstract.php index abace7bbde..d5b2a32672 100644 --- a/library/Zend/Db/Table/Rowset/Abstract.php +++ b/library/Zend/Db/Table/Rowset/Abstract.php @@ -242,7 +242,7 @@ public function rewind() */ public function current() { - if ($this->valid() === false) { + if (!$this->valid()) { return null; } @@ -431,10 +431,8 @@ protected function _loadAndReturnRow($position) if ( $this->_table instanceof Zend_Db_Table_Abstract ) { $info = $this->_table->info(); - if ( $this->_rows[$position] instanceof Zend_Db_Table_Row_Abstract ) { - if ($info['cols'] == array_keys($this->_data[$position])) { - $this->_rows[$position]->setTable($this->getTable()); - } + if ( $this->_rows[$position] instanceof Zend_Db_Table_Row_Abstract && $info['cols'] == array_keys($this->_data[$position]) ) { + $this->_rows[$position]->setTable($this->getTable()); } } else { $this->_rows[$position]->setTable(null); diff --git a/library/Zend/Db/Table/Select.php b/library/Zend/Db/Table/Select.php index c352836c99..a7f2802dab 100644 --- a/library/Zend/Db/Table/Select.php +++ b/library/Zend/Db/Table/Select.php @@ -129,7 +129,7 @@ public function isReadOnly() $fields = $this->getPart(Zend_Db_Table_Select::COLUMNS); $cols = $this->_info[Zend_Db_Table_Abstract::COLS]; - if (!count($fields)) { + if (count($fields) === 0) { return $readOnly; } @@ -197,7 +197,7 @@ public function assemble() if (count($this->_parts[self::UNION]) == 0) { // If no fields are specified we assume all fields from primary table - if (!count($fields)) { + if (count($fields) === 0) { $this->from($primary, self::SQL_WILDCARD, $schema); $fields = $this->getPart(Zend_Db_Table_Select::COLUMNS); } @@ -209,11 +209,9 @@ public function assemble() list($table, $column) = $columnEntry; // Check each column to ensure it only references the primary table - if ($column) { - if (!isset($from[$table]) || $from[$table]['tableName'] != $primary) { - require_once 'Zend/Db/Table/Select/Exception.php'; - throw new Zend_Db_Table_Select_Exception('Select query cannot join with another table'); - } + if ($column && (!isset($from[$table]) || $from[$table]['tableName'] != $primary)) { + require_once 'Zend/Db/Table/Select/Exception.php'; + throw new Zend_Db_Table_Select_Exception('Select query cannot join with another table'); } } } diff --git a/library/Zend/Dojo/BuildLayer.php b/library/Zend/Dojo/BuildLayer.php index 74e05c5489..99b20c7224 100644 --- a/library/Zend/Dojo/BuildLayer.php +++ b/library/Zend/Dojo/BuildLayer.php @@ -299,7 +299,7 @@ public function setProfileOptions(array $options) */ public function addProfileOptions(array $options) { - $this->_profileOptions = $this->_profileOptions + $options; + $this->_profileOptions += $options; return $this; } @@ -475,9 +475,7 @@ public function generateLayerScript() } } - $content .= "})();"; - - return $content; + return $content . "})();"; } /** @@ -529,7 +527,6 @@ protected function _filterJsonProfileToJavascript($profile) require_once 'Zend/Json.php'; $profile = Zend_Json::encode($profile); $profile = trim($profile, '"'); - $profile = preg_replace('/' . preg_quote('\\') . '/', '', $profile); - return $profile; + return preg_replace('/' . preg_quote('\\', '/') . '/', '', $profile); } } diff --git a/library/Zend/Dojo/Data.php b/library/Zend/Dojo/Data.php index 8d59e78400..4ca4252951 100644 --- a/library/Zend/Dojo/Data.php +++ b/library/Zend/Dojo/Data.php @@ -251,11 +251,7 @@ public function getIdentifier() */ public function setLabel($label) { - if (null === $label) { - $this->_label = null; - } else { - $this->_label = (string) $label; - } + $this->_label = null === $label ? null : (string) $label; return $this; } @@ -539,11 +535,7 @@ protected function _normalizeItem($item, $id) } if (is_object($item)) { - if (method_exists($item, 'toArray')) { - $item = $item->toArray(); - } else { - $item = get_object_vars($item); - } + $item = method_exists($item, 'toArray') ? $item->toArray() : get_object_vars($item); } if ((null === $id) && !array_key_exists($identifier, $item)) { diff --git a/library/Zend/Dojo/Form.php b/library/Zend/Dojo/Form.php index c6da435ba8..6161a17aaa 100644 --- a/library/Zend/Dojo/Form.php +++ b/library/Zend/Dojo/Form.php @@ -79,10 +79,8 @@ public function loadDefaultDecorators() */ public function setView(Zend_View_Interface $view = null) { - if (null !== $view) { - if (false === $view->getPluginLoader('helper')->getPaths('Zend_Dojo_View_Helper')) { - $view->addHelperPath('Zend/Dojo/View/Helper', 'Zend_Dojo_View_Helper'); - } + if (null !== $view && false === $view->getPluginLoader('helper')->getPaths('Zend_Dojo_View_Helper')) { + $view->addHelperPath('Zend/Dojo/View/Helper', 'Zend_Dojo_View_Helper'); } return parent::setView($view); } diff --git a/library/Zend/Dojo/Form/Decorator/DijitContainer.php b/library/Zend/Dojo/Form/Decorator/DijitContainer.php index ea09895761..b3abf1c8fb 100644 --- a/library/Zend/Dojo/Form/Decorator/DijitContainer.php +++ b/library/Zend/Dojo/Form/Decorator/DijitContainer.php @@ -105,11 +105,7 @@ public function getDijitParams() { if (null === $this->_dijitParams) { $attribs = $this->getElement()->getAttribs(); - if (array_key_exists('dijitParams', $attribs)) { - $this->_dijitParams = $attribs['dijitParams']; - } else { - $this->_dijitParams = array(); - } + $this->_dijitParams = array_key_exists('dijitParams', $attribs) ? $attribs['dijitParams'] : array(); $options = $this->getOptions(); if (array_key_exists('dijitParams', $options)) { @@ -135,10 +131,8 @@ public function getTitle() { if (null === $this->_title) { $title = null; - if (null !== ($element = $this->getElement())) { - if (method_exists($element, 'getLegend')) { - $title = $element->getLegend(); - } + if (null !== ($element = $this->getElement()) && method_exists($element, 'getLegend')) { + $title = $element->getLegend(); } if (empty($title) && (null !== ($title = $this->getOption('legend')))) { $this->removeOption('legend'); @@ -170,7 +164,7 @@ public function render($content) { $element = $this->getElement(); $view = $element->getView(); - if (null === $view) { + if (!$view instanceof \Zend_View_Interface) { return $content; } diff --git a/library/Zend/Dojo/Form/Decorator/DijitElement.php b/library/Zend/Dojo/Form/Decorator/DijitElement.php index 3dc00f11e2..7a7f29879b 100644 --- a/library/Zend/Dojo/Form/Decorator/DijitElement.php +++ b/library/Zend/Dojo/Form/Decorator/DijitElement.php @@ -151,7 +151,7 @@ public function render($content) { $element = $this->getElement(); $view = $element->getView(); - if (null === $view) { + if (!$view instanceof \Zend_View_Interface) { require_once 'Zend/Form/Decorator/Exception.php'; throw new Zend_Form_Decorator_Exception('DijitElement decorator cannot render without a registered view object'); } diff --git a/library/Zend/Dojo/Form/Decorator/DijitForm.php b/library/Zend/Dojo/Form/Decorator/DijitForm.php index a78b1b03d7..65749c9b95 100644 --- a/library/Zend/Dojo/Form/Decorator/DijitForm.php +++ b/library/Zend/Dojo/Form/Decorator/DijitForm.php @@ -49,7 +49,7 @@ public function render($content) { $element = $this->getElement(); $view = $element->getView(); - if (null === $view) { + if (!$view instanceof \Zend_View_Interface) { return $content; } diff --git a/library/Zend/Dojo/Form/DisplayGroup.php b/library/Zend/Dojo/Form/DisplayGroup.php index e757ab7249..56b33989a8 100644 --- a/library/Zend/Dojo/Form/DisplayGroup.php +++ b/library/Zend/Dojo/Form/DisplayGroup.php @@ -58,10 +58,8 @@ public function __construct($name, Zend_Loader_PluginLoader $loader, $options = */ public function setView(Zend_View_Interface $view = null) { - if (null !== $view) { - if (false === $view->getPluginLoader('helper')->getPaths('Zend_Dojo_View_Helper')) { - $view->addHelperPath('Zend/Dojo/View/Helper', 'Zend_Dojo_View_Helper'); - } + if (null !== $view && false === $view->getPluginLoader('helper')->getPaths('Zend_Dojo_View_Helper')) { + $view->addHelperPath('Zend/Dojo/View/Helper', 'Zend_Dojo_View_Helper'); } return parent::setView($view); } diff --git a/library/Zend/Dojo/Form/Element/Dijit.php b/library/Zend/Dojo/Form/Element/Dijit.php index ef4596ed52..4e2cfa1c7a 100644 --- a/library/Zend/Dojo/Form/Element/Dijit.php +++ b/library/Zend/Dojo/Form/Element/Dijit.php @@ -179,10 +179,8 @@ public function loadDefaultDecorators() */ public function setView(Zend_View_Interface $view = null) { - if (null !== $view) { - if (false === $view->getPluginLoader('helper')->getPaths('Zend_Dojo_View_Helper')) { - $view->addHelperPath('Zend/Dojo/View/Helper', 'Zend_Dojo_View_Helper'); - } + if (null !== $view && false === $view->getPluginLoader('helper')->getPaths('Zend_Dojo_View_Helper')) { + $view->addHelperPath('Zend/Dojo/View/Helper', 'Zend_Dojo_View_Helper'); } return parent::setView($view); } diff --git a/library/Zend/Dojo/Form/Element/DijitMulti.php b/library/Zend/Dojo/Form/Element/DijitMulti.php index 9cff377bd5..0f7b391d9a 100644 --- a/library/Zend/Dojo/Form/Element/DijitMulti.php +++ b/library/Zend/Dojo/Form/Element/DijitMulti.php @@ -245,15 +245,13 @@ public function registerInArrayValidator() */ public function isValid($value, $context = null) { - if ($this->registerInArrayValidator()) { - if (!$this->getValidator('InArray')) { - $options = $this->getMultiOptions(); - $this->addValidator( - 'InArray', - true, - array(array_keys($options)) - ); - } + if ($this->registerInArrayValidator() && !$this->getValidator('InArray')) { + $options = $this->getMultiOptions(); + $this->addValidator( + 'InArray', + true, + array(array_keys($options)) + ); } return parent::isValid($value, $context); } diff --git a/library/Zend/Dojo/Form/Element/ValidationTextBox.php b/library/Zend/Dojo/Form/Element/ValidationTextBox.php index c196a6d18d..3b4a55b27b 100644 --- a/library/Zend/Dojo/Form/Element/ValidationTextBox.php +++ b/library/Zend/Dojo/Form/Element/ValidationTextBox.php @@ -134,7 +134,9 @@ public function setConstraints(array $constraints) { $tmp = $this->getConstraints(); $constraints = array_merge($tmp, $constraints); - array_walk_recursive($constraints, array($this, '_castBoolToString')); + array_walk_recursive($constraints, function ($item, string $key) : void { + $this->_castBoolToString($item, $key); + }); $this->setDijitParam('constraints', $constraints); return $this; } diff --git a/library/Zend/Dojo/View/Helper/ComboBox.php b/library/Zend/Dojo/View/Helper/ComboBox.php index 749e1ec71d..b56490bd0c 100644 --- a/library/Zend/Dojo/View/Helper/ComboBox.php +++ b/library/Zend/Dojo/View/Helper/ComboBox.php @@ -75,8 +75,7 @@ public function comboBox($id, $value = null, array $params = array(), array $att if (is_string($store)) { $html .= $store; } - $html .= $this->_createFormElement($id, $value, $params, $attribs); - return $html; + return $html . $this->_createFormElement($id, $value, $params, $attribs); } unset($params['store']); } elseif (array_key_exists('store', $params)) { @@ -90,14 +89,11 @@ public function comboBox($id, $value = null, array $params = array(), array $att $storeParams['params'] = $params['storeParams']; unset($params['storeParams']); } - if (false !== ($store = $this->_renderStore($storeParams, $id))) { - if (is_string($store)) { - $html .= $store; - } + if (false !== ($store = $this->_renderStore($storeParams, $id)) && is_string($store)) { + $html .= $store; } } - $html .= $this->_createFormElement($id, $value, $params, $attribs); - return $html; + return $html . $this->_createFormElement($id, $value, $params, $attribs); } // required for correct type casting in declerative mode diff --git a/library/Zend/Dojo/View/Helper/Dijit.php b/library/Zend/Dojo/View/Helper/Dijit.php index c3c108f790..f38cd0c7fd 100644 --- a/library/Zend/Dojo/View/Helper/Dijit.php +++ b/library/Zend/Dojo/View/Helper/Dijit.php @@ -154,11 +154,10 @@ protected function _createLayoutContainer($id, $content, array $params, array $a $attribs = $this->_prepareDijit($attribs, $params, 'layout', $dijit); $nodeType = $this->getRootNode(); - $html = '<' . $nodeType . $this->_htmlAttribs($attribs) . '>' + + return '<' . $nodeType . $this->_htmlAttribs($attribs) . '>' . $content . "\n"; - - return $html; } /** @@ -181,11 +180,9 @@ public function _createFormElement($id, $value, array $params, array $attribs, $ $attribs['type'] = $this->_elementType; $attribs = $this->_prepareDijit($attribs, $params, 'element', $dijit); - - $html = '_htmlAttribs($attribs) . $this->getClosingBracket(); - return $html; } /** @@ -283,7 +280,9 @@ protected function _createDijit($dijit, $id, array $params) { $params['dojoType'] = $dijit; - array_walk_recursive($params, array($this, '_castBoolToString')); + array_walk_recursive($params, function ($item, string $key) : void { + $this->_castBoolToString($item, $key); + }); $this->dojo->setDijit($id, $params); } diff --git a/library/Zend/Dojo/View/Helper/Dojo.php b/library/Zend/Dojo/View/Helper/Dojo.php index ecd4d1c481..ed4efae2a2 100644 --- a/library/Zend/Dojo/View/Helper/Dojo.php +++ b/library/Zend/Dojo/View/Helper/Dojo.php @@ -151,7 +151,7 @@ public static function setUseProgrammatic($style = self::PROGRAMMATIC_SCRIPT) */ public static function useDeclarative() { - return (false === self::$_useProgrammatic); + return (!self::$_useProgrammatic); } /** @@ -161,7 +161,7 @@ public static function useDeclarative() */ public static function useProgrammatic() { - return (false !== self::$_useProgrammatic); + return (self::$_useProgrammatic); } /** diff --git a/library/Zend/Dojo/View/Helper/Dojo/Container.php b/library/Zend/Dojo/View/Helper/Dojo/Container.php index 172bbcd550..c8a54943e2 100644 --- a/library/Zend/Dojo/View/Helper/Dojo/Container.php +++ b/library/Zend/Dojo/View/Helper/Dojo/Container.php @@ -430,7 +430,7 @@ public function getCdnBase() public function setCdnVersion($version = null) { $this->enable(); - if (preg_match('/^[1-9]\.[0-9]{1,2}(\.[0-9]{1,2})?$/', (string) $version)) { + if (preg_match('/^[1-9]\.\d{1,2}(\.\d{1,2})?$/', (string) $version)) { $this->_cdnVersion = $version; } return $this; @@ -508,7 +508,7 @@ public function getLocalPath() */ public function useLocalPath() { - return (null === $this->_localPath) ? false : true; + return null !== $this->_localPath; } /** @@ -960,22 +960,18 @@ public function __toString() $this->_isXhtml = $this->view->doctype()->isXhtml(); - if (Zend_Dojo_View_Helper_Dojo::useDeclarative()) { - if (null === $this->getDjConfigOption('parseOnLoad')) { - $this->setDjConfigOption('parseOnLoad', true); - } + if (Zend_Dojo_View_Helper_Dojo::useDeclarative() && null === $this->getDjConfigOption('parseOnLoad')) { + $this->setDjConfigOption('parseOnLoad', true); } if (!empty($this->_dijits)) { $this->registerDijitLoader(); } - - $html = $this->_renderStylesheets() . PHP_EOL + return $this->_renderStylesheets() . PHP_EOL . $this->_renderDjConfig() . PHP_EOL . $this->_renderDojoScriptTag() . PHP_EOL . $this->_renderLayers() . PHP_EOL . $this->_renderExtras(); - return $html; } /** @@ -1000,12 +996,8 @@ protected function _getLocalRelativePath() */ protected function _renderStylesheets() { - if ($this->useCdn()) { - $base = $this->getCdnBase() - . $this->getCdnVersion(); - } else { - $base = $this->_getLocalRelativePath(); - } + $base = $this->useCdn() ? $this->getCdnBase() + . $this->getCdnVersion() : $this->_getLocalRelativePath(); $registeredStylesheets = $this->getStylesheetModules(); foreach ($registeredStylesheets as $stylesheet) { @@ -1032,10 +1024,9 @@ protected function _renderStylesheets() foreach ($stylesheets as $stylesheet) { $style .= ' @import "' . $stylesheet . '";' . PHP_EOL; } - $style .= (($this->_isXhtml) ? '-->' : '-->') . PHP_EOL - . ''; - return $style; + return $style . ((($this->_isXhtml) ? '-->' : '-->') . PHP_EOL + . ''); } /** @@ -1051,13 +1042,12 @@ protected function _renderDjConfig() } require_once 'Zend/Json.php'; - $scriptTag = ''; - - return $scriptTag; } /** @@ -1078,9 +1068,7 @@ protected function _renderDojoScriptTag() } else { $source = $this->getLocalPath(); } - - $scriptTag = ''; - return $scriptTag; + return ''; } /** @@ -1165,13 +1153,11 @@ protected function _renderExtras() if (preg_match('/^\s*$/s', $content)) { return ''; } - - $html = ''; - return $html; } /** diff --git a/library/Zend/Dojo/View/Helper/Editor.php b/library/Zend/Dojo/View/Helper/Editor.php index c31179bc9e..434ae700ae 100644 --- a/library/Zend/Dojo/View/Helper/Editor.php +++ b/library/Zend/Dojo/View/Helper/Editor.php @@ -98,11 +98,7 @@ public function editor($id, $value = null, $params = array(), $attribs = array() } $hiddenName = $id; - if (array_key_exists('id', $attribs)) { - $hiddenId = $attribs['id']; - } else { - $hiddenId = $hiddenName; - } + $hiddenId = array_key_exists('id', $attribs) ? $attribs['id'] : $hiddenName; $hiddenId = $this->_normalizeId($hiddenId); $textareaName = $this->_normalizeEditorName($hiddenName); diff --git a/library/Zend/Dojo/View/Helper/SimpleTextarea.php b/library/Zend/Dojo/View/Helper/SimpleTextarea.php index 04bbbb7072..53127ae6c8 100644 --- a/library/Zend/Dojo/View/Helper/SimpleTextarea.php +++ b/library/Zend/Dojo/View/Helper/SimpleTextarea.php @@ -68,10 +68,8 @@ public function simpleTextarea($id, $value = null, array $params = array(), arra $attribs = $this->_prepareDijit($attribs, $params, 'textarea'); - $html = '_htmlAttribs($attribs) . '>' + return '_htmlAttribs($attribs) . '>' . $this->view->escape($value) . "\n"; - - return $html; } } diff --git a/library/Zend/Dojo/View/Helper/Textarea.php b/library/Zend/Dojo/View/Helper/Textarea.php index 03e04b8d38..40dfbe57ce 100644 --- a/library/Zend/Dojo/View/Helper/Textarea.php +++ b/library/Zend/Dojo/View/Helper/Textarea.php @@ -70,10 +70,8 @@ public function textarea($id, $value = null, array $params = array(), array $att $attribs = $this->_prepareDijit($attribs, $params, 'textarea'); - $html = '_htmlAttribs($attribs) . '>' + return '_htmlAttribs($attribs) . '>' . $value . "\n"; - - return $html; } } diff --git a/library/Zend/Dom/Query.php b/library/Zend/Dom/Query.php index 3f87cca176..fb8fa0cf06 100644 --- a/library/Zend/Dom/Query.php +++ b/library/Zend/Dom/Query.php @@ -129,11 +129,11 @@ public function setDocument($document, $encoding = null) if ($document instanceof DOMDocument) { return $this->setDocumentDom($document); } - if (0 === strlen($document)) { + if ((string) $document === '') { return $this; } // breaking XML declaration to make syntax highlighting work - if ('<' . '?xml' == substr(trim($document), 0, 5)) { + if (']*xmlns="([^"]+)"[^>]*>/i', $document, $matches)) { $this->_xpathNamespaces[] = $matches[1]; return $this->setDocumentXhtml($document, $encoding); @@ -272,11 +272,7 @@ public function queryXpath($xpathQuery, $query = null) $encoding = $this->getEncoding(); libxml_use_internal_errors(true); - if (null === $encoding) { - $domDoc = new DOMDocument('1.0'); - } else { - $domDoc = new DOMDocument('1.0', $encoding); - } + $domDoc = null === $encoding ? new DOMDocument('1.0') : new DOMDocument('1.0', $encoding); $type = $this->getDocumentType(); switch ($type) { case self::DOC_DOM: @@ -289,9 +285,7 @@ public function queryXpath($xpathQuery, $query = null) $success = ($domDoc !== false); } catch (Zend_Xml_Exception $e) { require_once 'Zend/Dom/Exception.php'; - throw new Zend_Dom_Exception( - $e->getMessage() - ); + throw new Zend_Dom_Exception($e->getMessage(), $e->getCode(), $e); } break; case self::DOC_HTML: diff --git a/library/Zend/Dom/Query/Css2Xpath.php b/library/Zend/Dom/Query/Css2Xpath.php index 5612ad7abf..af0b60f4d9 100644 --- a/library/Zend/Dom/Query/Css2Xpath.php +++ b/library/Zend/Dom/Query/Css2Xpath.php @@ -71,7 +71,7 @@ public static function transform($path) $paths[] = $xpath . $pathSegment; } } else { - foreach ($paths as $key => $xpath) { + foreach (array_keys($paths) as $key) { $paths[$key] .= '//' . $pathSegment; } } diff --git a/library/Zend/Dom/Query/Result.php b/library/Zend/Dom/Query/Result.php index ab5bd0eda6..106407a527 100644 --- a/library/Zend/Dom/Query/Result.php +++ b/library/Zend/Dom/Query/Result.php @@ -133,10 +133,7 @@ public function rewind() */ public function valid() { - if (in_array($this->_position, range(0, $this->_nodeList->length - 1)) && $this->_nodeList->length > 0) { - return true; - } - return false; + return in_array($this->_position, range(0, $this->_nodeList->length - 1)) && $this->_nodeList->length > 0; } /** diff --git a/library/Zend/EventManager/EventManager.php b/library/Zend/EventManager/EventManager.php index 732b7a2618..f927b071a4 100644 --- a/library/Zend/EventManager/EventManager.php +++ b/library/Zend/EventManager/EventManager.php @@ -353,7 +353,7 @@ public function detach($listener) if (!$return) { return false; } - if (!count($this->events[$event])) { + if (count($this->events[$event]) === 0) { unset($this->events[$event]); } return true; @@ -532,7 +532,7 @@ protected function getSharedListeners($event) */ protected function insertListeners($masterListeners, $listeners) { - if (!count($listeners)) { + if (count($listeners) === 0) { return; } diff --git a/library/Zend/EventManager/Filter/FilterIterator.php b/library/Zend/EventManager/Filter/FilterIterator.php index dbbe711873..7be0bbdffc 100644 --- a/library/Zend/EventManager/Filter/FilterIterator.php +++ b/library/Zend/EventManager/Filter/FilterIterator.php @@ -43,12 +43,7 @@ class Zend_EventManager_Filter_FilterIterator extends Zend_Stdlib_SplPriorityQue public function contains($datum) { $chain = clone $this; - foreach ($chain as $item) { - if ($item === $datum) { - return true; - } - } - return false; + return in_array($datum, $chain, true); } /** @@ -106,8 +101,6 @@ public function next($context = null, array $params = array(), $chain = null) if (!$next instanceof Zend_Stdlib_CallbackHandler) { return; } - - $return = call_user_func($next->getCallback(), $context, $params, $chain); - return $return; + return call_user_func($next->getCallback(), $context, $params, $chain); } } diff --git a/library/Zend/EventManager/FilterChain.php b/library/Zend/EventManager/FilterChain.php index 8aa8741e43..00cf467b08 100644 --- a/library/Zend/EventManager/FilterChain.php +++ b/library/Zend/EventManager/FilterChain.php @@ -32,6 +32,7 @@ */ class Zend_EventManager_FilterChain implements Zend_EventManager_Filter { + public $responses; /** * @var Zend_EventManager_Filter_FilterIterator All filters */ diff --git a/library/Zend/EventManager/GlobalEventManager.php b/library/Zend/EventManager/GlobalEventManager.php index 19e5f24d4e..ce7fb825b4 100644 --- a/library/Zend/EventManager/GlobalEventManager.php +++ b/library/Zend/EventManager/GlobalEventManager.php @@ -57,7 +57,7 @@ public static function setEventCollection(Zend_EventManager_EventCollection $eve */ public static function getEventCollection() { - if (null === self::$events) { + if (!self::$events instanceof \Zend_EventManager_EventCollection) { self::setEventCollection(new Zend_EventManager_EventManager()); } return self::$events; diff --git a/library/Zend/EventManager/ResponseCollection.php b/library/Zend/EventManager/ResponseCollection.php index 6ef9d9aa18..adebd39fb5 100644 --- a/library/Zend/EventManager/ResponseCollection.php +++ b/library/Zend/EventManager/ResponseCollection.php @@ -91,7 +91,7 @@ public function bottom() { $this->rewind(); $value = array_pop($this->stack); - array_push($this->stack, $value); + $this->stack[] = $value; return $value; } @@ -253,7 +253,7 @@ public function prev() */ public function push($value) { - array_push($this->data, $value); + $this->data[] = $value; $this->count++; $this->stack = false; } @@ -341,8 +341,7 @@ public function unshift($value) public function valid() { $key = key($this->stack); - $var = ($key !== null && $key !== false); - return $var; + return $key !== null && $key !== false; } } } @@ -414,11 +413,6 @@ public function last() */ public function contains($value) { - foreach ($this as $response) { - if ($response === $value) { - return true; - } - } - return false; + return in_array($value, $this, true); } } diff --git a/library/Zend/Exception.php b/library/Zend/Exception.php index d97acb0f92..b233743502 100644 --- a/library/Zend/Exception.php +++ b/library/Zend/Exception.php @@ -74,12 +74,10 @@ public function __call($method, array $args) */ public function __toString() { - if (version_compare(PHP_VERSION, '5.3.0', '<')) { - if (null !== ($e = $this->getPrevious())) { - return $e->__toString() - . "\n\nNext " - . parent::__toString(); - } + if (version_compare(PHP_VERSION, '5.3.0', '<') && null !== ($e = $this->getPrevious())) { + return $e->__toString() + . "\n\nNext " + . parent::__toString(); } return parent::__toString(); } diff --git a/library/Zend/Feed.php b/library/Zend/Feed.php index edc61f9c0c..101030bba4 100644 --- a/library/Zend/Feed.php +++ b/library/Zend/Feed.php @@ -194,8 +194,7 @@ public static function importString($string) { if (trim($string) == '') { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('Document/string being imported' - . ' is an Empty string or comes from an empty HTTP response'); + throw new Zend_Feed_Exception('Document/string being imported is an Empty string or comes from an empty HTTP response'); } $doc = new DOMDocument; $doc = Zend_Xml_Security::scan($string, $doc); @@ -230,7 +229,7 @@ public static function importString($string) } // Try to find the base feed element of an RSS feed - if ($doc->getElementsByTagName('channel')->item(0)) { + if ($doc->getElementsByTagName('channel')->item(0) !== null) { /** * @see Zend_Feed_Rss */ diff --git a/library/Zend/Feed/Abstract.php b/library/Zend/Feed/Abstract.php index 287a65b793..18a580d778 100644 --- a/library/Zend/Feed/Abstract.php +++ b/library/Zend/Feed/Abstract.php @@ -272,8 +272,7 @@ protected function _importFeedFromString($feed) { if (trim($feed) == '') { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('Remote feed being imported' - . ' is an Empty string or comes from an empty HTTP response'); + throw new Zend_Feed_Exception('Remote feed being imported is an Empty string or comes from an empty HTTP response'); } $doc = new DOMDocument; $doc = Zend_Xml_Security::scan($feed, $doc); diff --git a/library/Zend/Feed/Atom.php b/library/Zend/Feed/Atom.php index 2ee08cef6a..975ea42df3 100644 --- a/library/Zend/Feed/Atom.php +++ b/library/Zend/Feed/Atom.php @@ -85,10 +85,10 @@ public function __wakeup() // Find the base feed element and create an alias to it. $element = $this->_element->getElementsByTagName('feed')->item(0); - if (!$element) { + if (!$element instanceof \DOMElement) { // Try to find a single instead. $element = $this->_element->getElementsByTagName($this->_entryElementName)->item(0); - if (!$element) { + if (!$element instanceof \DOMElement) { /** * @see Zend_Feed_Exception */ @@ -198,22 +198,22 @@ protected function _mapFeedHeaders($array) $title->appendChild($this->_element->createCDATASection($array->title)); $feed->appendChild($title); - if (isset($array->author)) { + if (property_exists($array, 'author') && $array->author !== null) { $author = $this->_element->createElement('author'); $name = $this->_element->createElement('name', $array->author); $author->appendChild($name); - if (isset($array->email)) { + if (property_exists($array, 'email') && $array->email !== null) { $email = $this->_element->createElement('email', $array->email); $author->appendChild($email); } $feed->appendChild($author); } - $updated = isset($array->lastUpdate) ? $array->lastUpdate : time(); + $updated = property_exists($array, 'lastUpdate') && $array->lastUpdate !== null ? $array->lastUpdate : time(); $updated = $this->_element->createElement('updated', date(DATE_ATOM, $updated)); $feed->appendChild($updated); - if (isset($array->published)) { + if (property_exists($array, 'published') && $array->published !== null) { $published = $this->_element->createElement('published', date(DATE_ATOM, $array->published)); $feed->appendChild($published); } @@ -221,28 +221,28 @@ protected function _mapFeedHeaders($array) $link = $this->_element->createElement('link'); $link->setAttribute('rel', 'self'); $link->setAttribute('href', $array->link); - if (isset($array->language)) { + if (property_exists($array, 'language') && $array->language !== null) { $link->setAttribute('hreflang', $array->language); } $feed->appendChild($link); - if (isset($array->description)) { + if (property_exists($array, 'description') && $array->description !== null) { $subtitle = $this->_element->createElement('subtitle'); $subtitle->appendChild($this->_element->createCDATASection($array->description)); $feed->appendChild($subtitle); } - if (isset($array->copyright)) { + if (property_exists($array, 'copyright') && $array->copyright !== null) { $copyright = $this->_element->createElement('rights', $array->copyright); $feed->appendChild($copyright); } - if (isset($array->image)) { + if (property_exists($array, 'image') && $array->image !== null) { $image = $this->_element->createElement('logo', $array->image); $feed->appendChild($image); } - $generator = !empty($array->generator) ? $array->generator : 'Zend_Feed'; + $generator = empty($array->generator) ? 'Zend_Feed' : $array->generator; $generator = $this->_element->createElement('generator', $generator); $feed->appendChild($generator); @@ -271,14 +271,14 @@ protected function _mapFeedEntries(DOMElement $root, $array) foreach ($array as $dataentry) { $entry = $this->_element->createElement('entry'); - $id = $this->_element->createElement('id', isset($dataentry->guid) ? $dataentry->guid : $dataentry->link); + $id = $this->_element->createElement('id', property_exists($dataentry, 'guid') && $dataentry->guid !== null ? $dataentry->guid : $dataentry->link); $entry->appendChild($id); $title = $this->_element->createElement('title'); $title->appendChild($this->_element->createCDATASection($dataentry->title)); $entry->appendChild($title); - $updated = isset($dataentry->lastUpdate) ? $dataentry->lastUpdate : time(); + $updated = property_exists($dataentry, 'lastUpdate') && $dataentry->lastUpdate !== null ? $dataentry->lastUpdate : time(); $updated = $this->_element->createElement('updated', date(DATE_ATOM, $updated)); $entry->appendChild($updated); @@ -291,14 +291,14 @@ protected function _mapFeedEntries(DOMElement $root, $array) $summary->appendChild($this->_element->createCDATASection($dataentry->description)); $entry->appendChild($summary); - if (isset($dataentry->content)) { + if (property_exists($dataentry, 'content') && $dataentry->content !== null) { $content = $this->_element->createElement('content'); $content->setAttribute('type', 'html'); $content->appendChild($this->_element->createCDATASection($dataentry->content)); $entry->appendChild($content); } - if (isset($dataentry->category)) { + if (property_exists($dataentry, 'category') && $dataentry->category !== null) { foreach ($dataentry->category as $category) { $node = $this->_element->createElement('category'); $node->setAttribute('term', $category['term']); @@ -309,7 +309,7 @@ protected function _mapFeedEntries(DOMElement $root, $array) } } - if (isset($dataentry->source)) { + if (property_exists($dataentry, 'source') && $dataentry->source !== null) { $source = $this->_element->createElement('source'); $title = $this->_element->createElement('title', $dataentry->source['title']); $source->appendChild($title); @@ -319,7 +319,7 @@ protected function _mapFeedEntries(DOMElement $root, $array) $source->appendChild($link); } - if (isset($dataentry->enclosure)) { + if (property_exists($dataentry, 'enclosure') && $dataentry->enclosure !== null) { foreach ($dataentry->enclosure as $enclosure) { $node = $this->_element->createElement('link'); $node->setAttribute('rel', 'enclosure'); @@ -334,13 +334,13 @@ protected function _mapFeedEntries(DOMElement $root, $array) } } - if (isset($dataentry->comments)) { + if (property_exists($dataentry, 'comments') && $dataentry->comments !== null) { $comments = $this->_element->createElementNS('http://wellformedweb.org/CommentAPI/', 'wfw:comment', $dataentry->comments); $entry->appendChild($comments); } - if (isset($dataentry->commentRss)) { + if (property_exists($dataentry, 'commentRss') && $dataentry->commentRss !== null) { $comments = $this->_element->createElementNS('http://wellformedweb.org/CommentAPI/', 'wfw:commentRss', $dataentry->commentRss); diff --git a/library/Zend/Feed/Builder/Entry.php b/library/Zend/Feed/Builder/Entry.php index d911cf6658..195ad2d981 100644 --- a/library/Zend/Feed/Builder/Entry.php +++ b/library/Zend/Feed/Builder/Entry.php @@ -283,11 +283,7 @@ public function setEnclosures(array $enclosures) */ public function addEnclosure($url, $type = '', $length = '') { - if (!$this->offsetExists('enclosure')) { - $enclosure = array(); - } else { - $enclosure = $this->offsetGet('enclosure'); - } + $enclosure = $this->offsetExists('enclosure') ? $this->offsetGet('enclosure') : array(); $enclosure[] = array('url' => $url, 'type' => $type, 'length' => $length); diff --git a/library/Zend/Feed/Builder/Header.php b/library/Zend/Feed/Builder/Header.php index 7ff4d9b9ba..fd78147973 100644 --- a/library/Zend/Feed/Builder/Header.php +++ b/library/Zend/Feed/Builder/Header.php @@ -320,7 +320,7 @@ public function setCloud($uri, $procedure, $protocol) require_once 'Zend/Feed/Builder/Exception.php'; throw new Zend_Feed_Builder_Exception('Passed parameter is not a valid HTTP URI'); } - if (!$uri->getPort()) { + if ($uri->getPort() === '' || $uri->getPort() === '0') { $uri->setPort(80); } $this->offsetSet('cloud', array('uri' => $uri, diff --git a/library/Zend/Feed/Element.php b/library/Zend/Feed/Element.php index 6e8ffde88b..09fd2e6ba7 100644 --- a/library/Zend/Feed/Element.php +++ b/library/Zend/Feed/Element.php @@ -227,7 +227,7 @@ public function __set($var, $val) $this->ensureAppended(); $nodes = $this->_children($var); - if (!$nodes) { + if ($nodes === []) { if (strpos($var, ':') !== false) { list($ns, $elt) = explode(':', $var, 2); $node = $this->_element->ownerDocument->createElementNS(Zend_Feed::lookupNamespace($ns), @@ -293,7 +293,7 @@ public function __call($var, $unused) { $nodes = $this->_children($var); - if (!$nodes) { + if ($nodes === []) { return null; } elseif (count($nodes) > 1) { return $nodes; diff --git a/library/Zend/Feed/Entry/Abstract.php b/library/Zend/Feed/Entry/Abstract.php index 4601805c0e..2422bbfb4d 100644 --- a/library/Zend/Feed/Entry/Abstract.php +++ b/library/Zend/Feed/Entry/Abstract.php @@ -103,7 +103,7 @@ public function __construct($uri = null, $element = null) } $element = $doc->getElementsByTagName($this->_rootElement)->item(0); - if (!$element) { + if (!$element instanceof \DOMElement) { /** * @see Zend_Feed_Exception */ diff --git a/library/Zend/Feed/Entry/Atom.php b/library/Zend/Feed/Entry/Atom.php index 3c3a0a8469..8e07aa917a 100644 --- a/library/Zend/Feed/Entry/Atom.php +++ b/library/Zend/Feed/Entry/Atom.php @@ -217,7 +217,7 @@ public function save($postUri = null) } $newEntry = $newEntry->getElementsByTagName($this->_rootElement)->item(0); - if (!$newEntry) { + if (!$newEntry instanceof \DOMElement) { /** * @see Zend_Feed_Exception */ @@ -226,7 +226,7 @@ public function save($postUri = null) . "\n\n" . $client->responseBody); } - if ($this->_element->parentNode) { + if ($this->_element->parentNode !== null) { $oldElement = $this->_element; $this->_element = $oldElement->ownerDocument->importNode($newEntry, true); $oldElement->parentNode->replaceChild($this->_element, $oldElement); diff --git a/library/Zend/Feed/Pubsubhubbub.php b/library/Zend/Feed/Pubsubhubbub.php index 6485630ef0..a6f7316bb9 100644 --- a/library/Zend/Feed/Pubsubhubbub.php +++ b/library/Zend/Feed/Pubsubhubbub.php @@ -147,7 +147,6 @@ public static function clearHttpClient() public static function urlencode($string) { $rawencoded = rawurlencode($string); - $rfcencoded = str_replace('%7E', '~', $rawencoded); - return $rfcencoded; + return str_replace('%7E', '~', $rawencoded); } } diff --git a/library/Zend/Feed/Pubsubhubbub/CallbackAbstract.php b/library/Zend/Feed/Pubsubhubbub/CallbackAbstract.php index 0dc7262f0d..87fc296302 100644 --- a/library/Zend/Feed/Pubsubhubbub/CallbackAbstract.php +++ b/library/Zend/Feed/Pubsubhubbub/CallbackAbstract.php @@ -140,8 +140,7 @@ public function getStorage() { if ($this->_storage === null) { require_once 'Zend/Feed/Pubsubhubbub/Exception.php'; - throw new Zend_Feed_Pubsubhubbub_Exception('No storage object has been' - . ' set that subclasses Zend_Feed_Pubsubhubbub_Model_SubscriptionInterface'); + throw new Zend_Feed_Pubsubhubbub_Exception('No storage object has been set that subclasses Zend_Feed_Pubsubhubbub_Model_SubscriptionInterface'); } return $this->_storage; } @@ -196,11 +195,10 @@ public function getHttpResponse() */ public function setSubscriberCount($count) { - $count = intval($count); + $count = (int) $count; if ($count <= 0) { require_once 'Zend/Feed/Pubsubhubbub/Exception.php'; - throw new Zend_Feed_Pubsubhubbub_Exception('Subscriber count must be' - . ' greater than zero'); + throw new Zend_Feed_Pubsubhubbub_Exception('Subscriber count must be greater than zero'); } $this->_subscriberCount = $count; return $this; diff --git a/library/Zend/Feed/Pubsubhubbub/HttpResponse.php b/library/Zend/Feed/Pubsubhubbub/HttpResponse.php index 10c8dbd354..3b940fa82e 100644 --- a/library/Zend/Feed/Pubsubhubbub/HttpResponse.php +++ b/library/Zend/Feed/Pubsubhubbub/HttpResponse.php @@ -76,7 +76,7 @@ public function sendHeaders() { if (count($this->_headers) || (200 != $this->_httpResponseCode)) { $this->canSendHeaders(true); - } elseif (200 == $this->_httpResponseCode) { + } elseif (200 === $this->_httpResponseCode) { return; } $httpCodeSent = false; @@ -229,7 +229,6 @@ protected function _normalizeHeader($name) { $filtered = str_replace(array('-', '_'), ' ', (string) $name); $filtered = ucwords(strtolower($filtered)); - $filtered = str_replace(' ', '-', $filtered); - return $filtered; + return str_replace(' ', '-', $filtered); } } diff --git a/library/Zend/Feed/Pubsubhubbub/Model/Subscription.php b/library/Zend/Feed/Pubsubhubbub/Model/Subscription.php index 74c59798d5..f09dc9ce28 100644 --- a/library/Zend/Feed/Pubsubhubbub/Model/Subscription.php +++ b/library/Zend/Feed/Pubsubhubbub/Model/Subscription.php @@ -58,7 +58,7 @@ public function setSubscription(array $data) ); } $result = $this->_db->find($data['id']); - if (count($result)) { + if (count($result) > 0) { $data['created_time'] = $result->current()->created_time; $now = new Zend_Date; if (isset($data['lease_seconds'])) { @@ -92,7 +92,7 @@ public function getSubscription($key) .' of "' . $key . '" must be a non-empty string'); } $result = $this->_db->find($key); - if (count($result)) { + if (count($result) > 0) { return $result->current()->toArray(); } return false; @@ -114,10 +114,7 @@ public function hasSubscription($key) .' of "' . $key . '" must be a non-empty string'); } $result = $this->_db->find($key); - if (count($result)) { - return true; - } - return false; + return (bool) count($result); } /** @@ -129,7 +126,7 @@ public function hasSubscription($key) public function deleteSubscription($key) { $result = $this->_db->find($key); - if (count($result)) { + if (count($result) > 0) { $this->_db->delete( $this->_db->getAdapter()->quoteInto('id = ?', $key) ); diff --git a/library/Zend/Feed/Pubsubhubbub/Publisher.php b/library/Zend/Feed/Pubsubhubbub/Publisher.php index 89378bdd5e..ca20b49f93 100644 --- a/library/Zend/Feed/Pubsubhubbub/Publisher.php +++ b/library/Zend/Feed/Pubsubhubbub/Publisher.php @@ -271,8 +271,7 @@ public function notifyAll() $hubs = $this->getHubUrls(); if (empty($hubs)) { require_once 'Zend/Feed/Pubsubhubbub/Exception.php'; - throw new Zend_Feed_Pubsubhubbub_Exception('No Hub Server URLs' - . ' have been set so no notifcations can be sent'); + throw new Zend_Feed_Pubsubhubbub_Exception('No Hub Server URLs have been set so no notifcations can be sent'); } $this->_errors = array(); foreach ($hubs as $url) { @@ -371,10 +370,7 @@ public function getParameters() */ public function isSuccess() { - if (count($this->_errors) > 0) { - return false; - } - return true; + return !($this->_errors !== []); } /** @@ -408,8 +404,7 @@ protected function _getHttpClient() $topics = $this->getUpdatedTopicUrls(); if (empty($topics)) { require_once 'Zend/Feed/Pubsubhubbub/Exception.php'; - throw new Zend_Feed_Pubsubhubbub_Exception('No updated topic URLs' - . ' have been set'); + throw new Zend_Feed_Pubsubhubbub_Exception('No updated topic URLs have been set'); } foreach ($topics as $topicUrl) { $params[] = 'hub.url=' . urlencode($topicUrl); diff --git a/library/Zend/Feed/Pubsubhubbub/Subscriber.php b/library/Zend/Feed/Pubsubhubbub/Subscriber.php index da1f688831..1c06fcc950 100644 --- a/library/Zend/Feed/Pubsubhubbub/Subscriber.php +++ b/library/Zend/Feed/Pubsubhubbub/Subscriber.php @@ -234,8 +234,7 @@ public function getTopicUrl() { if (empty($this->_topicUrl)) { require_once 'Zend/Feed/Pubsubhubbub/Exception.php'; - throw new Zend_Feed_Pubsubhubbub_Exception('A valid Topic (RSS or Atom' - . ' feed) URL MUST be set before attempting any operation'); + throw new Zend_Feed_Pubsubhubbub_Exception('A valid Topic (RSS or Atom feed) URL MUST be set before attempting any operation'); } return $this->_topicUrl; } @@ -249,11 +248,10 @@ public function getTopicUrl() */ public function setLeaseSeconds($seconds) { - $seconds = intval($seconds); + $seconds = (int) $seconds; if ($seconds <= 0) { require_once 'Zend/Feed/Pubsubhubbub/Exception.php'; - throw new Zend_Feed_Pubsubhubbub_Exception('Expected lease seconds' - . ' must be an integer greater than zero'); + throw new Zend_Feed_Pubsubhubbub_Exception('Expected lease seconds must be an integer greater than zero'); } $this->_leaseSeconds = $seconds; return $this; @@ -300,8 +298,7 @@ public function getCallbackUrl() { if (empty($this->_callbackUrl)) { require_once 'Zend/Feed/Pubsubhubbub/Exception.php'; - throw new Zend_Feed_Pubsubhubbub_Exception('A valid Callback URL MUST be' - . ' set before attempting any operation'); + throw new Zend_Feed_Pubsubhubbub_Exception('A valid Callback URL MUST be set before attempting any operation'); } return $this->_callbackUrl; } @@ -560,8 +557,7 @@ public function getStorage() { if ($this->_storage === null) { require_once 'Zend/Feed/Pubsubhubbub/Exception.php'; - throw new Zend_Feed_Pubsubhubbub_Exception('No storage vehicle ' - . 'has been set.'); + throw new Zend_Feed_Pubsubhubbub_Exception('No storage vehicle has been set.'); } return $this->_storage; } @@ -592,10 +588,7 @@ public function unsubscribeAll() */ public function isSuccess() { - if (count($this->_errors) > 0) { - return false; - } - return true; + return !($this->_errors !== []); } /** @@ -636,8 +629,7 @@ protected function _doRequest($mode) $hubs = $this->getHubUrls(); if (empty($hubs)) { require_once 'Zend/Feed/Pubsubhubbub/Exception.php'; - throw new Zend_Feed_Pubsubhubbub_Exception('No Hub Server URLs' - . ' have been set so no subscriptions can be attempted'); + throw new Zend_Feed_Pubsubhubbub_Exception('No Hub Server URLs have been set so no subscriptions can be attempted'); } $this->_errors = array(); $this->_asyncHubs = array(); @@ -725,9 +717,7 @@ protected function _getRequestParameters($hubUrl, $mode) ); } $params['hub.verify'] = array(); - foreach($vmodes as $vmode) { - $params['hub.verify'][] = $vmode; - } + $params['hub.verify'] = $vmodes; /** * Establish a persistent verify_token and attach key to callback @@ -738,7 +728,7 @@ protected function _getRequestParameters($hubUrl, $mode) $params['hub.verify_token'] = $token; // Note: query string only usable with PuSH 0.2 Hubs - if (!$this->_usePathParameter) { + if ($this->_usePathParameter === '' || $this->_usePathParameter === '0') { $params['hub.callback'] = $this->getCallbackUrl() . '?xhub.subscription=' . Zend_Feed_Pubsubhubbub::urlencode($key); } else { @@ -806,8 +796,7 @@ protected function _generateVerifyToken() protected function _generateSubscriptionKey(array $params, $hubUrl) { $keyBase = $params['hub.topic'] . $hubUrl; - $key = md5($keyBase); - return $key; + return md5($keyBase); } /** diff --git a/library/Zend/Feed/Pubsubhubbub/Subscriber/Callback.php b/library/Zend/Feed/Pubsubhubbub/Subscriber/Callback.php index d08d41cdf5..597ffcbdad 100644 --- a/library/Zend/Feed/Pubsubhubbub/Subscriber/Callback.php +++ b/library/Zend/Feed/Pubsubhubbub/Subscriber/Callback.php @@ -178,15 +178,11 @@ public function isValidHubVerification(array $httpGetData) if (!Zend_Uri::check($httpGetData['hub_topic'])) { return false; } - /** * Attempt to retrieve any Verification Token Key attached to Callback * URL's path by our Subscriber implementation */ - if (!$this->_hasValidVerifyToken($httpGetData)) { - return false; - } - return true; + return $this->_hasValidVerifyToken($httpGetData); } /** @@ -209,10 +205,7 @@ public function setFeedUpdate($feed) */ public function hasFeedUpdate() { - if ($this->_feedUpdate === null) { - return false; - } - return true; + return $this->_feedUpdate !== null; } /** @@ -269,7 +262,7 @@ protected function _detectVerifyTokenKey(array $httpGetData = null) /** * Available when sub keys encoding in Callback URL path */ - if (isset($this->_subscriptionKey)) { + if ($this->_subscriptionKey !== null) { return $this->_subscriptionKey; } diff --git a/library/Zend/Feed/Reader.php b/library/Zend/Feed/Reader.php index 79613dc1d3..2bfd3f2155 100644 --- a/library/Zend/Feed/Reader.php +++ b/library/Zend/Feed/Reader.php @@ -344,9 +344,7 @@ public static function importString($string) $dom = Zend_Xml_Security::scan($string, $dom); } catch (Zend_Xml_Exception $e) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception( - $e->getMessage() - ); + throw new Zend_Feed_Exception($e->getMessage(), $e->getCode(), $e); } if (!$dom) { // Build error message @@ -373,8 +371,7 @@ public static function importString($string) $reader = new Zend_Feed_Reader_Feed_Atom($dom, $type); } else { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('The URI used does not point to a ' - . 'valid Atom, RSS or RDF feed that Zend_Feed_Reader can parse.'); + throw new Zend_Feed_Exception('The URI used does not point to a valid Atom, RSS or RDF feed that Zend_Feed_Reader can parse.'); } return $reader; } @@ -416,10 +413,8 @@ public static function findFeedLinks($uri) } $responseHtml = $response->getBody(); $libxml_errflag = libxml_use_internal_errors(true); - $oldValue = libxml_disable_entity_loader(true); $dom = new DOMDocument; $status = $dom->loadHTML($responseHtml); - libxml_disable_entity_loader($oldValue); libxml_use_internal_errors($libxml_errflag); if (!$status) { // Build error message @@ -461,9 +456,7 @@ public static function detectType($feed, $specOnly = false) $dom = Zend_Xml_Security::scan($feed, $dom); } catch (Zend_Xml_Exception $e) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception( - $e->getMessage() - ); + throw new Zend_Feed_Exception($e->getMessage(), $e->getCode(), $e); } //libxml_disable_entity_loader($oldValue); @ini_restore('track_errors'); @@ -485,7 +478,7 @@ public static function detectType($feed, $specOnly = false) } $xpath = new DOMXPath($dom); - if ($xpath->query('/rss')->length) { + if ($xpath->query('/rss')->length !== 0) { $type = self::TYPE_RSS_ANY; $version = $xpath->evaluate('string(/rss/@version)'); @@ -518,7 +511,7 @@ public static function detectType($feed, $specOnly = false) $xpath->registerNamespace('rdf', self::NAMESPACE_RDF); - if ($xpath->query('/rdf:RDF')->length) { + if ($xpath->query('/rdf:RDF')->length !== 0) { $xpath->registerNamespace('rss', self::NAMESPACE_RSS_10); if ($xpath->query('/rdf:RDF/rss:channel')->length @@ -543,11 +536,11 @@ public static function detectType($feed, $specOnly = false) $type = self::TYPE_ATOM_ANY; $xpath->registerNamespace('atom', self::NAMESPACE_ATOM_10); - if ($xpath->query('//atom:feed')->length) { + if ($xpath->query('//atom:feed')->length !== 0) { return self::TYPE_ATOM_10; } - if ($xpath->query('//atom:entry')->length) { + if ($xpath->query('//atom:entry')->length !== 0) { if ($specOnly == true) { return self::TYPE_ATOM_10; } else { @@ -557,7 +550,7 @@ public static function detectType($feed, $specOnly = false) $xpath->registerNamespace('atom', self::NAMESPACE_ATOM_03); - if ($xpath->query('//atom:feed')->length) { + if ($xpath->query('//atom:feed')->length !== 0) { return self::TYPE_ATOM_03; } @@ -633,11 +626,9 @@ public static function registerExtension($name) { $feedName = $name . '_Feed'; $entryName = $name . '_Entry'; - if (self::isRegistered($name)) { - if (self::getPluginLoader()->isLoaded($feedName) || - self::getPluginLoader()->isLoaded($entryName)) { - return; - } + if (self::isRegistered($name) && (self::getPluginLoader()->isLoaded($feedName) || + self::getPluginLoader()->isLoaded($entryName))) { + return; } try { self::getPluginLoader()->load($feedName); @@ -668,12 +659,8 @@ public static function isRegistered($extensionName) { $feedName = $extensionName . '_Feed'; $entryName = $extensionName . '_Entry'; - if (in_array($feedName, self::$_extensions['feed']) - || in_array($entryName, self::$_extensions['entry']) - ) { - return true; - } - return false; + return in_array($feedName, self::$_extensions['feed']) + || in_array($entryName, self::$_extensions['entry']); } /** diff --git a/library/Zend/Feed/Reader/Collection/Category.php b/library/Zend/Feed/Reader/Collection/Category.php index 2ee9b3d512..e78f4b8b2a 100644 --- a/library/Zend/Feed/Reader/Collection/Category.php +++ b/library/Zend/Feed/Reader/Collection/Category.php @@ -45,11 +45,7 @@ class Zend_Feed_Reader_Collection_Category public function getValues() { $categories = array(); foreach ($this->getIterator() as $element) { - if (isset($element['label']) && !empty($element['label'])) { - $categories[] = $element['label']; - } else { - $categories[] = $element['term']; - } + $categories[] = isset($element['label']) && !empty($element['label']) ? $element['label'] : $element['term']; } return array_unique($categories); } diff --git a/library/Zend/Feed/Reader/Entry/Rss.php b/library/Zend/Feed/Reader/Entry/Rss.php index 52eaa3d206..ac284cf81d 100644 --- a/library/Zend/Feed/Reader/Entry/Rss.php +++ b/library/Zend/Feed/Reader/Entry/Rss.php @@ -176,7 +176,7 @@ public function getAuthors() } else { $list = $this->_xpath->query($this->_xpathQueryRdf . '//rss:author'); } - if ($list->length) { + if ($list->length !== 0) { foreach ($list as $author) { $string = trim($author->nodeValue); $email = null; @@ -292,7 +292,7 @@ public function getDateModified() } } - if (!$date) { + if ($date === null) { $date = $this->getExtension('DublinCore')->getDate(); } @@ -370,7 +370,7 @@ public function getEnclosure() } } - if (!$enclosure) { + if ($enclosure === null) { $enclosure = $this->getExtension('Atom')->getEnclosure(); } @@ -407,9 +407,9 @@ public function getId() } if (!$id) { - if ($this->getPermalink()) { + if ($this->getPermalink() !== '' && $this->getPermalink() !== '0') { $id = $this->getPermalink(); - } elseif ($this->getTitle()) { + } elseif ($this->getTitle() !== '' && $this->getTitle() !== '0') { $id = $this->getTitle(); } else { $id = null; @@ -460,7 +460,7 @@ public function getLinks() $list = $this->_xpath->query($this->_xpathQueryRdf.'//rss:link'); } - if (!$list->length) { + if ($list->length === 0) { $links = $this->getExtension('Atom')->getLinks(); } else { foreach ($list as $link) { @@ -491,7 +491,7 @@ public function getCategories() $list = $this->_xpath->query($this->_xpathQueryRdf.'//rss:category'); } - if ($list->length) { + if ($list->length !== 0) { $categoryCollection = new Zend_Feed_Reader_Collection_Category; foreach ($list as $category) { $categoryCollection[] = array( diff --git a/library/Zend/Feed/Reader/EntryAbstract.php b/library/Zend/Feed/Reader/EntryAbstract.php index a55e0953ef..05e9c83361 100644 --- a/library/Zend/Feed/Reader/EntryAbstract.php +++ b/library/Zend/Feed/Reader/EntryAbstract.php @@ -82,13 +82,9 @@ public function __construct(DOMElement $entry, $entryKey, $type = null) $this->_entry = $entry; $this->_entryKey = $entryKey; $this->_domDocument = $entry->ownerDocument; - if ($type !== null) { - $this->_data['type'] = $type; - } else { - $this->_data['type'] = Zend_Feed_Reader::detectType( - $this->_domDocument - ); - } + $this->_data['type'] = $type !== null ? $type : Zend_Feed_Reader::detectType( + $this->_domDocument + ); $this->_loadExtensions(); } diff --git a/library/Zend/Feed/Reader/Extension/Atom/Entry.php b/library/Zend/Feed/Reader/Extension/Atom/Entry.php index abe26c8510..a57079c07e 100644 --- a/library/Zend/Feed/Reader/Extension/Atom/Entry.php +++ b/library/Zend/Feed/Reader/Extension/Atom/Entry.php @@ -89,14 +89,14 @@ public function getAuthors() $authors = array(); $list = $this->getXpath()->query($this->getXpathPrefix() . '//atom:author'); - if (!$list->length) { + if ($list->length === 0) { /** * TODO: Limit query to feed level els only! */ $list = $this->getXpath()->query('//atom:author'); } - if ($list->length) { + if ($list->length !== 0) { foreach ($list as $author) { $author = $this->_getAuthor($author); if (!empty($author)) { @@ -173,7 +173,7 @@ public function getContent() */ protected function _collectXhtml($xhtml, $prefix) { - if (!empty($prefix)) $prefix = $prefix . ':'; + if (!empty($prefix)) $prefix .= ':'; $matches = array( "/<\?xml[^<]*>[^<]*<" . $prefix . "div[^<]*/", "/<\/" . $prefix . "div>\s*$/" @@ -306,9 +306,9 @@ public function getId() $id = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/atom:id)'); if (!$id) { - if ($this->getPermalink()) { + if ($this->getPermalink() !== '' && $this->getPermalink() !== '0') { $id = $this->getPermalink(); - } elseif ($this->getTitle()) { + } elseif ($this->getTitle() !== '' && $this->getTitle() !== '0') { $id = $this->getTitle(); } else { $id = null; @@ -385,7 +385,7 @@ public function getLinks() $this->getXpathPrefix() . '//atom:link[not(@rel)]/@href' ); - if ($list->length) { + if ($list->length !== 0) { foreach ($list as $link) { $links[] = $this->_absolutiseUri($link->value); } @@ -446,7 +446,7 @@ public function getCommentCount() $this->getXpathPrefix() . '//atom:link[@rel="replies"]/@thread10:count' ); - if ($list->length) { + if ($list->length !== 0) { $count = $list->item(0)->value; } @@ -472,7 +472,7 @@ public function getCommentLink() $this->getXpathPrefix() . '//atom:link[@rel="replies" and @type="text/html"]/@href' ); - if ($list->length) { + if ($list->length !== 0) { $link = $list->item(0)->value; $link = $this->_absolutiseUri($link); } @@ -499,7 +499,7 @@ public function getCommentFeedLink($type = 'atom') $this->getXpathPrefix() . '//atom:link[@rel="replies" and @type="application/'.$type.'+xml"]/@href' ); - if ($list->length) { + if ($list->length !== 0) { $link = $list->item(0)->value; $link = $this->_absolutiseUri($link); } @@ -532,7 +532,7 @@ public function getCategories() $list = $this->getXpath()->query($this->getXpathPrefix() . '//atom10:category'); } - if ($list->length) { + if ($list->length !== 0) { $categoryCollection = new Zend_Feed_Reader_Collection_Category; foreach ($list as $category) { $categoryCollection[] = array( @@ -565,7 +565,7 @@ public function getSource() // TODO: Investigate why _getAtomType() fails here. Is it even needed? if ($this->getType() == Zend_Feed_Reader::TYPE_ATOM_10) { $list = $this->getXpath()->query($this->getXpathPrefix() . '/atom:source[1]'); - if ($list->length) { + if ($list->length !== 0) { $element = $list->item(0); $source = new Zend_Feed_Reader_Feed_Atom_Source($element, $this->getXpathPrefix()); } @@ -581,12 +581,10 @@ public function getSource() */ protected function _absolutiseUri($link) { - if (!Zend_Uri::check($link)) { - if ($this->getBaseUrl() !== null) { - $link = $this->getBaseUrl() . $link; - if (!Zend_Uri::check($link)) { - $link = null; - } + if (!Zend_Uri::check($link) && $this->getBaseUrl() !== null) { + $link = $this->getBaseUrl() . $link; + if (!Zend_Uri::check($link)) { + $link = null; } } return $link; diff --git a/library/Zend/Feed/Reader/Extension/Atom/Feed.php b/library/Zend/Feed/Reader/Extension/Atom/Feed.php index 535c9fc1b5..912cb0ea84 100644 --- a/library/Zend/Feed/Reader/Extension/Atom/Feed.php +++ b/library/Zend/Feed/Reader/Extension/Atom/Feed.php @@ -80,7 +80,7 @@ public function getAuthors() $authors = array(); - if ($list->length) { + if ($list->length !== 0) { foreach ($list as $author) { $author = $this->_getAuthor($author); if (!empty($author)) { @@ -305,11 +305,7 @@ public function getImage() $imageUrl = $this->_xpath->evaluate('string(' . $this->getXpathPrefix() . '/atom:logo)'); - if (!$imageUrl) { - $image = null; - } else { - $image = array('uri'=>$imageUrl); - } + $image = $imageUrl ? array('uri'=>$imageUrl) : null; $this->_data['image'] = $image; @@ -329,11 +325,7 @@ public function getIcon() $imageUrl = $this->_xpath->evaluate('string(' . $this->getXpathPrefix() . '/atom:icon)'); - if (!$imageUrl) { - $image = null; - } else { - $image = array('uri'=>$imageUrl); - } + $image = $imageUrl ? array('uri'=>$imageUrl) : null; $this->_data['icon'] = $image; @@ -379,7 +371,7 @@ public function getLink() $this->getXpathPrefix() . '/atom:link[not(@rel)]/@href' ); - if ($list->length) { + if ($list->length !== 0) { $link = $list->item(0)->nodeValue; $link = $this->_absolutiseUri($link); } @@ -424,7 +416,7 @@ public function getHubs() $list = $this->_xpath->query($this->getXpathPrefix() . '//atom:link[@rel="hub"]/@href'); - if ($list->length) { + if ($list->length !== 0) { foreach ($list as $uri) { $hubs[] = $this->_absolutiseUri($uri->nodeValue); } @@ -482,7 +474,7 @@ public function getCategories() $list = $this->_xpath->query($this->getXpathPrefix() . '/atom10:category'); } - if ($list->length) { + if ($list->length !== 0) { $categoryCollection = new Zend_Feed_Reader_Collection_Category; foreach ($list as $category) { $categoryCollection[] = array( @@ -538,12 +530,10 @@ protected function _getAuthor(DOMElement $element) */ protected function _absolutiseUri($link) { - if (!Zend_Uri::check($link)) { - if ($this->getBaseUrl() !== null) { - $link = $this->getBaseUrl() . $link; - if (!Zend_Uri::check($link)) { - $link = null; - } + if (!Zend_Uri::check($link) && $this->getBaseUrl() !== null) { + $link = $this->getBaseUrl() . $link; + if (!Zend_Uri::check($link)) { + $link = null; } } return $link; diff --git a/library/Zend/Feed/Reader/Extension/DublinCore/Feed.php b/library/Zend/Feed/Reader/Extension/DublinCore/Feed.php index 168235fc27..6734e71959 100644 --- a/library/Zend/Feed/Reader/Extension/DublinCore/Feed.php +++ b/library/Zend/Feed/Reader/Extension/DublinCore/Feed.php @@ -74,18 +74,18 @@ public function getAuthors() $authors = array(); $list = $this->_xpath->query('//dc11:creator'); - if (!$list->length) { + if ($list->length === 0) { $list = $this->_xpath->query('//dc10:creator'); } - if (!$list->length) { + if ($list->length === 0) { $list = $this->_xpath->query('//dc11:publisher'); - if (!$list->length) { + if ($list->length === 0) { $list = $this->_xpath->query('//dc10:publisher'); } } - if ($list->length) { + if ($list->length !== 0) { foreach ($list as $author) { $authors[] = array( 'name' => $author->nodeValue diff --git a/library/Zend/Feed/Reader/Extension/EntryAbstract.php b/library/Zend/Feed/Reader/Extension/EntryAbstract.php index 6b1cda6235..130d48cc8d 100644 --- a/library/Zend/Feed/Reader/Extension/EntryAbstract.php +++ b/library/Zend/Feed/Reader/Extension/EntryAbstract.php @@ -83,11 +83,7 @@ public function __construct(DOMElement $entry, $entryKey, $type = null) $this->_entryKey = $entryKey; $this->_domDocument = $entry->ownerDocument; - if ($type !== null) { - $this->_data['type'] = $type; - } else { - $this->_data['type'] = Zend_Feed_Reader::detectType($entry->ownerDocument, true); - } + $this->_data['type'] = $type !== null ? $type : Zend_Feed_Reader::detectType($entry->ownerDocument, true); // set the XPath query prefix for the entry being queried if ($this->getType() == Zend_Feed_Reader::TYPE_RSS_10 || $this->getType() == Zend_Feed_Reader::TYPE_RSS_090 @@ -119,8 +115,7 @@ public function getDomDocument() */ public function getEncoding() { - $assumed = $this->getDomDocument()->encoding; - return $assumed; + return $this->getDomDocument()->encoding; } /** diff --git a/library/Zend/Feed/Reader/Extension/FeedAbstract.php b/library/Zend/Feed/Reader/Extension/FeedAbstract.php index 93b0b579e2..06afc1fd00 100644 --- a/library/Zend/Feed/Reader/Extension/FeedAbstract.php +++ b/library/Zend/Feed/Reader/Extension/FeedAbstract.php @@ -82,17 +82,9 @@ public function __construct(DomDocument $dom, $type = null, DOMXPath $xpath = nu { $this->_domDocument = $dom; - if ($type !== null) { - $this->_data['type'] = $type; - } else { - $this->_data['type'] = Zend_Feed_Reader::detectType($dom); - } - - if ($xpath !== null) { - $this->_xpath = $xpath; - } else { - $this->_xpath = new DOMXPath($this->_domDocument); - } + $this->_data['type'] = $type !== null ? $type : Zend_Feed_Reader::detectType($dom); + + $this->_xpath = $xpath !== null ? $xpath : new DOMXPath($this->_domDocument); $this->_registerNamespaces(); } @@ -114,8 +106,7 @@ public function getDomDocument() */ public function getEncoding() { - $assumed = $this->getDomDocument()->encoding; - return $assumed; + return $this->getDomDocument()->encoding; } /** diff --git a/library/Zend/Feed/Reader/Extension/Podcast/Feed.php b/library/Zend/Feed/Reader/Extension/Podcast/Feed.php index 0cffab413d..29f74bfb08 100644 --- a/library/Zend/Feed/Reader/Extension/Podcast/Feed.php +++ b/library/Zend/Feed/Reader/Extension/Podcast/Feed.php @@ -110,7 +110,7 @@ public function getCategories() } - if (!$categories) { + if ($categories === []) { $categories = null; } @@ -225,7 +225,7 @@ public function getOwner() if (!empty($email)) { $owner = $email . (empty($name) ? '' : ' (' . $name . ')'); - } else if (!empty($name)) { + } elseif (!empty($name)) { $owner = $name; } diff --git a/library/Zend/Feed/Reader/Feed/Rss.php b/library/Zend/Feed/Reader/Feed/Rss.php index ab176246f0..53b720517b 100644 --- a/library/Zend/Feed/Reader/Feed/Rss.php +++ b/library/Zend/Feed/Reader/Feed/Rss.php @@ -126,7 +126,7 @@ public function getAuthors() } else { $list = $this->_xpath->query('//rss:author'); } - if ($list->length) { + if ($list->length !== 0) { foreach ($list as $author) { $string = trim($author->nodeValue); $email = null; @@ -253,7 +253,7 @@ public function getDateModified() } } - if (!$date) { + if ($date === null) { $date = $this->getExtension('DublinCore')->getDate(); } @@ -315,7 +315,7 @@ public function getLastBuildDate() } } - if (!$date) { + if ($date === null) { $date = null; } @@ -642,11 +642,7 @@ public function getHubs() $hubs = $this->getExtension('Atom')->getHubs(); - if (empty($hubs)) { - $hubs = null; - } else { - $hubs = array_unique($hubs); - } + $hubs = empty($hubs) ? null : array_unique($hubs); $this->_data['hubs'] = $hubs; @@ -671,7 +667,7 @@ public function getCategories() $list = $this->_xpath->query('/rdf:RDF/rss:channel//rss:category'); } - if ($list->length) { + if ($list->length !== 0) { $categoryCollection = new Zend_Feed_Reader_Collection_Category; foreach ($list as $category) { $categoryCollection[] = array( diff --git a/library/Zend/Feed/Reader/FeedAbstract.php b/library/Zend/Feed/Reader/FeedAbstract.php index 3426958fba..f6f66c61ce 100644 --- a/library/Zend/Feed/Reader/FeedAbstract.php +++ b/library/Zend/Feed/Reader/FeedAbstract.php @@ -97,11 +97,7 @@ public function __construct(DomDocument $domDocument, $type = null) $this->_domDocument = $domDocument; $this->_xpath = new DOMXPath($this->_domDocument); - if ($type !== null) { - $this->_data['type'] = $type; - } else { - $this->_data['type'] = Zend_Feed_Reader::detectType($this->_domDocument); - } + $this->_data['type'] = $type !== null ? $type : Zend_Feed_Reader::detectType($this->_domDocument); $this->_registerNamespaces(); $this->_indexEntries(); $this->_loadExtensions(); diff --git a/library/Zend/Feed/Reader/FeedSet.php b/library/Zend/Feed/Reader/FeedSet.php index 39dd872ef4..bebe64749d 100644 --- a/library/Zend/Feed/Reader/FeedSet.php +++ b/library/Zend/Feed/Reader/FeedSet.php @@ -67,11 +67,11 @@ public function addLinks(DOMNodeList $links, $uri) || !$link->getAttribute('type') || !$link->getAttribute('href')) { continue; } - if (!isset($this->rss) && $link->getAttribute('type') == 'application/rss+xml') { + if (!($this->rss !== null) && $link->getAttribute('type') == 'application/rss+xml') { $this->rss = $this->_absolutiseUri(trim($link->getAttribute('href')), $uri); - } elseif(!isset($this->atom) && $link->getAttribute('type') == 'application/atom+xml') { + } elseif(!($this->atom !== null) && $link->getAttribute('type') == 'application/atom+xml') { $this->atom = $this->_absolutiseUri(trim($link->getAttribute('href')), $uri); - } elseif(!isset($this->rdf) && $link->getAttribute('type') == 'application/rdf+xml') { + } elseif(!($this->rdf !== null) && $link->getAttribute('type') == 'application/rdf+xml') { $this->rdf = $this->_absolutiseUri(trim($link->getAttribute('href')), $uri); } $this[] = new self(array( @@ -87,18 +87,14 @@ public function addLinks(DOMNodeList $links, $uri) */ protected function _absolutiseUri($link, $uri = null) { - if (!Zend_Uri::check($link)) { - if ($uri !== null) { - $uri = Zend_Uri::factory($uri); - - if ($link[0] !== '/') { - $link = $uri->getPath() . '/' . $link; - } - - $link = $uri->getScheme() . '://' . $uri->getHost() . '/' . $this->_canonicalizePath($link); - if (!Zend_Uri::check($link)) { - $link = null; - } + if (!Zend_Uri::check($link) && $uri !== null) { + $uri = Zend_Uri::factory($uri); + if ($link[0] !== '/') { + $link = $uri->getPath() . '/' . $link; + } + $link = $uri->getScheme() . '://' . $uri->getHost() . '/' . $this->_canonicalizePath($link); + if (!Zend_Uri::check($link)) { + $link = null; } } return $link; diff --git a/library/Zend/Feed/Rss.php b/library/Zend/Feed/Rss.php index 5035d35d77..1d1f215f5c 100644 --- a/library/Zend/Feed/Rss.php +++ b/library/Zend/Feed/Rss.php @@ -81,12 +81,8 @@ public function __wakeup() // Find the base channel element and create an alias to it. $rdfTags = $this->_element->getElementsByTagNameNS('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'RDF'); - if ($rdfTags->length != 0) { - $this->_element = $rdfTags->item(0); - } else { - $this->_element = $this->_element->getElementsByTagName('channel')->item(0); - } - if (!$this->_element) { + $this->_element = $rdfTags->length != 0 ? $rdfTags->item(0) : $this->_element->getElementsByTagName('channel')->item(0); + if (!$this->_element instanceof \DOMElement) { /** * @see Zend_Feed_Exception */ @@ -141,16 +137,16 @@ protected function _mapFeedHeaders($array) $link = $this->_element->createElement('link', $array->link); $channel->appendChild($link); - $desc = isset($array->description) ? $array->description : ''; + $desc = property_exists($array, 'description') && $array->description !== null ? $array->description : ''; $description = $this->_element->createElement('description'); $description->appendChild($this->_element->createCDATASection($desc)); $channel->appendChild($description); - $pubdate = isset($array->lastUpdate) ? $array->lastUpdate : time(); + $pubdate = property_exists($array, 'lastUpdate') && $array->lastUpdate !== null ? $array->lastUpdate : time(); $pubdate = $this->_element->createElement('pubDate', date(DATE_RSS, $pubdate)); $channel->appendChild($pubdate); - if (isset($array->published)) { + if (property_exists($array, 'published') && $array->published !== null) { $lastBuildDate = $this->_element->createElement('lastBuildDate', date(DATE_RSS, $array->published)); $channel->appendChild($lastBuildDate); } @@ -166,7 +162,7 @@ protected function _mapFeedHeaders($array) $author = $this->_element->createElement('managingEditor', ltrim($editor)); $channel->appendChild($author); } - if (isset($array->webmaster)) { + if (property_exists($array, 'webmaster') && $array->webmaster !== null) { $channel->appendChild($this->_element->createElement('webMaster', $array->webmaster)); } @@ -175,7 +171,7 @@ protected function _mapFeedHeaders($array) $channel->appendChild($copyright); } - if (isset($array->category)) { + if (property_exists($array, 'category') && $array->category !== null) { $category = $this->_element->createElement('category', $array->category); $channel->appendChild($category); } @@ -193,7 +189,7 @@ protected function _mapFeedHeaders($array) $channel->appendChild($image); } - $generator = !empty($array->generator) ? $array->generator : 'Zend_Feed'; + $generator = empty($array->generator) ? 'Zend_Feed' : $array->generator; $generator = $this->_element->createElement('generator', $generator); $channel->appendChild($generator); @@ -205,7 +201,7 @@ protected function _mapFeedHeaders($array) $doc = $this->_element->createElement('docs', 'http://blogs.law.harvard.edu/tech/rss'); $channel->appendChild($doc); - if (isset($array->cloud)) { + if (property_exists($array, 'cloud') && $array->cloud !== null) { $cloud = $this->_element->createElement('cloud'); $cloud->setAttribute('domain', $array->cloud['uri']->getHost()); $cloud->setAttribute('port', $array->cloud['uri']->getPort()); @@ -215,17 +211,17 @@ protected function _mapFeedHeaders($array) $channel->appendChild($cloud); } - if (isset($array->ttl)) { + if (property_exists($array, 'ttl') && $array->ttl !== null) { $ttl = $this->_element->createElement('ttl', $array->ttl); $channel->appendChild($ttl); } - if (isset($array->rating)) { + if (property_exists($array, 'rating') && $array->rating !== null) { $rating = $this->_element->createElement('rating', $array->rating); $channel->appendChild($rating); } - if (isset($array->textInput)) { + if (property_exists($array, 'textInput') && $array->textInput !== null) { $textinput = $this->_element->createElement('textInput'); $textinput->appendChild($this->_element->createElement('title', $array->textInput['title'])); $textinput->appendChild($this->_element->createElement('description', $array->textInput['description'])); @@ -234,7 +230,7 @@ protected function _mapFeedHeaders($array) $channel->appendChild($textinput); } - if (isset($array->skipHours)) { + if (property_exists($array, 'skipHours') && $array->skipHours !== null) { $skipHours = $this->_element->createElement('skipHours'); foreach ($array->skipHours as $hour) { $skipHours->appendChild($this->_element->createElement('hour', $hour)); @@ -242,7 +238,7 @@ protected function _mapFeedHeaders($array) $channel->appendChild($skipHours); } - if (isset($array->skipDays)) { + if (property_exists($array, 'skipDays') && $array->skipDays !== null) { $skipDays = $this->_element->createElement('skipDays'); foreach ($array->skipDays as $day) { $skipDays->appendChild($this->_element->createElement('day', $day)); @@ -250,7 +246,7 @@ protected function _mapFeedHeaders($array) $channel->appendChild($skipDays); } - if (isset($array->itunes)) { + if (property_exists($array, 'itunes') && $array->itunes !== null) { $this->_buildiTunes($channel, $array); } @@ -268,9 +264,9 @@ private function _buildiTunes(DOMElement $root, $array) { /* author node */ $author = ''; - if (isset($array->itunes->author)) { + if (property_exists($array->itunes, 'author') && $array->itunes->author !== null) { $author = $array->itunes->author; - } elseif (isset($array->author)) { + } elseif (property_exists($array, 'author') && $array->author !== null) { $author = $array->author; } if (!empty($author)) { @@ -281,7 +277,7 @@ private function _buildiTunes(DOMElement $root, $array) /* owner node */ $author = ''; $email = ''; - if (isset($array->itunes->owner)) { + if (property_exists($array->itunes, 'owner') && $array->itunes->owner !== null) { if (isset($array->itunes->owner['name'])) { $author = $array->itunes->owner['name']; } @@ -289,10 +285,10 @@ private function _buildiTunes(DOMElement $root, $array) $email = $array->itunes->owner['email']; } } - if (empty($author) && isset($array->author)) { + if (empty($author) && (property_exists($array, 'author') && $array->author !== null)) { $author = $array->author; } - if (empty($email) && isset($array->email)) { + if (empty($email) && (property_exists($array, 'email') && $array->email !== null)) { $email = $array->email; } if (!empty($author) || !empty($email)) { @@ -308,9 +304,9 @@ private function _buildiTunes(DOMElement $root, $array) $root->appendChild($owner); } $image = ''; - if (isset($array->itunes->image)) { + if (property_exists($array->itunes, 'image') && $array->itunes->image !== null) { $image = $array->itunes->image; - } elseif (isset($array->image)) { + } elseif (property_exists($array, 'image') && $array->image !== null) { $image = $array->image; } if (!empty($image)) { @@ -319,9 +315,9 @@ private function _buildiTunes(DOMElement $root, $array) $root->appendChild($node); } $subtitle = ''; - if (isset($array->itunes->subtitle)) { + if (property_exists($array->itunes, 'subtitle') && $array->itunes->subtitle !== null) { $subtitle = $array->itunes->subtitle; - } elseif (isset($array->description)) { + } elseif (property_exists($array, 'description') && $array->description !== null) { $subtitle = $array->description; } if (!empty($subtitle)) { @@ -329,32 +325,32 @@ private function _buildiTunes(DOMElement $root, $array) $root->appendChild($node); } $summary = ''; - if (isset($array->itunes->summary)) { + if (property_exists($array->itunes, 'summary') && $array->itunes->summary !== null) { $summary = $array->itunes->summary; - } elseif (isset($array->description)) { + } elseif (property_exists($array, 'description') && $array->description !== null) { $summary = $array->description; } if (!empty($summary)) { $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:summary', $summary); $root->appendChild($node); } - if (isset($array->itunes->block)) { + if (property_exists($array->itunes, 'block') && $array->itunes->block !== null) { $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:block', $array->itunes->block); $root->appendChild($node); } - if (isset($array->itunes->explicit)) { + if (property_exists($array->itunes, 'explicit') && $array->itunes->explicit !== null) { $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:explicit', $array->itunes->explicit); $root->appendChild($node); } - if (isset($array->itunes->keywords)) { + if (property_exists($array->itunes, 'keywords') && $array->itunes->keywords !== null) { $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:keywords', $array->itunes->keywords); $root->appendChild($node); } - if (isset($array->itunes->new_feed_url)) { + if (property_exists($array->itunes, 'new_feed_url') && $array->itunes->new_feed_url !== null) { $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:new-feed-url', $array->itunes->new_feed_url); $root->appendChild($node); } - if (isset($array->itunes->category)) { + if (property_exists($array->itunes, 'category') && $array->itunes->category !== null) { foreach ($array->itunes->category as $i => $category) { $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:category'); $node->setAttribute('text', $category['main']); @@ -401,7 +397,7 @@ protected function _mapFeedEntries(DOMElement $root, $array) $title->appendChild($this->_element->createCDATASection($dataentry->title)); $item->appendChild($title); - if (isset($dataentry->author)) { + if (property_exists($dataentry, 'author') && $dataentry->author !== null) { $author = $this->_element->createElement('author', $dataentry->author); $item->appendChild($author); } @@ -409,7 +405,7 @@ protected function _mapFeedEntries(DOMElement $root, $array) $link = $this->_element->createElement('link', $dataentry->link); $item->appendChild($link); - if (isset($dataentry->guid)) { + if (property_exists($dataentry, 'guid') && $dataentry->guid !== null) { $guid = $this->_element->createElement('guid', $dataentry->guid); if (!Zend_Uri::check($dataentry->guid)) { $guid->setAttribute('isPermaLink', 'false'); @@ -421,17 +417,17 @@ protected function _mapFeedEntries(DOMElement $root, $array) $description->appendChild($this->_element->createCDATASection($dataentry->description)); $item->appendChild($description); - if (isset($dataentry->content)) { + if (property_exists($dataentry, 'content') && $dataentry->content !== null) { $content = $this->_element->createElement('content:encoded'); $content->appendChild($this->_element->createCDATASection($dataentry->content)); $item->appendChild($content); } - $pubdate = isset($dataentry->lastUpdate) ? $dataentry->lastUpdate : time(); + $pubdate = property_exists($dataentry, 'lastUpdate') && $dataentry->lastUpdate !== null ? $dataentry->lastUpdate : time(); $pubdate = $this->_element->createElement('pubDate', date(DATE_RSS, $pubdate)); $item->appendChild($pubdate); - if (isset($dataentry->category)) { + if (property_exists($dataentry, 'category') && $dataentry->category !== null) { foreach ($dataentry->category as $category) { $node = $this->_element->createElement('category'); $node->appendChild($this->_element->createCDATASection($category['term'])); @@ -442,17 +438,17 @@ protected function _mapFeedEntries(DOMElement $root, $array) } } - if (isset($dataentry->source)) { + if (property_exists($dataentry, 'source') && $dataentry->source !== null) { $source = $this->_element->createElement('source', $dataentry->source['title']); $source->setAttribute('url', $dataentry->source['url']); $item->appendChild($source); } - if (isset($dataentry->comments)) { + if (property_exists($dataentry, 'comments') && $dataentry->comments !== null) { $comments = $this->_element->createElement('comments', $dataentry->comments); $item->appendChild($comments); } - if (isset($dataentry->commentRss)) { + if (property_exists($dataentry, 'commentRss') && $dataentry->commentRss !== null) { $comments = $this->_element->createElementNS('http://wellformedweb.org/CommentAPI/', 'wfw:commentRss', $dataentry->commentRss); @@ -460,7 +456,7 @@ protected function _mapFeedEntries(DOMElement $root, $array) } - if (isset($dataentry->enclosure)) { + if (property_exists($dataentry, 'enclosure') && $dataentry->enclosure !== null) { foreach ($dataentry->enclosure as $enclosure) { $node = $this->_element->createElement('enclosure'); $node->setAttribute('url', $enclosure['url']); diff --git a/library/Zend/Feed/Writer.php b/library/Zend/Feed/Writer.php index 8eced7af38..9cfc23f7b0 100644 --- a/library/Zend/Feed/Writer.php +++ b/library/Zend/Feed/Writer.php @@ -153,14 +153,11 @@ public static function registerExtension($name) $entryName = $name . '_Entry'; $feedRendererName = $name . '_Renderer_Feed'; $entryRendererName = $name . '_Renderer_Entry'; - if (self::isRegistered($name)) { - if (self::getPluginLoader()->isLoaded($feedName) - || self::getPluginLoader()->isLoaded($entryName) - || self::getPluginLoader()->isLoaded($feedRendererName) - || self::getPluginLoader()->isLoaded($entryRendererName) - ) { - return; - } + if (self::isRegistered($name) && (self::getPluginLoader()->isLoaded($feedName) + || self::getPluginLoader()->isLoaded($entryName) + || self::getPluginLoader()->isLoaded($feedRendererName) + || self::getPluginLoader()->isLoaded($entryRendererName))) { + return; } try { self::getPluginLoader()->load($feedName); @@ -205,14 +202,10 @@ public static function isRegistered($extensionName) $entryName = $extensionName . '_Entry'; $feedRendererName = $extensionName . '_Renderer_Feed'; $entryRendererName = $extensionName . '_Renderer_Entry'; - if (in_array($feedName, self::$_extensions['feed']) + return in_array($feedName, self::$_extensions['feed']) || in_array($entryName, self::$_extensions['entry']) || in_array($feedRendererName, self::$_extensions['feedRenderer']) - || in_array($entryRendererName, self::$_extensions['entryRenderer']) - ) { - return true; - } - return false; + || in_array($entryRendererName, self::$_extensions['entryRenderer']); } /** diff --git a/library/Zend/Feed/Writer/Entry.php b/library/Zend/Feed/Writer/Entry.php index f364e0bbe0..598224acb4 100644 --- a/library/Zend/Feed/Writer/Entry.php +++ b/library/Zend/Feed/Writer/Entry.php @@ -329,8 +329,7 @@ public function setCommentFeedLink(array $link) } if (!isset($link['type']) || !in_array($link['type'], array('atom', 'rss', 'rdf'))) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('Invalid parameter: "type" must be one' - . ' of "atom", "rss" or "rdf"'); + throw new Zend_Feed_Exception('Invalid parameter: "type" must be one of "atom", "rss" or "rdf"'); } if (!isset($this->_data['commentFeedLinks'])) { $this->_data['commentFeedLinks'] = array(); @@ -550,15 +549,11 @@ public function addCategory(array $category) . 'contain at least a "term" element containing the machine ' . ' readable category name'); } - if (isset($category['scheme'])) { - if (empty($category['scheme']) - || !is_string($category['scheme']) - || !Zend_Uri::check($category['scheme']) - ) { - require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('The Atom scheme or RSS domain of' - . ' a category must be a valid URI'); - } + if (isset($category['scheme']) && (empty($category['scheme']) + || !is_string($category['scheme']) + || !Zend_Uri::check($category['scheme']))) { + require_once 'Zend/Feed/Exception.php'; + throw new Zend_Feed_Exception('The Atom scheme or RSS domain of a category must be a valid URI'); } if (!isset($this->_data['categories'])) { $this->_data['categories'] = array(); diff --git a/library/Zend/Feed/Writer/Extension/ITunes/Entry.php b/library/Zend/Feed/Writer/Extension/ITunes/Entry.php index fa99495f36..b3544472f4 100644 --- a/library/Zend/Feed/Writer/Extension/ITunes/Entry.php +++ b/library/Zend/Feed/Writer/Extension/ITunes/Entry.php @@ -73,13 +73,11 @@ public function setItunesBlock($value) { if (!ctype_alpha($value) && strlen((string) $value) > 0) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: "block" may only' - . ' contain alphabetic characters'); + throw new Zend_Feed_Exception('invalid parameter: "block" may only contain alphabetic characters'); } if (iconv_strlen($value, $this->getEncoding()) > 255) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: "block" may only' - . ' contain a maximum of 255 characters'); + throw new Zend_Feed_Exception('invalid parameter: "block" may only contain a maximum of 255 characters'); } $this->_data['block'] = $value; } @@ -108,8 +106,7 @@ public function addItunesAuthor($value) { if (iconv_strlen($value, $this->getEncoding()) > 255) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: any "author" may only' - . ' contain a maximum of 255 characters each'); + throw new Zend_Feed_Exception('invalid parameter: any "author" may only contain a maximum of 255 characters each'); } if (!isset($this->_data['authors'])) { $this->_data['authors'] = array(); @@ -128,12 +125,11 @@ public function setItunesDuration($value) { $value = (string) $value; if (!ctype_digit($value) - && !preg_match("/^\d+:[0-5]{1}[0-9]{1}$/", $value) - && !preg_match("/^\d+:[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}$/", $value) + && !preg_match("/^\\d+:[0-5]{1}\\d{1}\$/", $value) + && !preg_match("/^\\d+:[0-5]{1}\\d{1}:[0-5]{1}\\d{1}\$/", $value) ) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: "duration" may only' - . ' be of a specified [[HH:]MM:]SS format'); + throw new Zend_Feed_Exception('invalid parameter: "duration" may only be of a specified [[HH:]MM:]SS format'); } $this->_data['duration'] = $value; return $this; @@ -149,8 +145,7 @@ public function setItunesExplicit($value) { if (!in_array($value, array('yes','no','clean'))) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: "explicit" may only' - . ' be one of "yes", "no" or "clean"'); + throw new Zend_Feed_Exception('invalid parameter: "explicit" may only be one of "yes", "no" or "clean"'); } $this->_data['explicit'] = $value; return $this; @@ -166,8 +161,7 @@ public function setItunesKeywords(array $value) { if (count($value) > 12) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: "keywords" may only' - . ' contain a maximum of 12 terms'); + throw new Zend_Feed_Exception('invalid parameter: "keywords" may only contain a maximum of 12 terms'); } $concat = implode(',', $value); if (iconv_strlen($concat, $this->getEncoding()) > 255) { @@ -190,8 +184,7 @@ public function setItunesSubtitle($value) { if (iconv_strlen($value, $this->getEncoding()) > 255) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: "subtitle" may only' - . ' contain a maximum of 255 characters'); + throw new Zend_Feed_Exception('invalid parameter: "subtitle" may only contain a maximum of 255 characters'); } $this->_data['subtitle'] = $value; return $this; @@ -207,8 +200,7 @@ public function setItunesSummary($value) { if (iconv_strlen($value, $this->getEncoding()) > 4000) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: "summary" may only' - . ' contain a maximum of 4000 characters'); + throw new Zend_Feed_Exception('invalid parameter: "summary" may only contain a maximum of 4000 characters'); } $this->_data['summary'] = $value; return $this; diff --git a/library/Zend/Feed/Writer/Extension/ITunes/Feed.php b/library/Zend/Feed/Writer/Extension/ITunes/Feed.php index 3738e68b38..5f5a4225f9 100644 --- a/library/Zend/Feed/Writer/Extension/ITunes/Feed.php +++ b/library/Zend/Feed/Writer/Extension/ITunes/Feed.php @@ -73,13 +73,11 @@ public function setItunesBlock($value) { if (!ctype_alpha($value) && strlen((string) $value) > 0) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: "block" may only' - . ' contain alphabetic characters'); + throw new Zend_Feed_Exception('invalid parameter: "block" may only contain alphabetic characters'); } if (iconv_strlen($value, $this->getEncoding()) > 255) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: "block" may only' - . ' contain a maximum of 255 characters'); + throw new Zend_Feed_Exception('invalid parameter: "block" may only contain a maximum of 255 characters'); } $this->_data['block'] = $value; return $this; @@ -109,8 +107,7 @@ public function addItunesAuthor($value) { if (iconv_strlen($value, $this->getEncoding()) > 255) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: any "author" may only' - . ' contain a maximum of 255 characters each'); + throw new Zend_Feed_Exception('invalid parameter: any "author" may only contain a maximum of 255 characters each'); } if (!isset($this->_data['authors'])) { $this->_data['authors'] = array(); @@ -134,22 +131,19 @@ public function setItunesCategories(array $values) if (!is_array($value)) { if (iconv_strlen($value, $this->getEncoding()) > 255) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: any "category" may only' - . ' contain a maximum of 255 characters each'); + throw new Zend_Feed_Exception('invalid parameter: any "category" may only contain a maximum of 255 characters each'); } $this->_data['categories'][] = $value; } else { if (iconv_strlen($key, $this->getEncoding()) > 255) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: any "category" may only' - . ' contain a maximum of 255 characters each'); + throw new Zend_Feed_Exception('invalid parameter: any "category" may only contain a maximum of 255 characters each'); } $this->_data['categories'][$key] = array(); foreach ($value as $val) { if (iconv_strlen($val, $this->getEncoding()) > 255) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: any "category" may only' - . ' contain a maximum of 255 characters each'); + throw new Zend_Feed_Exception('invalid parameter: any "category" may only contain a maximum of 255 characters each'); } $this->_data['categories'][$key][] = $val; } @@ -168,8 +162,7 @@ public function setItunesImage($value) { if (!Zend_Uri::check($value)) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: "image" may only' - . ' be a valid URI/IRI'); + throw new Zend_Feed_Exception('invalid parameter: "image" may only be a valid URI/IRI'); } if (!in_array(substr($value, -3), array('jpg','png'))) { require_once 'Zend/Feed/Exception.php'; @@ -191,12 +184,11 @@ public function setItunesDuration($value) { $value = (string) $value; if (!ctype_digit($value) - && !preg_match("/^\d+:[0-5]{1}[0-9]{1}$/", $value) - && !preg_match("/^\d+:[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}$/", $value) + && !preg_match("/^\\d+:[0-5]{1}\\d{1}\$/", $value) + && !preg_match("/^\\d+:[0-5]{1}\\d{1}:[0-5]{1}\\d{1}\$/", $value) ) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: "duration" may only' - . ' be of a specified [[HH:]MM:]SS format'); + throw new Zend_Feed_Exception('invalid parameter: "duration" may only be of a specified [[HH:]MM:]SS format'); } $this->_data['duration'] = $value; return $this; @@ -212,8 +204,7 @@ public function setItunesExplicit($value) { if (!in_array($value, array('yes','no','clean'))) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: "explicit" may only' - . ' be one of "yes", "no" or "clean"'); + throw new Zend_Feed_Exception('invalid parameter: "explicit" may only be one of "yes", "no" or "clean"'); } $this->_data['explicit'] = $value; return $this; @@ -229,8 +220,7 @@ public function setItunesKeywords(array $value) { if (count($value) > 12) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: "keywords" may only' - . ' contain a maximum of 12 terms'); + throw new Zend_Feed_Exception('invalid parameter: "keywords" may only contain a maximum of 12 terms'); } $concat = implode(',', $value); if (iconv_strlen($concat, $this->getEncoding()) > 255) { @@ -253,8 +243,7 @@ public function setItunesNewFeedUrl($value) { if (!Zend_Uri::check($value)) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: "newFeedUrl" may only' - . ' be a valid URI/IRI'); + throw new Zend_Feed_Exception('invalid parameter: "newFeedUrl" may only be a valid URI/IRI'); } $this->_data['newFeedUrl'] = $value; return $this; @@ -284,8 +273,7 @@ public function addItunesOwner(array $value) { if (!isset($value['name']) || !isset($value['email'])) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: any "owner" must' - . ' be an array containing keys "name" and "email"'); + throw new Zend_Feed_Exception('invalid parameter: any "owner" must be an array containing keys "name" and "email"'); } if (iconv_strlen($value['name'], $this->getEncoding()) > 255 || iconv_strlen($value['email'], $this->getEncoding()) > 255 @@ -311,8 +299,7 @@ public function setItunesSubtitle($value) { if (iconv_strlen($value, $this->getEncoding()) > 255) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: "subtitle" may only' - . ' contain a maximum of 255 characters'); + throw new Zend_Feed_Exception('invalid parameter: "subtitle" may only contain a maximum of 255 characters'); } $this->_data['subtitle'] = $value; return $this; @@ -328,8 +315,7 @@ public function setItunesSummary($value) { if (iconv_strlen($value, $this->getEncoding()) > 4000) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('invalid parameter: "summary" may only' - . ' contain a maximum of 4000 characters'); + throw new Zend_Feed_Exception('invalid parameter: "summary" may only contain a maximum of 4000 characters'); } $this->_data['summary'] = $value; return $this; diff --git a/library/Zend/Feed/Writer/Feed/FeedAbstract.php b/library/Zend/Feed/Writer/Feed/FeedAbstract.php index b1898a5f28..2ef42ef070 100644 --- a/library/Zend/Feed/Writer/Feed/FeedAbstract.php +++ b/library/Zend/Feed/Writer/Feed/FeedAbstract.php @@ -60,6 +60,10 @@ */ class Zend_Feed_Writer_Feed_FeedAbstract { + /** + * @var mixed[]|object[]|mixed + */ + public $_extensions; /** * Contains all Feed level date to append in feed output * @@ -332,11 +336,7 @@ protected function _validateTagUri($id) $dvalid = true; } $validator = new Zend_Validate_EmailAddress; - if ($validator->isValid($matches['name'])) { - $nvalid = true; - } else { - $nvalid = $validator->isValid('info@' . $matches['name']); - } + $nvalid = $validator->isValid($matches['name']) ? true : $validator->isValid('info@' . $matches['name']); return $dvalid && $nvalid; } @@ -356,8 +356,7 @@ public function setImage(array $data) if (empty($data['uri']) || !is_string($data['uri']) || !Zend_Uri::check($data['uri'])) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('Invalid parameter: parameter \'uri\'' - . ' must be a non-empty string and valid URI/IRI'); + throw new Zend_Feed_Exception('Invalid parameter: parameter \'uri\' must be a non-empty string and valid URI/IRI'); } $this->_data['image'] = $data; } @@ -374,8 +373,7 @@ public function setIcon(array $data) if (empty($data['uri']) || !is_string($data['uri']) || !Zend_Uri::check($data['uri'])) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('Invalid parameter: parameter \'uri\'' - . ' must be a non-empty string and valid URI/IRI'); + throw new Zend_Feed_Exception('Invalid parameter: parameter \'uri\' must be a non-empty string and valid URI/IRI'); } $this->_data['icon'] = $data; } @@ -463,8 +461,7 @@ public function setBaseUrl($url) { if (empty($url) || !is_string($url) || !Zend_Uri::check($url)) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('Invalid parameter: "url" array value' - . ' must be a non-empty string and valid URI/IRI'); + throw new Zend_Feed_Exception('Invalid parameter: "url" array value must be a non-empty string and valid URI/IRI'); } $this->_data['baseUrl'] = $url; } @@ -478,8 +475,7 @@ public function addHub($url) { if (empty($url) || !is_string($url) || !Zend_Uri::check($url)) { require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('Invalid parameter: "url" array value' - . ' must be a non-empty string and valid URI/IRI'); + throw new Zend_Feed_Exception('Invalid parameter: "url" array value must be a non-empty string and valid URI/IRI'); } if (!isset($this->_data['hubs'])) { $this->_data['hubs'] = array(); @@ -512,15 +508,11 @@ public function addCategory(array $category) . 'contain at least a "term" element containing the machine ' . ' readable category name'); } - if (isset($category['scheme'])) { - if (empty($category['scheme']) - || !is_string($category['scheme']) - || !Zend_Uri::check($category['scheme']) - ) { - require_once 'Zend/Feed/Exception.php'; - throw new Zend_Feed_Exception('The Atom scheme or RSS domain of' - . ' a category must be a valid URI'); - } + if (isset($category['scheme']) && (empty($category['scheme']) + || !is_string($category['scheme']) + || !Zend_Uri::check($category['scheme']))) { + require_once 'Zend/Feed/Exception.php'; + throw new Zend_Feed_Exception('The Atom scheme or RSS domain of a category must be a valid URI'); } if (!isset($this->_data['categories'])) { $this->_data['categories'] = array(); diff --git a/library/Zend/Feed/Writer/Renderer/Entry/Atom.php b/library/Zend/Feed/Writer/Renderer/Entry/Atom.php index 6e595437e6..c943e39d45 100644 --- a/library/Zend/Feed/Writer/Renderer/Entry/Atom.php +++ b/library/Zend/Feed/Writer/Renderer/Entry/Atom.php @@ -95,8 +95,7 @@ protected function _setTitle(DOMDocument $dom, DOMElement $root) { if(!$this->getDataContainer()->getTitle()) { require_once 'Zend/Feed/Exception.php'; - $message = 'Atom 1.0 entry elements MUST contain exactly one' - . ' atom:title element but a title has not been set'; + $message = 'Atom 1.0 entry elements MUST contain exactly one atom:title element but a title has not been set'; $exception = new Zend_Feed_Exception($message); if (!$this->_ignoreExceptions) { throw $exception; @@ -322,11 +321,7 @@ protected function _validateTagUri($id) $dvalid = true; } $validator = new Zend_Validate_EmailAddress; - if ($validator->isValid($matches['name'])) { - $nvalid = true; - } else { - $nvalid = $validator->isValid('info@' . $matches['name']); - } + $nvalid = $validator->isValid($matches['name']) ? true : $validator->isValid('info@' . $matches['name']); return $dvalid && $nvalid; } diff --git a/library/Zend/Feed/Writer/Renderer/Entry/Rss.php b/library/Zend/Feed/Writer/Renderer/Entry/Rss.php index a26db5b1f0..5f7f9f3497 100644 --- a/library/Zend/Feed/Writer/Renderer/Entry/Rss.php +++ b/library/Zend/Feed/Writer/Renderer/Entry/Rss.php @@ -240,8 +240,7 @@ protected function _setEnclosure(DOMDocument $dom, DOMElement $root) } if (isset($data['length']) && (int) $data['length'] <= 0) { require_once 'Zend/Feed/Exception.php'; - $exception = new Zend_Feed_Exception('Enclosure "length" must be an integer' - . ' indicating the content\'s length in bytes'); + $exception = new Zend_Feed_Exception('Enclosure "length" must be an integer indicating the content\'s length in bytes'); if (!$this->_ignoreExceptions) { throw $exception; } else { diff --git a/library/Zend/Feed/Writer/Renderer/Feed/Atom.php b/library/Zend/Feed/Writer/Renderer/Feed/Atom.php index a91c71455c..8d45932f0f 100644 --- a/library/Zend/Feed/Writer/Renderer/Feed/Atom.php +++ b/library/Zend/Feed/Writer/Renderer/Feed/Atom.php @@ -115,7 +115,7 @@ public function render() } $renderer = new Zend_Feed_Writer_Renderer_Entry_Atom_Deleted($entry); } - if ($this->_ignoreExceptions === true) { + if ($this->_ignoreExceptions) { $renderer->ignoreExceptions(); } $renderer->setType($this->getType()); diff --git a/library/Zend/Feed/Writer/Renderer/Feed/Atom/AtomAbstract.php b/library/Zend/Feed/Writer/Renderer/Feed/Atom/AtomAbstract.php index 0f8ccc110f..b315289d8a 100644 --- a/library/Zend/Feed/Writer/Renderer/Feed/Atom/AtomAbstract.php +++ b/library/Zend/Feed/Writer/Renderer/Feed/Atom/AtomAbstract.php @@ -80,8 +80,7 @@ protected function _setTitle(DOMDocument $dom, DOMElement $root) { if(!$this->getDataContainer()->getTitle()) { require_once 'Zend/Feed/Exception.php'; - $message = 'Atom 1.0 feed elements MUST contain exactly one' - . ' atom:title element but a title has not been set'; + $message = 'Atom 1.0 feed elements MUST contain exactly one atom:title element but a title has not been set'; $exception = new Zend_Feed_Exception($message); if (!$this->_ignoreExceptions) { throw $exception; diff --git a/library/Zend/Feed/Writer/Renderer/Feed/Rss.php b/library/Zend/Feed/Writer/Renderer/Feed/Rss.php index 973154cb72..1272fb309b 100644 --- a/library/Zend/Feed/Writer/Renderer/Feed/Rss.php +++ b/library/Zend/Feed/Writer/Renderer/Feed/Rss.php @@ -105,7 +105,7 @@ public function render() } else { continue; } - if ($this->_ignoreExceptions === true) { + if ($this->_ignoreExceptions) { $renderer->ignoreExceptions(); } $renderer->setType($this->getType()); @@ -147,8 +147,7 @@ protected function _setTitle(DOMDocument $dom, DOMElement $root) { if(!$this->getDataContainer()->getTitle()) { require_once 'Zend/Feed/Exception.php'; - $message = 'RSS 2.0 feed elements MUST contain exactly one' - . ' title element but a title has not been set'; + $message = 'RSS 2.0 feed elements MUST contain exactly one title element but a title has not been set'; $exception = new Zend_Feed_Exception($message); if (!$this->_ignoreExceptions) { throw $exception; @@ -175,8 +174,7 @@ protected function _setDescription(DOMDocument $dom, DOMElement $root) { if(!$this->getDataContainer()->getDescription()) { require_once 'Zend/Feed/Exception.php'; - $message = 'RSS 2.0 feed elements MUST contain exactly one' - . ' description element but one has not been set'; + $message = 'RSS 2.0 feed elements MUST contain exactly one description element but one has not been set'; $exception = new Zend_Feed_Exception($message); if (!$this->_ignoreExceptions) { throw $exception; @@ -252,8 +250,7 @@ protected function _setLink(DOMDocument $dom, DOMElement $root) $value = $this->getDataContainer()->getLink(); if(!$value) { require_once 'Zend/Feed/Exception.php'; - $message = 'RSS 2.0 feed elements MUST contain exactly one' - . ' link element but one has not been set'; + $message = 'RSS 2.0 feed elements MUST contain exactly one link element but one has not been set'; $exception = new Zend_Feed_Exception($message); if (!$this->_ignoreExceptions) { throw $exception; @@ -343,8 +340,7 @@ protected function _setImage(DOMDocument $dom, DOMElement $root) if (empty($image['link']) || !is_string($image['link']) || !Zend_Uri::check($image['link'])) { require_once 'Zend/Feed/Exception.php'; - $message = 'Invalid parameter: parameter \'link\'' - . ' must be a non-empty string and valid URI/IRI'; + $message = 'Invalid parameter: parameter \'link\' must be a non-empty string and valid URI/IRI'; $exception = new Zend_Feed_Exception($message); if (!$this->_ignoreExceptions) { throw $exception; @@ -370,8 +366,7 @@ protected function _setImage(DOMDocument $dom, DOMElement $root) if (isset($image['height'])) { if (!ctype_digit((string) $image['height']) || $image['height'] > 400) { require_once 'Zend/Feed/Exception.php'; - $message = 'Invalid parameter: parameter \'height\'' - . ' must be an integer not exceeding 400'; + $message = 'Invalid parameter: parameter \'height\' must be an integer not exceeding 400'; $exception = new Zend_Feed_Exception($message); if (!$this->_ignoreExceptions) { throw $exception; @@ -388,8 +383,7 @@ protected function _setImage(DOMDocument $dom, DOMElement $root) if (isset($image['width'])) { if (!ctype_digit((string) $image['width']) || $image['width'] > 144) { require_once 'Zend/Feed/Exception.php'; - $message = 'Invalid parameter: parameter \'width\'' - . ' must be an integer not exceeding 144'; + $message = 'Invalid parameter: parameter \'width\' must be an integer not exceeding 144'; $exception = new Zend_Feed_Exception($message); if (!$this->_ignoreExceptions) { throw $exception; @@ -406,8 +400,7 @@ protected function _setImage(DOMDocument $dom, DOMElement $root) if (isset($image['description'])) { if (empty($image['description']) || !is_string($image['description'])) { require_once 'Zend/Feed/Exception.php'; - $message = 'Invalid parameter: parameter \'description\'' - . ' must be a non-empty string'; + $message = 'Invalid parameter: parameter \'description\' must be a non-empty string'; $exception = new Zend_Feed_Exception($message); if (!$this->_ignoreExceptions) { throw $exception; diff --git a/library/Zend/Feed/Writer/Renderer/RendererAbstract.php b/library/Zend/Feed/Writer/Renderer/RendererAbstract.php index 05a61bfdc1..94a2557b28 100644 --- a/library/Zend/Feed/Writer/Renderer/RendererAbstract.php +++ b/library/Zend/Feed/Writer/Renderer/RendererAbstract.php @@ -234,11 +234,7 @@ protected function _loadExtensions() { Zend_Feed_Writer::registerCoreExtensions(); $all = Zend_Feed_Writer::getExtensions(); - if (stripos(get_class($this), 'entry')) { - $exts = $all['entryRenderer']; - } else { - $exts = $all['feedRenderer']; - } + $exts = stripos(get_class($this), 'entry') ? $all['entryRenderer'] : $all['feedRenderer']; foreach ($exts as $extension) { $className = Zend_Feed_Writer::getPluginLoader()->getClassName($extension); $this->_extensions[$extension] = new $className( diff --git a/library/Zend/File/ClassFileLocator.php b/library/Zend/File/ClassFileLocator.php index 3dee60358f..ed8907fd38 100644 --- a/library/Zend/File/ClassFileLocator.php +++ b/library/Zend/File/ClassFileLocator.php @@ -90,7 +90,7 @@ public function accept() } // If not a PHP file, skip - if ($file->getBasename('.php') == $file->getBasename()) { + if ($file->getBasename('.php') === $file->getBasename()) { return false; } @@ -150,11 +150,7 @@ public function accept() // If a classname was found, set it in the object, and // return boolean true (found) if (!isset($namespace) || null === $namespace) { - if (isset($saveNamespace) && $saveNamespace) { - $namespace = $savedNamespace; - } else { - $namespace = null; - } + $namespace = isset($saveNamespace) && $saveNamespace ? $savedNamespace : null; } $class = (null === $namespace) ? $content : $namespace . '\\' . $content; @@ -169,10 +165,7 @@ public function accept() } } $classes = $file->getClasses(); - if (!empty($classes)) { - return true; - } // No class-type tokens found; return false - return false; + return !empty($classes); } } diff --git a/library/Zend/File/Transfer.php b/library/Zend/File/Transfer.php index 28e15271a6..474c275a80 100644 --- a/library/Zend/File/Transfer.php +++ b/library/Zend/File/Transfer.php @@ -109,11 +109,7 @@ public function getAdapter($direction = null) */ public function __call($method, array $options) { - if (array_key_exists('direction', $options)) { - $direction = (integer) $options['direction']; - } else { - $direction = 0; - } + $direction = array_key_exists('direction', $options) ? (integer) $options['direction'] : 0; if (method_exists($this->_adapter[$direction], $method)) { return call_user_func_array(array($this->_adapter[$direction], $method), $options); diff --git a/library/Zend/File/Transfer/Adapter/Abstract.php b/library/Zend/File/Transfer/Adapter/Abstract.php index 3266d06f87..3d3bf6539b 100644 --- a/library/Zend/File/Transfer/Adapter/Abstract.php +++ b/library/Zend/File/Transfer/Adapter/Abstract.php @@ -381,13 +381,13 @@ public function addValidators(array $validators, $files = null) foreach ($validators as $name => $validatorInfo) { if ($validatorInfo instanceof Zend_Validate_Interface) { $this->addValidator($validatorInfo, null, null, $files); - } else if (is_string($validatorInfo)) { + } elseif (is_string($validatorInfo)) { if (!is_int($name)) { $this->addValidator($name, null, $validatorInfo, $files); } else { $this->addValidator($validatorInfo, null, null, $files); } - } else if (is_array($validatorInfo)) { + } elseif (is_array($validatorInfo)) { $argc = count($validatorInfo); $breakChainOnFailure = false; $options = array(); @@ -396,36 +396,32 @@ public function addValidators(array $validators, $files = null) if (isset($validatorInfo['breakChainOnFailure'])) { $breakChainOnFailure = $validatorInfo['breakChainOnFailure']; } - if (isset($validatorInfo['options'])) { $options = $validatorInfo['options']; } - + $this->addValidator($validator, $breakChainOnFailure, $options, $files); + } elseif (is_string($name)) { + $validator = $name; + $options = $validatorInfo; $this->addValidator($validator, $breakChainOnFailure, $options, $files); } else { - if (is_string($name)) { - $validator = $name; - $options = $validatorInfo; - $this->addValidator($validator, $breakChainOnFailure, $options, $files); - } else { - $file = $files; - switch (true) { - case (0 == $argc): - break; - case (1 <= $argc): - $validator = array_shift($validatorInfo); - case (2 <= $argc): - $breakChainOnFailure = array_shift($validatorInfo); - case (3 <= $argc): - $options = array_shift($validatorInfo); - case (4 <= $argc): - if (!empty($validatorInfo)) { - $file = array_shift($validatorInfo); - } - default: - $this->addValidator($validator, $breakChainOnFailure, $options, $file); - break; - } + $file = $files; + switch (true) { + case (0 == $argc): + break; + case (1 <= $argc): + $validator = array_shift($validatorInfo); + case (2 <= $argc): + $breakChainOnFailure = array_shift($validatorInfo); + case (3 <= $argc): + $options = array_shift($validatorInfo); + case (4 <= $argc): + if (!empty($validatorInfo)) { + $file = array_shift($validatorInfo); + } + default: + $this->addValidator($validator, $breakChainOnFailure, $options, $file); + break; } } } else { @@ -598,12 +594,8 @@ public function setOptions($options = array(), $files = null) { public function getOptions($files = null) { $file = $this->_getFiles($files, false, true); - foreach ($file as $key => $content) { - if (isset($this->_files[$key]['options'])) { - $options[$key] = $this->_files[$key]['options']; - } else { - $options[$key] = array(); - } + foreach (array_keys($file) as $key) { + $options[$key] = isset($this->_files[$key]['options']) ? $this->_files[$key]['options'] : array(); } return $options; @@ -634,21 +626,15 @@ public function isValid($files = null) continue; } - if (array_key_exists('destination', $content)) { - $checkit = $content['destination']; - } else { - $checkit = dirname($content['tmp_name']); - } + $checkit = array_key_exists('destination', $content) ? $content['destination'] : dirname($content['tmp_name']); $checkit .= DIRECTORY_SEPARATOR . $content['name']; $validator->addFile($checkit); } } - if (isset($count)) { - if (!$validator->isValid($count['tmp_name'], $count)) { - $this->_messages += $validator->getMessages(); - } + if (isset($count) && !$validator->isValid($count['tmp_name'], $count)) { + $this->_messages += $validator->getMessages(); } foreach ($check as $key => $content) { @@ -664,49 +650,36 @@ public function isValid($files = null) $validator->setTranslator($translator); } - if (($class === 'Zend_Validate_File_Upload') and (empty($content['tmp_name']))) { - $tocheck = $key; - } else { - $tocheck = $content['tmp_name']; - } + $tocheck = ($class === 'Zend_Validate_File_Upload' && empty($content['tmp_name'])) ? $key : $content['tmp_name']; if (!$validator->isValid($tocheck, $content)) { $fileerrors += $validator->getMessages(); } - if (!empty($content['options']['ignoreNoFile']) and (isset($fileerrors['fileUploadErrorNoFile']))) { + if (!empty($content['options']['ignoreNoFile']) && isset($fileerrors['fileUploadErrorNoFile'])) { unset($fileerrors['fileUploadErrorNoFile']); break; } - if (($class === 'Zend_Validate_File_Upload') and (count($fileerrors) > 0)) { + if ($class === 'Zend_Validate_File_Upload' && count($fileerrors) > 0) { break; } - if (($this->_break[$class]) and (count($fileerrors) > 0)) { + if ($this->_break[$class] && count($fileerrors) > 0) { $break = true; break; } } } - if (count($fileerrors) > 0) { - $this->_files[$key]['validated'] = false; - } else { - $this->_files[$key]['validated'] = true; - } + $this->_files[$key]['validated'] = count($fileerrors) <= 0; $this->_messages += $fileerrors; if ($break) { break; } } - - if (count($this->_messages) > 0) { - return false; - } - - return true; + return !(count($this->_messages) > 0); } /** @@ -951,7 +924,7 @@ public function getFileName($file = null, $path = true) continue; } - if ($path === true) { + if ($path) { $directory = $this->getDestination($file) . DIRECTORY_SEPARATOR; } @@ -1046,12 +1019,12 @@ public function setDestination($destination, $files = null) } if ($files === null) { - foreach ($this->_files as $file => $content) { + foreach (array_keys($this->_files) as $file) { $this->_files[$file]['destination'] = $destination; } } else { $files = $this->_getFiles($files, true, true); - if (empty($files) and is_string($orig)) { + if (empty($files) && is_string($orig)) { $this->_files[$orig]['destination'] = $destination; } @@ -1075,7 +1048,7 @@ public function getDestination($files = null) $orig = $files; $files = $this->_getFiles($files, false, true); $destinations = array(); - if (empty($files) and is_string($orig)) { + if (empty($files) && is_string($orig)) { if (isset($this->_files[$orig]['destination'])) { $destinations[$orig] = $this->_files[$orig]['destination']; } else { @@ -1084,7 +1057,7 @@ public function getDestination($files = null) } } - foreach ($files as $key => $content) { + foreach (array_keys($files) as $key) { if (isset($this->_files[$key]['destination'])) { $destinations[$key] = $this->_files[$key]['destination']; } else { @@ -1096,7 +1069,7 @@ public function getDestination($files = null) if (empty($destinations)) { $destinations = $this->_getTmpDir(); - } else if (count($destinations) == 1) { + } elseif (count($destinations) == 1) { $destinations = current($destinations); } @@ -1112,7 +1085,7 @@ public function getDestination($files = null) */ public function setTranslator($translator = null) { - if (null === $translator) { + if (!$translator instanceof \Zend_Translate_Adapter) { $this->_translator = null; } elseif ($translator instanceof Zend_Translate_Adapter) { $this->_translator = $translator; @@ -1182,9 +1155,9 @@ public function getHash($hash = 'crc32', $files = null) foreach($files as $key => $value) { if (file_exists($value['name'])) { $result[$key] = hash_file($hash, $value['name']); - } else if (file_exists($value['tmp_name'])) { + } elseif (file_exists($value['tmp_name'])) { $result[$key] = hash_file($hash, $value['tmp_name']); - } else if (empty($value['options']['ignoreNoFile'])) { + } elseif (empty($value['options']['ignoreNoFile'])) { require_once 'Zend/File/Transfer/Exception.php'; throw new Zend_File_Transfer_Exception("The file '{$value['name']}' does not exist"); } @@ -1210,12 +1183,8 @@ public function getFileSize($files = null) $result = array(); foreach($files as $key => $value) { if (file_exists($value['name']) || file_exists($value['tmp_name'])) { - if ($value['options']['useByteString']) { - $result[$key] = self::_toByteString($value['size']); - } else { - $result[$key] = $value['size']; - } - } else if (empty($value['options']['ignoreNoFile'])) { + $result[$key] = $value['options']['useByteString'] ? self::_toByteString($value['size']) : $value['size']; + } elseif (empty($value['options']['ignoreNoFile'])) { require_once 'Zend/File/Transfer/Exception.php'; throw new Zend_File_Transfer_Exception("The file '{$value['name']}' does not exist"); } else { @@ -1240,7 +1209,7 @@ protected function _detectFileSize($value) { if (file_exists($value['name'])) { $result = sprintf("%u", @filesize($value['name'])); - } else if (file_exists($value['tmp_name'])) { + } elseif (file_exists($value['tmp_name'])) { $result = sprintf("%u", @filesize($value['tmp_name'])); } else { return null; @@ -1264,7 +1233,7 @@ public function getMimeType($files = null) foreach($files as $key => $value) { if (file_exists($value['name']) || file_exists($value['tmp_name'])) { $result[$key] = $value['type']; - } else if (empty($value['options']['ignoreNoFile'])) { + } elseif (empty($value['options']['ignoreNoFile'])) { require_once 'Zend/File/Transfer/Exception.php'; throw new Zend_File_Transfer_Exception("The file '{$value['name']}' does not exist"); } else { @@ -1289,7 +1258,7 @@ protected function _detectMimeType($value) { if (file_exists($value['name'])) { $file = $value['name']; - } else if (file_exists($value['tmp_name'])) { + } elseif (file_exists($value['tmp_name'])) { $file = $value['tmp_name']; } else { return null; @@ -1364,12 +1333,7 @@ protected function _filter($files = null) } } } - - if (count($this->_messages) > 0) { - return false; - } - - return true; + return !($this->_messages !== []); } /** @@ -1435,7 +1399,7 @@ protected function _getTmpDir() protected function _isPathWriteable($path) { $tempFile = rtrim($path, "/\\"); - $tempFile .= '/' . 'test.1'; + $tempFile .= '/test.1'; $result = @file_put_contents($tempFile, 'TEST'); @@ -1444,12 +1408,7 @@ protected function _isPathWriteable($path) } $result = @unlink($tempFile); - - if ($result == false) { - return false; - } - - return true; + return !($result == false); } /** @@ -1496,7 +1455,7 @@ protected function _getFiles($files, $names = false, $noexception = false) } if (empty($found)) { - if ($noexception !== false) { + if ($noexception) { return array(); } @@ -1540,7 +1499,7 @@ protected function _getValidatorIdentifier($name) } foreach (array_keys($this->_validators) as $test) { - if (preg_match('/' . preg_quote($name) . '$/i', (string) $test)) { + if (preg_match('/' . preg_quote($name, '/') . '$/i', (string) $test)) { return $test; } } @@ -1561,7 +1520,7 @@ protected function _getFilterIdentifier($name) } foreach (array_keys($this->_filters) as $test) { - if (preg_match('/' . preg_quote($name) . '$/i', (string) $test)) { + if (preg_match('/' . preg_quote($name, '/') . '$/i', (string) $test)) { return $test; } } diff --git a/library/Zend/File/Transfer/Adapter/Http.php b/library/Zend/File/Transfer/Adapter/Http.php index 2265e4ff1a..829ba0abc8 100644 --- a/library/Zend/File/Transfer/Adapter/Http.php +++ b/library/Zend/File/Transfer/Adapter/Http.php @@ -121,14 +121,14 @@ public function isValid($files = null) $content = 0; if (isset($_SERVER['CONTENT_LENGTH'])) { $content = $_SERVER['CONTENT_LENGTH']; - } else if (!empty($_POST)) { + } elseif (!empty($_POST)) { $content = serialize($_POST); } // Workaround for a PHP error returning empty $_FILES when form data exceeds php settings if (empty($this->_files) && ($content > 0)) { if (is_array($files)) { - if (0 === count($files)) { + if ([] === $files) { return false; } @@ -306,7 +306,7 @@ public function isUploaded($files = null) */ public static function getProgress($id = null) { - if (!function_exists('apc_fetch') and !function_exists('uploadprogress_get_info')) { + if (!function_exists('apc_fetch') && !function_exists('uploadprogress_get_info')) { require_once 'Zend/File/Transfer/Exception.php'; throw new Zend_File_Transfer_Exception('Neither APC nor uploadprogress extension installed'); } @@ -352,12 +352,11 @@ public static function getProgress($id = null) if (!empty($id)) { if (self::isApcAvailable()) { - $call = call_user_func(self::$_callbackApc, ini_get('apc.rfc1867_prefix') . $id); if (is_array($call)) { $status = $call + $status; } - } else if (self::isUploadProgressAvailable()) { + } elseif (self::isUploadProgressAvailable()) { $call = call_user_func(self::$_callbackUploadProgress, $id); if (is_array($call)) { $status = $call + $status; @@ -373,7 +372,7 @@ public static function getProgress($id = null) if (!is_array($call)) { $status['done'] = true; $status['message'] = 'Failure while retrieving the upload progress'; - } else if (!empty($status['cancel_upload'])) { + } elseif (!empty($status['cancel_upload'])) { $status['done'] = true; $status['message'] = 'The upload has been canceled'; } else { diff --git a/library/Zend/Filter.php b/library/Zend/Filter.php index 1256ff9bd6..94bac63282 100644 --- a/library/Zend/Filter.php +++ b/library/Zend/Filter.php @@ -225,11 +225,7 @@ public static function filterStatic($value, $classBaseName, array $args = array( $class = new ReflectionClass($className); if ($class->implementsInterface('Zend_Filter_Interface')) { - if ($class->hasMethod('__construct')) { - $object = $class->newInstanceArgs($args); - } else { - $object = $class->newInstance(); - } + $object = $class->hasMethod('__construct') ? $class->newInstanceArgs($args) : $class->newInstance(); return $object->filter($value); } } diff --git a/library/Zend/Filter/Alnum.php b/library/Zend/Filter/Alnum.php index 7455dafe45..0bca2a8ec4 100644 --- a/library/Zend/Filter/Alnum.php +++ b/library/Zend/Filter/Alnum.php @@ -75,17 +75,13 @@ public function __construct($allowWhiteSpace = false) { if ($allowWhiteSpace instanceof Zend_Config) { $allowWhiteSpace = $allowWhiteSpace->toArray(); - } else if (is_array($allowWhiteSpace)) { - if (array_key_exists('allowwhitespace', $allowWhiteSpace)) { - $allowWhiteSpace = $allowWhiteSpace['allowwhitespace']; - } else { - $allowWhiteSpace = false; - } + } elseif (is_array($allowWhiteSpace)) { + $allowWhiteSpace = array_key_exists('allowwhitespace', $allowWhiteSpace) ? $allowWhiteSpace['allowwhitespace'] : false; } $this->allowWhiteSpace = (boolean) $allowWhiteSpace; if (null === self::$_unicodeEnabled) { - self::$_unicodeEnabled = (@preg_match('/\pL/u', 'a')) ? true : false; + self::$_unicodeEnabled = (bool) @preg_match('/\pL/u', 'a'); } if (null === self::$_meansEnglishAlphabet) { @@ -133,13 +129,7 @@ public function filter($value) if (!self::$_unicodeEnabled) { // POSIX named classes are not supported, use alternative a-zA-Z0-9 match $pattern = '/[^a-zA-Z0-9' . $whiteSpace . ']/'; - } else if (self::$_meansEnglishAlphabet) { - //The Alphabet means english alphabet. - $pattern = '/[^a-zA-Z0-9' . $whiteSpace . ']/u'; - } else { - //The Alphabet means each language's alphabet. - $pattern = '/[^\p{L}\p{N}' . $whiteSpace . ']/u'; - } + } else $pattern = self::$_meansEnglishAlphabet ? '/[^a-zA-Z0-9' . $whiteSpace . ']/u' : '/[^\p{L}\p{N}' . $whiteSpace . ']/u'; return preg_replace($pattern, '', (string) $value); } diff --git a/library/Zend/Filter/Alpha.php b/library/Zend/Filter/Alpha.php index 7374da1665..1665c6261f 100644 --- a/library/Zend/Filter/Alpha.php +++ b/library/Zend/Filter/Alpha.php @@ -75,17 +75,13 @@ public function __construct($allowWhiteSpace = false) { if ($allowWhiteSpace instanceof Zend_Config) { $allowWhiteSpace = $allowWhiteSpace->toArray(); - } else if (is_array($allowWhiteSpace)) { - if (array_key_exists('allowwhitespace', $allowWhiteSpace)) { - $allowWhiteSpace = $allowWhiteSpace['allowwhitespace']; - } else { - $allowWhiteSpace = false; - } + } elseif (is_array($allowWhiteSpace)) { + $allowWhiteSpace = array_key_exists('allowwhitespace', $allowWhiteSpace) ? $allowWhiteSpace['allowwhitespace'] : false; } $this->allowWhiteSpace = (boolean) $allowWhiteSpace; if (null === self::$_unicodeEnabled) { - self::$_unicodeEnabled = (@preg_match('/\pL/u', 'a')) ? true : false; + self::$_unicodeEnabled = (bool) @preg_match('/\pL/u', 'a'); } if (null === self::$_meansEnglishAlphabet) { @@ -133,13 +129,7 @@ public function filter($value) if (!self::$_unicodeEnabled) { // POSIX named classes are not supported, use alternative a-zA-Z match $pattern = '/[^a-zA-Z' . $whiteSpace . ']/'; - } else if (self::$_meansEnglishAlphabet) { - //The Alphabet means english alphabet. - $pattern = '/[^a-zA-Z' . $whiteSpace . ']/u'; - } else { - //The Alphabet means each language's alphabet. - $pattern = '/[^\p{L}' . $whiteSpace . ']/u'; - } + } else $pattern = self::$_meansEnglishAlphabet ? '/[^a-zA-Z' . $whiteSpace . ']/u' : '/[^\p{L}' . $whiteSpace . ']/u'; return preg_replace($pattern, '', (string) $value); } diff --git a/library/Zend/Filter/Boolean.php b/library/Zend/Filter/Boolean.php index 1388629caf..e710b407e9 100644 --- a/library/Zend/Filter/Boolean.php +++ b/library/Zend/Filter/Boolean.php @@ -247,11 +247,11 @@ public function filter($value) require_once 'Zend/Locale.php'; $locales = $this->getLocale(); foreach ($locales as $locale) { - if ($this->_getLocalizedQuestion($value, false, $locale) === false) { + if (!$this->_getLocalizedQuestion($value, false, $locale)) { return false; } - if (!$casting && ($this->_getLocalizedQuestion($value, true, $locale) === true)) { + if (!$casting && ($this->_getLocalizedQuestion($value, true, $locale))) { return true; } } @@ -366,7 +366,7 @@ protected function _getLocalizedQuestion($value, $yes, $locale) $str = explode(':', (string) $str); if (!empty($str)) { foreach($str as $no) { - if (($no == $value) || (strtolower($no) == strtolower($value))) { + if (($no === $value) || (strtolower($no) === strtolower($value))) { return $return; } } diff --git a/library/Zend/Filter/Callback.php b/library/Zend/Filter/Callback.php index f7961ea511..a6d9dfd4e1 100644 --- a/library/Zend/Filter/Callback.php +++ b/library/Zend/Filter/Callback.php @@ -56,13 +56,12 @@ public function __construct($options) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (!is_array($options) || !array_key_exists('callback', $options)) { + } elseif (!is_array($options) || !array_key_exists('callback', $options)) { $options = func_get_args(); $temp['callback'] = array_shift($options); if (!empty($options)) { $temp['options'] = array_shift($options); } - $options = $temp; } @@ -138,11 +137,7 @@ public function filter($value) $options = array(); if ($this->_options !== null) { - if (!is_array($this->_options)) { - $options = array($this->_options); - } else { - $options = $this->_options; - } + $options = is_array($this->_options) ? $this->_options : array($this->_options); } array_unshift($options, $value); diff --git a/library/Zend/Filter/Compress/CompressAbstract.php b/library/Zend/Filter/Compress/CompressAbstract.php index 2b20ac6f07..f4abb8f2b4 100644 --- a/library/Zend/Filter/Compress/CompressAbstract.php +++ b/library/Zend/Filter/Compress/CompressAbstract.php @@ -34,6 +34,10 @@ */ abstract class Zend_Filter_Compress_CompressAbstract implements Zend_Filter_Compress_CompressInterface { + /** + * @var array|mixed + */ + public $_options; /** * Class constructor * diff --git a/library/Zend/Filter/Compress/Gz.php b/library/Zend/Filter/Compress/Gz.php index 819795c5c9..3df0ab641a 100644 --- a/library/Zend/Filter/Compress/Gz.php +++ b/library/Zend/Filter/Compress/Gz.php @@ -154,11 +154,10 @@ public function compress($content) require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception("Error opening the archive '" . $this->_options['archive'] . "'"); } - gzwrite($file, $content); gzclose($file); $compressed = true; - } else if ($this->_options['mode'] == 'deflate') { + } elseif ($this->_options['mode'] == 'deflate') { $compressed = gzdeflate($content, $this->getLevel()); } else { $compressed = gzcompress($content, $this->getLevel()); @@ -202,11 +201,7 @@ public function decompress($content) $file = gzopen($archive, 'r'); $compressed = gzread($file, $size); gzclose($file); - } else if ($mode == 'deflate') { - $compressed = gzinflate($content); - } else { - $compressed = gzuncompress($content); - } + } else $compressed = $mode == 'deflate' ? gzinflate($content) : gzuncompress($content); if (!$compressed) { require_once 'Zend/Filter/Exception.php'; diff --git a/library/Zend/Filter/Compress/Lzf.php b/library/Zend/Filter/Compress/Lzf.php index 33115105a0..407b28ac76 100644 --- a/library/Zend/Filter/Compress/Lzf.php +++ b/library/Zend/Filter/Compress/Lzf.php @@ -54,7 +54,7 @@ public function __construct() public function compress($content) { $compressed = lzf_compress($content); - if (!$compressed) { + if ($compressed === '' || $compressed === '0') { require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception('Error during compression'); } @@ -71,7 +71,7 @@ public function compress($content) public function decompress($content) { $compressed = lzf_decompress($content); - if (!$compressed) { + if ($compressed === '' || $compressed === '0') { require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception('Error during compression'); } diff --git a/library/Zend/Filter/Compress/Rar.php b/library/Zend/Filter/Compress/Rar.php index 934cd03162..1af84321aa 100644 --- a/library/Zend/Filter/Compress/Rar.php +++ b/library/Zend/Filter/Compress/Rar.php @@ -210,11 +210,7 @@ public function decompress($content) } $password = $this->getPassword(); - if ($password !== null) { - $archive = rar_open($archive, $password); - } else { - $archive = rar_open($archive); - } + $archive = $password !== null ? rar_open($archive, $password) : rar_open($archive); if (!$archive) { require_once 'Zend/Filter/Exception.php'; diff --git a/library/Zend/Filter/Compress/Zip.php b/library/Zend/Filter/Compress/Zip.php index 9c71a88444..048390928f 100644 --- a/library/Zend/Filter/Compress/Zip.php +++ b/library/Zend/Filter/Compress/Zip.php @@ -149,7 +149,7 @@ public function compress($content) } if (is_dir($current . $node)) { - array_push($stack, $current . $node . DIRECTORY_SEPARATOR); + $stack[] = $current . $node . DIRECTORY_SEPARATOR; } if (is_file($current . $node)) { @@ -162,7 +162,7 @@ public function compress($content) foreach ($files as $file) { $zip->addFile($current . $file, $local . $file); - if ($res !== true) { + if (!$res) { require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception($this->_errorString($res)); } @@ -170,21 +170,17 @@ public function compress($content) } } else { $res = $zip->addFile($content, $basename); - if ($res !== true) { + if (!$res) { require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception($this->_errorString($res)); } } } else { $file = $this->getTarget(); - if (!is_dir($file)) { - $file = basename($file); - } else { - $file = "zip.tmp"; - } + $file = is_dir($file) ? "zip.tmp" : basename($file); $res = $zip->addFromString($file, $content); - if ($res !== true) { + if (!$res) { require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception($this->_errorString($res)); } @@ -252,7 +248,7 @@ public function decompress($content) } $res = @$zip->extractTo($target); - if ($res !== true) { + if (!$res) { require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception($this->_errorString($res)); } diff --git a/library/Zend/Filter/Digits.php b/library/Zend/Filter/Digits.php index 01c3ed5a73..1ee833fa50 100644 --- a/library/Zend/Filter/Digits.php +++ b/library/Zend/Filter/Digits.php @@ -52,7 +52,7 @@ class Zend_Filter_Digits implements Zend_Filter_Interface public function __construct() { if (null === self::$_unicodeEnabled) { - self::$_unicodeEnabled = (@preg_match('/\pL/u', 'a')) ? true : false; + self::$_unicodeEnabled = (bool) @preg_match('/\pL/u', 'a'); } } @@ -69,13 +69,7 @@ public function filter($value) if (!self::$_unicodeEnabled) { // POSIX named classes are not supported, use alternative 0-9 match $pattern = '/[^0-9]/'; - } else if (extension_loaded('mbstring')) { - // Filter for the value with mbstring - $pattern = '/[^[:digit:]]/'; - } else { - // Filter for the value without mbstring - $pattern = '/[\p{^N}]/'; - } + } else $pattern = extension_loaded('mbstring') ? '/[^[:digit:]]/' : '/[\p{^N}]/'; return preg_replace($pattern, '', (string) $value); } diff --git a/library/Zend/Filter/Encrypt.php b/library/Zend/Filter/Encrypt.php index 881c9489f7..797521931c 100644 --- a/library/Zend/Filter/Encrypt.php +++ b/library/Zend/Filter/Encrypt.php @@ -78,7 +78,7 @@ public function setAdapter($options = null) { if (is_string($options)) { $adapter = $options; - } else if (isset($options['adapter'])) { + } elseif (isset($options['adapter'])) { $adapter = $options['adapter']; unset($options['adapter']); } else { @@ -115,7 +115,7 @@ public function setAdapter($options = null) public function __call($method, $options) { $part = substr($method, 0, 3); - if ((($part != 'get') and ($part != 'set')) or !method_exists($this->_adapter, $method)) { + if ($part != 'get' && $part != 'set' || !method_exists($this->_adapter, $method)) { require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception("Unknown method '{$method}'"); } diff --git a/library/Zend/Filter/Encrypt/Mcrypt.php b/library/Zend/Filter/Encrypt/Mcrypt.php index 1acd2aa5af..22d8374d21 100644 --- a/library/Zend/Filter/Encrypt/Mcrypt.php +++ b/library/Zend/Filter/Encrypt/Mcrypt.php @@ -122,7 +122,7 @@ public function setEncryption($options) throw new Zend_Filter_Exception('Invalid options argument provided to filter'); } - $options = $options + $this->getEncryption(); + $options += $this->getEncryption(); $algorithms = mcrypt_list_algorithms($options['algorithm_directory']); if (!in_array($options['algorithm'], $algorithms)) { require_once 'Zend/Filter/Exception.php'; @@ -174,17 +174,15 @@ public function setVector($vector = null) $this->_srand(); if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && version_compare(PHP_VERSION, '5.3.0', '<')) { $method = MCRYPT_RAND; + } elseif (file_exists('/dev/urandom') || (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')) { + $method = MCRYPT_DEV_URANDOM; + } elseif (file_exists('/dev/random')) { + $method = MCRYPT_DEV_RANDOM; } else { - if (file_exists('/dev/urandom') || (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')) { - $method = MCRYPT_DEV_URANDOM; - } elseif (file_exists('/dev/random')) { - $method = MCRYPT_DEV_RANDOM; - } else { - $method = MCRYPT_RAND; - } + $method = MCRYPT_RAND; } $vector = mcrypt_create_iv($size, $method); - } else if (strlen($vector) != $size) { + } elseif (strlen($vector) != $size) { require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception('The given vector has a wrong size for the set algorithm'); } @@ -334,7 +332,7 @@ protected function _initCipher($cipher) $this->_srand(); $keysize = mcrypt_enc_get_key_size($cipher); $key = substr(md5($key), 0, $keysize); - } else if (!in_array(strlen((string) $key), $keysizes)) { + } elseif (!in_array(strlen((string) $key), $keysizes)) { require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception('The given key has a wrong size for the set algorithm'); } diff --git a/library/Zend/Filter/Encrypt/Openssl.php b/library/Zend/Filter/Encrypt/Openssl.php index bd57bfe802..fdba14bfe6 100644 --- a/library/Zend/Filter/Encrypt/Openssl.php +++ b/library/Zend/Filter/Encrypt/Openssl.php @@ -176,8 +176,7 @@ protected function _setKeys($keys) */ public function getPublicKey() { - $key = $this->_keys['public']; - return $key; + return $this->_keys['public']; } /** @@ -209,8 +208,7 @@ public function setPublicKey($key) */ public function getPrivateKey() { - $key = $this->_keys['private']; - return $key; + return $this->_keys['private']; } /** @@ -247,8 +245,7 @@ public function setPrivateKey($key, $passphrase = null) */ public function getEnvelopeKey() { - $key = $this->_keys['envelope']; - return $key; + return $this->_keys['envelope']; } /** @@ -439,11 +436,7 @@ public function decrypt($value) if ($this->_package) { $details = openssl_pkey_get_details($keys); - if ($details !== false) { - $fingerprint = md5($details['key']); - } else { - $fingerprint = md5("ZendFramework"); - } + $fingerprint = $details !== false ? md5($details['key']) : md5("ZendFramework"); $count = unpack('ncount', $value); $count = $count['count']; @@ -465,7 +458,7 @@ public function decrypt($value) $crypt = openssl_open($value, $decrypted, $envelope, $keys); openssl_free_key($keys); - if ($crypt === false) { + if (!$crypt) { require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception('Openssl was not able to decrypt you content with the given options'); } diff --git a/library/Zend/Filter/File/Decrypt.php b/library/Zend/Filter/File/Decrypt.php index 9e167d90ec..b1ef31f8a4 100644 --- a/library/Zend/Filter/File/Decrypt.php +++ b/library/Zend/Filter/File/Decrypt.php @@ -78,11 +78,11 @@ public function filter($value) throw new Zend_Filter_Exception("File '$value' not found"); } - if (!isset($this->_filename)) { + if (!($this->_filename !== null)) { $this->_filename = $value; } - if (file_exists($this->_filename) and !is_writable($this->_filename)) { + if (file_exists($this->_filename) && !is_writable($this->_filename)) { require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception("File '{$this->_filename}' is not writable"); } diff --git a/library/Zend/Filter/File/Encrypt.php b/library/Zend/Filter/File/Encrypt.php index 23c71b4b0a..3fbd01df74 100644 --- a/library/Zend/Filter/File/Encrypt.php +++ b/library/Zend/Filter/File/Encrypt.php @@ -78,11 +78,11 @@ public function filter($value) throw new Zend_Filter_Exception("File '$value' not found"); } - if (!isset($this->_filename)) { + if (!($this->_filename !== null)) { $this->_filename = $value; } - if (file_exists($this->_filename) and !is_writable($this->_filename)) { + if (file_exists($this->_filename) && !is_writable($this->_filename)) { require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception("File '{$this->_filename}' is not writable"); } diff --git a/library/Zend/Filter/File/Rename.php b/library/Zend/Filter/File/Rename.php index 80a5cfb8aa..3aed1fe897 100644 --- a/library/Zend/Filter/File/Rename.php +++ b/library/Zend/Filter/File/Rename.php @@ -274,11 +274,9 @@ protected function _getFileName($file) { $rename = array(); foreach ($this->_files as $value) { - if ($value['source'] == '*') { - if (!isset($rename['source'])) { - $rename = $value; - $rename['source'] = $file; - } + if ($value['source'] == '*' && !isset($rename['source'])) { + $rename = $value; + $rename['source'] = $file; } if ($value['source'] == $file) { @@ -290,14 +288,14 @@ protected function _getFileName($file) return $file; } - if (!isset($rename['target']) or ($rename['target'] == '*')) { + if (!isset($rename['target']) || $rename['target'] == '*') { $rename['target'] = $rename['source']; } if (is_dir($rename['target'])) { $name = basename($rename['source']); $last = $rename['target'][strlen((string) $rename['target']) - 1]; - if (($last != '/') and ($last != '\\')) { + if ($last != '/' && $last != '\\') { $rename['target'] .= DIRECTORY_SEPARATOR; } diff --git a/library/Zend/Filter/HtmlEntities.php b/library/Zend/Filter/HtmlEntities.php index 0c1dfecb95..971bc12f15 100644 --- a/library/Zend/Filter/HtmlEntities.php +++ b/library/Zend/Filter/HtmlEntities.php @@ -64,13 +64,12 @@ public function __construct($options = array()) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (!is_array($options)) { + } elseif (!is_array($options)) { $options = func_get_args(); $temp['quotestyle'] = array_shift($options); if (!empty($options)) { $temp['charset'] = array_shift($options); } - $options = $temp; } @@ -206,7 +205,7 @@ public function filter($value) $enc = $this->getEncoding(); $value = iconv('', $enc . '//IGNORE', (string) $value); $filtered = htmlentities($value, $this->getQuoteStyle(), $enc, $this->getDoubleQuote()); - if (!strlen($filtered)) { + if ($filtered === '') { require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception('Encoding mismatch has resulted in htmlentities errors'); } diff --git a/library/Zend/Filter/Inflector.php b/library/Zend/Filter/Inflector.php index e50afe8978..b2fad3198e 100644 --- a/library/Zend/Filter/Inflector.php +++ b/library/Zend/Filter/Inflector.php @@ -74,26 +74,21 @@ public function __construct($options = null) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (!is_array($options)) { + } elseif (!is_array($options)) { $options = func_get_args(); $temp = array(); - if (!empty($options)) { $temp['target'] = array_shift($options); } - if (!empty($options)) { $temp['rules'] = array_shift($options); } - if (!empty($options)) { $temp['throwTargetExceptionsOn'] = array_shift($options); } - if (!empty($options)) { $temp['targetReplacementIdentifier'] = array_shift($options); } - $options = $temp; } @@ -150,11 +145,9 @@ public function setOptions($options) { } // Set Präfix Path - if (array_key_exists('filterPrefixPath', $options)) { - if (!is_scalar($options['filterPrefixPath'])) { - foreach ($options['filterPrefixPath'] as $prefix => $path) { - $this->addFilterPrefixPath($prefix, $path); - } + if (array_key_exists('filterPrefixPath', $options) && !is_scalar($options['filterPrefixPath'])) { + foreach ($options['filterPrefixPath'] as $prefix => $path) { + $this->addFilterPrefixPath($prefix, $path); } } @@ -199,7 +192,7 @@ public function addFilterPrefixPath($prefix, $path) */ public function setThrowTargetExceptionsOn($throwTargetExceptionsOn) { - $this->_throwTargetExceptionsOn = ($throwTargetExceptionsOn == true) ? true : false; + $this->_throwTargetExceptionsOn = $throwTargetExceptionsOn == true; return $this; } @@ -221,7 +214,7 @@ public function isThrowTargetExceptionsOn() */ public function setTargetReplacementIdentifier($targetReplacementIdentifier) { - if ($targetReplacementIdentifier) { + if ($targetReplacementIdentifier !== '' && $targetReplacementIdentifier !== '0') { $this->_targetReplacementIdentifier = (string) $targetReplacementIdentifier; } @@ -349,10 +342,8 @@ public function getRules($spec = null) public function getRule($spec, $index) { $spec = $this->_normalizeSpec($spec); - if (isset($this->_rules[$spec]) && is_array($this->_rules[$spec])) { - if (isset($this->_rules[$spec][$index])) { - return $this->_rules[$spec][$index]; - } + if (isset($this->_rules[$spec]) && is_array($this->_rules[$spec]) && isset($this->_rules[$spec][$index])) { + return $this->_rules[$spec][$index]; } return false; } diff --git a/library/Zend/Filter/Input.php b/library/Zend/Filter/Input.php index c3229fa6fb..7731e1a688 100644 --- a/library/Zend/Filter/Input.php +++ b/library/Zend/Filter/Input.php @@ -441,7 +441,7 @@ public function isValid($fieldName = null) { $this->_process(); if ($fieldName === null) { - return !($this->hasMissing() || $this->hasInvalid()); + return !$this->hasMissing() && !$this->hasInvalid(); } return array_key_exists($fieldName, $this->_validFields); } @@ -601,7 +601,7 @@ public function getTranslator() return null; } - if ($this->_translator === null) { + if (!$this->_translator instanceof \Zend_Translate_Adapter) { require_once 'Zend/Registry.php'; if (Zend_Registry::isRegistered('Zend_Translate')) { $translator = Zend_Registry::get('Zend_Translate'); @@ -752,8 +752,7 @@ protected function _getMissingMessage($rule, $field) } $message = str_replace('%rule%', $rule, $message); - $message = str_replace('%field%', $field, $message); - return $message; + return str_replace('%field%', $field, $message); } /** @@ -772,8 +771,7 @@ protected function _getNotEmptyMessage($rule, $field) } $message = str_replace('%rule%', $rule, $message); - $message = str_replace('%field%', $field, $message); - return $message; + return str_replace('%field%', $field, $message); } /** @@ -781,7 +779,7 @@ protected function _getNotEmptyMessage($rule, $field) */ protected function _process() { - if ($this->_processed === false) { + if (!$this->_processed) { $this->_filter(); $this->_validate(); $this->_processed = true; @@ -874,26 +872,21 @@ protected function _validate() } } - if (!$foundNotEmptyValidator) { - $validatorRule[self::ALLOW_EMPTY] = $this->_defaults[self::ALLOW_EMPTY]; - } else { - $validatorRule[self::ALLOW_EMPTY] = false; - } + $validatorRule[self::ALLOW_EMPTY] = $foundNotEmptyValidator ? false : $this->_defaults[self::ALLOW_EMPTY]; } if (!isset($validatorRule[self::MESSAGES])) { $validatorRule[self::MESSAGES] = array(); - } else if (!is_array($validatorRule[self::MESSAGES])) { + } elseif (!is_array($validatorRule[self::MESSAGES])) { $validatorRule[self::MESSAGES] = array($validatorRule[self::MESSAGES]); - } else if (array_intersect_key($validatorList, $validatorRule[self::MESSAGES])) { + } elseif (array_intersect_key($validatorList, $validatorRule[self::MESSAGES])) { // this seems pointless... it just re-adds what it already has... // I can disable all this and not a single unit test fails... // There are now corresponding numeric keys in the validation rule messages array // Treat it as a named messages list for all rule validators $unifiedMessages = $validatorRule[self::MESSAGES]; $validatorRule[self::MESSAGES] = array(); - - foreach ($validatorList as $key => $validator) { + foreach (array_keys($validatorList) as $key) { if (array_key_exists($key, $unifiedMessages)) { $validatorRule[self::MESSAGES][$key] = $unifiedMessages[$key]; } @@ -968,7 +961,7 @@ protected function _validate() unset($this->_data[$field]); } } - foreach ($this->_validFields as $field => $value) { + foreach (array_keys($this->_validFields) as $field) { unset($this->_data[$field]); } @@ -992,23 +985,20 @@ protected function _validateRule(array $validatorRule) foreach ((array) $validatorRule[self::FIELDS] as $key => $field) { if (array_key_exists($field, $this->_data)) { $data[$field] = $this->_data[$field]; - } else if (isset($validatorRule[self::DEFAULT_VALUE])) { + } elseif (isset($validatorRule[self::DEFAULT_VALUE])) { /** @todo according to this code default value can't be an array. It has to be reviewed */ if (!is_array($validatorRule[self::DEFAULT_VALUE])) { // Default value is a scalar $data[$field] = $validatorRule[self::DEFAULT_VALUE]; - } else { - // Default value is an array. Search for corresponding key - if (isset($validatorRule[self::DEFAULT_VALUE][$key])) { - $data[$field] = $validatorRule[self::DEFAULT_VALUE][$key]; - } else if ($validatorRule[self::PRESENCE] == self::PRESENCE_REQUIRED) { - // Default value array is provided, but it doesn't have an entry for current field - // and presence is required - $this->_missingFields[$validatorRule[self::RULE]][] = - $this->_getMissingMessage($validatorRule[self::RULE], $field); - } + } elseif (isset($validatorRule[self::DEFAULT_VALUE][$key])) { + $data[$field] = $validatorRule[self::DEFAULT_VALUE][$key]; + } elseif ($validatorRule[self::PRESENCE] == self::PRESENCE_REQUIRED) { + // Default value array is provided, but it doesn't have an entry for current field + // and presence is required + $this->_missingFields[$validatorRule[self::RULE]][] = + $this->_getMissingMessage($validatorRule[self::RULE], $field); } - } else if ($validatorRule[self::PRESENCE] == self::PRESENCE_REQUIRED) { + } elseif ($validatorRule[self::PRESENCE] == self::PRESENCE_REQUIRED) { $this->_missingFields[$validatorRule[self::RULE]][] = $this->_getMissingMessage($validatorRule[self::RULE], $field); } @@ -1056,29 +1046,25 @@ protected function _validateRule(array $validatorRule) return; } } - if (!$validatorRule[self::VALIDATOR_CHAIN]->isValid($data)) { $this->_invalidMessages[$validatorRule[self::RULE]] = $validatorRule[self::VALIDATOR_CHAIN]->getMessages(); $this->_invalidErrors[$validatorRule[self::RULE]] = $validatorRule[self::VALIDATOR_CHAIN]->getErrors(); return; } - } else if (count($data) > 0) { + } elseif ($data !== []) { // $data is actually a one element array $fieldNames = array_keys($data); $fieldName = reset($fieldNames); $field = reset($data); - $failed = false; if (!is_array($field)) { $field = array($field); } - // if there is no Zend_Validate_NotEmpty instance in the rules, we will use the default if (!($notEmptyValidator = $this->_getNotEmptyValidatorInstance($validatorRule))) { $notEmptyValidator = $this->_getValidator('NotEmpty'); $notEmptyValidator->setMessage($this->_getNotEmptyMessage($validatorRule[self::RULE], $fieldName)); } - if ($validatorRule[self::ALLOW_EMPTY]) { $validatorChain = $validatorRule[self::VALIDATOR_CHAIN]; } else { @@ -1086,7 +1072,6 @@ protected function _validateRule(array $validatorRule) $validatorChain->addValidator($notEmptyValidator, true /* Always break on failure */); $validatorChain->addValidator($validatorRule[self::VALIDATOR_CHAIN]); } - foreach ($field as $key => $value) { if ($validatorRule[self::ALLOW_EMPTY] && !$notEmptyValidator->isValid($value)) { // Field is empty AND it's allowed. Do nothing. @@ -1109,12 +1094,7 @@ protected function _validateRule(array $validatorRule) } $this->_invalidMessages[$validatorRule[self::RULE]] = $collectedMessages; - if (isset($this->_invalidErrors[$validatorRule[self::RULE]])) { - $this->_invalidErrors[$validatorRule[self::RULE]] = array_merge($this->_invalidErrors[$validatorRule[self::RULE]], - $validatorChain->getErrors()); - } else { - $this->_invalidErrors[$validatorRule[self::RULE]] = $validatorChain->getErrors(); - } + $this->_invalidErrors[$validatorRule[self::RULE]] = array_merge($this->_invalidErrors[$validatorRule[self::RULE]] ?? [], $validatorChain->getErrors()); unset($this->_validFields[$fieldName]); $failed = true; if ($validatorRule[self::BREAK_CHAIN]) { @@ -1146,7 +1126,7 @@ protected function _validateRule(array $validatorRule) */ protected function _getNotEmptyValidatorInstance($validatorRule) { foreach ($validatorRule as $rule => $value) { - if (is_object($value) and $value instanceof Zend_Validate_NotEmpty) { + if (is_object($value) && $value instanceof Zend_Validate_NotEmpty) { return $value; } } @@ -1197,13 +1177,7 @@ protected function _getFilterOrValidator($type, $classBaseName) throw new Zend_Filter_Exception("Class '$className' based on basename '$classBaseName' must implement the '$interfaceName' interface"); } - if ($class->hasMethod('__construct')) { - $object = $class->newInstanceArgs($args); - } else { - $object = $class->newInstance(); - } - - return $object; + return $class->hasMethod('__construct') ? $class->newInstanceArgs($args) : $class->newInstance(); } } diff --git a/library/Zend/Filter/LocalizedToNormalized.php b/library/Zend/Filter/LocalizedToNormalized.php index 8e83321542..d3aacd6ebe 100644 --- a/library/Zend/Filter/LocalizedToNormalized.php +++ b/library/Zend/Filter/LocalizedToNormalized.php @@ -99,10 +99,10 @@ public function filter($value) { if (Zend_Locale_Format::isNumber($value, $this->_options)) { return Zend_Locale_Format::getNumber($value, $this->_options); - } else if (($this->_options['date_format'] === null) && (strpos($value, ':') !== false)) { + } elseif (($this->_options['date_format'] === null) && (strpos($value, ':') !== false)) { // Special case, no date format specified, detect time input return Zend_Locale_Format::getTime($value, $this->_options); - } else if (Zend_Locale_Format::checkDateFormat($value, $this->_options)) { + } elseif (Zend_Locale_Format::checkDateFormat($value, $this->_options)) { // Detect date or time input return Zend_Locale_Format::getDate($value, $this->_options); } diff --git a/library/Zend/Filter/NormalizedToLocalized.php b/library/Zend/Filter/NormalizedToLocalized.php index 60dbb9e065..1bf392fb24 100644 --- a/library/Zend/Filter/NormalizedToLocalized.php +++ b/library/Zend/Filter/NormalizedToLocalized.php @@ -100,9 +100,9 @@ public function filter($value) require_once 'Zend/Date.php'; $date = new Zend_Date($value, $this->_options['locale']); return $date->toString($this->_options['date_format']); - } else if ($this->_options['precision'] === 0) { + } elseif ($this->_options['precision'] === 0) { return Zend_Locale_Format::toInteger($value, $this->_options); - } else if ($this->_options['precision'] === null) { + } elseif ($this->_options['precision'] === null) { return Zend_Locale_Format::toFloat($value, $this->_options); } diff --git a/library/Zend/Filter/Null.php b/library/Zend/Filter/Null.php index c798800416..f13f42c437 100644 --- a/library/Zend/Filter/Null.php +++ b/library/Zend/Filter/Null.php @@ -64,14 +64,14 @@ public function __construct($options = null) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (!is_array($options)) { + } elseif (!is_array($options)) { $options = func_get_args(); $temp = array(); if (!empty($options)) { $temp = array_shift($options); } $options = $temp; - } else if (is_array($options) && array_key_exists('type', $options)) { + } elseif (is_array($options) && array_key_exists('type', $options)) { $options = $options['type']; } @@ -104,16 +104,13 @@ public function setType($type = null) foreach($type as $value) { if (is_int($value)) { $detected += $value; - } else if (in_array($value, $this->_constants)) { + } elseif (in_array($value, $this->_constants)) { $detected += array_search($value, $this->_constants); } } - $type = $detected; - } else if (is_string($type)) { - if (in_array($type, $this->_constants)) { - $type = array_search($type, $this->_constants); - } + } elseif (is_string($type) && in_array($type, $this->_constants)) { + $type = array_search($type, $this->_constants); } if (!is_int($type) || ($type < 0) || ($type > self::ALL)) { diff --git a/library/Zend/Filter/PregReplace.php b/library/Zend/Filter/PregReplace.php index 7100c3717d..0afbf7ccb9 100644 --- a/library/Zend/Filter/PregReplace.php +++ b/library/Zend/Filter/PregReplace.php @@ -72,7 +72,7 @@ static public function isUnicodeSupportEnabled() */ static protected function _determineUnicodeSupport() { - self::$_unicodeSupportEnabled = (@preg_match('/\pL/u', 'a')) ? true : false; + self::$_unicodeSupportEnabled = (bool) @preg_match('/\pL/u', 'a'); } /** @@ -88,17 +88,15 @@ public function __construct($options = null) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (!is_array($options)) { + } elseif (!is_array($options)) { $options = func_get_args(); $temp = array(); if (!empty($options)) { $temp['match'] = array_shift($options); } - if (!empty($options)) { $temp['replace'] = array_shift($options); } - $options = $temp; } @@ -168,6 +166,9 @@ public function filter($value) throw new Zend_Filter_Exception(get_class($this) . ' does not have a valid MatchPattern set.'); } + if (null === $value) { + return $value; + } return preg_replace($this->_matchPattern, $this->_replacement, $value); } diff --git a/library/Zend/Filter/RealPath.php b/library/Zend/Filter/RealPath.php index 00881de5f5..3c662f6d9d 100644 --- a/library/Zend/Filter/RealPath.php +++ b/library/Zend/Filter/RealPath.php @@ -71,10 +71,8 @@ public function setExists($exists) $exists = $exists->toArray(); } - if (is_array($exists)) { - if (isset($exists['exists'])) { - $exists = (boolean) $exists['exists']; - } + if (is_array($exists) && isset($exists['exists'])) { + $exists = (boolean) $exists['exists']; } $this->_exists = (boolean) $exists; @@ -124,7 +122,7 @@ public function filter($value) if ($dir == '..') { array_pop($stack); } else { - array_push($stack, $dir); + $stack[] = $dir; } } } diff --git a/library/Zend/Filter/StringToLower.php b/library/Zend/Filter/StringToLower.php index b208cfe77a..e053d6d742 100644 --- a/library/Zend/Filter/StringToLower.php +++ b/library/Zend/Filter/StringToLower.php @@ -48,7 +48,7 @@ public function __construct($options = null) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (!is_array($options)) { + } elseif (!is_array($options)) { $options = func_get_args(); $temp = array(); if (!empty($options)) { diff --git a/library/Zend/Filter/StringToUpper.php b/library/Zend/Filter/StringToUpper.php index 8fe362055f..4644d72a6f 100644 --- a/library/Zend/Filter/StringToUpper.php +++ b/library/Zend/Filter/StringToUpper.php @@ -48,7 +48,7 @@ public function __construct($options = null) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (!is_array($options)) { + } elseif (!is_array($options)) { $options = func_get_args(); $temp = array(); if (!empty($options)) { @@ -112,7 +112,7 @@ public function setEncoding($encoding = null) */ public function filter($value) { - if ($this->_encoding) { + if ($this->_encoding !== '' && $this->_encoding !== '0') { return mb_strtoupper((string) $value, $this->_encoding); } diff --git a/library/Zend/Filter/StringTrim.php b/library/Zend/Filter/StringTrim.php index 4f86d89e2c..b39fbce7fc 100644 --- a/library/Zend/Filter/StringTrim.php +++ b/library/Zend/Filter/StringTrim.php @@ -52,7 +52,7 @@ public function __construct($options = null) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (!is_array($options)) { + } elseif (!is_array($options)) { $options = func_get_args(); $temp['charlist'] = array_shift($options); $options = $temp; diff --git a/library/Zend/Filter/StripTags.php b/library/Zend/Filter/StripTags.php index 2ee3f45172..9196a5f8ed 100644 --- a/library/Zend/Filter/StripTags.php +++ b/library/Zend/Filter/StripTags.php @@ -84,18 +84,16 @@ public function __construct($options = null) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if ((!is_array($options)) || (is_array($options) && !array_key_exists('allowTags', $options) && + } elseif ((!is_array($options)) || (is_array($options) && !array_key_exists('allowTags', $options) && !array_key_exists('allowAttribs', $options) && !array_key_exists('allowComments', $options))) { $options = func_get_args(); $temp['allowTags'] = array_shift($options); if (!empty($options)) { $temp['allowAttribs'] = array_shift($options); } - if (!empty($options)) { $temp['allowComments'] = array_shift($options); } - $options = $temp; } @@ -169,9 +167,7 @@ public function setTagsAllowed($tagsAllowed) $tagName = strtolower($element); // Store the tag as allowed with no attributes $this->_tagsAllowed[$tagName] = array(); - } - // Otherwise, if a tag was provided with attributes - else if (is_string($index) && (is_array($element) || is_string($element))) { + } elseif (is_string($index) && (is_array($element) || is_string($element))) { // Canonicalize the tag name $tagName = strtolower($index); // Canonicalize the attributes @@ -246,11 +242,7 @@ public function filter($value) $value = substr($value, $pos); // If there is no comment closing tag, strip whole text - if (!preg_match('/--\s*>/s', $value)) { - $value = ''; - } else { - $value = preg_replace('/<(?:!(?:--[\s\S]*?--\s*)?(>))/s', '', $value); - } + $value = preg_match('/--\s*>/s', $value) ? preg_replace('/<(?:!(?:--[\s\S]*?--\s*)?(>))/s', '', $value) : ''; $value = $start . $value; } @@ -264,16 +256,12 @@ public function filter($value) // Iterate over each set of matches foreach ($matches[1] as $index => $preTag) { // If the pre-tag text is non-empty, strip any ">" characters from it - if (strlen((string) $preTag)) { + if (strlen((string) $preTag) !== 0) { $preTag = str_replace('>', '', $preTag); } // If a tag exists in this match, then filter the tag $tag = $matches[2][$index]; - if (strlen((string) $tag)) { - $tagFiltered = $this->_filterTag($tag); - } else { - $tagFiltered = ''; - } + $tagFiltered = strlen((string) $tag) !== 0 ? $this->_filterTag($tag) : ''; // Add the filtered pre-tag text and filtered tag to the data buffer $dataFiltered .= $preTag . $tagFiltered; } @@ -317,7 +305,7 @@ protected function _filterTag($tag) $tagAttributes = trim($tagAttributes); // If there are non-whitespace characters in the attribute string - if (strlen($tagAttributes)) { + if (strlen($tagAttributes) !== 0) { // Parse iteratively for well-formed attributes preg_match_all('/([\w-]+)\s*=\s*(?:(")(.*?)"|(\')(.*?)\')/s', $tagAttributes, $matches); diff --git a/library/Zend/Form.php b/library/Zend/Form.php index 250ca6e248..6578cb202e 100644 --- a/library/Zend/Form.php +++ b/library/Zend/Form.php @@ -265,7 +265,7 @@ public function __clone() /** @var Zend_Form_DisplayGroup $clone */ $clone = clone $group; $elements = array(); - foreach ($clone->getElements() as $name => $e) { + foreach (array_keys($clone->getElements()) as $name) { $elements[] = $this->getElement($name); } $clone->setElements($elements); @@ -495,7 +495,9 @@ public function getPluginLoader($type = null) */ public function addPrefixPath($prefix, $path, $type = null) { - $type = strtoupper($type); + if (null !== $type) { + $type = strtoupper($type); + } switch ($type) { case self::DECORATOR: case self::ELEMENT: @@ -587,7 +589,7 @@ public function addElementPrefixPath($prefix, $path, $type = null) */ public function addElementPrefixPaths(array $spec) { - $this->_elementPrefixPaths = $this->_elementPrefixPaths + $spec; + $this->_elementPrefixPaths += $spec; /** @var Zend_Form_Element $element */ foreach ($this->getElements() as $element) { @@ -921,9 +923,8 @@ public function getId() } $id = str_replace('][', '-', $id); $id = str_replace(array(']', '['), '-', $id); - $id = trim($id, '-'); - return $id; + return trim($id, '-'); } /** @@ -1131,9 +1132,8 @@ public function createElement($type, $name, $options = null) } $class = $this->getPluginLoader(self::ELEMENT)->load($type); - $element = new $class($name, $options); - return $element; + return new $class($name, $options); } /** @@ -1321,17 +1321,15 @@ public function setDefaults(array $defaults) public function setDefault($name, $value) { $name = (string) $name; - if ($element = $this->getElement($name)) { + if (($element = $this->getElement($name)) !== null) { $element->setValue($value); - } else { - if (is_scalar($value)) { - /** @var Zend_Form_SubForm $subForm */ - foreach ($this->getSubForms() as $subForm) { - $subForm->setDefault($name, $value); - } - } elseif (is_array($value) && ($subForm = $this->getSubForm($name))) { - $subForm->setDefaults($value); + } elseif (is_scalar($value)) { + /** @var Zend_Form_SubForm $subForm */ + foreach ($this->getSubForms() as $subForm) { + $subForm->setDefault($name, $value); } + } elseif (is_array($value) && ($subForm = $this->getSubForm($name))) { + $subForm->setDefaults($value); } return $this; } @@ -1344,11 +1342,11 @@ public function setDefault($name, $value) */ public function getValue($name) { - if ($element = $this->getElement($name)) { + if (($element = $this->getElement($name)) !== null) { return $element->getValue(); } - if ($subForm = $this->getSubForm($name)) { + if (($subForm = $this->getSubForm($name)) !== null) { return $subForm->getValues(true); } @@ -1379,10 +1377,8 @@ public function getValues($suppressArrayNotation = false) foreach ($this->getElements() as $key => $element) { if (!$element->getIgnore()) { $merge = array(); - if (($belongsTo = $element->getBelongsTo()) !== $eBelongTo) { - if ('' !== (string)$belongsTo) { - $key = $belongsTo . '[' . $key . ']'; - } + if (($belongsTo = $element->getBelongsTo()) !== $eBelongTo && '' !== (string)$belongsTo) { + $key = $belongsTo . '[' . $key . ']'; } $merge = $this->_attachToArray($element->getValue(), $key); $values = $this->_array_replace_recursive($values, $merge); @@ -1484,7 +1480,7 @@ public function getValidValues($data, $suppressArrayNotation = false) */ public function getUnfilteredValue($name) { - if ($element = $this->getElement($name)) { + if (($element = $this->getElement($name)) !== null) { return $element->getUnfilteredValue(); } return null; @@ -1568,10 +1564,8 @@ protected function _setElementsBelongTo($name = null) foreach ($this->getElements() as $element) { $element->setBelongsTo($array); } - } else { - if (null !== ($element = $this->getElement($name))) { - $element->setBelongsTo($array); - } + } elseif (null !== ($element = $this->getElement($name))) { + $element->setBelongsTo($array); } } @@ -2106,8 +2100,7 @@ protected function _getArrayName($value) } $start = strrpos($value, '[') + 1; - $name = substr($value, $start, $endPos - $start); - return $name; + return substr($value, $start, $endPos - $start); } /** @@ -2192,9 +2185,7 @@ protected function _attachToArray($value, $arrayPath) $arrayPath = trim(substr($arrayPath, 0, $arrayPos), ']'); } - $value = array($arrayPath => $value); - - return $value; + return array($arrayPath => $value); } /** @@ -2216,7 +2207,7 @@ public function getElementsAndSubFormsOrdered() if ($this->$name instanceof Zend_Form_Element || $this->$name instanceof Zend_Form) { array_splice($ordered, $order, 0, array($this->$name)); - } else if ($this->$name instanceof Zend_Form_DisplayGroup) { + } elseif ($this->$name instanceof Zend_Form_DisplayGroup) { $subordered = array(); /** @var Zend_Form_Element $element */ foreach ($this->$name->getElements() as $element) { @@ -2559,7 +2550,7 @@ public function getErrors($name = null, $suppressArrayNotation = false) if (null !== $name) { if (isset($this->_elements[$name])) { return $this->getElement($name)->getErrors(); - } else if (isset($this->_subForms[$name])) { + } elseif (isset($this->_subForms[$name])) { return $this->getSubForm($name)->getErrors(null, true); } } @@ -2601,14 +2592,14 @@ public function getMessages($name = null, $suppressArrayNotation = false) if (null !== $name) { if (isset($this->_elements[$name])) { return $this->getElement($name)->getMessages(); - } else if (isset($this->_subForms[$name])) { + } elseif (isset($this->_subForms[$name])) { return $this->getSubForm($name)->getMessages(null, true); } /** @var Zend_Form_SubForm $subForm */ foreach ($this->getSubForms() as $key => $subForm) { if ($subForm->isArray()) { $belongTo = $subForm->getElementsBelongTo(); - if ($name == $this->_getArrayName($belongTo)) { + if ($name === $this->_getArrayName($belongTo)) { return $subForm->getMessages(null, true); } } @@ -2634,12 +2625,8 @@ public function getMessages($name = null, $suppressArrayNotation = false) foreach ($this->getSubForms() as $key => $subForm) { $merge = $subForm->getMessages(null, true); if (!empty($merge)) { - if (!$subForm->isArray()) { - $merge = array($key => $merge); - } else { - $merge = $this->_attachToArray($merge, - $subForm->getElementsBelongTo()); - } + $merge = $subForm->isArray() ? $this->_attachToArray($merge, + $subForm->getElementsBelongTo()) : array($key => $merge); $messages = $this->_array_replace_recursive($messages, $merge); } } @@ -2688,7 +2675,7 @@ public function setView(Zend_View_Interface $view = null) */ public function getView() { - if (null === $this->_view) { + if (!$this->_view instanceof \Zend_View_Interface) { require_once 'Zend/Controller/Action/HelperBroker.php'; $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer'); $this->setView($viewRenderer->view); @@ -2707,13 +2694,8 @@ public function getView() protected function _getDecorator($name, $options) { $class = $this->getPluginLoader(self::DECORATOR)->load($name); - if (null === $options) { - $decorator = new $class; - } else { - $decorator = new $class($options); - } - return $decorator; + return null === $options ? new $class : new $class($options); } /** @@ -3007,8 +2989,7 @@ public function render(Zend_View_Interface $view = null) public function __toString() { try { - $return = $this->render(); - return $return; + return $this->render(); } catch (Exception $e) { $message = "Exception caught by form: " . $e->getMessage() . "\nStack Trace:\n" . $e->getTraceAsString(); @@ -3029,7 +3010,7 @@ public function __toString() */ public function setTranslator($translator = null) { - if (null === $translator) { + if (!$translator instanceof \Zend_Translate) { $this->_translator = null; } elseif ($translator instanceof Zend_Translate_Adapter) { $this->_translator = $translator; @@ -3052,7 +3033,7 @@ public function setTranslator($translator = null) */ public static function setDefaultTranslator($translator = null) { - if (null === $translator) { + if (!$translator instanceof \Zend_Translate) { self::$_translatorDefault = null; } elseif ($translator instanceof Zend_Translate_Adapter) { self::$_translatorDefault = $translator; @@ -3186,11 +3167,7 @@ public function __set($name, $value) } require_once 'Zend/Form/Exception.php'; - if (is_object($value)) { - $type = get_class($value); - } else { - $type = gettype($value); - } + $type = is_object($value) ? get_class($value) : gettype($value); throw new Zend_Form_Exception('Only form elements and groups may be overloaded; variable of type "' . $type . '" provided'); } @@ -3202,14 +3179,9 @@ public function __set($name, $value) */ public function __isset($name) { - if (isset($this->_elements[$name]) + return isset($this->_elements[$name]) || isset($this->_subForms[$name]) - || isset($this->_displayGroups[$name])) - { - return true; - } - - return false; + || isset($this->_displayGroups[$name]); } /** @@ -3246,7 +3218,7 @@ public function __call($method, $args) if (false !== ($decorator = $this->getDecorator($decoratorName))) { $decorator->setElement($this); $seed = ''; - if (0 < count($args)) { + if ([] !== $args) { $seed = array_shift($args); } if ($decoratorName === 'FormElements' || @@ -3272,7 +3244,7 @@ public function __call($method, $args) * @throws Zend_Form_Exception * @return Zend_Form_Element|Zend_Form_DisplayGroup|Zend_Form */ - public function current() + public function current(): mixed { $this->_sort(); current($this->_order); @@ -3295,7 +3267,7 @@ public function current() * * @return string */ - public function key() + public function key(): string { $this->_sort(); return key($this->_order); @@ -3306,7 +3278,7 @@ public function key() * * @return void */ - public function next() + public function next(): void { $this->_sort(); next($this->_order); @@ -3317,7 +3289,7 @@ public function next() * * @return void */ - public function rewind() + public function rewind(): void { $this->_sort(); reset($this->_order); @@ -3328,7 +3300,7 @@ public function rewind() * * @return bool */ - public function valid() + public function valid(): bool { $this->_sort(); return (current($this->_order) !== false); @@ -3339,7 +3311,7 @@ public function valid() * * @return int */ - public function count() + public function count(): int { return count($this->_order); } @@ -3464,7 +3436,7 @@ protected function _loadDecorator(array $decorator, $name) $decoratorsExchange = array(); unset($order[$name]); asort($order); - foreach ($order as $key => $index) { + foreach (array_keys($order) as $key) { if ($key == $newName) { $decoratorsExchange[$key] = $instance; continue; diff --git a/library/Zend/Form/Decorator/Callback.php b/library/Zend/Form/Decorator/Callback.php index 73dfc27da6..91d7351293 100644 --- a/library/Zend/Form/Decorator/Callback.php +++ b/library/Zend/Form/Decorator/Callback.php @@ -83,11 +83,9 @@ public function setCallback($callback) */ public function getCallback() { - if (null === $this->_callback) { - if (null !== ($callback = $this->getOption('callback'))) { - $this->setCallback($callback); - $this->removeOption('callback'); - } + if (null === $this->_callback && null !== ($callback = $this->getOption('callback'))) { + $this->setCallback($callback); + $this->removeOption('callback'); } return $this->_callback; diff --git a/library/Zend/Form/Decorator/Captcha.php b/library/Zend/Form/Decorator/Captcha.php index b2bf609ab3..aa03c8b1bb 100644 --- a/library/Zend/Form/Decorator/Captcha.php +++ b/library/Zend/Form/Decorator/Captcha.php @@ -50,7 +50,7 @@ public function render($content) } $view = $element->getView(); - if (null === $view) { + if (!$view instanceof \Zend_View_Interface) { return $content; } diff --git a/library/Zend/Form/Decorator/Captcha/ReCaptcha.php b/library/Zend/Form/Decorator/Captcha/ReCaptcha.php index c89fb25a49..1cd4019aa8 100644 --- a/library/Zend/Form/Decorator/Captcha/ReCaptcha.php +++ b/library/Zend/Form/Decorator/Captcha/ReCaptcha.php @@ -50,7 +50,7 @@ public function render($content) } $view = $element->getView(); - if (null === $view) { + if (!$view instanceof \Zend_View_Interface) { return $content; } diff --git a/library/Zend/Form/Decorator/Captcha/Word.php b/library/Zend/Form/Decorator/Captcha/Word.php index 9bff8dc66b..73b543ac39 100644 --- a/library/Zend/Form/Decorator/Captcha/Word.php +++ b/library/Zend/Form/Decorator/Captcha/Word.php @@ -46,7 +46,7 @@ public function render($content) { $element = $this->getElement(); $view = $element->getView(); - if (null === $view) { + if (!$view instanceof \Zend_View_Interface) { return $content; } diff --git a/library/Zend/Form/Decorator/Description.php b/library/Zend/Form/Decorator/Description.php index e47b337db8..044f5729b9 100644 --- a/library/Zend/Form/Decorator/Description.php +++ b/library/Zend/Form/Decorator/Description.php @@ -154,7 +154,7 @@ public function render($content) { $element = $this->getElement(); $view = $element->getView(); - if (null === $view) { + if (!$view instanceof \Zend_View_Interface) { return $content; } diff --git a/library/Zend/Form/Decorator/Errors.php b/library/Zend/Form/Decorator/Errors.php index 0a907d8c8e..c046b98299 100644 --- a/library/Zend/Form/Decorator/Errors.php +++ b/library/Zend/Form/Decorator/Errors.php @@ -46,7 +46,7 @@ public function render($content) { $element = $this->getElement(); $view = $element->getView(); - if (null === $view) { + if (!$view instanceof \Zend_View_Interface) { return $content; } diff --git a/library/Zend/Form/Decorator/Fieldset.php b/library/Zend/Form/Decorator/Fieldset.php index 2b132dac7e..9686942ca0 100644 --- a/library/Zend/Form/Decorator/Fieldset.php +++ b/library/Zend/Form/Decorator/Fieldset.php @@ -100,11 +100,9 @@ public function setLegend($value) public function getLegend() { $legend = $this->_legend; - if ((null === $legend) && (null !== ($element = $this->getElement()))) { - if (method_exists($element, 'getLegend')) { - $legend = $element->getLegend(); - $this->setLegend($legend); - } + if ((null === $legend) && (null !== ($element = $this->getElement())) && method_exists($element, 'getLegend')) { + $legend = $element->getLegend(); + $this->setLegend($legend); } if ((null === $legend) && (null !== ($legend = $this->getOption('legend')))) { $this->setLegend($legend); @@ -124,7 +122,7 @@ public function render($content) { $element = $this->getElement(); $view = $element->getView(); - if (null === $view) { + if (!$view instanceof \Zend_View_Interface) { return $content; } diff --git a/library/Zend/Form/Decorator/File.php b/library/Zend/Form/Decorator/File.php index 2343ec1e9f..dd28d40daf 100644 --- a/library/Zend/Form/Decorator/File.php +++ b/library/Zend/Form/Decorator/File.php @@ -113,7 +113,7 @@ public function render($content) if (Zend_File_Transfer_Adapter_Http::isApcAvailable()) { $markup[] = $view->formHidden(ini_get('apc.rfc1867_name'), uniqid(), array('id' => 'progress_key')); - } else if (Zend_File_Transfer_Adapter_Http::isUploadProgressAvailable()) { + } elseif (Zend_File_Transfer_Adapter_Http::isUploadProgressAvailable()) { $markup[] = $view->formHidden('UPLOAD_IDENTIFIER', uniqid(), array('id' => 'progress_key')); } diff --git a/library/Zend/Form/Decorator/Form.php b/library/Zend/Form/Decorator/Form.php index 11b82b815f..a89aee4147 100644 --- a/library/Zend/Form/Decorator/Form.php +++ b/library/Zend/Form/Decorator/Form.php @@ -121,7 +121,7 @@ public function render($content) { $form = $this->getElement(); $view = $form->getView(); - if (null === $view) { + if (!$view instanceof \Zend_View_Interface) { return $content; } diff --git a/library/Zend/Form/Decorator/FormElements.php b/library/Zend/Form/Decorator/FormElements.php index 956d10102f..13243e71e4 100644 --- a/library/Zend/Form/Decorator/FormElements.php +++ b/library/Zend/Form/Decorator/FormElements.php @@ -103,9 +103,9 @@ public function render($content) } elseif (!empty($belongsTo) && ($item instanceof Zend_Form)) { if ($item->isArray()) { $name = $this->mergeBelongsTo($belongsTo, $item->getElementsBelongTo()); - $item->setElementsBelongTo($name, true); + $item->setElementsBelongTo($name); } else { - $item->setElementsBelongTo($belongsTo, true); + $item->setElementsBelongTo($belongsTo); } } elseif (!empty($belongsTo) && ($item instanceof Zend_Form_DisplayGroup)) { foreach ($item as $element) { diff --git a/library/Zend/Form/Decorator/FormErrors.php b/library/Zend/Form/Decorator/FormErrors.php index 29ca94e729..b884159315 100644 --- a/library/Zend/Form/Decorator/FormErrors.php +++ b/library/Zend/Form/Decorator/FormErrors.php @@ -89,7 +89,7 @@ public function render($content) } $view = $form->getView(); - if (null === $view) { + if (!$view instanceof \Zend_View_Interface) { return $content; } @@ -493,16 +493,15 @@ protected function _recurseForm(Zend_Form $form, Zend_View_Interface $view) foreach ($form->getElementsAndSubFormsOrdered() as $subitem) { if ($subitem instanceof Zend_Form_Element && !$this->getOnlyCustomFormErrors()) { $messages = $subitem->getMessages(); - if (count($messages)) { + if ($messages !== []) { $subitem->setView($view); $content .= $this->getMarkupListItemStart() . $this->renderLabel($subitem, $view) . $view->formErrors($messages, $this->getOptions()) . $this->getMarkupListItemEnd(); } - } else if ($subitem instanceof Zend_Form && !$this->ignoreSubForms()) { + } elseif ($subitem instanceof Zend_Form && !$this->ignoreSubForms()) { $markup = $this->_recurseForm($subitem, $view); - if (!empty($markup)) { $content .= $this->getMarkupListStart() . $markup diff --git a/library/Zend/Form/Decorator/HtmlTag.php b/library/Zend/Form/Decorator/HtmlTag.php index 300fdc0e3f..2e9b40e14d 100644 --- a/library/Zend/Form/Decorator/HtmlTag.php +++ b/library/Zend/Form/Decorator/HtmlTag.php @@ -108,7 +108,7 @@ protected function _htmlAttribs(array $attribs) */ public function normalizeTag($tag) { - if (!isset($this->_tagFilter)) { + if (!($this->_tagFilter !== null)) { require_once 'Zend/Filter.php'; require_once 'Zend/Filter/Alnum.php'; require_once 'Zend/Filter/StringToLower.php'; @@ -165,8 +165,7 @@ protected function _getOpenTag($tag, array $attribs = null) if (null !== $attribs) { $html .= $this->_htmlAttribs($attribs); } - $html .= '>'; - return $html; + return $html . '>'; } /** diff --git a/library/Zend/Form/Decorator/Image.php b/library/Zend/Form/Decorator/Image.php index 96ef0ff0df..cc653195af 100644 --- a/library/Zend/Form/Decorator/Image.php +++ b/library/Zend/Form/Decorator/Image.php @@ -121,7 +121,7 @@ public function render($content) { $element = $this->getElement(); $view = $element->getView(); - if (null === $view) { + if (!$view instanceof \Zend_View_Interface) { return $content; } diff --git a/library/Zend/Form/Decorator/Label.php b/library/Zend/Form/Decorator/Label.php index 8359b78828..7ced09f6fd 100644 --- a/library/Zend/Form/Decorator/Label.php +++ b/library/Zend/Form/Decorator/Label.php @@ -94,11 +94,9 @@ public function setId($id) public function getId() { $id = $this->getOption('id'); - if (null === $id) { - if (null !== ($element = $this->getElement())) { - $id = $element->getId(); - $this->setId($id); - } + if (null === $id && null !== ($element = $this->getElement())) { + $id = $element->getId(); + $this->setId($id); } return $id; @@ -112,11 +110,7 @@ public function getId() */ public function setTag($tag) { - if (empty($tag)) { - $this->_tag = null; - } else { - $this->_tag = (string) $tag; - } + $this->_tag = empty($tag) ? null : (string) $tag; $this->removeOption('tag'); @@ -150,11 +144,7 @@ public function getTag() */ public function setTagClass($tagClass) { - if (empty($tagClass)) { - $this->_tagClass = null; - } else { - $this->_tagClass = (string) $tagClass; - } + $this->_tagClass = empty($tagClass) ? null : (string) $tagClass; $this->removeOption('tagClass'); @@ -264,7 +254,7 @@ public function __call($method, $args) switch ($head) { case 'set': - if (0 === count($args)) { + if ([] === $args) { require_once 'Zend/Form/Exception.php'; throw new Zend_Form_Exception(sprintf('Method "%s" requires at least one argument; none provided', $method)); } @@ -313,11 +303,7 @@ public function getLabel() $separator = $this->getSeparator(); if (!empty($label)) { - if ($element->isRequired()) { - $label = $reqPrefix . $label . $reqSuffix; - } else { - $label = $optPrefix . $label . $optSuffix; - } + $label = $element->isRequired() ? $reqPrefix . $label . $reqSuffix : $optPrefix . $label . $optSuffix; } return $label; @@ -363,7 +349,7 @@ public function render($content) { $element = $this->getElement(); $view = $element->getView(); - if (null === $view) { + if (!$view instanceof \Zend_View_Interface) { return $content; } diff --git a/library/Zend/Form/Decorator/PrepareElements.php b/library/Zend/Form/Decorator/PrepareElements.php index 002e4f6c33..6bbc7e10d0 100644 --- a/library/Zend/Form/Decorator/PrepareElements.php +++ b/library/Zend/Form/Decorator/PrepareElements.php @@ -75,9 +75,9 @@ protected function _recursivelyPrepareForm(Zend_Form $form) } elseif (!empty($belongsTo) && ($item instanceof Zend_Form)) { if ($item->isArray()) { $name = $this->mergeBelongsTo($belongsTo, $item->getElementsBelongTo()); - $item->setElementsBelongTo($name, true); + $item->setElementsBelongTo($name); } else { - $item->setElementsBelongTo($belongsTo, true); + $item->setElementsBelongTo($belongsTo); } $this->_recursivelyPrepareForm($item); } elseif (!empty($belongsTo) && ($item instanceof Zend_Form_DisplayGroup)) { diff --git a/library/Zend/Form/Decorator/Tooltip.php b/library/Zend/Form/Decorator/Tooltip.php index 1dc7dbca30..9c91e80905 100644 --- a/library/Zend/Form/Decorator/Tooltip.php +++ b/library/Zend/Form/Decorator/Tooltip.php @@ -45,10 +45,8 @@ class Zend_Form_Decorator_Tooltip extends Zend_Form_Decorator_Abstract */ public function render($content) { - if (null !== ($title = $this->getElement()->getAttrib('title'))) { - if (null !== ($translator = $this->getElement()->getTranslator())) { - $title = $translator->translate($title); - } + if (null !== ($title = $this->getElement()->getAttrib('title')) && null !== ($translator = $this->getElement()->getTranslator())) { + $title = $translator->translate($title); } $this->getElement()->setAttrib('title', $title); diff --git a/library/Zend/Form/Decorator/ViewHelper.php b/library/Zend/Form/Decorator/ViewHelper.php index 92d54e75ef..46b26f8a91 100644 --- a/library/Zend/Form/Decorator/ViewHelper.php +++ b/library/Zend/Form/Decorator/ViewHelper.php @@ -153,10 +153,8 @@ public function getElementAttribs() unset($attribs['helper']); } - if (method_exists($element, 'getSeparator')) { - if (null !== ($listsep = $element->getSeparator())) { - $attribs['listsep'] = $listsep; - } + if (method_exists($element, 'getSeparator') && null !== ($listsep = $element->getSeparator())) { + $attribs['listsep'] = $listsep; } if (isset($attribs['id'])) { @@ -165,11 +163,9 @@ public function getElementAttribs() $id = $element->getName(); - if ($element instanceof Zend_Form_Element) { - if (null !== ($belongsTo = $element->getBelongsTo())) { - $belongsTo = preg_replace('/\[([^\]]+)\]/', '-$1', $belongsTo); - $id = $belongsTo . '-' . $id; - } + if ($element instanceof Zend_Form_Element && null !== ($belongsTo = $element->getBelongsTo())) { + $belongsTo = preg_replace('/\[([^\]]+)\]/', '-$1', $belongsTo); + $id = $belongsTo . '-' . $id; } $element->setAttrib('id', $id); @@ -222,7 +218,7 @@ public function render($content) $element = $this->getElement(); $view = $element->getView(); - if (null === $view) { + if (!$view instanceof \Zend_View_Interface) { require_once 'Zend/Form/Decorator/Exception.php'; throw new Zend_Form_Decorator_Exception('ViewHelper decorator cannot render without a registered view object'); } diff --git a/library/Zend/Form/Decorator/ViewScript.php b/library/Zend/Form/Decorator/ViewScript.php index f735872d15..f4474f8986 100644 --- a/library/Zend/Form/Decorator/ViewScript.php +++ b/library/Zend/Form/Decorator/ViewScript.php @@ -90,11 +90,9 @@ public function setViewScript($script) public function getViewScript() { if (null === $this->_viewScript) { - if (null !== ($element = $this->getElement())) { - if (null !== ($viewScript = $element->getAttrib('viewScript'))) { - $this->setViewScript($viewScript); - return $viewScript; - } + if (null !== ($element = $this->getElement()) && null !== ($viewScript = $element->getAttrib('viewScript'))) { + $this->setViewScript($viewScript); + return $viewScript; } if (null !== ($viewScript = $this->getOption('viewScript'))) { @@ -126,11 +124,9 @@ public function setViewModule($viewModule) public function getViewModule() { if (null === $this->_viewModule) { - if (null !== ($element = $this->getElement())) { - if (null !== ($viewModule = $element->getAttrib('viewModule'))) { - $this->setViewModule($viewModule); - return $viewModule; - } + if (null !== ($element = $this->getElement()) && null !== ($viewModule = $element->getAttrib('viewModule'))) { + $this->setViewModule($viewModule); + return $viewModule; } if (null !== ($viewModule = $this->getOption('viewModule'))) { @@ -152,7 +148,7 @@ public function render($content) { $element = $this->getElement(); $view = $element->getView(); - if (null === $view) { + if (!$view instanceof \Zend_View_Interface) { return $content; } diff --git a/library/Zend/Form/DisplayGroup.php b/library/Zend/Form/DisplayGroup.php index cdb0d39499..2ee9ab05bb 100644 --- a/library/Zend/Form/DisplayGroup.php +++ b/library/Zend/Form/DisplayGroup.php @@ -29,6 +29,7 @@ */ class Zend_Form_DisplayGroup implements Iterator,Countable { + public $id; /** * Group attributes * @var array @@ -369,7 +370,7 @@ public function getFullyQualifiedName() */ public function getId() { - if (isset($this->id)) { + if (property_exists($this, 'id') && $this->id !== null) { return $this->id; } @@ -386,9 +387,8 @@ public function getId() } $id = str_replace('][', '-', $id); $id = str_replace(array(']', '['), '-', $id); - $id = trim($id, '-'); - return $id; + return trim($id, '-'); } /** @@ -685,13 +685,8 @@ public function loadDefaultDecorators() protected function _getDecorator($name, $options = null) { $class = $this->getPluginLoader()->load($name); - if (null === $options) { - $decorator = new $class; - } else { - $decorator = new $class($options); - } - return $decorator; + return null === $options ? new $class : new $class($options); } /** @@ -895,7 +890,7 @@ public function setView(Zend_View_Interface $view = null) */ public function getView() { - if (null === $this->_view) { + if (!$this->_view instanceof \Zend_View_Interface) { require_once 'Zend/Controller/Action/HelperBroker.php'; $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer'); $this->setView($viewRenderer->view); @@ -930,8 +925,7 @@ public function render(Zend_View_Interface $view = null) public function __toString() { try { - $return = $this->render(); - return $return; + return $this->render(); } catch (Exception $e) { trigger_error($e->getMessage(), E_USER_WARNING); return ''; @@ -968,7 +962,7 @@ public function getTranslator() return null; } - if (null === $this->_translator) { + if (!$this->_translator instanceof \Zend_Translate_Adapter) { require_once 'Zend/Form.php'; return Zend_Form::getDefaultTranslator(); } @@ -1025,7 +1019,7 @@ public function __call($method, $args) if (false !== ($decorator = $this->getDecorator($decoratorName))) { $decorator->setElement($this); $seed = ''; - if (0 < count($args)) { + if ([] !== $args) { $seed = array_shift($args); } return $decorator->render($seed); @@ -1046,7 +1040,7 @@ public function __call($method, $args) * * @return Zend_Form_Element */ - public function current() + public function current(): mixed { $this->_sort(); current($this->_elementOrder); @@ -1059,7 +1053,7 @@ public function current() * * @return string */ - public function key() + public function key(): string { $this->_sort(); return key($this->_elementOrder); @@ -1070,7 +1064,7 @@ public function key() * * @return void */ - public function next() + public function next(): void { $this->_sort(); next($this->_elementOrder); @@ -1081,7 +1075,7 @@ public function next() * * @return void */ - public function rewind() + public function rewind(): void { $this->_sort(); reset($this->_elementOrder); @@ -1092,7 +1086,7 @@ public function rewind() * * @return bool */ - public function valid() + public function valid(): bool { $this->_sort(); return (current($this->_elementOrder) !== false); @@ -1103,7 +1097,7 @@ public function valid() * * @return int */ - public function count() + public function count(): int { return count($this->_elements); } @@ -1165,7 +1159,7 @@ protected function _loadDecorator(array $decorator, $name) $decoratorsExchange = array(); unset($order[$name]); asort($order); - foreach ($order as $key => $index) { + foreach (array_keys($order) as $key) { if ($key == $newName) { $decoratorsExchange[$key] = $instance; continue; diff --git a/library/Zend/Form/Element.php b/library/Zend/Form/Element.php index e90bd66460..48d30793c8 100644 --- a/library/Zend/Form/Element.php +++ b/library/Zend/Form/Element.php @@ -371,10 +371,8 @@ public function setOptions(array $options) foreach ($options as $key => $value) { $method = 'set' . ucfirst($key); - if (in_array($method, array('setTranslator', 'setPluginLoader', 'setView'))) { - if (!is_object($value)) { - continue; - } + if (in_array($method, array('setTranslator', 'setPluginLoader', 'setView')) && !is_object($value)) { + continue; } if (method_exists($this, $method)) { @@ -410,7 +408,7 @@ public function setConfig(Zend_Config $config) */ public function setTranslator($translator = null) { - if (null === $translator) { + if (!$translator instanceof \Zend_Translate_Adapter) { $this->_translator = null; } elseif ($translator instanceof Zend_Translate_Adapter) { $this->_translator = $translator; @@ -547,7 +545,7 @@ public function getFullyQualifiedName() */ public function getId() { - if (isset($this->id)) { + if (property_exists($this, 'id') && $this->id !== null) { return $this->id; } @@ -564,9 +562,8 @@ public function getId() } $id = str_replace('][', '-', $id); $id = str_replace(array(']', '['), '-', $id); - $id = trim($id, '-'); - return $id; + return trim($id, '-'); } /** @@ -605,7 +602,9 @@ public function getValue() $valueFiltered = $this->_value; if ($this->isArray() && is_array($valueFiltered)) { - array_walk_recursive($valueFiltered, array($this, '_filterValue')); + array_walk_recursive($valueFiltered, function (string $value, string $key) : void { + $this->_filterValue($value, $key); + }); } else { $this->_filterValue($valueFiltered, $valueFiltered); } @@ -912,7 +911,7 @@ public function getAttribs() { $attribs = get_object_vars($this); unset($attribs['helper']); - foreach ($attribs as $key => $value) { + foreach (array_keys($attribs) as $key) { if ('_' == substr($key, 0, 1)) { unset($attribs[$key]); } @@ -997,7 +996,7 @@ public function __call($method, $args) if (false !== ($decorator = $this->getDecorator($decoratorName))) { $decorator->setElement($this); $seed = ''; - if (0 < count($args)) { + if ([] !== $args) { $seed = array_shift($args); } return $decorator->render($seed); @@ -1091,7 +1090,9 @@ public function getPluginLoader($type) */ public function addPrefixPath($prefix, $path, $type = null) { - $type = strtoupper($type); + if (null !== $type) { + $type = strtoupper($type); + } switch ($type) { case self::DECORATOR: case self::FILTER: @@ -1175,7 +1176,7 @@ public function addValidator($validator, $breakChainOnFailure = false, $options if ($validator instanceof Zend_Validate_Interface) { $name = get_class($validator); - if (!isset($validator->zfBreakChainOnFailure)) { + if (!(property_exists($validator, 'zfBreakChainOnFailure') && $validator->zfBreakChainOnFailure !== null)) { $validator->zfBreakChainOnFailure = $breakChainOnFailure; } } elseif (is_string($validator)) { @@ -1418,12 +1419,9 @@ public function isValid($value, $context = null) if ($isArray && is_array($value)) { $messages = array(); $errors = array(); - if (empty($value)) { - if ($this->isRequired() - || (!$this->isRequired() && !$this->getAllowEmpty()) - ) { - $value = ''; - } + if (empty($value) && ($this->isRequired() + || (!$this->isRequired() && !$this->getAllowEmpty()))) { + $value = ''; } foreach ((array)$value as $val) { if (!$validator->isValid($val, $context)) { @@ -1560,7 +1558,7 @@ public function markAsError() { $messages = $this->getMessages(); $customMessages = $this->_getErrorMessages(); - $messages = $messages + $customMessages; + $messages += $customMessages; if (empty($messages)) { $this->_isError = true; } else { @@ -1836,7 +1834,7 @@ public function setView(Zend_View_Interface $view = null) */ public function getView() { - if (null === $this->_view) { + if (!$this->_view instanceof \Zend_View_Interface) { require_once 'Zend/Controller/Action/HelperBroker.php'; $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer'); $this->setView($viewRenderer->view); @@ -1854,13 +1852,8 @@ public function getView() protected function _getDecorator($name, $options) { $class = $this->getPluginLoader(self::DECORATOR)->load($name); - if (null === $options) { - $decorator = new $class; - } else { - $decorator = new $class($options); - } - return $decorator; + return null === $options ? new $class : new $class($options); } /** @@ -2083,8 +2076,7 @@ public function render(Zend_View_Interface $view = null) public function __toString() { try { - $return = $this->render(); - return $return; + return $this->render(); } catch (Exception $e) { trigger_error($e->getMessage(), E_USER_WARNING); return ''; @@ -2111,11 +2103,7 @@ protected function _loadFilter(array $filter) $instance = new $name; } else { $r = new ReflectionClass($name); - if ($r->hasMethod('__construct')) { - $instance = $r->newInstanceArgs((array) $filter['options']); - } else { - $instance = $r->newInstance(); - } + $instance = $r->hasMethod('__construct') ? $r->newInstanceArgs(array_values((array) $filter['options'])) : $r->newInstance(); } if ($origName != $name) { @@ -2125,7 +2113,7 @@ protected function _loadFilter(array $filter) $filtersExchange = array(); unset($order[$origName]); asort($order); - foreach ($order as $key => $index) { + foreach (array_keys($order) as $key) { if ($key == $name) { $filtersExchange[$key] = $instance; continue; @@ -2178,11 +2166,7 @@ protected function _loadValidator(array $validator) } } - if ($numeric) { - $instance = $r->newInstanceArgs((array) $validator['options']); - } else { - $instance = $r->newInstance($validator['options']); - } + $instance = $numeric ? $r->newInstanceArgs((array) $validator['options']) : $r->newInstance($validator['options']); } else { $instance = $r->newInstance(); } @@ -2204,7 +2188,7 @@ protected function _loadValidator(array $validator) $validatorsExchange = array(); unset($order[$origName]); asort($order); - foreach ($order as $key => $index) { + foreach (array_keys($order) as $key) { if ($key == $name) { $validatorsExchange[$key] = $instance; continue; @@ -2242,7 +2226,7 @@ protected function _loadDecorator(array $decorator, $name) $decoratorsExchange = array(); unset($order[$name]); asort($order); - foreach ($order as $key => $index) { + foreach (array_keys($order) as $key) { if ($key == $newName) { $decoratorsExchange[$key] = $instance; continue; @@ -2276,7 +2260,7 @@ protected function _getErrorMessages() foreach ($value as $val) { $aggregateMessages[] = str_replace('%value%', $val, $message); } - if (count($aggregateMessages)) { + if ($aggregateMessages !== []) { if ($this->_concatJustValuesInErrorMessage) { $values = implode($this->getErrorMessageSeparator(), $value); $messages[$key] = str_replace('%value%', $values, $message); diff --git a/library/Zend/Form/Element/Captcha.php b/library/Zend/Form/Element/Captcha.php index d18ba8403f..f5afd326b9 100644 --- a/library/Zend/Form/Element/Captcha.php +++ b/library/Zend/Form/Element/Captcha.php @@ -93,11 +93,7 @@ public function setCaptcha($captcha, $options = array()) $instance = new $name; } else { $r = new ReflectionClass($name); - if ($r->hasMethod('__construct')) { - $instance = $r->newInstanceArgs(array($options)); - } else { - $instance = $r->newInstance(); - } + $instance = $r->hasMethod('__construct') ? $r->newInstanceArgs(array($options)) : $r->newInstance(); } } diff --git a/library/Zend/Form/Element/File.php b/library/Zend/Form/Element/File.php index 0f3e162d89..b0bef3c122 100644 --- a/library/Zend/Form/Element/File.php +++ b/library/Zend/Form/Element/File.php @@ -457,18 +457,12 @@ public function isValid($value, $context = null) */ public function receive() { - if (!$this->_validated) { - if (!$this->isValid($this->getName())) { - return false; - } + if (!$this->_validated && !$this->isValid($this->getName())) { + return false; } $adapter = $this->getTransferAdapter(); - if ($adapter->receive($this->getName())) { - return true; - } - - return false; + return $adapter->receive($this->getName()); } /** @@ -755,7 +749,7 @@ public function getTranslator() } $translator = $this->getTransferAdapter()->getTranslator(); - if (null === $translator) { + if (!$translator instanceof \Zend_Translate_Adapter) { require_once 'Zend/Form.php'; return Zend_Form::getDefaultTranslator(); } diff --git a/library/Zend/Form/Element/Hash.php b/library/Zend/Form/Element/Hash.php index a5f99f345f..d6c8bf55ec 100644 --- a/library/Zend/Form/Element/Hash.php +++ b/library/Zend/Form/Element/Hash.php @@ -125,11 +125,7 @@ public function getSession() public function initCsrfValidator() { $session = $this->getSession(); - if (isset($session->hash)) { - $rightHash = $session->hash; - } else { - $rightHash = null; - } + $rightHash = property_exists($session, 'hash') && $session->hash !== null ? $session->hash : null; $this->addValidator('Identical', true, array($rightHash)); return $this; diff --git a/library/Zend/Form/Element/Multi.php b/library/Zend/Form/Element/Multi.php index 9fb9511528..fb88ced253 100644 --- a/library/Zend/Form/Element/Multi.php +++ b/library/Zend/Form/Element/Multi.php @@ -243,27 +243,23 @@ public function registerInArrayValidator() */ public function isValid($value, $context = null) { - if ($this->registerInArrayValidator()) { - if (!$this->getValidator('InArray')) { - $multiOptions = $this->getMultiOptions(); - $options = array(); - - foreach ($multiOptions as $opt_value => $opt_label) { - // optgroup instead of option label - if (is_array($opt_label)) { - $options = array_merge($options, array_keys($opt_label)); - } - else { - $options[] = $opt_value; - } + if ($this->registerInArrayValidator() && !$this->getValidator('InArray')) { + $multiOptions = $this->getMultiOptions(); + $options = array(); + foreach ($multiOptions as $opt_value => $opt_label) { + // optgroup instead of option label + if (is_array($opt_label)) { + $options = array_merge($options, array_keys($opt_label)); + } + else { + $options[] = $opt_value; } - - $this->addValidator( - 'InArray', - true, - array($options) - ); } + $this->addValidator( + 'InArray', + true, + array($options) + ); } return parent::isValid($value, $context); } diff --git a/library/Zend/Gdata.php b/library/Zend/Gdata.php index 7ffabc9063..87a08dd87c 100644 --- a/library/Zend/Gdata.php +++ b/library/Zend/Gdata.php @@ -156,8 +156,7 @@ public function getFeed($location, $className='Zend_Gdata_Feed') } else { require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( - 'You must specify the location as either a string URI ' . - 'or a child of Zend_Gdata_Query'); + 'You must specify the location as either a string URI or a child of Zend_Gdata_Query'); } return parent::getFeed($uri, $className); } @@ -181,8 +180,7 @@ public function getEntry($location, $className='Zend_Gdata_Entry') } else { require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( - 'You must specify the location as either a string URI ' . - 'or a child of Zend_Gdata_Query'); + 'You must specify the location as either a string URI or a child of Zend_Gdata_Query'); } return parent::getEntry($uri, $className); } @@ -230,12 +228,8 @@ public function performHttpRequest($method, $url, $headers = array(), $body = nu public function isAuthenticated() { $client = parent::getHttpClient(); - if ($client->getClientLoginToken() || - $client->getAuthSubToken()) { - return true; - } - - return false; + return $client->getClientLoginToken() || + $client->getAuthSubToken(); } } diff --git a/library/Zend/Gdata/Analytics/AccountQuery.php b/library/Zend/Gdata/Analytics/AccountQuery.php index 2f2f14f727..dbcc884230 100644 --- a/library/Zend/Gdata/Analytics/AccountQuery.php +++ b/library/Zend/Gdata/Analytics/AccountQuery.php @@ -172,19 +172,17 @@ public function getQueryUrl() $url = $this->_defaultFeedUri; // add account id - if ($this->_webproperties or $this->_profiles or $this->_goals) { + if ($this->_webproperties || $this->_profiles || $this->_goals) { $url .= '/' . $this->_accountId . '/webproperties'; } - if ($this->_profiles or $this->_goals) { + if ($this->_profiles || $this->_goals) { $url .= '/' . $this->_webpropertyId . '/profiles'; } if ($this->_goals) { $url .= '/' . $this->_profileId . '/goals'; } - - $url .= $this->getQueryString(); - return $url; + return $url . $this->getQueryString(); } } diff --git a/library/Zend/Gdata/Analytics/DataQuery.php b/library/Zend/Gdata/Analytics/DataQuery.php index 237c306e39..121119f41e 100644 --- a/library/Zend/Gdata/Analytics/DataQuery.php +++ b/library/Zend/Gdata/Analytics/DataQuery.php @@ -363,7 +363,7 @@ public function setSegment($segment) public function getQueryUrl() { $uri = $this->_defaultFeedUri; - if (isset($this->_url)) { + if ($this->_url !== null) { $uri = $this->_url; } @@ -393,11 +393,9 @@ public function getQueryUrl() $filters.=($filter[1]===true?';':',').$filter[0]; } - if ($filters!="") { + if ($filters != "") { $this->setParam('filters', ltrim($filters, ",;")); } - - $uri .= $this->getQueryString(); - return $uri; + return $uri . $this->getQueryString(); } } diff --git a/library/Zend/Gdata/App.php b/library/Zend/Gdata/App.php index 137fafa8f0..561b8ead00 100644 --- a/library/Zend/Gdata/App.php +++ b/library/Zend/Gdata/App.php @@ -341,8 +341,7 @@ public static function setGzipEnabled($enabled = false) if ($enabled && !function_exists('gzinflate')) { require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( - 'You cannot enable gzipped responses if the zlib module ' . - 'is not enabled in your PHP installation.'); + 'You cannot enable gzipped responses if the zlib module is not enabled in your PHP installation.'); } self::$_gzipEnabled = $enabled; @@ -415,7 +414,7 @@ public static function getMaxRedirects() */ public function setMajorProtocolVersion($value) { - if (!($value >= 1)) { + if ($value < 1) { require_once('Zend/Gdata/App/InvalidArgumentException.php'); throw new Zend_Gdata_App_InvalidArgumentException( 'Major protocol version must be >= 1'); @@ -445,7 +444,7 @@ public function getMajorProtocolVersion() */ public function setMinorProtocolVersion($value) { - if (!($value >= 0)) { + if ($value < 0) { require_once('Zend/Gdata/App/InvalidArgumentException.php'); throw new Zend_Gdata_App_InvalidArgumentException( 'Minor protocol version must be >= 0'); @@ -618,8 +617,7 @@ public function performHttpRequest($method, $url, $headers = null, $headers['x-http-method-override'] != 'DELETE') { require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( - 'You must specify the data to post as either a ' . - 'string or a child of Zend_Gdata_App_Entry'); + 'You must specify the data to post as either a string or a child of Zend_Gdata_App_Entry'); } if ($url === null) { require_once 'Zend/Gdata/App/InvalidArgumentException.php'; @@ -693,7 +691,7 @@ public function performHttpRequest($method, $url, $headers = null, $this->_httpClient->setAdapter($oldHttpAdapter); } require_once 'Zend/Gdata/App/HttpException.php'; - throw new Zend_Gdata_App_HttpException($e->getMessage(), $e); + throw new Zend_Gdata_App_HttpException($e->getMessage(), $e, $e); } if ($response->isRedirect() && $response->getStatus() != '304') { if ($remainingRedirects > 0) { @@ -742,7 +740,7 @@ public static function import($uri, $client = null, $requestData['method'], $requestData['url']); $feedContent = $response->getBody(); - if (false === $useObjectMapping) { + if (!$useObjectMapping) { return $feedContent; } $feed = self::importString($feedContent, $className); @@ -1111,11 +1109,7 @@ public function retrieveAllEntriesForFeed($feed) { } $next = $feed->getLink('next'); - if ($next !== null) { - $feed = $this->getFeed($next->href, $feedClass); - } else { - $feed = null; - } + $feed = $next !== null ? $this->getFeed($next->href, $feedClass) : null; } while ($feed != null); return $result; @@ -1235,11 +1229,7 @@ public function usingObjectMapping() */ public function useObjectMapping($value) { - if ($value === True) { - $this->_useObjectMapping = true; - } else { - $this->_useObjectMapping = false; - } + $this->_useObjectMapping = $value; } } diff --git a/library/Zend/Gdata/App/Base.php b/library/Zend/Gdata/App/Base.php index 4635840370..89ded23734 100644 --- a/library/Zend/Gdata/App/Base.php +++ b/library/Zend/Gdata/App/Base.php @@ -300,7 +300,7 @@ public function transferFromDOM($node) */ public function transferFromXML($xml) { - if ($xml) { + if ($xml !== '' && $xml !== '0') { // Load the feed as an XML DOMDocument object @ini_set('track_errors', 1); $doc = new DOMDocument(); @@ -311,7 +311,7 @@ public function transferFromXML($xml) throw new Zend_Gdata_App_Exception("DOMDocument cannot parse XML: $php_errormsg"); } $element = $doc->getElementsByTagName($this->_rootElement)->item(0); - if (!$element) { + if (!$element instanceof \DOMElement) { require_once 'Zend/Gdata/App/Exception.php'; throw new Zend_Gdata_App_Exception('No root <' . $this->_rootElement . '> element'); } @@ -480,7 +480,7 @@ public function __get($name) $method = 'get'.ucfirst($name); if (method_exists($this, $method)) { return call_user_func(array(&$this, $method)); - } else if (property_exists($this, "_${name}")) { + } elseif (property_exists($this, "_${name}")) { return $this->{'_' . $name}; } else { require_once 'Zend/Gdata/App/InvalidArgumentException.php'; @@ -506,7 +506,7 @@ public function __set($name, $val) $method = 'set'.ucfirst($name); if (method_exists($this, $method)) { return call_user_func(array(&$this, $method), $val); - } else if (isset($this->{'_' . $name}) || ($this->{'_' . $name} === null)) { + } elseif (isset($this->{'_' . $name}) || ($this->{'_' . $name} === null)) { $this->{'_' . $name} = $val; } else { require_once 'Zend/Gdata/App/InvalidArgumentException.php'; @@ -528,20 +528,18 @@ public function __isset($name) require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Property ' . $name . ' does not exist'); - } else { - if (isset($this->{$privName})) { - if (is_array($this->{$privName})) { - if (count($this->{$privName}) > 0) { - return true; - } else { - return false; - } - } else { + } elseif (isset($this->{$privName})) { + if (is_array($this->{$privName})) { + if ($this->{$privName} !== []) { return true; + } else { + return false; } } else { - return false; + return true; } + } else { + return false; } } @@ -553,11 +551,7 @@ public function __isset($name) public function __unset($name) { if (isset($this->{'_' . $name})) { - if (is_array($this->{'_' . $name})) { - $this->{'_' . $name} = array(); - } else { - $this->{'_' . $name} = null; - } + $this->{'_' . $name} = is_array($this->{'_' . $name}) ? array() : null; } } diff --git a/library/Zend/Gdata/App/BaseMediaSource.php b/library/Zend/Gdata/App/BaseMediaSource.php index 7e136ac455..1874fb60c3 100644 --- a/library/Zend/Gdata/App/BaseMediaSource.php +++ b/library/Zend/Gdata/App/BaseMediaSource.php @@ -113,7 +113,7 @@ public function __get($name) $method = 'get'.ucfirst($name); if (method_exists($this, $method)) { return call_user_func(array(&$this, $method)); - } else if (property_exists($this, "_${name}")) { + } elseif (property_exists($this, "_${name}")) { return $this->{'_' . $name}; } else { require_once 'Zend/Gdata/App/InvalidArgumentException.php'; @@ -137,7 +137,7 @@ public function __set($name, $val) $method = 'set'.ucfirst($name); if (method_exists($this, $method)) { return call_user_func(array(&$this, $method), $val); - } else if (isset($this->{'_' . $name}) || ($this->{'_' . $name} === null)) { + } elseif (isset($this->{'_' . $name}) || ($this->{'_' . $name} === null)) { $this->{'_' . $name} = $val; } else { require_once 'Zend/Gdata/App/InvalidArgumentException.php'; @@ -159,20 +159,18 @@ public function __isset($name) require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Property ' . $name . ' does not exist'); - } else { - if (isset($this->{$privName})) { - if (is_array($this->{$privName})) { - if (count($this->{$privName}) > 0) { - return true; - } else { - return false; - } - } else { + } elseif (isset($this->{$privName})) { + if (is_array($this->{$privName})) { + if ($this->{$privName} !== []) { return true; + } else { + return false; } } else { - return false; + return true; } + } else { + return false; } } diff --git a/library/Zend/Gdata/App/Feed.php b/library/Zend/Gdata/App/Feed.php index 2e07bd0bd4..2ff1586b34 100755 --- a/library/Zend/Gdata/App/Feed.php +++ b/library/Zend/Gdata/App/Feed.php @@ -282,8 +282,7 @@ public function getNextFeed() $nextLink = $this->getNextLink(); if (!$nextLink) { require_once 'Zend/Gdata/App/HttpException.php'; - throw new Zend_Gdata_App_Exception('No link to next set ' . - 'of results found.'); + throw new Zend_Gdata_App_Exception('No link to next set of results found.'); } $nextLinkHref = $nextLink->getHref(); $service = new Zend_Gdata_App($this->getHttpClient()); @@ -303,8 +302,7 @@ public function getPreviousFeed() $previousLink = $this->getPreviousLink(); if (!$previousLink) { require_once 'Zend/Gdata/App/HttpException.php'; - throw new Zend_Gdata_App_Exception('No link to previous set ' . - 'of results found.'); + throw new Zend_Gdata_App_Exception('No link to previous set of results found.'); } $previousLinkHref = $previousLink->getHref(); $service = new Zend_Gdata_App($this->getHttpClient()); diff --git a/library/Zend/Gdata/App/FeedEntryParent.php b/library/Zend/Gdata/App/FeedEntryParent.php index 89c6fcc150..3c67516978 100755 --- a/library/Zend/Gdata/App/FeedEntryParent.php +++ b/library/Zend/Gdata/App/FeedEntryParent.php @@ -172,8 +172,7 @@ public function getHttpClient() if (!$this->_service) { $this->_service = new Zend_Gdata_App(); } - $client = $this->_service->getHttpClient(); - return $client; + return $this->_service->getHttpClient(); } /** @@ -592,7 +591,7 @@ public function getEtag() { */ public function setMajorProtocolVersion($value) { - if (!($value >= 1) && ($value !== null)) { + if ($value < 1 && ($value !== null)) { require_once('Zend/Gdata/App/InvalidArgumentException.php'); throw new Zend_Gdata_App_InvalidArgumentException( 'Major protocol version must be >= 1'); @@ -622,7 +621,7 @@ public function getMajorProtocolVersion() */ public function setMinorProtocolVersion($value) { - if (!($value >= 0)) { + if ($value < 0) { require_once('Zend/Gdata/App/InvalidArgumentException.php'); throw new Zend_Gdata_App_InvalidArgumentException( 'Minor protocol version must be >= 0 or null'); diff --git a/library/Zend/Gdata/App/FeedSourceParent.php b/library/Zend/Gdata/App/FeedSourceParent.php index 9bdbbad769..b2e7670d4c 100644 --- a/library/Zend/Gdata/App/FeedSourceParent.php +++ b/library/Zend/Gdata/App/FeedSourceParent.php @@ -131,10 +131,7 @@ public function setService($instance) */ public function __get($var) { - switch ($var) { - default: - return parent::__get($var); - } + return parent::__get($var); } diff --git a/library/Zend/Gdata/App/Util.php b/library/Zend/Gdata/App/Util.php index d570b86bfc..309ad3bc5c 100644 --- a/library/Zend/Gdata/App/Util.php +++ b/library/Zend/Gdata/App/Util.php @@ -76,7 +76,7 @@ public static function findGreatestBoundedValue($maximumKey, $collection) $foundKey = $maximumKey; // Sanity check: Make sure that the collection isn't empty - if (sizeof($collection) == 0) { + if (count($collection) == 0) { require_once 'Zend/Gdata/App/Exception.php'; throw new Zend_Gdata_App_Exception("Empty namespace collection encountered."); } diff --git a/library/Zend/Gdata/AuthSub.php b/library/Zend/Gdata/AuthSub.php index dfd718586f..1f887000c4 100644 --- a/library/Zend/Gdata/AuthSub.php +++ b/library/Zend/Gdata/AuthSub.php @@ -119,16 +119,16 @@ public static function getAuthSubSessionToken( $response = $client->request('GET'); } catch (Zend_Http_Client_Exception $e) { require_once 'Zend/Gdata/App/HttpException.php'; - throw new Zend_Gdata_App_HttpException($e->getMessage(), $e); + throw new Zend_Gdata_App_HttpException($e->getMessage(), $e, $e); } // Parse Google's response if ($response->isSuccessful()) { $goog_resp = array(); foreach (explode("\n", (string) $response->getBody()) as $l) { - $l = chop($l); - if ($l) { - list($key, $val) = explode('=', chop($l), 2); + $l = rtrim($l); + if ($l !== '' && $l !== '0') { + list($key, $val) = explode('=', rtrim($l), 2); $goog_resp[$key] = $val; } } @@ -171,7 +171,7 @@ public static function AuthSubRevokeToken($token, $client = null, } catch (Zend_Http_Client_Exception $e) { ob_end_clean(); require_once 'Zend/Gdata/App/HttpException.php'; - throw new Zend_Gdata_App_HttpException($e->getMessage(), $e); + throw new Zend_Gdata_App_HttpException($e->getMessage(), $e, $e); } ob_end_clean(); // Parse Google's response @@ -213,7 +213,7 @@ public static function getAuthSubTokenInfo( } catch (Zend_Http_Client_Exception $e) { ob_end_clean(); require_once 'Zend/Gdata/App/HttpException.php'; - throw new Zend_Gdata_App_HttpException($e->getMessage(), $e); + throw new Zend_Gdata_App_HttpException($e->getMessage(), $e, $e); } ob_end_clean(); return $response->getBody(); diff --git a/library/Zend/Gdata/Books.php b/library/Zend/Gdata/Books.php index 48c5bb867c..b02d686ae7 100755 --- a/library/Zend/Gdata/Books.php +++ b/library/Zend/Gdata/Books.php @@ -105,11 +105,7 @@ public function getVolumeFeed($location = null) { if ($location == null) { $uri = self::VOLUME_FEED_URI; - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getFeed($uri, 'Zend_Gdata_Books_VolumeFeed'); } @@ -127,11 +123,7 @@ public function getVolumeEntry($volumeId = null, $location = null) { if ($volumeId !== null) { $uri = self::VOLUME_FEED_URI . "/" . $volumeId; - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getEntry($uri, 'Zend_Gdata_Books_VolumeEntry'); } @@ -145,11 +137,7 @@ public function getVolumeEntry($volumeId = null, $location = null) */ public function getUserLibraryFeed($location = null) { - if ($location == null) { - $uri = self::MY_LIBRARY_FEED_URI; - } else { - $uri = $location; - } + $uri = $location == null ? self::MY_LIBRARY_FEED_URI : $location; return parent::getFeed($uri, 'Zend_Gdata_Books_VolumeFeed'); } @@ -163,11 +151,7 @@ public function getUserLibraryFeed($location = null) */ public function getUserAnnotationFeed($location = null) { - if ($location == null) { - $uri = self::MY_ANNOTATION_FEED_URI; - } else { - $uri = $location; - } + $uri = $location == null ? self::MY_ANNOTATION_FEED_URI : $location; return parent::getFeed($uri, 'Zend_Gdata_Books_VolumeFeed'); } @@ -181,11 +165,7 @@ public function getUserAnnotationFeed($location = null) */ public function insertVolume($entry, $location = null) { - if ($location == null) { - $uri = self::MY_LIBRARY_FEED_URI; - } else { - $uri = $location; - } + $uri = $location == null ? self::MY_LIBRARY_FEED_URI : $location; return parent::insertEntry( $entry, $uri, 'Zend_Gdata_Books_VolumeEntry'); } diff --git a/library/Zend/Gdata/Books/VolumeQuery.php b/library/Zend/Gdata/Books/VolumeQuery.php index 37853f37c5..affe7b54db 100755 --- a/library/Zend/Gdata/Books/VolumeQuery.php +++ b/library/Zend/Gdata/Books/VolumeQuery.php @@ -97,16 +97,11 @@ public function getMinViewability() */ public function getQueryUrl() { - if (isset($this->_url)) { - $url = $this->_url; - } else { - $url = Zend_Gdata_Books::VOLUME_FEED_URI; - } + $url = $this->_url !== null ? $this->_url : Zend_Gdata_Books::VOLUME_FEED_URI; if ($this->getCategory() !== null) { $url .= '/-/' . $this->getCategory(); } - $url = $url . $this->getQueryString(); - return $url; + return $url . $this->getQueryString(); } } diff --git a/library/Zend/Gdata/Calendar.php b/library/Zend/Gdata/Calendar.php index 6169d9ca5f..2963a8819d 100644 --- a/library/Zend/Gdata/Calendar.php +++ b/library/Zend/Gdata/Calendar.php @@ -99,11 +99,7 @@ public function getCalendarEventFeed($location = null) { if ($location == null) { $uri = self::CALENDAR_EVENT_FEED_URI; - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getFeed($uri, 'Zend_Gdata_Calendar_EventFeed'); } @@ -118,11 +114,7 @@ public function getCalendarEventEntry($location = null) require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getEntry($uri, 'Zend_Gdata_Calendar_EventEntry'); } @@ -149,11 +141,7 @@ public function getCalendarListEntry($location = null) require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getEntry($uri,'Zend_Gdata_Calendar_ListEntry'); } @@ -162,8 +150,7 @@ public function insertEvent($event, $uri=null) if ($uri == null) { $uri = $this->_defaultPostUri; } - $newEvent = $this->insertEntry($event, $uri, 'Zend_Gdata_Calendar_EventEntry'); - return $newEvent; + return $this->insertEntry($event, $uri, 'Zend_Gdata_Calendar_EventEntry'); } } diff --git a/library/Zend/Gdata/Calendar/EventQuery.php b/library/Zend/Gdata/Calendar/EventQuery.php index 6e986be97c..200e345ded 100644 --- a/library/Zend/Gdata/Calendar/EventQuery.php +++ b/library/Zend/Gdata/Calendar/EventQuery.php @@ -396,7 +396,7 @@ public function setSingleEvents($value) if ($value !== null) { if (is_bool($value)) { $this->_params['singleevents'] = ($value?'true':'false'); - } elseif ($value == 'true' | $value == 'false') { + } elseif (($value == 'true' | $value == 'false') !== 0) { $this->_params['singleevents'] = $value; } else { require_once 'Zend/Gdata/App/Exception.php'; @@ -445,7 +445,7 @@ public function setFutureEvents($value) if ($value !== null) { if (is_bool($value)) { $this->_params['futureevents'] = ($value?'true':'false'); - } elseif ($value == 'true' | $value == 'false') { + } elseif (($value == 'true' | $value == 'false') !== 0) { $this->_params['futureevents'] = $value; } else { require_once 'Zend/Gdata/App/Exception.php'; @@ -464,11 +464,7 @@ public function setFutureEvents($value) */ public function getQueryUrl() { - if (isset($this->_url)) { - $uri = $this->_url; - } else { - $uri = $this->_defaultFeedUri; - } + $uri = $this->_url !== null ? $this->_url : $this->_defaultFeedUri; if ($this->getUser() != null) { $uri .= '/' . $this->getUser(); } @@ -484,8 +480,7 @@ public function getQueryUrl() $uri .= '/comments/' . $this->getComments(); } } - $uri .= $this->getQueryString(); - return $uri; + return $uri . $this->getQueryString(); } } diff --git a/library/Zend/Gdata/Calendar/Extension/Hidden.php b/library/Zend/Gdata/Calendar/Extension/Hidden.php index 376091b6f4..3ae27632ee 100644 --- a/library/Zend/Gdata/Calendar/Extension/Hidden.php +++ b/library/Zend/Gdata/Calendar/Extension/Hidden.php @@ -85,11 +85,9 @@ protected function takeAttributeFromDOM($attribute) case 'value': if ($attribute->nodeValue == "true") { $this->_value = true; - } - else if ($attribute->nodeValue == "false") { + } elseif ($attribute->nodeValue == "false") { $this->_value = false; - } - else { + } else { require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for gCal:selected#value."); } diff --git a/library/Zend/Gdata/Calendar/Extension/QuickAdd.php b/library/Zend/Gdata/Calendar/Extension/QuickAdd.php index b63df0b43d..ab72643fff 100644 --- a/library/Zend/Gdata/Calendar/Extension/QuickAdd.php +++ b/library/Zend/Gdata/Calendar/Extension/QuickAdd.php @@ -85,11 +85,9 @@ protected function takeAttributeFromDOM($attribute) case 'value': if ($attribute->nodeValue == "true") { $this->_value = true; - } - else if ($attribute->nodeValue == "false") { + } elseif ($attribute->nodeValue == "false") { $this->_value = false; - } - else { + } else { throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for gCal:selected#value."); } break; diff --git a/library/Zend/Gdata/Calendar/Extension/Selected.php b/library/Zend/Gdata/Calendar/Extension/Selected.php index f65b447a1d..fd6e0778f3 100644 --- a/library/Zend/Gdata/Calendar/Extension/Selected.php +++ b/library/Zend/Gdata/Calendar/Extension/Selected.php @@ -85,11 +85,9 @@ protected function takeAttributeFromDOM($attribute) case 'value': if ($attribute->nodeValue == "true") { $this->_value = true; - } - else if ($attribute->nodeValue == "false") { + } elseif ($attribute->nodeValue == "false") { $this->_value = false; - } - else { + } else { require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for gCal:selected#value."); } diff --git a/library/Zend/Gdata/Calendar/Extension/SendEventNotifications.php b/library/Zend/Gdata/Calendar/Extension/SendEventNotifications.php index aa41fec0c1..2b50e25b22 100644 --- a/library/Zend/Gdata/Calendar/Extension/SendEventNotifications.php +++ b/library/Zend/Gdata/Calendar/Extension/SendEventNotifications.php @@ -84,11 +84,9 @@ protected function takeAttributeFromDOM($attribute) case 'value': if ($attribute->nodeValue == "true") { $this->_value = true; - } - else if ($attribute->nodeValue == "false") { + } elseif ($attribute->nodeValue == "false") { $this->_value = false; - } - else { + } else { throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for gCal:selected#value."); } break; diff --git a/library/Zend/Gdata/ClientLogin.php b/library/Zend/Gdata/ClientLogin.php index 2e8d9bffe7..2ace711632 100644 --- a/library/Zend/Gdata/ClientLogin.php +++ b/library/Zend/Gdata/ClientLogin.php @@ -89,8 +89,7 @@ public static function getHttpClient($email, $password, $service = 'xapi', if (! ($email && $password)) { require_once 'Zend/Gdata/App/AuthException.php'; throw new Zend_Gdata_App_AuthException( - 'Please set your Google credentials before trying to ' . - 'authenticate'); + 'Please set your Google credentials before trying to authenticate'); } if ($client == null) { @@ -125,8 +124,7 @@ public static function getHttpClient($email, $password, $service = 'xapi', else { require_once 'Zend/Gdata/App/AuthException.php'; throw new Zend_Gdata_App_AuthException( - 'Please provide both a token ID and a user\'s response ' . - 'to the CAPTCHA challenge.'); + 'Please provide both a token ID and a user\'s response to the CAPTCHA challenge.'); } } @@ -138,16 +136,16 @@ public static function getHttpClient($email, $password, $service = 'xapi', $response = $client->request('POST'); } catch (Zend_Http_Client_Exception $e) { require_once 'Zend/Gdata/App/HttpException.php'; - throw new Zend_Gdata_App_HttpException($e->getMessage(), $e); + throw new Zend_Gdata_App_HttpException($e->getMessage(), $e, $e); } ob_end_clean(); // Parse Google's response $goog_resp = array(); foreach (explode("\n", $response->getBody()) as $l) { - $l = chop($l); - if ($l) { - list($key, $val) = explode('=', chop($l), 2); + $l = rtrim($l); + if ($l !== '' && $l !== '0') { + list($key, $val) = explode('=', rtrim($l), 2); $goog_resp[$key] = $val; } } diff --git a/library/Zend/Gdata/Docs.php b/library/Zend/Gdata/Docs.php index ec056c863a..34a93747ac 100755 --- a/library/Zend/Gdata/Docs.php +++ b/library/Zend/Gdata/Docs.php @@ -130,11 +130,7 @@ public function getDocumentListFeed($location = null) { if ($location === null) { $uri = self::DOCUMENTS_LIST_FEED_URI; - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getFeed($uri, 'Zend_Gdata_Docs_DocumentListFeed'); } @@ -152,11 +148,7 @@ public function getDocumentListEntry($location = null) throw new Zend_Gdata_App_InvalidArgumentException( 'Location must not be null' ); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getEntry($uri, 'Zend_Gdata_Docs_DocumentListEntry'); } @@ -245,11 +237,7 @@ public function uploadFile($fileLocation, $title = null, $mimeType = null, // Create the media source which describes the file. $fs = $this->newMediaFileSource($fileLocation); - if ($title !== null) { - $slugHeader = $title; - } else { - $slugHeader = $fileLocation; - } + $slugHeader = $title !== null ? $title : $fileLocation; // Set the slug header to tell the Google Documents server what the // title of the document should be and what the file extension was diff --git a/library/Zend/Gdata/Docs/Query.php b/library/Zend/Gdata/Docs/Query.php index 8d32d55683..8325ee5c1e 100755 --- a/library/Zend/Gdata/Docs/Query.php +++ b/library/Zend/Gdata/Docs/Query.php @@ -214,9 +214,7 @@ public function getQueryUrl() throw new Zend_Gdata_App_Exception( 'A projection must be provided for cell queries.'); } - - $uri .= $this->getQueryString(); - return $uri; + return $uri . $this->getQueryString(); } } diff --git a/library/Zend/Gdata/Entry.php b/library/Zend/Gdata/Entry.php index 6a7eae3568..c527ff2734 100644 --- a/library/Zend/Gdata/Entry.php +++ b/library/Zend/Gdata/Entry.php @@ -56,12 +56,10 @@ public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) $element = parent::getDOM($doc, $majorVersion, $minorVersion); // ETags are special. We only support them in protocol >= 2.X. // This will be duplicated by the HTTP ETag header. - if ($majorVersion >= 2) { - if ($this->_etag != null) { - $element->setAttributeNS($this->lookupNamespace('gd'), - 'gd:etag', - $this->_etag); - } + if ($majorVersion >= 2 && $this->_etag != null) { + $element->setAttributeNS($this->lookupNamespace('gd'), + 'gd:etag', + $this->_etag); } return $element; } diff --git a/library/Zend/Gdata/Extension/EntryLink.php b/library/Zend/Gdata/Extension/EntryLink.php index 6fb784f505..5ddaf0d199 100644 --- a/library/Zend/Gdata/Extension/EntryLink.php +++ b/library/Zend/Gdata/Extension/EntryLink.php @@ -101,11 +101,9 @@ protected function takeAttributeFromDOM($attribute) case 'readOnly': if ($attribute->nodeValue == "true") { $this->_readOnly = true; - } - else if ($attribute->nodeValue == "false") { + } elseif ($attribute->nodeValue == "false") { $this->_readOnly = false; - } - else { + } else { throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for gCal:selected#value."); } break; diff --git a/library/Zend/Gdata/Extension/FeedLink.php b/library/Zend/Gdata/Extension/FeedLink.php index 2bed52b202..cfd29eb096 100644 --- a/library/Zend/Gdata/Extension/FeedLink.php +++ b/library/Zend/Gdata/Extension/FeedLink.php @@ -109,11 +109,9 @@ protected function takeAttributeFromDOM($attribute) case 'readOnly': if ($attribute->nodeValue == "true") { $this->_readOnly = true; - } - else if ($attribute->nodeValue == "false") { + } elseif ($attribute->nodeValue == "false") { $this->_readOnly = false; - } - else { + } else { throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for gCal:selected#value."); } break; diff --git a/library/Zend/Gdata/Extension/RecurrenceException.php b/library/Zend/Gdata/Extension/RecurrenceException.php index 8bd3bbf9c8..01632be174 100644 --- a/library/Zend/Gdata/Extension/RecurrenceException.php +++ b/library/Zend/Gdata/Extension/RecurrenceException.php @@ -106,11 +106,9 @@ protected function takeAttributeFromDOM($attribute) case 'specialized': if ($attribute->nodeValue == "true") { $this->_specialized = true; - } - else if ($attribute->nodeValue == "false") { + } elseif ($attribute->nodeValue == "false") { $this->_specialized = false; - } - else { + } else { throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for gCal:selected#value."); } break; diff --git a/library/Zend/Gdata/Extension/Reminder.php b/library/Zend/Gdata/Extension/Reminder.php index bdb7e64500..729011da70 100644 --- a/library/Zend/Gdata/Extension/Reminder.php +++ b/library/Zend/Gdata/Extension/Reminder.php @@ -103,14 +103,15 @@ protected function takeAttributeFromDOM($attribute) public function __toString() { $s = ''; - if ($this->_absoluteTime) + if ($this->_absoluteTime) { $s = " at " . $this->_absoluteTime; - else if ($this->_days) + } elseif ($this->_days) { $s = " in " . $this->_days . " days"; - else if ($this->_hours) + } elseif ($this->_hours) { $s = " in " . $this->_hours . " hours"; - else if ($this->_minutes) + } elseif ($this->_minutes) { $s = " in " . $this->_minutes . " minutes"; + } return $this->_method . $s; } diff --git a/library/Zend/Gdata/Feed.php b/library/Zend/Gdata/Feed.php index 5274e4374e..b30f27bb7c 100644 --- a/library/Zend/Gdata/Feed.php +++ b/library/Zend/Gdata/Feed.php @@ -112,12 +112,10 @@ public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) // ETags are special. We only support them in protocol >= 2.X. // This will be duplicated by the HTTP ETag header. - if ($majorVersion >= 2) { - if ($this->_etag != null) { - $element->setAttributeNS($this->lookupNamespace('gd'), - 'gd:etag', - $this->_etag); - } + if ($majorVersion >= 2 && $this->_etag != null) { + $element->setAttributeNS($this->lookupNamespace('gd'), + 'gd:etag', + $this->_etag); } return $element; diff --git a/library/Zend/Gdata/Gapps.php b/library/Zend/Gdata/Gapps.php index 7f2924ef4f..db3fa39836 100644 --- a/library/Zend/Gdata/Gapps.php +++ b/library/Zend/Gdata/Gapps.php @@ -338,7 +338,7 @@ public function getBaseUrl($domain = null) { if ($domain !== null) { return self::APPS_BASE_FEED_URI . '/' . $domain; - } else if ($this->_domain !== null) { + } elseif ($this->_domain !== null) { return self::APPS_BASE_FEED_URI . '/' . $this->_domain; } else { require_once 'Zend/Gdata/App/InvalidArgumentException.php'; @@ -361,11 +361,7 @@ public function getUserFeed($location = null) { if ($location === null) { $uri = $this->getBaseUrl() . self::APPS_USER_PATH; - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getFeed($uri, 'Zend_Gdata_Gapps_UserFeed'); } @@ -383,11 +379,7 @@ public function getNicknameFeed($location = null) { if ($location === null) { $uri = $this->getBaseUrl() . self::APPS_NICKNAME_PATH; - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getFeed($uri, 'Zend_Gdata_Gapps_NicknameFeed'); } @@ -407,11 +399,7 @@ public function getGroupFeed($location = null) if ($location === null) { $uri = self::APPS_BASE_FEED_URI . self::APPS_GROUP_PATH . '/'; $uri .= $this->getDomain(); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getFeed($uri, 'Zend_Gdata_Gapps_GroupFeed'); } @@ -432,11 +420,7 @@ public function getMemberFeed($location = null) require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getFeed($uri, 'Zend_Gdata_Gapps_MemberFeed'); } @@ -457,11 +441,7 @@ public function getOwnerFeed($location = null) require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getFeed($uri, 'Zend_Gdata_Gapps_OwnerFeed'); } @@ -480,11 +460,7 @@ public function getEmailListFeed($location = null) { if ($location === null) { $uri = $this->getBaseUrl() . self::APPS_NICKNAME_PATH; - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getFeed($uri, 'Zend_Gdata_Gapps_EmailListFeed'); } @@ -504,11 +480,7 @@ public function getEmailListRecipientFeed($location) require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getFeed($uri, 'Zend_Gdata_Gapps_EmailListRecipientFeed'); } @@ -527,11 +499,7 @@ public function getUserEntry($location) require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getEntry($uri, 'Zend_Gdata_Gapps_UserEntry'); } @@ -550,11 +518,7 @@ public function getNicknameEntry($location) require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getEntry($uri, 'Zend_Gdata_Gapps_NicknameEntry'); } @@ -573,11 +537,7 @@ public function getGroupEntry($location = null) require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getEntry($uri, 'Zend_Gdata_Gapps_GroupEntry'); } @@ -596,11 +556,7 @@ public function getMemberEntry($location = null) require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getEntry($uri, 'Zend_Gdata_Gapps_MemberEntry'); } @@ -619,11 +575,7 @@ public function getOwnerEntry($location = null) require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getEntry($uri, 'Zend_Gdata_Gapps_OwnerEntry'); } @@ -642,11 +594,7 @@ public function getEmailListEntry($location) require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getEntry($uri, 'Zend_Gdata_Gapps_EmailListEntry'); } @@ -665,11 +613,7 @@ public function getEmailListRecipientEntry($location) require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getEntry($uri, 'Zend_Gdata_Gapps_EmailListRecipientEntry'); } @@ -691,8 +635,7 @@ public function insertUser($user, $uri = null) if ($uri === null) { $uri = $this->getBaseUrl() . self::APPS_USER_PATH; } - $newEntry = $this->insertEntry($user, $uri, 'Zend_Gdata_Gapps_UserEntry'); - return $newEntry; + return $this->insertEntry($user, $uri, 'Zend_Gdata_Gapps_UserEntry'); } /** @@ -714,8 +657,7 @@ public function insertNickname($nickname, $uri = null) if ($uri === null) { $uri = $this->getBaseUrl() . self::APPS_NICKNAME_PATH; } - $newEntry = $this->insertEntry($nickname, $uri, 'Zend_Gdata_Gapps_NicknameEntry'); - return $newEntry; + return $this->insertEntry($nickname, $uri, 'Zend_Gdata_Gapps_NicknameEntry'); } /** @@ -737,8 +679,7 @@ public function insertGroup($group, $uri = null) $uri = self::APPS_BASE_FEED_URI . self::APPS_GROUP_PATH . '/'; $uri .= $this->getDomain(); } - $newEntry = $this->insertEntry($group, $uri, 'Zend_Gdata_Gapps_GroupEntry'); - return $newEntry; + return $this->insertEntry($group, $uri, 'Zend_Gdata_Gapps_GroupEntry'); } /** @@ -761,8 +702,7 @@ public function insertMember($member, $uri = null) throw new Zend_Gdata_App_InvalidArgumentException( 'URI must not be null'); } - $newEntry = $this->insertEntry($member, $uri, 'Zend_Gdata_Gapps_MemberEntry'); - return $newEntry; + return $this->insertEntry($member, $uri, 'Zend_Gdata_Gapps_MemberEntry'); } /** @@ -785,8 +725,7 @@ public function insertOwner($owner, $uri = null) throw new Zend_Gdata_App_InvalidArgumentException( 'URI must not be null'); } - $newEntry = $this->insertEntry($owner, $uri, 'Zend_Gdata_Gapps_OwnerEntry'); - return $newEntry; + return $this->insertEntry($owner, $uri, 'Zend_Gdata_Gapps_OwnerEntry'); } /** @@ -808,8 +747,7 @@ public function insertEmailList($emailList, $uri = null) if ($uri === null) { $uri = $this->getBaseUrl() . self::APPS_EMAIL_LIST_PATH; } - $newEntry = $this->insertEntry($emailList, $uri, 'Zend_Gdata_Gapps_EmailListEntry'); - return $newEntry; + return $this->insertEntry($emailList, $uri, 'Zend_Gdata_Gapps_EmailListEntry'); } /** @@ -835,8 +773,7 @@ public function insertEmailListRecipient($recipient, $uri = null) } elseif ($uri instanceof Zend_Gdata_Gapps_EmailListEntry) { $uri = $uri->getLink('edit')->href; } - $newEntry = $this->insertEntry($recipient, $uri, 'Zend_Gdata_Gapps_EmailListRecipientEntry'); - return $newEntry; + return $this->insertEntry($recipient, $uri, 'Zend_Gdata_Gapps_EmailListRecipientEntry'); } /** @@ -1113,9 +1050,8 @@ public function retrieveNickname($nickname) { public function retrieveNicknames($username) { $query = $this->newNicknameQuery(); $query->setUsername($username); - $nicknameFeed = $this->retrieveAllEntriesForFeed( + return $this->retrieveAllEntriesForFeed( $this->getNicknameFeed($query)); - return $nicknameFeed; } /** diff --git a/library/Zend/Gdata/Gapps/EmailListQuery.php b/library/Zend/Gdata/Gapps/EmailListQuery.php index a57a0c7ddc..362aac07b0 100644 --- a/library/Zend/Gdata/Gapps/EmailListQuery.php +++ b/library/Zend/Gdata/Gapps/EmailListQuery.php @@ -180,8 +180,7 @@ public function getQueryUrl() if ($this->_emailListName !== null) { $uri .= '/' . $this->_emailListName; } - $uri .= $this->getQueryString(); - return $uri; + return $uri . $this->getQueryString(); } } diff --git a/library/Zend/Gdata/Gapps/Extension/Login.php b/library/Zend/Gdata/Gapps/Extension/Login.php index c95a05dec9..d921bf73ea 100644 --- a/library/Zend/Gdata/Gapps/Extension/Login.php +++ b/library/Zend/Gdata/Gapps/Extension/Login.php @@ -204,11 +204,9 @@ protected function takeAttributeFromDOM($attribute) case 'admin': if ($attribute->nodeValue == "true") { $this->_admin = true; - } - else if ($attribute->nodeValue == "false") { + } elseif ($attribute->nodeValue == "false") { $this->_admin = false; - } - else { + } else { require_once('Zend/Gdata/App/InvalidArgumentException.php'); throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for apps:login#admin."); } @@ -216,11 +214,9 @@ protected function takeAttributeFromDOM($attribute) case 'agreedToTerms': if ($attribute->nodeValue == "true") { $this->_agreedToTerms = true; - } - else if ($attribute->nodeValue == "false") { + } elseif ($attribute->nodeValue == "false") { $this->_agreedToTerms = false; - } - else { + } else { require_once('Zend/Gdata/App/InvalidArgumentException.php'); throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for apps:login#agreedToTerms."); } @@ -228,11 +224,9 @@ protected function takeAttributeFromDOM($attribute) case 'suspended': if ($attribute->nodeValue == "true") { $this->_suspended = true; - } - else if ($attribute->nodeValue == "false") { + } elseif ($attribute->nodeValue == "false") { $this->_suspended = false; - } - else { + } else { require_once('Zend/Gdata/App/InvalidArgumentException.php'); throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for apps:login#suspended."); } @@ -240,11 +234,9 @@ protected function takeAttributeFromDOM($attribute) case 'changePasswordAtNextLogin': if ($attribute->nodeValue == "true") { $this->_changePasswordAtNextLogin = true; - } - else if ($attribute->nodeValue == "false") { + } elseif ($attribute->nodeValue == "false") { $this->_changePasswordAtNextLogin = false; - } - else { + } else { require_once('Zend/Gdata/App/InvalidArgumentException.php'); throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for apps:login#changePasswordAtNextLogin."); } diff --git a/library/Zend/Gdata/Gapps/GroupQuery.php b/library/Zend/Gdata/Gapps/GroupQuery.php index 90b4dcccbe..82d204bb32 100644 --- a/library/Zend/Gdata/Gapps/GroupQuery.php +++ b/library/Zend/Gdata/Gapps/GroupQuery.php @@ -137,11 +137,7 @@ public function getMember() public function setDirectOnly($value) { if ($value !== null) { - if($value == true) { - $this->_params['directOnly'] = 'true'; - } else { - $this->_params['directOnly'] = 'false'; - } + $this->_params['directOnly'] = $value == true ? 'true' : 'false'; } else { unset($this->_params['directOnly']); } @@ -218,9 +214,7 @@ public function getQueryUrl() if(array_key_exists('member', $this->_params)) { $uri .= '/'; } - - $uri .= $this->getQueryString(); - return $uri; + return $uri . $this->getQueryString(); } } diff --git a/library/Zend/Gdata/Gapps/MemberQuery.php b/library/Zend/Gdata/Gapps/MemberQuery.php index 008baa129e..4ed0b1014a 100644 --- a/library/Zend/Gdata/Gapps/MemberQuery.php +++ b/library/Zend/Gdata/Gapps/MemberQuery.php @@ -187,8 +187,7 @@ public function getQueryUrl() if ($this->_memberId !== null) { $uri .= '/' . $this->_memberId; } - $uri .= $this->getQueryString(); - return $uri; + return $uri . $this->getQueryString(); } } diff --git a/library/Zend/Gdata/Gapps/NicknameQuery.php b/library/Zend/Gdata/Gapps/NicknameQuery.php index be14ae82c5..a3e8437444 100644 --- a/library/Zend/Gdata/Gapps/NicknameQuery.php +++ b/library/Zend/Gdata/Gapps/NicknameQuery.php @@ -179,8 +179,7 @@ public function getQueryUrl() if ($this->_nickname !== null) { $uri .= '/' . $this->_nickname; } - $uri .= $this->getQueryString(); - return $uri; + return $uri . $this->getQueryString(); } } diff --git a/library/Zend/Gdata/Gapps/OwnerQuery.php b/library/Zend/Gdata/Gapps/OwnerQuery.php index 4674bba67b..796a0387be 100644 --- a/library/Zend/Gdata/Gapps/OwnerQuery.php +++ b/library/Zend/Gdata/Gapps/OwnerQuery.php @@ -139,9 +139,7 @@ public function getQueryUrl() if ($this->_ownerEmail !== null) { $uri .= '/' . $this->_ownerEmail; } - - $uri .= $this->getQueryString(); - return $uri; + return $uri . $this->getQueryString(); } } diff --git a/library/Zend/Gdata/Gapps/Query.php b/library/Zend/Gdata/Gapps/Query.php index 1ed266f83a..7a2d0f7ef8 100644 --- a/library/Zend/Gdata/Gapps/Query.php +++ b/library/Zend/Gdata/Gapps/Query.php @@ -109,11 +109,9 @@ public function getBaseUrl($domain = null) { if ($domain !== null) { return Zend_Gdata_Gapps::APPS_BASE_FEED_URI . '/' . $domain; - } - else if ($this->_domain !== null) { + } elseif ($this->_domain !== null) { return Zend_Gdata_Gapps::APPS_BASE_FEED_URI . '/' . $this->_domain; - } - else { + } else { require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Domain must be specified.'); diff --git a/library/Zend/Gdata/Gapps/ServiceException.php b/library/Zend/Gdata/Gapps/ServiceException.php index 674ba4d156..f4ba6c760b 100644 --- a/library/Zend/Gdata/Gapps/ServiceException.php +++ b/library/Zend/Gdata/Gapps/ServiceException.php @@ -128,8 +128,7 @@ public function getErrors() { */ public function getError($errorCode) { if (array_key_exists($errorCode, $this->_errors)) { - $result = $this->_errors[$errorCode]; - return $result; + return $this->_errors[$errorCode]; } else { return null; } @@ -155,7 +154,7 @@ public function hasError($errorCode) { * @throws Zend_Gdata_App_Exception */ public function importFromString($string) { - if ($string) { + if ($string !== '' && $string !== '0') { // Check to see if an AppsForYourDomainError exists // // track_errors is temporarily enabled so that if an error @@ -176,7 +175,7 @@ public function importFromString($string) { // Ensure that the outermost node is an AppsForYourDomain error. // If it isn't, something has gone horribly wrong. $rootElement = $doc->getElementsByTagName($this->_rootElement)->item(0); - if (!$rootElement) { + if (!$rootElement instanceof \DOMElement) { require_once 'Zend/Gdata/App/Exception.php'; throw new Zend_Gdata_App_Exception('No root <' . $this->_rootElement . '> element found, cannot parse feed.'); } diff --git a/library/Zend/Gdata/Gapps/UserQuery.php b/library/Zend/Gdata/Gapps/UserQuery.php index a488594729..2b0ab6f9dd 100644 --- a/library/Zend/Gdata/Gapps/UserQuery.php +++ b/library/Zend/Gdata/Gapps/UserQuery.php @@ -140,8 +140,7 @@ public function getQueryUrl() if ($this->_username !== null) { $uri .= '/' . $this->_username; } - $uri .= $this->getQueryString(); - return $uri; + return $uri . $this->getQueryString(); } } diff --git a/library/Zend/Gdata/Geo/Extension/GeoRssWhere.php b/library/Zend/Gdata/Geo/Extension/GeoRssWhere.php index dd5e9472d7..22997e83a7 100755 --- a/library/Zend/Gdata/Geo/Extension/GeoRssWhere.php +++ b/library/Zend/Gdata/Geo/Extension/GeoRssWhere.php @@ -100,12 +100,10 @@ protected function takeChildFromDOM($child) { $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('gml') . ':' . 'Point'; - $point = new Zend_Gdata_Geo_Extension_GmlPoint(); - $point->transferFromDOM($child); - $this->_point = $point; - break; + if ($absoluteNodeName === $this->lookupNamespace('gml') . ':' . 'Point') { + $point = new Zend_Gdata_Geo_Extension_GmlPoint(); + $point->transferFromDOM($child); + $this->_point = $point; } } diff --git a/library/Zend/Gdata/Geo/Extension/GmlPoint.php b/library/Zend/Gdata/Geo/Extension/GmlPoint.php index c29bb8afd9..228074db04 100755 --- a/library/Zend/Gdata/Geo/Extension/GmlPoint.php +++ b/library/Zend/Gdata/Geo/Extension/GmlPoint.php @@ -100,12 +100,10 @@ protected function takeChildFromDOM($child) { $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; - switch ($absoluteNodeName) { - case $this->lookupNamespace('gml') . ':' . 'pos'; - $pos = new Zend_Gdata_Geo_Extension_GmlPos(); - $pos->transferFromDOM($child); - $this->_pos = $pos; - break; + if ($absoluteNodeName === $this->lookupNamespace('gml') . ':' . 'pos') { + $pos = new Zend_Gdata_Geo_Extension_GmlPos(); + $pos->transferFromDOM($child); + $this->_pos = $pos; } } diff --git a/library/Zend/Gdata/HttpAdapterStreamingProxy.php b/library/Zend/Gdata/HttpAdapterStreamingProxy.php index aa2efeb54c..33ed088d79 100644 --- a/library/Zend/Gdata/HttpAdapterStreamingProxy.php +++ b/library/Zend/Gdata/HttpAdapterStreamingProxy.php @@ -76,8 +76,7 @@ public function write($method, $uri, $http_ver = '1.1', $headers = array(), $bod if ($this->connected_to[0] != $host || $this->connected_to[1] != $port) { require_once 'Zend/Http/Client/Adapter/Exception.php'; throw new Zend_Http_Client_Adapter_Exception( - 'Trying to write but we are connected to the wrong proxy ' . - 'server'); + 'Trying to write but we are connected to the wrong proxy server'); } // Add Proxy-Authorization header diff --git a/library/Zend/Gdata/HttpAdapterStreamingSocket.php b/library/Zend/Gdata/HttpAdapterStreamingSocket.php index b7a09cded6..50c5dab4c0 100644 --- a/library/Zend/Gdata/HttpAdapterStreamingSocket.php +++ b/library/Zend/Gdata/HttpAdapterStreamingSocket.php @@ -79,7 +79,7 @@ public function write($method, $uri, $http_ver = '1.1', $headers = array(), // Build request headers $path = $uri->getPath(); - if ($uri->getQuery()) $path .= '?' . $uri->getQuery(); + if ($uri->getQuery() !== '' && $uri->getQuery() !== '0') $path .= '?' . $uri->getQuery(); $request = "{$method} {$path} HTTP/{$http_ver}\r\n"; foreach ($headers as $k => $v) { if (is_string($k)) $v = ucfirst($k) . ": $v"; diff --git a/library/Zend/Gdata/HttpClient.php b/library/Zend/Gdata/HttpClient.php index 2b8f45f674..fedf7efe81 100644 --- a/library/Zend/Gdata/HttpClient.php +++ b/library/Zend/Gdata/HttpClient.php @@ -129,8 +129,7 @@ public function setAuthSubPrivateKey($key, $passphrase = null) { if ($key != null && !function_exists('openssl_pkey_get_private')) { require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( - 'You cannot enable secure AuthSub if the openssl module ' . - 'is not enabled in your PHP installation.'); + 'You cannot enable secure AuthSub if the openssl module is not enabled in your PHP installation.'); } $this->_authSubPrivateKeyId = openssl_pkey_get_private( $key, $passphrase); diff --git a/library/Zend/Gdata/MimeBodyString.php b/library/Zend/Gdata/MimeBodyString.php index acbeac50db..cab336b563 100644 --- a/library/Zend/Gdata/MimeBodyString.php +++ b/library/Zend/Gdata/MimeBodyString.php @@ -66,9 +66,9 @@ public function __construct($sourceString) public function read($bytesRequested) { $len = strlen($this->_sourceString); - if($this->_bytesRead == $len) { + if ($this->_bytesRead == $len) { return FALSE; - } else if($bytesRequested > $len - $this->_bytesRead) { + } elseif ($bytesRequested > $len - $this->_bytesRead) { $bytesRequested = $len - $this->_bytesRead; } diff --git a/library/Zend/Gdata/Photos.php b/library/Zend/Gdata/Photos.php index d052b7c0c3..a2508cbd0b 100755 --- a/library/Zend/Gdata/Photos.php +++ b/library/Zend/Gdata/Photos.php @@ -155,14 +155,14 @@ public function getUserFeed($userName = null, $location = null) $location->setUser($userName); } $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Query) { + } elseif ($location instanceof Zend_Gdata_Query) { if ($userName !== null) { $location->setUser($userName); } $uri = $location->getQueryUrl(); - } else if ($location !== null) { + } elseif ($location !== null) { $uri = $location; - } else if ($userName !== null) { + } elseif ($userName !== null) { $uri = self::PICASA_BASE_FEED_URI . '/' . self::DEFAULT_PROJECTION . '/' . self::USER_PATH . '/' . $userName; @@ -190,14 +190,10 @@ public function getAlbumFeed($location = null) require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Photos_UserQuery) { + } elseif ($location instanceof Zend_Gdata_Photos_UserQuery) { $location->setType('feed'); $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getFeed($uri, 'Zend_Gdata_Photos_AlbumFeed'); } @@ -218,14 +214,10 @@ public function getPhotoFeed($location = null) $uri = self::PICASA_BASE_FEED_URI . '/' . self::DEFAULT_PROJECTION . '/' . self::COMMUNITY_SEARCH_PATH; - } else if ($location instanceof Zend_Gdata_Photos_UserQuery) { + } elseif ($location instanceof Zend_Gdata_Photos_UserQuery) { $location->setType('feed'); $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getFeed($uri, 'Zend_Gdata_Photos_PhotoFeed'); } @@ -243,14 +235,10 @@ public function getUserEntry($location) require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Photos_UserQuery) { + } elseif ($location instanceof Zend_Gdata_Photos_UserQuery) { $location->setType('entry'); $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getEntry($uri, 'Zend_Gdata_Photos_UserEntry'); } @@ -268,14 +256,10 @@ public function getAlbumEntry($location) require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Photos_UserQuery) { + } elseif ($location instanceof Zend_Gdata_Photos_UserQuery) { $location->setType('entry'); $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getEntry($uri, 'Zend_Gdata_Photos_AlbumEntry'); } @@ -293,14 +277,10 @@ public function getPhotoEntry($location) require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Photos_UserQuery) { + } elseif ($location instanceof Zend_Gdata_Photos_UserQuery) { $location->setType('entry'); $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getEntry($uri, 'Zend_Gdata_Photos_PhotoEntry'); } @@ -318,14 +298,10 @@ public function getTagEntry($location) require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Photos_UserQuery) { + } elseif ($location instanceof Zend_Gdata_Photos_UserQuery) { $location->setType('entry'); $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getEntry($uri, 'Zend_Gdata_Photos_TagEntry'); } @@ -343,14 +319,10 @@ public function getCommentEntry($location) require_once 'Zend/Gdata/App/InvalidArgumentException.php'; throw new Zend_Gdata_App_InvalidArgumentException( 'Location must not be null'); - } else if ($location instanceof Zend_Gdata_Photos_UserQuery) { + } elseif ($location instanceof Zend_Gdata_Photos_UserQuery) { $location->setType('entry'); $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Query) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + } else $uri = $location instanceof Zend_Gdata_Query ? $location->getQueryUrl() : $location; return parent::getEntry($uri, 'Zend_Gdata_Photos_CommentEntry'); } @@ -374,8 +346,7 @@ public function insertAlbumEntry($album, $uri = null) self::DEFAULT_PROJECTION . '/' . self::USER_PATH . '/' . self::DEFAULT_USER; } - $newEntry = $this->insertEntry($album, $uri, 'Zend_Gdata_Photos_AlbumEntry'); - return $newEntry; + return $this->insertEntry($album, $uri, 'Zend_Gdata_Photos_AlbumEntry'); } /** @@ -400,8 +371,7 @@ public function insertPhotoEntry($photo, $uri = null) throw new Zend_Gdata_App_InvalidArgumentException( 'URI must not be null'); } - $newEntry = $this->insertEntry($photo, $uri, 'Zend_Gdata_Photos_PhotoEntry'); - return $newEntry; + return $this->insertEntry($photo, $uri, 'Zend_Gdata_Photos_PhotoEntry'); } /** @@ -426,8 +396,7 @@ public function insertTagEntry($tag, $uri = null) throw new Zend_Gdata_App_InvalidArgumentException( 'URI must not be null'); } - $newEntry = $this->insertEntry($tag, $uri, 'Zend_Gdata_Photos_TagEntry'); - return $newEntry; + return $this->insertEntry($tag, $uri, 'Zend_Gdata_Photos_TagEntry'); } /** @@ -453,8 +422,7 @@ public function insertCommentEntry($comment, $uri = null) throw new Zend_Gdata_App_InvalidArgumentException( 'URI must not be null'); } - $newEntry = $this->insertEntry($comment, $uri, 'Zend_Gdata_Photos_CommentEntry'); - return $newEntry; + return $this->insertEntry($comment, $uri, 'Zend_Gdata_Photos_CommentEntry'); } /** diff --git a/library/Zend/Gdata/Photos/UserQuery.php b/library/Zend/Gdata/Photos/UserQuery.php index 02cf231a7c..cf3f35f688 100755 --- a/library/Zend/Gdata/Photos/UserQuery.php +++ b/library/Zend/Gdata/Photos/UserQuery.php @@ -134,11 +134,7 @@ public function getType() */ public function setUser($value) { - if ($value !== null) { - $this->_user = $value; - } else { - $this->_user = Zend_Gdata_Photos::DEFAULT_USER; - } + $this->_user = $value !== null ? $value : Zend_Gdata_Photos::DEFAULT_USER; } /** diff --git a/library/Zend/Gdata/Query.php b/library/Zend/Gdata/Query.php index fae21af6bd..92ba45d0e2 100644 --- a/library/Zend/Gdata/Query.php +++ b/library/Zend/Gdata/Query.php @@ -89,7 +89,7 @@ public function getQueryString() } $queryArray[] = urlencode($name) . '=' . urlencode($value); } - if (count($queryArray) > 0) { + if ($queryArray !== []) { return '?' . implode('&', $queryArray); } else { return ''; @@ -109,16 +109,11 @@ public function resetParameters() */ public function getQueryUrl() { - if ($this->_url == null) { - $url = $this->_defaultFeedUri; - } else { - $url = $this->_url; - } + $url = $this->_url == null ? $this->_defaultFeedUri : $this->_url; if ($this->getCategory() !== null) { $url .= '/-/' . $this->getCategory(); } - $url .= $this->getQueryString(); - return $url; + return $url . $this->getQueryString(); } /** @@ -284,7 +279,7 @@ public function getAlt() public function getMaxResults() { if (array_key_exists('max-results', $this->_params)) { - return intval($this->_params['max-results']); + return (int) $this->_params['max-results']; } else { return null; } @@ -308,7 +303,7 @@ public function getQuery() public function getStartIndex() { if (array_key_exists('start-index', $this->_params)) { - return intval($this->_params['start-index']); + return (int) $this->_params['start-index']; } else { return null; } diff --git a/library/Zend/Gdata/Spreadsheets.php b/library/Zend/Gdata/Spreadsheets.php index 8887b01ae2..ab599812f5 100644 --- a/library/Zend/Gdata/Spreadsheets.php +++ b/library/Zend/Gdata/Spreadsheets.php @@ -94,6 +94,7 @@ */ class Zend_Gdata_Spreadsheets extends Zend_Gdata { + public string $_server; const SPREADSHEETS_FEED_URI = 'https://spreadsheets.google.com/feeds/spreadsheets'; const SPREADSHEETS_POST_URI = 'https://spreadsheets.google.com/feeds/spreadsheets/private/full'; const WORKSHEETS_FEED_LINK_URI = 'http://schemas.google.com/spreadsheets/2006#worksheetsfeed'; @@ -138,7 +139,7 @@ public function getSpreadsheetFeed($location = null) { if ($location == null) { $uri = self::SPREADSHEETS_FEED_URI; - } else if ($location instanceof Zend_Gdata_Spreadsheets_DocumentQuery) { + } elseif ($location instanceof Zend_Gdata_Spreadsheets_DocumentQuery) { if ($location->getDocumentType() == null) { $location->setDocumentType('spreadsheets'); } @@ -183,7 +184,7 @@ public function getWorksheetFeed($location) $location->setDocumentType('worksheets'); } $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Spreadsheets_SpreadsheetEntry) { + } elseif ($location instanceof Zend_Gdata_Spreadsheets_SpreadsheetEntry) { $uri = $location->getLink(self::WORKSHEETS_FEED_LINK_URI)->href; } else { $uri = $location; @@ -222,7 +223,7 @@ public function getCellFeed($location) { if ($location instanceof Zend_Gdata_Spreadsheets_CellQuery) { $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Spreadsheets_WorksheetEntry) { + } elseif ($location instanceof Zend_Gdata_Spreadsheets_WorksheetEntry) { $uri = $location->getLink(self::CELL_FEED_LINK_URI)->href; } else { $uri = $location; @@ -238,11 +239,7 @@ public function getCellFeed($location) */ public function getCellEntry($location) { - if ($location instanceof Zend_Gdata_Spreadsheets_CellQuery) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + $uri = $location instanceof Zend_Gdata_Spreadsheets_CellQuery ? $location->getQueryUrl() : $location; return parent::getEntry($uri, 'Zend_Gdata_Spreadsheets_CellEntry'); } @@ -257,7 +254,7 @@ public function getListFeed($location) { if ($location instanceof Zend_Gdata_Spreadsheets_ListQuery) { $uri = $location->getQueryUrl(); - } else if ($location instanceof Zend_Gdata_Spreadsheets_WorksheetEntry) { + } elseif ($location instanceof Zend_Gdata_Spreadsheets_WorksheetEntry) { $uri = $location->getLink(self::LIST_FEED_LINK_URI)->href; } else { $uri = $location; @@ -274,11 +271,7 @@ public function getListFeed($location) */ public function getListEntry($location) { - if ($location instanceof Zend_Gdata_Spreadsheets_ListQuery) { - $uri = $location->getQueryUrl(); - } else { - $uri = $location; - } + $uri = $location instanceof Zend_Gdata_Spreadsheets_ListQuery ? $location->getQueryUrl() : $location; return parent::getEntry($uri, 'Zend_Gdata_Spreadsheets_ListEntry'); } @@ -304,8 +297,7 @@ public function updateCell($row, $col, $inputValue, $key, $wkshtId = 'default') $entry = $this->getCellEntry($query); $entry->setCell(new Zend_Gdata_Spreadsheets_Extension_Cell(null, $row, $col, $inputValue)); - $response = $entry->save(); - return $response; + return $entry->save(); } /** @@ -405,7 +397,7 @@ public function getSpreadsheetCellFeedContents($location, $range = null, $empty $cellQuery = null; if ($location instanceof Zend_Gdata_Spreadsheets_CellQuery) { $cellQuery = $location; - } else if ($location instanceof Zend_Gdata_Spreadsheets_WorksheetEntry) { + } elseif ($location instanceof Zend_Gdata_Spreadsheets_WorksheetEntry) { $url = $location->getLink(self::CELL_FEED_LINK_URI)->href; $cellQuery = new Zend_Gdata_Spreadsheets_CellQuery($url); } else { diff --git a/library/Zend/Gdata/Spreadsheets/CellQuery.php b/library/Zend/Gdata/Spreadsheets/CellQuery.php index 17790f9d32..4e74174e93 100644 --- a/library/Zend/Gdata/Spreadsheets/CellQuery.php +++ b/library/Zend/Gdata/Spreadsheets/CellQuery.php @@ -333,7 +333,7 @@ public function setReturnEmpty($value) { if (is_bool($value)) { $this->_params['return-empty'] = ($value?'true':'false'); - } else if ($value != null) { + } elseif ($value != null) { $this->_params['return-empty'] = $value; } else { unset($this->_params['return-empty']); @@ -399,9 +399,7 @@ public function getQueryUrl() } else { $uri = $this->_url; } - - $uri .= $this->getQueryString(); - return $uri; + return $uri . $this->getQueryString(); } /** diff --git a/library/Zend/Gdata/Spreadsheets/DocumentQuery.php b/library/Zend/Gdata/Spreadsheets/DocumentQuery.php index d5e879d68e..fad760354a 100644 --- a/library/Zend/Gdata/Spreadsheets/DocumentQuery.php +++ b/library/Zend/Gdata/Spreadsheets/DocumentQuery.php @@ -259,7 +259,7 @@ public function getQueryUrl() if ($this->_spreadsheetKey != null) { $uri .= '/'.$this->_spreadsheetKey; } - } else if ($this->_documentType == 'worksheets') { + } elseif ($this->_documentType == 'worksheets') { if ($this->_spreadsheetKey != null) { $uri .= '/'.$this->_spreadsheetKey; } else { @@ -271,9 +271,7 @@ public function getQueryUrl() $uri .= '/'.$this->_worksheetId; } } - - $uri .= $this->getQueryString(); - return $uri; + return $uri . $this->getQueryString(); } /** diff --git a/library/Zend/Gdata/Spreadsheets/Extension/Cell.php b/library/Zend/Gdata/Spreadsheets/Extension/Cell.php index 142f7af09a..6d51a0c6bd 100644 --- a/library/Zend/Gdata/Spreadsheets/Extension/Cell.php +++ b/library/Zend/Gdata/Spreadsheets/Extension/Cell.php @@ -98,8 +98,8 @@ public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) $element = parent::getDOM($doc, $majorVersion, $minorVersion); $element->setAttribute('row', $this->_row); $element->setAttribute('col', $this->_col); - if ($this->_inputValue) $element->setAttribute('inputValue', $this->_inputValue); - if ($this->_numericValue) $element->setAttribute('numericValue', $this->_numericValue); + if ($this->_inputValue !== '' && $this->_inputValue !== '0') $element->setAttribute('inputValue', $this->_inputValue); + if ($this->_numericValue !== '' && $this->_numericValue !== '0') $element->setAttribute('numericValue', $this->_numericValue); return $element; } diff --git a/library/Zend/Gdata/Spreadsheets/Extension/Custom.php b/library/Zend/Gdata/Spreadsheets/Extension/Custom.php index a02754fbe5..fc90c6b211 100644 --- a/library/Zend/Gdata/Spreadsheets/Extension/Custom.php +++ b/library/Zend/Gdata/Spreadsheets/Extension/Custom.php @@ -61,8 +61,7 @@ public function __construct($column = null, $value = null) public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) { - $element = parent::getDOM($doc, $majorVersion, $minorVersion); - return $element; + return parent::getDOM($doc, $majorVersion, $minorVersion); } /** diff --git a/library/Zend/Gdata/Spreadsheets/ListEntry.php b/library/Zend/Gdata/Spreadsheets/ListEntry.php index 3f950c1aa7..34768a699e 100644 --- a/library/Zend/Gdata/Spreadsheets/ListEntry.php +++ b/library/Zend/Gdata/Spreadsheets/ListEntry.php @@ -118,12 +118,10 @@ public function getCustomByName($name = null) { if ($name === null) { return $this->_customByName; + } elseif (array_key_exists($name, $this->customByName)) { + return $this->_customByName[$name]; } else { - if (array_key_exists($name, $this->customByName)) { - return $this->_customByName[$name]; - } else { - return null; - } + return null; } } diff --git a/library/Zend/Gdata/Spreadsheets/ListQuery.php b/library/Zend/Gdata/Spreadsheets/ListQuery.php index 3a6156b291..930cc21779 100644 --- a/library/Zend/Gdata/Spreadsheets/ListQuery.php +++ b/library/Zend/Gdata/Spreadsheets/ListQuery.php @@ -288,9 +288,7 @@ public function getQueryUrl() if ($this->_rowId != null) { $uri .= '/'.$this->_rowId; } - - $uri .= $this->getQueryString(); - return $uri; + return $uri . $this->getQueryString(); } /** diff --git a/library/Zend/Http/Client.php b/library/Zend/Http/Client.php index 24a120d6a3..5f524726f9 100644 --- a/library/Zend/Http/Client.php +++ b/library/Zend/Http/Client.php @@ -71,6 +71,10 @@ */ class Zend_Http_Client { + /** + * @var bool|mixed|string + */ + public $_stream_name; /** * HTTP request methods */ @@ -324,7 +328,7 @@ public function setUri($uri) } // We have no ports, set the defaults - if (! $uri->getPort()) { + if ($uri->getPort() === '' || $uri->getPort() === '0') { $uri->setPort(($uri->getScheme() == 'https' ? 443 : 80)); } @@ -645,7 +649,7 @@ public function setCookieJar($cookiejar = true) if ($cookiejar instanceof Zend_Http_CookieJar) { $this->cookiejar = $cookiejar; - } elseif ($cookiejar === true) { + } elseif ($cookiejar) { $this->cookiejar = new Zend_Http_CookieJar(); } elseif (! $cookiejar) { $this->cookiejar = null; @@ -697,7 +701,7 @@ public function setCookie($cookie, $value = null) $value = urlencode($value); } - if (isset($this->cookiejar)) { + if ($this->cookiejar !== null) { if ($cookie instanceof Zend_Http_Cookie) { $this->cookiejar->addCookie($cookie); } elseif (is_string($cookie) && $value !== null) { @@ -1049,9 +1053,9 @@ public function request($method = null) // @see ZF-11671 to unmask for some services to foo=val1&foo=val2 if ($this->getUnmaskStatus()) { if ($this->_queryBracketsEscaped) { - $query = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $query); + $query = preg_replace('/%5B(?:\d|[1-9]\d+)%5D=/', '=', $query); } else { - $query = preg_replace('/\\[(?:[0-9]|[1-9][0-9]+)\\]=/', '=', $query); + $query = preg_replace('/\[(?:\d|[1-9]\d+)\]=/', '=', $query); } } @@ -1070,7 +1074,7 @@ public function request($method = null) // Open the connection, send the request and read the response $this->adapter->connect($uri->getHost(), $uri->getPort(), - ($uri->getScheme() == 'https' ? true : false)); + ($uri->getScheme() == 'https')); if($this->config['output_stream']) { if($this->adapter instanceof Zend_Http_Client_Adapter_Stream) { @@ -1087,7 +1091,7 @@ public function request($method = null) $uri, $this->config['httpversion'], $headers, $body); $response = $this->adapter->read(); - if (! $response) { + if ($response === '' || $response === '0') { /** @see Zend_Http_Client_Exception */ require_once 'Zend/Http/Client/Exception.php'; throw new Zend_Http_Client_Exception('Unable to read response, or response is empty'); @@ -1115,7 +1119,7 @@ public function request($method = null) } // Load cookies into cookie jar - if (isset($this->cookiejar)) { + if ($this->cookiejar !== null) { $this->cookiejar->addCookiesFromResponse($response, $uri, $this->config['encodecookies']); } @@ -1189,8 +1193,7 @@ protected function _prepareHeaders() $host = $this->uri->getHost(); // If the port is not default, add it - if (! (($this->uri->getScheme() == 'http' && $this->uri->getPort() == 80) || - ($this->uri->getScheme() == 'https' && $this->uri->getPort() == 443))) { + if (!($this->uri->getScheme() == 'http' && $this->uri->getPort() == 80) && !($this->uri->getScheme() == 'https' && $this->uri->getPort() == 443)) { $host .= ':' . $this->uri->getPort(); } @@ -1198,25 +1201,19 @@ protected function _prepareHeaders() } // Set the connection header - if (! isset($this->headers['connection'])) { - if (! $this->config['keepalive']) { - $headers[] = "Connection: close"; - } + if (! isset($this->headers['connection']) && ! $this->config['keepalive']) { + $headers[] = "Connection: close"; } // Set the Accept-encoding header if not set - depending on whether // zlib is available or not. if (! isset($this->headers['accept-encoding'])) { - if (function_exists('gzinflate')) { - $headers[] = 'Accept-encoding: gzip, deflate'; - } else { - $headers[] = 'Accept-encoding: identity'; - } + $headers[] = function_exists('gzinflate') ? 'Accept-encoding: gzip, deflate' : 'Accept-encoding: identity'; } // Set the Content-Type header if (($this->method == self::POST || $this->method == self::PUT) && - (! isset($this->headers[strtolower(self::CONTENT_TYPE)]) && isset($this->enctype))) { + (! isset($this->headers[strtolower(self::CONTENT_TYPE)]) && $this->enctype !== null)) { $headers[] = self::CONTENT_TYPE . ': ' . $this->enctype; } @@ -1233,7 +1230,7 @@ protected function _prepareHeaders() } // Load cookies from cookie jar - if (isset($this->cookiejar)) { + if ($this->cookiejar !== null) { $cookstr = $this->cookiejar->getMatchingCookies($this->uri, true, Zend_Http_CookieJar::COOKIE_STRING_CONCAT); @@ -1268,12 +1265,12 @@ protected function _prepareBody() return ''; } - if (isset($this->raw_post_data) && is_resource($this->raw_post_data)) { + if ($this->raw_post_data !== null && is_resource($this->raw_post_data)) { return $this->raw_post_data; } // If we have raw_post_data set, just use it as the body. - if (isset($this->raw_post_data)) { + if ($this->raw_post_data !== null) { $this->setHeaders(self::CONTENT_LENGTH, strlen($this->raw_post_data)); return $this->raw_post_data; @@ -1282,12 +1279,12 @@ protected function _prepareBody() $body = ''; // If we have files to upload, force enctype to multipart/form-data - if (count ($this->files) > 0) { + if ($this->files !== []) { $this->setEncType(self::ENC_FORMDATA); } // If we have POST parameters or files, encode and add them to the body - if (count($this->paramsPost) > 0 || count($this->files) > 0) { + if ($this->paramsPost !== [] || $this->files !== []) { switch($this->enctype) { case self::ENC_FORMDATA: // Encode body as multipart/form-data @@ -1537,11 +1534,7 @@ protected static function _flattenParametersArray($parray, $prefix = null) // Calculate array key if ($prefix) { - if (is_int($name)) { - $key = $prefix . '[]'; - } else { - $key = $prefix . "[$name]"; - } + $key = is_int($name) ? $prefix . '[]' : $prefix . "[$name]"; } else { $key = $name; } diff --git a/library/Zend/Http/Client/Adapter/Curl.php b/library/Zend/Http/Client/Adapter/Curl.php index 263e066cdb..d61e87bee9 100644 --- a/library/Zend/Http/Client/Adapter/Curl.php +++ b/library/Zend/Http/Client/Adapter/Curl.php @@ -218,7 +218,7 @@ public function connect($host, $port = 80, $secure = false) // Do the actual connection $this->_curl = curl_init(); if ($port != 80) { - curl_setopt($this->_curl, CURLOPT_PORT, intval($port)); + curl_setopt($this->_curl, CURLOPT_PORT, (int) $port); } // Set connection timeout @@ -251,7 +251,7 @@ public function connect($host, $port = 80, $secure = false) throw new Zend_Http_Client_Adapter_Exception('Unable to Connect to ' . $host . ':' . $port); } - if ($secure !== false) { + if ($secure) { // Behave the same like Zend_Http_Adapter_Socket on SSL options. if (isset($this->_config['sslcert'])) { curl_setopt($this->_curl, CURLOPT_SSLCERT, $this->_config['sslcert']); @@ -383,7 +383,9 @@ public function write($method, $uri, $httpVersion = 1.1, $headers = array(), $bo if($this->out_stream) { // headers will be read into the response curl_setopt($this->_curl, CURLOPT_HEADER, false); - curl_setopt($this->_curl, CURLOPT_HEADERFUNCTION, array($this, "readHeader")); + curl_setopt($this->_curl, CURLOPT_HEADERFUNCTION, function ($curl, string $header) : int { + return $this->readHeader($curl, $header); + }); // and data will be written into the file curl_setopt($this->_curl, CURLOPT_FILE, $this->out_stream); } else { @@ -430,11 +432,9 @@ public function write($method, $uri, $httpVersion = 1.1, $headers = array(), $bo // set additional curl options if (isset($this->_config['curloptions'])) { foreach ((array)$this->_config['curloptions'] as $k => $v) { - if (!in_array($k, $this->_invalidOverwritableCurlOptions)) { - if (curl_setopt($this->_curl, $k, $v) == false) { - require_once 'Zend/Http/Client/Exception.php'; - throw new Zend_Http_Client_Exception(sprintf("Unknown or erroreous cURL option '%s' set", $k)); - } + if (!in_array($k, $this->_invalidOverwritableCurlOptions) && curl_setopt($this->_curl, $k, $v) == false) { + require_once 'Zend/Http/Client/Exception.php'; + throw new Zend_Http_Client_Exception(sprintf("Unknown or erroreous cURL option '%s' set", $k)); } } } diff --git a/library/Zend/Http/Client/Adapter/Proxy.php b/library/Zend/Http/Client/Adapter/Proxy.php index 9a00bb3a42..d593fc2e8d 100644 --- a/library/Zend/Http/Client/Adapter/Proxy.php +++ b/library/Zend/Http/Client/Adapter/Proxy.php @@ -188,7 +188,7 @@ public function write( // Build request headers if ($this->negotiated) { $path = $uri->getPath(); - if ($uri->getQuery()) { + if ($uri->getQuery() !== '' && $uri->getQuery() !== '0') { $path .= '?' . $uri->getQuery(); } $request = "$method $path HTTP/$http_ver\r\n"; @@ -217,13 +217,11 @@ public function write( ); } - if(is_resource($body)) { - if(stream_copy_to_stream($body, $this->socket) == 0) { - require_once 'Zend/Http/Client/Adapter/Exception.php'; - throw new Zend_Http_Client_Adapter_Exception( - 'Error writing request to server' - ); - } + if (is_resource($body) && stream_copy_to_stream($body, $this->socket) == 0) { + require_once 'Zend/Http/Client/Adapter/Exception.php'; + throw new Zend_Http_Client_Adapter_Exception( + 'Error writing request to server' + ); } return $request; @@ -280,7 +278,7 @@ protected function connectHandshake( $gotStatus = $gotStatus || (strpos($line, 'HTTP') !== false); if ($gotStatus) { $response .= $line; - if (!chop($line)) { + if (!rtrim($line)) { break; } } @@ -314,8 +312,7 @@ protected function connectHandshake( if (!$success) { require_once 'Zend/Http/Client/Adapter/Exception.php'; throw new Zend_Http_Client_Adapter_Exception( - 'Unable to connect to HTTPS server through proxy: could not ' - . 'negotiate secure connection.' + 'Unable to connect to HTTPS server through proxy: could not negotiate secure connection.' ); } } diff --git a/library/Zend/Http/Client/Adapter/Socket.php b/library/Zend/Http/Client/Adapter/Socket.php index 6ae1b1ff46..d1213a6246 100644 --- a/library/Zend/Http/Client/Adapter/Socket.php +++ b/library/Zend/Http/Client/Adapter/Socket.php @@ -195,27 +195,23 @@ public function connect($host, $port = 80, $secure = false) $host = ($secure ? $this->config['ssltransport'] : 'tcp') . '://' . $host; // If we are connected to the wrong host, disconnect first - if (($this->connected_to[0] != $host || $this->connected_to[1] != $port)) { - if (is_resource($this->socket)) $this->close(); + if ((($this->connected_to[0] != $host || $this->connected_to[1] != $port) && is_resource($this->socket))) { + $this->close(); } // Now, if we are not connected, connect if (! is_resource($this->socket) || ! $this->config['keepalive']) { $context = $this->getStreamContext(); if ($secure || $this->config['sslusecontext']) { - if ($this->config['sslcert'] !== null) { - if (! stream_context_set_option($context, 'ssl', 'local_cert', - $this->config['sslcert'])) { - require_once 'Zend/Http/Client/Adapter/Exception.php'; - throw new Zend_Http_Client_Adapter_Exception('Unable to set sslcert option'); - } + if ($this->config['sslcert'] !== null && ! stream_context_set_option($context, 'ssl', 'local_cert', + $this->config['sslcert'])) { + require_once 'Zend/Http/Client/Adapter/Exception.php'; + throw new Zend_Http_Client_Adapter_Exception('Unable to set sslcert option'); } - if ($this->config['sslpassphrase'] !== null) { - if (! stream_context_set_option($context, 'ssl', 'passphrase', - $this->config['sslpassphrase'])) { - require_once 'Zend/Http/Client/Adapter/Exception.php'; - throw new Zend_Http_Client_Adapter_Exception('Unable to set sslpassphrase option'); - } + if ($this->config['sslpassphrase'] !== null && ! stream_context_set_option($context, 'ssl', 'passphrase', + $this->config['sslpassphrase'])) { + require_once 'Zend/Http/Client/Adapter/Exception.php'; + throw new Zend_Http_Client_Adapter_Exception('Unable to set sslpassphrase option'); } } @@ -277,7 +273,7 @@ public function write($method, $uri, $http_ver = '1.1', $headers = array(), $bod // Build request headers $path = $uri->getPath(); - if ($uri->getQuery()) $path .= '?' . $uri->getQuery(); + if ($uri->getQuery() !== '' && $uri->getQuery() !== '0') $path .= '?' . $uri->getQuery(); $request = "{$method} {$path} HTTP/{$http_ver}\r\n"; foreach ($headers as $k => $v) { if (is_string($k)) $v = ucfirst($k) . ": $v"; @@ -297,11 +293,9 @@ public function write($method, $uri, $http_ver = '1.1', $headers = array(), $bod throw new Zend_Http_Client_Adapter_Exception('Error writing request to server'); } - if(is_resource($body)) { - if(stream_copy_to_stream($body, $this->socket) == 0) { - require_once 'Zend/Http/Client/Adapter/Exception.php'; - throw new Zend_Http_Client_Adapter_Exception('Error writing request to server'); - } + if (is_resource($body) && stream_copy_to_stream($body, $this->socket) == 0) { + require_once 'Zend/Http/Client/Adapter/Exception.php'; + throw new Zend_Http_Client_Adapter_Exception('Error writing request to server'); } return $request; @@ -387,7 +381,7 @@ public function read() } } else { $line = @fread($this->socket, $read_to - $current_pos); - if ($line === false || strlen($line) === 0) { + if ($line === false || $line === '') { $this->_checkSocketReadTimeout(); break; } @@ -439,7 +433,7 @@ public function read() } } else { $chunk = @fread($this->socket, $read_to - $current_pos); - if ($chunk === false || strlen($chunk) === 0) { + if ($chunk === false || $chunk === '') { $this->_checkSocketReadTimeout(); break; } @@ -462,7 +456,7 @@ public function read() } } else { $buff = @fread($this->socket, 8192); - if ($buff === false || strlen($buff) === 0) { + if ($buff === false || $buff === '') { $this->_checkSocketReadTimeout(); break; } else { @@ -470,7 +464,7 @@ public function read() } } - } while (feof($this->socket) === false); + } while (!feof($this->socket)); $this->close(); } @@ -536,8 +530,8 @@ public function setOutputStream($stream) */ public function __destruct() { - if (! $this->config['persistent']) { - if ($this->socket) $this->close(); + if (! $this->config['persistent'] && $this->socket) { + $this->close(); } } } diff --git a/library/Zend/Http/Client/Adapter/Test.php b/library/Zend/Http/Client/Adapter/Test.php index fc70b8af1f..4e638e5abe 100644 --- a/library/Zend/Http/Client/Adapter/Test.php +++ b/library/Zend/Http/Client/Adapter/Test.php @@ -156,7 +156,7 @@ public function write($method, $uri, $http_ver = '1.1', $headers = array(), $bod // Build request headers $path = $uri->getPath(); - if ($uri->getQuery()) $path .= '?' . $uri->getQuery(); + if ($uri->getQuery() !== '' && $uri->getQuery() !== '0') $path .= '?' . $uri->getQuery(); $request = "{$method} {$path} HTTP/{$http_ver}\r\n"; foreach ($headers as $k => $v) { if (is_string($k)) $v = ucfirst($k) . ": $v"; diff --git a/library/Zend/Http/Cookie.php b/library/Zend/Http/Cookie.php index d4400c2e26..3ded6631ae 100644 --- a/library/Zend/Http/Cookie.php +++ b/library/Zend/Http/Cookie.php @@ -114,12 +114,12 @@ public function __construct($name, $value, $domain, $expires = null, $path = nul throw new Zend_Http_Exception("Cookie name cannot contain these characters: =,; \\t\\r\\n\\013\\014 ({$name})"); } - if (! $this->name = (string) $name) { + if (($this->name = (string) $name) === '' || ($this->name = (string) $name) === '0') { require_once 'Zend/Http/Exception.php'; throw new Zend_Http_Exception('Cookies must have a name'); } - if (! $this->domain = (string) $domain) { + if (($this->domain = (string) $domain) === '' || ($this->domain = (string) $domain) === '0') { require_once 'Zend/Http/Exception.php'; throw new Zend_Http_Exception('Cookies must have a domain'); } @@ -247,14 +247,9 @@ public function match($uri, $matchSessionCookies = true, $now = null) if (! self::matchCookieDomain($this->getDomain(), $uri->getHost())) { return false; } - // Check that path matches using prefix match - if (! self::matchCookiePath($this->getPath(), $uri->getPath())) { - return false; - } - // If we didn't die until now, return true. - return true; + return self::matchCookiePath($this->getPath(), $uri->getPath()); } /** @@ -357,7 +352,7 @@ public static function fromString($cookieStr, $refUri = null, $encodeValue = tru if ($name !== '') { $ret = new self($name, $value, $domain, $expires, $path, $secure); - $ret->encodeValue = ($encodeValue) ? true : false; + $ret->encodeValue = $encodeValue; return $ret; } else { return false; @@ -376,12 +371,12 @@ public static function fromString($cookieStr, $refUri = null, $encodeValue = tru */ public static function matchCookieDomain($cookieDomain, $host) { - if (! $cookieDomain) { + if ($cookieDomain === '' || $cookieDomain === '0') { require_once 'Zend/Http/Exception.php'; throw new Zend_Http_Exception("\$cookieDomain is expected to be a cookie domain"); } - if (! $host) { + if ($host === '' || $host === '0') { require_once 'Zend/Http/Exception.php'; throw new Zend_Http_Exception("\$host is expected to be a host name"); } @@ -394,8 +389,8 @@ public static function matchCookieDomain($cookieDomain, $host) } // Check for either exact match or suffix match - return ($cookieDomain == $host || - preg_match('/\.' . preg_quote($cookieDomain) . '$/', $host)); + return ($cookieDomain === $host || + preg_match('/\.' . preg_quote($cookieDomain, '/') . '$/', $host)); } /** @@ -409,12 +404,12 @@ public static function matchCookieDomain($cookieDomain, $host) */ public static function matchCookiePath($cookiePath, $path) { - if (! $cookiePath) { + if ($cookiePath === '' || $cookiePath === '0') { require_once 'Zend/Http/Exception.php'; throw new Zend_Http_Exception("\$cookiePath is expected to be a cookie path"); } - if (! $path) { + if ($path === '' || $path === '0') { require_once 'Zend/Http/Exception.php'; throw new Zend_Http_Exception("\$path is expected to be a host name"); } diff --git a/library/Zend/Http/CookieJar.php b/library/Zend/Http/CookieJar.php index a76d1fcf10..e979df3449 100644 --- a/library/Zend/Http/CookieJar.php +++ b/library/Zend/Http/CookieJar.php @@ -248,7 +248,7 @@ public function getCookie($uri, $cookie_name, $ret_as = self::COOKIE_OBJECT) // Get correct cookie path $path = $uri->getPath(); $path = substr($path, 0, strrpos($path, '/')); - if (! $path) $path = '/'; + if ($path === '' || $path === '0') $path = '/'; if (isset($this->cookies[$uri->getHost()][$path][$cookie_name])) { $cookie = $this->cookies[$uri->getHost()][$path][$cookie_name]; @@ -290,7 +290,7 @@ protected function _flattenCookiesArray($ptr, $ret_as = self::COOKIE_OBJECT) { $ret = ($ret_as == self::COOKIE_STRING_CONCAT || $ret_as == self::COOKIE_STRING_CONCAT_STRICT) ? '' : array(); foreach ($ptr as $item) { if ($ret_as == self::COOKIE_STRING_CONCAT_STRICT) { - $postfix_combine = (!is_array($item) ? ' ' : ''); + $postfix_combine = (is_array($item) ? '' : ' '); $ret .= $this->_flattenCookiesArray($item, $ret_as) . $postfix_combine; } elseif ($ret_as == self::COOKIE_STRING_CONCAT) { $ret .= $this->_flattenCookiesArray($item, $ret_as); diff --git a/library/Zend/Http/Header/SetCookie.php b/library/Zend/Http/Header/SetCookie.php index ca5bef631d..3f6c37febb 100644 --- a/library/Zend/Http/Header/SetCookie.php +++ b/library/Zend/Http/Header/SetCookie.php @@ -52,6 +52,7 @@ class Zend_Http_Header_SetCookie { + public string $type; /** * Cookie name * @@ -246,11 +247,7 @@ public function getFieldValue() } $value = $this->getValue(); - if (strpos($value,'"')!==false) { - $value = '"'.urlencode(str_replace('"', '', $value)).'"'; - } else { - $value = urlencode($value); - } + $value = strpos($value,'"')!==false ? '"'.urlencode(str_replace('"', '', $value)).'"' : urlencode($value); $fieldValue = $this->getName() . '=' . $value; $version = $this->getVersion(); @@ -264,17 +261,17 @@ public function getFieldValue() } $expires = $this->getExpires(); - if ($expires) { + if ($expires !== 0) { $fieldValue .= '; Expires=' . $expires; } $domain = $this->getDomain(); - if ($domain) { + if ($domain !== '' && $domain !== '0') { $fieldValue .= '; Domain=' . $domain; } $path = $this->getPath(); - if ($path) { + if ($path !== '' && $path !== '0') { $fieldValue .= '; Path=' . $path; } diff --git a/library/Zend/Http/Response.php b/library/Zend/Http/Response.php index 01432a683e..475ffe789f 100644 --- a/library/Zend/Http/Response.php +++ b/library/Zend/Http/Response.php @@ -191,11 +191,7 @@ public function __construct($code, array $headers, $body = null, $version = '1.1 // If we got the response message, set it. Else, set it according to // the response code - if (is_string($message)) { - $this->message = $message; - } else { - $this->message = self::responseCodeAsText($code); - } + $this->message = is_string($message) ? $message : self::responseCodeAsText($code); } /** @@ -206,11 +202,7 @@ public function __construct($code, array $headers, $body = null, $version = '1.1 public function isError() { $restype = floor($this->code / 100); - if ($restype == 4 || $restype == 5) { - return true; - } - - return false; + return $restype == 4 || $restype == 5; } /** @@ -221,11 +213,8 @@ public function isError() public function isSuccessful() { $restype = floor($this->code / 100); - if ($restype == 2 || $restype == 1) { // Shouldn't 3xx count as success as well ??? - return true; - } - - return false; + // Shouldn't 3xx count as success as well ??? + return $restype == 2 || $restype == 1; } /** @@ -236,11 +225,7 @@ public function isSuccessful() public function isRedirect() { $restype = floor($this->code / 100); - if ($restype == 3) { - return true; - } - - return false; + return $restype == 3; } /** @@ -504,7 +489,7 @@ public static function extractHeaders($response_str) // First, split body and headers. Headers are separated from the // message at exactly the sequence "\r\n\r\n" $parts = preg_split('|(?:\r\n){2}|m', $response_str, 2); - if (! $parts[0]) { + if ($parts[0] === '' || $parts[0] === '0') { return $headers; } diff --git a/library/Zend/Http/UserAgent/AbstractDevice.php b/library/Zend/Http/UserAgent/AbstractDevice.php index 0125a05c50..c0439a8193 100644 --- a/library/Zend/Http/UserAgent/AbstractDevice.php +++ b/library/Zend/Http/UserAgent/AbstractDevice.php @@ -33,6 +33,8 @@ abstract class Zend_Http_UserAgent_AbstractDevice implements Zend_Http_UserAgent_Device { + public $device_os; + public $list; /** * Browser signature * @@ -319,7 +321,7 @@ protected function _getDefaultFeatures() $this->setFeature('is_' . strtolower($this->getType()), true, 'product_info'); /* sets the browser name */ - if (isset($this->list) && empty($this->_browser)) { + if (property_exists($this, 'list') && $this->list !== null && empty($this->_browser)) { $lowerUserAgent = strtolower($this->getUserAgent()); foreach ($this->list as $browser_signature) { if (strpos($lowerUserAgent, $browser_signature) !== false) { @@ -354,20 +356,16 @@ protected function _getDefaultFeatures() if (strpos($this->_server['server_software'], 'Unix') !== false) { $server['os'] = 'unix'; - if (isset($_ENV['MACHTYPE'])) { - if (strpos($_ENV['MACHTYPE'], 'linux') !== false) { - $server['os'] = 'linux'; - } + if (isset($_ENV['MACHTYPE']) && strpos($_ENV['MACHTYPE'], 'linux') !== false) { + $server['os'] = 'linux'; } } elseif (strpos($this->_server['server_software'], 'Win') !== false) { $server['os'] = 'windows'; } - if (preg_match('/Apache\/([0-9\.]*)/', (string) $this->_server['server_software'], $arr)) { - if ($arr[1]) { - $server['version'] = $arr[1]; - $server['server'] = 'apache'; - } + if (preg_match('/Apache\/([0-9\.]*)/', (string) $this->_server['server_software'], $arr) && $arr[1]) { + $server['version'] = $arr[1]; + $server['server'] = 'apache'; } } @@ -445,7 +443,7 @@ public static function extractFromUserAgent($userAgent) // some browsers do not have a platform token $result['device_os_token'] = $result['compatibility_flag']; } - if ($match2) { + if ($match2 !== []) { $i = 0; $max = count($match2[0]); for ($i = 0; $i < $max; $i ++) { @@ -465,11 +463,9 @@ public static function extractFromUserAgent($userAgent) 'U' => 'strong security', 'I' => 'weak security', ); - if (!empty($result['browser_token'])) { - if (isset($security[$result['browser_token']])) { - $result['security_level'] = $security[$result['browser_token']]; - unset($result['browser_token']); - } + if (!empty($result['browser_token']) && isset($security[$result['browser_token']])) { + $result['security_level'] = $security[$result['browser_token']]; + unset($result['browser_token']); } $product = strtolower($result['browser_name']); @@ -521,30 +517,27 @@ public static function extractFromUserAgent($userAgent) $result['browser_engine'] = 'MSIE'; $result['browser_name'] = 'Internet Explorer'; } - if (isset($result['device_os_token'])) { - if (strpos($result['device_os_token'], 'Win') !== false) { - - $windows = array( - 'Windows NT 6.1' => 'Windows 7', - 'Windows NT 6.0' => 'Windows Vista', - 'Windows NT 5.2' => 'Windows Server 2003', - 'Windows NT 5.1' => 'Windows XP', - 'Windows NT 5.01' => 'Windows 2000 SP1', - 'Windows NT 5.0' => 'Windows 2000', - 'Windows NT 4.0' => 'Microsoft Windows NT 4.0', - 'WinNT' => 'Microsoft Windows NT 4.0', - 'Windows 98; Win 9x 4.90' => 'Windows Me', - 'Windows 98' => 'Windows 98', - 'Win98' => 'Windows 98', - 'Windows 95' => 'Windows 95', - 'Win95' => 'Windows 95', - 'Windows CE' => 'Windows CE', - ); - if (isset($windows[$result['device_os_token']])) { - $result['device_os_name'] = $windows[$result['device_os_token']]; - } else { - $result['device_os_name'] = $result['device_os_token']; - } + if (isset($result['device_os_token']) && strpos($result['device_os_token'], 'Win') !== false) { + $windows = array( + 'Windows NT 6.1' => 'Windows 7', + 'Windows NT 6.0' => 'Windows Vista', + 'Windows NT 5.2' => 'Windows Server 2003', + 'Windows NT 5.1' => 'Windows XP', + 'Windows NT 5.01' => 'Windows 2000 SP1', + 'Windows NT 5.0' => 'Windows 2000', + 'Windows NT 4.0' => 'Microsoft Windows NT 4.0', + 'WinNT' => 'Microsoft Windows NT 4.0', + 'Windows 98; Win 9x 4.90' => 'Windows Me', + 'Windows 98' => 'Windows 98', + 'Win98' => 'Windows 98', + 'Windows 95' => 'Windows 95', + 'Win95' => 'Windows 95', + 'Windows CE' => 'Windows CE', + ); + if (isset($windows[$result['device_os_token']])) { + $result['device_os_name'] = $windows[$result['device_os_token']]; + } else { + $result['device_os_name'] = $result['device_os_token']; } } @@ -554,25 +547,23 @@ public static function extractFromUserAgent($userAgent) 'iPod', 'iPad', ); - if (isset($result['compatibility_flag'])) { - if (in_array($result['compatibility_flag'], $apple_device)) { - $result['device'] = strtolower($result['compatibility_flag']); - $result['device_os_token'] = 'iPhone OS'; - if (isset($comment[3])) { - $result['browser_language'] = trim($comment[3]); - } - if (isset($result['others']['detail'][1])) { - $result['browser_version'] = $result['others']['detail'][1][2]; - } elseif (isset($result['others']['detail']) && count($result['others']['detail'])) { - $result['browser_version'] = $result['others']['detail'][0][2]; - } - if (!empty($result['others']['detail'][2])) { - $result['firmware'] = $result['others']['detail'][2][2]; - } - if (!empty($result['others']['detail'][3])) { - $result['browser_name'] = $result['others']['detail'][3][1]; - $result['browser_build'] = $result['others']['detail'][3][2]; - } + if (isset($result['compatibility_flag']) && in_array($result['compatibility_flag'], $apple_device)) { + $result['device'] = strtolower($result['compatibility_flag']); + $result['device_os_token'] = 'iPhone OS'; + if (isset($comment[3])) { + $result['browser_language'] = trim($comment[3]); + } + if (isset($result['others']['detail'][1])) { + $result['browser_version'] = $result['others']['detail'][1][2]; + } elseif (isset($result['others']['detail']) && count($result['others']['detail'])) { + $result['browser_version'] = $result['others']['detail'][0][2]; + } + if (!empty($result['others']['detail'][2])) { + $result['firmware'] = $result['others']['detail'][2][2]; + } + if (!empty($result['others']['detail'][3])) { + $result['browser_name'] = $result['others']['detail'][3][1]; + $result['browser_build'] = $result['others']['detail'][3][2]; } } @@ -636,7 +627,7 @@ public static function extractFromUserAgent($userAgent) // Gecko (Firefox or compatible) if ($result['others']['detail'][0][1] == 'Gecko') { $searchRV = true; - if (!empty($result['others']['detail'][1][1]) && !empty($result['others']['detail'][count($result['others']['detail']) - 1][2]) || strpos(strtolower($result['others']['full']), 'opera') !== false) { + if (!empty($result['others']['detail'][1][1]) && !empty($result['others']['detail'][count($result['others']['detail']) - 1][2]) || stripos($result['others']['full'], 'opera') !== false) { $searchRV = false; $result['browser_engine'] = $result['others']['detail'][0][1]; @@ -713,10 +704,8 @@ public static function extractFromUserAgent($userAgent) } // Opera Mini - if (isset($result["browser_token"])) { - if (strpos($result["browser_token"], 'Opera Mini') !== false) { - $result['browser_name'] = 'Opera Mini'; - } + if (isset($result["browser_token"]) && strpos($result["browser_token"], 'Opera Mini') !== false) { + $result['browser_name'] = 'Opera Mini'; } // Symbian @@ -726,17 +715,13 @@ public static function extractFromUserAgent($userAgent) } // UA ends with 'Opera X.XX' - if (isset($result['browser_name']) && isset($result['browser_engine'])) { - if ($result['browser_name'] == 'Opera' && $result['browser_engine'] == 'Gecko' && empty($result['browser_version'])) { - $result['browser_version'] = $result['others']['detail'][count($result['others']['detail']) - 1][1]; - } + if (isset($result['browser_name']) && isset($result['browser_engine']) && ($result['browser_name'] == 'Opera' && $result['browser_engine'] == 'Gecko' && empty($result['browser_version']))) { + $result['browser_version'] = $result['others']['detail'][count($result['others']['detail']) - 1][1]; } // cleanup - if (isset($result['browser_version']) && isset($result['browser_build'])) { - if ($result['browser_version'] == $result['browser_build']) { - unset($result['browser_build']); - } + if (isset($result['browser_version']) && isset($result['browser_build']) && $result['browser_version'] == $result['browser_build']) { + unset($result['browser_build']); } // compatibility @@ -744,10 +729,8 @@ public static function extractFromUserAgent($userAgent) $compatibility['Gecko'] = 'Firefox'; $compatibility['MSIE'] = 'Internet Explorer'; $compatibility['Presto'] = 'Opera'; - if (!empty($result['browser_engine'])) { - if (isset($compatibility[$result['browser_engine']])) { - $result['browser_compatibility'] = $compatibility[$result['browser_engine']]; - } + if (!empty($result['browser_engine']) && isset($compatibility[$result['browser_engine']])) { + $result['browser_compatibility'] = $compatibility[$result['browser_engine']]; } ksort($result); @@ -985,11 +968,9 @@ protected static function _matchAgentAgainstSignatures($userAgent, $signatures) { $userAgent = strtolower($userAgent); foreach ($signatures as $signature) { - if (!empty($signature)) { - if (strpos($userAgent, $signature) !== false) { - // Browser signature was found in user agent string - return true; - } + if (!empty($signature) && strpos($userAgent, $signature) !== false) { + // Browser signature was found in user agent string + return true; } } return false; diff --git a/library/Zend/Http/UserAgent/Features/Adapter/DeviceAtlas.php b/library/Zend/Http/UserAgent/Features/Adapter/DeviceAtlas.php index 26cb0e97e7..9c318aca48 100644 --- a/library/Zend/Http/UserAgent/Features/Adapter/DeviceAtlas.php +++ b/library/Zend/Http/UserAgent/Features/Adapter/DeviceAtlas.php @@ -44,11 +44,9 @@ class Zend_Http_UserAgent_Features_Adapter_DeviceAtlas implements Zend_Http_User */ public static function getFromRequest($request, array $config) { - if (!class_exists('Mobi_Mtld_DA_Api')) { - if (!isset($config['deviceatlas'])) { - require_once 'Zend/Http/UserAgent/Features/Exception.php'; - throw new Zend_Http_UserAgent_Features_Exception('"DeviceAtlas" configuration is not defined'); - } + if (!class_exists('Mobi_Mtld_DA_Api') && !isset($config['deviceatlas'])) { + require_once 'Zend/Http/UserAgent/Features/Exception.php'; + throw new Zend_Http_UserAgent_Features_Exception('"DeviceAtlas" configuration is not defined'); } $config = $config['deviceatlas']; @@ -71,8 +69,6 @@ public static function getFromRequest($request, array $config) //load the device data-tree : e.g. 'json/DeviceAtlas.json $tree = Mobi_Mtld_DA_Api::getTreeFromFile($config['deviceatlas_data']); - $properties = Mobi_Mtld_DA_Api::getProperties($tree, $request['http_user_agent']); - - return $properties; + return Mobi_Mtld_DA_Api::getProperties($tree, $request['http_user_agent']); } } diff --git a/library/Zend/Http/UserAgent/Mobile.php b/library/Zend/Http/UserAgent/Mobile.php index 3450552db2..112362b3b0 100644 --- a/library/Zend/Http/UserAgent/Mobile.php +++ b/library/Zend/Http/UserAgent/Mobile.php @@ -278,32 +278,23 @@ class Zend_Http_UserAgent_Mobile extends Zend_Http_UserAgent_AbstractDevice public static function match($userAgent, $server) { // To have a quick identification, try light-weight tests first - if (isset($server['all_http'])) { - if (strpos(strtolower(str_replace(' ', '', $server['all_http'])), 'operam') !== false) { - // Opera Mini or Opera Mobi - return true; - } + if (isset($server['all_http']) && stripos(str_replace(' ', '', $server['all_http']), 'operam') !== false) { + // Opera Mini or Opera Mobi + return true; } if (isset($server['http_x_wap_profile']) || isset($server['http_profile'])) { return true; } - if (isset($server['http_accept'])) { - if (self::_matchAgentAgainstSignatures($server['http_accept'], self::$_haTerms)) { - return true; - } - } - - if (self::userAgentStart($userAgent)) { + if (isset($server['http_accept']) && self::_matchAgentAgainstSignatures($server['http_accept'], self::$_haTerms)) { return true; } - if (self::_matchAgentAgainstSignatures($userAgent, self::$_uaSignatures)) { + if (self::userAgentStart($userAgent) !== '' && self::userAgentStart($userAgent) !== '0') { return true; } - - return false; + return self::_matchAgentAgainstSignatures($userAgent, self::$_uaSignatures); } /** diff --git a/library/Zend/Json.php b/library/Zend/Json.php index 791ca28aa5..d38817b9b4 100644 --- a/library/Zend/Json.php +++ b/library/Zend/Json.php @@ -74,7 +74,7 @@ class Zend_Json public static function decode($encodedValue, $objectDecodeType = Zend_Json::TYPE_ARRAY) { $encodedValue = (string) $encodedValue; - if (function_exists('json_decode') && self::$useBuiltinEncoderDecoder !== true) { + if (function_exists('json_decode') && !self::$useBuiltinEncoderDecoder) { $decode = json_decode($encodedValue, $objectDecodeType); // php < 5.3 @@ -150,7 +150,7 @@ public static function encode($valueToEncode, $cycleCheck = false, $options = ar } // Encoding - if (function_exists('json_encode') && self::$useBuiltinEncoderDecoder !== true) { + if (function_exists('json_encode') && !self::$useBuiltinEncoderDecoder) { $encodedResult = json_encode($valueToEncode); } else { require_once 'Zend/Json/Encoder.php'; @@ -206,7 +206,7 @@ protected static function _recursiveJsonExprFinder(&$value, array &$javascriptEx ); $value = $magicKey; } elseif (is_array($value)) { - foreach ($value as $k => $v) { + foreach (array_keys($value) as $k) { $value[$k] = self::_recursiveJsonExprFinder($value[$k], $javascriptExpressions, $k); } } elseif (is_object($value)) { diff --git a/library/Zend/Json/Decoder.php b/library/Zend/Json/Decoder.php index 5a11595f80..26b6597b61 100644 --- a/library/Zend/Json/Decoder.php +++ b/library/Zend/Json/Decoder.php @@ -34,6 +34,10 @@ */ class Zend_Json_Decoder { + /** + * @var bool|float|int|mixed|string|null + */ + public $_tokenValue; /** * Parse tokens used to decode the JSON object. These are not * for public consumption, they are just used internally to the @@ -433,7 +437,7 @@ protected function _getNextToken() $chr = $str[$i]; if ($chr == '-' || $chr == '.' || ($chr >= '0' && $chr <= '9')) { - if (preg_match('/-?([0-9])*(\.[0-9]*)?((e|E)((-|\+)?)[0-9]+)?/s', + if (preg_match('/-?(\d)*(\.\d*)?((e|E)((-|\+)?)\d+)?/s', $str, $matches, PREG_OFFSET_CAPTURE, $start) && $matches[0][1] == $start) { $datum = $matches[0][0]; @@ -443,7 +447,7 @@ protected function _getNextToken() require_once 'Zend/Json/Exception.php'; throw new Zend_Json_Exception("Octal notation not supported by JSON (value: $datum)"); } else { - $val = intval($datum); + $val = (int) $datum; $fVal = floatval($datum); $this->_tokenValue = ($val == $fVal ? $val : $fVal); } @@ -555,18 +559,18 @@ protected static function _utf162utf8($utf16) $bytes = (ord($utf16[0]) << 8) | ord($utf16[1]); switch (true) { - case ((0x7F & $bytes) == $bytes): + case ((0x7F & $bytes) === $bytes): // this case should never be reached, because we are in ASCII range // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0x7F & $bytes); - case (0x07FF & $bytes) == $bytes: + case (0x07FF & $bytes) === $bytes: // return a 2-byte UTF-8 character // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0xC0 | (($bytes >> 6) & 0x1F)) . chr(0x80 | ($bytes & 0x3F)); - case (0xFFFF & $bytes) == $bytes: + case (0xFFFF & $bytes) === $bytes: // return a 3-byte UTF-8 character // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0xE0 | (($bytes >> 12) & 0x0F)) diff --git a/library/Zend/Json/Encoder.php b/library/Zend/Json/Encoder.php index 9013b285c3..5d047b3700 100644 --- a/library/Zend/Json/Encoder.php +++ b/library/Zend/Json/Encoder.php @@ -73,7 +73,7 @@ protected function __construct($cycleCheck = false, $options = array()) */ public static function encode($value, $cycleCheck = false, $options = array()) { - $encoder = new self(($cycleCheck) ? true : false, $options); + $encoder = new self($cycleCheck, $options); return $encoder->_encodeValue($value); } @@ -91,7 +91,7 @@ protected function _encodeValue(&$value) { if (is_object($value)) { return $this->_encodeObject($value); - } else if (is_array($value)) { + } elseif (is_array($value)) { return $this->_encodeArray($value); } @@ -168,11 +168,7 @@ protected function _encodeObject(&$value) */ protected function _wasVisited(&$value) { - if (in_array($value, $this->_visited, true)) { - return true; - } - - return false; + return in_array($value, $this->_visited, true); } diff --git a/library/Zend/Json/Server.php b/library/Zend/Json/Server.php index 817eeb26c7..b9f9268171 100644 --- a/library/Zend/Json/Server.php +++ b/library/Zend/Json/Server.php @@ -310,15 +310,13 @@ public function autoEmitResponse() */ public function __call($method, $args) { - if (preg_match('/^(set|get)/', $method, $matches)) { - if (in_array($method, $this->_getSmdMethods())) { - if ('set' == $matches[1]) { - $value = array_shift($args); - $this->getServiceMap()->$method($value); - return $this; - } else { - return $this->getServiceMap()->$method(); - } + if (preg_match('/^(set|get)/', $method, $matches) && in_array($method, $this->_getSmdMethods())) { + if ('set' == $matches[1]) { + $value = array_shift($args); + $this->getServiceMap()->$method($value); + return $this; + } else { + return $this->getServiceMap()->$method(); } } return null; @@ -385,7 +383,7 @@ protected function _getDefaultParams(array $args, array $params) if (array_key_exists('default', $param)) { $value = $param['default']; } - array_push($args, $value); + $args[] = $value; } return $args; } @@ -425,7 +423,7 @@ protected function _getParams(Zend_Server_Method_Definition $method) } elseif (in_array($newType, $params[$key]['type'])) { continue; } - array_push($params[$key]['type'], $parameter->getType()); + $params[$key]['type'][] = $parameter->getType(); } } return $params; diff --git a/library/Zend/Json/Server/Cache.php b/library/Zend/Json/Server/Cache.php index bb86870a4e..83bdd27c50 100644 --- a/library/Zend/Json/Server/Cache.php +++ b/library/Zend/Json/Server/Cache.php @@ -50,12 +50,7 @@ public static function saveSmd($filename, Zend_Json_Server $server) { return false; } - - if (0 === @file_put_contents($filename, $server->getServiceMap()->toJson())) { - return false; - } - - return true; + return 0 !== @file_put_contents($filename, $server->getServiceMap()->toJson()); } /** diff --git a/library/Zend/Json/Server/Request.php b/library/Zend/Json/Server/Request.php index 72983e4897..cb41fc48e7 100644 --- a/library/Zend/Json/Server/Request.php +++ b/library/Zend/Json/Server/Request.php @@ -221,11 +221,7 @@ public function getId() */ public function setVersion($version) { - if ('2.0' == $version) { - $this->_version = '2.0'; - } else { - $this->_version = '1.0'; - } + $this->_version = '2.0' == $version ? '2.0' : '1.0'; return $this; } diff --git a/library/Zend/Json/Server/Response.php b/library/Zend/Json/Server/Response.php index c5c6c7e36c..d24cbbbd8c 100644 --- a/library/Zend/Json/Server/Response.php +++ b/library/Zend/Json/Server/Response.php @@ -29,6 +29,7 @@ */ class Zend_Json_Server_Response { + public $_args; /** * Response error * @var null|Zend_Json_Server_Error @@ -147,11 +148,7 @@ public function setVersion($version) $version = is_array($version) ? implode(' ', $version) : $version; - if ((string)$version == '2.0') { - $this->_version = '2.0'; - } else { - $this->_version = null; - } + $this->_version = (string)$version == '2.0' ? '2.0' : null; return $this; } diff --git a/library/Zend/Json/Server/Smd.php b/library/Zend/Json/Server/Smd.php index ba650af224..3e02f595d4 100644 --- a/library/Zend/Json/Server/Smd.php +++ b/library/Zend/Json/Server/Smd.php @@ -395,7 +395,7 @@ public function toArray() $envelope = $this->getEnvelope(); $contentType = $this->getContentType(); $SMDVersion = self::SMD_VERSION; - $service = compact('transport', 'envelope', 'contentType', 'SMDVersion'); + $service = ['transport' => $transport, 'envelope' => $envelope, 'contentType' => $contentType, 'SMDVersion' => $SMDVersion]; if (null !== ($target = $this->getTarget())) { $service['target'] = $target; @@ -426,7 +426,7 @@ public function toDojoArray() { $SMDVersion = '.1'; $serviceType = 'JSON-RPC'; - $service = compact('SMDVersion', 'serviceType'); + $service = ['SMDVersion' => $SMDVersion, 'serviceType' => $serviceType]; $target = $this->getTarget(); diff --git a/library/Zend/Json/Server/Smd/Service.php b/library/Zend/Json/Server/Smd/Service.php index 64c31463a1..bce757f13c 100644 --- a/library/Zend/Json/Server/Smd/Service.php +++ b/library/Zend/Json/Server/Smd/Service.php @@ -287,11 +287,9 @@ public function addParam($type, array $options = array(), $order = null) 'type' => $type, ); foreach ($options as $key => $value) { - if (in_array($key, array_keys($this->_paramOptionTypes))) { - if (null !== ($callback = $this->_paramOptionTypes[$key])) { - if (!$callback($value)) { - continue; - } + if (array_key_exists($key, $this->_paramOptionTypes)) { + if (null !== ($callback = $this->_paramOptionTypes[$key]) && !$callback($value)) { + continue; } $paramOptions[$key] = $value; } @@ -324,7 +322,7 @@ public function addParams(array $params) continue; } $type = $options['type']; - $order = (array_key_exists('order', $options)) ? $options['order'] : null; + $order = $options['order'] ?? null; $this->addParam($type, $options, $order); } return $this; @@ -415,10 +413,10 @@ public function toArray() $returns = $this->getReturn(); if (empty($target)) { - return compact('envelope', 'transport', 'parameters', 'returns'); + return ['envelope' => $envelope, 'transport' => $transport, 'parameters' => $parameters, 'returns' => $returns]; } - return $paramInfo = compact('envelope', 'target', 'transport', 'parameters', 'returns'); + return $paramInfo = ['envelope' => $envelope, 'target' => $target, 'transport' => $transport, 'parameters' => $parameters, 'returns' => $returns]; } /** diff --git a/library/Zend/Layout.php b/library/Zend/Layout.php index fa8ab81a6e..3c27344dd2 100644 --- a/library/Zend/Layout.php +++ b/library/Zend/Layout.php @@ -174,12 +174,10 @@ public static function startMvc($options = null) { if (null === self::$_mvcInstance) { self::$_mvcInstance = new self($options, true); - } else { - if (is_string($options)) { - self::$_mvcInstance->setLayoutPath($options); - } elseif (is_array($options) || $options instanceof Zend_Config) { - self::$_mvcInstance->setOptions($options); - } + } elseif (is_string($options)) { + self::$_mvcInstance->setLayoutPath($options); + } elseif (is_array($options) || $options instanceof Zend_Config) { + self::$_mvcInstance->setOptions($options); } return self::$_mvcInstance; @@ -460,7 +458,7 @@ public function getContentKey() */ protected function _setMvcEnabled($mvcEnabled) { - $this->_mvcEnabled = ($mvcEnabled) ? true : false; + $this->_mvcEnabled = $mvcEnabled; return $this; } @@ -482,7 +480,7 @@ public function getMvcEnabled() */ public function setMvcSuccessfulActionOnly($successfulActionOnly) { - $this->_mvcSuccessfulActionOnly = ($successfulActionOnly) ? true : false; + $this->_mvcSuccessfulActionOnly = $successfulActionOnly; return $this; } diff --git a/library/Zend/Ldap.php b/library/Zend/Ldap.php index 3a3b6e3c72..f896ea767c 100644 --- a/library/Zend/Ldap.php +++ b/library/Zend/Ldap.php @@ -161,7 +161,7 @@ public function getResource() public function getLastErrorCode() { $ret = @ldap_get_option($this->_resource, LDAP_OPT_ERROR_NUMBER, $err); - if ($ret === true) { + if ($ret) { if ($err <= -1 && $err >= -17) { /** * @see Zend_Ldap_Exception @@ -207,11 +207,7 @@ public function getLastError(&$errorCode = null, array &$errorMessages = null) } $message = ''; - if ($errorCode > 0) { - $message = '0x' . dechex($errorCode) . ' '; - } else { - $message = ''; - } + $message = $errorCode > 0 ? '0x' . dechex($errorCode) . ' ' : ''; if (count($errorMessages) > 0) { $message .= '(' . implode('; ', $errorMessages) . ')'; } else { @@ -309,7 +305,7 @@ public function setOptions($options) } } } - if (count($options) > 0) { + if ($options !== []) { $key = key($options); /** * @see Zend_Ldap_Exception @@ -403,13 +399,9 @@ protected function _getAccountCanonicalForm() if (!$accountCanonicalForm) { $accountDomainName = $this->_getAccountDomainName(); $accountDomainNameShort = $this->_getAccountDomainNameShort(); - if ($accountDomainNameShort) { + if ($accountDomainNameShort !== '' && $accountDomainNameShort !== '0') { $accountCanonicalForm = Zend_Ldap::ACCTNAME_FORM_BACKSLASH; - } else if ($accountDomainName) { - $accountCanonicalForm = Zend_Ldap::ACCTNAME_FORM_PRINCIPAL; - } else { - $accountCanonicalForm = Zend_Ldap::ACCTNAME_FORM_USERNAME; - } + } else $accountCanonicalForm = $accountDomainName !== '' && $accountDomainName !== '0' ? Zend_Ldap::ACCTNAME_FORM_PRINCIPAL : Zend_Ldap::ACCTNAME_FORM_USERNAME; } return $accountCanonicalForm; @@ -484,7 +476,7 @@ protected function _getAccountFilter($acctname) $this->_splitName($acctname, $dname, $aname); $accountFilterFormat = $this->_getAccountFilterFormat(); $aname = Zend_Ldap_Filter_Abstract::escapeValue($aname); - if ($accountFilterFormat) { + if ($accountFilterFormat !== '' && $accountFilterFormat !== '0') { return sprintf($accountFilterFormat, $aname); } if (!$this->_getBindRequiresDn()) { @@ -556,10 +548,7 @@ protected function _isPossibleAuthority($dname) if (strcasecmp($dname, $accountDomainName) == 0) { return true; } - if (strcasecmp($dname, $accountDomainNameShort) == 0) { - return true; - } - return false; + return strcasecmp($dname, $accountDomainNameShort) == 0; } /** @@ -590,11 +579,7 @@ public function getCanonicalAccountName($acctname, $form = 0) throw new Zend_Ldap_Exception(null, "Invalid account name syntax: $acctname"); } - if (function_exists('mb_strtolower')) { - $uname = mb_strtolower($uname, 'UTF-8'); - } else { - $uname = strtolower($uname); - } + $uname = function_exists('mb_strtolower') ? mb_strtolower($uname, 'UTF-8') : strtolower($uname); if ($form === 0) { $form = $this->_getAccountCanonicalForm(); @@ -607,7 +592,7 @@ public function getCanonicalAccountName($acctname, $form = 0) return $uname; case Zend_Ldap::ACCTNAME_FORM_BACKSLASH: $accountDomainNameShort = $this->_getAccountDomainNameShort(); - if (!$accountDomainNameShort) { + if ($accountDomainNameShort === '' || $accountDomainNameShort === '0') { /** * @see Zend_Ldap_Exception */ @@ -617,7 +602,7 @@ public function getCanonicalAccountName($acctname, $form = 0) return "$accountDomainNameShort\\$uname"; case Zend_Ldap::ACCTNAME_FORM_PRINCIPAL: $accountDomainName = $this->_getAccountDomainName(); - if (!$accountDomainName) { + if ($accountDomainName === '' || $accountDomainName === '0') { /** * @see Zend_Ldap_Exception */ @@ -642,7 +627,7 @@ public function getCanonicalAccountName($acctname, $form = 0) protected function _getAccount($acctname, array $attrs = null) { $baseDn = $this->getBaseDn(); - if (!$baseDn) { + if ($baseDn === '' || $baseDn === '0') { /** * @see Zend_Ldap_Exception */ @@ -651,7 +636,7 @@ protected function _getAccount($acctname, array $attrs = null) } $accountFilter = $this->_getAccountFilter($acctname); - if (!$accountFilter) { + if ($accountFilter === '' || $accountFilter === '0') { /** * @see Zend_Ldap_Exception */ @@ -669,7 +654,7 @@ protected function _getAccount($acctname, array $attrs = null) $acct = $accounts->getFirst(); $accounts->close(); return $acct; - } else if ($count === 0) { + } elseif ($count === 0) { /** * @see Zend_Ldap_Exception */ @@ -724,23 +709,11 @@ public function connect($host = null, $port = null, $useSsl = null, $useStartTls if ($host === null) { $host = $this->_getHost(); } - if ($port === null) { - $port = $this->_getPort(); - } else { - $port = (int)$port; - } - if ($useSsl === null) { - $useSsl = $this->_getUseSsl(); - } else { - $useSsl = (bool)$useSsl; - } - if ($useStartTls === null) { - $useStartTls = $this->_getUseStartTls(); - } else { - $useStartTls = (bool)$useStartTls; - } + $port = $port === null ? $this->_getPort() : (int)$port; + $useSsl = $useSsl === null ? $this->_getUseSsl() : (bool)$useSsl; + $useStartTls = $useStartTls === null ? $this->_getUseStartTls() : (bool)$useStartTls; - if (!$host) { + if ($host === '' || $host === '0') { /** * @see Zend_Ldap_Exception */ @@ -765,7 +738,7 @@ public function connect($host = null, $port = null, $useSsl = null, $useStartTls } else { $this->_connectString = 'ldap://' . $host; } - if ($port) { + if ($port !== 0) { $this->_connectString .= ':' . $port; } } @@ -777,16 +750,14 @@ public function connect($host = null, $port = null, $useSsl = null, $useStartTls */ $resource = ($useUri) ? @ldap_connect($this->_connectString) : @ldap_connect($host, $port); - if (is_resource($resource) === true) { + if (is_resource($resource)) { $this->_resource = $resource; $this->_boundUser = false; $optReferrals = ($this->_getOptReferrals()) ? 1 : 0; if (@ldap_set_option($resource, LDAP_OPT_PROTOCOL_VERSION, 3) && - @ldap_set_option($resource, LDAP_OPT_REFERRALS, $optReferrals)) { - if ($useSsl || !$useStartTls || @ldap_start_tls($resource)) { - return $this; - } + @ldap_set_option($resource, LDAP_OPT_REFERRALS, $optReferrals) && ($useSsl || !$useStartTls || @ldap_start_tls($resource))) { + return $this; } /** @@ -874,7 +845,7 @@ public function bind($username = null, $password = null) $this->connect(); } - if ($username !== null && $password === '' && $this->_getAllowEmptyPassword() !== true) { + if ($username !== null && $password === '' && !$this->_getAllowEmptyPassword()) { /** * @see Zend_Ldap_Exception */ @@ -892,12 +863,11 @@ public function bind($username = null, $password = null) * @see Zend_Ldap_Exception */ require_once 'Zend/Ldap/Exception.php'; - switch ($this->getLastErrorCode()) { - case Zend_Ldap_Exception::LDAP_SERVER_DOWN: - /* If the error is related to establishing a connection rather than binding, - * the connect string is more informative than the username. - */ - $message = $this->_connectString; + if ($this->getLastErrorCode() === Zend_Ldap_Exception::LDAP_SERVER_DOWN) { + /* If the error is related to establishing a connection rather than binding, + * the connect string is more informative than the username. + */ + $message = $this->_connectString; } $zle = new Zend_Ldap_Exception($this, $message); @@ -961,8 +931,7 @@ public function search($filter, $basedn = null, $scope = self::SEARCH_SCOPE_SUB, if ($basedn === null) { $basedn = $this->getBaseDn(); - } - else if ($basedn instanceof Zend_Ldap_Dn) { + } elseif ($basedn instanceof Zend_Ldap_Dn) { $basedn = $basedn->toString(); } @@ -1131,7 +1100,7 @@ public function searchEntries($filter, $basedn = null, $scope = self::SEARCH_SCO } $result = $this->search($filter, $basedn, $scope, $attributes, $sort, null, $sizelimit, $timelimit); $items = $result->toArray(); - if ((bool)$reverseSort === true) { + if ((bool)$reverseSort) { $items = array_reverse($items, false); } return $items; @@ -1153,7 +1122,7 @@ public function getEntry($dn, array $attributes = array(), $throwOnNotFound = fa $attributes, null); return $result->getFirst(); } catch (Zend_Ldap_Exception $e){ - if ($throwOnNotFound !== false) throw $e; + if ($throwOnNotFound) throw $e; } return null; } @@ -1171,8 +1140,9 @@ public static function prepareLdapEntryArray(array &$entry) foreach ($entry as $key => $value) { if (is_array($value)) { foreach ($value as $i => $v) { - if ($v === null) unset($value[$i]); - else if (!is_scalar($v)) { + if ($v === null) { + unset($value[$i]); + } elseif (!is_scalar($v)) { throw new InvalidArgumentException('Only scalar values allowed in LDAP data'); } else { $v = (string)$v; @@ -1184,18 +1154,13 @@ public static function prepareLdapEntryArray(array &$entry) } } $entry[$key] = array_values($value); + } elseif ($value === null) { + $entry[$key] = array(); + } elseif (!is_scalar($value)) { + throw new InvalidArgumentException('Only scalar values allowed in LDAP data'); } else { - if ($value === null) $entry[$key] = array(); - else if (!is_scalar($value)) { - throw new InvalidArgumentException('Only scalar values allowed in LDAP data'); - } else { - $value = (string)$value; - if (strlen($value) == 0) { - $entry[$key] = array(); - } else { - $entry[$key] = array($value); - } - } + $value = (string)$value; + $entry[$key] = strlen($value) == 0 ? array() : array($value); } } $entry = array_change_key_case($entry, CASE_LOWER); @@ -1216,7 +1181,7 @@ public function add($dn, array $entry) } self::prepareLdapEntryArray($entry); foreach ($entry as $key => $value) { - if (is_array($value) && count($value) === 0) { + if (is_array($value) && $value === []) { unset($entry[$key]); } } @@ -1226,7 +1191,7 @@ public function add($dn, array $entry) $value = Zend_Ldap_Dn::unescapeValue($value); if (!array_key_exists($key, $entry)) { $entry[$key] = array($value); - } else if (!in_array($value, $entry[$key])) { + } elseif (!in_array($value, $entry[$key])) { $entry[$key] = array_merge(array($value), $entry[$key]); } } @@ -1239,7 +1204,7 @@ public function add($dn, array $entry) } $isAdded = @ldap_add($this->getResource(), $dn->toString(), $entry); - if($isAdded === false) { + if(!$isAdded) { /** * @see Zend_Ldap_Exception */ @@ -1282,7 +1247,7 @@ public function update($dn, array $entry) if (count($entry) > 0) { $isModified = @ldap_modify($this->getResource(), $dn->toString(), $entry); - if($isModified === false) { + if(!$isModified) { /** * @see Zend_Ldap_Exception */ @@ -1327,16 +1292,14 @@ public function delete($dn, $recursively = false) if ($dn instanceof Zend_Ldap_Dn) { $dn = $dn->toString(); } - if ($recursively === true) { - if ($this->countChildren($dn)>0) { - $children = $this->_getChildrenDns($dn); - foreach ($children as $c) { - $this->delete($c, true); - } + if ($recursively && $this->countChildren($dn)>0) { + $children = $this->_getChildrenDns($dn); + foreach ($children as $c) { + $this->delete($c, true); } } $isDeleted = @ldap_delete($this->getResource(), $dn); - if($isDeleted === false) { + if(!$isDeleted) { /** * @see Zend_Ldap_Exception */ @@ -1391,17 +1354,9 @@ protected function _getChildrenDns($parentDn) */ public function moveToSubtree($from, $to, $recursively = false, $alwaysEmulate = false) { - if ($from instanceof Zend_Ldap_Dn) { - $orgDnParts = $from->toArray(); - } else { - $orgDnParts = Zend_Ldap_Dn::explodeDn($from); - } + $orgDnParts = $from instanceof Zend_Ldap_Dn ? $from->toArray() : Zend_Ldap_Dn::explodeDn($from); - if ($to instanceof Zend_Ldap_Dn) { - $newParentDnParts = $to->toArray(); - } else { - $newParentDnParts = Zend_Ldap_Dn::explodeDn($to); - } + $newParentDnParts = $to instanceof Zend_Ldap_Dn ? $to->toArray() : Zend_Ldap_Dn::explodeDn($to); $newDnParts = array_merge(array(array_shift($orgDnParts)), $newParentDnParts); $newDn = Zend_Ldap_Dn::fromArray($newDnParts); @@ -1440,31 +1395,31 @@ public function move($from, $to, $recursively = false, $alwaysEmulate = false) public function rename($from, $to, $recursively = false, $alwaysEmulate = false) { $emulate = (bool)$alwaysEmulate; - if (!function_exists('ldap_rename')) $emulate = true; - else if ($recursively) $emulate = true; + if (!function_exists('ldap_rename')) { + $emulate = true; + } elseif ($recursively) { + $emulate = true; + } - if ($emulate === false) { + if (!$emulate) { if ($from instanceof Zend_Ldap_Dn) { $from = $from->toString(); } - if ($to instanceof Zend_Ldap_Dn) { - $newDnParts = $to->toArray(); - } else { - $newDnParts = Zend_Ldap_Dn::explodeDn($to); - } + $newDnParts = $to instanceof Zend_Ldap_Dn ? $to->toArray() : Zend_Ldap_Dn::explodeDn($to); $newRdn = Zend_Ldap_Dn::implodeRdn(array_shift($newDnParts)); $newParent = Zend_Ldap_Dn::implodeDn($newDnParts); $isOK = @ldap_rename($this->getResource(), $from, $newRdn, $newParent, true); - if($isOK === false) { + if (!$isOK) { /** * @see Zend_Ldap_Exception */ require_once 'Zend/Ldap/Exception.php'; throw new Zend_Ldap_Exception($this, 'renaming ' . $from . ' to ' . $to); + } elseif (!$this->exists($to)) { + $emulate = true; } - else if (!$this->exists($to)) $emulate = true; } if ($emulate) { $this->copy($from, $to, $recursively); @@ -1484,17 +1439,9 @@ public function rename($from, $to, $recursively = false, $alwaysEmulate = false) */ public function copyToSubtree($from, $to, $recursively = false) { - if ($from instanceof Zend_Ldap_Dn) { - $orgDnParts = $from->toArray(); - } else { - $orgDnParts = Zend_Ldap_Dn::explodeDn($from); - } + $orgDnParts = $from instanceof Zend_Ldap_Dn ? $from->toArray() : Zend_Ldap_Dn::explodeDn($from); - if ($to instanceof Zend_Ldap_Dn) { - $newParentDnParts = $to->toArray(); - } else { - $newParentDnParts = Zend_Ldap_Dn::explodeDn($to); - } + $newParentDnParts = $to instanceof Zend_Ldap_Dn ? $to->toArray() : Zend_Ldap_Dn::explodeDn($to); $newDnParts = array_merge(array(array_shift($orgDnParts)), $newParentDnParts); $newDn = Zend_Ldap_Dn::fromArray($newDnParts); @@ -1514,14 +1461,10 @@ public function copy($from, $to, $recursively = false) { $entry = $this->getEntry($from, array(), true); - if ($to instanceof Zend_Ldap_Dn) { - $toDnParts = $to->toArray(); - } else { - $toDnParts = Zend_Ldap_Dn::explodeDn($to); - } + $toDnParts = $to instanceof Zend_Ldap_Dn ? $to->toArray() : Zend_Ldap_Dn::explodeDn($to); $this->add($to, $entry); - if ($recursively === true && $this->countChildren($from)>0) { + if ($recursively && $this->countChildren($from)>0) { $children = $this->_getChildrenDns($from); foreach ($children as $c) { $cDnParts = Zend_Ldap_Dn::explodeDn($c); @@ -1557,7 +1500,7 @@ public function getNode($dn) */ public function getBaseNode() { - return $this->getNode($this->getBaseDn(), $this); + return $this->getNode($this->getBaseDn()); } /** diff --git a/library/Zend/Ldap/Attribute.php b/library/Zend/Ldap/Attribute.php index b3177fb3a5..6bede3b751 100644 --- a/library/Zend/Ldap/Attribute.php +++ b/library/Zend/Ldap/Attribute.php @@ -56,21 +56,18 @@ public static function setAttribute(array &$data, $attribName, $value, $append = { $attribName = strtolower($attribName); $valArray = array(); - if (is_array($value) || ($value instanceof Traversable)) - { + if (is_array($value) || ($value instanceof Traversable)) { foreach ($value as $v) { $v = self::_valueToLdap($v); if ($v !== null) $valArray[] = $v; } - } - else if ($value !== null) - { + } elseif ($value !== null) { $value = self::_valueToLdap($value); if ($value !== null) $valArray[] = $value; } - if ($append === true && isset($data[$attribName])) + if ($append && isset($data[$attribName])) { if (is_string($data[$attribName])) $data[$attribName] = array($data[$attribName]); $data[$attribName] = array_merge($data[$attribName], $valArray); @@ -100,10 +97,10 @@ public static function getAttribute(array $data, $attribName, $index = null) $retArray[] = self::_valueFromLdap($v); } return $retArray; - } else if (is_int($index)) { + } elseif (is_int($index)) { if (!isset($data[$attribName])) { return null; - } else if ($index >= 0 && $index= 0 && $indexformat('U'); - } else if (is_string($value)) { + } elseif (is_string($value)) { try { return Zend_Ldap_Converter::fromLdapDateTime($value, false)->format('U'); } catch (InvalidArgumentException $e) { diff --git a/library/Zend/Ldap/Collection/Iterator/Default.php b/library/Zend/Ldap/Collection/Iterator/Default.php index d1d44fb66e..5a3d6f4bd1 100644 --- a/library/Zend/Ldap/Collection/Iterator/Default.php +++ b/library/Zend/Ldap/Collection/Iterator/Default.php @@ -139,7 +139,7 @@ public function setAttributeNameTreatment($attributeNameTreatment) if (is_callable($attributeNameTreatment)) { if (is_string($attributeNameTreatment) && !function_exists($attributeNameTreatment)) { $this->_attributeNameTreatment = self::ATTRIBUTE_TO_LOWER; - } else if (is_array($attributeNameTreatment) && + } elseif (is_array($attributeNameTreatment) && !method_exists($attributeNameTreatment[0], $attributeNameTreatment[1])) { $this->_attributeNameTreatment = self::ATTRIBUTE_TO_LOWER; } else { @@ -200,8 +200,7 @@ public function current() $entry = array('dn' => $this->key()); $ber_identifier = null; - $name = @ldap_first_attribute($this->_ldap->getResource(), $this->_current, - $ber_identifier); + $name = @ldap_first_attribute($this->_ldap->getResource(), $this->_current); while ($name) { $data = @ldap_get_values_len($this->_ldap->getResource(), $this->_current, $name); unset($data['count']); @@ -221,8 +220,7 @@ public function current() break; } $entry[$attrName] = $data; - $name = @ldap_next_attribute($this->_ldap->getResource(), $this->_current, - $ber_identifier); + $name = @ldap_next_attribute($this->_ldap->getResource(), $this->_current); } ksort($entry, SORT_LOCALE_STRING); return $entry; @@ -269,8 +267,8 @@ public function next() if ($code === Zend_Ldap_Exception::LDAP_SIZELIMIT_EXCEEDED) { // we have reached the size limit enforced by the server return; - } else if ($code > Zend_Ldap_Exception::LDAP_SUCCESS) { - throw new Zend_Ldap_Exception($this->_ldap, 'getting next entry (' . $msg . ')'); + } elseif ($code > Zend_Ldap_Exception::LDAP_SUCCESS) { + throw new Zend_Ldap_Exception($this->_ldap, 'getting next entry (' . $msg . ')'); } } } else { diff --git a/library/Zend/Ldap/Converter.php b/library/Zend/Ldap/Converter.php index e8677e1f16..4d39726e4a 100644 --- a/library/Zend/Ldap/Converter.php +++ b/library/Zend/Ldap/Converter.php @@ -112,21 +112,21 @@ public static function toLdap($value, $type = self::STANDARD) default: if (is_string($value)) { return $value; - } else if (is_int($value) || is_float($value)) { + } elseif (is_int($value) || is_float($value)) { return (string)$value; - } else if (is_bool($value)) { + } elseif (is_bool($value)) { return self::toldapBoolean($value); - } else if (is_object($value)) { + } elseif (is_object($value)) { if ($value instanceof DateTime) { return self::toLdapDatetime($value); - } else if ($value instanceof Zend_Date) { + } elseif ($value instanceof Zend_Date) { return self::toLdapDatetime($value); } else { return self::toLdapSerialize($value); } - } else if (is_array($value)) { + } elseif (is_array($value)) { return self::toLdapSerialize($value); - } else if (is_resource($value) && get_resource_type($value) === 'stream') { + } elseif (is_resource($value) && get_resource_type($value) === 'stream') { return stream_get_contents($value); } else { return null; @@ -157,16 +157,16 @@ public static function toLdapDateTime($date, $asUtc = true) if (is_int($date)) { $date = new DateTime('@' . $date); $date->setTimezone(new DateTimeZone(date_default_timezone_get())); - } else if (is_string($date)) { + } elseif (is_string($date)) { $date = new DateTime($date); - } else if ($date instanceof Zend_Date) { + } elseif ($date instanceof Zend_Date) { $date = new DateTime($date->get(Zend_Date::ISO_8601)); } else { throw new InvalidArgumentException('Parameter $date is not of the expected type'); } } $timezone = $date->format('O'); - if (true === $asUtc) { + if ($asUtc) { $date->setTimezone(new DateTimeZone('UTC')); $timezone = 'Z'; } @@ -234,7 +234,7 @@ public static function fromLdap($value, $type = self::STANDARD, $dateTimeAsUtc = if (is_numeric($value)) { // prevent numeric values to be treated as date/time return $value; - } else if ('TRUE' === $value || 'FALSE' === $value) { + } elseif ('TRUE' === $value || 'FALSE' === $value) { return self::fromLdapBoolean($value); } if (preg_match('/^\d{4}[\d\+\-Z\.]*$/', $value)) { @@ -383,9 +383,9 @@ public static function fromLdapDateTime($date, $asUtc = true) */ public static function fromLdapBoolean($value) { - if ( 'TRUE' === $value ) { + if ('TRUE' === $value) { return true; - } else if ( 'FALSE' === $value ) { + } elseif ('FALSE' === $value) { return false; } else { throw new InvalidArgumentException('The given value is not a boolean value'); diff --git a/library/Zend/Ldap/Dn.php b/library/Zend/Ldap/Dn.php index 7faf86ebd0..fc8a3fceab 100644 --- a/library/Zend/Ldap/Dn.php +++ b/library/Zend/Ldap/Dn.php @@ -66,7 +66,7 @@ public static function factory($dn, $caseFold = null) { if (is_array($dn)) { return self::fromArray($dn, $caseFold); - } else if (is_string($dn)) { + } elseif (is_string($dn)) { return self::fromString($dn, $caseFold); } else { /** @@ -88,11 +88,7 @@ public static function factory($dn, $caseFold = null) public static function fromString($dn, $caseFold = null) { $dn = trim($dn); - if (empty($dn)) { - $dnArray = array(); - } else { - $dnArray = self::explodeDn((string)$dn); - } + $dnArray = empty($dn) ? array() : self::explodeDn((string)$dn); return new self($dnArray, $caseFold); } @@ -527,7 +523,7 @@ public static function escapeValue($values = array()) $val = '\20' . $val; } for ($i = 0; $i $singleK) { + if (is_array($singleK) && is_array($v[$i]) && (count($k[$i]) === count($v[$i]))) { $multi = array(); - for ($j = 0; $j < count($k[$i]); $j++) { - $key=$k[$i][$j]; + $itemsCount = count($k[$i]); + for ($j = 0; $j < $itemsCount; $j++) { + $key=$singleK[$j]; $val=$v[$i][$j]; $multi[$key] = $val; } $ret[] = $multi; - } else if (is_string($k[$i]) && is_string($v[$i])) { - $ret[] = array($k[$i] => $v[$i]); + } elseif (is_string($singleK) && is_string($v[$i])) { + $ret[] = array($singleK => $v[$i]); } } if ($keys !== null) $keys = $k; @@ -641,13 +638,16 @@ public static function checkDn($dn, array &$keys = null, array &$vals = null, $ka = array(); $va = array(); for ($di = 0; $di <= $slen; $di++) { - $ch = ($di == $slen) ? 0 : $dn[$di]; + $ch = ($di === $slen) ? 0 : $dn[$di]; switch ($state) { case 1: // collect key if ($ch === '=') { $key = trim(substr($dn, $ko, $di - $ko)); - if ($caseFold == self::ATTR_CASEFOLD_LOWER) $key = strtolower($key); - else if ($caseFold == self::ATTR_CASEFOLD_UPPER) $key = strtoupper($key); + if ($caseFold == self::ATTR_CASEFOLD_LOWER) { + $key = strtolower($key); + } elseif ($caseFold == self::ATTR_CASEFOLD_UPPER) { + $key = strtoupper($key); + } if (is_array($multi)) { $keyId = strtolower($key); if (in_array($keyId, $multi)) { @@ -660,14 +660,14 @@ public static function checkDn($dn, array &$keys = null, array &$vals = null, } $state = 2; $vo = $di + 1; - } else if ($ch === ',' || $ch === ';' || $ch === '+') { + } elseif ($ch === ',' || $ch === ';' || $ch === '+') { return false; } break; case 2: // collect value if ($ch === '\\') { $state = 3; - } else if ($ch === ',' || $ch === ';' || $ch === 0 || $ch === '+') { + } elseif ($ch === ',' || $ch === ';' || $ch === 0 || $ch === '+') { $value = self::unescapeValue(trim(substr($dn, $vo, $di - $vo))); if (is_array($multi)) { $va[count($va)-1][] = $value; @@ -682,10 +682,10 @@ public static function checkDn($dn, array &$keys = null, array &$vals = null, $ka[] = array($lastKey); $va[] = array($lastVal); $multi = array(strtolower($lastKey)); - } else if ($ch === ','|| $ch === ';' || $ch === 0) { + } elseif ($ch === ','|| $ch === ';' || $ch === 0) { $multi = false; } - } else if ($ch === '=') { + } elseif ($ch === '=') { return false; } break; @@ -786,8 +786,8 @@ public static function isChildOf($childDn, $parentDn) $startIndex = count($cdn)-count($pdn); if ($startIndex<0) return false; - for ($i = 0; $i $singlePdn) { + if ($cdn[$i+$startIndex] != $singlePdn) return false; } return true; } diff --git a/library/Zend/Ldap/Exception.php b/library/Zend/Ldap/Exception.php index 4d6aaeec5d..005f6c5fed 100644 --- a/library/Zend/Ldap/Exception.php +++ b/library/Zend/Ldap/Exception.php @@ -132,10 +132,8 @@ public function __construct(Zend_Ldap $ldap = null, $str = null, $code = 0) $code = $oldCode; } } - if (empty($message)) { - if ($code > 0) { - $message = '0x' . dechex($code) . ': '; - } + if (empty($message) && $code > 0) { + $message = '0x' . dechex($code) . ': '; } if (!empty($str)) { diff --git a/library/Zend/Ldap/Filter/Logical.php b/library/Zend/Ldap/Filter/Logical.php index 7c57f10004..51ca32d5dc 100644 --- a/library/Zend/Ldap/Filter/Logical.php +++ b/library/Zend/Ldap/Filter/Logical.php @@ -66,8 +66,9 @@ abstract class Zend_Ldap_Filter_Logical extends Zend_Ldap_Filter_Abstract protected function __construct(array $subfilters, $symbol) { foreach ($subfilters as $key => $s) { - if (is_string($s)) $subfilters[$key] = new Zend_Ldap_Filter_String($s); - else if (!($s instanceof Zend_Ldap_Filter_Abstract)) { + if (is_string($s)) { + $subfilters[$key] = new Zend_Ldap_Filter_String($s); + } elseif (!($s instanceof Zend_Ldap_Filter_Abstract)) { /** * @see Zend_Ldap_Filter_Exception */ @@ -101,7 +102,6 @@ public function toString() { $return = '(' . $this->_symbol; foreach ($this->_subfilters as $sub) $return .= $sub->toString(); - $return .= ')'; - return $return; + return $return . ')'; } } diff --git a/library/Zend/Ldap/Filter/Mask.php b/library/Zend/Ldap/Filter/Mask.php index 6846bdbc20..95d176b8e6 100644 --- a/library/Zend/Ldap/Filter/Mask.php +++ b/library/Zend/Ldap/Filter/Mask.php @@ -47,7 +47,8 @@ public function __construct($mask, $value) { $args = func_get_args(); array_shift($args); - for ($i = 0; $i 0 && $name === 'dn') { + } elseif (count($item) > 0 && $name === 'dn') { $items[] = $item; $item = array(); $last = null; } $last = array($name, $type, $value); - } else if (trim($line) === '') { + } elseif (trim($line) === '') { continue; } } @@ -130,7 +130,7 @@ protected function _pushAttribute(array $attribute, array &$entry) } if ($name === 'dn') { $entry[$name] = $value; - } else if (isset($entry[$name]) && $value !== '') { + } elseif (isset($entry[$name]) && $value !== '') { $entry[$name][] = $value; } else { $entry[$name] = ($value !== '') ? array($value) : array(); @@ -161,9 +161,9 @@ protected function _encode($value) { if (is_scalar($value)) { return $this->_encodeString($value); - } else if (is_array($value)) { + } elseif (is_array($value)) { return $this->_encodeAttributes($value); - } else if ($value instanceof Zend_Ldap_Node) { + } elseif ($value instanceof Zend_Ldap_Node) { return $value->toLdif($this->_options); } return null; @@ -207,10 +207,10 @@ protected function _encodeString($string, &$base64 = null) if ($char >= 127) { $base64 = true; break; - } else if ($i === 0 && in_array($char, $unsafe_init_char)) { + } elseif ($i === 0 && in_array($char, $unsafe_init_char)) { $base64 = true; break; - } else if (in_array($char, $unsafe_char)) { + } elseif (in_array($char, $unsafe_char)) { $base64 = true; break; } @@ -220,7 +220,7 @@ protected function _encodeString($string, &$base64 = null) $base64 = true; } - if ($base64 === true) { + if ($base64) { $string = base64_encode($string); } diff --git a/library/Zend/Ldap/Node.php b/library/Zend/Ldap/Node.php index f718cc1676..e8e0b56adc 100644 --- a/library/Zend/Ldap/Node.php +++ b/library/Zend/Ldap/Node.php @@ -218,13 +218,9 @@ public function isAttached() protected function _loadData(array $data, $fromDataSource) { parent::_loadData($data, $fromDataSource); - if ($fromDataSource === true) { - $this->_originalData = $data; - } else { - $this->_originalData = array(); - } + $this->_originalData = $fromDataSource ? $data : array(); $this->_children = null; - $this->_markAsNew(($fromDataSource === true) ? false : true); + $this->_markAsNew(!$fromDataSource); $this->_markAsToBeDeleted(false); } @@ -240,7 +236,7 @@ public static function create($dn, array $objectClass = array()) { if (is_string($dn) || is_array($dn)) { $dn = Zend_Ldap_Dn::factory($dn); - } else if ($dn instanceof Zend_Ldap_Dn) { + } elseif ($dn instanceof Zend_Ldap_Dn) { $dn = clone $dn; } else { /** @@ -267,7 +263,7 @@ public static function fromLdap($dn, Zend_Ldap $ldap) { if (is_string($dn) || is_array($dn)) { $dn = Zend_Ldap_Dn::factory($dn); - } else if ($dn instanceof Zend_Ldap_Dn) { + } elseif ($dn instanceof Zend_Ldap_Dn) { $dn = clone $dn; } else { /** @@ -280,8 +276,7 @@ public static function fromLdap($dn, Zend_Ldap $ldap) if ($data === null) { return null; } - $entry = new self($dn, $data, true, $ldap); - return $entry; + return new self($dn, $data, true, $ldap); } /** @@ -303,7 +298,7 @@ public static function fromArray(array $data, $fromDataSource = false) } if (is_string($data['dn']) || is_array($data['dn'])) { $dn = Zend_Ldap_Dn::factory($data['dn']); - } else if ($data['dn'] instanceof Zend_Ldap_Dn) { + } elseif ($data['dn'] instanceof Zend_Ldap_Dn) { $dn = clone $data['dn']; } else { /** @@ -312,7 +307,7 @@ public static function fromArray(array $data, $fromDataSource = false) require_once 'Zend/Ldap/Exception.php'; throw new Zend_Ldap_Exception(null, '\'dn\' key is of a wrong data type.'); } - $fromDataSource = ($fromDataSource === true) ? true : false; + $fromDataSource = $fromDataSource; $new = new self($dn, $data, $fromDataSource, null); $new->_ensureRdnAttributeValues(); return $new; @@ -329,7 +324,7 @@ protected function _ensureRdnAttributeValues($overwrite = false) foreach ($this->getRdnArray() as $key => $value) { if (!array_key_exists($key, $this->_currentData) || $overwrite) { Zend_Ldap_Attribute::setAttribute($this->_currentData, $key, $value, false); - } else if (!in_array($value, $this->_currentData[$key])) { + } elseif (!in_array($value, $this->_currentData[$key])) { Zend_Ldap_Attribute::setAttribute($this->_currentData, $key, $value, true); } } @@ -344,7 +339,7 @@ protected function _ensureRdnAttributeValues($overwrite = false) */ protected function _markAsNew($new) { - $this->_new = ($new === false) ? false : true; + $this->_new = $new; } /** @@ -369,7 +364,7 @@ public function isNew() */ protected function _markAsToBeDeleted($delete) { - $this->_delete = ($delete === true) ? true : false; + $this->_delete = $delete; } @@ -405,7 +400,7 @@ public function willBeMoved() { if ($this->isNew() || $this->willBeDeleted()) { return false; - } else if ($this->_newDn !== null) { + } elseif ($this->_newDn !== null) { return ($this->_dn != $this->_newDn); } else { return false; @@ -456,7 +451,7 @@ public function update(Zend_Ldap $ldap = null) $this->_preRename(); $recursive = $this->hasChildren(); $ldap->rename($this->_dn, $this->_newDn, $recursive, false); - foreach ($this->_newDn->getRdn() as $key => $value) { + foreach (array_keys($this->_newDn->getRdn()) as $key) { if (array_key_exists($key, $changedData)) { unset($changedData[$key]); } @@ -465,7 +460,7 @@ public function update(Zend_Ldap $ldap = null) $this->_newDn = null; $this->_postRename(); } - if (count($changedData) > 0) { + if ($changedData !== []) { $this->_preUpdate(); $ldap->update($this->_getDn(), $changedData); $this->_postUpdate(); @@ -496,8 +491,7 @@ protected function _getDn() */ public function getCurrentDn() { - $dn = clone parent::_getDn(); - return $dn; + return clone parent::_getDn(); } /** @@ -511,11 +505,7 @@ public function getCurrentDn() */ public function setDn($newDn) { - if ($newDn instanceof Zend_Ldap_Dn) { - $this->_newDn = clone $newDn; - } else { - $this->_newDn = Zend_Ldap_Dn::factory($newDn); - } + $this->_newDn = $newDn instanceof Zend_Ldap_Dn ? clone $newDn : Zend_Ldap_Dn::factory($newDn); $this->_ensureRdnAttributeValues(true); return $this; } @@ -610,7 +600,7 @@ public function getChangedData() foreach ($this->_currentData as $key => $value) { if (!array_key_exists($key, $this->_originalData) && !empty($value)) { $changed[$key] = $value; - } else if ($this->_originalData[$key] !== $this->_currentData[$key]) { + } elseif ($this->_originalData[$key] !== $this->_currentData[$key]) { $changed[$key] = $value; } } @@ -633,9 +623,9 @@ public function getChanges() foreach ($this->_currentData as $key => $value) { if (!array_key_exists($key, $this->_originalData) && !empty($value)) { $changes['add'][$key] = $value; - } else if (count($this->_originalData[$key]) === 0 && !empty($value)) { + } elseif (count($this->_originalData[$key]) === 0 && !empty($value)) { $changes['add'][$key] = $value; - } else if ($this->_originalData[$key] !== $this->_currentData[$key]) { + } elseif ($this->_originalData[$key] !== $this->_currentData[$key]) { if (empty($value)) { $changes['delete'][$key] = $value; } else { @@ -815,21 +805,19 @@ protected function _assertChangeableAttribute($name) */ require_once 'Zend/Ldap/Exception.php'; throw new Zend_Ldap_Exception(null, 'DN cannot be changed.'); - } - else if (array_key_exists($name, $rdn)) { + } elseif (array_key_exists($name, $rdn)) { /** * @see Zend_Ldap_Exception */ require_once 'Zend/Ldap/Exception.php'; throw new Zend_Ldap_Exception(null, 'Cannot change attribute because it\'s part of the RDN'); - } else if (in_array($name, self::$_systemAttributes)) { + } elseif (in_array($name, self::$_systemAttributes)) { /** * @see Zend_Ldap_Exception */ require_once 'Zend/Ldap/Exception.php'; throw new Zend_Ldap_Exception(null, 'Cannot change attribute because it\'s read-only'); - } - else return true; + } else return true; } /** @@ -1015,7 +1003,7 @@ public function hasChildren() return false; } } else { - return (count($this->_children) > 0); + return ($this->_children !== []); } } diff --git a/library/Zend/Ldap/Node/Abstract.php b/library/Zend/Ldap/Node/Abstract.php index febc549bf2..e12c0451cb 100644 --- a/library/Zend/Ldap/Node/Abstract.php +++ b/library/Zend/Ldap/Node/Abstract.php @@ -129,8 +129,7 @@ protected function _getDn() */ public function getDn() { - $dn = clone $this->_getDn(); - return $dn; + return clone $this->_getDn(); } /** @@ -208,7 +207,7 @@ public function getObjectClass() public function getAttributes($includeSystemAttributes = true) { $data = array(); - foreach ($this->getData($includeSystemAttributes) as $name => $value) { + foreach (array_keys($this->getData($includeSystemAttributes)) as $name) { $data[$name] = $this->getAttribute($name, null); } return $data; @@ -269,14 +268,9 @@ public function toJson($includeSystemAttributes = true) */ public function getData($includeSystemAttributes = true) { - if ($includeSystemAttributes === false) { + if (!$includeSystemAttributes) { $data = array(); - foreach ($this->_currentData as $key => $value) { - if (!in_array($key, self::$_systemAttributes)) { - $data[$key] = $value; - } - } - return $data; + return array_filter($this->_currentData, fn($value) => !in_array($key, self::$_systemAttributes)); } else { return $this->_currentData; } diff --git a/library/Zend/Ldap/Node/RootDse.php b/library/Zend/Ldap/Node/RootDse.php index f70682e94a..a0fbd147bb 100644 --- a/library/Zend/Ldap/Node/RootDse.php +++ b/library/Zend/Ldap/Node/RootDse.php @@ -58,13 +58,13 @@ public static function create(Zend_Ldap $ldap) */ require_once 'Zend/Ldap/Node/RootDse/ActiveDirectory.php'; return new Zend_Ldap_Node_RootDse_ActiveDirectory($dn, $data); - } else if (isset($data['dsaname'])) { + } elseif (isset($data['dsaname'])) { /** * @see Zend_Ldap_Node_RootDse_ActiveDirectory */ require_once 'Zend/Ldap/Node/RootDse/eDirectory.php'; return new Zend_Ldap_Node_RootDse_eDirectory($dn, $data); - } else if (isset($data['structuralobjectclass']) && + } elseif (isset($data['structuralobjectclass']) && $data['structuralobjectclass'][0] === 'OpenLDAProotDSE') { /** * @see Zend_Ldap_Node_RootDse_OpenLdap diff --git a/library/Zend/Ldap/Node/Schema/AttributeType/OpenLdap.php b/library/Zend/Ldap/Node/Schema/AttributeType/OpenLdap.php index 3b2e0321e2..d33cf29829 100644 --- a/library/Zend/Ldap/Node/Schema/AttributeType/OpenLdap.php +++ b/library/Zend/Ldap/Node/Schema/AttributeType/OpenLdap.php @@ -71,7 +71,7 @@ public function getSyntax() { if ($this->syntax === null) { $parent = $this->getParent(); - if ($parent === null) return null; + if (!$parent instanceof \Zend_Ldap_Node_Schema_AttributeType_OpenLdap) return null; else return $parent->getSyntax(); } else { return $this->syntax; @@ -88,7 +88,7 @@ public function getMaxLength() $maxLength = $this->{'max-length'}; if ($maxLength === null) { $parent = $this->getParent(); - if ($parent === null) return null; + if (!$parent instanceof \Zend_Ldap_Node_Schema_AttributeType_OpenLdap) return null; else return $parent->getMaxLength(); } else { return (int)$maxLength; diff --git a/library/Zend/Ldap/Node/Schema/ObjectClass/OpenLdap.php b/library/Zend/Ldap/Node/Schema/ObjectClass/OpenLdap.php index 747f8d5e0e..5cfb2af606 100644 --- a/library/Zend/Ldap/Node/Schema/ObjectClass/OpenLdap.php +++ b/library/Zend/Ldap/Node/Schema/ObjectClass/OpenLdap.php @@ -143,9 +143,9 @@ public function getType() { if ($this->structural) { return Zend_Ldap_Node_Schema::OBJECTCLASS_TYPE_STRUCTURAL; - } else if ($this->abstract) { + } elseif ($this->abstract) { return Zend_Ldap_Node_Schema::OBJECTCLASS_TYPE_ABSTRACT; - } else if ($this->auxiliary) { + } elseif ($this->auxiliary) { return Zend_Ldap_Node_Schema::OBJECTCLASS_TYPE_AUXILIARY; } else { return Zend_Ldap_Node_Schema::OBJECTCLASS_TYPE_UNKNOWN; diff --git a/library/Zend/Ldap/Node/Schema/OpenLdap.php b/library/Zend/Ldap/Node/Schema/OpenLdap.php index 80a376d098..87a71d7b5d 100644 --- a/library/Zend/Ldap/Node/Schema/OpenLdap.php +++ b/library/Zend/Ldap/Node/Schema/OpenLdap.php @@ -199,12 +199,10 @@ protected function _parseAttributeType($value) $attributeType['oid'] = array_shift($tokens); // first token is the oid $this->_parseLdapSchemaSyntax($attributeType, $tokens); - if (array_key_exists('syntax', $attributeType)) { - // get max length from syntax - if (preg_match('/^(.+){(\d+)}$/', (string) $attributeType['syntax'], $matches)) { - $attributeType['syntax'] = $matches[1]; - $attributeType['max-length'] = $matches[2]; - } + // get max length from syntax + if (array_key_exists('syntax', $attributeType) && preg_match('/^(.+){(\d+)}$/', (string) $attributeType['syntax'], $matches)) { + $attributeType['syntax'] = $matches[1]; + $attributeType['max-length'] = $matches[2]; } $this->_ensureNameAttribute($attributeType); @@ -444,7 +442,7 @@ protected function _parseLdapSchemaSyntax(array &$data, array $tokens) // tokens that can have multiple values $multiValue = array('must', 'may', 'sup'); - while (count($tokens) > 0) { + while ($tokens !== []) { $token = strtolower(array_shift($tokens)); if (in_array($token, $noValue)) { $data[$token] = true; // single value token diff --git a/library/Zend/Loader.php b/library/Zend/Loader.php index 8d8ea3fa7a..8780a3c22d 100644 --- a/library/Zend/Loader.php +++ b/library/Zend/Loader.php @@ -204,16 +204,7 @@ public static function explodeIncludePath($path = null) if (null === $path) { $path = get_include_path(); } - - if (PATH_SEPARATOR == ':') { - // On *nix systems, include_paths which include paths with a stream - // schema cannot be safely explode'd, so we have to be a bit more - // intelligent in the approach. - $paths = preg_split('#:(?!//)#', (string) $path); - } else { - $paths = explode(PATH_SEPARATOR, (string) $path); - } - return $paths; + return PATH_SEPARATOR == ':' ? preg_split('#:(?!//)#', (string) $path) : explode(PATH_SEPARATOR, (string) $path); } /** @@ -337,7 +328,6 @@ public static function standardiseFile($file) $fileName = substr($fileName, $lastNsPos + 1); $file = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; } - $file .= str_replace('_', DIRECTORY_SEPARATOR, $fileName) . '.php'; - return $file; + return $file . (str_replace('_', DIRECTORY_SEPARATOR, $fileName) . '.php'); } } diff --git a/library/Zend/Loader/Autoloader.php b/library/Zend/Loader/Autoloader.php index 9d9772e302..072783742e 100644 --- a/library/Zend/Loader/Autoloader.php +++ b/library/Zend/Loader/Autoloader.php @@ -334,11 +334,9 @@ public function getClassAutoloaders($class) if ('' == $ns) { continue; } - if (0 === strpos($class, $ns)) { - if ((false === $namespace) || (strlen((string) $ns) > strlen((string) $namespace))) { - $namespace = $ns; - $autoloaders = $this->getNamespaceAutoloaders($ns); - } + if (0 === strpos($class, $ns) && ((false === $namespace) || (strlen((string) $ns) > strlen((string) $namespace)))) { + $namespace = $ns; + $autoloaders = $this->getNamespaceAutoloaders($ns); } } @@ -353,7 +351,7 @@ public function getClassAutoloaders($class) // Add non-namespaced autoloaders $autoloadersNonNamespace = $this->getNamespaceAutoloaders(''); - if (count($autoloadersNonNamespace)) { + if ($autoloadersNonNamespace !== []) { foreach ($autoloadersNonNamespace as $ns) { $autoloaders[] = $ns; } @@ -401,13 +399,13 @@ public function unshiftAutoloader($callback, $namespace = '') public function pushAutoloader($callback, $namespace = '') { $autoloaders = $this->getAutoloaders(); - array_push($autoloaders, $callback); + $autoloaders[] = $callback; $this->setAutoloaders($autoloaders); $namespace = (array) $namespace; foreach ($namespace as $ns) { $autoloaders = $this->getNamespaceAutoloaders($ns); - array_push($autoloaders, $callback); + $autoloaders[] = $callback; $this->_setNamespaceAutoloaders($autoloaders, $ns); } @@ -460,7 +458,9 @@ public function removeAutoloader($callback, $namespace = null) protected function __construct() { spl_autoload_register(array(__CLASS__, 'autoload')); - $this->_internalAutoloader = array($this, '_autoload'); + $this->_internalAutoloader = function (string $class) : bool { + return $this->_autoload($class); + }; } /** @@ -516,9 +516,7 @@ protected function _getVersionPath($path, $version) if (empty($availableVersions)) { throw new Zend_Loader_Exception('No valid ZF installations discovered'); } - - $matchedVersion = array_pop($availableVersions); - return $matchedVersion; + return array_pop($availableVersions); } /** diff --git a/library/Zend/Loader/Autoloader/Resource.php b/library/Zend/Loader/Autoloader/Resource.php index b9279c257c..9c256a0486 100644 --- a/library/Zend/Loader/Autoloader/Resource.php +++ b/library/Zend/Loader/Autoloader/Resource.php @@ -34,6 +34,7 @@ */ class Zend_Loader_Autoloader_Resource implements Zend_Loader_Autoloader_Interface { + public array $_resources; /** * @var string Base path to resource classes */ @@ -151,7 +152,7 @@ public function getClassPath($class) $namespace[] = array_shift($segments); } $namespace = implode('_', $namespace); - if ($namespace != $namespaceTopLevel) { + if ($namespace !== $namespaceTopLevel) { // wrong prefix? we're done return false; } @@ -197,7 +198,7 @@ public function getClassPath($class) public function autoload($class) { $classPath = $this->getClassPath($class); - if (false !== $classPath) { + if ($classPath) { return include $classPath; } return false; diff --git a/library/Zend/Loader/AutoloaderFactory.php b/library/Zend/Loader/AutoloaderFactory.php index 9fc2836525..0e7be0a207 100644 --- a/library/Zend/Loader/AutoloaderFactory.php +++ b/library/Zend/Loader/AutoloaderFactory.php @@ -91,15 +91,12 @@ public static function factory($options = null) foreach ($options as $class => $options) { if (!isset(self::$loaders[$class])) { // Check class map autoloader - if ($class == self::CLASS_MAP_AUTOLOADER) { - if (!class_exists(self::CLASS_MAP_AUTOLOADER)) { - // Extract the filename from the classname - $classMapLoader = substr( - strrchr(self::CLASS_MAP_AUTOLOADER, '_'), 1 - ); - - require_once dirname(__FILE__) . "/$classMapLoader.php"; - } + if ($class == self::CLASS_MAP_AUTOLOADER && !class_exists(self::CLASS_MAP_AUTOLOADER)) { + // Extract the filename from the classname + $classMapLoader = substr( + strrchr(self::CLASS_MAP_AUTOLOADER, '_'), 1 + ); + require_once dirname(__FILE__) . "/$classMapLoader.php"; } // Autoload with standard autoloader @@ -114,14 +111,12 @@ public static function factory($options = null) // unfortunately is_subclass_of is broken on some 5.3 versions // additionally instanceof is also broken for this use case - if (version_compare(PHP_VERSION, '5.3.7', '>=')) { - if (!is_subclass_of($class, 'Zend_Loader_SplAutoloader')) { - require_once 'Exception/InvalidArgumentException.php'; - throw new Zend_Loader_Exception_InvalidArgumentException(sprintf( - 'Autoloader class %s must implement Zend\\Loader\\SplAutoloader', - $class - )); - } + if (version_compare(PHP_VERSION, '5.3.7', '>=') && !is_subclass_of($class, 'Zend_Loader_SplAutoloader')) { + require_once 'Exception/InvalidArgumentException.php'; + throw new Zend_Loader_Exception_InvalidArgumentException(sprintf( + 'Autoloader class %s must implement Zend\\Loader\\SplAutoloader', + $class + )); } if ($class === self::STANDARD_AUTOLOADER) { diff --git a/library/Zend/Loader/ClassMapAutoloader.php b/library/Zend/Loader/ClassMapAutoloader.php index 177c2f5ad7..8552b02c5e 100644 --- a/library/Zend/Loader/ClassMapAutoloader.php +++ b/library/Zend/Loader/ClassMapAutoloader.php @@ -157,9 +157,13 @@ public function autoload($class) public function register() { if (version_compare(PHP_VERSION, '5.3.0', '>=')) { - spl_autoload_register(array($this, 'autoload'), true, true); + spl_autoload_register(function (string $class) : void { + $this->autoload($class); + }, true, true); } else { - spl_autoload_register(array($this, 'autoload'), true); + spl_autoload_register(function (string $class) : void { + $this->autoload($class); + }, true); } } @@ -181,7 +185,7 @@ protected function loadMapFromFile($location) throw new Zend_Loader_Exception_InvalidArgumentException('Map file provided does not exist'); } - if (!$path = self::realPharPath($location)) { + if (($path = self::realPharPath($location)) === '' || ($path = self::realPharPath($location)) === '0') { $path = realpath($location); } @@ -190,9 +194,7 @@ protected function loadMapFromFile($location) return $this; } - $map = include $path; - - return $map; + return include $path; } /** diff --git a/library/Zend/Loader/PluginLoader.php b/library/Zend/Loader/PluginLoader.php index 118684302d..2e13005ed5 100644 --- a/library/Zend/Loader/PluginLoader.php +++ b/library/Zend/Loader/PluginLoader.php @@ -372,11 +372,7 @@ public function load($name, $throwExceptions = true) return $this->getClassName($name); } - if ($this->_useStaticRegistry) { - $registry = self::$_staticPrefixToPaths[$this->_useStaticRegistry]; - } else { - $registry = $this->_prefixToPaths; - } + $registry = $this->_useStaticRegistry ? self::$_staticPrefixToPaths[$this->_useStaticRegistry] : $this->_prefixToPaths; $registry = array_reverse($registry, true); $found = false; diff --git a/library/Zend/Loader/StandardAutoloader.php b/library/Zend/Loader/StandardAutoloader.php index 2c6c045c52..b81dbf2e12 100644 --- a/library/Zend/Loader/StandardAutoloader.php +++ b/library/Zend/Loader/StandardAutoloader.php @@ -255,7 +255,9 @@ public function autoload($class) */ public function register() { - spl_autoload_register(array($this, 'autoload')); + spl_autoload_register(function (string $class) : string|false { + return $this->autoload($class); + }); } /** @@ -321,7 +323,9 @@ protected function loadClass($class, $type) return false; } $this->error = false; - set_error_handler(array($this, 'handleError'), E_WARNING); + set_error_handler(function ($errno, $errstr) : void { + $this->handleError($errno, $errstr); + }, E_WARNING); include $filename; restore_error_handler(); if ($this->error) { @@ -360,8 +364,7 @@ protected function normalizeDirectory($directory) $directory[strlen($directory) - 1] = DIRECTORY_SEPARATOR; return $directory; } - $directory .= DIRECTORY_SEPARATOR; - return $directory; + return $directory . DIRECTORY_SEPARATOR; } } diff --git a/library/Zend/Locale.php b/library/Zend/Locale.php index e59d7640e3..0da50b9bfe 100644 --- a/library/Zend/Locale.php +++ b/library/Zend/Locale.php @@ -1152,13 +1152,12 @@ public function __toString() * * @return array Returns an array of all locale string */ - public static function getDefault() + public static function getDefault(...$params) { - if ((self::$compatibilityMode === true) or (func_num_args() > 0)) { + if (self::$compatibilityMode || func_num_args() > 0) { if (!self::$_breakChain) { self::$_breakChain = true; trigger_error('You are running Zend_Locale in compatibility mode... please migrate your scripts', E_USER_NOTICE); - $params = func_get_args(); $param = null; if (isset($params[0])) { $param = $params[0]; @@ -1186,13 +1185,12 @@ public static function getDefault() */ public static function setDefault($locale, $quality = 1) { - if (($locale === 'auto') or ($locale === 'root') or ($locale === 'default') or - ($locale === 'environment') or ($locale === 'browser')) { + if ($locale === 'auto' || $locale === 'root' || $locale === 'default' || $locale === 'environment' || $locale === 'browser') { require_once 'Zend/Locale/Exception.php'; throw new Zend_Locale_Exception('Only full qualified locales can be used as default!'); } - if (($quality < 0.1) or ($quality > 100)) { + if ($quality < 0.1 || $quality > 100) { require_once 'Zend/Locale/Exception.php'; throw new Zend_Locale_Exception("Quality must be between 0.1 and 100"); } @@ -1202,11 +1200,11 @@ public static function setDefault($locale, $quality = 1) } $locale = self::_prepareLocale($locale); - if (isset(self::$_localeData[(string) $locale]) === true) { + if (isset(self::$_localeData[(string) $locale])) { self::$_default = array((string) $locale => $quality); } else { $elocale = explode('_', (string) $locale); - if (isset(self::$_localeData[$elocale[0]]) === true) { + if (isset(self::$_localeData[$elocale[0]])) { self::$_default = array($elocale[0] => $quality); } else { require_once 'Zend/Locale/Exception.php'; @@ -1247,7 +1245,7 @@ public static function getEnvironment() if ($language !== 'C') { if (strpos($language, '.') !== false) { $language = substr($language, 0, strpos($language, '.')); - } else if (strpos($language, '@') !== false) { + } elseif (strpos($language, '@') !== false) { $language = substr($language, 0, strpos($language, '@')); } @@ -1263,7 +1261,7 @@ public static function getEnvironment() $language ); - if (isset(self::$_localeData[$language]) === true) { + if (isset(self::$_localeData[$language])) { $languagearray[$language] = 1; if (strpos($language, '_') !== false) { $languagearray[substr($language, 0, strpos($language, '_'))] = 1; @@ -1305,18 +1303,14 @@ public static function getBrowser() foreach ($accepted as $accept) { $match = null; - $result = preg_match('/^([a-z]{1,8}(?:[-_][a-z]{1,8})*)(?:;\s*q=(0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?))?$/i', + $result = preg_match('/^([a-z]{1,8}(?:[-_][a-z]{1,8})*)(?:;\s*q=(0(?:\.\d{1,3})?|1(?:\.0{1,3})?))?$/i', (string) $accept, $match); if ($result < 1) { continue; } - if (isset($match[2]) === true) { - $quality = (float) $match[2]; - } else { - $quality = 1.0; - } + $quality = isset($match[2]) ? (float) $match[2] : 1.0; $countrys = explode('-', (string) $match[1]); $region = array_shift($countrys); @@ -1332,7 +1326,7 @@ public static function getBrowser() $languages[$region . '_' . strtoupper($country)] = $quality; } - if ((isset($languages[$region]) === false) || ($languages[$region] < $quality)) { + if ((!isset($languages[$region])) || ($languages[$region] < $quality)) { $languages[$region] = $quality; } } @@ -1351,25 +1345,19 @@ public function setLocale($locale = null) { $locale = self::_prepareLocale($locale); - if (isset(self::$_localeData[(string) $locale]) === false) { + if (!isset(self::$_localeData[(string) $locale])) { // Is it an alias? If so, we can use this locale - if (isset(self::$_localeAliases[$locale]) === true) { + if (isset(self::$_localeAliases[$locale])) { $this->_locale = $locale; return; } $region = substr((string) $locale, 0, 3); - if (isset($region[2]) === true) { - if (($region[2] === '_') or ($region[2] === '-')) { - $region = substr($region, 0, 2); - } + if (isset($region[2]) && ($region[2] === '_' || $region[2] === '-')) { + $region = substr($region, 0, 2); } - if (isset(self::$_localeData[(string) $region]) === true) { - $this->_locale = $region; - } else { - $this->_locale = 'root'; - } + $this->_locale = isset(self::$_localeData[(string) $region]) ? $region : 'root'; } else { $this->_locale = $locale; } @@ -1394,7 +1382,7 @@ public function getLanguage() public function getRegion() { $locale = explode('_', $this->_locale); - if (isset($locale[1]) === true) { + if (isset($locale[1])) { return $locale[1]; } @@ -1417,7 +1405,7 @@ public static function getHttpCharset() $accepted = preg_split('/,\s*/', $httpcharsets); foreach ($accepted as $accept) { - if (empty($accept) === true) { + if (empty($accept)) { continue; } @@ -1442,11 +1430,7 @@ public static function getHttpCharset() */ public function equals(Zend_Locale $object) { - if ($object->toString() === $this->toString()) { - return true; - } - - return false; + return $object->toString() === $this->toString(); } /** @@ -1464,7 +1448,7 @@ public static function getTranslationList($path = null, $locale = null, $value = require_once 'Zend/Locale/Data.php'; $locale = self::findLocale($locale); $result = Zend_Locale_Data::getList($locale, $path, $value); - if (empty($result) === true) { + if (empty($result)) { return false; } @@ -1538,7 +1522,7 @@ public static function getTranslation($value = null, $path = null, $locale = nul require_once 'Zend/Locale/Data.php'; $locale = self::findLocale($locale); $result = Zend_Locale_Data::getContent($locale, $path, $value); - if (empty($result) === true && '0' !== $result) { + if (empty($result) && '0' !== $result) { return false; } @@ -1634,11 +1618,11 @@ public static function getQuestion($locale = null) private static function _prepareQuestionString($input) { $regex = ''; - if (is_array($input) === true) { + if (is_array($input)) { $regex = '^'; $start = true; foreach ($input as $row) { - if ($start === false) { + if (!$start) { $regex .= '|'; } @@ -1693,7 +1677,7 @@ public static function isLocale($locale, $strict = false, $compatible = true) return true; } - if (($locale === null) || (!is_string($locale) and !is_array($locale))) { + if (($locale === null) || (!is_string($locale) && !is_array($locale))) { return false; } @@ -1703,24 +1687,22 @@ public static function isLocale($locale, $strict = false, $compatible = true) return false; } - if (($compatible === true) and (self::$compatibilityMode === true)) { + if ($compatible && self::$compatibilityMode) { trigger_error('You are running Zend_Locale in compatibility mode... please migrate your scripts', E_USER_NOTICE); - if (isset(self::$_localeData[$locale]) === true) { + if (isset(self::$_localeData[$locale])) { return $locale; - } else if (!$strict) { + } elseif (!$strict) { $locale = explode('_', $locale); - if (isset(self::$_localeData[$locale[0]]) === true) { + if (isset(self::$_localeData[$locale[0]])) { return $locale[0]; } } - } else { - if (isset(self::$_localeData[$locale]) === true) { + } elseif (isset(self::$_localeData[$locale])) { + return true; + } elseif (!$strict) { + $locale = explode('_', $locale); + if (isset(self::$_localeData[$locale[0]])) { return true; - } else if (!$strict) { - $locale = explode('_', $locale); - if (isset(self::$_localeData[$locale[0]]) === true) { - return true; - } } } @@ -1854,7 +1836,7 @@ public static function removeCache() public static function clearCache($tag = null) { require_once 'Zend/Locale/Data.php'; - Zend_Locale_Data::clearCache($tag); + Zend_Locale_Data::clearCache(); } /** @@ -1887,7 +1869,7 @@ private static function _prepareLocale($locale, $strict = false) return ''; } - if (empty(self::$_auto) === true) { + if (empty(self::$_auto)) { self::$_browser = self::getBrowser(); self::$_environment = self::getEnvironment(); self::$_breakChain = true; @@ -1907,11 +1889,11 @@ private static function _prepareLocale($locale, $strict = false) $locale = self::$_default; } - if (($locale === 'auto') or ($locale === null)) { + if ($locale === 'auto' || $locale === null) { $locale = self::$_auto; } - if (is_array($locale) === true) { + if (is_array($locale)) { $locale = key($locale); } } @@ -2003,7 +1985,7 @@ public static function getAlias($locale) $locale = $locale->toString(); } - if (isset(self::$_localeAliases[$locale]) === true) { + if (isset(self::$_localeAliases[$locale])) { return self::$_localeAliases[$locale]; } diff --git a/library/Zend/Locale/Data.php b/library/Zend/Locale/Data.php index 8645f9c6d0..feffcbf9f0 100644 --- a/library/Zend/Locale/Data.php +++ b/library/Zend/Locale/Data.php @@ -109,25 +109,15 @@ private static function _readFile($locale, $path, $attribute, $value, $temp) foreach ($result as &$found) { if (empty($value)) { - if (empty($attribute)) { // Case 1 $temp[] = (string) $found; - } else if (empty($temp[(string) $found[$attribute]])){ + } elseif (empty($temp[(string) $found[$attribute]])) { // Case 2 $temp[(string) $found[$attribute]] = (string) $found; } - - } else if (empty ($temp[$value])) { - - if (empty($attribute)) { - // Case 3 - $temp[$value] = (string) $found; - } else { - // Case 4 - $temp[$value] = (string) $found[$attribute]; - } - + } elseif (empty ($temp[$value])) { + $temp[$value] = empty($attribute) ? (string) $found : (string) $found[$attribute]; } } } @@ -269,7 +259,7 @@ private static function _getFile($locale, $path, $attribute = false, $value = fa private static function _calendarDetail($locale, $list) { $ret = "001"; - foreach ($list as $key => $value) { + foreach (array_keys($list) as $key) { if (strpos($locale, '_') !== false) { $locale = substr($locale, strpos($locale, '_') + 1); } @@ -352,14 +342,14 @@ public static function getList($locale, $path, $value = false) case 'territory': $temp = self::_getFile($locale, '/ldml/localeDisplayNames/territories/territory', 'type'); if ($value === 1) { - foreach($temp as $key => $value) { - if ((is_numeric($key) === false) and ($key != 'QO') and ($key != 'EU')) { + foreach(array_keys($temp) as $key) { + if (!is_numeric($key) && $key != 'QO' && $key != 'EU') { unset($temp[$key]); } } - } else if ($value === 2) { - foreach($temp as $key => $value) { - if (is_numeric($key) or ($key == 'QO') or ($key == 'EU')) { + } elseif ($value === 2) { + foreach(array_keys($temp) as $key) { + if (is_numeric($key) || $key == 'QO' || $key == 'EU') { unset($temp[$key]); } } @@ -377,14 +367,10 @@ public static function getList($locale, $path, $value = false) case 'type': if (empty($value)) { $temp = self::_getFile($locale, '/ldml/localeDisplayNames/types/type', 'type'); + } elseif ($value == 'calendar' || $value == 'collation' || $value == 'currency') { + $temp = self::_getFile($locale, '/ldml/localeDisplayNames/types/type[@key=\'' . $value . '\']', 'type'); } else { - if (($value == 'calendar') or - ($value == 'collation') or - ($value == 'currency')) { - $temp = self::_getFile($locale, '/ldml/localeDisplayNames/types/type[@key=\'' . $value . '\']', 'type'); - } else { - $temp = self::_getFile($locale, '/ldml/localeDisplayNames/types/type[@type=\'' . $value . '\']', 'type'); - } + $temp = self::_getFile($locale, '/ldml/localeDisplayNames/types/type[@type=\'' . $value . '\']', 'type'); } break; @@ -589,7 +575,7 @@ public static function getList($locale, $path, $value = false) $value = "gregorian"; } $_temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/dateTimeFormats/availableFormats/dateFormatItem', 'id'); - foreach($_temp as $key => $found) { + foreach(array_keys($_temp) as $key) { $temp += self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/dateTimeFormats/availableFormats/dateFormatItem[@id=\'' . $key . '\']', '', $key); } break; @@ -599,7 +585,7 @@ public static function getList($locale, $path, $value = false) $value = "gregorian"; } $_temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/dateTimeFormats/intervalFormats/intervalFormatItem', 'id'); - foreach($_temp as $key => $found) { + foreach(array_keys($_temp) as $key) { $temp[$key] = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/dateTimeFormats/intervalFormats/intervalFormatItem[@id=\'' . $key . '\']/greatestDifference', 'id'); } break; @@ -610,7 +596,7 @@ public static function getList($locale, $path, $value = false) } $temp2 = self::_getFile($locale, '/ldml/dates/fields/field', 'type'); // $temp2 = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/fields/field', 'type'); - foreach ($temp2 as $key => $keyvalue) { + foreach (array_keys($temp2) as $key) { $temp += self::_getFile($locale, '/ldml/dates/fields/field[@type=\'' . $key . '\']/displayName', '', $key); // $temp += self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/fields/field[@type=\'' . $key . '\']/displayName', '', $key); } @@ -640,14 +626,14 @@ public static function getList($locale, $path, $value = false) case 'nametocurrency': $_temp = self::_getFile($locale, '/ldml/numbers/currencies/currency', 'type'); - foreach ($_temp as $key => $found) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile($locale, '/ldml/numbers/currencies/currency[@type=\'' . $key . '\']/displayName', '', $key); } break; case 'currencytoname': $_temp = self::_getFile($locale, '/ldml/numbers/currencies/currency', 'type'); - foreach ($_temp as $key => $keyvalue) { + foreach (array_keys($_temp) as $key) { $val = self::_getFile($locale, '/ldml/numbers/currencies/currency[@type=\'' . $key . '\']/displayName', '', $key); if (!isset($val[$key])) { continue; @@ -662,7 +648,7 @@ public static function getList($locale, $path, $value = false) case 'currencysymbol': $_temp = self::_getFile($locale, '/ldml/numbers/currencies/currency', 'type'); - foreach ($_temp as $key => $found) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile($locale, '/ldml/numbers/currencies/currency[@type=\'' . $key . '\']/symbol', '', $key); } break; @@ -674,28 +660,28 @@ public static function getList($locale, $path, $value = false) case 'currencyfraction': $_temp = self::_getFile('supplementalData', '/supplementalData/currencyData/fractions/info', 'iso4217'); - foreach ($_temp as $key => $found) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile('supplementalData', '/supplementalData/currencyData/fractions/info[@iso4217=\'' . $key . '\']', 'digits', $key); } break; case 'currencyrounding': $_temp = self::_getFile('supplementalData', '/supplementalData/currencyData/fractions/info', 'iso4217'); - foreach ($_temp as $key => $found) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile('supplementalData', '/supplementalData/currencyData/fractions/info[@iso4217=\'' . $key . '\']', 'rounding', $key); } break; case 'currencytoregion': $_temp = self::_getFile('supplementalData', '/supplementalData/currencyData/region', 'iso3166'); - foreach ($_temp as $key => $keyvalue) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile('supplementalData', '/supplementalData/currencyData/region[@iso3166=\'' . $key . '\']/currency', 'iso4217', $key); } break; case 'regiontocurrency': $_temp = self::_getFile('supplementalData', '/supplementalData/currencyData/region', 'iso3166'); - foreach ($_temp as $key => $keyvalue) { + foreach (array_keys($_temp) as $key) { $val = self::_getFile('supplementalData', '/supplementalData/currencyData/region[@iso3166=\'' . $key . '\']/currency', 'iso4217', $key); if (!isset($val[$key])) { continue; @@ -710,7 +696,7 @@ public static function getList($locale, $path, $value = false) case 'regiontoterritory': $_temp = self::_getFile('supplementalData', '/supplementalData/territoryContainment/group', 'type'); - foreach ($_temp as $key => $found) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile('supplementalData', '/supplementalData/territoryContainment/group[@type=\'' . $key . '\']', 'contains', $key); } break; @@ -718,7 +704,7 @@ public static function getList($locale, $path, $value = false) case 'territorytoregion': $_temp2 = self::_getFile('supplementalData', '/supplementalData/territoryContainment/group', 'type'); $_temp = array(); - foreach ($_temp2 as $key => $found) { + foreach (array_keys($_temp2) as $key) { $_temp += self::_getFile('supplementalData', '/supplementalData/territoryContainment/group[@type=\'' . $key . '\']', 'contains', $key); } foreach($_temp as $key => $found) { @@ -735,7 +721,7 @@ public static function getList($locale, $path, $value = false) case 'scripttolanguage': $_temp = self::_getFile('supplementalData', '/supplementalData/languageData/language', 'type'); - foreach ($_temp as $key => $found) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile('supplementalData', '/supplementalData/languageData/language[@type=\'' . $key . '\']', 'scripts', $key); if (empty($temp[$key])) { unset($temp[$key]); @@ -746,7 +732,7 @@ public static function getList($locale, $path, $value = false) case 'languagetoscript': $_temp2 = self::_getFile('supplementalData', '/supplementalData/languageData/language', 'type'); $_temp = array(); - foreach ($_temp2 as $key => $found) { + foreach (array_keys($_temp2) as $key) { $_temp += self::_getFile('supplementalData', '/supplementalData/languageData/language[@type=\'' . $key . '\']', 'scripts', $key); } foreach($_temp as $key => $found) { @@ -766,7 +752,7 @@ public static function getList($locale, $path, $value = false) case 'territorytolanguage': $_temp = self::_getFile('supplementalData', '/supplementalData/languageData/language', 'type'); - foreach ($_temp as $key => $found) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile('supplementalData', '/supplementalData/languageData/language[@type=\'' . $key . '\']', 'territories', $key); if (empty($temp[$key])) { unset($temp[$key]); @@ -777,7 +763,7 @@ public static function getList($locale, $path, $value = false) case 'languagetoterritory': $_temp2 = self::_getFile('supplementalData', '/supplementalData/languageData/language', 'type'); $_temp = array(); - foreach ($_temp2 as $key => $found) { + foreach (array_keys($_temp2) as $key) { $_temp += self::_getFile('supplementalData', '/supplementalData/languageData/language[@type=\'' . $key . '\']', 'territories', $key); } foreach($_temp as $key => $found) { @@ -797,35 +783,35 @@ public static function getList($locale, $path, $value = false) case 'timezonetowindows': $_temp = self::_getFile('windowsZones', '/supplementalData/windowsZones/mapTimezones/mapZone', 'other'); - foreach ($_temp as $key => $found) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile('windowsZones', '/supplementalData/windowsZones/mapTimezones/mapZone[@other=\'' . $key . '\']', 'type', $key); } break; case 'windowstotimezone': $_temp = self::_getFile('windowsZones', '/supplementalData/windowsZones/mapTimezones/mapZone', 'type'); - foreach ($_temp as $key => $found) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile('windowsZones', '/supplementalData/windowsZones/mapTimezones/mapZone[@type=\'' .$key . '\']', 'other', $key); } break; case 'territorytotimezone': $_temp = self::_getFile('metaZones', '/supplementalData/metaZones/mapTimezones/mapZone', 'type'); - foreach ($_temp as $key => $found) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile('metaZones', '/supplementalData/metaZones/mapTimezones/mapZone[@type=\'' . $key . '\']', 'territory', $key); } break; case 'timezonetoterritory': $_temp = self::_getFile('metaZones', '/supplementalData/metaZones/mapTimezones/mapZone', 'territory'); - foreach ($_temp as $key => $found) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile('metaZones', '/supplementalData/metaZones/mapTimezones/mapZone[@territory=\'' . $key . '\']', 'type', $key); } break; case 'citytotimezone': $_temp = self::_getFile($locale, '/ldml/dates/timeZoneNames/zone', 'type'); - foreach($_temp as $key => $found) { + foreach(array_keys($_temp) as $key) { $temp += self::_getFile($locale, '/ldml/dates/timeZoneNames/zone[@type=\'' . $key . '\']/exemplarCity', '', $key); } break; @@ -833,7 +819,7 @@ public static function getList($locale, $path, $value = false) case 'timezonetocity': $_temp = self::_getFile($locale, '/ldml/dates/timeZoneNames/zone', 'type'); $temp = array(); - foreach($_temp as $key => $found) { + foreach(array_keys($_temp) as $key) { $temp += self::_getFile($locale, '/ldml/dates/timeZoneNames/zone[@type=\'' . $key . '\']/exemplarCity', '', $key); if (!empty($temp[$key])) { $temp[$temp[$key]] = $key; @@ -844,14 +830,14 @@ public static function getList($locale, $path, $value = false) case 'phonetoterritory': $_temp = self::_getFile('telephoneCodeData', '/supplementalData/telephoneCodeData/codesByTerritory', 'territory'); - foreach ($_temp as $key => $keyvalue) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile('telephoneCodeData', '/supplementalData/telephoneCodeData/codesByTerritory[@territory=\'' . $key . '\']/telephoneCountryCode', 'code', $key); } break; case 'territorytophone': $_temp = self::_getFile('telephoneCodeData', '/supplementalData/telephoneCodeData/codesByTerritory', 'territory'); - foreach ($_temp as $key => $keyvalue) { + foreach (array_keys($_temp) as $key) { $val = self::_getFile('telephoneCodeData', '/supplementalData/telephoneCodeData/codesByTerritory[@territory=\'' . $key . '\']/telephoneCountryCode', 'code', $key); if (!isset($val[$key])) { continue; @@ -866,42 +852,42 @@ public static function getList($locale, $path, $value = false) case 'numerictoterritory': $_temp = self::_getFile('supplementalData', '/supplementalData/codeMappings/territoryCodes', 'type'); - foreach ($_temp as $key => $keyvalue) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile('supplementalData', '/supplementalData/codeMappings/territoryCodes[@type=\'' . $key . '\']', 'numeric', $key); } break; case 'territorytonumeric': $_temp = self::_getFile('supplementalData', '/supplementalData/codeMappings/territoryCodes', 'numeric'); - foreach ($_temp as $key => $keyvalue) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile('supplementalData', '/supplementalData/codeMappings/territoryCodes[@numeric=\'' . $key . '\']', 'type', $key); } break; case 'alpha3toterritory': $_temp = self::_getFile('supplementalData', '/supplementalData/codeMappings/territoryCodes', 'type'); - foreach ($_temp as $key => $keyvalue) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile('supplementalData', '/supplementalData/codeMappings/territoryCodes[@type=\'' . $key . '\']', 'alpha3', $key); } break; case 'territorytoalpha3': $_temp = self::_getFile('supplementalData', '/supplementalData/codeMappings/territoryCodes', 'alpha3'); - foreach ($_temp as $key => $keyvalue) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile('supplementalData', '/supplementalData/codeMappings/territoryCodes[@alpha3=\'' . $key . '\']', 'type', $key); } break; case 'postaltoterritory': $_temp = self::_getFile('postalCodeData', '/supplementalData/postalCodeData/postCodeRegex', 'territoryId'); - foreach ($_temp as $key => $keyvalue) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile('postalCodeData', '/supplementalData/postalCodeData/postCodeRegex[@territoryId=\'' . $key . '\']', 'territoryId'); } break; case 'numberingsystem': $_temp = self::_getFile('numberingSystems', '/supplementalData/numberingSystems/numberingSystem', 'id'); - foreach ($_temp as $key => $keyvalue) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile('numberingSystems', '/supplementalData/numberingSystems/numberingSystem[@id=\'' . $key . '\']', 'digits', $key); if (empty($temp[$key])) { unset($temp[$key]); @@ -911,7 +897,7 @@ public static function getList($locale, $path, $value = false) case 'chartofallback': $_temp = self::_getFile('characters', '/supplementalData/characters/character-fallback/character', 'value'); - foreach ($_temp as $key => $keyvalue) { + foreach (array_keys($_temp) as $key) { $temp2 = self::_getFile('characters', '/supplementalData/characters/character-fallback/character[@value=\'' . $key . '\']/substitute', '', $key); $temp[current($temp2)] = $key; } @@ -919,21 +905,21 @@ public static function getList($locale, $path, $value = false) case 'fallbacktochar': $_temp = self::_getFile('characters', '/supplementalData/characters/character-fallback/character', 'value'); - foreach ($_temp as $key => $keyvalue) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile('characters', '/supplementalData/characters/character-fallback/character[@value=\'' . $key . '\']/substitute', '', $key); } break; case 'localeupgrade': $_temp = self::_getFile('likelySubtags', '/supplementalData/likelySubtags/likelySubtag', 'from'); - foreach ($_temp as $key => $keyvalue) { + foreach (array_keys($_temp) as $key) { $temp += self::_getFile('likelySubtags', '/supplementalData/likelySubtags/likelySubtag[@from=\'' . $key . '\']', 'to', $key); } break; case 'unit': $_temp = self::_getFile($locale, '/ldml/units/unitLength/unit', 'type'); - foreach($_temp as $key => $keyvalue) { + foreach(array_keys($_temp) as $key) { $_temp2 = self::_getFile($locale, '/ldml/units/unitLength/unit[@type=\'' . $key . '\']/unitPattern', 'count'); $temp[$key] = $_temp2; } @@ -982,7 +968,7 @@ public static function getContent($locale, $path, $value = false) if (is_array($value)) { $val = implode('_' , $value); } - $val = urlencode($val); + $val = urlencode((string) $val); $id = self::_filterCacheId('Zend_LocaleC_' . $locale . '_' . $path . '_' . $val); if (!self::$_cacheDisabled && ($result = self::$_cache->load($id))) { return unserialize($result); @@ -1240,9 +1226,9 @@ public static function getContent($locale, $path, $value = false) $temp = self::_getFile($locale, '/ldml/numbers/currencies/currency[@type=\'' . $value . '\']/displayName', '', $value); $_temp = self::_getFile($locale, '/ldml/numbers/currencies/currency', 'type'); $temp = array(); - foreach ($_temp as $key => $keyvalue) { + foreach (array_keys($_temp) as $key) { $val = self::_getFile($locale, '/ldml/numbers/currencies/currency[@type=\'' . $key . '\']/displayName', '', $key); - if (!isset($val[$key]) or ($val[$key] != $value)) { + if (!isset($val[$key]) || $val[$key] != $value) { continue; } if (!isset($temp[$val[$key]])) { @@ -1282,9 +1268,9 @@ public static function getContent($locale, $path, $value = false) case 'regiontocurrency': $_temp = self::_getFile('supplementalData', '/supplementalData/currencyData/region', 'iso3166'); $temp = array(); - foreach ($_temp as $key => $keyvalue) { + foreach (array_keys($_temp) as $key) { $val = self::_getFile('supplementalData', '/supplementalData/currencyData/region[@iso3166=\'' . $key . '\']/currency', 'iso4217', $key); - if (!isset($val[$key]) or ($val[$key] != $value)) { + if (!isset($val[$key]) || $val[$key] != $value) { continue; } if (!isset($temp[$val[$key]])) { @@ -1302,7 +1288,7 @@ public static function getContent($locale, $path, $value = false) case 'territorytoregion': $_temp2 = self::_getFile('supplementalData', '/supplementalData/territoryContainment/group', 'type'); $_temp = array(); - foreach ($_temp2 as $key => $found) { + foreach (array_keys($_temp2) as $key) { $_temp += self::_getFile('supplementalData', '/supplementalData/territoryContainment/group[@type=\'' . $key . '\']', 'contains', $key); } $temp = array(); @@ -1328,7 +1314,7 @@ public static function getContent($locale, $path, $value = false) case 'languagetoscript': $_temp2 = self::_getFile('supplementalData', '/supplementalData/languageData/language', 'type'); $_temp = array(); - foreach ($_temp2 as $key => $found) { + foreach (array_keys($_temp2) as $key) { $_temp += self::_getFile('supplementalData', '/supplementalData/languageData/language[@type=\'' . $key . '\']', 'scripts', $key); } $temp = array(); @@ -1354,7 +1340,7 @@ public static function getContent($locale, $path, $value = false) case 'languagetoterritory': $_temp2 = self::_getFile('supplementalData', '/supplementalData/languageData/language', 'type'); $_temp = array(); - foreach ($_temp2 as $key => $found) { + foreach (array_keys($_temp2) as $key) { $_temp += self::_getFile('supplementalData', '/supplementalData/languageData/language[@type=\'' . $key . '\']', 'territories', $key); } $temp = array(); @@ -1396,12 +1382,10 @@ public static function getContent($locale, $path, $value = false) case 'timezonetocity': $_temp = self::_getFile($locale, '/ldml/dates/timeZoneNames/zone', 'type'); $temp = array(); - foreach($_temp as $key => $found) { + foreach(array_keys($_temp) as $key) { $temp += self::_getFile($locale, '/ldml/dates/timeZoneNames/zone[@type=\'' . $key . '\']/exemplarCity', '', $key); - if (!empty($temp[$key])) { - if ($temp[$key] == $value) { - $temp[$temp[$key]] = $key; - } + if (!empty($temp[$key]) && $temp[$key] == $value) { + $temp[$temp[$key]] = $key; } unset($temp[$key]); } @@ -1414,7 +1398,7 @@ public static function getContent($locale, $path, $value = false) case 'territorytophone': $_temp2 = self::_getFile('telephoneCodeData', '/supplementalData/telephoneCodeData/codesByTerritory', 'territory'); $_temp = array(); - foreach ($_temp2 as $key => $found) { + foreach (array_keys($_temp2) as $key) { $_temp += self::_getFile('telephoneCodeData', '/supplementalData/telephoneCodeData/codesByTerritory[@territory=\'' . $key . '\']/telephoneCountryCode', 'code', $key); } $temp = array(); @@ -1459,7 +1443,7 @@ public static function getContent($locale, $path, $value = false) case 'chartofallback': $_temp = self::_getFile('characters', '/supplementalData/characters/character-fallback/character', 'value'); - foreach ($_temp as $key => $keyvalue) { + foreach (array_keys($_temp) as $key) { $temp2 = self::_getFile('characters', '/supplementalData/characters/character-fallback/character[@value=\'' . $key . '\']/substitute', '', $key); if (current($temp2) == $value) { $temp = $key; @@ -1537,11 +1521,7 @@ public static function setCache(Zend_Cache_Core $cache) */ public static function hasCache() { - if (self::$_cache !== null) { - return true; - } - - return false; + return self::$_cache !== null; } /** diff --git a/library/Zend/Locale/Format.php b/library/Zend/Locale/Format.php index 0f5943541e..678eb73d78 100644 --- a/library/Zend/Locale/Format.php +++ b/library/Zend/Locale/Format.php @@ -83,10 +83,8 @@ private static function _checkOptions(array $options = array()) } foreach ($options as $name => $value) { $name = strtolower($name); - if ($name !== 'locale') { - if (gettype($value) === 'string') { - $value = strtolower($value); - } + if ($name !== 'locale' && gettype($value) === 'string') { + $value = strtolower($value); } switch($name) { @@ -97,7 +95,7 @@ private static function _checkOptions(array $options = array()) $locale = $options['locale']; } $options['number_format'] = Zend_Locale_Data::getContent($locale, 'decimalnumber'); - } else if ((gettype($value) !== 'string') and ($value !== NULL)) { + } elseif (gettype($value) !== 'string' && $value !== NULL) { require_once 'Zend/Locale/Exception.php'; $stringValue = (string)(is_array($value) ? implode(' ', $value) : $value); throw new Zend_Locale_Exception("Unknown number format type '" . gettype($value) . "'. " @@ -112,16 +110,13 @@ private static function _checkOptions(array $options = array()) $locale = $options['locale']; } $options['date_format'] = Zend_Locale_Format::getDateFormat($locale); - } else if ((gettype($value) !== 'string') and ($value !== NULL)) { + } elseif (gettype($value) !== 'string' && $value !== NULL) { require_once 'Zend/Locale/Exception.php'; $stringValue = (string)(is_array($value) ? implode(' ', $value) : $value); throw new Zend_Locale_Exception("Unknown dateformat type '" . gettype($value) . "'. " . "Format '$stringValue' must be a valid ISO or PHP date format string."); - } else { - if (((isset($options['format_type']) === true) and ($options['format_type'] == 'php')) or - ((isset($options['format_type']) === false) and (self::$_options['format_type'] == 'php'))) { - $options['date_format'] = Zend_Locale_Format::convertPhpToIsoFormat($value); - } + } elseif (isset($options['format_type']) && $options['format_type'] == 'php' || !isset($options['format_type']) && self::$_options['format_type'] == 'php') { + $options['date_format'] = Zend_Locale_Format::convertPhpToIsoFormat($value); } break; @@ -327,15 +322,13 @@ public static function toNumber($value, array $options = array()) if (strpos($format, '.')) { if (is_numeric($options['precision'])) { $value = Zend_Locale_Math::round($value, $options['precision']); + } elseif (substr($format, iconv_strpos($format, '.') + 1, 3) == '###') { + $options['precision'] = null; } else { - if (substr($format, iconv_strpos($format, '.') + 1, 3) == '###') { - $options['precision'] = null; - } else { - $options['precision'] = iconv_strlen(iconv_substr($format, iconv_strpos($format, '.') + 1, - iconv_strrpos($format, '0') - iconv_strpos($format, '.'))); - $format = iconv_substr($format, 0, iconv_strpos($format, '.') + 1) . '###' - . iconv_substr($format, iconv_strrpos($format, '0') + 1); - } + $options['precision'] = iconv_strlen(iconv_substr($format, iconv_strpos($format, '.') + 1, + iconv_strrpos($format, '0') - iconv_strpos($format, '.'))); + $format = iconv_substr($format, 0, iconv_strpos($format, '.') + 1) . '###' + . iconv_substr($format, iconv_strrpos($format, '0') + 1); } } else { $value = Zend_Locale_Math::round($value, 0); @@ -358,29 +351,19 @@ public static function toNumber($value, array $options = array()) } else { $precstr = iconv_substr($value, $pos + 1, $options['precision']); if (iconv_strlen($precstr) < $options['precision']) { - $precstr = $precstr . str_pad("0", ($options['precision'] - iconv_strlen($precstr)), "0"); + $precstr .= str_pad("0", ($options['precision'] - iconv_strlen($precstr)), "0"); } } - } else { - if ($options['precision'] > 0) { - $precstr = str_pad("0", ($options['precision']), "0"); - } + } elseif ($options['precision'] > 0) { + $precstr = str_pad("0", ($options['precision']), "0"); } if ($options['precision'] === null) { - if (isset($precstr)) { - $options['precision'] = iconv_strlen($precstr); - } else { - $options['precision'] = 0; - } + $options['precision'] = isset($precstr) ? iconv_strlen($precstr) : 0; } // get fraction and format lengths - if (strpos($value, '.') !== false) { - $number = substr((string) $value, 0, strpos($value, '.')); - } else { - $number = $value; - } + $number = strpos($value, '.') !== false ? substr((string) $value, 0, strpos($value, '.')) : $value; $prec = call_user_func(Zend_Locale_Math::$sub, $value, $number, $options['precision']); $prec = Zend_Locale_Math::floatalize($prec); @@ -389,7 +372,7 @@ public static function toNumber($value, array $options = array()) $prec = iconv_substr($prec, 1); } - if (($prec == 0) and ($options['precision'] > 0)) { + if ($prec == 0 && $options['precision'] > 0) { $prec = "0.0"; } @@ -433,7 +416,7 @@ public static function toNumber($value, array $options = array()) if ($group == 0) { // no seperation $format = $number . iconv_substr($format, $point); - } else if ($group == $group2) { + } elseif ($group === $group2) { // only 1 seperation $seperation = ($point - $group); for ($x = iconv_strlen($number); $x > $seperation; $x -= $seperation) { @@ -486,11 +469,7 @@ private static function _seperateFormat($format, $value, $precision) if (iconv_strpos($format, ';') !== false) { if (call_user_func(Zend_Locale_Math::$comp, $value, 0, $precision) < 0) { $tmpformat = iconv_substr($format, iconv_strpos($format, ';') + 1); - if ($tmpformat[0] == '(') { - $format = iconv_substr($format, 0, iconv_strpos($format, ';')); - } else { - $format = $tmpformat; - } + $format = $tmpformat[0] == '(' ? iconv_substr($format, 0, iconv_strpos($format, ';')) : $tmpformat; } else { $format = iconv_substr($format, 0, iconv_strpos($format, ';')); } @@ -575,9 +554,9 @@ private static function _getRegexForType($type, $options) $regex[$pkey] .= '[' . $symbols['plus'] . '+]{0,1}'; } - if (($parts[$key + 1]) == '##0') { + if (($parts[$key + 1]) == '##0') { $regex[$pkey] .= '[0-9]{1,3}'; - } else if (($parts[$key + 1]) == '##') { + } elseif (($parts[$key + 1]) == '##') { $regex[$pkey] .= '[0-9]{1,2}'; } else { throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 1):"' . $pattern . '"'); @@ -593,7 +572,7 @@ private static function _getRegexForType($type, $options) case '##0': if ($parts[$key - 1] == '##') { $regex[$pkey] .= '[0-9]'; - } else if (($parts[$key - 1] == '#') || ($parts[$key - 1] == '-#')) { + } elseif (($parts[$key - 1] == '#') || ($parts[$key - 1] == '-#')) { $regex[$pkey] .= '(\\' . $symbols['group'] . '{0,1}[0-9]{3})*'; } else { throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 3):"' . $pattern . '"'); @@ -613,7 +592,7 @@ private static function _getRegexForType($type, $options) if (strpos($pattern, 'E') !== false) { if (($pattern == '#E0') || ($pattern == '#E00')) { $regex[$pkey] .= '[' . $symbols['plus']. '+]{0,1}[0-9]{1,}(\\' . $symbols['decimal'] . '[0-9]{1,})*[eE][' . $symbols['plus']. '+]{0,1}[0-9]{1,}'; - } else if (($pattern == '-#E0') || ($pattern == '-#E00')) { + } elseif (($pattern == '-#E0') || ($pattern == '-#E00')) { $regex[$pkey] .= '[' . $symbols['minus']. '-]{0,1}[0-9]{1,}(\\' . $symbols['decimal'] . '[0-9]{1,})*[eE][' . $symbols['minus']. '-]{0,1}[0-9]{1,}'; } else { throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 5):"' . $pattern . '"'); @@ -623,7 +602,7 @@ private static function _getRegexForType($type, $options) if (!empty($end)) { if ($end == '###') { $regex[$pkey] .= '(\\' . $symbols['decimal'] . '{1}[0-9]{1,}){0,1}'; - } else if ($end == '###-') { + } elseif ($end == '###-') { $regex[$pkey] .= '(\\' . $symbols['decimal'] . '{1}[0-9]{1,}){0,1}[' . $symbols['minus']. '-]'; } else { throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 6):"' . $pattern . '"'); @@ -694,7 +673,7 @@ public static function isFloat($value, array $options = array()) public static function getInteger($input, array $options = array()) { $options['precision'] = 0; - return intval(self::getFloat($input, $options)); + return (int) self::getFloat($input, $options); } /** @@ -723,12 +702,7 @@ public static function isInteger($value, array $options = array()) if (!self::isNumber($value, $options)) { return false; } - - if (self::getInteger($value, $options) == self::getFloat($value, $options)) { - return true; - } - - return false; + return self::getInteger($value, $options) == self::getFloat($value, $options); } /** @@ -788,11 +762,7 @@ public static function convertPhpToIsoFormat($format) $inEscapedString = false; } // Convert the unescaped char if needed - if (isset($convert[$char])) { - $converted[] = $convert[$char]; - } else { - $converted[] = $char; - } + $converted[] = isset($convert[$char]) ? $convert[$char] : $char; } } @@ -898,7 +868,7 @@ private static function _parseDate($date, $options) if (iconv_strpos($format, 'a') !== false) { if (iconv_strpos(strtoupper($number), strtoupper(Zend_Locale_Data::getContent($options['locale'], 'am'))) !== false) { $am = true; - } else if (iconv_strpos(strtoupper($number), strtoupper(Zend_Locale_Data::getContent($options['locale'], 'pm'))) !== false) { + } elseif (iconv_strpos(strtoupper($number), strtoupper(Zend_Locale_Data::getContent($options['locale'], 'pm'))) !== false) { $am = false; } } @@ -997,9 +967,9 @@ private static function _parseDate($date, $options) // AM/PM correction if ($hour !== false) { - if (($am === true) and ($result['hour'] == 12)){ + if ($am === true && $result['hour'] == 12) { $result['hour'] = 0; - } else if (($am === false) and ($result['hour'] != 12)) { + } elseif ($am === false && $result['hour'] != 12) { $result['hour'] += 12; } } @@ -1010,83 +980,69 @@ private static function _parseDate($date, $options) if ($day !== false) { // fix false month - if (isset($result['day']) and isset($result['month'])) { - if (($position !== false) and ((iconv_strpos($date, $result['day']) === false) or - (isset($result['year']) and (iconv_strpos($date, $result['year']) === false)))) { - if ($options['fix_date'] !== true) { - self::_setEncoding($oenc); - require_once 'Zend/Locale/Exception.php'; - throw new Zend_Locale_Exception("Unable to parse date '$date' using '" . $format - . "' (false month, $position, $month)"); - } - $temp = $result['day']; - $result['day'] = $result['month']; - $result['month'] = $temp; - $result['fixed'] = 1; + if ((isset($result['day']) && isset($result['month'])) && ($position !== false && (iconv_strpos($date, $result['day']) === false || isset($result['year']) && iconv_strpos($date, $result['year']) === false))) { + if ($options['fix_date'] !== true) { + self::_setEncoding($oenc); + require_once 'Zend/Locale/Exception.php'; + throw new Zend_Locale_Exception("Unable to parse date '$date' using '" . $format + . "' (false month, $position, $month)"); } + $temp = $result['day']; + $result['day'] = $result['month']; + $result['month'] = $temp; + $result['fixed'] = 1; } // fix switched values d <> y - if (isset($result['day']) and isset($result['year'])) { - if ($result['day'] > 31) { - if ($options['fix_date'] !== true) { - self::_setEncoding($oenc); - require_once 'Zend/Locale/Exception.php'; - throw new Zend_Locale_Exception("Unable to parse date '$date' using '" - . $format . "' (d <> y)"); - } - $temp = $result['year']; - $result['year'] = $result['day']; - $result['day'] = $temp; - $result['fixed'] = 2; + if ((isset($result['day']) && isset($result['year'])) && $result['day'] > 31) { + if ($options['fix_date'] !== true) { + self::_setEncoding($oenc); + require_once 'Zend/Locale/Exception.php'; + throw new Zend_Locale_Exception("Unable to parse date '$date' using '" + . $format . "' (d <> y)"); } + $temp = $result['year']; + $result['year'] = $result['day']; + $result['day'] = $temp; + $result['fixed'] = 2; } // fix switched values M <> y - if (isset($result['month']) and isset($result['year'])) { - if ($result['month'] > 31) { - if ($options['fix_date'] !== true) { - self::_setEncoding($oenc); - require_once 'Zend/Locale/Exception.php'; - throw new Zend_Locale_Exception("Unable to parse date '$date' using '" - . $format . "' (M <> y)"); - } - $temp = $result['year']; - $result['year'] = $result['month']; - $result['month'] = $temp; - $result['fixed'] = 3; + if ((isset($result['month']) && isset($result['year'])) && $result['month'] > 31) { + if ($options['fix_date'] !== true) { + self::_setEncoding($oenc); + require_once 'Zend/Locale/Exception.php'; + throw new Zend_Locale_Exception("Unable to parse date '$date' using '" + . $format . "' (M <> y)"); } + $temp = $result['year']; + $result['year'] = $result['month']; + $result['month'] = $temp; + $result['fixed'] = 3; } // fix switched values M <> d - if (isset($result['month']) and isset($result['day'])) { - if ($result['month'] > 12) { - if ($options['fix_date'] !== true || $result['month'] > 31) { - self::_setEncoding($oenc); - require_once 'Zend/Locale/Exception.php'; - throw new Zend_Locale_Exception("Unable to parse date '$date' using '" - . $format . "' (M <> d)"); - } - $temp = $result['day']; - $result['day'] = $result['month']; - $result['month'] = $temp; - $result['fixed'] = 4; + if ((isset($result['month']) && isset($result['day'])) && $result['month'] > 12) { + if ($options['fix_date'] !== true || $result['month'] > 31) { + self::_setEncoding($oenc); + require_once 'Zend/Locale/Exception.php'; + throw new Zend_Locale_Exception("Unable to parse date '$date' using '" + . $format . "' (M <> d)"); } + $temp = $result['day']; + $result['day'] = $result['month']; + $result['month'] = $temp; + $result['fixed'] = 4; } } - if (isset($result['year'])) { - if (((iconv_strlen($result['year']) == 2) && ($result['year'] < 10)) || - (((iconv_strpos($format, 'yy') !== false) && (iconv_strpos($format, 'yyyy') === false)) || - ((iconv_strpos($format, 'YY') !== false) && (iconv_strpos($format, 'YYYY') === false)))) { - if (($result['year'] >= 0) && ($result['year'] < 100)) { - if ($result['year'] < 70) { - $result['year'] = (int) $result['year'] + 100; - } - - $result['year'] = (int) $result['year'] + 1900; - } + if (isset($result['year']) && (((iconv_strlen($result['year']) == 2) && ($result['year'] < 10)) || + (((iconv_strpos($format, 'yy') !== false) && (iconv_strpos($format, 'yyyy') === false)) || + ((iconv_strpos($format, 'YY') !== false) && (iconv_strpos($format, 'YYYY') === false)))) && (($result['year'] >= 0) && ($result['year'] < 100))) { + if ($result['year'] < 70) { + $result['year'] = (int) $result['year'] + 100; } + $result['year'] = (int) $result['year'] + 1900; } self::_setEncoding($oenc); @@ -1186,34 +1142,32 @@ public static function checkDateFormat($date, array $options = array()) $options = self::_checkOptions($options) + self::$_options; // day expected but not parsed - if ((iconv_strpos($options['date_format'], 'd', 0, 'UTF-8') !== false) and (!isset($date['day']) or ($date['day'] === ""))) { + if (iconv_strpos($options['date_format'], 'd', 0, 'UTF-8') !== false && (!isset($date['day']) || $date['day'] === "")) { return false; } // month expected but not parsed - if ((iconv_strpos($options['date_format'], 'M', 0, 'UTF-8') !== false) and (!isset($date['month']) or ($date['month'] === ""))) { + if (iconv_strpos($options['date_format'], 'M', 0, 'UTF-8') !== false && (!isset($date['month']) || $date['month'] === "")) { return false; } // year expected but not parsed - if (((iconv_strpos($options['date_format'], 'Y', 0, 'UTF-8') !== false) or - (iconv_strpos($options['date_format'], 'y', 0, 'UTF-8') !== false)) and (!isset($date['year']) or ($date['year'] === ""))) { + if ((iconv_strpos($options['date_format'], 'Y', 0, 'UTF-8') !== false || iconv_strpos($options['date_format'], 'y', 0, 'UTF-8') !== false) && (!isset($date['year']) || $date['year'] === "")) { return false; } // second expected but not parsed - if ((iconv_strpos($options['date_format'], 's', 0, 'UTF-8') !== false) and (!isset($date['second']) or ($date['second'] === ""))) { + if (iconv_strpos($options['date_format'], 's', 0, 'UTF-8') !== false && (!isset($date['second']) || $date['second'] === "")) { return false; } // minute expected but not parsed - if ((iconv_strpos($options['date_format'], 'm', 0, 'UTF-8') !== false) and (!isset($date['minute']) or ($date['minute'] === ""))) { + if (iconv_strpos($options['date_format'], 'm', 0, 'UTF-8') !== false && (!isset($date['minute']) || $date['minute'] === "")) { return false; } // hour expected but not parsed - if (((iconv_strpos($options['date_format'], 'H', 0, 'UTF-8') !== false) or - (iconv_strpos($options['date_format'], 'h', 0, 'UTF-8') !== false)) and (!isset($date['hour']) or ($date['hour'] === ""))) { + if ((iconv_strpos($options['date_format'], 'H', 0, 'UTF-8') !== false || iconv_strpos($options['date_format'], 'h', 0, 'UTF-8') !== false) && (!isset($date['hour']) || $date['hour'] === "")) { return false; } @@ -1306,7 +1260,7 @@ public static function getDateTime($datetime, array $options = array()) */ protected static function _getUniCodeSupport() { - return (@preg_match('/\pL/u', 'a')) ? true : false; + return (bool) @preg_match('/\pL/u', 'a'); } /** @@ -1317,11 +1271,9 @@ protected static function _getUniCodeSupport() */ protected static function _getEncoding() { - $oenc = PHP_VERSION_ID < 50600 + return PHP_VERSION_ID < 50600 ? iconv_get_encoding('internal_encoding') : ini_get('default_charset'); - - return $oenc; } /** diff --git a/library/Zend/Locale/Math.php b/library/Zend/Locale/Math.php index b521690571..b1ba7bf940 100644 --- a/library/Zend/Locale/Math.php +++ b/library/Zend/Locale/Math.php @@ -177,7 +177,7 @@ public static function normalize($value) $value = str_replace($convert['thousands_sep'], "",(string) $value); $value = str_replace($convert['positive_sign'], "", $value); $value = str_replace($convert['decimal_point'], ".",$value); - if (!empty($convert['negative_sign']) and (strpos($value, $convert['negative_sign']))) { + if (!empty($convert['negative_sign']) && strpos($value, $convert['negative_sign'])) { $value = str_replace($convert['negative_sign'], "", $value); $value = "-" . $value; } @@ -196,7 +196,7 @@ public static function localize($value) { $convert = localeconv(); $value = str_replace(".", $convert['decimal_point'], (string) $value); - if (!empty($convert['negative_sign']) and (strpos($value, "-"))) { + if (!empty($convert['negative_sign']) && strpos($value, "-")) { $value = str_replace("-", $convert['negative_sign'], $value); } return $value; diff --git a/library/Zend/Locale/Math/PhpMath.php b/library/Zend/Locale/Math/PhpMath.php index c06f20d1f7..cdea7f7ab4 100644 --- a/library/Zend/Locale/Math/PhpMath.php +++ b/library/Zend/Locale/Math/PhpMath.php @@ -69,7 +69,7 @@ public static function Add($op1, $op2, $scale = null) $op1 = self::normalize($op1); $op2 = self::normalize($op2); $result = $op1 + $op2; - if (is_infinite($result) or (abs($result - $op2 - $op1) > $precision)) { + if (is_infinite($result) || abs($result - $op2 - $op1) > $precision) { require_once 'Zend/Locale/Math/Exception.php'; throw new Zend_Locale_Math_Exception("addition overflow: $op1 + $op2 != $result", $op1, $op2, $result); } @@ -92,7 +92,7 @@ public static function Sub($op1, $op2, $scale = null) $op1 = self::normalize($op1); $op2 = self::normalize($op2); $result = $op1 - $op2; - if (is_infinite($result) or (abs($result + $op2 - $op1) > $precision)) { + if (is_infinite($result) || abs($result + $op2 - $op1) > $precision) { require_once 'Zend/Locale/Math/Exception.php'; throw new Zend_Locale_Math_Exception("subtraction overflow: $op1 - $op2 != $result", $op1, $op2, $result); } @@ -114,7 +114,7 @@ public static function Pow($op1, $op2, $scale = null) $op2 = ($op2 > 0) ? floor($op2) : ceil($op2); $result = pow($op1, $op2); - if (is_infinite($result) or is_nan($result)) { + if (is_infinite($result) || is_nan($result)) { require_once 'Zend/Locale/Math/Exception.php'; throw new Zend_Locale_Math_Exception("power overflow: $op1 ^ $op2", $op1, $op2, $result); } @@ -134,7 +134,7 @@ public static function Mul($op1, $op2, $scale = null) $op1 = self::normalize($op1); $op2 = self::normalize($op2); $result = $op1 * $op2; - if (is_infinite($result) or is_nan($result)) { + if (is_infinite($result) || is_nan($result)) { require_once 'Zend/Locale/Math/Exception.php'; throw new Zend_Locale_Math_Exception("multiplication overflow: $op1 * $op2 != $result", $op1, $op2, $result); } @@ -158,7 +158,7 @@ public static function Div($op1, $op2, $scale = null) $op1 = self::normalize($op1); $op2 = self::normalize($op2); $result = $op1 / $op2; - if (is_infinite($result) or is_nan($result)) { + if (is_infinite($result) || is_nan($result)) { require_once 'Zend/Locale/Math/Exception.php'; throw new Zend_Locale_Math_Exception("division overflow: $op1 / $op2 != $result", $op1, $op2, $result); } @@ -198,7 +198,7 @@ public static function Mod($op1, $op2) return NULL; } $result = $op1 % $op2; - if (is_nan($result) or (($op1 - $result) % $op2 != 0)) { + if (is_nan($result) || ($op1 - $result) % $op2 != 0) { require_once 'Zend/Locale/Math/Exception.php'; throw new Zend_Locale_Math_Exception("modulus calculation error: $op1 % $op2 != $result", $op1, $op2, $result); } @@ -217,7 +217,7 @@ public static function Comp($op1, $op2, $scale = null) } $op1 = self::normalize($op1); $op2 = self::normalize($op2); - if ($scale <> 0) { + if ($scale != 0) { $op1 = self::round($op1, $scale); $op2 = self::round($op2, $scale); } else { @@ -226,7 +226,7 @@ public static function Comp($op1, $op2, $scale = null) } if ($op1 > $op2) { return 1; - } else if ($op1 < $op2) { + } elseif ($op1 < $op2) { return -1; } return 0; diff --git a/library/Zend/Log.php b/library/Zend/Log.php index df2135969b..f74c389853 100644 --- a/library/Zend/Log.php +++ b/library/Zend/Log.php @@ -328,7 +328,7 @@ protected function getClassName($config, $type, $defaultNamespace) } // empty namespace given? - if (strlen((string) $namespace) === 0) { + if ((string) $namespace === '') { return $className; } @@ -479,7 +479,7 @@ public function addPriority($name, $priority) $name = strtoupper($name); if (isset($this->_priorities[$priority]) - || false !== array_search($name, $this->_priorities)) { + || in_array($name, $this->_priorities)) { /** @see Zend_Log_Exception */ require_once 'Zend/Log/Exception.php'; throw new Zend_Log_Exception('Existing priorities cannot be overwritten'); @@ -536,8 +536,7 @@ public function addWriter($writer) /** @see Zend_Log_Exception */ require_once 'Zend/Log/Exception.php'; throw new Zend_Log_Exception( - 'Writer must be an instance of Zend_Log_Writer_Abstract' - . ' or you should pass a configuration array' + 'Writer must be an instance of Zend_Log_Writer_Abstract or you should pass a configuration array' ); } @@ -580,7 +579,9 @@ public function registerErrorHandler() return $this; } - $this->_origErrorHandler = set_error_handler(array($this, 'errorHandler')); + $this->_origErrorHandler = set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline, array $errcontext) : bool { + return $this->errorHandler($errno, $errstr, $errfile, $errline, $errcontext); + }); // Contruct a default map of phpErrors to Zend_Log priorities. // Some of the errors are uncatchable, but are included for completeness @@ -623,12 +624,8 @@ public function errorHandler($errno, $errstr, $errfile, $errline, $errcontext) { $errorLevel = error_reporting(); - if ($errorLevel & $errno) { - if (isset($this->_errorHandlerMap[$errno])) { - $priority = $this->_errorHandlerMap[$errno]; - } else { - $priority = Zend_Log::INFO; - } + if (($errorLevel & $errno) !== 0) { + $priority = isset($this->_errorHandlerMap[$errno]) ? $this->_errorHandlerMap[$errno] : Zend_Log::INFO; $this->log($errstr, $priority, array('errno'=>$errno, 'file'=>$errfile, 'line'=>$errline, 'context'=>$errcontext)); } diff --git a/library/Zend/Log/Formatter/Simple.php b/library/Zend/Log/Formatter/Simple.php index 965fa762a0..c12e39efa0 100644 --- a/library/Zend/Log/Formatter/Simple.php +++ b/library/Zend/Log/Formatter/Simple.php @@ -100,7 +100,9 @@ public function format($event) $value = gettype($value); } - $output = str_replace("%$name%", $value, $output); + if (null !== $value) { + $output = str_replace("%$name%", $value, $output); + } } return $output; diff --git a/library/Zend/Log/Formatter/Xml.php b/library/Zend/Log/Formatter/Xml.php index 71c47d336f..d569219090 100644 --- a/library/Zend/Log/Formatter/Xml.php +++ b/library/Zend/Log/Formatter/Xml.php @@ -66,11 +66,11 @@ public function __construct($options = array()) 'rootElement' => array_shift($args) ); - if (count($args)) { + if ($args !== []) { $options['elementMap'] = array_shift($args); } - if (count($args)) { + if ($args !== []) { $options['encoding'] = array_shift($args); } } diff --git a/library/Zend/Log/Writer/Mail.php b/library/Zend/Log/Writer/Mail.php index 931dfe97bc..fb506d8bc5 100644 --- a/library/Zend/Log/Writer/Mail.php +++ b/library/Zend/Log/Writer/Mail.php @@ -207,7 +207,7 @@ protected static function _constructMailFromConfig(array $config) } $headerAddresses = array_intersect_key($config, self::$_methodMapHeaders); - if (count($headerAddresses)) { + if ($headerAddresses !== []) { foreach ($headerAddresses as $header => $address) { $method = self::$_methodMapHeaders[$header]; if (is_array($address) && isset($address['name']) @@ -217,11 +217,7 @@ protected static function _constructMailFromConfig(array $config) $address['email'], $address['name'] ); - } else if (is_array($address) && isset($address['email'])) { - $params = array($address['email']); - } else { - $params = array($address); - } + } else $params = is_array($address) && isset($address['email']) ? array($address['email']) : array($address); call_user_func_array(array($mail, $method), $params); } } @@ -279,12 +275,7 @@ protected function _write($event) // layout if one exists. Otherwise, just use the event with its // default format. if ($this->_layout) { - if ($this->_layoutFormatter) { - $this->_layoutEventsToMail[] = - $this->_layoutFormatter->format($event); - } else { - $this->_layoutEventsToMail[] = $formattedEvent; - } + $this->_layoutEventsToMail[] = $this->_layoutFormatter ? $this->_layoutFormatter->format($event) : $formattedEvent; } } @@ -314,8 +305,7 @@ public function setLayoutFormatter(Zend_Log_Formatter_Interface $formatter) { if (!$this->_layout) { throw new Zend_Log_Exception( - 'cannot set formatter for layout; ' . - 'a Zend_Layout instance is not in use'); + 'cannot set formatter for layout; a Zend_Layout instance is not in use'); } $this->_layoutFormatter = $formatter; @@ -337,10 +327,9 @@ public function setLayoutFormatter(Zend_Log_Formatter_Interface $formatter) */ public function setSubjectPrependText($subject) { - if ($this->_mail->getSubject()) { + if ($this->_mail->getSubject() !== '' && $this->_mail->getSubject() !== '0') { throw new Zend_Log_Exception( - 'subject already set on mail; ' . - 'cannot set subject prepend text'); + 'subject already set on mail; cannot set subject prepend text'); } $this->_subjectPrependText = (string) $subject; diff --git a/library/Zend/Log/Writer/Syslog.php b/library/Zend/Log/Writer/Syslog.php index 66dfeaabf9..ece0aabdc4 100644 --- a/library/Zend/Log/Writer/Syslog.php +++ b/library/Zend/Log/Writer/Syslog.php @@ -190,7 +190,7 @@ public function setFacility($facility) return $this; } - if (!count($this->_validFacilities)) { + if ($this->_validFacilities === []) { $this->_initializeValidFacilities(); } diff --git a/library/Zend/Mail.php b/library/Zend/Mail.php index 264d9790b6..fc8b1808b1 100644 --- a/library/Zend/Mail.php +++ b/library/Zend/Mail.php @@ -501,7 +501,7 @@ public function getPartCount() */ protected function _encodeHeader($value) { - if (Zend_Mime::isPrintable($value) === false) { + if (!Zend_Mime::isPrintable($value)) { if ($this->getHeaderEncoding() === Zend_Mime::ENCODING_QUOTEDPRINTABLE) { $value = Zend_Mime::encodeQuotedPrintableHeader($value, $this->getCharset(), Zend_Mime::LINELENGTH, Zend_Mime::LINEEND); } else { @@ -977,20 +977,19 @@ public function setDate($date = null) if ($this->_date === null) { if ($date === null) { $date = date('r'); - } else if (is_int($date)) { + } elseif (is_int($date)) { $date = date('r', $date); - } else if (is_string($date)) { + } elseif (is_string($date)) { $date = strtotime($date); if ($date === false || $date < 0) { /** * @see Zend_Mail_Exception */ require_once 'Zend/Mail/Exception.php'; - throw new Zend_Mail_Exception('String representations of Date Header must be ' . - 'strtotime()-compatible'); + throw new Zend_Mail_Exception('String representations of Date Header must be strtotime()-compatible'); } $date = date('r', $date); - } else if ($date instanceof Zend_Date) { + } elseif ($date instanceof Zend_Date) { $date = $date->get(Zend_Date::RFC_2822); } else { /** @@ -1112,17 +1111,9 @@ public function createMessageId() { $rand = mt_rand(); - if ($this->_recipients !== array()) { - $recipient = array_rand($this->_recipients); - } else { - $recipient = 'unknown'; - } + $recipient = $this->_recipients !== array() ? array_rand($this->_recipients) : 'unknown'; - if (isset($_SERVER["SERVER_NAME"])) { - $hostName = $_SERVER["SERVER_NAME"]; - } else { - $hostName = php_uname('n'); - } + $hostName = isset($_SERVER["SERVER_NAME"]) ? $_SERVER["SERVER_NAME"] : php_uname('n'); return sha1($time . $user . $rand . $recipient) . '@' . $hostName; } @@ -1271,11 +1262,7 @@ protected function _formatAddress($email, $name) return $email; } else { $encodedName = $this->_encodeHeader($name); - if ($encodedName === $name && strcspn($name, '()<>[]:;@\\,.') != strlen($name)) { - $format = '"%s" <%s>'; - } else { - $format = '%s <%s>'; - } + $format = $encodedName === $name && strcspn($name, '()<>[]:;@\\,.') != strlen($name) ? '"%s" <%s>' : '%s <%s>'; return sprintf($format, $encodedName, $email); } } diff --git a/library/Zend/Mail/Part.php b/library/Zend/Mail/Part.php index ca881a791e..a3f66391df 100644 --- a/library/Zend/Mail/Part.php +++ b/library/Zend/Mail/Part.php @@ -145,18 +145,15 @@ public function __construct(array $params) if (isset($params['raw'])) { Zend_Mime_Decode::splitMessage($params['raw'], $this->_headers, $this->_content, "\r\n"); - } else if (isset($params['headers'])) { + } elseif (isset($params['headers'])) { if (is_array($params['headers'])) { $this->_headers = $params['headers']; $this->_validateHeaders($this->_headers); + } elseif (!empty($params['noToplines'])) { + Zend_Mime_Decode::splitMessage($params['headers'], $this->_headers, $null, "\r\n"); } else { - if (!empty($params['noToplines'])) { - Zend_Mime_Decode::splitMessage($params['headers'], $this->_headers, $null, "\r\n"); - } else { - Zend_Mime_Decode::splitMessage($params['headers'], $this->_headers, $this->_topLines, "\r\n"); - } + Zend_Mime_Decode::splitMessage($params['headers'], $this->_headers, $this->_topLines, "\r\n"); } - if (isset($params['content'])) { $this->_content = $params['content']; } @@ -195,7 +192,7 @@ public function setPartClass($class) */ public function getPartClass() { - if ( !$this->_partClass ) { + if ( $this->_partClass === '' || $this->_partClass === '0' ) { $this->_partClass = __CLASS__; } return $this->_partClass; @@ -230,7 +227,7 @@ public function getContent() return $this->_content; } - if ($this->_mail) { + if ($this->_mail !== null) { return $this->_mail->getRawContent($this->_messageNum); } else { /** @@ -341,7 +338,7 @@ public function countParts() } $this->_countParts = count($this->_parts); - if ($this->_countParts) { + if ($this->_countParts !== 0) { return $this->_countParts; } @@ -368,7 +365,7 @@ public function countParts() public function getHeaders() { if ($this->_headers === null) { - if (!$this->_mail) { + if ($this->_mail === null) { $this->_headers = array(); } else { $part = $this->_mail->getRawHeader($this->_messageNum); diff --git a/library/Zend/Mail/Part/File.php b/library/Zend/Mail/Part/File.php index 8c1c99b41c..3866b6f1e8 100644 --- a/library/Zend/Mail/Part/File.php +++ b/library/Zend/Mail/Part/File.php @@ -64,11 +64,7 @@ public function __construct(array $params) throw new Zend_Mail_Exception('no file given in params'); } - if (!is_resource($params['file'])) { - $this->_fh = fopen($params['file'], 'r'); - } else { - $this->_fh = $params['file']; - } + $this->_fh = is_resource($params['file']) ? $params['file'] : fopen($params['file'], 'r'); if (!$this->_fh) { /** * @see Zend_Mail_Exception @@ -134,7 +130,7 @@ public function __construct(array $params) $this->_partPos[] = $part; } $part = array($pos); - } else if ($line == '--' . $boundary . '--') { + } elseif ($line === '--' . $boundary . '--') { $part[1] = $lastPos; $this->_partPos[] = $part; break; diff --git a/library/Zend/Mail/Protocol/Abstract.php b/library/Zend/Mail/Protocol/Abstract.php index ef90b09688..1f1a6c34dd 100644 --- a/library/Zend/Mail/Protocol/Abstract.php +++ b/library/Zend/Mail/Protocol/Abstract.php @@ -142,7 +142,7 @@ public function __construct($host = '127.0.0.1', $port = null) * @see Zend_Mail_Protocol_Exception */ require_once 'Zend/Mail/Protocol/Exception.php'; - throw new Zend_Mail_Protocol_Exception(join(', ', $this->_validHost->getMessages())); + throw new Zend_Mail_Protocol_Exception(implode(', ', $this->_validHost->getMessages())); } $this->_host = $host; @@ -277,7 +277,7 @@ protected function _connect($remote) throw new Zend_Mail_Protocol_Exception($errorStr); } - if (($result = $this->_setStreamTimeout(self::TIMEOUT_CONNECTION)) === false) { + if (!($result = $this->_setStreamTimeout(self::TIMEOUT_CONNECTION))) { /** * @see Zend_Mail_Protocol_Exception */ diff --git a/library/Zend/Mail/Protocol/Imap.php b/library/Zend/Mail/Protocol/Imap.php index b56c92b0cd..4be1bfd6d6 100644 --- a/library/Zend/Mail/Protocol/Imap.php +++ b/library/Zend/Mail/Protocol/Imap.php @@ -57,7 +57,7 @@ class Zend_Mail_Protocol_Imap */ function __construct($host = '', $port = null, $ssl = false) { - if ($host) { + if ($host !== '' && $host !== '0') { $this->connect($host, $port, $ssl); } } @@ -204,16 +204,14 @@ protected function _decodeLine($line) while (($pos = strpos($line, ' ')) !== false) { $token = substr($line, 0, $pos); while ($token[0] == '(') { - array_push($stack, $tokens); + $stack[] = $tokens; $tokens = array(); $token = substr($token, 1); } - if ($token[0] == '"') { - if (preg_match('%^\(*"((.|\\\\|\\")*?)" *%', $line, $matches)) { - $tokens[] = $matches[1]; - $line = substr($line, strlen((string) $matches[0])); - continue; - } + if ($token[0] == '"' && preg_match('%^\(*"((.|\\\\|\\")*?)" *%', $line, $matches)) { + $tokens[] = $matches[1]; + $line = substr($line, strlen((string) $matches[0])); + continue; } if ($token[0] == '{') { $endPos = strpos($token, '}'); @@ -283,11 +281,7 @@ protected function _decodeLine($line) public function readLine(&$tokens = array(), $wantedTag = '*', $dontParse = false) { $line = $this->_nextTaggedLine($tag); - if (!$dontParse) { - $tokens = $this->_decodeLine($line); - } else { - $tokens = $line; - } + $tokens = $dontParse ? $line : $this->_decodeLine($line); // if tag is wanted tag we might be at the end of a multiline response return $tag == $wantedTag; @@ -317,8 +311,8 @@ public function readResponse($tag, $dontParse = false) } // last line has response code if ($tokens[0] == 'OK') { - return $lines ? $lines : true; - } else if ($tokens[0] == 'NO'){ + return $lines !== [] ? $lines : true; + } elseif ($tokens[0] == 'NO') { return false; } return null; @@ -344,7 +338,7 @@ public function sendRequest($command, $tokens = array(), &$tag = null) foreach ($tokens as $token) { if (is_array($token)) { - if (@fputs($this->_socket, $line . ' ' . $token[0] . "\r\n") === false) { + if (@fwrite($this->_socket, $line . ' ' . $token[0] . "\r\n") === false) { /** * @see Zend_Mail_Protocol_Exception */ @@ -364,7 +358,7 @@ public function sendRequest($command, $tokens = array(), &$tag = null) } } - if (@fputs($this->_socket, $line . "\r\n") === false) { + if (@fwrite($this->_socket, $line . "\r\n") === false) { /** * @see Zend_Mail_Protocol_Exception */ @@ -385,9 +379,8 @@ public function sendRequest($command, $tokens = array(), &$tag = null) public function requestAndResponse($command, $tokens = array(), $dontParse = false) { $this->sendRequest($command, $tokens, $tag); - $response = $this->readResponse($tag, $dontParse); - return $response; + return $this->readResponse($tag, $dontParse); } /** @@ -570,13 +563,9 @@ public function fetch($items, $from, $to = null) { if (is_array($from)) { $set = implode(',', $from); - } else if ($to === null) { + } elseif ($to === null) { $set = (int)$from; - } else if ($to === INF) { - $set = (int)$from . ':*'; - } else { - $set = (int)$from . ':' . (int)$to; - } + } else $set = $to === INF ? (int)$from . ':*' : (int)$from . ':' . (int)$to; $items = (array)$items; $itemList = $this->escapeList($items); @@ -695,7 +684,7 @@ public function store(array $flags, $from, $to = null, $mode = null, $silent = t $result = $this->requestAndResponse('STORE', array($set, $item, $flags), $silent); if ($silent) { - return $result ? true : false; + return (bool) $result; } $tokens = $result; diff --git a/library/Zend/Mail/Protocol/Pop3.php b/library/Zend/Mail/Protocol/Pop3.php index 9a76228792..0b099892ee 100644 --- a/library/Zend/Mail/Protocol/Pop3.php +++ b/library/Zend/Mail/Protocol/Pop3.php @@ -64,7 +64,7 @@ class Zend_Mail_Protocol_Pop3 */ public function __construct($host = '', $port = null, $ssl = false) { - if ($host) { + if ($host !== '' && $host !== '0') { $this->connect($host, $port, $ssl); } } @@ -114,11 +114,7 @@ public function connect($host, $port = null, $ssl = false) strtok($welcome, '<'); $this->_timestamp = strtok('>'); - if (!strpos($this->_timestamp, '@')) { - $this->_timestamp = null; - } else { - $this->_timestamp = '<' . $this->_timestamp . '>'; - } + $this->_timestamp = strpos($this->_timestamp, '@') ? '<' . $this->_timestamp . '>' : null; if ($ssl === 'TLS') { $this->request('STLS'); @@ -145,7 +141,7 @@ public function connect($host, $port = null, $ssl = false) */ public function sendRequest($request) { - $result = @fputs($this->_socket, $request . "\r\n"); + $result = @fwrite($this->_socket, $request . "\r\n"); if (!$result) { /** * @see Zend_Mail_Protocol_Exception @@ -351,7 +347,7 @@ public function uniqueid($msgno = null) $result = explode("\n", $result); $messages = array(); foreach ($result as $line) { - if (!$line) { + if ($line === '' || $line === '0') { continue; } list($no, $id) = explode(' ', trim($line), 2); @@ -431,8 +427,7 @@ public function retrive($msgno) */ public function retrieve($msgno) { - $result = $this->request("RETR $msgno", true); - return $result; + return $this->request("RETR $msgno", true); } /** diff --git a/library/Zend/Mail/Protocol/Smtp.php b/library/Zend/Mail/Protocol/Smtp.php index bbb0850bca..5619b216a2 100644 --- a/library/Zend/Mail/Protocol/Smtp.php +++ b/library/Zend/Mail/Protocol/Smtp.php @@ -147,10 +147,8 @@ public function __construct($host = '127.0.0.1', $port = null, array $config = a } // If no port has been specified then check the master PHP ini file. Defaults to 25 if the ini setting is null. - if ($port == null) { - if (($port = ini_get('smtp_port')) == '') { - $port = 25; - } + if ($port == null && ($port = ini_get('smtp_port')) == '') { + $port = 25; } parent::__construct($host, $port); @@ -178,7 +176,7 @@ public function connect() public function helo($host = '127.0.0.1') { // Respect RFC 2821 and disallow HELO attempts if session is already initiated. - if ($this->_sess === true) { + if ($this->_sess) { /** * @see Zend_Mail_Protocol_Exception */ @@ -192,7 +190,7 @@ public function helo($host = '127.0.0.1') * @see Zend_Mail_Protocol_Exception */ require_once 'Zend/Mail/Protocol/Exception.php'; - throw new Zend_Mail_Protocol_Exception(join(', ', $this->_validHost->getMessages())); + throw new Zend_Mail_Protocol_Exception(implode(', ', $this->_validHost->getMessages())); } // Initiate helo sequence @@ -249,7 +247,7 @@ protected function _ehlo($host) */ public function mail($from) { - if ($this->_sess !== true) { + if (!$this->_sess) { /** * @see Zend_Mail_Protocol_Exception */ diff --git a/library/Zend/Mail/Protocol/Smtp/Auth/Crammd5.php b/library/Zend/Mail/Protocol/Smtp/Auth/Crammd5.php index ea9ad7f305..fd82dfe55d 100644 --- a/library/Zend/Mail/Protocol/Smtp/Auth/Crammd5.php +++ b/library/Zend/Mail/Protocol/Smtp/Auth/Crammd5.php @@ -38,6 +38,14 @@ */ class Zend_Mail_Protocol_Smtp_Auth_Crammd5 extends Zend_Mail_Protocol_Smtp { + /** + * @var mixed + */ + public $_username; + /** + * @var mixed + */ + public $_password; /** * Constructor. * @@ -101,8 +109,7 @@ protected function _hmacMd5($key, $data, $block = 64) $k_opad = substr($key, 0, 64) ^ str_repeat(chr(0x5C), 64); $inner = pack('H32', md5($k_ipad . $data)); - $digest = md5($k_opad . $inner); - return $digest; + return md5($k_opad . $inner); } } diff --git a/library/Zend/Mail/Storage/Folder.php b/library/Zend/Mail/Storage/Folder.php index 191dbca203..bce6a04977 100644 --- a/library/Zend/Mail/Storage/Folder.php +++ b/library/Zend/Mail/Storage/Folder.php @@ -65,7 +65,7 @@ class Zend_Mail_Storage_Folder implements RecursiveIterator public function __construct($localName, $globalName = '', $selectable = true, array $folders = array()) { $this->_localName = $localName; - $this->_globalName = $globalName ? $globalName : $localName; + $this->_globalName = $globalName !== '' && $globalName !== '0' ? $globalName : $localName; $this->_selectable = $selectable; $this->_folders = $folders; } diff --git a/library/Zend/Mail/Storage/Folder/Maildir.php b/library/Zend/Mail/Storage/Folder/Maildir.php index 23139ee56b..a4e673e277 100644 --- a/library/Zend/Mail/Storage/Folder/Maildir.php +++ b/library/Zend/Mail/Storage/Folder/Maildir.php @@ -86,7 +86,7 @@ public function __construct($params) $params = (object)$params; } - if (!isset($params->dirname) || !is_dir($params->dirname)) { + if (!(property_exists($params, 'dirname') && $params->dirname !== null) || !is_dir($params->dirname)) { /** * @see Zend_Mail_Storage_Exception */ @@ -96,10 +96,10 @@ public function __construct($params) $this->_rootdir = rtrim($params->dirname, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; - $this->_delim = isset($params->delim) ? $params->delim : '.'; + $this->_delim = property_exists($params, 'delim') && $params->delim !== null ? $params->delim : '.'; $this->_buildFolderTree(); - $this->selectFolder(!empty($params->folder) ? $params->folder : 'INBOX'); + $this->selectFolder(empty($params->folder) ? 'INBOX' : $params->folder); $this->_has['top'] = true; $this->_has['flags'] = true; } @@ -155,19 +155,19 @@ protected function _buildFolderTree() require_once 'Zend/Mail/Storage/Exception.php'; throw new Zend_Mail_Storage_Exception('error while reading maildir'); } - array_push($stack, $parent); + $stack[] = $parent; $parent = $dir . $this->_delim; $folder = new Zend_Mail_Storage_Folder($local, substr($dir, 1), true); $parentFolder->$local = $folder; - array_push($folderStack, $parentFolder); + $folderStack[] = $parentFolder; $parentFolder = $folder; break; - } else if ($stack) { + } elseif ($stack !== []) { $parent = array_pop($stack); $parentFolder = array_pop($folderStack); } } while ($stack); - if (!$stack) { + if ($stack === []) { /** * @see Zend_Mail_Storage_Exception */ @@ -242,7 +242,7 @@ public function selectFolder($globalName) throw new Zend_Mail_Storage_Exception("{$this->_currentFolder} is not selectable", 0, $e); } // seems like file has vanished; rebuilding folder tree - but it's still an exception - $this->_buildFolderTree($this->_rootdir); + $this->_buildFolderTree(); /** * @see Zend_Mail_Storage_Exception */ diff --git a/library/Zend/Mail/Storage/Folder/Mbox.php b/library/Zend/Mail/Storage/Folder/Mbox.php index ad9429dc33..8f8acb39cd 100644 --- a/library/Zend/Mail/Storage/Folder/Mbox.php +++ b/library/Zend/Mail/Storage/Folder/Mbox.php @@ -82,7 +82,7 @@ public function __construct($params) $params = (object)$params; } - if (isset($params->filename)) { + if (property_exists($params, 'filename') && $params->filename !== null) { /** * @see Zend_Mail_Storage_Exception */ @@ -90,7 +90,7 @@ public function __construct($params) throw new Zend_Mail_Storage_Exception('use Zend_Mail_Storage_Mbox for a single file'); } - if (!isset($params->dirname) || !is_dir($params->dirname)) { + if (!(property_exists($params, 'dirname') && $params->dirname !== null) || !is_dir($params->dirname)) { /** * @see Zend_Mail_Storage_Exception */ @@ -101,7 +101,7 @@ public function __construct($params) $this->_rootdir = rtrim($params->dirname, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $this->_buildFolderTree($this->_rootdir); - $this->selectFolder(!empty($params->folder) ? $params->folder : 'INBOX'); + $this->selectFolder(empty($params->folder) ? 'INBOX' : $params->folder); $this->_has['top'] = true; $this->_has['uniqueid'] = false; } @@ -120,7 +120,7 @@ public function __construct($params) */ protected function _buildFolderTree($currentDir, $parentFolder = null, $parentGlobalName = '') { - if (!$parentFolder) { + if ($parentFolder === null) { $this->_rootFolder = new Zend_Mail_Storage_Folder('/', '/', false); $parentFolder = $this->_rootFolder; } diff --git a/library/Zend/Mail/Storage/Imap.php b/library/Zend/Mail/Storage/Imap.php index 422ce53e73..75562501c5 100644 --- a/library/Zend/Mail/Storage/Imap.php +++ b/library/Zend/Mail/Storage/Imap.php @@ -114,7 +114,7 @@ class Zend_Mail_Storage_Imap extends Zend_Mail_Storage_Abstract */ public function countMessages($flags = null) { - if (!$this->_currentFolder) { + if ($this->_currentFolder === '' || $this->_currentFolder === '0') { /** * @see Zend_Mail_Storage_Exception */ @@ -147,7 +147,7 @@ public function countMessages($flags = null) */ public function getSize($id = 0) { - if ($id) { + if ($id !== 0) { return $this->_protocol->fetch('RFC822.SIZE', $id); } return $this->_protocol->fetch('RFC822.SIZE', 1, INF); @@ -258,7 +258,7 @@ public function __construct($params) return; } - if (!isset($params->user)) { + if (!(property_exists($params, 'user') && $params->user !== null)) { /** * @see Zend_Mail_Storage_Exception */ @@ -266,10 +266,10 @@ public function __construct($params) throw new Zend_Mail_Storage_Exception('need at least user in params'); } - $host = isset($params->host) ? $params->host : 'localhost'; - $password = isset($params->password) ? $params->password : ''; - $port = isset($params->port) ? $params->port : null; - $ssl = isset($params->ssl) ? $params->ssl : false; + $host = property_exists($params, 'host') && $params->host !== null ? $params->host : 'localhost'; + $password = property_exists($params, 'password') && $params->password !== null ? $params->password : ''; + $port = property_exists($params, 'port') && $params->port !== null ? $params->port : null; + $ssl = property_exists($params, 'ssl') && $params->ssl !== null ? $params->ssl : false; $this->_protocol = new Zend_Mail_Protocol_Imap(); $this->_protocol->connect($host, $port, $ssl); @@ -280,7 +280,7 @@ public function __construct($params) require_once 'Zend/Mail/Storage/Exception.php'; throw new Zend_Mail_Storage_Exception('cannot login, user or password wrong'); } - $this->selectFolder(isset($params->folder) ? $params->folder : 'INBOX'); + $this->selectFolder(property_exists($params, 'folder') && $params->folder !== null ? $params->folder : 'INBOX'); } /** @@ -397,7 +397,7 @@ public function getNumberByUniqueId($id) public function getFolders($rootFolder = null) { $folders = $this->_protocol->listMailbox((string)$rootFolder); - if (!$folders) { + if ($folders === []) { /** * @see Zend_Mail_Storage_Exception */ @@ -416,26 +416,21 @@ public function getFolders($rootFolder = null) do { if (!$parent || strpos($globalName, $parent) === 0) { $pos = strrpos($globalName, $data['delim']); - if ($pos === false) { - $localName = $globalName; - } else { - $localName = substr($globalName, $pos + 1); - } + $localName = $pos === false ? $globalName : substr($globalName, $pos + 1); $selectable = !$data['flags'] || !in_array('\\Noselect', $data['flags']); - - array_push($stack, $parent); + $stack[] = $parent; $parent = $globalName . $data['delim']; $folder = new Zend_Mail_Storage_Folder($localName, $globalName, $selectable); $parentFolder->$localName = $folder; - array_push($folderStack, $parentFolder); + $folderStack[] = $parentFolder; $parentFolder = $folder; break; - } else if ($stack) { + } elseif ($stack !== []) { $parent = array_pop($stack); $parentFolder = array_pop($folderStack); } } while ($stack); - if (!$stack) { + if ($stack === []) { /** * @see Zend_Mail_Storage_Exception */ @@ -498,11 +493,7 @@ public function createFolder($name, $parentFolder = null) // TODO: we assume / as the hierarchy delim - need to get that from the folder class! if ($parentFolder instanceof Zend_Mail_Storage_Folder) { $folder = $parentFolder->getGlobalName() . '/' . $name; - } else if ($parentFolder != null) { - $folder = $parentFolder . '/' . $name; - } else { - $folder = $name; - } + } else $folder = $parentFolder != null ? $parentFolder . '/' . $name : $name; if (!$this->_protocol->create($folder)) { /** diff --git a/library/Zend/Mail/Storage/Maildir.php b/library/Zend/Mail/Storage/Maildir.php index 76708e8564..f1223473ef 100644 --- a/library/Zend/Mail/Storage/Maildir.php +++ b/library/Zend/Mail/Storage/Maildir.php @@ -98,7 +98,7 @@ public function countMessages($flags = null) $flags = array_flip($flags); foreach ($this->_files as $file) { - foreach ($flags as $flag => $v) { + foreach (array_keys($flags) as $flag) { if (!isset($file['flaglookup'][$flag])) { continue 2; } @@ -209,7 +209,7 @@ public function getRawHeader($id, $part = null, $topLines = 0) $content = ''; while (!feof($fh)) { $line = fgets($fh); - if (!trim($line)) { + if (trim($line) === '' || trim($line) === '0') { break; } $content .= $line; @@ -266,7 +266,7 @@ public function __construct($params) $params = (object)$params; } - if (!isset($params->dirname) || !is_dir($params->dirname)) { + if (!(property_exists($params, 'dirname') && $params->dirname !== null) || !is_dir($params->dirname)) { /** * @see Zend_Mail_Storage_Exception */ @@ -332,7 +332,7 @@ protected function _openMaildir($dirname) if ($dh) { $this->_getMaildirFiles($dh, $dirname . '/new/', array(Zend_Mail_Storage::FLAG_RECENT)); closedir($dh); - } else if (file_exists($dirname . '/new/')) { + } elseif (file_exists($dirname . '/new/')) { /** * @see Zend_Mail_Storage_Exception */ diff --git a/library/Zend/Mail/Storage/Mbox.php b/library/Zend/Mail/Storage/Mbox.php index ddcc0fca68..d89abacf4c 100644 --- a/library/Zend/Mail/Storage/Mbox.php +++ b/library/Zend/Mail/Storage/Mbox.php @@ -153,7 +153,7 @@ public function getMessage($id) $message = $this->getRawHeader($id); // file pointer is after headers now - if ($bodyLines) { + if ($bodyLines !== 0) { $message .= "\n"; while ($bodyLines-- && ftell($this->_fh) < $this->_positions[$id - 1]['end']) { $message .= fgets($this->_fh); @@ -225,7 +225,7 @@ public function __construct($params) $params = (object)$params; } - if (!isset($params->filename) /* || Zend_Loader::isReadable($params['filename']) */) { + if (!(property_exists($params, 'filename') && $params->filename !== null) /* || Zend_Loader::isReadable($params['filename']) */) { /** * @see Zend_Mail_Storage_Exception */ diff --git a/library/Zend/Mail/Storage/Pop3.php b/library/Zend/Mail/Storage/Pop3.php index 234b546c4b..5eed1e5963 100644 --- a/library/Zend/Mail/Storage/Pop3.php +++ b/library/Zend/Mail/Storage/Pop3.php @@ -75,7 +75,7 @@ public function countMessages() */ public function getSize($id = 0) { - $id = $id ? $id : null; + $id = $id !== 0 ? $id : null; return $this->_protocol->getList($id); } @@ -173,7 +173,7 @@ public function __construct($params) return; } - if (!isset($params->user)) { + if (!(property_exists($params, 'user') && $params->user !== null)) { /** * @see Zend_Mail_Storage_Exception */ @@ -181,10 +181,10 @@ public function __construct($params) throw new Zend_Mail_Storage_Exception('need at least user in params'); } - $host = isset($params->host) ? $params->host : 'localhost'; - $password = isset($params->password) ? $params->password : ''; - $port = isset($params->port) ? $params->port : null; - $ssl = isset($params->ssl) ? $params->ssl : false; + $host = property_exists($params, 'host') && $params->host !== null ? $params->host : 'localhost'; + $password = property_exists($params, 'password') && $params->password !== null ? $params->password : ''; + $port = property_exists($params, 'port') && $params->port !== null ? $params->port : null; + $ssl = property_exists($params, 'ssl') && $params->ssl !== null ? $params->ssl : false; $this->_protocol = new Zend_Mail_Protocol_Pop3(); $this->_protocol->connect($host, $port, $ssl); @@ -319,7 +319,7 @@ public function __get($var) } catch(Zend_Mail_Exception $e) { // ignoring error } - $this->_has['uniqueid'] = $id ? true : false; + $this->_has['uniqueid'] = (bool) $id; return $this->_has['uniqueid']; } diff --git a/library/Zend/Mail/Storage/Writable/Maildir.php b/library/Zend/Mail/Storage/Writable/Maildir.php index f05ad43d49..c40360159f 100644 --- a/library/Zend/Mail/Storage/Writable/Maildir.php +++ b/library/Zend/Mail/Storage/Writable/Maildir.php @@ -69,33 +69,29 @@ public static function initMaildir($dir) require_once 'Zend/Mail/Storage/Exception.php'; throw new Zend_Mail_Storage_Exception('maildir must be a directory if already exists'); } - } else { - if (!mkdir($dir)) { - /** - * @see Zend_Mail_Storage_Exception - */ - require_once 'Zend/Mail/Storage/Exception.php'; - $dir = dirname($dir); - if (!file_exists($dir)) { - throw new Zend_Mail_Storage_Exception("parent $dir not found"); - } else if (!is_dir($dir)) { - throw new Zend_Mail_Storage_Exception("parent $dir not a directory"); - } else { - throw new Zend_Mail_Storage_Exception('cannot create maildir'); - } + } elseif (!mkdir($dir)) { + /** + * @see Zend_Mail_Storage_Exception + */ + require_once 'Zend/Mail/Storage/Exception.php'; + $dir = dirname($dir); + if (!file_exists($dir)) { + throw new Zend_Mail_Storage_Exception("parent $dir not found"); + } elseif (!is_dir($dir)) { + throw new Zend_Mail_Storage_Exception("parent $dir not a directory"); + } else { + throw new Zend_Mail_Storage_Exception('cannot create maildir'); } } foreach (array('cur', 'tmp', 'new') as $subdir) { - if (!@mkdir($dir . DIRECTORY_SEPARATOR . $subdir)) { - // ignore if dir exists (i.e. was already valid maildir or two processes try to create one) - if (!file_exists($dir . DIRECTORY_SEPARATOR . $subdir)) { - /** - * @see Zend_Mail_Storage_Exception - */ - require_once 'Zend/Mail/Storage/Exception.php'; - throw new Zend_Mail_Storage_Exception('could not create subdir ' . $subdir); - } + // ignore if dir exists (i.e. was already valid maildir or two processes try to create one) + if (!@mkdir($dir . DIRECTORY_SEPARATOR . $subdir) && !file_exists($dir . DIRECTORY_SEPARATOR . $subdir)) { + /** + * @see Zend_Mail_Storage_Exception + */ + require_once 'Zend/Mail/Storage/Exception.php'; + throw new Zend_Mail_Storage_Exception('could not create subdir ' . $subdir); } } } @@ -113,7 +109,7 @@ public function __construct($params) { $params = (object)$params; } - if (!empty($params->create) && isset($params->dirname) && !file_exists($params->dirname . DIRECTORY_SEPARATOR . 'cur')) { + if (!empty($params->create) && (property_exists($params, 'dirname') && $params->dirname !== null) && !file_exists($params->dirname . DIRECTORY_SEPARATOR . 'cur')) { self::initMaildir($params->dirname); } @@ -135,11 +131,7 @@ public function createFolder($name, $parentFolder = null) { if ($parentFolder instanceof Zend_Mail_Storage_Folder) { $folder = $parentFolder->getGlobalName() . $this->_delim . $name; - } else if ($parentFolder != null) { - $folder = rtrim($parentFolder, $this->_delim) . $this->_delim . $name; - } else { - $folder = $name; - } + } else $folder = $parentFolder != null ? rtrim($parentFolder, $this->_delim) . $this->_delim . $name : $name; $folder = trim($folder, $this->_delim); @@ -150,7 +142,7 @@ public function createFolder($name, $parentFolder = null) } catch (Zend_Mail_Exception $e) { // ok } - if ($exists) { + if ($exists !== null) { /** * @see Zend_Mail_Storage_Exception */ @@ -174,7 +166,7 @@ public function createFolder($name, $parentFolder = null) // check if we got tricked and would create a dir outside of the rootdir or not as direct child if (strpos($folder, DIRECTORY_SEPARATOR) !== false || strpos($folder, '/') !== false - || dirname($fulldir) . DIRECTORY_SEPARATOR != $this->_rootdir) { + || dirname($fulldir) . DIRECTORY_SEPARATOR !== $this->_rootdir) { /** * @see Zend_Mail_Storage_Exception */ @@ -287,14 +279,12 @@ public function removeFolder($name) } } closedir($dh); - if ($subdir !== '.') { - if (!rmdir($dir)) { - /** - * @see Zend_Mail_Storage_Exception - */ - require_once 'Zend/Mail/Storage/Exception.php'; - throw new Zend_Mail_Storage_Exception("error removing $subdir"); - } + if ($subdir !== '.' && !rmdir($dir)) { + /** + * @see Zend_Mail_Storage_Exception + */ + require_once 'Zend/Mail/Storage/Exception.php'; + throw new Zend_Mail_Storage_Exception("error removing $subdir"); } } @@ -310,7 +300,7 @@ public function removeFolder($name) $parent = strpos($name, $this->_delim) ? substr($name, 0, strrpos($name, $this->_delim)) : null; $localName = $parent ? substr($name, strlen($parent) + 1) : $name; - unset($this->getFolders($parent)->$localName); + unset($this->getFolders($parent)->getLocalName()); } /** @@ -437,14 +427,12 @@ protected function _createTmpFile($folder = 'INBOX') } else { $tmpdir = $this->_rootdir . '.' . $folder . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR; } - if (!file_exists($tmpdir)) { - if (!mkdir($tmpdir)) { - /** - * @see Zend_Mail_Storage_Exception - */ - require_once 'Zend/Mail/Storage/Exception.php'; - throw new Zend_Mail_Storage_Exception('problems creating tmp dir'); - } + if (!file_exists($tmpdir) && !mkdir($tmpdir)) { + /** + * @see Zend_Mail_Storage_Exception + */ + require_once 'Zend/Mail/Storage/Exception.php'; + throw new Zend_Mail_Storage_Exception('problems creating tmp dir'); } // we should retry to create a unique id if a file with the same name exists @@ -567,7 +555,7 @@ public function appendMessage($message, $folder = null, $flags = null, $recent = if (is_resource($message) && get_resource_type($message) == 'stream') { stream_copy_to_stream($message, $temp_file['handle']); } else { - fputs($temp_file['handle'], $message); + fwrite($temp_file['handle'], $message); } fclose($temp_file['handle']); @@ -592,7 +580,7 @@ public function appendMessage($message, $folder = null, $flags = null, $recent = } @unlink($temp_file['filename']); - if ($exception) { + if ($exception !== null) { throw $exception; } @@ -658,7 +646,7 @@ public function copyMessage($id, $folder) */ require_once 'Zend/Mail/Storage/Exception.php'; $exception = new Zend_Mail_Storage_Exception('cannot copy message file'); - } else if (!link($temp_file['filename'], $new_file)) { + } elseif (!link($temp_file['filename'], $new_file)) { /** * @see Zend_Mail_Storage_Exception */ @@ -667,11 +655,11 @@ public function copyMessage($id, $folder) } @unlink($temp_file['filename']); - if ($exception) { + if ($exception !== null) { throw $exception; } - if ($folder->getGlobalName() == $this->_currentFolder + if ($folder->getGlobalName() === $this->_currentFolder || ($this->_currentFolder == 'INBOX' && $folder->getGlobalName() == '/')) { $this->_files[] = array('uniq' => $temp_file['uniq'], 'flags' => $flags, @@ -696,7 +684,7 @@ public function moveMessage($id, $folder) { $folder = $this->getFolders($folder); } - if ($folder->getGlobalName() == $this->_currentFolder + if ($folder->getGlobalName() === $this->_currentFolder || ($this->_currentFolder == 'INBOX' && $folder->getGlobalName() == '/')) { /** * @see Zend_Mail_Storage_Exception @@ -739,7 +727,7 @@ public function moveMessage($id, $folder) { } @unlink($temp_file['filename']); - if ($exception) { + if ($exception !== null) { throw $exception; } @@ -880,11 +868,7 @@ protected function _calculateMaildirsize() { $folders = new RecursiveIteratorIterator($this->getFolders(), RecursiveIteratorIterator::SELF_FIRST); foreach ($folders as $folder) { $subdir = $folder->getGlobalName(); - if ($subdir == 'INBOX') { - $subdir = ''; - } else { - $subdir = '.' . $subdir; - } + $subdir = $subdir == 'INBOX' ? '' : '.' . $subdir; if ($subdir == 'Trash') { continue; } @@ -941,8 +925,8 @@ protected function _calculateMaildirsize() { $definition[] = $value . $type; } $definition = implode(',', $definition); - fputs($fh, "$definition\n"); - fputs($fh, "$total_size $messages\n"); + fwrite($fh, "$definition\n"); + fwrite($fh, "$total_size $messages\n"); fclose($fh); rename($tmp['filename'], $this->_rootdir . 'maildirsize'); foreach ($timestamps as $dir => $timestamp) { diff --git a/library/Zend/Mail/Transport/Abstract.php b/library/Zend/Mail/Transport/Abstract.php index f5eb181ff4..c3776b49e8 100644 --- a/library/Zend/Mail/Transport/Abstract.php +++ b/library/Zend/Mail/Transport/Abstract.php @@ -129,7 +129,7 @@ protected function _getHeaders($boundary) if (null !== $boundary) { // Build multipart mail $type = $this->_mail->getType(); - if (!$type) { + if ($type === '' || $type === '0') { if ($this->_mail->hasAttachments) { $type = Zend_Mime::MULTIPART_MIXED; } elseif ($this->_mail->getBodyText() && $this->_mail->getBodyHtml()) { diff --git a/library/Zend/Mail/Transport/File.php b/library/Zend/Mail/Transport/File.php index 2ca97627ad..eba288a080 100644 --- a/library/Zend/Mail/Transport/File.php +++ b/library/Zend/Mail/Transport/File.php @@ -72,7 +72,9 @@ public function __construct($options = null) $options['path'] = sys_get_temp_dir(); } if (!isset($options['callback'])) { - $options['callback'] = array($this, 'defaultCallback'); + $options['callback'] = function ($transport) : string { + return $this->defaultCallback($transport); + }; } $this->setOptions($options); diff --git a/library/Zend/Mail/Transport/Sendmail.php b/library/Zend/Mail/Transport/Sendmail.php index 28bf3b9813..b04814bbe0 100644 --- a/library/Zend/Mail/Transport/Sendmail.php +++ b/library/Zend/Mail/Transport/Sendmail.php @@ -98,7 +98,9 @@ public function __construct($parameters = null) public function _sendMail() { if ($this->parameters === null) { - set_error_handler(array($this, '_handleMailErrors')); + set_error_handler(function (int $errno, string $errstr, ?string $errfile = \null, ?string $errline = \null, ?array $errcontext = \null) : bool { + return $this->_handleMailErrors($errno, $errstr, $errfile, $errline, $errcontext); + }); $result = mail( $this->recipients, $this->_mail->getSubject(), @@ -119,7 +121,9 @@ public function _sendMail() ); } - set_error_handler(array($this, '_handleMailErrors')); + set_error_handler(function (int $errno, string $errstr, ?string $errfile = \null, ?string $errline = \null, ?array $errcontext = \null) : bool { + return $this->_handleMailErrors($errno, $errstr, $errfile, $errline, $errcontext); + }); $result = mail( $this->recipients, $this->_mail->getSubject(), diff --git a/library/Zend/Mail/Transport/Smtp.php b/library/Zend/Mail/Transport/Smtp.php index 2afe681eba..b3253c8708 100644 --- a/library/Zend/Mail/Transport/Smtp.php +++ b/library/Zend/Mail/Transport/Smtp.php @@ -188,7 +188,7 @@ public function _sendMail() if (!($this->_connection instanceof Zend_Mail_Protocol_Smtp)) { // Check if authentication is required and determine required class $connectionClass = 'Zend_Mail_Protocol_Smtp'; - if ($this->_auth) { + if ($this->_auth !== '' && $this->_auth !== '0') { $connectionClass .= '_Auth_' . ucwords($this->_auth); } if (!class_exists($connectionClass)) { diff --git a/library/Zend/Markup.php b/library/Zend/Markup.php index 3662f52a05..83578262ef 100644 --- a/library/Zend/Markup.php +++ b/library/Zend/Markup.php @@ -127,8 +127,7 @@ public static function factory($parser, $renderer = 'Html', array $options = arr $parser = new $parserClass(); $options['parser'] = $parser; - $renderer = new $rendererClass($options); - return $renderer; + return new $rendererClass($options); } } diff --git a/library/Zend/Markup/Parser/Bbcode.php b/library/Zend/Markup/Parser/Bbcode.php index 218dcb3f66..6d02e97f72 100644 --- a/library/Zend/Markup/Parser/Bbcode.php +++ b/library/Zend/Markup/Parser/Bbcode.php @@ -286,11 +286,7 @@ protected function _tokenize() $this->_temp['attributes'][$attribute] = ''; - if (empty($matches['eq'])) { - $this->_state = self::STATE_SCANATTRS; - } else { - $this->_state = self::STATE_PARSEVALUE; - } + $this->_state = empty($matches['eq']) ? self::STATE_SCANATTRS : self::STATE_PARSEVALUE; } break; case self::STATE_PARSEVALUE: @@ -303,11 +299,7 @@ protected function _tokenize() $this->_pointer += strlen((string) $matches[0]); - if (!empty($matches['quote'])) { - $this->_temp['attributes'][$attribute] = $matches['valuequote']; - } else { - $this->_temp['attributes'][$attribute] = $matches['value']; - } + $this->_temp['attributes'][$attribute] = empty($matches['quote']) ? $matches['value'] : $matches['valuequote']; $this->_temp['tag'] .= $matches[0]; $this->_state = self::STATE_SCANATTRS; @@ -337,17 +329,14 @@ public function _createTree() if ($this->_isStopper($token['tag'])) { // find the stopper $oldItems = array(); - while (!in_array($token['tag'], $this->_tags[$this->_current->getName()]['stoppers'])) { $oldItems[] = clone $this->_current; $this->_current = $this->_current->getParent(); } - // we found the stopper, so stop the tag $this->_current->setStopper($token['tag']); $this->_removeFromSearchedStoppers($this->_current); $this->_current = $this->_current->getParent(); - // add the old items again if there are any if (!empty($oldItems)) { foreach (array_reverse($oldItems) as $item) { @@ -357,56 +346,18 @@ public function _createTree() $this->_current = $item; } } - } else { - if ($token['type'] == Zend_Markup_Token::TYPE_TAG) { - if ($token['tag'] == self::NEWLINE) { - // this is a newline tag, add it as a token - $this->_current->addChild(new Zend_Markup_Token( - "\n", - Zend_Markup_Token::TYPE_NONE, - '', - array(), - $this->_current - )); - } elseif (isset($token['name']) && ($token['name'][0] == '/')) { - // this is a stopper, add it as a empty token - $this->_current->addChild(new Zend_Markup_Token( - $token['tag'], - Zend_Markup_Token::TYPE_NONE, - '', - array(), - $this->_current - )); - } elseif (isset($this->_tags[$this->_current->getName()]['parse_inside']) - && !$this->_tags[$this->_current->getName()]['parse_inside'] - ) { - $this->_current->addChild(new Zend_Markup_Token( - $token['tag'], - Zend_Markup_Token::TYPE_NONE, - '', - array(), - $this->_current - )); - } else { - // add the tag - $child = new Zend_Markup_Token( - $token['tag'], - $token['type'], - $token['name'], - $token['attributes'], - $this->_current - ); - $this->_current->addChild($child); - - // add stoppers for this tag, if its has stoppers - if ($this->_getType($token['name']) == self::TYPE_DEFAULT) { - $this->_current = $child; - - $this->_addToSearchedStoppers($this->_current); - } - } - } else { - // no tag, just add it as a simple token + } elseif ($token['type'] == Zend_Markup_Token::TYPE_TAG) { + if ($token['tag'] == self::NEWLINE) { + // this is a newline tag, add it as a token + $this->_current->addChild(new Zend_Markup_Token( + "\n", + Zend_Markup_Token::TYPE_NONE, + '', + array(), + $this->_current + )); + } elseif (isset($token['name']) && ($token['name'][0] == '/')) { + // this is a stopper, add it as a empty token $this->_current->addChild(new Zend_Markup_Token( $token['tag'], Zend_Markup_Token::TYPE_NONE, @@ -414,7 +365,43 @@ public function _createTree() array(), $this->_current )); + } elseif (isset($this->_tags[$this->_current->getName()]['parse_inside']) + && !$this->_tags[$this->_current->getName()]['parse_inside'] + ) { + $this->_current->addChild(new Zend_Markup_Token( + $token['tag'], + Zend_Markup_Token::TYPE_NONE, + '', + array(), + $this->_current + )); + } else { + // add the tag + $child = new Zend_Markup_Token( + $token['tag'], + $token['type'], + $token['name'], + $token['attributes'], + $this->_current + ); + $this->_current->addChild($child); + + // add stoppers for this tag, if its has stoppers + if ($this->_getType($token['name']) == self::TYPE_DEFAULT) { + $this->_current = $child; + + $this->_addToSearchedStoppers($this->_current); + } } + } else { + // no tag, just add it as a simple token + $this->_current->addChild(new Zend_Markup_Token( + $token['tag'], + Zend_Markup_Token::TYPE_NONE, + '', + array(), + $this->_current + )); } } } @@ -460,12 +447,7 @@ protected function _getType($name) protected function _isStopper($tag) { $this->_checkTagDeclaration($this->_current->getName()); - - if (!empty($this->_searchedStoppers[$tag])) { - return true; - } - - return false; + return !empty($this->_searchedStoppers[$tag]); } /** diff --git a/library/Zend/Markup/Renderer/Html.php b/library/Zend/Markup/Renderer/Html.php index 09eb456ea5..a5e44565fc 100644 --- a/library/Zend/Markup/Renderer/Html.php +++ b/library/Zend/Markup/Renderer/Html.php @@ -478,12 +478,7 @@ public static function checkColor($color) if (in_array($color, $colors)) { return true; } - - if (preg_match('/\#[0-9a-f]{6}/i', $color)) { - return true; - } - - return false; + return (bool) preg_match('/\#[0-9a-f]{6}/i', $color); } /** @@ -514,12 +509,7 @@ public static function isValidUri($uri) if ($components === false) { return false; } - - if (!isset($components['host'])) { - return false; - } - - return true; + return isset($components['host']); default: return true; diff --git a/library/Zend/Markup/Renderer/Html/Url.php b/library/Zend/Markup/Renderer/Html/Url.php index 82389cbfeb..62f3b503a7 100644 --- a/library/Zend/Markup/Renderer/Html/Url.php +++ b/library/Zend/Markup/Renderer/Html/Url.php @@ -51,11 +51,7 @@ class Zend_Markup_Renderer_Html_Url extends Zend_Markup_Renderer_Html_HtmlAbstra */ public function convert(Zend_Markup_Token $token, $text) { - if ($token->hasAttribute('url')) { - $uri = $token->getAttribute('url'); - } else { - $uri = $text; - } + $uri = $token->hasAttribute('url') ? $token->getAttribute('url') : $text; if (!preg_match('/^([a-z][a-z+\-.]*):/i', $uri)) { $uri = 'http://' . $uri; diff --git a/library/Zend/Markup/Renderer/RendererAbstract.php b/library/Zend/Markup/Renderer/RendererAbstract.php index 9667f41058..f7f81f3944 100644 --- a/library/Zend/Markup/Renderer/RendererAbstract.php +++ b/library/Zend/Markup/Renderer/RendererAbstract.php @@ -253,20 +253,17 @@ public function addMarkup($name, $type, array $options) 'type' => self::TYPE_ALIAS, 'name' => $options['name'] ); + } elseif ($type && array_key_exists('empty', $options) && $options['empty']) { + // add a single replace markup + $options['type'] = $type; + $options['filter'] = $filter; + $this->_markups[$name] = $options; } else { - if ($type && array_key_exists('empty', $options) && $options['empty']) { - // add a single replace markup - $options['type'] = $type; - $options['filter'] = $filter; - - $this->_markups[$name] = $options; - } else { - // add a replace markup - $options['type'] = $type; - $options['filter'] = $filter; + // add a replace markup + $options['type'] = $type; + $options['filter'] = $filter; - $this->_markups[$name] = $options; - } + $this->_markups[$name] = $options; } return $this; } @@ -301,11 +298,7 @@ public function clearMarkups() */ public function render($value) { - if ($value instanceof Zend_Markup_TokenList) { - $tokenList = $value; - } else { - $tokenList = $this->getParser()->parse($value); - } + $tokenList = $value instanceof Zend_Markup_TokenList ? $value : $this->getParser()->parse($value); $root = $tokenList->current(); @@ -380,7 +373,7 @@ protected function _execute(Zend_Markup_Token $token) } $name = $this->_getMarkupName($token); - $markup = (!$name) ? false : $this->_markups[$name]; + $markup = ($name) ? $this->_markups[$name] : false; $empty = (is_array($markup) && array_key_exists('empty', $markup) && $markup['empty']); // check if the tag has content @@ -437,13 +430,10 @@ protected function _execute(Zend_Markup_Token $token) } else { $return = $markup['callback']->convert($token, null); } + } elseif ($markup['type'] && !$empty) { + $return = $this->_executeReplace($token, $markup); } else { - // replace - if ($markup['type'] && !$empty) { - $return = $this->_executeReplace($token, $markup); - } else { - $return = $this->_executeSingleReplace($token, $markup); - } + $return = $this->_executeSingleReplace($token, $markup); } // reset to the old values diff --git a/library/Zend/Measure/Abstract.php b/library/Zend/Measure/Abstract.php index e2fd87a57b..25bde4862e 100644 --- a/library/Zend/Measure/Abstract.php +++ b/library/Zend/Measure/Abstract.php @@ -81,7 +81,7 @@ abstract class Zend_Measure_Abstract */ public function __construct($value, $type = null, $locale = null) { - if (($type !== null) and (Zend_Locale::isLocale($type, null, false))) { + if ($type !== null && Zend_Locale::isLocale($type, null, false)) { $locale = $type; $type = null; } @@ -91,7 +91,7 @@ public function __construct($value, $type = null, $locale = null) $type = $this->_units['STANDARD']; } - if (isset($this->_units[$type]) === false) { + if (!isset($this->_units[$type])) { require_once 'Zend/Measure/Exception.php'; throw new Zend_Measure_Exception("Type ($type) is unknown"); } @@ -120,7 +120,7 @@ public function setLocale($locale = null, $check = false) { if (empty($locale)) { require_once 'Zend/Registry.php'; - if (Zend_Registry::isRegistered('Zend_Locale') === true) { + if (Zend_Registry::isRegistered('Zend_Locale')) { $locale = Zend_Registry::get('Zend_Locale'); } } @@ -154,11 +154,7 @@ public function setLocale($locale = null, $check = false) */ public function getValue($round = -1, $locale = null) { - if ($round < 0) { - $return = $this->_value; - } else { - $return = Zend_Locale_Math::round($this->_value, $round); - } + $return = $round < 0 ? $this->_value : Zend_Locale_Math::round($this->_value, $round); if ($locale !== null) { $this->setLocale($locale, true); @@ -179,7 +175,7 @@ public function getValue($round = -1, $locale = null) */ public function setValue($value, $type = null, $locale = null) { - if (($type !== null) and (Zend_Locale::isLocale($type, null, false))) { + if ($type !== null && Zend_Locale::isLocale($type, null, false)) { $locale = $type; $type = null; } @@ -309,11 +305,7 @@ public function setType($type) */ public function equals($object) { - if ((string) $object == $this->toString()) { - return true; - } - - return false; + return (string) $object === $this->toString(); } /** @@ -409,7 +401,7 @@ public function compare($object) if ($value < 0) { return -1; - } else if ($value > 0) { + } elseif ($value > 0) { return 1; } diff --git a/library/Zend/Measure/Number.php b/library/Zend/Measure/Number.php index 2de8ae9282..20e0bfdf4d 100644 --- a/library/Zend/Measure/Number.php +++ b/library/Zend/Measure/Number.php @@ -144,7 +144,7 @@ class Zend_Measure_Number extends Zend_Measure_Abstract */ public function __construct($value, $type, $locale = null) { - if (($type !== null) and (Zend_Locale::isLocale($type, null, false))) { + if ($type !== null && Zend_Locale::isLocale($type, null, false)) { $locale = $type; $type = null; } @@ -168,7 +168,7 @@ public function __construct($value, $type, $locale = null) $type = $this->_units['STANDARD']; } - if (isset($this->_units[$type]) === false) { + if (!isset($this->_units[$type])) { require_once 'Zend/Measure/Exception.php'; throw new Zend_Measure_Exception("Type ($type) is unknown"); } @@ -296,14 +296,15 @@ private function _toDecimal($input, $type) $input = preg_replace(array_keys(self::$_romanconvert), array_values(self::$_romanconvert), $input); $split = preg_split('//', strrev($input), -1, PREG_SPLIT_NO_EMPTY); + $splitCount = count($split); - for ($x =0; $x < sizeof($split); $x++) { + for ($x =0; $x < $splitCount; $x++) { if ($split[$x] == '/') { continue; } $num = self::$_roman[$split[$x]]; - if (($x > 0 and ($split[$x-1] != '/') and ($num < self::$_roman[$split[$x-1]]))) { + if (($x > 0 && $split[$x-1] != '/' && $num < self::$_roman[$split[$x-1]])) { $num -= $num; } @@ -332,7 +333,7 @@ private function _fromDecimal($value, $type) $count = 200; $base = $this->_units[$type][0]; - while (call_user_func(Zend_Locale_Math::$comp, $value, 0, 25) <> 0) { + while (call_user_func(Zend_Locale_Math::$comp, $value, 0, 25) != 0) { $target = call_user_func(Zend_Locale_Math::$mod, $value, $base); $newvalue = strtoupper(dechex($target)) . $newvalue; @@ -358,7 +359,7 @@ private function _fromDecimal($value, $type) $romanval = array_values(array_reverse(self::$_roman)); $romankey = array_keys(array_reverse(self::$_roman)); $count = 200; - while (call_user_func(Zend_Locale_Math::$comp, $value, 0, 25) <> 0) { + while (call_user_func(Zend_Locale_Math::$comp, $value, 0, 25) != 0) { while ($value >= $romanval[$i]) { $value -= $romanval[$i]; $newvalue .= $romankey[$i]; @@ -392,12 +393,12 @@ private function _fromDecimal($value, $type) */ public function setType($type) { - if (empty($this->_units[$type]) === true) { + if (empty($this->_units[$type])) { require_once 'Zend/Measure/Exception.php'; throw new Zend_Measure_Exception('Unknown type of number:' . $type); } - $value = $this->_toDecimal($this->getValue(-1), $this->getType(-1)); + $value = $this->_toDecimal($this->getValue(-1), $this->getType()); $value = $this->_fromDecimal($value, $type); $this->_value = $value; diff --git a/library/Zend/Memory/Container/Movable.php b/library/Zend/Memory/Container/Movable.php index 48bf30dace..80c6b03fd8 100644 --- a/library/Zend/Memory/Container/Movable.php +++ b/library/Zend/Memory/Container/Movable.php @@ -89,7 +89,7 @@ public function __construct(Zend_Memory_Manager $memoryManager, $id, $value) */ public function lock() { - if ( !($this->_state & self::LOADED) ) { + if ( ($this->_state & self::LOADED) === 0 ) { $this->_memManager->load($this, $this->_id); $this->_state |= self::LOADED; } @@ -139,7 +139,7 @@ public function __get($property) throw new Zend_Memory_Exception('Unknown property: Zend_Memory_container::$' . $property); } - if ( !($this->_state & self::LOADED) ) { + if ( ($this->_state & self::LOADED) === 0 ) { $this->_memManager->load($this, $this->_id); $this->_state |= self::LOADED; } @@ -178,7 +178,7 @@ public function __set($property, $value) */ public function &getRef() { - if ( !($this->_state & self::LOADED) ) { + if ( ($this->_state & self::LOADED) === 0 ) { $this->_memManager->load($this, $this->_id); $this->_state |= self::LOADED; } @@ -217,7 +217,7 @@ public function processUpdate() */ public function startTrace() { - if ( !($this->_state & self::LOADED) ) { + if ( ($this->_state & self::LOADED) === 0 ) { $this->_memManager->load($this, $this->_id); $this->_state |= self::LOADED; } diff --git a/library/Zend/Mime.php b/library/Zend/Mime.php index 5530b6cb59..ef28f9d20f 100644 --- a/library/Zend/Mime.php +++ b/library/Zend/Mime.php @@ -453,9 +453,8 @@ public static function encodeQuotedPrintable( } $out = rtrim($out, $lineEnd); - $out = rtrim($out, '='); - return $out; + return rtrim($out, '='); } /** @@ -468,9 +467,8 @@ private static function _encodeQuotedPrintable($str) { $str = str_replace('=', '=3D', $str); $str = str_replace(self::$qpKeys, self::$qpReplaceValues, $str); - $str = rtrim($str); - return $str; + return rtrim($str); } /** @@ -526,14 +524,14 @@ public static function encodeQuotedPrintableHeader( $lines[$currentLine] .= $tmp; } } + $linesCount = count($lines); // assemble the lines together by pre- and appending delimiters, charset, encoding. - for ($i = 0; $i < count($lines); $i++) { + for ($i = 0; $i < $linesCount; $i++) { $lines[$i] = " " . $prefix . $lines[$i] . "?="; } - $str = trim(implode($lineEnd, $lines)); - return $str; + return trim(implode($lineEnd, $lines)); } /** @@ -544,13 +542,7 @@ public static function encodeQuotedPrintableHeader( */ private static function getNextQuotedPrintableToken($str) { - if (substr($str, 0, 1) == "=") { - $token = substr($str, 0, 3); - } else { - $token = substr($str, 0, 1); - } - - return $token; + return substr($str, 0, 1) == "=" ? substr($str, 0, 3) : substr($str, 0, 1); } /** @@ -574,9 +566,8 @@ public static function encodeBase64Header( $encodedValue = str_replace( $lineEnd, $suffix . $lineEnd . ' ' . $prefix, $encodedValue ); - $encodedValue = $prefix . $encodedValue . $suffix; - return $encodedValue; + return $prefix . $encodedValue . $suffix; } /** @@ -603,11 +594,7 @@ public static function encodeBase64( public function __construct($boundary = null) { // This string needs to be somewhat unique - if ($boundary === null) { - $this->_boundary = '=_' . md5(microtime(1) . self::$makeUnique++); - } else { - $this->_boundary = $boundary; - } + $this->_boundary = $boundary === null ? '=_' . md5(microtime(1) . self::$makeUnique++) : $boundary; } /** diff --git a/library/Zend/Mime/Decode.php b/library/Zend/Mime/Decode.php index 5a19b7aef3..eaac722641 100644 --- a/library/Zend/Mime/Decode.php +++ b/library/Zend/Mime/Decode.php @@ -147,19 +147,15 @@ public static function splitMessage( if (strpos($message, $EOL . $EOL)) { list($headers, $body) = explode($EOL . $EOL, $message, 2); // next is the standard new line + } elseif ($EOL != "\r\n" && strpos($message, "\r\n\r\n")) { + list($headers, $body) = explode("\r\n\r\n", $message, 2); + // next is the other "standard" new line + } elseif ($EOL != "\n" && strpos($message, "\n\n")) { + list($headers, $body) = explode("\n\n", $message, 2); + // at last resort find anything that looks like a new line } else { - if ($EOL != "\r\n" && strpos($message, "\r\n\r\n")) { - list($headers, $body) = explode("\r\n\r\n", $message, 2); - // next is the other "standard" new line - } else { - if ($EOL != "\n" && strpos($message, "\n\n")) { - list($headers, $body) = explode("\n\n", $message, 2); - // at last resort find anything that looks like a new line - } else { - @list($headers, $body) = - @preg_split("%([\r\n]+)\\1%U", $message, 2); - } - } + @list($headers, $body) = + @preg_split("%([\r\n]+)\\1%U", $message, 2); } $headers = iconv_mime_decode_headers( @@ -233,9 +229,9 @@ public static function splitHeaderField( throw new Zend_Exception('not a valid header field'); } - if ($wantedPart) { + if ($wantedPart !== '' && $wantedPart !== '0') { foreach ($matches[1] as $key => $name) { - if (strcasecmp($name, $wantedPart)) { + if (strcasecmp($name, $wantedPart) !== 0) { continue; } if ($matches[2][$key][0] != '"') { @@ -251,11 +247,7 @@ public static function splitHeaderField( $split = array(); foreach ($matches[1] as $key => $name) { $name = strtolower($name); - if ($matches[2][$key][0] == '"') { - $split[$name] = substr($matches[2][$key], 1, -1); - } else { - $split[$name] = $matches[2][$key]; - } + $split[$name] = $matches[2][$key][0] == '"' ? substr($matches[2][$key], 1, -1) : $matches[2][$key]; } return $split; diff --git a/library/Zend/Mime/Part.php b/library/Zend/Mime/Part.php index c28e95cf44..662163ccdf 100644 --- a/library/Zend/Mime/Part.php +++ b/library/Zend/Mime/Part.php @@ -252,11 +252,11 @@ public function getHeadersArray($EOL = Zend_Mime::LINEEND) $headers = array(); $contentType = $this->type; - if ($this->charset) { + if ($this->charset !== '' && $this->charset !== '0') { $contentType .= '; charset=' . $this->charset; } - if ($this->boundary) { + if ($this->boundary !== '' && $this->boundary !== '0') { $contentType .= ';' . $EOL . " boundary=\"" . $this->boundary . '"'; } @@ -266,23 +266,23 @@ public function getHeadersArray($EOL = Zend_Mime::LINEEND) $contentType ); - if ($this->encoding) { + if ($this->encoding !== '' && $this->encoding !== '0') { $headers[] = array( 'Content-Transfer-Encoding', $this->encoding ); } - if ($this->id) { + if ($this->id !== '' && $this->id !== '0') { $headers[] = array( 'Content-ID', '<' . $this->id . '>' ); } - if ($this->disposition) { + if ($this->disposition !== '' && $this->disposition !== '0') { $disposition = $this->disposition; - if ($this->filename) { + if ($this->filename !== '' && $this->filename !== '0') { $disposition .= '; filename="' . $this->filename . '"'; } $headers[] = array( @@ -291,21 +291,21 @@ public function getHeadersArray($EOL = Zend_Mime::LINEEND) ); } - if ($this->description) { + if ($this->description !== '' && $this->description !== '0') { $headers[] = array( 'Content-Description', $this->description ); } - if ($this->location) { + if ($this->location !== '' && $this->location !== '0') { $headers[] = array( 'Content-Location', $this->location ); } - if ($this->language) { + if ($this->language !== '' && $this->language !== '0') { $headers[] = array( 'Content-Language', $this->language diff --git a/library/Zend/Mobile/Push/Apns.php b/library/Zend/Mobile/Push/Apns.php index f12eb0d6dd..f999019099 100644 --- a/library/Zend/Mobile/Push/Apns.php +++ b/library/Zend/Mobile/Push/Apns.php @@ -154,7 +154,7 @@ protected function _connect($uri) $ssl = array( 'local_cert' => $this->_certificate, ); - if ($this->_certificatePassphrase) { + if ($this->_certificatePassphrase !== '' && $this->_certificatePassphrase !== '0') { $ssl['passphrase'] = $this->_certificatePassphrase; } @@ -227,7 +227,7 @@ public function connect($env = self::SERVER_PRODUCTION_URI) throw new Zend_Mobile_Push_Exception('$env is not a valid environment'); } - if (!$this->_certificate) { + if ($this->_certificate === '' || $this->_certificate === '0') { throw new Zend_Mobile_Push_Exception('A certificate must be set prior to calling ::connect'); } diff --git a/library/Zend/Mobile/Push/Message/Abstract.php b/library/Zend/Mobile/Push/Message/Abstract.php index 9c8651af45..c6e7e3b1fd 100644 --- a/library/Zend/Mobile/Push/Message/Abstract.php +++ b/library/Zend/Mobile/Push/Message/Abstract.php @@ -91,7 +91,7 @@ public function getId() /** * Set Message ID * - * @param int|string|float|bool $id Scalar + * @param scalar $id Scalar * @return Zend_Mobile_Push_Message_Abstract * @throws Exception */ diff --git a/library/Zend/Mobile/Push/Message/Apns.php b/library/Zend/Mobile/Push/Message/Apns.php index 1dd637e10f..8648b55a7e 100644 --- a/library/Zend/Mobile/Push/Message/Apns.php +++ b/library/Zend/Mobile/Push/Message/Apns.php @@ -274,7 +274,7 @@ public function getCustomData() */ public function validate() { - if (!is_string($this->_token) || strlen($this->_token) === 0) { + if (!is_string($this->_token) || $this->_token === '') { return false; } if (null != $this->_id && !is_numeric($this->_id)) { diff --git a/library/Zend/Mobile/Push/Message/Gcm.php b/library/Zend/Mobile/Push/Message/Gcm.php index 0e36190747..265ec645f8 100644 --- a/library/Zend/Mobile/Push/Message/Gcm.php +++ b/library/Zend/Mobile/Push/Message/Gcm.php @@ -95,7 +95,7 @@ public function setToken($token) $this->clearToken(); if (is_string($token)) { $this->addToken($token); - } else if (is_array($token)) { + } elseif (is_array($token)) { foreach ($token as $t) { $this->addToken($t); } @@ -237,7 +237,7 @@ public function validate() } if ($this->_ttl !== 2419200 && (!is_scalar($this->_id) || - strlen((string) $this->_id) === 0)) { + (string) $this->_id === '')) { return false; } return true; diff --git a/library/Zend/Mobile/Push/Message/Interface.php b/library/Zend/Mobile/Push/Message/Interface.php index 27be3256a3..86117b1f7e 100644 --- a/library/Zend/Mobile/Push/Message/Interface.php +++ b/library/Zend/Mobile/Push/Message/Interface.php @@ -57,7 +57,7 @@ public function getId(); /** * Set Id * - * @param int|string|float|bool $id Scalar + * @param scalar $id Scalar * @return Zend_Mobile_Push_Message_Abstract */ public function setId($id); diff --git a/library/Zend/Mobile/Push/Message/Mpns.php b/library/Zend/Mobile/Push/Message/Mpns.php index 15f187b4e6..5261a81dcc 100644 --- a/library/Zend/Mobile/Push/Message/Mpns.php +++ b/library/Zend/Mobile/Push/Message/Mpns.php @@ -109,7 +109,7 @@ abstract public function getXmlPayload(); */ public function validate() { - if (!isset($this->_token) || strlen($this->_token) === 0) { + if (!($this->_token !== null) || $this->_token === '') { return false; } return parent::validate(); diff --git a/library/Zend/Mobile/Push/Message/Mpns/Raw.php b/library/Zend/Mobile/Push/Message/Mpns/Raw.php index 99d87802bc..67c001ce14 100644 --- a/library/Zend/Mobile/Push/Message/Mpns/Raw.php +++ b/library/Zend/Mobile/Push/Message/Mpns/Raw.php @@ -59,7 +59,7 @@ class Zend_Mobile_Push_Message_Mpns_Raw extends Zend_Mobile_Push_Message_Mpns */ public function getDelay() { - if (!$this->_delay) { + if ($this->_delay === 0) { return self::DELAY_IMMEDIATE; } return $this->_delay; @@ -141,7 +141,7 @@ public function getXmlPayload() */ public function validate() { - if (!isset($this->_token) || strlen($this->_token) === 0) { + if (!($this->_token !== null) || $this->_token === '') { return false; } if (empty($this->_msg)) { diff --git a/library/Zend/Mobile/Push/Message/Mpns/Tile.php b/library/Zend/Mobile/Push/Message/Mpns/Tile.php index 965412452d..c43e074c3a 100644 --- a/library/Zend/Mobile/Push/Message/Mpns/Tile.php +++ b/library/Zend/Mobile/Push/Message/Mpns/Tile.php @@ -279,7 +279,7 @@ public function setTileId($tileId) */ public function getDelay() { - if (!$this->_delay) { + if ($this->_delay === 0) { return self::DELAY_IMMEDIATE; } return $this->_delay; @@ -324,24 +324,21 @@ public function getXmlPayload() { $ret = '' . '' - . '_tileId) ? ' Id="' . htmlspecialchars($this->_tileId) . '"' : '') . '>' + . '_tileId !== '' && $this->_tileId !== '0') ? ' Id="' . htmlspecialchars($this->_tileId) . '"' : '') . '>' . '' . htmlspecialchars($this->_backgroundImage) . '' . '' . (int) $this->_count . '' . '' . htmlspecialchars($this->_title) . ''; - if ($this->_backBackgroundImage) { + if ($this->_backBackgroundImage !== '' && $this->_backBackgroundImage !== '0') { $ret .= '' . htmlspecialchars($this->_backBackgroundImage) . ''; } - if ($this->_backTitle) { + if ($this->_backTitle !== '' && $this->_backTitle !== '0') { $ret .= '' . htmlspecialchars($this->_backTitle) . ''; } - if ($this->_backContent) { + if ($this->_backContent !== '' && $this->_backContent !== '0') { $ret .= '' . htmlspecialchars($this->_backContent) . ''; } - - $ret .= '' - . ''; - return $ret; + return $ret . ''; } /** @@ -351,7 +348,7 @@ public function getXmlPayload() */ public function validate() { - if (!isset($this->_token) || strlen($this->_token) === 0) { + if (!($this->_token !== null) || $this->_token === '') { return false; } if (empty($this->_backgroundImage)) { diff --git a/library/Zend/Mobile/Push/Message/Mpns/Toast.php b/library/Zend/Mobile/Push/Message/Mpns/Toast.php index 14381c1a77..02a2637ba1 100644 --- a/library/Zend/Mobile/Push/Message/Mpns/Toast.php +++ b/library/Zend/Mobile/Push/Message/Mpns/Toast.php @@ -148,7 +148,7 @@ public function setParams($params) */ public function getDelay() { - if (!$this->_delay) { + if ($this->_delay === 0) { return self::DELAY_IMMEDIATE; } return $this->_delay; @@ -199,9 +199,7 @@ public function getXmlPayload() if (!empty($this->_params)) { $ret .= '' . htmlspecialchars($this->_params) . ''; } - $ret .= '' - . ''; - return $ret; + return $ret . ''; } /** @@ -211,7 +209,7 @@ public function getXmlPayload() */ public function validate() { - if (!isset($this->_token) || strlen($this->_token) === 0) { + if (!($this->_token !== null) || $this->_token === '') { return false; } if (empty($this->_title)) { diff --git a/library/Zend/Mobile/Push/Response/Gcm.php b/library/Zend/Mobile/Push/Response/Gcm.php index 6222e6dce5..ee1135d10b 100644 --- a/library/Zend/Mobile/Push/Response/Gcm.php +++ b/library/Zend/Mobile/Push/Response/Gcm.php @@ -97,7 +97,7 @@ public function __construct($responseString = null, Zend_Mobile_Push_Message_Gcm $this->setResponse($response); } - if ($message) { + if ($message !== null) { $this->setMessage($message); } diff --git a/library/Zend/Navigation.php b/library/Zend/Navigation.php index 0c7f7c5781..d499700e20 100644 --- a/library/Zend/Navigation.php +++ b/library/Zend/Navigation.php @@ -47,8 +47,7 @@ public function __construct($pages = null) } elseif (null !== $pages) { require_once 'Zend/Navigation/Exception.php'; throw new Zend_Navigation_Exception( - 'Invalid argument: $pages must be an array, an ' . - 'instance of Zend_Config, or null'); + 'Invalid argument: $pages must be an array, an instance of Zend_Config, or null'); } } } diff --git a/library/Zend/Navigation/Container.php b/library/Zend/Navigation/Container.php index dc8c2f0000..05a29bc8e4 100644 --- a/library/Zend/Navigation/Container.php +++ b/library/Zend/Navigation/Container.php @@ -118,8 +118,7 @@ public function addPage($page) } elseif (!$page instanceof Zend_Navigation_Page) { require_once 'Zend/Navigation/Exception.php'; throw new Zend_Navigation_Exception( - 'Invalid argument: $page must be an instance of ' . - 'Zend_Navigation_Page or Zend_Config, or an array'); + 'Invalid argument: $page must be an instance of Zend_Navigation_Page or Zend_Config, or an array'); } $hash = $page->hashCode(); @@ -280,7 +279,7 @@ public function hasPage(Zend_Navigation_Page $page, $recursive = false) */ public function hasPages() { - return count($this->_index) > 0; + return $this->_index !== []; } /** @@ -308,28 +307,21 @@ public function findOneBy($property, $value, $useRegex = false) foreach ($pageProperty as $item) { if (is_array($item)) { // Use regex? - if (true === $useRegex) { + if ($useRegex) { foreach ($item as $item2) { if (0 !== preg_match($value, (string) $item2)) { return $page; } } - } else { - if (in_array($value, $item)) { - return $page; - } + } elseif (in_array($value, $item)) { + return $page; } - } else { - // Use regex? - if (true === $useRegex) { - if (0 !== preg_match($value, (string) $item)) { - return $page; - } - } else { - if ($item == $value) { - return $page; - } + } elseif ($useRegex) { + if (0 !== preg_match($value, (string) $item)) { + return $page; } + } elseif ($item == $value) { + return $page; } } @@ -337,14 +329,12 @@ public function findOneBy($property, $value, $useRegex = false) } // Use regex? - if (true === $useRegex) { + if ($useRegex) { if (preg_match($value, (string) $pageProperty)) { return $page; } - } else { - if ($pageProperty == $value) { - return $page; - } + } elseif ($pageProperty == $value) { + return $page; } } @@ -379,28 +369,21 @@ public function findAllBy($property, $value, $useRegex = false) foreach ($pageProperty as $item) { if (is_array($item)) { // Use regex? - if (true === $useRegex) { + if ($useRegex) { foreach ($item as $item2) { if (0 !== preg_match($value, (string) $item2)) { $found[] = $page; } } - } else { - if (in_array($value, $item)) { - $found[] = $page; - } + } elseif (in_array($value, $item)) { + $found[] = $page; } - } else { - // Use regex? - if (true === $useRegex) { - if (0 !== preg_match($value, (string) $item)) { - $found[] = $page; - } - } else { - if ($item == $value) { - $found[] = $page; - } + } elseif ($useRegex) { + if (0 !== preg_match($value, (string) $item)) { + $found[] = $page; } + } elseif ($item == $value) { + $found[] = $page; } } @@ -408,14 +391,12 @@ public function findAllBy($property, $value, $useRegex = false) } // Use regex? - if (true === $useRegex) { + if ($useRegex) { if (0 !== preg_match($value, (string) $pageProperty)) { $found[] = $page; } - } else { - if ($pageProperty == $value) { - $found[] = $page; - } + } elseif ($pageProperty == $value) { + $found[] = $page; } } @@ -509,7 +490,7 @@ public function toArray() * @return Zend_Navigation_Page current page or null * @throws Zend_Navigation_Exception if the index is invalid */ - public function current() + public function current(): mixed { $this->_sort(); current($this->_index); @@ -520,8 +501,7 @@ public function current() } else { require_once 'Zend/Navigation/Exception.php'; throw new Zend_Navigation_Exception( - 'Corruption detected in container; ' . - 'invalid key found in internal iterator'); + 'Corruption detected in container; invalid key found in internal iterator'); } } @@ -532,7 +512,7 @@ public function current() * * @return string hash code of current page */ - public function key() + public function key(): string { $this->_sort(); return key($this->_index); @@ -545,7 +525,7 @@ public function key() * * @return void */ - public function next() + public function next(): void { $this->_sort(); next($this->_index); @@ -558,7 +538,7 @@ public function next() * * @return void */ - public function rewind() + public function rewind(): void { $this->_sort(); reset($this->_index); @@ -571,7 +551,7 @@ public function rewind() * * @return bool */ - public function valid() + public function valid(): bool { $this->_sort(); return current($this->_index) !== false; @@ -584,7 +564,7 @@ public function valid() * * @return bool whether container has any pages */ - public function hasChildren() + public function hasChildren(): bool { return $this->hasPages(); } @@ -596,6 +576,7 @@ public function hasChildren() * * @return Zend_Navigation_Page|null */ + #[\ReturnTypeWillChange] public function getChildren() { $hash = key($this->_index); @@ -616,7 +597,7 @@ public function getChildren() * * @return int number of pages in the container */ - public function count() + public function count(): int { return count($this->_index); } diff --git a/library/Zend/Navigation/Page.php b/library/Zend/Navigation/Page.php index c3a799800f..258e4e1a11 100644 --- a/library/Zend/Navigation/Page.php +++ b/library/Zend/Navigation/Page.php @@ -221,36 +221,31 @@ public static function factory($options) if (isset($options['type'])) { $type = $options['type']; - } elseif(self::getDefaultPageType()!= null) { + } elseif(self::getDefaultPageType() != null) { $type = self::getDefaultPageType(); } - if(isset($type)) { - if (is_string($type) && !empty($type)) { - switch (strtolower($type)) { - case 'mvc': - $type = 'Zend_Navigation_Page_Mvc'; - break; - case 'uri': - $type = 'Zend_Navigation_Page_Uri'; - break; - } - - if (!class_exists($type)) { - require_once 'Zend/Loader.php'; - @Zend_Loader::loadClass($type); - } - - $page = new $type($options); - if (!$page instanceof Zend_Navigation_Page) { - require_once 'Zend/Navigation/Exception.php'; - throw new Zend_Navigation_Exception(sprintf( - 'Invalid argument: Detected type "%s", which ' . - 'is not an instance of Zend_Navigation_Page', - $type)); - } - return $page; + if (isset($type) && (is_string($type) && !empty($type))) { + switch (strtolower($type)) { + case 'mvc': + $type = 'Zend_Navigation_Page_Mvc'; + break; + case 'uri': + $type = 'Zend_Navigation_Page_Uri'; + break; } + if (!class_exists($type)) { + require_once 'Zend/Loader.php'; + @Zend_Loader::loadClass($type); + } + $page = new $type($options); + if (!$page instanceof Zend_Navigation_Page) { + require_once 'Zend/Navigation/Exception.php'; + throw new Zend_Navigation_Exception(sprintf( + 'Invalid argument: Detected type "%s", which is not an instance of Zend_Navigation_Page', + $type)); + } + return $page; } $hasUri = isset($options['uri']); @@ -576,8 +571,7 @@ public function setRel($relations = null) if (!is_array($relations)) { require_once 'Zend/Navigation/Exception.php'; throw new Zend_Navigation_Exception( - 'Invalid argument: $relations must be an ' . - 'array or an instance of Zend_Config'); + 'Invalid argument: $relations must be an array or an instance of Zend_Config'); } foreach ($relations as $name => $relation) { @@ -639,8 +633,7 @@ public function setRev($relations = null) if (!is_array($relations)) { require_once 'Zend/Navigation/Exception.php'; throw new Zend_Navigation_Exception( - 'Invalid argument: $relations must be an ' . - 'array or an instance of Zend_Config'); + 'Invalid argument: $relations must be an array or an instance of Zend_Config'); } foreach ($relations as $name => $relation) { @@ -812,14 +805,13 @@ public function setOrder($order = null) if (null !== $order && !is_int($order)) { require_once 'Zend/Navigation/Exception.php'; throw new Zend_Navigation_Exception( - 'Invalid argument: $order must be an integer or null, ' . - 'or a string that casts to an integer'); + 'Invalid argument: $order must be an integer or null, or a string that casts to an integer'); } $this->_order = $order; // notify parent, if any - if (isset($this->_parent)) { + if ($this->_parent !== null) { $this->_parent->notifyOrderUpdated(); } @@ -857,8 +849,7 @@ public function setResource($resource = null) } else { require_once 'Zend/Navigation/Exception.php'; throw new Zend_Navigation_Exception( - 'Invalid argument: $resource must be null, a string, ' . - ' or an instance of Zend_Acl_Resource_Interface'); + 'Invalid argument: $resource must be null, a string, or an instance of Zend_Acl_Resource_Interface'); } return $this; @@ -972,11 +963,9 @@ public function setVisible($visible = true) */ public function isVisible($recursive = false) { - if ($recursive && isset($this->_parent) && - $this->_parent instanceof Zend_Navigation_Page) { - if (!$this->_parent->isVisible(true)) { - return false; - } + if ($recursive && $this->_parent !== null && + $this->_parent instanceof Zend_Navigation_Page && !$this->_parent->isVisible(true)) { + return false; } return $this->_visible; diff --git a/library/Zend/Navigation/Page/Mvc.php b/library/Zend/Navigation/Page/Mvc.php index 4c55f378c0..65531d7162 100644 --- a/library/Zend/Navigation/Page/Mvc.php +++ b/library/Zend/Navigation/Page/Mvc.php @@ -163,7 +163,7 @@ public function isActive($recursive = false) $front = Zend_Controller_Front::getInstance(); $request = $front->getRequest(); $reqParams = array(); - if ($request) { + if ($request !== null) { $reqParams = $request->getParams(); if (!array_key_exists('module', $reqParams)) { $reqParams['module'] = $front->getDefaultModule(); @@ -205,8 +205,7 @@ public function isActive($recursive = false) } } - if (count(array_intersect_assoc($reqParams, $myParams)) == - count($myParams) + if (count(array_intersect_assoc($reqParams, $myParams)) === count($myParams) ) { $this->_active = true; @@ -229,7 +228,7 @@ public function isActive($recursive = false) */ public function getHref() { - if ($this->_hrefCache) { + if ($this->_hrefCache !== '' && $this->_hrefCache !== '0') { return $this->_hrefCache; } diff --git a/library/Zend/Oauth/Client.php b/library/Zend/Oauth/Client.php index 03b794dc84..694fe80959 100644 --- a/library/Zend/Oauth/Client.php +++ b/library/Zend/Oauth/Client.php @@ -76,10 +76,10 @@ class Zend_Oauth_Client extends Zend_Http_Client */ public function __construct($oauthOptions, $uri = null, $config = null) { - if ($config instanceof Zend_Config && !isset($config->rfc3986_strict)) { + if ($config instanceof Zend_Config && !(property_exists($config, 'rfc3986_strict') && $config->rfc3986_strict !== null)) { $config = $config->toArray(); $config['rfc3986_strict'] = true; - } else if (null === $config || + } elseif (null === $config || (is_array($config) && !isset($config['rfc3986_strict']))) { $config['rfc3986_strict'] = true; } @@ -265,7 +265,7 @@ public function prepareOauth() } elseif ($requestScheme == Zend_Oauth::REQUEST_SCHEME_QUERYSTRING) { $params = $this->paramsGet; $query = $this->getUri()->getQuery(); - if ($query) { + if ($query !== '' && $query !== '0') { $queryParts = explode('&', $this->getUri()->getQuery()); foreach ($queryParts as $queryPart) { $kvTuple = explode('=', $queryPart); diff --git a/library/Zend/Oauth/Consumer.php b/library/Zend/Oauth/Consumer.php index 5f5f32ffb4..38d426f507 100644 --- a/library/Zend/Oauth/Consumer.php +++ b/library/Zend/Oauth/Consumer.php @@ -213,8 +213,7 @@ public function getAccessToken( if ($authorizedToken->getToken() !== $token->getToken()) { require_once 'Zend/Oauth/Exception.php'; throw new Zend_Oauth_Exception( - 'Authorized token from Service Provider does not match' - . ' supplied Request Token details' + 'Authorized token from Service Provider does not match supplied Request Token details' ); } } else { diff --git a/library/Zend/Oauth/Http.php b/library/Zend/Oauth/Http.php index bf5620211e..b0e9da1025 100644 --- a/library/Zend/Oauth/Http.php +++ b/library/Zend/Oauth/Http.php @@ -89,11 +89,7 @@ public function __construct( if ($parameters !== null) { $this->setParameters($parameters); } - if ($utility !== null) { - $this->_httpUtility = $utility; - } else { - $this->_httpUtility = new Zend_Oauth_Http_Utility; - } + $this->_httpUtility = $utility !== null ? $utility : new Zend_Oauth_Http_Utility; } /** diff --git a/library/Zend/Oauth/Http/AccessToken.php b/library/Zend/Oauth/Http/AccessToken.php index 9766813cce..6445a19e40 100644 --- a/library/Zend/Oauth/Http/AccessToken.php +++ b/library/Zend/Oauth/Http/AccessToken.php @@ -49,8 +49,7 @@ public function execute() { $params = $this->assembleParams(); $response = $this->startRequestCycle($params); - $return = new Zend_Oauth_Token_Access($response); - return $return; + return new Zend_Oauth_Token_Access($response); } /** @@ -179,7 +178,7 @@ protected function _attemptRequest(array $params) */ protected function _cleanParamsOfIllegalCustomParameters(array $params) { - foreach ($params as $key=>$value) { + foreach (array_keys($params) as $key) { if (!preg_match("/^oauth_/", (string) $key)) { unset($params[$key]); } diff --git a/library/Zend/Oauth/Http/RequestToken.php b/library/Zend/Oauth/Http/RequestToken.php index 44ae2da7a1..be5c3c7452 100644 --- a/library/Zend/Oauth/Http/RequestToken.php +++ b/library/Zend/Oauth/Http/RequestToken.php @@ -49,8 +49,7 @@ public function execute() { $params = $this->assembleParams(); $response = $this->startRequestCycle($params); - $return = new Zend_Oauth_Token_Request($response); - return $return; + return new Zend_Oauth_Token_Request($response); } /** @@ -69,11 +68,7 @@ public function assembleParams() ); // indicates we support 1.0a - if ($this->_consumer->getCallbackUrl()) { - $params['oauth_callback'] = $this->_consumer->getCallbackUrl(); - } else { - $params['oauth_callback'] = 'oob'; - } + $params['oauth_callback'] = $this->_consumer->getCallbackUrl() ? $this->_consumer->getCallbackUrl() : 'oob'; if (!empty($this->_parameters)) { $params = array_merge($params, $this->_parameters); diff --git a/library/Zend/Oauth/Http/Utility.php b/library/Zend/Oauth/Http/Utility.php index 9973fda71c..f6b566a431 100644 --- a/library/Zend/Oauth/Http/Utility.php +++ b/library/Zend/Oauth/Http/Utility.php @@ -88,7 +88,7 @@ public function assembleParams( public function toEncodedQueryString(array $params, $customParamsOnly = false) { if ($customParamsOnly) { - foreach ($params as $key=>$value) { + foreach (array_keys($params) as $key) { if (preg_match("/^oauth_/", (string) $key)) { unset($params[$key]); } @@ -118,10 +118,8 @@ public function toAuthorizationHeader(array $params, $realm = null, $excludeCust ); foreach ($params as $key => $value) { - if ($excludeCustomParams) { - if (!preg_match("/^oauth_/", (string) $key)) { - continue; - } + if ($excludeCustomParams && !preg_match("/^oauth_/", (string) $key)) { + continue; } $headerValue[] = self::urlEncode($key) . '="' @@ -211,7 +209,6 @@ public function generateTimestamp() public static function urlEncode($value) { $encoded = rawurlencode($value); - $encoded = str_replace('%7E', '~', $encoded); - return $encoded; + return str_replace('%7E', '~', $encoded); } } diff --git a/library/Zend/Oauth/Signature/Plaintext.php b/library/Zend/Oauth/Signature/Plaintext.php index e39b676770..21977d5828 100644 --- a/library/Zend/Oauth/Signature/Plaintext.php +++ b/library/Zend/Oauth/Signature/Plaintext.php @@ -43,7 +43,6 @@ public function sign(array $params, $method = null, $url = null) if ($this->_tokenSecret === null) { return $this->_consumerSecret . '&'; } - $return = implode('&', array($this->_consumerSecret, $this->_tokenSecret)); - return $return; + return implode('&', array($this->_consumerSecret, $this->_tokenSecret)); } } diff --git a/library/Zend/Oauth/Signature/Rsa.php b/library/Zend/Oauth/Signature/Rsa.php index c79d4a3e79..98f98a167b 100644 --- a/library/Zend/Oauth/Signature/Rsa.php +++ b/library/Zend/Oauth/Signature/Rsa.php @@ -45,12 +45,11 @@ public function sign(array $params, $method = null, $url = null) { $rsa = new Zend_Crypt_Rsa; $rsa->setHashAlgorithm($this->_hashAlgorithm); - $sign = $rsa->sign( + return $rsa->sign( $this->_getBaseSignatureString($params, $method, $url), $this->_key, Zend_Crypt_Rsa::BASE64 ); - return $sign; } /** diff --git a/library/Zend/Oauth/Signature/SignatureAbstract.php b/library/Zend/Oauth/Signature/SignatureAbstract.php index 688f4606ce..1a72a74ab6 100644 --- a/library/Zend/Oauth/Signature/SignatureAbstract.php +++ b/library/Zend/Oauth/Signature/SignatureAbstract.php @@ -104,7 +104,7 @@ public function normaliseBaseSignatureUrl($url) $uri->setQuery(''); $uri->setFragment(''); $uri->setHost(strtolower($uri->getHost())); - return $uri->getUri(true); + return $uri->getUri(); } /** diff --git a/library/Zend/Oauth/Token.php b/library/Zend/Oauth/Token.php index 08f23e5c12..e558944796 100644 --- a/library/Zend/Oauth/Token.php +++ b/library/Zend/Oauth/Token.php @@ -71,15 +71,11 @@ public function __construct( if ($response !== null) { $this->_response = $response; $params = $this->_parseParameters($response); - if (count($params) > 0) { + if ($params !== []) { $this->setParams($params); } } - if ($utility !== null) { - $this->_httpUtility = $utility; - } else { - $this->_httpUtility = new Zend_Oauth_Http_Utility; - } + $this->_httpUtility = $utility !== null ? $utility : new Zend_Oauth_Http_Utility; } /** @@ -90,13 +86,9 @@ public function __construct( */ public function isValid() { - if (isset($this->_params[self::TOKEN_PARAM_KEY]) + return isset($this->_params[self::TOKEN_PARAM_KEY]) && !empty($this->_params[self::TOKEN_PARAM_KEY]) - && isset($this->_params[self::TOKEN_SECRET_PARAM_KEY]) - ) { - return true; - } - return false; + && isset($this->_params[self::TOKEN_SECRET_PARAM_KEY]); } /** diff --git a/library/Zend/Oauth/Token/AuthorizedRequest.php b/library/Zend/Oauth/Token/AuthorizedRequest.php index 9ae2bbb032..b513c57df8 100644 --- a/library/Zend/Oauth/Token/AuthorizedRequest.php +++ b/library/Zend/Oauth/Token/AuthorizedRequest.php @@ -47,15 +47,11 @@ public function __construct(array $data = null, Zend_Oauth_Http_Utility $utility if ($data !== null) { $this->_data = $data; $params = $this->_parseData(); - if (count($params) > 0) { + if ($params !== []) { $this->setParams($params); } } - if ($utility !== null) { - $this->_httpUtility = $utility; - } else { - $this->_httpUtility = new Zend_Oauth_Http_Utility; - } + $this->_httpUtility = $utility !== null ? $utility : new Zend_Oauth_Http_Utility; } /** @@ -75,12 +71,8 @@ public function getData() */ public function isValid() { - if (isset($this->_params[self::TOKEN_PARAM_KEY]) - && !empty($this->_params[self::TOKEN_PARAM_KEY]) - ) { - return true; - } - return false; + return isset($this->_params[self::TOKEN_PARAM_KEY]) + && !empty($this->_params[self::TOKEN_PARAM_KEY]); } /** diff --git a/library/Zend/OpenId.php b/library/Zend/OpenId.php index abf2b73e37..5b4564efa6 100644 --- a/library/Zend/OpenId.php +++ b/library/Zend/OpenId.php @@ -108,7 +108,7 @@ static public function selfUrl() $url = substr($_SERVER['HTTP_HOST'], 0, $pos); $port = substr($_SERVER['HTTP_HOST'], $pos); } - } else if (isset($_SERVER['SERVER_NAME'])) { + } elseif (isset($_SERVER['SERVER_NAME'])) { $url = $_SERVER['SERVER_NAME']; if (isset($_SERVER['SERVER_PORT'])) { $port = ':' . $_SERVER['SERVER_PORT']; @@ -140,13 +140,13 @@ static public function selfUrl() } else { $url .= substr($_SERVER['REQUEST_URI'], 0, $query); } - } else if (isset($_SERVER['SCRIPT_URL'])) { + } elseif (isset($_SERVER['SCRIPT_URL'])) { $url .= $_SERVER['SCRIPT_URL']; - } else if (isset($_SERVER['REDIRECT_URL'])) { + } elseif (isset($_SERVER['REDIRECT_URL'])) { $url .= $_SERVER['REDIRECT_URL']; - } else if (isset($_SERVER['PHP_SELF'])) { + } elseif (isset($_SERVER['PHP_SELF'])) { $url .= $_SERVER['PHP_SELF']; - } else if (isset($_SERVER['SCRIPT_NAME'])) { + } elseif (isset($_SERVER['SCRIPT_NAME'])) { $url .= $_SERVER['SCRIPT_NAME']; if (isset($_SERVER['PATH_INFO'])) { $url .= $_SERVER['PATH_INFO']; @@ -165,32 +165,30 @@ static public function absoluteUrl($url) { if (empty($url)) { return Zend_OpenId::selfUrl(); - } else if (!preg_match('|^([^:]+)://|', $url)) { - if (preg_match('|^([^:]+)://([^:@]*(?:[:][^@]*)?@)?([^/:@?#]*)(?:[:]([^/?#]*))?(/[^?]*)?((?:[?](?:[^#]*))?(?:#.*)?)$|', Zend_OpenId::selfUrl(), $reg)) { - $scheme = $reg[1]; - $auth = $reg[2]; - $host = $reg[3]; - $port = $reg[4]; - $path = $reg[5]; - $query = $reg[6]; - if ($url[0] == '/') { - return $scheme - . '://' - . $auth - . $host - . (empty($port) ? '' : (':' . $port)) - . $url; - } else { - $dir = dirname($path); - return $scheme - . '://' - . $auth - . $host - . (empty($port) ? '' : (':' . $port)) - . (strlen($dir) > 1 ? $dir : '') - . '/' - . $url; - } + } elseif (!preg_match('|^([^:]+)://|', $url) && preg_match('|^([^:]+)://([^:@]*(?:[:][^@]*)?@)?([^/:@?#]*)(?:[:]([^/?#]*))?(/[^?]*)?((?:[?](?:[^#]*))?(?:#.*)?)$|', Zend_OpenId::selfUrl(), $reg)) { + $scheme = $reg[1]; + $auth = $reg[2]; + $host = $reg[3]; + $port = $reg[4]; + $path = $reg[5]; + $query = $reg[6]; + if ($url[0] == '/') { + return $scheme + . '://' + . $auth + . $host + . (empty($port) ? '' : (':' . $port)) + . $url; + } else { + $dir = dirname($path); + return $scheme + . '://' + . $auth + . $host + . (empty($port) ? '' : (':' . $port)) + . (strlen($dir) > 1 ? $dir : '') + . '/' + . $url; } } return $url; @@ -238,9 +236,9 @@ static public function normalizeUrl(&$id) ++$i; if ($id[$i] >= '0' && $id[$i] <= '9') { $c = ord($id[$i]) - ord('0'); - } else if ($id[$i] >= 'A' && $id[$i] <= 'F') { + } elseif ($id[$i] >= 'A' && $id[$i] <= 'F') { $c = ord($id[$i]) - ord('A') + 10; - } else if ($id[$i] >= 'a' && $id[$i] <= 'f') { + } elseif ($id[$i] >= 'a' && $id[$i] <= 'f') { $c = ord($id[$i]) - ord('a') + 10; } else { return false; @@ -248,9 +246,9 @@ static public function normalizeUrl(&$id) ++$i; if ($id[$i] >= '0' && $id[$i] <= '9') { $c = ($c << 4) | (ord($id[$i]) - ord('0')); - } else if ($id[$i] >= 'A' && $id[$i] <= 'F') { + } elseif ($id[$i] >= 'A' && $id[$i] <= 'F') { $c = ($c << 4) | (ord($id[$i]) - ord('A') + 10); - } else if ($id[$i] >= 'a' && $id[$i] <= 'f') { + } elseif ($id[$i] >= 'a' && $id[$i] <= 'f') { $c = ($c << 4) | (ord($id[$i]) - ord('a') + 10); } else { return false; @@ -271,7 +269,7 @@ static public function normalizeUrl(&$id) } else { $res .= chr(($c >> 4) - 10 + ord('A')); } - $c = $c & 0xf; + $c &= 0xf; if ($c < 10) { $res .= chr($c + ord('0')); } else { @@ -317,14 +315,14 @@ static public function normalizeUrl(&$id) ++$i; if ($i < $n && $path[$i] == '.') { ++$i; - if ($i == $n || $path[$i] == '/') { + if ($i === $n || $path[$i] == '/') { if (($pos = strrpos($res, '/')) !== false) { $res = substr($res, 0, $pos); } } else { $res .= '/..'; } - } else if ($i != $n && $path[$i] != '/') { + } elseif ($i !== $n && $path[$i] != '/') { $res .= '/.'; } } else { @@ -342,10 +340,8 @@ static public function normalizeUrl(&$id) if ($port == 80) { $port = ''; } - } else if ($scheme == 'https') { - if ($port == 443) { - $port = ''; - } + } elseif ($scheme == 'https' && $port == 443) { + $port = ''; } if (empty($path)) { $path = '/'; @@ -386,16 +382,16 @@ static public function normalizeUrl(&$id) static public function normalize(&$id) { $id = trim($id); - if (strlen($id) === 0) { + if ($id === '') { return true; } // 7.2.1 if (strpos($id, 'xri://$ip*') === 0) { $id = substr($id, strlen('xri://$ip*')); - } else if (strpos($id, 'xri://$dns*') === 0) { + } elseif (strpos($id, 'xri://$dns*') === 0) { $id = substr($id, strlen('xri://$dns*')); - } else if (strpos($id, 'xri://') === 0) { + } elseif (strpos($id, 'xri://') === 0) { $id = substr($id, strlen('xri://')); } @@ -440,14 +436,14 @@ static public function redirect($url, $params = null, if ($method == 'POST') { $body = "\n"; $body .= "
\n"; - if (is_array($params) && count($params) > 0) { + if (is_array($params) && $params !== []) { foreach($params as $key => $value) { $body .= '\n"; } } $body .= "\n"; $body .= "
\n"; - } else if (is_array($params) && count($params) > 0) { + } elseif (is_array($params) && $params !== []) { if (strpos($url, '?') === false) { $url .= '?' . self::paramsToQuery($params); } else { @@ -456,7 +452,7 @@ static public function redirect($url, $params = null, } if (!empty($body)) { $response->setBody($body); - } else if (!$response->canSendHeaders()) { + } elseif (!$response->canSendHeaders()) { $response->setBody(""); @@ -497,14 +493,12 @@ static public function digest($func, $data) { if (function_exists('openssl_digest')) { return openssl_digest($data, $func, true); - } else if (function_exists('hash')) { + } elseif (function_exists('hash')) { return hash($func, $data, true); - } else if ($func === 'sha1') { + } elseif ($func === 'sha1') { return sha1($data, true); - } else if ($func === 'sha256') { - if (function_exists('mhash')) { - return mhash(MHASH_SHA256 , $data); - } + } elseif ($func === 'sha256' && function_exists('mhash')) { + return mhash(MHASH_SHA256 , $data); } require_once "Zend/OpenId/Exception.php"; throw new Zend_OpenId_Exception( @@ -553,7 +547,7 @@ static protected function binToBigNum($bin) { if (extension_loaded('gmp')) { return gmp_init(bin2hex($bin), 16); - } else if (extension_loaded('bcmath')) { + } elseif (extension_loaded('bcmath')) { $bn = 0; $len = Zend_OpenId::strlen($bin); for ($i = 0; $i < $len; $i++) { @@ -582,15 +576,15 @@ static protected function bigNumToBin($bn) $s = gmp_strval($bn, 16); if (strlen($s) % 2 != 0) { $s = '0' . $s; - } else if ($s[0] > '7') { + } elseif ($s[0] > '7') { $s = '00' . $s; } return pack("H*", $s); - } else if (extension_loaded('bcmath')) { + } elseif (extension_loaded('bcmath')) { $cmp = bccomp($bn, 0); if ($cmp == 0) { return "\0"; - } else if ($cmp < 0) { + } elseif ($cmp < 0) { require_once "Zend/OpenId/Exception.php"; throw new Zend_OpenId_Exception( 'Big integer arithmetic error', @@ -644,7 +638,7 @@ static public function createDhKey($p, $g, $priv_key = null) $bn_priv_key = self::binToBigNum($priv_key); if (extension_loaded('gmp')) { $bn_pub_key = gmp_powm($bn_g, $bn_priv_key, $bn_p); - } else if (extension_loaded('bcmath')) { + } elseif (extension_loaded('bcmath')) { $bn_pub_key = bcpowmod($bn_g, $bn_priv_key, $bn_p); } $pub_key = self::bigNumToBin($bn_pub_key); @@ -700,11 +694,11 @@ static public function computeDhSecret($pub_key, $dh) $ret = "\0" . $ret; } return $ret; - } else if (extension_loaded('gmp')) { + } elseif (extension_loaded('gmp')) { $bn_pub_key = self::binToBigNum($pub_key); $bn_secret = gmp_powm($bn_pub_key, $dh['priv_key'], $dh['p']); return self::bigNumToBin($bn_secret); - } else if (extension_loaded('bcmath')) { + } elseif (extension_loaded('bcmath')) { $bn_pub_key = self::binToBigNum($pub_key); $bn_secret = bcpowmod($bn_pub_key, $dh['priv_key'], $dh['p']); return self::bigNumToBin($bn_secret); diff --git a/library/Zend/OpenId/Consumer.php b/library/Zend/OpenId/Consumer.php index 37abf9c960..4472d5fcc9 100644 --- a/library/Zend/OpenId/Consumer.php +++ b/library/Zend/OpenId/Consumer.php @@ -203,18 +203,14 @@ public function verify($params, &$identity = "", $extensions = null) if (isset($params["openid_claimed_id"])) { $identity = $params["openid_claimed_id"]; - } else if (isset($params["openid_identity"])){ - $identity = $params["openid_identity"]; - } else { - $identity = ""; - } + } else $identity = isset($params["openid_identity"]) ? $params["openid_identity"] : ""; if ($version < 2.0 && !isset($params["openid_claimed_id"])) { if ($this->_session !== null) { if ($this->_session->identity === $identity) { $identity = $this->_session->claimed_id; } - } else if (defined('SID')) { + } elseif (defined('SID')) { if (isset($_SESSION["zend_openid"]["identity"]) && isset($_SESSION["zend_openid"]["claimed_id"]) && $_SESSION["zend_openid"]["identity"] === $identity) { @@ -257,7 +253,7 @@ public function verify($params, &$identity = "", $extensions = null) /* Ignore query part in openid.return_to */ $pos = strpos($params['openid_return_to'], '?'); if ($pos === false || - SUBSTR($params['openid_return_to'], 0 , $pos) != Zend_OpenId::selfUrl()) { + SUBSTR($params['openid_return_to'], 0 , $pos) !== Zend_OpenId::selfUrl()) { $this->_setError("Wrong openid.return_to '". $params['openid_return_to']."' != '" . Zend_OpenId::selfUrl() ."'"); @@ -272,22 +268,20 @@ public function verify($params, &$identity = "", $extensions = null) if (empty($params['openid_op_endpoint'])) { $this->_setError("Missing openid.op_endpoint"); return false; - /* OpenID 2.0 (11.3) Checking the Nonce */ - } else if (!$this->_storage->isUniqueNonce($params['openid_op_endpoint'], $params['openid_response_nonce'])) { + /* OpenID 2.0 (11.3) Checking the Nonce */ + } elseif (!$this->_storage->isUniqueNonce($params['openid_op_endpoint'], $params['openid_response_nonce'])) { $this->_setError("Duplicate openid.response_nonce"); return false; } } - if (!empty($params['openid_invalidate_handle'])) { - if ($this->_storage->getAssociationByHandle( - $params['openid_invalidate_handle'], - $url, - $macFunc, - $secret, - $expires)) { - $this->_storage->delAssociation($url); - } + if (!empty($params['openid_invalidate_handle']) && $this->_storage->getAssociationByHandle( + $params['openid_invalidate_handle'], + $url, + $macFunc, + $secret, + $expires)) { + $this->_storage->delAssociation($url); } if ($this->_storage->getAssociationByHandle( @@ -319,8 +313,7 @@ public function verify($params, &$identity = "", $extensions = null) foreach ($signed as $key) { $data .= $key . ':' . $params['openid_' . strtr($key,'.','_')] . "\n"; } - if (base64_decode($params['openid_sig']) == - Zend_OpenId::hashHmac($macFunc, $data, $secret)) { + if (base64_decode($params['openid_sig']) === Zend_OpenId::hashHmac($macFunc, $data, $secret)) { if (!Zend_OpenId_Extension::forAll($extensions, 'parseResponse', $params)) { $this->_setError("Extension::parseResponse failure"); return false; @@ -331,10 +324,10 @@ public function verify($params, &$identity = "", $extensions = null) if (!Zend_OpenId::normalize($id)) { $this->_setError("Normalization failed"); return false; - } else if (!$this->_discovery($id, $discovered_server, $discovered_version)) { + } elseif (!$this->_discovery($id, $discovered_server, $discovered_version)) { $this->_setError("Discovery failed: " . $this->getError()); return false; - } else if ((!empty($params['openid_identity']) && + } elseif ((!empty($params['openid_identity']) && $params["openid_identity"] != $id) || (!empty($params['openid_op_endpoint']) && $params['openid_op_endpoint'] != $discovered_server) || @@ -354,7 +347,7 @@ public function verify($params, &$identity = "", $extensions = null) /* Use dumb mode */ if (isset($params['openid_claimed_id'])) { $id = $params['openid_claimed_id']; - } else if (isset($params['openid_identity'])) { + } elseif (isset($params['openid_identity'])) { $id = $params['openid_identity']; } else { $this->_setError("Missing openid.claimed_id and openid.identity"); @@ -364,7 +357,7 @@ public function verify($params, &$identity = "", $extensions = null) if (!Zend_OpenId::normalize($id)) { $this->_setError("Normalization failed"); return false; - } else if (!$this->_discovery($id, $server, $discovered_version)) { + } elseif (!$this->_discovery($id, $server, $discovered_version)) { $this->_setError("Discovery failed: " . $this->getError()); return false; } @@ -383,9 +376,9 @@ public function verify($params, &$identity = "", $extensions = null) foreach ($params as $key => $val) { if (strpos($key, 'openid_ns_') === 0) { $key = 'openid.ns.' . substr($key, strlen('openid_ns_')); - } else if (strpos($key, 'openid_sreg_') === 0) { + } elseif (strpos($key, 'openid_sreg_') === 0) { $key = 'openid.sreg.' . substr($key, strlen('openid_sreg_')); - } else if (strpos($key, 'openid_') === 0) { + } elseif (strpos($key, 'openid_') === 0) { $key = 'openid.' . substr($key, strlen('openid_')); } $params2[$key] = $val; @@ -410,15 +403,13 @@ public function verify($params, &$identity = "", $extensions = null) } } $ret = $r; - if (!empty($ret['invalidate_handle'])) { - if ($this->_storage->getAssociationByHandle( - $ret['invalidate_handle'], - $url, - $macFunc, - $secret, - $expires)) { - $this->_storage->delAssociation($url); - } + if (!empty($ret['invalidate_handle']) && $this->_storage->getAssociationByHandle( + $ret['invalidate_handle'], + $url, + $macFunc, + $secret, + $expires)) { + $this->_storage->delAssociation($url); } if (isset($ret['is_valid']) && $ret['is_valid'] == 'true') { if (!Zend_OpenId_Extension::forAll($extensions, 'parseResponse', $params)) { @@ -625,7 +616,7 @@ protected function _associate($url, $version, $priv_key=null) if ($params['openid.session_type'] == 'DH-SHA256') { $params['openid.session_type'] = 'DH-SHA1'; $params['openid.assoc_type'] = 'HMAC-SHA1'; - } else if ($params['openid.session_type'] == 'DH-SHA1') { + } elseif ($params['openid.session_type'] == 'DH-SHA1') { $params['openid.session_type'] = 'no-encryption'; } else { $this->_setError("The OpenID service responded with: " . $ret['error_code']); @@ -665,7 +656,7 @@ protected function _associate($url, $version, $priv_key=null) if ($ret['assoc_type'] == 'HMAC-SHA1') { $macFunc = 'sha1'; - } else if ($ret['assoc_type'] == 'HMAC-SHA256' && + } elseif ($ret['assoc_type'] == 'HMAC-SHA256' && $version >= 2.0) { $macFunc = 'sha256'; } else { @@ -677,12 +668,12 @@ protected function _associate($url, $version, $priv_key=null) ($version >= 2.0 && $ret['session_type'] == 'no-encryption')) && isset($ret['mac_key'])) { $secret = base64_decode($ret['mac_key']); - } else if (isset($ret['session_type']) && + } elseif (isset($ret['session_type']) && $ret['session_type'] == 'DH-SHA1' && !empty($ret['dh_server_public']) && !empty($ret['enc_mac_key'])) { $dhFunc = 'sha1'; - } else if (isset($ret['session_type']) && + } elseif (isset($ret['session_type']) && $ret['session_type'] == 'DH-SHA256' && $version >= 2.0 && !empty($ret['dh_server_public']) && @@ -711,11 +702,9 @@ protected function _associate($url, $version, $priv_key=null) $this->_setError("The length of the sha1 secret must be 20"); return false; } - } else if ($macFunc == 'sha256') { - if (Zend_OpenId::strlen($secret) != 32) { - $this->_setError("The length of the sha256 secret must be 32"); - return false; - } + } elseif ($macFunc == 'sha256' && Zend_OpenId::strlen($secret) != 32) { + $this->_setError("The length of the sha256 secret must be 32"); + return false; } $this->_addAssociation( $url, @@ -762,7 +751,7 @@ protected function _discovery(&$id, &$server, &$version) $r)) { $XRDS = $r[3]; $version = 2.0; - $response = $this->_httpRequest($XRDS); + $response = $this->_httpRequest($XRDS); if (preg_match( '/([^\t]*)<\/URI>/i', (string) $response, @@ -774,28 +763,25 @@ protected function _discovery(&$id, &$server, &$version) else { $this->_setError("Unable to get URI for XRDS discovery"); } - } - - /* HTML-based discovery */ - else if (preg_match( + } elseif (preg_match( '/]*rel=(["\'])[ \t]*(?:[^ \t"\']+[ \t]+)*?openid2.provider[ \t]*[^"\']*\\1[^>]*href=(["\'])([^"\']+)\\2[^>]*\/?>/i', $response, $r)) { $version = 2.0; $server = $r[3]; - } else if (preg_match( + } elseif (preg_match( '/]*href=(["\'])([^"\']+)\\1[^>]*rel=(["\'])[ \t]*(?:[^ \t"\']+[ \t]+)*?openid2.provider[ \t]*[^"\']*\\3[^>]*\/?>/i', $response, $r)) { $version = 2.0; $server = $r[2]; - } else if (preg_match( + } elseif (preg_match( '/]*rel=(["\'])[ \t]*(?:[^ \t"\']+[ \t]+)*?openid.server[ \t]*[^"\']*\\1[^>]*href=(["\'])([^"\']+)\\2[^>]*\/?>/i', $response, $r)) { $version = 1.1; $server = $r[3]; - } else if (preg_match( + } elseif (preg_match( '/]*href=(["\'])([^"\']+)\\1[^>]*rel=(["\'])[ \t]*(?:[^ \t"\']+[ \t]+)*?openid.server[ \t]*[^"\']*\\3[^>]*\/?>/i', $response, $r)) { @@ -810,24 +796,22 @@ protected function _discovery(&$id, &$server, &$version) (string) $response, $r)) { $realId = $r[3]; - } else if (preg_match( + } elseif (preg_match( '/]*href=(["\'])([^"\']+)\\1[^>]*rel=(["\'])[ \t]*(?:[^ \t"\']+[ \t]+)*?openid2.local_id[ \t]*[^"\']*\\3[^>]*\/?>/i', (string) $response, $r)) { $realId = $r[2]; } - } else { - if (preg_match( - '/]*rel=(["\'])[ \t]*(?:[^ \t"\']+[ \t]+)*?openid.delegate[ \t]*[^"\']*\\1[^>]*href=(["\'])([^"\']+)\\2[^>]*\/?>/i', - (string) $response, - $r)) { - $realId = $r[3]; - } else if (preg_match( - '/]*href=(["\'])([^"\']+)\\1[^>]*rel=(["\'])[ \t]*(?:[^ \t"\']+[ \t]+)*?openid.delegate[ \t]*[^"\']*\\3[^>]*\/?>/i', - (string) $response, - $r)) { - $realId = $r[2]; - } + } elseif (preg_match( + '/]*rel=(["\'])[ \t]*(?:[^ \t"\']+[ \t]+)*?openid.delegate[ \t]*[^"\']*\\1[^>]*href=(["\'])([^"\']+)\\2[^>]*\/?>/i', + (string) $response, + $r)) { + $realId = $r[3]; + } elseif (preg_match( + '/]*href=(["\'])([^"\']+)\\1[^>]*rel=(["\'])[ \t]*(?:[^ \t"\']+[ \t]+)*?openid.delegate[ \t]*[^"\']*\\3[^>]*\/?>/i', + (string) $response, + $r)) { + $realId = $r[2]; } $expire = time() + 60 * 60; @@ -900,7 +884,7 @@ protected function _checkId($immediate, $id, $returnTo=null, $root=null, if ($this->_session !== null) { $this->_session->identity = $id; $this->_session->claimed_id = $claimedId; - } else if (defined('SID')) { + } elseif (defined('SID')) { $_SESSION["zend_openid"] = array( "identity" => $id, "claimed_id" => $claimedId); diff --git a/library/Zend/OpenId/Consumer/Storage/File.php b/library/Zend/OpenId/Consumer/Storage/File.php index a1a96b8540..119a9cf304 100644 --- a/library/Zend/OpenId/Consumer/Storage/File.php +++ b/library/Zend/OpenId/Consumer/Storage/File.php @@ -68,16 +68,14 @@ public function __construct($dir = null) $dir = $tmp . '/openid/consumer'; } $this->_dir = $dir; - if (!is_dir($this->_dir)) { - if (!@mkdir($this->_dir, 0700, 1)) { - /** - * @see Zend_OpenId_Exception - */ - require_once 'Zend/OpenId/Exception.php'; - throw new Zend_OpenId_Exception( - 'Cannot access storage directory ' . $dir, - Zend_OpenId_Exception::ERROR_STORAGE); - } + if (!is_dir($this->_dir) && !@mkdir($this->_dir, 0700, 1)) { + /** + * @see Zend_OpenId_Exception + */ + require_once 'Zend/OpenId/Exception.php'; + throw new Zend_OpenId_Exception( + 'Cannot access storage directory ' . $dir, + Zend_OpenId_Exception::ERROR_STORAGE); } if (($f = fopen($this->_dir.'/assoc.lock', 'w+')) === null) { /** @@ -485,11 +483,7 @@ public function purgeNonces($date=null) } unset($nonceFiles); } else { - if (is_string($date)) { - $time = time($date); - } else { - $time = $date; - } + $time = is_string($date) ? time() : $date; $nonceFiles = glob($this->_dir . '/nonce_*'); foreach ((array) $nonceFiles as $name) { if (filemtime($name) < $time) { diff --git a/library/Zend/OpenId/Extension.php b/library/Zend/OpenId/Extension.php index 8dbdd5d722..bf18eff911 100644 --- a/library/Zend/OpenId/Extension.php +++ b/library/Zend/OpenId/Extension.php @@ -52,7 +52,7 @@ static public function forAll($extensions, $func, &$params) return false; } } - } else if (!is_object($extensions) || + } elseif (!is_object($extensions) || !($extensions instanceof Zend_OpenId_Extension) || !$extensions->$func($params)) { return false; diff --git a/library/Zend/OpenId/Extension/Sreg.php b/library/Zend/OpenId/Extension/Sreg.php index 45617df45c..6828e3c6c3 100644 --- a/library/Zend/OpenId/Extension/Sreg.php +++ b/library/Zend/OpenId/Extension/Sreg.php @@ -120,7 +120,7 @@ public static function getSregProperties() */ public function prepareRequest(&$params) { - if (is_array($this->_props) && count($this->_props) > 0) { + if (is_array($this->_props) && $this->_props !== []) { foreach ($this->_props as $prop => $req) { if ($req) { if (isset($required)) { @@ -128,12 +128,10 @@ public function prepareRequest(&$params) } else { $required = $prop; } + } elseif (isset($optional)) { + $optional .= ','.$prop; } else { - if (isset($optional)) { - $optional .= ','.$prop; - } else { - $optional = $prop; - } + $optional = $prop; } } if ($this->_version >= 1.1) { @@ -168,11 +166,7 @@ public function parseRequest($params) } else { $this->_version= 1.0; } - if (!empty($params['openid_sreg_policy_url'])) { - $this->_policy_url = $params['openid_sreg_policy_url']; - } else { - $this->_policy_url = null; - } + $this->_policy_url = empty($params['openid_sreg_policy_url']) ? null : $params['openid_sreg_policy_url']; $props = array(); if (!empty($params['openid_sreg_optional'])) { foreach (explode(',', (string) $params['openid_sreg_optional']) as $prop) { @@ -193,7 +187,7 @@ public function parseRequest($params) } } - $this->_props = (count($props2) > 0) ? $props2 : null; + $this->_props = ($props2 !== []) ? $props2 : null; return true; } @@ -205,7 +199,7 @@ public function parseRequest($params) */ public function prepareResponse(&$params) { - if (is_array($this->_props) && count($this->_props) > 0) { + if (is_array($this->_props) && $this->_props !== []) { if ($this->_version >= 1.1) { $params['openid.ns.sreg'] = Zend_OpenId_Extension_Sreg::NAMESPACE_1_1; } @@ -239,7 +233,7 @@ public function parseResponse($params) $props[$prop] = $params['openid_sreg_' . $prop]; } } - if (isset($this->_props) && is_array($this->_props)) { + if ($this->_props !== null && is_array($this->_props)) { foreach (self::getSregProperties() as $prop) { if (isset($this->_props[$prop]) && $this->_props[$prop] && @@ -248,7 +242,7 @@ public function parseResponse($params) } } } - $this->_props = (count($props) > 0) ? $props : null; + $this->_props = ($props !== []) ? $props : null; return true; } @@ -275,14 +269,10 @@ public function getTrustData(&$data) */ public function checkTrustData($data) { - if (is_array($this->_props) && count($this->_props) > 0) { + if (is_array($this->_props) && $this->_props !== []) { $props = array(); $name = get_class(); - if (isset($data[$name])) { - $props = $data[$name]; - } else { - $props = array(); - } + $props = isset($data[$name]) ? $data[$name] : array(); $props2 = array(); foreach ($this->_props as $prop => $req) { if (empty($props[$prop])) { @@ -293,7 +283,7 @@ public function checkTrustData($data) $props2[$prop] = $props[$prop]; } } - $this->_props = (count($props2) > 0) ? $props2 : null; + $this->_props = ($props2 !== []) ? $props2 : null; } return true; } diff --git a/library/Zend/OpenId/Provider.php b/library/Zend/OpenId/Provider.php index 4549c57399..22e07d9df0 100644 --- a/library/Zend/OpenId/Provider.php +++ b/library/Zend/OpenId/Provider.php @@ -234,9 +234,9 @@ public function getSiteRoot($params) } if ($version >= 2.0 && isset($params['openid_realm'])) { $root = $params['openid_realm']; - } else if ($version < 2.0 && isset($params['openid_trust_root'])) { + } elseif ($version < 2.0 && isset($params['openid_trust_root'])) { $root = $params['openid_trust_root']; - } else if (isset($params['openid_return_to'])) { + } elseif (isset($params['openid_return_to'])) { $root = $params['openid_return_to']; } else { return false; @@ -339,7 +339,7 @@ public function handle($params=null, $extensions=null, if ($params === null) { if ($_SERVER["REQUEST_METHOD"] == "GET") { $params = $_GET; - } else if ($_SERVER["REQUEST_METHOD"] == "POST") { + } elseif ($_SERVER["REQUEST_METHOD"] == "POST") { $params = $_POST; } else { return false; @@ -358,21 +358,21 @@ public function handle($params=null, $extensions=null, $ret .= $key . ':' . $val . "\n"; } return $ret; - } else if ($params['openid_mode'] == 'checkid_immediate') { + } elseif ($params['openid_mode'] == 'checkid_immediate') { $ret = $this->_checkId($version, $params, 1, $extensions, $response); if (is_bool($ret)) return $ret; if (!empty($params['openid_return_to'])) { Zend_OpenId::redirect($params['openid_return_to'], $ret, $response); } return true; - } else if ($params['openid_mode'] == 'checkid_setup') { + } elseif ($params['openid_mode'] == 'checkid_setup') { $ret = $this->_checkId($version, $params, 0, $extensions, $response); if (is_bool($ret)) return $ret; if (!empty($params['openid_return_to'])) { Zend_OpenId::redirect($params['openid_return_to'], $ret, $response); } return true; - } else if ($params['openid_mode'] == 'check_authentication') { + } elseif ($params['openid_mode'] == 'check_authentication') { $response = $this->_checkAuthentication($version, $params); $ret = ''; foreach ($response as $key => $val) { @@ -394,9 +394,11 @@ public function handle($params=null, $extensions=null, protected function _genSecret($func) { if ($func == 'sha1') { - $macLen = 20; /* 160 bit */ - } else if ($func == 'sha256') { - $macLen = 32; /* 256 bit */ + $macLen = 20; + /* 160 bit */ + } elseif ($func == 'sha256') { + $macLen = 32; + /* 256 bit */ } else { return false; } @@ -423,7 +425,7 @@ protected function _associate($version, $params) if (isset($params['openid_assoc_type']) && $params['openid_assoc_type'] == 'HMAC-SHA1') { $macFunc = 'sha1'; - } else if (isset($params['openid_assoc_type']) && + } elseif (isset($params['openid_assoc_type']) && $params['openid_assoc_type'] == 'HMAC-SHA256' && $version >= 2.0) { $macFunc = 'sha256'; @@ -440,10 +442,10 @@ protected function _associate($version, $params) if (empty($params['openid_session_type']) || $params['openid_session_type'] == 'no-encryption') { $ret['mac_key'] = base64_encode($secret); - } else if (isset($params['openid_session_type']) && + } elseif (isset($params['openid_session_type']) && $params['openid_session_type'] == 'DH-SHA1') { $dhFunc = 'sha1'; - } else if (isset($params['openid_session_type']) && + } elseif (isset($params['openid_session_type']) && $params['openid_session_type'] == 'DH-SHA256' && $version >= 2.0) { $dhFunc = 'sha256'; @@ -462,11 +464,7 @@ protected function _associate($version, $params) $ret['error'] = 'Wrong "openid.dh_consumer_public"'; return $ret; } - if (empty($params['openid_dh_gen'])) { - $g = pack('H*', Zend_OpenId::DH_G); - } else { - $g = base64_decode($params['openid_dh_gen']); - } + $g = empty($params['openid_dh_gen']) ? pack('H*', Zend_OpenId::DH_G) : base64_decode($params['openid_dh_gen']); if (empty($params['openid_dh_modulus'])) { $p = pack('H*', Zend_OpenId::DH_P); } else { @@ -537,9 +535,9 @@ protected function _checkId($version, $params, $immediate, $extensions=null, foreach ($params as $key => $val) { if (strpos($key, 'openid_ns_') === 0) { $key = 'openid.ns.' . substr($key, strlen('openid_ns_')); - } else if (strpos($key, 'openid_sreg_') === 0) { + } elseif (strpos($key, 'openid_sreg_') === 0) { $key = 'openid.sreg.' . substr($key, strlen('openid_sreg_')); - } else if (strpos($key, 'openid_') === 0) { + } elseif (strpos($key, 'openid_') === 0) { $key = 'openid.' . substr($key, strlen('openid_')); } $params2[$key] = $val; @@ -594,24 +592,22 @@ protected function _checkId($version, $params, $immediate, $extensions=null, } } - if (is_array($trusted)) { - if (!Zend_OpenId_Extension::forAll($extensions, 'checkTrustData', $trusted)) { - $trusted = null; - } + if (is_array($trusted) && !Zend_OpenId_Extension::forAll($extensions, 'checkTrustData', $trusted)) { + $trusted = null; } if ($trusted === false) { $ret['openid.mode'] = 'cancel'; return $ret; - } else if ($trusted === null) { + } elseif ($trusted === null) { /* Redirect to Server Trust Screen */ $params2 = array(); foreach ($params as $key => $val) { if (strpos($key, 'openid_ns_') === 0) { $key = 'openid.ns.' . substr($key, strlen('openid_ns_')); - } else if (strpos($key, 'openid_sreg_') === 0) { + } elseif (strpos($key, 'openid_sreg_') === 0) { $key = 'openid.sreg.' . substr($key, strlen('openid_sreg_')); - } else if (strpos($key, 'openid_') === 0) { + } elseif (strpos($key, 'openid_') === 0) { $key = 'openid.' . substr($key, strlen('openid_')); } $params2[$key] = $val; @@ -701,11 +697,7 @@ protected function _respond($version, $ret, $params, $extensions=null) } if ($version >= 2.0) { - if (!empty($this->_opEndpoint)) { - $ret['openid.op_endpoint'] = $this->_opEndpoint; - } else { - $ret['openid.op_endpoint'] = Zend_OpenId::selfUrl(); - } + $ret['openid.op_endpoint'] = empty($this->_opEndpoint) ? Zend_OpenId::selfUrl() : $this->_opEndpoint; } $ret['openid.response_nonce'] = gmdate('Y-m-d\TH:i:s\Z') . uniqid(); $ret['openid.mode'] = 'id_res'; diff --git a/library/Zend/OpenId/Provider/Storage/File.php b/library/Zend/OpenId/Provider/Storage/File.php index eff62cc321..13458f7f9d 100644 --- a/library/Zend/OpenId/Provider/Storage/File.php +++ b/library/Zend/OpenId/Provider/Storage/File.php @@ -68,12 +68,10 @@ public function __construct($dir = null) $dir = $tmp . '/openid/provider'; } $this->_dir = $dir; - if (!is_dir($this->_dir)) { - if (!@mkdir($this->_dir, 0700, 1)) { - throw new Zend_OpenId_Exception( - "Cannot access storage directory $dir", - Zend_OpenId_Exception::ERROR_STORAGE); - } + if (!is_dir($this->_dir) && !@mkdir($this->_dir, 0700, 1)) { + throw new Zend_OpenId_Exception( + "Cannot access storage directory $dir", + Zend_OpenId_Exception::ERROR_STORAGE); } if (($f = fopen($this->_dir.'/assoc.lock', 'w+')) === null) { throw new Zend_OpenId_Exception( diff --git a/library/Zend/OpenId/Provider/User/Session.php b/library/Zend/OpenId/Provider/User/Session.php index af071615c2..06d92c2123 100644 --- a/library/Zend/OpenId/Provider/User/Session.php +++ b/library/Zend/OpenId/Provider/User/Session.php @@ -58,11 +58,7 @@ class Zend_OpenId_Provider_User_Session extends Zend_OpenId_Provider_User */ public function __construct(Zend_Session_Namespace $session = null) { - if ($session === null) { - $this->_session = new Zend_Session_Namespace("openid"); - } else { - $this->_session = $session; - } + $this->_session = $session === null ? new Zend_Session_Namespace("openid") : $session; } /** @@ -84,7 +80,7 @@ public function setLoggedInUser($id) */ public function getLoggedInUser() { - if (isset($this->_session->logged_in)) { + if (property_exists($this->_session, 'logged_in') && $this->_session->logged_in !== null) { return $this->_session->logged_in; } return false; diff --git a/library/Zend/Paginator.php b/library/Zend/Paginator.php index 673d942736..30bd5345c4 100644 --- a/library/Zend/Paginator.php +++ b/library/Zend/Paginator.php @@ -276,13 +276,13 @@ public static function factory($data, $adapter = self::INTERNAL_ADAPTER, if ($adapter == self::INTERNAL_ADAPTER) { if (is_array($data)) { $adapter = 'Array'; - } else if ($data instanceof Zend_Db_Table_Select) { + } elseif ($data instanceof Zend_Db_Table_Select) { $adapter = 'DbTableSelect'; - } else if ($data instanceof Zend_Db_Select) { + } elseif ($data instanceof Zend_Db_Select) { $adapter = 'DbSelect'; - } else if ($data instanceof Iterator) { + } elseif ($data instanceof Iterator) { $adapter = 'Iterator'; - } else if (is_integer($data)) { + } elseif (is_int($data)) { $adapter = 'Null'; } else { $type = (is_object($data)) ? get_class($data) : gettype($data); @@ -450,7 +450,7 @@ public function __construct($adapter) { if ($adapter instanceof Zend_Paginator_Adapter_Interface) { $this->_adapter = $adapter; - } else if ($adapter instanceof Zend_Paginator_AdapterAggregate) { + } elseif ($adapter instanceof Zend_Paginator_AdapterAggregate) { $this->_adapter = $adapter->getPaginatorAdapter(); } else { /** @@ -488,8 +488,7 @@ public function __construct($adapter) public function __toString() { try { - $return = $this->render(); - return $return; + return $this->render(); } catch (Exception $e) { trigger_error($e->getMessage(), E_USER_WARNING); } @@ -514,9 +513,9 @@ public function setCacheEnabled($enable) * * @return integer */ - public function count() + public function count(): int { - if (!$this->_pageCount) { + if ($this->_pageCount === 0) { $this->_pageCount = $this->_calculatePageCount(); } @@ -689,7 +688,7 @@ public function getItem($itemNumber, $pageNumber = null) { if ($pageNumber == null) { $pageNumber = $this->getCurrentPageNumber(); - } else if ($pageNumber < 0) { + } elseif ($pageNumber < 0) { $pageNumber = ($this->count() + 1) + $pageNumber; } @@ -767,13 +766,7 @@ public function getItemCount($items) { $itemCount = 0; - if (is_array($items) || $items instanceof Countable) { - $itemCount = count($items); - } else { // $items is something like LimitIterator - $itemCount = iterator_count($items); - } - - return $itemCount; + return is_array($items) || $items instanceof Countable ? count($items) : iterator_count($items); } /** @@ -818,7 +811,7 @@ public function getItemsByPage($pageNumber) * * @return Traversable */ - public function getIterator() + public function getIterator(): Traversable { return $this->getCurrentItems(); } @@ -1146,8 +1139,7 @@ protected function _loadScrollingStyle($scrollingStyle = null) */ require_once 'Zend/View/Exception.php'; - throw new Zend_View_Exception('Scrolling style must implement ' . - 'Zend_Paginator_ScrollingStyle_Interface'); + throw new Zend_View_Exception('Scrolling style must implement Zend_Paginator_ScrollingStyle_Interface'); } return $scrollingStyle; @@ -1166,8 +1158,7 @@ protected function _loadScrollingStyle($scrollingStyle = null) */ require_once 'Zend/View/Exception.php'; - throw new Zend_View_Exception('Scrolling style must be a class ' . - 'name or object implementing Zend_Paginator_ScrollingStyle_Interface'); + throw new Zend_View_Exception('Scrolling style must be a class name or object implementing Zend_Paginator_ScrollingStyle_Interface'); } } } diff --git a/library/Zend/Paginator/Adapter/DbSelect.php b/library/Zend/Paginator/Adapter/DbSelect.php index 3a9a41cb70..62dbed24c6 100644 --- a/library/Zend/Paginator/Adapter/DbSelect.php +++ b/library/Zend/Paginator/Adapter/DbSelect.php @@ -118,17 +118,13 @@ public function setRowCount($rowCount) { if ($rowCount instanceof Zend_Db_Select) { $columns = $rowCount->getPart(Zend_Db_Select::COLUMNS); - $countColumnPart = empty($columns[0][2]) ? $columns[0][1] : $columns[0][2]; - if ($countColumnPart instanceof Zend_Db_Expr) { $countColumnPart = $countColumnPart->__toString(); } - $rowCountColumn = $this->_select->getAdapter()->foldCase(self::ROW_COUNT_COLUMN); - // The select query can contain only one column, which should be the row count column if (false === strpos($countColumnPart, $rowCountColumn)) { /** @@ -138,11 +134,9 @@ public function setRowCount($rowCount) throw new Zend_Paginator_Exception('Row count column not found'); } - $result = $rowCount->query(Zend_Db::FETCH_ASSOC)->fetch(); - $this->_rowCount = count($result) > 0 ? $result[$rowCountColumn] : 0; - } else if (is_integer($rowCount)) { + } elseif (is_int($rowCount)) { $this->_rowCount = $rowCount; } else { /** @@ -244,9 +238,8 @@ public function getCountSelect() ->select() ->bind($rowCount->getBind()) ->from($rowCount); - } else if ($isDistinct) { + } elseif ($isDistinct) { $part = $columnParts[0]; - if ($part[1] !== Zend_Db_Select::SQL_WILDCARD && !($part[1] instanceof Zend_Db_Expr)) { $column = $db->quoteIdentifier($part[1], true); @@ -256,7 +249,7 @@ public function getCountSelect() $groupPart = $column; } - } else if (!empty($groupParts)) { + } elseif (!empty($groupParts)) { $groupPart = $db->quoteIdentifier($groupParts[0], true); } diff --git a/library/Zend/Paginator/ScrollingStyle/Elastic.php b/library/Zend/Paginator/ScrollingStyle/Elastic.php index 35cf9964ed..30588c2765 100644 --- a/library/Zend/Paginator/ScrollingStyle/Elastic.php +++ b/library/Zend/Paginator/ScrollingStyle/Elastic.php @@ -54,7 +54,7 @@ public function getPages(Zend_Paginator $paginator, $pageRange = null) if ($originalPageRange + $pageNumber - 1 < $pageRange) { $pageRange = $originalPageRange + $pageNumber - 1; - } else if ($originalPageRange + $pageNumber - 1 > count($paginator)) { + } elseif ($originalPageRange + $pageNumber - 1 > count($paginator)) { $pageRange = $originalPageRange + count($paginator) - $pageNumber; } diff --git a/library/Zend/Pdf.php b/library/Zend/Pdf.php index 85c0050b35..6d171a4bdc 100644 --- a/library/Zend/Pdf.php +++ b/library/Zend/Pdf.php @@ -83,7 +83,8 @@ */ class Zend_Pdf { - /**** Class Constants ****/ + public string $_pdfHeaderVersion; + /**** Class Constants ****/ /** * Version number of generated PDF documents. @@ -480,7 +481,7 @@ protected function _loadPages(Zend_Pdf_Element_Reference $pages, $attributes = a foreach ($pages->Kids->items as $child) { if ($child->Type->value == 'Pages') { $this->_loadPages($child, $attributes); - } else if ($child->Type->value == 'Page') { + } elseif ($child->Type->value == 'Page') { foreach (self::$_inheritableAttributes as $property) { if ($child->$property === null && array_key_exists($property, $attributes)) { /** @@ -496,7 +497,6 @@ protected function _loadPages(Zend_Pdf_Element_Reference $pages, $attributes = a } } } - require_once 'Zend/Pdf/Page.php'; $this->pages[] = new Zend_Pdf_Page($child, $this->_objFactory); } @@ -528,19 +528,14 @@ protected function _loadNamedDestinations(Zend_Pdf_Element_Reference $root, $pdf $this->_namedTargets[$name] = Zend_Pdf_Target::load($destination); } } - } else { - // PDF version is 1.1 (or earlier) - // Look for Destinations sructure at Dest entry of document catalog - if ($root->Dests !== null) { - if ($root->Dests->getType() != Zend_Pdf_Element::TYPE_DICTIONARY) { - require_once 'Zend/Pdf/Exception.php'; - throw new Zend_Pdf_Exception('Document catalog Dests entry must be a dictionary.'); - } - - require_once 'Zend/Pdf/Target.php'; - foreach ($root->Dests->getKeys() as $destKey) { - $this->_namedTargets[$destKey] = Zend_Pdf_Target::load($root->Dests->$destKey); - } + } elseif ($root->Dests !== null) { + if ($root->Dests->getType() != Zend_Pdf_Element::TYPE_DICTIONARY) { + require_once 'Zend/Pdf/Exception.php'; + throw new Zend_Pdf_Exception('Document catalog Dests entry must be a dictionary.'); + } + require_once 'Zend/Pdf/Target.php'; + foreach ($root->Dests->getKeys() as $destKey) { + $this->_namedTargets[$destKey] = Zend_Pdf_Target::load($root->Dests->$destKey); } } } @@ -752,7 +747,7 @@ protected function _dumpPages() if ($this->resolveDestination($namedTarget, false) === null) { unset($this->_namedTargets[$name]); } - } else if ($namedTarget instanceof Zend_Pdf_Action) { + } elseif ($namedTarget instanceof Zend_Pdf_Action) { // Named target is an action if ($this->_cleanUpAction($namedTarget, false) === null) { // Action is a GoTo action with an unresolved destination @@ -776,7 +771,7 @@ protected function _dumpPages() if ($this->resolveDestination($target, false) === null) { $outline->setTarget(null); } - } else if ($target instanceof Zend_Pdf_Action) { + } elseif ($target instanceof Zend_Pdf_Action) { // Outline target is an action if ($this->_cleanUpAction($target, false) === null) { // Action is a GoTo action with an unresolved destination @@ -797,7 +792,7 @@ protected function _dumpPages() // Action is a GoTo action with an unresolved destination $this->setOpenAction(null); } - } else if ($openAction instanceof Zend_Pdf_Destination) { + } elseif ($openAction instanceof Zend_Pdf_Destination) { // OpenAction target is a destination if ($this->resolveDestination($openAction, false) === null) { $this->setOpenAction(null); @@ -862,10 +857,10 @@ protected function _dumpOutlines() } } else { $updateOutlinesNavigation = false; - if (count($this->_originalOutlines) != count($this->outlines)) { + if (count($this->_originalOutlines) !== count($this->outlines)) { // If original and current outlines arrays have different size then outlines list was updated $updateOutlinesNavigation = true; - } else if ( !(array_keys($this->_originalOutlines) === array_keys($this->outlines)) ) { + } elseif (array_keys($this->_originalOutlines) !== array_keys($this->outlines)) { // If original and current outlines arrays have different keys (with a glance to an order) then outlines list was updated $updateOutlinesNavigation = true; } else { @@ -1234,8 +1229,7 @@ public function extractFonts() foreach ($fontResources->getKeys() as $fontResourceName) { $fontDictionary = $fontResources->$fontResourceName; - if (! ($fontDictionary instanceof Zend_Pdf_Element_Reference || - $fontDictionary instanceof Zend_Pdf_Element_Object) ) { + if (!$fontDictionary instanceof Zend_Pdf_Element_Reference && !$fontDictionary instanceof Zend_Pdf_Element_Object ) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Font dictionary has to be an indirect object or object reference.'); } @@ -1289,8 +1283,7 @@ public function extractFont($fontName) foreach ($fontResources->getKeys() as $fontResourceName) { $fontDictionary = $fontResources->$fontResourceName; - if (! ($fontDictionary instanceof Zend_Pdf_Element_Reference || - $fontDictionary instanceof Zend_Pdf_Element_Object) ) { + if (!$fontDictionary instanceof Zend_Pdf_Element_Reference && !$fontDictionary instanceof Zend_Pdf_Element_Object ) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Font dictionary has to be an indirect object or object reference.'); } @@ -1342,7 +1335,7 @@ public function render($newSegmentOnly = false, $outputStream = null) } // Save document properties if necessary - if ($this->properties != $this->_originalProperties) { + if ($this->properties !== $this->_originalProperties) { $docInfo = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary()); foreach ($this->properties as $key => $value) { @@ -1384,7 +1377,7 @@ public function render($newSegmentOnly = false, $outputStream = null) case 'Creator': // break intentionally omitted case 'Producer': - if (extension_loaded('mbstring') === true) { + if (extension_loaded('mbstring')) { $detected = mb_detect_encoding($value); if ($detected !== 'ASCII') { $value = "\xfe\xff" . mb_convert_encoding($value, 'UTF-16', $detected); @@ -1572,11 +1565,7 @@ public function addJavaScript($javaScript) $javaScript = array($javaScript); } - if (null === $this->_javaScript) { - $this->_javaScript = $javaScript; - } else { - $this->_javaScript = array_merge($this->_javaScript, $javaScript); - } + $this->_javaScript = null === $this->_javaScript ? $javaScript : array_merge($this->_javaScript, $javaScript); if (!empty($this->_javaScript)) { $items = array(); @@ -1624,11 +1613,7 @@ public function addJavaScript($javaScript) */ public static function pdfDate($timestamp = null) { - if ($timestamp === null) { - $date = date('\D\:YmdHisO'); - } else { - $date = date('\D\:YmdHisO', $timestamp); - } + $date = $timestamp === null ? date('\D\:YmdHisO') : date('\D\:YmdHisO', $timestamp); return substr_replace($date, '\'', -2, 0) . '\''; } diff --git a/library/Zend/Pdf/Action.php b/library/Zend/Pdf/Action.php index 2b1864c46f..b7b3f9beed 100644 --- a/library/Zend/Pdf/Action.php +++ b/library/Zend/Pdf/Action.php @@ -40,6 +40,7 @@ */ abstract class Zend_Pdf_Action extends Zend_Pdf_Target implements RecursiveIterator, Countable { + public $childOutlines; /** * Action dictionary * @@ -86,7 +87,7 @@ public function __construct(Zend_Pdf_Element $dictionary, SplObjectStorage $proc $processedActions->attach($dictionary->Next); $this->next[] = Zend_Pdf_Action::load($dictionary->Next, $processedActions); } - } else if ($dictionary->Next instanceof Zend_Pdf_Element_Array) { + } elseif ($dictionary->Next instanceof Zend_Pdf_Element_Array) { foreach ($dictionary->Next->items as $chainedActionDictionary) { // Check if dictionary object is not already processed if (!$processedActions->contains($chainedActionDictionary)) { @@ -123,7 +124,7 @@ public static function load(Zend_Pdf_Element $dictionary, SplObjectStorage $proc require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('$dictionary mast be a direct or an indirect dictionary object.'); } - if (isset($dictionary->Type) && $dictionary->Type->value != 'Action') { + if (property_exists($dictionary, 'Type') && $dictionary->Type !== null && $dictionary->Type->value != 'Action') { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Action dictionary Type entry must be set to \'Action\'.'); } @@ -264,10 +265,10 @@ public function dumpAction(Zend_Pdf_ElementFactory_Interface $factory, SplObject $processedActions->attach($this); $childListUpdated = false; - if (count($this->_originalNextList) != count($this->next)) { + if (count($this->_originalNextList) !== count($this->next)) { // If original and current children arrays have different size then children list was updated $childListUpdated = true; - } else if ( !(array_keys($this->_originalNextList) === array_keys($this->next)) ) { + } elseif (array_keys($this->_originalNextList) !== array_keys($this->next)) { // If original and current children arrays have different keys (with a glance to an order) then children list was updated $childListUpdated = true; } else { @@ -384,7 +385,7 @@ public function getChildren() */ public function hasChildren() { - return count($this->next) > 0; + return $this->next !== []; } diff --git a/library/Zend/Pdf/Action/URI.php b/library/Zend/Pdf/Action/URI.php index 611a9a6ae6..ceb31ce918 100644 --- a/library/Zend/Pdf/Action/URI.php +++ b/library/Zend/Pdf/Action/URI.php @@ -140,11 +140,7 @@ public function setIsMap($isMap) { $this->_actionDictionary->touch(); - if ($isMap) { - $this->_actionDictionary->IsMap = new Zend_Pdf_Element_Boolean(true); - } else { - $this->_actionDictionary->IsMap = null; - } + $this->_actionDictionary->IsMap = $isMap ? new Zend_Pdf_Element_Boolean(true) : null; return $this; } diff --git a/library/Zend/Pdf/Canvas.php b/library/Zend/Pdf/Canvas.php index f320aa7258..d2134e6c80 100644 --- a/library/Zend/Pdf/Canvas.php +++ b/library/Zend/Pdf/Canvas.php @@ -31,6 +31,10 @@ */ class Zend_Pdf_Canvas extends Zend_Pdf_Canvas_Abstract { + /** + * @var array + */ + public array $_procset; /** * Canvas procedure sets. * diff --git a/library/Zend/Pdf/Canvas/Abstract.php b/library/Zend/Pdf/Canvas/Abstract.php index 556dd9a453..15063b1cf9 100644 --- a/library/Zend/Pdf/Canvas/Abstract.php +++ b/library/Zend/Pdf/Canvas/Abstract.php @@ -123,32 +123,16 @@ public function drawCanvas(Zend_Pdf_Canvas_Interface $canvas, $x1, $y1, $x2 = nu $this->translate($x1, $y1); - if ($x2 === null) { - $with = $canvas->getWidth(); - } else { - $with = $x2 - $x1; - } - if ($y2 === null) { - $height = $canvas->getHeight(); - } else { - $height = $y2 - $y1; - } + $with = $x2 === null ? $canvas->getWidth() : $x2 - $x1; + $height = $y2 === null ? $canvas->getHeight() : $y2 - $y1; $this->clipRectangle(0, 0, $with, $height); if ($x2 !== null || $y2 !== null) { // Drawn canvas has to be scaled. - if ($x2 !== null) { - $xScale = $with/$canvas->getWidth(); - } else { - $xScale = 1; - } + $xScale = $x2 !== null ? $with/$canvas->getWidth() : 1; - if ($y2 !== null) { - $yScale = $height/$canvas->getHeight(); - } else { - $yScale = 1; - } + $yScale = $y2 !== null ? $height/$canvas->getHeight() : 1; $this->scale($xScale, $yScale); } @@ -274,7 +258,7 @@ public function setStyle(Zend_Pdf_Style $style) if ($style->getFont() !== null) { $this->setFont($style->getFont(), $style->getFontSize()); } - $this->_contents .= $style->instructions($this->_dictionary->Resources); + $this->_contents .= $style->instructions(); $this->_style = $style; @@ -436,7 +420,7 @@ public function clipEllipse($x1, $y1, $x2, $y2, $startAngle = null, $endAngle = if ($startAngle !== null) { if ($startAngle != 0) { $startAngle = fmod($startAngle, M_PI*2); } - if ($endAngle != 0) { $endAngle = fmod($endAngle, M_PI*2); } + if ($endAngle != 0) { $endAngle = fmod($endAngle, M_PI*2); } if ($startAngle > $endAngle) { $endAngle += M_PI*2; @@ -609,7 +593,7 @@ public function drawEllipse($x1, $y1, $x2, $y2, $param5 = null, $param6 = null, // drawEllipse($x1, $y1, $x2, $y2); $startAngle = null; $fillType = Zend_Pdf_Page::SHAPE_DRAW_FILL_AND_STROKE; - } else if ($param6 === null) { + } elseif ($param6 === null) { // drawEllipse($x1, $y1, $x2, $y2, $fillType); $startAngle = null; $fillType = $param5; @@ -619,11 +603,7 @@ public function drawEllipse($x1, $y1, $x2, $y2, $param5 = null, $param6 = null, $startAngle = $param5; $endAngle = $param6; - if ($param7 === null) { - $fillType = Zend_Pdf_Page::SHAPE_DRAW_FILL_AND_STROKE; - } else { - $fillType = $param7; - } + $fillType = $param7 === null ? Zend_Pdf_Page::SHAPE_DRAW_FILL_AND_STROKE : $param7; } $this->_addProcSet('PDF'); @@ -647,7 +627,7 @@ public function drawEllipse($x1, $y1, $x2, $y2, $param5 = null, $param6 = null, if ($startAngle !== null) { if ($startAngle != 0) { $startAngle = fmod($startAngle, M_PI*2); } - if ($endAngle != 0) { $endAngle = fmod($endAngle, M_PI*2); } + if ($endAngle != 0) { $endAngle = fmod($endAngle, M_PI*2); } if ($startAngle > $endAngle) { $endAngle += M_PI*2; diff --git a/library/Zend/Pdf/Cmap.php b/library/Zend/Pdf/Cmap.php index 29ca4adab0..5769460a1f 100644 --- a/library/Zend/Pdf/Cmap.php +++ b/library/Zend/Pdf/Cmap.php @@ -269,7 +269,7 @@ abstract public function getCoveredCharactersGlyphs(); */ protected function _extractInt2(&$data, $index) { - if (($index < 0) | (($index + 1) > strlen($data))) { + if ((($index < 0) | (($index + 1) > strlen($data))) !== 0) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception("Index out of range: $index", Zend_Pdf_Exception::INDEX_OUT_OF_RANGE); @@ -296,13 +296,12 @@ protected function _extractInt2(&$data, $index) */ protected function _extractUInt2(&$data, $index) { - if (($index < 0) | (($index + 1) > strlen($data))) { + if ((($index < 0) | (($index + 1) > strlen($data))) !== 0) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception("Index out of range: $index", Zend_Pdf_Exception::INDEX_OUT_OF_RANGE); } - $number = (ord($data[$index]) << 8) | ord($data[++$index]); - return $number; + return (ord($data[$index]) << 8) | ord($data[++$index]); } /** @@ -323,14 +322,13 @@ protected function _extractUInt2(&$data, $index) */ protected function _extractUInt4(&$data, $index) { - if (($index < 0) | (($index + 3) > strlen($data))) { + if ((($index < 0) | (($index + 3) > strlen($data))) !== 0) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception("Index out of range: $index", Zend_Pdf_Exception::INDEX_OUT_OF_RANGE); } - $number = (ord($data[$index]) << 24) | (ord($data[++$index]) << 16) | + return (ord($data[$index]) << 24) | (ord($data[++$index]) << 16) | (ord($data[++$index]) << 8) | ord($data[++$index]); - return $number; } } diff --git a/library/Zend/Pdf/Cmap/SegmentToDelta.php b/library/Zend/Pdf/Cmap/SegmentToDelta.php index d72d3eb844..593addc123 100644 --- a/library/Zend/Pdf/Cmap/SegmentToDelta.php +++ b/library/Zend/Pdf/Cmap/SegmentToDelta.php @@ -138,11 +138,7 @@ public function glyphNumbersForCharacters($characterCodes) * If it is smaller, our target is probably above it, so move the * search range to the end of the segment list. */ - if ($this->_searchRangeEndCode >= $characterCode) { - $searchIndex = $this->_searchRange; - } else { - $searchIndex = $this->_segmentCount; - } + $searchIndex = $this->_searchRangeEndCode >= $characterCode ? $this->_searchRange : $this->_segmentCount; /* Now do a binary search to find the first segment whose end code * is greater or equal to our character code. No matter the number @@ -214,11 +210,7 @@ public function glyphNumberForCharacter($characterCode) return Zend_Pdf_Cmap::MISSING_CHARACTER_GLYPH; } - if ($this->_searchRangeEndCode >= $characterCode) { - $searchIndex = $this->_searchRange; - } else { - $searchIndex = $this->_segmentCount; - } + $searchIndex = $this->_searchRangeEndCode >= $characterCode ? $this->_searchRange : $this->_segmentCount; for ($i = 1; $i <= $this->_searchIterations; $i++) { if ($this->_segmentTableEndCodes[$searchIndex] >= $characterCode) { diff --git a/library/Zend/Pdf/Cmap/TrimmedTable.php b/library/Zend/Pdf/Cmap/TrimmedTable.php index a2f859e3da..4fee53d23e 100644 --- a/library/Zend/Pdf/Cmap/TrimmedTable.php +++ b/library/Zend/Pdf/Cmap/TrimmedTable.php @@ -205,7 +205,7 @@ public function __construct($cmapData) $entryCount = $this->_extractUInt2($cmapData, 8); $expectedCount = ($length - 10) >> 1; - if ($entryCount != $expectedCount) { + if ($entryCount !== $expectedCount) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception("Entry count is wrong; expected: $expectedCount; actual: $entryCount", Zend_Pdf_Exception::CMAP_WRONG_ENTRY_COUNT); diff --git a/library/Zend/Pdf/Color/Html.php b/library/Zend/Pdf/Color/Html.php index d1ba0f758b..a44ed91580 100644 --- a/library/Zend/Pdf/Color/Html.php +++ b/library/Zend/Pdf/Color/Html.php @@ -93,7 +93,7 @@ public static function color($color) $r = round((hexdec($matches[1]) / 255), 3); $g = round((hexdec($matches[2]) / 255), 3); $b = round((hexdec($matches[3]) / 255), 3); - if (($r == $g) && ($g == $b)) { + if (($r === $g) && ($g === $b)) { require_once 'Zend/Pdf/Color/GrayScale.php'; return new Zend_Pdf_Color_GrayScale($r); } else { diff --git a/library/Zend/Pdf/Destination/Fit.php b/library/Zend/Pdf/Destination/Fit.php index 1fb91d3275..48a2675479 100644 --- a/library/Zend/Pdf/Destination/Fit.php +++ b/library/Zend/Pdf/Destination/Fit.php @@ -61,7 +61,7 @@ public static function create($page) if ($page instanceof Zend_Pdf_Page) { $destinationArray->items[] = $page->getPageDictionary(); - } else if (is_integer($page)) { + } elseif (is_int($page)) { $destinationArray->items[] = new Zend_Pdf_Element_Numeric($page); } else { require_once 'Zend/Pdf/Exception.php'; diff --git a/library/Zend/Pdf/Destination/FitBoundingBox.php b/library/Zend/Pdf/Destination/FitBoundingBox.php index 11d7d0fcc1..db393235e6 100644 --- a/library/Zend/Pdf/Destination/FitBoundingBox.php +++ b/library/Zend/Pdf/Destination/FitBoundingBox.php @@ -61,7 +61,7 @@ public static function create($page) if ($page instanceof Zend_Pdf_Page) { $destinationArray->items[] = $page->getPageDictionary(); - } else if (is_integer($page)) { + } elseif (is_int($page)) { $destinationArray->items[] = new Zend_Pdf_Element_Numeric($page); } else { require_once 'Zend/Pdf/Exception.php'; diff --git a/library/Zend/Pdf/Destination/FitBoundingBoxHorizontally.php b/library/Zend/Pdf/Destination/FitBoundingBoxHorizontally.php index 3c65c69161..506f5571ba 100644 --- a/library/Zend/Pdf/Destination/FitBoundingBoxHorizontally.php +++ b/library/Zend/Pdf/Destination/FitBoundingBoxHorizontally.php @@ -61,7 +61,7 @@ public static function create($page, $top) if ($page instanceof Zend_Pdf_Page) { $destinationArray->items[] = $page->getPageDictionary(); - } else if (is_integer($page)) { + } elseif (is_int($page)) { $destinationArray->items[] = new Zend_Pdf_Element_Numeric($page); } else { require_once 'Zend/Pdf/Exception.php'; diff --git a/library/Zend/Pdf/Destination/FitBoundingBoxVertically.php b/library/Zend/Pdf/Destination/FitBoundingBoxVertically.php index 63b0edaef7..e24d6cc1c3 100644 --- a/library/Zend/Pdf/Destination/FitBoundingBoxVertically.php +++ b/library/Zend/Pdf/Destination/FitBoundingBoxVertically.php @@ -60,7 +60,7 @@ public static function create($page, $left) if ($page instanceof Zend_Pdf_Page) { $destinationArray->items[] = $page->getPageDictionary(); - } else if (is_integer($page)) { + } elseif (is_int($page)) { $destinationArray->items[] = new Zend_Pdf_Element_Numeric($page); } else { require_once 'Zend/Pdf/Exception.php'; diff --git a/library/Zend/Pdf/Destination/FitHorizontally.php b/library/Zend/Pdf/Destination/FitHorizontally.php index 758eacc67c..2f375e5897 100644 --- a/library/Zend/Pdf/Destination/FitHorizontally.php +++ b/library/Zend/Pdf/Destination/FitHorizontally.php @@ -60,7 +60,7 @@ public static function create($page, $top) if ($page instanceof Zend_Pdf_Page) { $destinationArray->items[] = $page->getPageDictionary(); - } else if (is_integer($page)) { + } elseif (is_int($page)) { $destinationArray->items[] = new Zend_Pdf_Element_Numeric($page); } else { require_once 'Zend/Pdf/Exception.php'; diff --git a/library/Zend/Pdf/Destination/FitRectangle.php b/library/Zend/Pdf/Destination/FitRectangle.php index 28309837e7..829b6d52b8 100644 --- a/library/Zend/Pdf/Destination/FitRectangle.php +++ b/library/Zend/Pdf/Destination/FitRectangle.php @@ -65,7 +65,7 @@ public static function create($page, $left, $bottom, $right, $top) if ($page instanceof Zend_Pdf_Page) { $destinationArray->items[] = $page->getPageDictionary(); - } else if (is_integer($page)) { + } elseif (is_int($page)) { $destinationArray->items[] = new Zend_Pdf_Element_Numeric($page); } else { require_once 'Zend/Pdf/Exception.php'; diff --git a/library/Zend/Pdf/Destination/FitVertically.php b/library/Zend/Pdf/Destination/FitVertically.php index a7a95c8783..0e7a3c1af5 100644 --- a/library/Zend/Pdf/Destination/FitVertically.php +++ b/library/Zend/Pdf/Destination/FitVertically.php @@ -60,7 +60,7 @@ public static function create($page, $left) if ($page instanceof Zend_Pdf_Page) { $destinationArray->items[] = $page->getPageDictionary(); - } else if (is_integer($page)) { + } elseif (is_int($page)) { $destinationArray->items[] = new Zend_Pdf_Element_Numeric($page); } else { require_once 'Zend/Pdf/Exception.php'; diff --git a/library/Zend/Pdf/Destination/Zoom.php b/library/Zend/Pdf/Destination/Zoom.php index a95bf7efcc..e3e799c787 100644 --- a/library/Zend/Pdf/Destination/Zoom.php +++ b/library/Zend/Pdf/Destination/Zoom.php @@ -64,7 +64,7 @@ public static function create($page, $left = null, $top = null, $zoom = null) if ($page instanceof Zend_Pdf_Page) { $destinationArray->items[] = $page->getPageDictionary(); - } else if (is_integer($page)) { + } elseif (is_int($page)) { $destinationArray->items[] = new Zend_Pdf_Element_Numeric($page); } else { require_once 'Zend/Pdf/Exception.php'; @@ -73,23 +73,11 @@ public static function create($page, $left = null, $top = null, $zoom = null) $destinationArray->items[] = new Zend_Pdf_Element_Name('XYZ'); - if ($left === null) { - $destinationArray->items[] = new Zend_Pdf_Element_Null(); - } else { - $destinationArray->items[] = new Zend_Pdf_Element_Numeric($left); - } + $destinationArray->items[] = $left === null ? new Zend_Pdf_Element_Null() : new Zend_Pdf_Element_Numeric($left); - if ($top === null) { - $destinationArray->items[] = new Zend_Pdf_Element_Null(); - } else { - $destinationArray->items[] = new Zend_Pdf_Element_Numeric($top); - } + $destinationArray->items[] = $top === null ? new Zend_Pdf_Element_Null() : new Zend_Pdf_Element_Numeric($top); - if ($zoom === null) { - $destinationArray->items[] = new Zend_Pdf_Element_Null(); - } else { - $destinationArray->items[] = new Zend_Pdf_Element_Numeric($zoom); - } + $destinationArray->items[] = $zoom === null ? new Zend_Pdf_Element_Null() : new Zend_Pdf_Element_Numeric($zoom); return new Zend_Pdf_Destination_Zoom($destinationArray); } @@ -139,11 +127,7 @@ public function getTopEdge() */ public function setTopEdge($top) { - if ($top === null) { - $this->_destinationArray->items[3] = new Zend_Pdf_Element_Null(); - } else { - $this->_destinationArray->items[3] = new Zend_Pdf_Element_Numeric($top); - } + $this->_destinationArray->items[3] = $top === null ? new Zend_Pdf_Element_Null() : new Zend_Pdf_Element_Numeric($top); return $this; } diff --git a/library/Zend/Pdf/Element.php b/library/Zend/Pdf/Element.php index 0486ac60d8..aaf6860b85 100644 --- a/library/Zend/Pdf/Element.php +++ b/library/Zend/Pdf/Element.php @@ -29,6 +29,7 @@ */ abstract class Zend_Pdf_Element { + public $value; const TYPE_BOOL = 1; const TYPE_NUMERIC = 2; const TYPE_STRING = 3; @@ -147,20 +148,18 @@ public static function phpToPdf($input) if (is_numeric($input)) { require_once 'Zend/Pdf/Element/Numeric.php'; return new Zend_Pdf_Element_Numeric($input); - } else if (is_bool($input)) { + } elseif (is_bool($input)) { require_once 'Zend/Pdf/Element/Boolean.php'; return new Zend_Pdf_Element_Boolean($input); - } else if (is_array($input)) { + } elseif (is_array($input)) { $pdfElementsArray = array(); $isDictionary = false; - foreach ($input as $key => $value) { if (is_string($key)) { $isDictionary = true; } $pdfElementsArray[$key] = Zend_Pdf_Element::phpToPdf($value); } - if ($isDictionary) { require_once 'Zend/Pdf/Element/Dictionary.php'; return new Zend_Pdf_Element_Dictionary($pdfElementsArray); diff --git a/library/Zend/Pdf/Element/Array.php b/library/Zend/Pdf/Element/Array.php index d301fc3b6d..433b4e0c2c 100644 --- a/library/Zend/Pdf/Element/Array.php +++ b/library/Zend/Pdf/Element/Array.php @@ -62,7 +62,7 @@ public function __construct($val = null) } $this->items[] = $element; } - } else if ($val !== null){ + } elseif ($val !== null) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Argument must be an array'); } @@ -123,9 +123,8 @@ public function toString($factory = null) $outStr .= $element->toString($factory) . ' '; } - $outStr .= ']'; - return $outStr; + return $outStr . ']'; } /** diff --git a/library/Zend/Pdf/Element/Dictionary.php b/library/Zend/Pdf/Element/Dictionary.php index 3d9cf96e8d..c3ca87f1ff 100644 --- a/library/Zend/Pdf/Element/Dictionary.php +++ b/library/Zend/Pdf/Element/Dictionary.php @@ -56,7 +56,7 @@ public function __construct($val = null) { if ($val === null) { return; - } else if (!is_array($val)) { + } elseif (!is_array($val)) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Argument must be an array'); } @@ -106,10 +106,8 @@ public function getKeys() */ public function __get($item) { - $element = isset($this->_items[$item]) ? $this->_items[$item] + return isset($this->_items[$item]) ? $this->_items[$item] : null; - - return $element; } /** @@ -163,9 +161,8 @@ public function toString($factory = null) $nameObj = new Zend_Pdf_Element_Name($name); $outStr .= $nameObj->toString($factory) . ' ' . $element->toString($factory) . ' '; } - $outStr .= '>>'; - return $outStr; + return $outStr . '>>'; } /** diff --git a/library/Zend/Pdf/Element/Name.php b/library/Zend/Pdf/Element/Name.php index fb589d4ab6..b7314f48c9 100644 --- a/library/Zend/Pdf/Element/Name.php +++ b/library/Zend/Pdf/Element/Name.php @@ -50,7 +50,7 @@ class Zend_Pdf_Element_Name extends Zend_Pdf_Element */ public function __construct($val) { - settype($val, 'string'); + $val = (string) $val; if (strpos($val,"\x00") !== false) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Null character is not allowed in PDF Names'); diff --git a/library/Zend/Pdf/Element/Numeric.php b/library/Zend/Pdf/Element/Numeric.php index 557f99cc1f..f79de6ad7d 100644 --- a/library/Zend/Pdf/Element/Numeric.php +++ b/library/Zend/Pdf/Element/Numeric.php @@ -78,7 +78,7 @@ public function getType() */ public function toString($factory = null) { - if (is_integer($this->value)) { + if (is_int($this->value)) { return (string)$this->value; } diff --git a/library/Zend/Pdf/Element/Object.php b/library/Zend/Pdf/Element/Object.php index 44fbf37be9..26476f3856 100644 --- a/library/Zend/Pdf/Element/Object.php +++ b/library/Zend/Pdf/Element/Object.php @@ -78,12 +78,12 @@ public function __construct(Zend_Pdf_Element $val, $objNum, $genNum, Zend_Pdf_El throw new Zend_Pdf_Exception('Object number must not be an instance of Zend_Pdf_Element_Object.'); } - if ( !(is_integer($objNum) && $objNum > 0) ) { + if ( !(is_int($objNum) && $objNum > 0) ) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Object number must be positive integer.'); } - if ( !(is_integer($genNum) && $genNum >= 0) ) { + if ( !(is_int($genNum) && $genNum >= 0) ) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Generation number must be non-negative integer.'); } @@ -150,11 +150,7 @@ public function getGenNum() */ public function toString($factory = null) { - if ($factory === null) { - $shift = 0; - } else { - $shift = $factory->getEnumerationShift($this->_factory); - } + $shift = $factory === null ? 0 : $factory->getEnumerationShift($this->_factory); return $this->_objNum + $shift . ' ' . $this->_genNum . ' R'; } diff --git a/library/Zend/Pdf/Element/Object/Stream.php b/library/Zend/Pdf/Element/Object/Stream.php index d92daab86f..afe5e9069b 100644 --- a/library/Zend/Pdf/Element/Object/Stream.php +++ b/library/Zend/Pdf/Element/Object/Stream.php @@ -104,22 +104,20 @@ private function _extractDictionaryData() $dictionaryArray['DecodeParms'] = array(); if ($this->_dictionary->Filter === null) { // Do nothing. - } else if ($this->_dictionary->Filter->getType() == Zend_Pdf_Element::TYPE_ARRAY) { + } elseif ($this->_dictionary->Filter->getType() == Zend_Pdf_Element::TYPE_ARRAY) { foreach ($this->_dictionary->Filter->items as $id => $filter) { $dictionaryArray['Filter'][$id] = $filter->value; $dictionaryArray['DecodeParms'][$id] = array(); - if ($this->_dictionary->DecodeParms !== null ) { - if ($this->_dictionary->DecodeParms->items[$id] !== null && - $this->_dictionary->DecodeParms->items[$id]->value !== null ) { - foreach ($this->_dictionary->DecodeParms->items[$id]->getKeys() as $paramKey) { - $dictionaryArray['DecodeParms'][$id][$paramKey] = - $this->_dictionary->DecodeParms->items[$id]->$paramKey->value; - } + if ($this->_dictionary->DecodeParms !== null && ($this->_dictionary->DecodeParms->items[$id] !== null && + $this->_dictionary->DecodeParms->items[$id]->value !== null) ) { + foreach ($this->_dictionary->DecodeParms->items[$id]->getKeys() as $paramKey) { + $dictionaryArray['DecodeParms'][$id][$paramKey] = + $this->_dictionary->DecodeParms->items[$id]->$paramKey->value; } } } - } else if ($this->_dictionary->Filter->getType() != Zend_Pdf_Element::TYPE_NULL) { + } elseif ($this->_dictionary->Filter->getType() != Zend_Pdf_Element::TYPE_NULL) { $dictionaryArray['Filter'][0] = $this->_dictionary->Filter->value; $dictionaryArray['DecodeParms'][0] = array(); if ($this->_dictionary->DecodeParms !== null ) { @@ -138,18 +136,16 @@ private function _extractDictionaryData() $dictionaryArray['FDecodeParms'] = array(); if ($this->_dictionary->FFilter === null) { // Do nothing. - } else if ($this->_dictionary->FFilter->getType() == Zend_Pdf_Element::TYPE_ARRAY) { + } elseif ($this->_dictionary->FFilter->getType() == Zend_Pdf_Element::TYPE_ARRAY) { foreach ($this->_dictionary->FFilter->items as $id => $filter) { $dictionaryArray['FFilter'][$id] = $filter->value; $dictionaryArray['FDecodeParms'][$id] = array(); - if ($this->_dictionary->FDecodeParms !== null ) { - if ($this->_dictionary->FDecodeParms->items[$id] !== null && - $this->_dictionary->FDecodeParms->items[$id]->value !== null) { - foreach ($this->_dictionary->FDecodeParms->items[$id]->getKeys() as $paramKey) { - $dictionaryArray['FDecodeParms'][$id][$paramKey] = - $this->_dictionary->FDecodeParms->items[$id]->items[$paramKey]->value; - } + if ($this->_dictionary->FDecodeParms !== null && ($this->_dictionary->FDecodeParms->items[$id] !== null && + $this->_dictionary->FDecodeParms->items[$id]->value !== null) ) { + foreach ($this->_dictionary->FDecodeParms->items[$id]->getKeys() as $paramKey) { + $dictionaryArray['FDecodeParms'][$id][$paramKey] = + $this->_dictionary->FDecodeParms->items[$id]->items[$paramKey]->value; } } } @@ -423,9 +419,8 @@ public function dump(Zend_Pdf_ElementFactory $factory) if ($this->_streamDecoded) { $this->_initialDictionaryData = $this->_extractDictionaryData(); $this->_encodeStream(); - } else if ($this->_initialDictionaryData != null) { + } elseif ($this->_initialDictionaryData != null) { $newDictionary = $this->_extractDictionaryData(); - if ($this->_initialDictionaryData !== $newDictionary) { $this->_decodeStream(); $this->_initialDictionaryData = $newDictionary; diff --git a/library/Zend/Pdf/Element/Reference.php b/library/Zend/Pdf/Element/Reference.php index 27ca760b7a..5fccc4f1f2 100644 --- a/library/Zend/Pdf/Element/Reference.php +++ b/library/Zend/Pdf/Element/Reference.php @@ -90,11 +90,11 @@ class Zend_Pdf_Element_Reference extends Zend_Pdf_Element */ public function __construct($objNum, $genNum = 0, Zend_Pdf_Element_Reference_Context $context, Zend_Pdf_ElementFactory $factory) { - if ( !(is_integer($objNum) && $objNum > 0) ) { + if ( !(is_int($objNum) && $objNum > 0) ) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Object number must be positive integer'); } - if ( !(is_integer($genNum) && $genNum >= 0) ) { + if ( !(is_int($genNum) && $genNum >= 0) ) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Generation number must be non-negative integer'); } @@ -140,11 +140,7 @@ public function getType() */ public function toString($factory = null) { - if ($factory === null) { - $shift = 0; - } else { - $shift = $factory->getEnumerationShift($this->_factory); - } + $shift = $factory === null ? 0 : $factory->getEnumerationShift($this->_factory); return $this->_objNum + $shift . ' ' . $this->_genNum . ' R'; } @@ -173,7 +169,7 @@ private function _dereference() return; } - if ($obj->toString() != $this->_objNum . ' ' . $this->_genNum . ' R') { + if ($obj->toString() !== $this->_objNum . ' ' . $this->_genNum . ' R') { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Incorrect reference to the object'); } diff --git a/library/Zend/Pdf/Element/Reference/Table.php b/library/Zend/Pdf/Element/Reference/Table.php index fa36262dbb..d036f0ccc1 100644 --- a/library/Zend/Pdf/Element/Reference/Table.php +++ b/library/Zend/Pdf/Element/Reference/Table.php @@ -136,7 +136,7 @@ public function getOffset($ref) return null; } - if (isset($this->_parent)) { + if ($this->_parent !== null) { return $this->_parent->getOffset($ref); } @@ -162,7 +162,7 @@ public function getNextFree($ref) return $this->_free[$ref]; } - if (isset($this->_parent)) { + if ($this->_parent !== null) { return $this->_parent->getNextFree($ref); } @@ -188,7 +188,7 @@ public function getNewGeneration($objNum) return $this->_generations[$objNum]; } - if (isset($this->_parent)) { + if ($this->_parent !== null) { return $this->_parent->getNewGeneration($objNum); } diff --git a/library/Zend/Pdf/Element/String.php b/library/Zend/Pdf/Element/String.php index c840166ec8..a42a1bb521 100644 --- a/library/Zend/Pdf/Element/String.php +++ b/library/Zend/Pdf/Element/String.php @@ -173,7 +173,7 @@ public static function unescape($str) while ($offset < strlen($str)) { // Searche for the next escaped character/sequence $escapeCharOffset = strpos($str, '\\', $offset); - if ($escapeCharOffset === false || $escapeCharOffset == strlen($str) - 1) { + if ($escapeCharOffset === false || $escapeCharOffset === strlen($str) - 1) { // There are no escaped characters or '\' char has came at the end of string $outEntries[] = substr($str, $offset); break; diff --git a/library/Zend/Pdf/FileParser.php b/library/Zend/Pdf/FileParser.php index 6e88d0997f..e79ad66de2 100644 --- a/library/Zend/Pdf/FileParser.php +++ b/library/Zend/Pdf/FileParser.php @@ -257,7 +257,7 @@ public function readInt($size, $byteOrder = Zend_Pdf_FileParser::BYTE_ORDER_BIG_ $number = ($number << 8) | ord($bytes[$i]); } } - } else if ($byteOrder == Zend_Pdf_FileParser::BYTE_ORDER_LITTLE_ENDIAN) { + } elseif ($byteOrder == Zend_Pdf_FileParser::BYTE_ORDER_LITTLE_ENDIAN) { $number = ord($bytes[$size - 1]); if (($number & 0x80) == 0x80) { /* Negative number. See discussion above. @@ -316,7 +316,7 @@ public function readUInt($size, $byteOrder = Zend_Pdf_FileParser::BYTE_ORDER_BIG for ($i = 1; $i < $size; $i++) { $number = ($number << 8) | ord($bytes[$i]); } - } else if ($byteOrder == Zend_Pdf_FileParser::BYTE_ORDER_LITTLE_ENDIAN) { + } elseif ($byteOrder == Zend_Pdf_FileParser::BYTE_ORDER_LITTLE_ENDIAN) { $number = 0; for ($i = --$size; $i >= 0; $i--) { $number |= ord($bytes[$i]) << ($i * 8); @@ -339,8 +339,7 @@ public function readUInt($size, $byteOrder = Zend_Pdf_FileParser::BYTE_ORDER_BIG public function isBitSet($bit, $bitField) { $bitMask = 1 << $bit; - $isSet = (($bitField & $bitMask) == $bitMask); - return $isSet; + return ($bitField & $bitMask) === $bitMask; } /** @@ -369,8 +368,7 @@ public function readFixed($mantissaBits, $fractionBits, throw new Zend_Pdf_Exception('Fixed-point numbers are whole bytes', Zend_Pdf_Exception::BAD_FIXED_POINT_SIZE); } - $number = $this->readInt(($bitsToRead >> 3), $byteOrder) / (1 << $fractionBits); - return $number; + return $this->readInt(($bitsToRead >> 3), $byteOrder) / (1 << $fractionBits); } /** @@ -411,7 +409,7 @@ public function readStringUTF16($byteCount, return $bytes; } return iconv('UTF-16BE', $characterSet, $bytes); - } else if ($byteOrder == Zend_Pdf_FileParser::BYTE_ORDER_LITTLE_ENDIAN) { + } elseif ($byteOrder == Zend_Pdf_FileParser::BYTE_ORDER_LITTLE_ENDIAN) { if ($characterSet == 'UTF-16LE') { return $bytes; } diff --git a/library/Zend/Pdf/FileParser/Font/OpenType.php b/library/Zend/Pdf/FileParser/Font/OpenType.php index d542599697..f3ea5263ef 100644 --- a/library/Zend/Pdf/FileParser/Font/OpenType.php +++ b/library/Zend/Pdf/FileParser/Font/OpenType.php @@ -316,9 +316,7 @@ protected function _parseNameTable() $platformID = $this->readUInt(2); $encodingID = $this->readUInt(2); - if (! ( (($platformID == 3) && ($encodingID == 1)) || // Microsoft Unicode - (($platformID == 1) && ($encodingID == 0)) // Mac Roman - ) ) { + if (!(($platformID == 3) && ($encodingID == 1)) && !(($platformID == 1) && ($encodingID == 0)) ) { $this->skipBytes(8); // Not a supported encoding. Move on. continue; } @@ -896,8 +894,7 @@ protected function _parseCmapTable() $cmapLength = $this->readUInt(2); $language = $this->readUInt(2); if ($language != 0) { - $this->_debugLog('Type 0 cmap tables must be language-independent;' - . ' language: %d; skipping', $language); + $this->_debugLog('Type 0 cmap tables must be language-independent; language: %d; skipping', $language); break; } break; @@ -907,8 +904,7 @@ protected function _parseCmapTable() $cmapLength = $this->readUInt(2); $language = $this->readUInt(2); if ($language != 0) { - $this->_debugLog('Warning: cmap tables must be language-independent - this font' - . ' may not work properly; language: %d', $language); + $this->_debugLog('Warning: cmap tables must be language-independent - this font may not work properly; language: %d', $language); } break; @@ -1050,7 +1046,8 @@ protected function _readTableVersion($minVersion, $maxVersion) */ protected function _languageCodeForPlatform($platformID, $languageID) { - if ($platformID == 3) { // Microsoft encoding. + if ($platformID == 3) { + // Microsoft encoding. /* The low-order bytes specify the language, the high-order bytes * specify the dialect. We just care about the language. For the * complete list, see: @@ -1092,8 +1089,8 @@ protected function _languageCodeForPlatform($platformID, $languageID) default: return null; } - - } else if ($platformID == 1) { // Macintosh encoding. + } elseif ($platformID == 1) { + // Macintosh encoding. switch ($languageID) { case 0: return 'en'; @@ -1129,7 +1126,6 @@ protected function _languageCodeForPlatform($platformID, $languageID) default: return null; } - } else { // Unknown encoding. return null; } diff --git a/library/Zend/Pdf/FileParser/Image/Png.php b/library/Zend/Pdf/FileParser/Image/Png.php index f2665ebcc5..dac8b1deb9 100644 --- a/library/Zend/Pdf/FileParser/Image/Png.php +++ b/library/Zend/Pdf/FileParser/Image/Png.php @@ -156,15 +156,11 @@ public function parse() protected function _parseSignature() { $this->moveToOffset(1); //Skip the first byte (%) - if('PNG' != $this->readBytes(3)) { - $this->_isPNG = false; - } else { - $this->_isPNG = true; - } + $this->_isPNG = 'PNG' == $this->readBytes(3); } protected function _checkSignature() { - if(!isset($this->_isPNG)) { + if(!($this->_isPNG !== null)) { $this->_parseSignature(); } return $this->_isPNG; @@ -235,7 +231,7 @@ protected function _parseIHDRChunk() { protected function _parseIDATChunk($chunkOffset, $chunkLength) { $this->moveToOffset($chunkOffset); - if(!isset($this->_imageData)) { + if(!($this->_imageData !== null)) { $this->_imageData = $this->readBytes($chunkLength); } else { $this->_imageData .= $this->readBytes($chunkLength); diff --git a/library/Zend/Pdf/FileParserDataSource.php b/library/Zend/Pdf/FileParserDataSource.php index 9a8fda5dfc..095721f310 100644 --- a/library/Zend/Pdf/FileParserDataSource.php +++ b/library/Zend/Pdf/FileParserDataSource.php @@ -155,7 +155,7 @@ public function getSize() */ public function moveToOffset($offset) { - if ($this->_offset == $offset) { + if ($this->_offset === $offset) { return; // Not moving; do nothing. } if ($offset < 0) { diff --git a/library/Zend/Pdf/FileParserDataSource/File.php b/library/Zend/Pdf/FileParserDataSource/File.php index 2e8c8eabc9..43280df57c 100644 --- a/library/Zend/Pdf/FileParserDataSource/File.php +++ b/library/Zend/Pdf/FileParserDataSource/File.php @@ -74,7 +74,7 @@ class Zend_Pdf_FileParserDataSource_File extends Zend_Pdf_FileParserDataSource */ public function __construct($filePath) { - if (! (is_file($filePath) || is_link($filePath))) { + if (!is_file($filePath) && !is_link($filePath)) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception("Invalid file path: $filePath", Zend_Pdf_Exception::BAD_FILE_PATH); @@ -178,7 +178,7 @@ public function __toString() */ public function moveToOffset($offset) { - if ($this->_offset == $offset) { + if ($this->_offset === $offset) { return; // Not moving; do nothing. } parent::moveToOffset($offset); diff --git a/library/Zend/Pdf/Filter/AsciiHex.php b/library/Zend/Pdf/Filter/AsciiHex.php index b48d9b5e2f..8d0bfe5183 100644 --- a/library/Zend/Pdf/Filter/AsciiHex.php +++ b/library/Zend/Pdf/Filter/AsciiHex.php @@ -92,11 +92,11 @@ public static function decode($data, $params = null) break; default: - if ($charCode >= 0x30 /*'0'*/ && $charCode <= 0x39 /*'9'*/) { + if ($charCode >= 0x30 /*'0'*/ && $charCode <= 0x39) { $code = $charCode - 0x30; - } else if ($charCode >= 0x41 /*'A'*/ && $charCode <= 0x46 /*'F'*/) { + } elseif ($charCode >= 0x41 /*'A'*/ && $charCode <= 0x46) { $code = $charCode - 0x37/*0x41 - 0x0A*/; - } else if ($charCode >= 0x61 /*'a'*/ && $charCode <= 0x66 /*'f'*/) { + } elseif ($charCode >= 0x61 /*'a'*/ && $charCode <= 0x66) { $code = $charCode - 0x57/*0x61 - 0x0A*/; } else { require_once 'Zend/Pdf/Exception.php'; diff --git a/library/Zend/Pdf/Filter/Compression.php b/library/Zend/Pdf/Filter/Compression.php index 422cf6fa5c..1ebf6cfc0a 100644 --- a/library/Zend/Pdf/Filter/Compression.php +++ b/library/Zend/Pdf/Filter/Compression.php @@ -52,7 +52,7 @@ private static function _paeth($a, $b, $c) // breaking ties in order a,b,c. if ($pa <= $pb && $pa <= $pc) { return $a; - } else if ($pb <= $pc) { + } elseif ($pb <= $pc) { return $b; } else { return $c; @@ -198,7 +198,7 @@ protected static function _applyEncodeParams($data, $params) { $output = ''; $offset = 0; - if (!is_integer($rows)) { + if (!is_int($rows)) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Wrong data length.'); } diff --git a/library/Zend/Pdf/Filter/RunLength.php b/library/Zend/Pdf/Filter/RunLength.php index b4c20a6cae..2b313dfb74 100644 --- a/library/Zend/Pdf/Filter/RunLength.php +++ b/library/Zend/Pdf/Filter/RunLength.php @@ -51,7 +51,7 @@ public static function encode($data, $params = null) // Do not encode 2 char chains since they produce 2 char run sequence, // but it takes more time to decode such output (because of processing additional run) if (($repeatedCharChainLength = strspn($data, $data[$offset], $offset + 1, 127) + 1) > 2) { - if ($chainStartOffset != $offset) { + if ($chainStartOffset !== $offset) { // Drop down previouse (non-repeatable chars) run $output .= chr($offset - $chainStartOffset - 1) . substr($data, $chainStartOffset, $offset - $chainStartOffset); @@ -79,9 +79,7 @@ public static function encode($data, $params = null) $output .= chr($offset - $chainStartOffset - 1) . substr($data, $chainStartOffset, $offset - $chainStartOffset); } - $output .= "\x80"; - - return $output; + return $output . "\x80"; } /** @@ -106,15 +104,12 @@ public static function decode($data, $params = null) if ($length == 128) { // EOD byte break; - } else if ($length < 128) { + } elseif ($length < 128) { $length++; - $output .= substr($data, $offset, $length); - $offset += $length; - } else if ($length > 128) { + } elseif ($length > 128) { $output .= str_repeat($data[$offset], 257 - $length); - $offset++; } } diff --git a/library/Zend/Pdf/Outline.php b/library/Zend/Pdf/Outline.php index 688a287a5b..c9c666d263 100644 --- a/library/Zend/Pdf/Outline.php +++ b/library/Zend/Pdf/Outline.php @@ -33,6 +33,11 @@ */ abstract class Zend_Pdf_Outline implements RecursiveIterator, Countable { + public $_title; + public $_color; + public $_italic; + public $_bold; + public $_target; /** * True if outline is open. * @@ -231,7 +236,7 @@ public static function create($param1, $param2 = null) { require_once 'Zend/Pdf/Outline/Created.php'; if (is_string($param1)) { - if ($param2 !== null && !($param2 instanceof Zend_Pdf_Target || is_string($param2))) { + if ($param2 !== null && (!$param2 instanceof Zend_Pdf_Target && !is_string($param2))) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Outline create method takes $title (string) and $target (Zend_Pdf_Target or string) or an array as an input'); } @@ -353,7 +358,7 @@ public function getChildren() */ public function hasChildren() { - return count($this->childOutlines) > 0; + return $this->childOutlines !== []; } diff --git a/library/Zend/Pdf/Outline/Created.php b/library/Zend/Pdf/Outline/Created.php index c319492c3c..30e905c0d9 100644 --- a/library/Zend/Pdf/Outline/Created.php +++ b/library/Zend/Pdf/Outline/Created.php @@ -261,9 +261,9 @@ public function dumpOutline(Zend_Pdf_ElementFactory_Interface $factory, $target = $this->getTarget(); if ($target === null) { // Do nothing - } else if ($target instanceof Zend_Pdf_Destination) { + } elseif ($target instanceof Zend_Pdf_Destination) { $outlineDictionary->Dest = $target->getResource(); - } else if ($target instanceof Zend_Pdf_Action) { + } elseif ($target instanceof Zend_Pdf_Action) { $outlineDictionary->A = $target->getResource(); } else { require_once 'Zend/Pdf/Exception.php'; diff --git a/library/Zend/Pdf/Outline/Loaded.php b/library/Zend/Pdf/Outline/Loaded.php index 1c3228c12e..1ecf5364dc 100644 --- a/library/Zend/Pdf/Outline/Loaded.php +++ b/library/Zend/Pdf/Outline/Loaded.php @@ -103,7 +103,7 @@ public function setIsOpen($isOpen) $childrenCount = $this->_outlineDictionary->Count->value; $isOpenCurrentState = ($childrenCount > 0); - if ($isOpen != $isOpenCurrentState) { + if ($isOpen !== $isOpenCurrentState) { $this->_outlineDictionary->Count->touch(); $this->_outlineDictionary->Count->value = ($isOpen? 1 : -1)*abs($childrenCount); } @@ -138,9 +138,9 @@ public function setIsItalic($isItalic) } else { $this->_outlineDictionary->F->touch(); if ($isItalic) { - $this->_outlineDictionary->F->value = $this->_outlineDictionary->F->value | 1; + $this->_outlineDictionary->F->value |= 1; } else { - $this->_outlineDictionary->F->value = $this->_outlineDictionary->F->value | ~1; + $this->_outlineDictionary->F->value |= ~1; } } return $this; @@ -173,9 +173,9 @@ public function setIsBold($isBold) } else { $this->_outlineDictionary->F->touch(); if ($isBold) { - $this->_outlineDictionary->F->value = $this->_outlineDictionary->F->value | 2; + $this->_outlineDictionary->F->value |= 2; } else { - $this->_outlineDictionary->F->value = $this->_outlineDictionary->F->value | ~2; + $this->_outlineDictionary->F->value |= ~2; } } return $this; @@ -236,10 +236,9 @@ public function getTarget() require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Outline dictionary may contain Dest or A entry, but not both.'); } - require_once 'Zend/Pdf/Destination.php'; return Zend_Pdf_Destination::load($this->_outlineDictionary->Dest); - } else if ($this->_outlineDictionary->A !== null) { + } elseif ($this->_outlineDictionary->A !== null) { require_once 'Zend/Pdf/Action.php'; return Zend_Pdf_Action::load($this->_outlineDictionary->A); } @@ -267,10 +266,10 @@ public function setTarget($target = null) if ($target === null) { $this->_outlineDictionary->Dest = null; $this->_outlineDictionary->A = null; - } else if ($target instanceof Zend_Pdf_Destination) { + } elseif ($target instanceof Zend_Pdf_Destination) { $this->_outlineDictionary->Dest = $target->getResource(); $this->_outlineDictionary->A = null; - } else if ($target instanceof Zend_Pdf_Action) { + } elseif ($target instanceof Zend_Pdf_Action) { $this->_outlineDictionary->Dest = null; $this->_outlineDictionary->A = $target->getResource(); } else { @@ -389,10 +388,10 @@ public function dumpOutline(Zend_Pdf_ElementFactory_Interface $factory, } $updateChildNavigation = false; - if (count($this->_originalChildOutlines) != count($this->childOutlines)) { + if (count($this->_originalChildOutlines) !== count($this->childOutlines)) { // If original and current children arrays have different size then children list was updated $updateChildNavigation = true; - } else if ( !(array_keys($this->_originalChildOutlines) === array_keys($this->childOutlines)) ) { + } elseif (array_keys($this->_originalChildOutlines) !== array_keys($this->childOutlines)) { // If original and current children arrays have different keys (with a glance to an order) then children list was updated $updateChildNavigation = true; } else { diff --git a/library/Zend/Pdf/Page.php b/library/Zend/Pdf/Page.php index 78b0c3de57..9ea11c621f 100644 --- a/library/Zend/Pdf/Page.php +++ b/library/Zend/Pdf/Page.php @@ -187,8 +187,7 @@ public function __construct($param1, $param2 = null, $param3 = null) $param1 instanceof Zend_Pdf_Element_Object ) && $param2 instanceof Zend_Pdf_ElementFactory_Interface && - $param3 === null - ) { + $param3 === null) { switch ($param1->getType()) { case Zend_Pdf_Element::TYPE_DICTIONARY: $this->_dictionary = $param1; @@ -209,16 +208,14 @@ public function __construct($param1, $param2 = null, $param3 = null) break; } - } else if ($param1 instanceof Zend_Pdf_Page && $param2 === null && $param3 === null) { + } elseif ($param1 instanceof Zend_Pdf_Page && $param2 === null && $param3 === null) { // Duplicate existing page. // Let already existing content and resources to be shared between pages // We don't give existing content modification functionality, so we don't need "deep copy" $this->_objFactory = $param1->_objFactory; $this->_attached = &$param1->_attached; $this->_safeGS = false; - $this->_dictionary = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary()); - foreach ($param1->_dictionary->getKeys() as $key) { if ($key == 'Contents') { // Clone Contents property @@ -238,9 +235,8 @@ public function __construct($param1, $param2 = null, $param3 = null) $this->_dictionary->$key = $param1->_dictionary->$key; } } - return; - } else if (is_string($param1) && + } elseif (is_string($param1) && ($param2 === null || $param2 instanceof Zend_Pdf_ElementFactory_Interface) && $param3 === null) { if ($param2 !== null) { @@ -250,8 +246,8 @@ public function __construct($param1, $param2 = null, $param3 = null) $this->_objFactory = Zend_Pdf_ElementFactory::createFactory(1); } $this->_attached = false; - $this->_safeGS = true; /** New page created. That's users App responsibility to track GS changes */ - + $this->_safeGS = true; + /** New page created. That's users App responsibility to track GS changes */ switch (strtolower($param1)) { case 'a4': $param1 = Zend_Pdf_Page::SIZE_A4; @@ -268,7 +264,6 @@ public function __construct($param1, $param2 = null, $param3 = null) default: // should be in "x:y" or "x:y:" form } - $pageDim = explode(':', $param1); if(count($pageDim) == 2 || count($pageDim) == 3) { $pageWidth = $pageDim[0]; @@ -284,8 +279,7 @@ public function __construct($param1, $param2 = null, $param3 = null) /** * @todo support of pagesize recalculation to "default user space units" */ - - } else if (is_numeric($param1) && is_numeric($param2) && + } elseif (is_numeric($param1) && is_numeric($param2) && ($param3 === null || $param3 instanceof Zend_Pdf_ElementFactory_Interface)) { if ($param3 !== null) { $this->_objFactory = $param3; @@ -293,12 +287,11 @@ public function __construct($param1, $param2 = null, $param3 = null) require_once 'Zend/Pdf/ElementFactory.php'; $this->_objFactory = Zend_Pdf_ElementFactory::createFactory(1); } - $this->_attached = false; - $this->_safeGS = true; /** New page created. That's users App responsibility to track GS changes */ + $this->_safeGS = true; + /** New page created. That's users App responsibility to track GS changes */ $pageWidth = $param1; $pageHeight = $param2; - } else { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Unrecognized method signature, wrong number of arguments or wrong argument types.'); @@ -657,8 +650,7 @@ public function extractFonts() foreach ($fontResources->getKeys() as $fontResourceName) { $fontDictionary = $fontResources->$fontResourceName; - if (! ($fontDictionary instanceof Zend_Pdf_Element_Reference || - $fontDictionary instanceof Zend_Pdf_Element_Object) ) { + if (!$fontDictionary instanceof Zend_Pdf_Element_Reference && !$fontDictionary instanceof Zend_Pdf_Element_Object ) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Font dictionary has to be an indirect object or object reference.'); } @@ -708,8 +700,7 @@ public function extractFont($fontName) foreach ($fontResources->getKeys() as $fontResourceName) { $fontDictionary = $fontResources->$fontResourceName; - if (! ($fontDictionary instanceof Zend_Pdf_Element_Reference || - $fontDictionary instanceof Zend_Pdf_Element_Object) ) { + if (!$fontDictionary instanceof Zend_Pdf_Element_Reference && !$fontDictionary instanceof Zend_Pdf_Element_Object ) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Font dictionary has to be an indirect object or object reference.'); } diff --git a/library/Zend/Pdf/Parser.php b/library/Zend/Pdf/Parser.php index 3908716dd2..1890d4f8fa 100644 --- a/library/Zend/Pdf/Parser.php +++ b/library/Zend/Pdf/Parser.php @@ -37,6 +37,7 @@ */ class Zend_Pdf_Parser { + public array $_refTable; /** * String parser * @@ -265,7 +266,8 @@ private function _loadXRefTable($offset) for ($count2 = 0; $count2 < $entries; $count2++) { if ($entryField1Size == 0) { $type = 1; - } else if ($entryField1Size == 1) { // Optimyze one-byte field case + } elseif ($entryField1Size == 1) { + // Optimyze one-byte field case $type = ord($xrefStreamData[$streamOffset++]); } else { $type = Zend_Pdf_StringParser::parseIntFromStream($xrefStreamData, $streamOffset, $entryField1Size); @@ -332,7 +334,7 @@ private function _loadXRefTable($offset) * It doesn't correspond to the actual data, but is true when trailer will be used * as a trailer for next generated PDF section. */ - $trailerObj->Prev = new Zend_Pdf_Element_Numeric($offset); + $trailerObj->setPrev(new Zend_Pdf_Element_Numeric($offset)); return $trailerObj; } diff --git a/library/Zend/Pdf/Resource/Font.php b/library/Zend/Pdf/Resource/Font.php index a0827d7aaa..53424d58ff 100644 --- a/library/Zend/Pdf/Resource/Font.php +++ b/library/Zend/Pdf/Resource/Font.php @@ -234,10 +234,8 @@ public function getFontName($nameType, $language, $characterSet = null) break; } } - } else { - if (isset($this->_fontNames[$nameType][$language])) { - $name = $this->_fontNames[$nameType][$language]; - } + } elseif (isset($this->_fontNames[$nameType][$language])) { + $name = $this->_fontNames[$nameType][$language]; } /* If the preferred language could not be found, use whatever is first. */ diff --git a/library/Zend/Pdf/Resource/Font/CidFont.php b/library/Zend/Pdf/Resource/Font/CidFont.php index dfee1aef4f..c4e23b0b0a 100644 --- a/library/Zend/Pdf/Resource/Font/CidFont.php +++ b/library/Zend/Pdf/Resource/Font/CidFont.php @@ -56,6 +56,10 @@ */ abstract class Zend_Pdf_Resource_Font_CidFont extends Zend_Pdf_Resource_Font { + /** + * @var mixed + */ + public $_isMonospaced; /** * Object representing the font's cmap (character to glyph map). * @var Zend_Pdf_Cmap @@ -166,7 +170,7 @@ public function __construct(Zend_Pdf_FileParser_Font_OpenType $fontParser) if ($lastCharCode == -1) { $charCodesSequense = array(); $sequenceStartCode = $charCode; - } else if ($charCode != $lastCharCode + 1) { + } elseif ($charCode != $lastCharCode + 1) { // New chracters sequence detected $widthsSequences[$sequenceStartCode] = $charCodesSequense; $charCodesSequense = array(); @@ -196,39 +200,31 @@ public function __construct(Zend_Pdf_FileParser_Font_OpenType $fontParser) $pdfCharsWidths[] = new Zend_Pdf_Element_Numeric($this->toEmSpace($lastWidth)); // Width // Reset widths sequence - $startCode = $startCode + $widthsInSequence; + $startCode += $widthsInSequence; $widthsInSequence = 0; } - // Collect new width $pdfWidths[] = new Zend_Pdf_Element_Numeric($this->toEmSpace($width)); - $lastWidth = $width; - } else { - // Width is equal to previous + } elseif (count($pdfWidths) != 0) { + // We already have some widths collected + // So, we've just detected new widths sequence + // Remove last element from widths list, since it's a part of widths sequence + array_pop($pdfWidths); + // and write the rest if it's not empty if (count($pdfWidths) != 0) { - // We already have some widths collected - // So, we've just detected new widths sequence - - // Remove last element from widths list, since it's a part of widths sequence - array_pop($pdfWidths); - - // and write the rest if it's not empty - if (count($pdfWidths) != 0) { - // Save it as 'c_1st [w1 w2 ... wn]'. - $pdfCharsWidths[] = new Zend_Pdf_Element_Numeric($startCode); // First character code - $pdfCharsWidths[] = new Zend_Pdf_Element_Array($pdfWidths); // Widths array - - // Reset widths collection - $startCode += count($pdfWidths); - $pdfWidths = array(); - } - - $widthsInSequence = 2; - } else { - // Continue widths sequence - $widthsInSequence++; + // Save it as 'c_1st [w1 w2 ... wn]'. + $pdfCharsWidths[] = new Zend_Pdf_Element_Numeric($startCode); // First character code + $pdfCharsWidths[] = new Zend_Pdf_Element_Array($pdfWidths); // Widths array + + // Reset widths collection + $startCode += count($pdfWidths); + $pdfWidths = array(); } + $widthsInSequence = 2; + } else { + // Continue widths sequence + $widthsInSequence++; } } @@ -236,14 +232,19 @@ public function __construct(Zend_Pdf_FileParser_Font_OpenType $fontParser) if (count($pdfWidths) != 0) { // We have some widths collected // Save it as 'c_1st [w1 w2 ... wn]'. - $pdfCharsWidths[] = new Zend_Pdf_Element_Numeric($startCode); // First character code - $pdfCharsWidths[] = new Zend_Pdf_Element_Array($pdfWidths); // Widths array - } else if ($widthsInSequence != 0){ + $pdfCharsWidths[] = new Zend_Pdf_Element_Numeric($startCode); + // First character code + $pdfCharsWidths[] = new Zend_Pdf_Element_Array($pdfWidths); + // Widths array + } elseif ($widthsInSequence != 0) { // We have widths sequence // Save it as 'c_1st c_last w'. - $pdfCharsWidths[] = new Zend_Pdf_Element_Numeric($startCode); // First character code - $pdfCharsWidths[] = new Zend_Pdf_Element_Numeric($startCode + $widthsInSequence - 1); // Last character code - $pdfCharsWidths[] = new Zend_Pdf_Element_Numeric($this->toEmSpace($lastWidth)); // Width + $pdfCharsWidths[] = new Zend_Pdf_Element_Numeric($startCode); + // First character code + $pdfCharsWidths[] = new Zend_Pdf_Element_Numeric($startCode + $widthsInSequence - 1); + // Last character code + $pdfCharsWidths[] = new Zend_Pdf_Element_Numeric($this->toEmSpace($lastWidth)); + // Width } } @@ -381,11 +382,7 @@ public function widthsForChars($charCodes) { $widths = array(); foreach ($charCodes as $key => $charCode) { - if (!isset($this->_charWidths[$charCode])) { - $widths[$key] = $this->_missingCharWidth; - } else { - $widths[$key] = $this->_charWidths[$charCode]; - } + $widths[$key] = isset($this->_charWidths[$charCode]) ? $this->_charWidths[$charCode] : $this->_missingCharWidth; } return $widths; } diff --git a/library/Zend/Pdf/Resource/Font/FontDescriptor.php b/library/Zend/Pdf/Resource/Font/FontDescriptor.php index bef833637a..9769f6305d 100644 --- a/library/Zend/Pdf/Resource/Font/FontDescriptor.php +++ b/library/Zend/Pdf/Resource/Font/FontDescriptor.php @@ -147,7 +147,7 @@ static public function factory(Zend_Pdf_Resource_Font $font, Zend_Pdf_FileParser * * First, the developer might specifically request not to embed the font. */ - if (!($embeddingOptions & Zend_Pdf_Font::EMBED_DONT_EMBED)) { + if (($embeddingOptions & Zend_Pdf_Font::EMBED_DONT_EMBED) === 0) { /* Second, the font author may have set copyright bits that prohibit * the font program from being embedded. Yes this is controversial, @@ -162,7 +162,7 @@ static public function factory(Zend_Pdf_Resource_Font $font, Zend_Pdf_FileParser /* This exception may be suppressed if the developer decides that * it's not a big deal that the font program can't be embedded. */ - if (!($embeddingOptions & Zend_Pdf_Font::EMBED_SUPPRESS_EMBED_EXCEPTION)) { + if (($embeddingOptions & Zend_Pdf_Font::EMBED_SUPPRESS_EMBED_EXCEPTION) === 0) { $message = 'This font cannot be embedded in the PDF document. If you would like to use ' . 'it anyway, you must pass Zend_Pdf_Font::EMBED_SUPPRESS_EMBED_EXCEPTION ' . 'in the $options parameter of the font constructor.'; @@ -183,15 +183,15 @@ static public function factory(Zend_Pdf_Resource_Font $font, Zend_Pdf_FileParser $fontFile = $fontParser->getDataSource()->readAllBytes(); $fontFileObject = $font->getFactory()->newStreamObject($fontFile); $fontFileObject->dictionary->Length1 = new Zend_Pdf_Element_Numeric(strlen($fontFile)); - if (!($embeddingOptions & Zend_Pdf_Font::EMBED_DONT_COMPRESS)) { + if (($embeddingOptions & Zend_Pdf_Font::EMBED_DONT_COMPRESS) === 0) { /* Compress the font file using Flate. This generally cuts file * sizes by about half! */ $fontFileObject->dictionary->Filter = new Zend_Pdf_Element_Name('FlateDecode'); } - if ($fontParser instanceof Zend_Pdf_FileParser_Font_OpenType_Type1 /* not implemented now */) { + if ($fontParser instanceof Zend_Pdf_FileParser_Font_OpenType_Type1) { $fontDescriptor->FontFile = $fontFileObject; - } else if ($fontParser instanceof Zend_Pdf_FileParser_Font_OpenType_TrueType) { + } elseif ($fontParser instanceof Zend_Pdf_FileParser_Font_OpenType_TrueType) { $fontDescriptor->FontFile2 = $fontFileObject; } else { $fontDescriptor->FontFile3 = $fontFileObject; diff --git a/library/Zend/Pdf/Resource/Font/Simple.php b/library/Zend/Pdf/Resource/Font/Simple.php index 9219bc8126..e987b00061 100644 --- a/library/Zend/Pdf/Resource/Font/Simple.php +++ b/library/Zend/Pdf/Resource/Font/Simple.php @@ -176,10 +176,9 @@ public function getCoveredPercentage($string, $charEncoding = '') /* Convert the string to UTF-16BE encoding so we can match the string's * character codes to those found in the cmap. */ - if ($charEncoding != 'UTF-16BE') { - if (PHP_OS != 'AIX') { // AIX doesnt know what UTF-16BE is - $string = iconv($charEncoding, 'UTF-16BE', $string); - } + if ($charEncoding != 'UTF-16BE' && PHP_OS != 'AIX') { + // AIX doesnt know what UTF-16BE is + $string = iconv($charEncoding, 'UTF-16BE', $string); } $charCount = (PHP_OS != 'AIX') ? iconv_strlen($string, 'UTF-16BE') : strlen((string) $string); diff --git a/library/Zend/Pdf/Resource/Font/Simple/Parsed.php b/library/Zend/Pdf/Resource/Font/Simple/Parsed.php index 5716d315af..309d6c03c8 100644 --- a/library/Zend/Pdf/Resource/Font/Simple/Parsed.php +++ b/library/Zend/Pdf/Resource/Font/Simple/Parsed.php @@ -42,6 +42,10 @@ */ abstract class Zend_Pdf_Resource_Font_Simple_Parsed extends Zend_Pdf_Resource_Font_Simple { + /** + * @var mixed + */ + public $_isMonospaced; /** * Object constructor * diff --git a/library/Zend/Pdf/Resource/Font/Simple/Standard/Courier.php b/library/Zend/Pdf/Resource/Font/Simple/Standard/Courier.php index 7bbf517d2e..22d9f7dc74 100644 Binary files a/library/Zend/Pdf/Resource/Font/Simple/Standard/Courier.php and b/library/Zend/Pdf/Resource/Font/Simple/Standard/Courier.php differ diff --git a/library/Zend/Pdf/Resource/Font/Simple/Standard/CourierBold.php b/library/Zend/Pdf/Resource/Font/Simple/Standard/CourierBold.php index 99788bb413..64a7a13c57 100644 Binary files a/library/Zend/Pdf/Resource/Font/Simple/Standard/CourierBold.php and b/library/Zend/Pdf/Resource/Font/Simple/Standard/CourierBold.php differ diff --git a/library/Zend/Pdf/Resource/Font/Simple/Standard/CourierBoldOblique.php b/library/Zend/Pdf/Resource/Font/Simple/Standard/CourierBoldOblique.php index 2f3527dd33..aee36b02ce 100644 Binary files a/library/Zend/Pdf/Resource/Font/Simple/Standard/CourierBoldOblique.php and b/library/Zend/Pdf/Resource/Font/Simple/Standard/CourierBoldOblique.php differ diff --git a/library/Zend/Pdf/Resource/Font/Simple/Standard/CourierOblique.php b/library/Zend/Pdf/Resource/Font/Simple/Standard/CourierOblique.php index 2f1766aaa5..7c5a962ae0 100644 Binary files a/library/Zend/Pdf/Resource/Font/Simple/Standard/CourierOblique.php and b/library/Zend/Pdf/Resource/Font/Simple/Standard/CourierOblique.php differ diff --git a/library/Zend/Pdf/Resource/Font/Simple/Standard/Helvetica.php b/library/Zend/Pdf/Resource/Font/Simple/Standard/Helvetica.php index c843bbf0c5..5158b54060 100644 Binary files a/library/Zend/Pdf/Resource/Font/Simple/Standard/Helvetica.php and b/library/Zend/Pdf/Resource/Font/Simple/Standard/Helvetica.php differ diff --git a/library/Zend/Pdf/Resource/Font/Simple/Standard/HelveticaBold.php b/library/Zend/Pdf/Resource/Font/Simple/Standard/HelveticaBold.php index 032d048ea4..6330518936 100644 Binary files a/library/Zend/Pdf/Resource/Font/Simple/Standard/HelveticaBold.php and b/library/Zend/Pdf/Resource/Font/Simple/Standard/HelveticaBold.php differ diff --git a/library/Zend/Pdf/Resource/Font/Simple/Standard/HelveticaBoldOblique.php b/library/Zend/Pdf/Resource/Font/Simple/Standard/HelveticaBoldOblique.php index 0ad846db4f..99b4de21c0 100644 Binary files a/library/Zend/Pdf/Resource/Font/Simple/Standard/HelveticaBoldOblique.php and b/library/Zend/Pdf/Resource/Font/Simple/Standard/HelveticaBoldOblique.php differ diff --git a/library/Zend/Pdf/Resource/Font/Simple/Standard/HelveticaOblique.php b/library/Zend/Pdf/Resource/Font/Simple/Standard/HelveticaOblique.php index add19f95f4..e902daf95f 100644 Binary files a/library/Zend/Pdf/Resource/Font/Simple/Standard/HelveticaOblique.php and b/library/Zend/Pdf/Resource/Font/Simple/Standard/HelveticaOblique.php differ diff --git a/library/Zend/Pdf/Resource/Font/Simple/Standard/Symbol.php b/library/Zend/Pdf/Resource/Font/Simple/Standard/Symbol.php index 588fec9c98..c2a6af3caa 100644 --- a/library/Zend/Pdf/Resource/Font/Simple/Standard/Symbol.php +++ b/library/Zend/Pdf/Resource/Font/Simple/Standard/Symbol.php @@ -48,7 +48,8 @@ */ class Zend_Pdf_Resource_Font_Simple_Standard_Symbol extends Zend_Pdf_Resource_Font_Simple_Standard { - /**** Instance Variables ****/ + public bool $_isMonospaced; + /**** Instance Variables ****/ /** @@ -218,8 +219,7 @@ public function __construct() $this->_fontNames[Zend_Pdf_Font::NAME_ID]['en'] = "\x00\x34\x00\x33\x00\x30\x00\x36\x00\x34"; $this->_fontNames[Zend_Pdf_Font::NAME_FULL]['en'] = - "\x00\x53\x00\x79\x00\x6d\x00\x62\x00\x6f\x00\x6c\x00\x20\x00\x4d\x00" - . "\x65\x00\x64\x00\x69\x00\x75\x00\x6d"; + 'Symbol Medium'; $this->_fontNames[Zend_Pdf_Font::NAME_VERSION]['en'] = "\x00\x30\x00\x30\x00\x31\x00\x2e\x00\x30\x00\x30\x00\x38"; $this->_fontNames[Zend_Pdf_Font::NAME_POSTSCRIPT]['en'] = diff --git a/library/Zend/Pdf/Resource/Font/Simple/Standard/TimesBold.php b/library/Zend/Pdf/Resource/Font/Simple/Standard/TimesBold.php index d1ca475cdb..490330b1be 100644 Binary files a/library/Zend/Pdf/Resource/Font/Simple/Standard/TimesBold.php and b/library/Zend/Pdf/Resource/Font/Simple/Standard/TimesBold.php differ diff --git a/library/Zend/Pdf/Resource/Font/Simple/Standard/TimesBoldItalic.php b/library/Zend/Pdf/Resource/Font/Simple/Standard/TimesBoldItalic.php index 5a0bf0f8a7..80a89d9001 100644 Binary files a/library/Zend/Pdf/Resource/Font/Simple/Standard/TimesBoldItalic.php and b/library/Zend/Pdf/Resource/Font/Simple/Standard/TimesBoldItalic.php differ diff --git a/library/Zend/Pdf/Resource/Font/Simple/Standard/TimesItalic.php b/library/Zend/Pdf/Resource/Font/Simple/Standard/TimesItalic.php index 6d9d4fb4cb..9507021a65 100644 Binary files a/library/Zend/Pdf/Resource/Font/Simple/Standard/TimesItalic.php and b/library/Zend/Pdf/Resource/Font/Simple/Standard/TimesItalic.php differ diff --git a/library/Zend/Pdf/Resource/Font/Simple/Standard/TimesRoman.php b/library/Zend/Pdf/Resource/Font/Simple/Standard/TimesRoman.php index baf8ffc7a6..c9b4dc02b0 100644 Binary files a/library/Zend/Pdf/Resource/Font/Simple/Standard/TimesRoman.php and b/library/Zend/Pdf/Resource/Font/Simple/Standard/TimesRoman.php differ diff --git a/library/Zend/Pdf/Resource/Font/Simple/Standard/ZapfDingbats.php b/library/Zend/Pdf/Resource/Font/Simple/Standard/ZapfDingbats.php index 042ddf2f9d..70a557e413 100644 --- a/library/Zend/Pdf/Resource/Font/Simple/Standard/ZapfDingbats.php +++ b/library/Zend/Pdf/Resource/Font/Simple/Standard/ZapfDingbats.php @@ -48,7 +48,8 @@ */ class Zend_Pdf_Resource_Font_Simple_Standard_ZapfDingbats extends Zend_Pdf_Resource_Font_Simple_Standard { - /**** Instance Variables ****/ + public bool $_isMonospaced; + /**** Instance Variables ****/ /** @@ -229,21 +230,17 @@ public function __construct() . "\x20\x00\x43\x00\x6f\x00\x72\x00\x70\x00\x6f\x00\x72\x00\x61\x00" . "\x74\x00\x69\x00\x6f\x00\x6e\x00\x2e"; $this->_fontNames[Zend_Pdf_Font::NAME_FAMILY]['en'] = - "\x00\x5a\x00\x61\x00\x70\x00\x66\x00\x44\x00\x69\x00\x6e\x00\x67\x00" - . "\x62\x00\x61\x00\x74\x00\x73"; + 'ZapfDingbats'; $this->_fontNames[Zend_Pdf_Font::NAME_STYLE]['en'] = "\x00\x4d\x00\x65\x00\x64\x00\x69\x00\x75\x00\x6d"; $this->_fontNames[Zend_Pdf_Font::NAME_ID]['en'] = "\x00\x34\x00\x33\x00\x30\x00\x38\x00\x32"; $this->_fontNames[Zend_Pdf_Font::NAME_FULL]['en'] = - "\x00\x5a\x00\x61\x00\x70\x00\x66\x00\x44\x00\x69\x00\x6e\x00\x67\x00" - . "\x62\x00\x61\x00\x74\x00\x73\x00\x20\x00\x4d\x00\x65\x00\x64\x00" - . "\x69\x00\x75\x00\x6d"; + 'ZapfDingbats Medium'; $this->_fontNames[Zend_Pdf_Font::NAME_VERSION]['en'] = "\x00\x30\x00\x30\x00\x32\x00\x2e\x00\x30\x00\x30\x00\x30"; $this->_fontNames[Zend_Pdf_Font::NAME_POSTSCRIPT]['en'] = - "\x00\x5a\x00\x61\x00\x70\x00\x66\x00\x44\x00\x69\x00\x6e\x00\x67\x00" - . "\x62\x00\x61\x00\x74\x00\x73"; + 'ZapfDingbats'; $this->_isBold = false; $this->_isItalic = false; diff --git a/library/Zend/Pdf/Resource/Font/Type0.php b/library/Zend/Pdf/Resource/Font/Type0.php index 4a88580cf4..ca80f16df0 100644 --- a/library/Zend/Pdf/Resource/Font/Type0.php +++ b/library/Zend/Pdf/Resource/Font/Type0.php @@ -62,6 +62,7 @@ */ class Zend_Pdf_Resource_Font_Type0 extends Zend_Pdf_Resource_Font { + public bool $_isMonospaced; /** * Descendant CIDFont * diff --git a/library/Zend/Pdf/Resource/Image/Jpeg.php b/library/Zend/Pdf/Resource/Image/Jpeg.php index ad13235bee..4813f4dabb 100644 --- a/library/Zend/Pdf/Resource/Image/Jpeg.php +++ b/library/Zend/Pdf/Resource/Image/Jpeg.php @@ -56,7 +56,7 @@ public function __construct($imageFileName) } $gd_options = gd_info(); - if ( (!isset($gd_options['JPG Support']) || $gd_options['JPG Support'] != true) && + if ( (!isset($gd_options['JPG Support']) || $gd_options['JPG Support'] != true) && (!isset($gd_options['JPEG Support']) || $gd_options['JPEG Support'] != true) ) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('JPG support is not configured properly.'); @@ -92,7 +92,7 @@ public function __construct($imageFileName) $imageDictionary->BitsPerComponent = new Zend_Pdf_Element_Numeric($imageInfo['bits']); if ($imageInfo[2] == IMAGETYPE_JPEG) { $imageDictionary->Filter = new Zend_Pdf_Element_Name('DCTDecode'); - } else if ($imageInfo[2] == IMAGETYPE_JPEG2000){ + } elseif ($imageInfo[2] == IMAGETYPE_JPEG2000) { $imageDictionary->Filter = new Zend_Pdf_Element_Name('JPXDecode'); } diff --git a/library/Zend/Pdf/Resource/Image/Tiff.php b/library/Zend/Pdf/Resource/Image/Tiff.php index 3618951a75..e6cb6c1b40 100644 --- a/library/Zend/Pdf/Resource/Image/Tiff.php +++ b/library/Zend/Pdf/Resource/Image/Tiff.php @@ -103,7 +103,7 @@ class Zend_Pdf_Resource_Image_Tiff extends Zend_Pdf_Resource_Image * @throws Zend_Pdf_Exception */ protected function unpackBytes($type, $bytes) { - if(!isset($this->_endianType)) { + if(!($this->_endianType !== null)) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception("The unpackBytes function can only be used after the endianness of the file is known"); } @@ -145,9 +145,9 @@ public function __construct($imageFileName) } $byteOrderIndicator = fread($imageFile, 2); - if($byteOrderIndicator == 'II') { + if ($byteOrderIndicator == 'II') { $this->_endianType = Zend_Pdf_Resource_Image_Tiff::TIFF_ENDIAN_LITTLE; - } else if($byteOrderIndicator == 'MM') { + } elseif ($byteOrderIndicator == 'MM') { $this->_endianType = Zend_Pdf_Resource_Image_Tiff::TIFF_ENDIAN_BIG; } else { require_once 'Zend/Pdf/Exception.php'; @@ -357,7 +357,7 @@ public function __construct($imageFileName) $ifdOffset = $this->unpackBytes(Zend_Pdf_Resource_Image_Tiff::UNPACK_TYPE_LONG, fread($imageFile, 4)); } - if(!isset($this->_imageDataOffset) || !isset($this->_imageDataLength)) { + if(!($this->_imageDataOffset !== null) || !($this->_imageDataLength !== null)) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception("TIFF: The image processed did not contain image data as expected."); } @@ -368,7 +368,7 @@ public function __construct($imageFileName) require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception("TIFF: The image contained multiple data offsets but not multiple data lengths. Tiff may be corrupt."); } - foreach($this->_imageDataOffset as $idx => $offset) { + foreach(array_keys($this->_imageDataOffset) as $idx) { fseek($imageFile, $this->_imageDataOffset[$idx], SEEK_SET); $imageDataBytes .= fread($imageFile, $this->_imageDataLength[$idx]); } @@ -386,7 +386,7 @@ public function __construct($imageFileName) parent::__construct(); $imageDictionary = $this->_resource->dictionary; - if(!isset($this->_width) || !isset($this->_width)) { + if(!($this->_width !== null) || !($this->_width !== null)) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception("Problem reading tiff file. Tiff is probably corrupt."); } @@ -411,7 +411,7 @@ public function __construct($imageFileName) $imageDictionary->Height = new Zend_Pdf_Element_Numeric($this->_height); $imageDictionary->ColorSpace = new Zend_Pdf_Element_Name($this->_colorSpace); $imageDictionary->BitsPerComponent = new Zend_Pdf_Element_Numeric($this->_bitsPerSample); - if(isset($this->_filter) && $this->_filter != 'None') { + if($this->_filter !== null && $this->_filter != 'None') { $imageDictionary->Filter = new Zend_Pdf_Element_Name($this->_filter); } diff --git a/library/Zend/Pdf/StringParser.php b/library/Zend/Pdf/StringParser.php index e54991047a..c61b96888c 100644 --- a/library/Zend/Pdf/StringParser.php +++ b/library/Zend/Pdf/StringParser.php @@ -265,11 +265,7 @@ public function readLexeme() } else { $start = $this->offset; $compare = ''; - if( version_compare( phpversion(), '5.2.5' ) >= 0) { - $compare = "()<>[]{}/%\x00\t\n\f\r "; - } else { - $compare = "()<>[]{}/%\x00\t\n\r "; - } + $compare = version_compare( phpversion(), '5.2.5' ) >= 0 ? "()<>[]{}/%\x00\t\n\f\r " : "()<>[]{}/%\x00\t\n\r "; $this->offset += strcspn($this->data, $compare, $this->offset); @@ -331,9 +327,9 @@ public function readElement($nextLexeme = null) default: if (strcasecmp($nextLexeme, 'true') == 0) { return ($this->_elements[] = new Zend_Pdf_Element_Boolean(true)); - } else if (strcasecmp($nextLexeme, 'false') == 0) { + } elseif (strcasecmp($nextLexeme, 'false') == 0) { return ($this->_elements[] = new Zend_Pdf_Element_Boolean(false)); - } else if (strcasecmp($nextLexeme, 'null') == 0) { + } elseif (strcasecmp($nextLexeme, 'null') == 0) { return ($this->_elements[] = new Zend_Pdf_Element_Null()); } @@ -492,11 +488,7 @@ private function _readReference($nextLexeme = null) { $start = $this->offset; - if ($nextLexeme === null) { - $objNum = $this->readLexeme(); - } else { - $objNum = $nextLexeme; - } + $objNum = $nextLexeme === null ? $this->readLexeme() : $nextLexeme; if (!ctype_digit($objNum)) { // it's not a reference $this->offset = $start; return null; @@ -514,9 +506,7 @@ private function _readReference($nextLexeme = null) return null; } - $ref = new Zend_Pdf_Element_Reference((int)$objNum, (int)$genNum, $this->_context, $this->_objFactory->resolve()); - - return $ref; + return new Zend_Pdf_Element_Reference((int)$objNum, (int)$genNum, $this->_context, $this->_objFactory->resolve()); } @@ -618,9 +608,9 @@ public function getObject($offset, Zend_Pdf_Element_Reference_Context $context) * This restriction gives the possibility to recognize all cases exactly */ if ($this->data[$this->offset] == "\r" && - $this->data[$this->offset + 1] == "\n" ) { + $this->data[$this->offset + 1] == "\n") { $this->offset += 2; - } else if ($this->data[$this->offset] == "\n" ) { + } elseif ($this->data[$this->offset] == "\n") { $this->offset++; } else { require_once 'Zend/Pdf/Exception.php'; diff --git a/library/Zend/Pdf/Target.php b/library/Zend/Pdf/Target.php index e9049a1f12..214a8207bd 100644 --- a/library/Zend/Pdf/Target.php +++ b/library/Zend/Pdf/Target.php @@ -45,7 +45,7 @@ public static function load(Zend_Pdf_Element $resource) { // It's a well-formed action, load it require_once 'Zend/Pdf/Action.php'; return Zend_Pdf_Action::load($resource); - } else if ($resource->D !== null) { + } elseif ($resource->D !== null) { // It's a destination $resource = $resource->D; } else { diff --git a/library/Zend/ProgressBar.php b/library/Zend/ProgressBar.php index 405b3e1952..142b046b3e 100644 --- a/library/Zend/ProgressBar.php +++ b/library/Zend/ProgressBar.php @@ -112,7 +112,7 @@ public function __construct(Zend_ProgressBar_Adapter $adapter, $min = 0, $max = // See If a persistenceNamespace exists and handle accordingly if ($this->_persistenceNamespace !== null) { - if (isset($this->_persistenceNamespace->isSet)) { + if (property_exists($this->_persistenceNamespace, 'isSet') && $this->_persistenceNamespace->isSet !== null) { $this->_startTime = $this->_persistenceNamespace->startTime; $this->_current = $this->_persistenceNamespace->current; $this->_statusText = $this->_persistenceNamespace->statusText; @@ -163,20 +163,12 @@ public function update($value = null, $text = null) } // Calculate percent - if ($this->_min === $this->_max) { - $percent = false; - } else { - $percent = (float) ($this->_current - $this->_min) / ($this->_max - $this->_min); - } + $percent = $this->_min === $this->_max ? false : (float) ($this->_current - $this->_min) / ($this->_max - $this->_min); // Calculate ETA $timeTaken = time() - $this->_startTime; - if ($percent === .0 || $percent === false) { - $timeRemaining = null; - } else { - $timeRemaining = round(((1 / $percent) * $timeTaken) - $timeTaken); - } + $timeRemaining = $percent === .0 || $percent === false ? null : round(((1 / $percent) * $timeTaken) - $timeTaken); // Poll the adapter $this->_adapter->notify($this->_current, $this->_max, $percent, $timeTaken, $timeRemaining, $this->_statusText); diff --git a/library/Zend/ProgressBar/Adapter/Console.php b/library/Zend/ProgressBar/Adapter/Console.php index 4cb281269c..542240cc8b 100644 --- a/library/Zend/ProgressBar/Adapter/Console.php +++ b/library/Zend/ProgressBar/Adapter/Console.php @@ -227,7 +227,7 @@ public function getOutputStream() */ public function setWidth($width = null) { - if ($width === null || !is_integer($width)) { + if ($width === null || !is_int($width)) { if (substr(PHP_OS, 0, 3) === 'WIN') { // We have to default to 79 on windows, because the windows // terminal always has a fixed width of 80 characters and the @@ -241,7 +241,7 @@ public function setWidth($width = null) // Try to determine the width through stty if (preg_match('#\d+ (\d+)#', (string) @shell_exec('stty size'), $match) === 1) { $this->_width = (int) $match[1]; - } else if (preg_match('#columns = (\d+);#', (string) @shell_exec('stty'), $match) === 1) { + } elseif (preg_match('#columns = (\d+);#', (string) @shell_exec('stty'), $match) === 1) { $this->_width = (int) $match[1]; } } @@ -268,7 +268,7 @@ public function setElements(array $elements) self::ELEMENT_ETA, self::ELEMENT_TEXT); - if (count(array_diff($elements, $allowedElements)) > 0) { + if (array_diff($elements, $allowedElements) !== []) { require_once 'Zend/ProgressBar/Adapter/Exception.php'; throw new Zend_ProgressBar_Adapter_Exception('Invalid element found in $elements array'); } diff --git a/library/Zend/Queue.php b/library/Zend/Queue.php index 5a0d2456e6..995615689f 100644 --- a/library/Zend/Queue.php +++ b/library/Zend/Queue.php @@ -328,7 +328,7 @@ public function createQueue($name, $timeout = null) throw new Zend_Queue_Exception('$name is not a string'); } - if ((null !== $timeout) && !is_integer($timeout)) { + if ((null !== $timeout) && !is_int($timeout)) { require_once 'Zend/Queue/Exception.php'; throw new Zend_Queue_Exception('$timeout must be an integer'); } @@ -368,12 +368,7 @@ public function createQueue($name, $timeout = null) */ public function deleteQueue() { - if ($this->isSupported('delete')) { - $deleted = $this->getAdapter()->delete($this->getName()); - } - else { - $deleted = true; - } + $deleted = $this->isSupported('delete') ? $this->getAdapter()->delete($this->getName()) : true; /** * @see Zend_Queue_Adapter_Null @@ -438,12 +433,12 @@ public function count() */ public function receive($maxMessages=null, $timeout=null) { - if (($maxMessages !== null) && !is_integer($maxMessages)) { + if (($maxMessages !== null) && !is_int($maxMessages)) { require_once 'Zend/Queue/Exception.php'; throw new Zend_Queue_Exception('$maxMessages must be an integer or null'); } - if (($timeout !== null) && !is_integer($timeout)) { + if (($timeout !== null) && !is_int($timeout)) { require_once 'Zend/Queue/Exception.php'; throw new Zend_Queue_Exception('$timeout must be an integer or null'); } @@ -528,14 +523,11 @@ protected function _setName($name) throw new Zend_Queue_Exception("$name is not a string"); } - if ($this->getAdapter()->isSupported('create')) { - if (!$this->getAdapter()->isExists($name)) { - $timeout = $this->getOption(self::TIMEOUT); - - if (!$this->getAdapter()->create($name, $timeout)) { - // Unable to create the new queue - return false; - } + if ($this->getAdapter()->isSupported('create') && !$this->getAdapter()->isExists($name)) { + $timeout = $this->getOption(self::TIMEOUT); + if (!$this->getAdapter()->create($name, $timeout)) { + // Unable to create the new queue + return false; } } diff --git a/library/Zend/Queue/Adapter/Activemq.php b/library/Zend/Queue/Adapter/Activemq.php index 5a59987d62..aa0b650cdc 100644 --- a/library/Zend/Queue/Adapter/Activemq.php +++ b/library/Zend/Queue/Adapter/Activemq.php @@ -236,26 +236,24 @@ public function receive($maxMessages=null, $timeout=null, Zend_Queue $queue=null $this->_subscribe($queue); } - if ($maxMessages > 0) { - if ($this->_client->canRead()) { - for ($i = 0; $i < $maxMessages; $i++) { - $response = $this->_client->receive(); - - switch ($response->getCommand()) { - case 'MESSAGE': - $datum = array( - 'message_id' => $response->getHeader('message-id'), - 'handle' => $response->getHeader('message-id'), - 'body' => $response->getBody(), - 'md5' => md5($response->getBody()) - ); - $data[] = $datum; - break; - default: - $block = print_r($response, true); - require_once 'Zend/Queue/Exception.php'; - throw new Zend_Queue_Exception('Invalid response received: ' . $block); - } + if ($maxMessages > 0 && $this->_client->canRead()) { + for ($i = 0; $i < $maxMessages; $i++) { + $response = $this->_client->receive(); + + switch ($response->getCommand()) { + case 'MESSAGE': + $datum = array( + 'message_id' => $response->getHeader('message-id'), + 'handle' => $response->getHeader('message-id'), + 'body' => $response->getBody(), + 'md5' => md5($response->getBody()) + ); + $data[] = $datum; + break; + default: + $block = print_r($response, true); + require_once 'Zend/Queue/Exception.php'; + throw new Zend_Queue_Exception('Invalid response received: ' . $block); } } } diff --git a/library/Zend/Queue/Adapter/Db.php b/library/Zend/Queue/Adapter/Db.php index 3658117b34..d5cb105be5 100644 --- a/library/Zend/Queue/Adapter/Db.php +++ b/library/Zend/Queue/Adapter/Db.php @@ -276,9 +276,7 @@ public function getQueues() $this->_queues[$queue->queue_name] = (int)$queue->queue_id; } - $list = array_keys($this->_queues); - - return $list; + return array_keys($this->_queues); } /** @@ -465,12 +463,7 @@ public function deleteMessage(Zend_Queue_Message $message) { $db = $this->_messageTable->getAdapter(); $where = $db->quoteInto('handle=?', $message->handle); - - if ($this->_messageTable->delete($where)) { - return true; - } - - return false; + return (bool) $this->_messageTable->delete($where); } /******************************************************************** @@ -524,7 +517,7 @@ protected function getQueueId($name) $queue = $this->_queueTable->fetchRow($query); - if ($queue === null) { + if (!$queue instanceof \Zend_Db_Table_Row_Abstract) { require_once 'Zend/Queue/Exception.php'; throw new Zend_Queue_Exception('Queue does not exist: ' . $name); } diff --git a/library/Zend/Queue/Adapter/Memcacheq.php b/library/Zend/Queue/Adapter/Memcacheq.php index 9b4a0e9444..13d2739c94 100644 --- a/library/Zend/Queue/Adapter/Memcacheq.php +++ b/library/Zend/Queue/Adapter/Memcacheq.php @@ -269,7 +269,7 @@ public function send($message, Zend_Queue $queue=null) ); $result = $this->_cache->set($queue->getName(), $message, 0, 0); - if ($result === false) { + if (!$result) { require_once 'Zend/Queue/Exception.php'; throw new Zend_Queue_Exception('failed to insert message into queue:' . $queue->getName()); } diff --git a/library/Zend/Queue/Adapter/PlatformJobQueue.php b/library/Zend/Queue/Adapter/PlatformJobQueue.php index 9ed8d2eea5..6f66b5e8f5 100644 --- a/library/Zend/Queue/Adapter/PlatformJobQueue.php +++ b/library/Zend/Queue/Adapter/PlatformJobQueue.php @@ -276,7 +276,7 @@ public function deleteMessage(Zend_Queue_Message $message) public function isJobIdExist($id) { - return (($this->_zendQueue->getJob($id))? true : false); + return ((bool) $this->_zendQueue->getJob($id)); } /******************************************************************** diff --git a/library/Zend/Queue/Message/Iterator.php b/library/Zend/Queue/Message/Iterator.php index d45ecf5d1c..0af1480508 100644 --- a/library/Zend/Queue/Message/Iterator.php +++ b/library/Zend/Queue/Message/Iterator.php @@ -226,9 +226,9 @@ public function rewind() */ public function current() { - return (($this->valid() === false) - ? null - : $this->_data[$this->_pointer]); // return the messages object + return (($this->valid()) + ? $this->_data[$this->_pointer] + : null); // return the messages object } /** diff --git a/library/Zend/Queue/Message/PlatformJob.php b/library/Zend/Queue/Message/PlatformJob.php index 4d4f6b2157..92d8437d12 100644 --- a/library/Zend/Queue/Message/PlatformJob.php +++ b/library/Zend/Queue/Message/PlatformJob.php @@ -107,7 +107,7 @@ public function setJobId($id) */ public function getJobId() { - return (($this->_id) ? $this->_id : $this->_job->getID()); + return (($this->_id !== '' && $this->_id !== '0') ? $this->_id : $this->_job->getID()); } /** @@ -127,7 +127,7 @@ public function getJob() */ public function __sleep() { - return serialize('_job', '_id', '_data'); + return serialize('_job'); } /** diff --git a/library/Zend/Queue/Stomp/Client.php b/library/Zend/Queue/Stomp/Client.php index 6fe3506229..1b17582388 100644 --- a/library/Zend/Queue/Stomp/Client.php +++ b/library/Zend/Queue/Stomp/Client.php @@ -66,7 +66,7 @@ public function __construct( */ public function __destruct() { - if ($this->getConnection()) { + if ($this->getConnection() !== null) { $this->getConnection()->close(true); } } diff --git a/library/Zend/Queue/Stomp/Frame.php b/library/Zend/Queue/Stomp/Frame.php index b3af4c7f87..b43faf5961 100644 --- a/library/Zend/Queue/Stomp/Frame.php +++ b/library/Zend/Queue/Stomp/Frame.php @@ -291,9 +291,8 @@ public function toFrame() if ($body !== false) { $frame .= $body; } - $frame .= self::END_OF_FRAME; - return $frame; + return $frame . self::END_OF_FRAME; } /** diff --git a/library/Zend/Reflection/Class.php b/library/Zend/Reflection/Class.php index 4819ef8695..7beee9b79f 100644 --- a/library/Zend/Reflection/Class.php +++ b/library/Zend/Reflection/Class.php @@ -87,10 +87,8 @@ public function getDocblock($reflectionClass = 'Zend_Reflection_Docblock') */ public function getStartLine($includeDocComment = false) { - if ($includeDocComment) { - if ($this->getDocComment() != '') { - return $this->getDocblock()->getStartLine(); - } + if ($includeDocComment && $this->getDocComment() != '') { + return $this->getDocblock()->getStartLine(); } return parent::getStartLine(); diff --git a/library/Zend/Reflection/Docblock/Tag.php b/library/Zend/Reflection/Docblock/Tag.php index 0dd3383ac1..02bdaa5789 100644 --- a/library/Zend/Reflection/Docblock/Tag.php +++ b/library/Zend/Reflection/Docblock/Tag.php @@ -96,9 +96,7 @@ public static function export() */ public function __toString() { - $str = "Docblock Tag [ * @".$this->_name." ]".PHP_EOL; - - return $str; + return "Docblock Tag [ * @".$this->_name." ]".PHP_EOL; } /** diff --git a/library/Zend/Reflection/File.php b/library/Zend/Reflection/File.php index 3e1b21c57d..9998b6cc24 100644 --- a/library/Zend/Reflection/File.php +++ b/library/Zend/Reflection/File.php @@ -37,6 +37,10 @@ */ class Zend_Reflection_File implements Reflector { + /** + * @var mixed|string + */ + public $_fileName; /** * @var string */ @@ -88,12 +92,10 @@ public function __construct($file) $fileName = $file; $fileRealpath = realpath($fileName); - if ($fileRealpath) { - // realpath() doesn't return false if Suhosin is included - // see http://uk3.php.net/manual/en/function.realpath.php#82770 - if (!file_exists($fileRealpath)) { - $fileRealpath = false; - } + // realpath() doesn't return false if Suhosin is included + // see http://uk3.php.net/manual/en/function.realpath.php#82770 + if ($fileRealpath && !file_exists($fileRealpath)) { + $fileRealpath = false; } if ($fileRealpath === false) { @@ -120,7 +122,7 @@ public static function findRealpathInIncludePath($fileName) { require_once 'Zend/Loader.php'; $includePaths = Zend_Loader::explodeIncludePath(); - while (count($includePaths) > 0) { + while ($includePaths !== []) { $filePath = array_shift($includePaths) . DIRECTORY_SEPARATOR . $fileName; if ( ($foundRealpath = realpath($filePath)) !== false) { @@ -339,7 +341,7 @@ protected function _reflect() // Maintain the count of open braces if ($token == '{') { $openBraces++; - } else if ($token == '}') { + } elseif ($token == '}') { if ( $embeddedVariableTrapped ) { $embeddedVariableTrapped = false; } else { diff --git a/library/Zend/Reflection/Function.php b/library/Zend/Reflection/Function.php index ac7f448011..c5a913e740 100644 --- a/library/Zend/Reflection/Function.php +++ b/library/Zend/Reflection/Function.php @@ -60,10 +60,8 @@ public function getDocblock($reflectionClass = 'Zend_Reflection_Docblock') */ public function getStartLine($includeDocComment = false) { - if ($includeDocComment) { - if ($this->getDocComment() != '') { - return $this->getDocblock()->getStartLine(); - } + if ($includeDocComment && $this->getDocComment() != '') { + return $this->getDocblock()->getStartLine(); } return parent::getStartLine(); @@ -123,7 +121,6 @@ public function getReturn() throw new Zend_Reflection_Exception('Function does not specify an @return annotation tag; cannot determine return type'); } $tag = $docblock->getTag('return'); - $return = Zend_Reflection_Docblock_Tag::factory('@return ' . $tag->getDescription()); - return $return; + return Zend_Reflection_Docblock_Tag::factory('@return ' . $tag->getDescription()); } } diff --git a/library/Zend/Reflection/Method.php b/library/Zend/Reflection/Method.php index 02e5d7fbcd..daa90466ae 100644 --- a/library/Zend/Reflection/Method.php +++ b/library/Zend/Reflection/Method.php @@ -71,10 +71,8 @@ public function getDocblock($reflectionClass = 'Zend_Reflection_Docblock') */ public function getStartLine($includeDocComment = false) { - if ($includeDocComment) { - if ($this->getDocComment() != '') { - return $this->getDocblock()->getStartLine(); - } + if ($includeDocComment && $this->getDocComment() != '') { + return $this->getDocblock()->getStartLine(); } return parent::getStartLine(); @@ -178,7 +176,7 @@ public function getBody() // push them back onto the lines stack as they are part of the body $restOfLastLine = trim(substr($lastLine, 0, strrpos($lastLine, '}')-1)); if (!empty($restOfLastLine)) { - array_push($lines, $restOfLastLine); + $lines[] = $restOfLastLine; } // just in case we had code on the bracket lines diff --git a/library/Zend/Rest/Client.php b/library/Zend/Rest/Client.php index a96edf310e..5d829da948 100644 --- a/library/Zend/Rest/Client.php +++ b/library/Zend/Rest/Client.php @@ -79,11 +79,7 @@ public function __construct($uri = null) */ public function setUri($uri) { - if ($uri instanceof Zend_Uri_Http) { - $this->_uri = $uri; - } else { - $this->_uri = Zend_Uri::factory($uri); - } + $this->_uri = $uri instanceof Zend_Uri_Http ? $uri : Zend_Uri::factory($uri); return $this; } @@ -265,7 +261,7 @@ public function __call($method, $args) return new Zend_Rest_Client_Result($response->getBody()); } else { // More than one arg means it's definitely a Zend_Rest_Server - if (sizeof($args) == 1) { + if (count($args) == 1) { // Uses first called function name as method name if (!isset($this->_data['method'])) { $this->_data['method'] = $method; @@ -274,7 +270,7 @@ public function __call($method, $args) $this->_data[$method] = $args[0]; } else { $this->_data['method'] = $method; - if (sizeof($args) > 0) { + if ($args !== []) { foreach ($args as $key => $arg) { $key = 'arg' . $key; $this->_data[$key] = $arg; diff --git a/library/Zend/Rest/Client/Result.php b/library/Zend/Rest/Client/Result.php index 26908427b3..f75d1dee6c 100644 --- a/library/Zend/Rest/Client/Result.php +++ b/library/Zend/Rest/Client/Result.php @@ -49,7 +49,9 @@ class Zend_Rest_Client_Result implements IteratorAggregate { */ public function __construct($data) { - set_error_handler(array($this, 'handleXmlErrors')); + set_error_handler(function (int $errno, string $errstr, ?string $errfile = \null, ?string $errline = \null, ?array $errcontext = \null) : bool { + return $this->handleXmlErrors($errno, $errstr, $errfile, $errline, $errcontext); + }); $this->_sxml = Zend_Xml_Security::scan($data); restore_error_handler(); if($this->_sxml === false) { @@ -100,8 +102,8 @@ public function toValue(SimpleXMLElement $value) */ public function __get($name) { - if (isset($this->_sxml->{$name})) { - return $this->_sxml->{$name}; + if (isset($this->_sxml->getName())) { + return $this->_sxml->getName(); } $result = $this->_sxml->xpath("//$name"); @@ -151,17 +153,12 @@ public function __call($method, $args) */ public function __isset($name) { - if (isset($this->_sxml->{$name})) { + if (isset($this->_sxml->getName())) { return true; } $result = $this->_sxml->xpath("//$name"); - - if (sizeof($result) > 0) { - return true; - } - - return false; + return count($result) > 0; } /** @@ -229,7 +226,7 @@ public function __toString() return (string) $message[0]; } else { $result = $this->_sxml->xpath('//response'); - if (sizeof($result) > 1) { + if (count($result) > 1) { return (string) "An error occured."; } else { return (string) $result[0]; diff --git a/library/Zend/Rest/Route.php b/library/Zend/Rest/Route.php index 88743a0ed4..99dbb3a87a 100644 --- a/library/Zend/Rest/Route.php +++ b/library/Zend/Rest/Route.php @@ -81,7 +81,7 @@ public function __construct(Zend_Controller_Front $front, ) { $this->_defaults = $defaults; - if ($responders) { + if ($responders !== []) { $this->_parseResponders($responders); } @@ -106,8 +106,7 @@ public static function getInstance(Zend_Config $config) $restfulConfigArray[$key] = explode(',', (string) $values); } } - $instance = new self($frontController, $defaultsArray, $restfulConfigArray); - return $instance; + return new self($frontController, $defaultsArray, $restfulConfigArray); } /** @@ -184,8 +183,8 @@ public function match($request, $partial = false) } // Digest URI params - if ($numSegs = count($path)) { - for ($i = 0; $i < $numSegs; $i = $i + 2) { + if (($numSegs = count($path)) !== 0) { + for ($i = 0; $i < $numSegs; $i += 2) { $key = urldecode($path[$i]); $val = isset($path[$i + 1]) ? $path[$i + 1] : null; $params[$key] = urldecode($val); @@ -207,11 +206,7 @@ public function match($request, $partial = false) // based on parameter count (posting to resource or collection) switch( $values[$this->_actionKey] ){ case 'post': - if ($pathElementCount > 0) { - $values[$this->_actionKey] = 'put'; - } else { - $values[$this->_actionKey] = 'post'; - } + $values[$this->_actionKey] = $pathElementCount > 0 ? 'put' : 'post'; break; case 'put': $values[$this->_actionKey] = 'put'; @@ -245,13 +240,13 @@ public function match($request, $partial = false) public function assemble($data = array(), $reset = false, $encode = true, $partial = false) { if (!$this->_keysSet) { - if (null === $this->_request) { + if (!$this->_request instanceof \Zend_Controller_Request_Abstract) { $this->_request = $this->_front->getRequest(); } $this->_setRequestKeys(); } - $params = (!$reset) ? $this->_values : array(); + $params = ($reset) ? array() : $this->_values; foreach ($data as $key => $value) { if ($value !== null) { @@ -265,10 +260,8 @@ public function assemble($data = array(), $reset = false, $encode = true, $parti $url = ''; - if ($this->_moduleValid || array_key_exists($this->_moduleKey, $data)) { - if ($params[$this->_moduleKey] != $this->_defaults[$this->_moduleKey]) { - $module = $params[$this->_moduleKey]; - } + if (($this->_moduleValid || array_key_exists($this->_moduleKey, $data)) && $params[$this->_moduleKey] != $this->_defaults[$this->_moduleKey]) { + $module = $params[$this->_moduleKey]; } unset($params[$this->_moduleKey]); @@ -357,10 +350,7 @@ protected function _checkRestfulModule($moduleName) if ($this->_fullRestfulModule($moduleName)) { return true; } - if ($this->_restfulControllers && array_key_exists($moduleName, $this->_restfulControllers)) { - return true; - } - return false; + return $this->_restfulControllers && array_key_exists($moduleName, $this->_restfulControllers); } /** @@ -379,13 +369,9 @@ protected function _checkRestfulController($moduleName, $controllerName) if ($this->_fullRestfulModule($moduleName)) { return true; } - if ($this->_checkRestfulModule($moduleName) + return $this->_checkRestfulModule($moduleName) && $this->_restfulControllers - && (false !== array_search($controllerName, $this->_restfulControllers[$moduleName])) - ) { - return true; - } - return false; + && (in_array($controllerName, $this->_restfulControllers[$moduleName])); } /** @@ -408,7 +394,7 @@ protected function _fullRestfulModule($moduleName) { return ( $this->_restfulModules - && (false !==array_search($moduleName, $this->_restfulModules)) + && (in_array($moduleName, $this->_restfulModules)) ); } } diff --git a/library/Zend/Rest/Server.php b/library/Zend/Rest/Server.php index 26f6c50371..b1a7406406 100644 --- a/library/Zend/Rest/Server.php +++ b/library/Zend/Rest/Server.php @@ -104,7 +104,9 @@ class Zend_Rest_Server implements Zend_Server_Interface */ public function __construct() { - set_exception_handler(array($this, "fault")); + set_exception_handler(function ($exception = \null, ?int $code = \null) : \DOMDocument { + return $this->fault($exception, $code); + }); $this->_reflection = new Zend_Server_Reflection(); } @@ -162,7 +164,7 @@ public function returnResponse($flag = null) return $this->_returnResponse; } - $this->_returnResponse = ($flag) ? true : false; + $this->_returnResponse = $flag; return $this; } @@ -176,7 +178,7 @@ public function returnResponse($flag = null) public function handle($request = false) { $this->_headers = array('Content-Type: text/xml'); - if (!$request) { + if ($request === []) { $request = $_REQUEST; } if (isset($request['method'])) { @@ -346,11 +348,7 @@ public function setClass($classname, $namespace = '', $argv = array()) protected function _handleStruct($struct) { $function = $this->_functions[$this->_method]; - if ($function instanceof Zend_Server_Reflection_Method) { - $class = $function->getDeclaringClass()->getName(); - } else { - $class = false; - } + $class = $function instanceof Zend_Server_Reflection_Method ? $function->getDeclaringClass()->getName() : false; $method = $function->getName(); @@ -427,11 +425,7 @@ protected function _structValue( protected function _handleScalar($value) { $function = $this->_functions[$this->_method]; - if ($function instanceof Zend_Server_Reflection_Method) { - $class = $function->getDeclaringClass()->getName(); - } else { - $class = false; - } + $class = $function instanceof Zend_Server_Reflection_Method ? $function->getDeclaringClass()->getName() : false; $method = $function->getName(); @@ -480,23 +474,15 @@ public function fault($exception = null, $code = null) { if (isset($this->_functions[$this->_method])) { $function = $this->_functions[$this->_method]; - } elseif (isset($this->_method)) { + } elseif ($this->_method !== null) { $function = $this->_method; } else { $function = 'rest'; } - if ($function instanceof Zend_Server_Reflection_Method) { - $class = $function->getDeclaringClass()->getName(); - } else { - $class = false; - } + $class = $function instanceof Zend_Server_Reflection_Method ? $function->getDeclaringClass()->getName() : false; - if ($function instanceof Zend_Server_Reflection_Function_Abstract) { - $method = $function->getName(); - } else { - $method = $function; - } + $method = $function instanceof Zend_Server_Reflection_Function_Abstract ? $function->getName() : $function; $dom = new DOMDocument('1.0', $this->getEncoding()); if ($class) { @@ -539,11 +525,7 @@ public function fault($exception = null, $code = null) $xmlMethod->appendChild($dom->createElement('status', 'failed')); // Headers to send - if ($code === null || (404 != $code)) { - $this->_headers[] = 'HTTP/1.0 400 Bad Request'; - } else { - $this->_headers[] = 'HTTP/1.0 404 File Not Found'; - } + $this->_headers[] = $code === null || (404 != $code) ? 'HTTP/1.0 400 Bad Request' : 'HTTP/1.0 404 File Not Found'; return $dom; } diff --git a/library/Zend/Search/Lucene.php b/library/Zend/Search/Lucene.php index 89e0dab523..6ae3187148 100644 --- a/library/Zend/Search/Lucene.php +++ b/library/Zend/Search/Lucene.php @@ -262,14 +262,14 @@ public static function getActualGeneration(Zend_Search_Lucene_Storage_Directory $genFile = $directory->getFileObject('segments.gen', false); $format = $genFile->readInt(); - if ($format != (int)0xFFFFFFFE) { + if ($format !== (int)0xFFFFFFFE) { throw new Zend_Search_Lucene_Exception('Wrong segments.gen file format'); } $gen1 = $genFile->readLong(); $gen2 = $genFile->readLong(); - if ($gen1 == $gen2) { + if ($gen1 === $gen2) { return $gen1; } @@ -371,7 +371,7 @@ private function _readPre21SegmentsFile() $format = $segmentsFile->readInt(); - if ($format != (int)0xFFFFFFFF) { + if ($format !== (int)0xFFFFFFFF) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Wrong segments file format'); } @@ -413,9 +413,9 @@ private function _readSegmentsFile() $format = $segmentsFile->readInt(); - if ($format == (int)0xFFFFFFFC) { + if ($format === (int)0xFFFFFFFC) { $this->_formatVersion = self::FORMAT_2_3; - } else if ($format == (int)0xFFFFFFFD) { + } elseif ($format == (int)0xFFFFFFFD) { $this->_formatVersion = self::FORMAT_2_1; } else { require_once 'Zend/Search/Lucene/Exception.php'; @@ -443,7 +443,7 @@ private function _readSegmentsFile() if ($this->_formatVersion == self::FORMAT_2_3) { $docStoreOffset = $segmentsFile->readInt(); - if ($docStoreOffset != (int)0xFFFFFFFF) { + if ($docStoreOffset !== (int)0xFFFFFFFF) { $docStoreSegment = $segmentsFile->readString(); $docStoreIsCompoundFile = $segmentsFile->readByte(); @@ -461,7 +461,7 @@ private function _readSegmentsFile() $numField = $segmentsFile->readInt(); $normGens = array(); - if ($numField != (int)0xFFFFFFFF) { + if ($numField !== (int)0xFFFFFFFF) { for ($count1 = 0; $count1 < $numField; $count1++) { $normGens[] = $segmentsFile->readLong(); } @@ -475,10 +475,10 @@ private function _readSegmentsFile() if ($isCompoundByte == 0xFF) { // The segment is not a compound file $isCompound = false; - } else if ($isCompoundByte == 0x00) { + } elseif ($isCompoundByte == 0x00) { // The status is unknown $isCompound = null; - } else if ($isCompoundByte == 0x01) { + } elseif ($isCompoundByte == 0x01) { // The segment is a compound file $isCompound = true; } @@ -564,7 +564,7 @@ public function __construct($directory = null, $create = false) if ($this->_generation == -1) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Index doesn\'t exists in the specified directory.'); - } else if ($this->_generation == 0) { + } elseif ($this->_generation == 0) { $this->_readPre21SegmentsFile(); } else { $this->_readSegmentsFile(); @@ -945,7 +945,7 @@ public function find($query) /** Zend_Search_Lucene_Search_QueryHit */ require_once 'Zend/Search/Lucene/Search/QueryHit.php'; - foreach ($query->matchedDocs() as $id => $num) { + foreach (array_keys($query->matchedDocs()) as $id) { $docScore = $query->score($id, $this); if( $docScore != 0 ) { $hit = new Zend_Search_Lucene_Search_QueryHit($this); @@ -999,7 +999,8 @@ public function find($query) $sortFieldValues = array(); require_once 'Zend/Search/Lucene/Exception.php'; - for ($count = 1; $count < count($argList); $count++) { + $argListCount = count($argList); + for ($count = 1; $count < $argListCount; $count++) { $fieldName = $argList[$count]; if (!is_string($fieldName)) { @@ -1038,19 +1039,17 @@ public function find($query) $sortArgs[] = &$sortFieldValues[$fieldName]; } - if ($count + 1 < count($argList) && is_integer($argList[$count+1])) { + if ($count + 1 < count($argList) && is_int($argList[$count+1])) { $count++; $sortArgs[] = &$argList[$count]; - if ($count + 1 < count($argList) && is_integer($argList[$count+1])) { + if ($count + 1 < count($argList) && is_int($argList[$count+1])) { $count++; $sortArgs[] = &$argList[$count]; + } elseif ($argList[$count] == SORT_ASC || $argList[$count] == SORT_DESC) { + $sortArgs[] = &$sortReg; } else { - if ($argList[$count] == SORT_ASC || $argList[$count] == SORT_DESC) { - $sortArgs[] = &$sortReg; - } else { - $sortArgs[] = &$sortAsc; - } + $sortArgs[] = &$sortAsc; } } else { $sortArgs[] = &$sortAsc; @@ -1134,7 +1133,7 @@ public function getDocument($id) $fieldInfo = $segmentInfo->getField($fieldNum); - if (!($bits & 2)) { // Text data + if (($bits & 2) === 0) { // Text data $field = new Zend_Search_Lucene_Field($fieldInfo->name, $fdtFile->readString(), 'UTF-8', @@ -1197,7 +1196,7 @@ public function termDocs(Zend_Search_Lucene_Index_Term $term, $docsFilter = null if (count($subResults) == 0) { return array(); - } else if (count($subResults) == 1) { + } elseif (count($subResults) == 1) { // Index is optimized (only one segment) // Do not perform array reindexing return reset($subResults); @@ -1231,7 +1230,7 @@ public function termDocsFilter(Zend_Search_Lucene_Index_Term $term, $docsFilter if (count($subResults) == 0) { return array(); - } else if (count($subResults) == 1) { + } elseif (count($subResults) == 1) { // Index is optimized (only one segment) // Do not perform array reindexing return reset($subResults); @@ -1484,8 +1483,7 @@ public function terms() while (($segmentInfo = $segmentInfoQueue->pop()) !== null) { if ($segmentInfoQueue->top() === null || - $segmentInfoQueue->top()->currentTerm()->key() != - $segmentInfo->currentTerm()->key()) { + $segmentInfoQueue->top()->currentTerm()->key() != $segmentInfo->currentTerm()->key()) { // We got new term $result[] = $segmentInfo->currentTerm(); } diff --git a/library/Zend/Search/Lucene/Document/Docx.php b/library/Zend/Search/Lucene/Document/Docx.php index ccf9a13d74..8d03124cbc 100644 --- a/library/Zend/Search/Lucene/Document/Docx.php +++ b/library/Zend/Search/Lucene/Document/Docx.php @@ -92,12 +92,7 @@ private function __construct($fileName, $storeContent) { } foreach ($runs as $run) { - if ($run->getName() == 'br') { - // Break element - $documentBody[] = ' '; - } else { - $documentBody[] = (string)$run; - } + $documentBody[] = $run->getName() == 'br' ? ' ' : (string)$run; } // Add space after each paragraph. So they are not bound together. diff --git a/library/Zend/Search/Lucene/Document/Html.php b/library/Zend/Search/Lucene/Document/Html.php index 41ae90d371..9d3bf59297 100644 --- a/library/Zend/Search/Lucene/Document/Html.php +++ b/library/Zend/Search/Lucene/Document/Html.php @@ -91,11 +91,7 @@ private function __construct($data, $isFile, $storeContent, $defaultEncoding = ' $this->_doc = new DOMDocument(); $this->_doc->substituteEntities = true; - if ($isFile) { - $htmlData = file_get_contents($data); - } else { - $htmlData = $data; - } + $htmlData = $isFile ? file_get_contents($data) : $data; @$this->_doc->loadHTML($htmlData); if ($this->_doc->encoding === null) { @@ -220,7 +216,7 @@ private function _retrieveNodeText(DOMNode $node, &$text) if(!in_array($node->parentNode->tagName, $this->_inlineTags)) { $text .= ' '; } - } else if ($node->nodeType == XML_ELEMENT_NODE && $node->nodeName != 'script') { + } elseif ($node->nodeType == XML_ELEMENT_NODE && $node->nodeName != 'script') { foreach ($node->childNodes as $childNode) { $this->_retrieveNodeText($childNode, $text); } @@ -362,11 +358,8 @@ protected function _highlightNodeRecursive(DOMNode $contextNode, $wordsToHighlig if ($childNode->nodeType == XML_TEXT_NODE) { // process node later to leave childNodes structure untouched $textNodes[] = $childNode; - } else { - // Process node if it's not a script node - if ($childNode->nodeName != 'script') { - $this->_highlightNodeRecursive($childNode, $wordsToHighlight, $callback, $params); - } + } elseif ($childNode->nodeName != 'script') { + $this->_highlightNodeRecursive($childNode, $wordsToHighlight, $callback, $params); } } @@ -396,7 +389,9 @@ public function applyColour($stringToHighlight, $colour) */ public function highlight($words, $colour = '#66ffff') { - return $this->highlightExtended($words, array($this, 'applyColour'), array($colour)); + return $this->highlightExtended($words, function (string $stringToHighlight, $colour) : string { + return $this->applyColour($stringToHighlight, $colour); + }, array($colour)); } diff --git a/library/Zend/Search/Lucene/Document/Xlsx.php b/library/Zend/Search/Lucene/Document/Xlsx.php index db245af4ec..2d82297fdd 100644 --- a/library/Zend/Search/Lucene/Document/Xlsx.php +++ b/library/Zend/Search/Lucene/Document/Xlsx.php @@ -114,11 +114,11 @@ private function __construct($fileName, $storeContent) $sharedStringsPath = $workbookRelations->xpath("rel:Relationship[@Type='" . Zend_Search_Lucene_Document_Xlsx::SCHEMA_SHAREDSTRINGS . "']"); $sharedStringsPath = (string)$sharedStringsPath[0]['Target']; $xmlStrings = Zend_Xml_Security::scan($package->getFromName( $this->absoluteZipPath(dirname($rel["Target"]) . "/" . $sharedStringsPath)) ); - if (isset($xmlStrings) && isset($xmlStrings->si)) { + if (isset($xmlStrings) && (property_exists($xmlStrings, 'si') && $xmlStrings->si !== null)) { foreach ($xmlStrings->si as $val) { - if (isset($val->t)) { + if (property_exists($val, 't') && $val->t !== null) { $sharedStrings[] = (string)$val->t; - } elseif (isset($val->r)) { + } elseif (property_exists($val, 'r') && $val->r !== null) { $sharedStrings[] = $this->_parseRichText($val); } } @@ -149,11 +149,7 @@ private function __construct($fileName, $storeContent) switch ($dataType) { case "s": // Value is a shared string - if ((string)$c->v != '') { - $value = $sharedStrings[intval($c->v)]; - } else { - $value = ''; - } + $value = (string)$c->v != '' ? $sharedStrings[(int) $c->v] : ''; break; @@ -162,11 +158,7 @@ private function __construct($fileName, $storeContent) $value = (string)$c->v; if ($value == '0') { $value = false; - } else if ($value == '1') { - $value = true; - } else { - $value = (bool)$c->v; - } + } else $value = $value == '1' ? true : (bool)$c->v; break; @@ -178,11 +170,7 @@ private function __construct($fileName, $storeContent) case "e": // Value is an error message - if ((string)$c->v != '') { - $value = (string)$c->v; - } else { - $value = ''; - } + $value = (string)$c->v != '' ? (string)$c->v : ''; break; @@ -241,7 +229,7 @@ private function __construct($fileName, $storeContent) private function _parseRichText($is = null) { $value = array(); - if (isset($is->t)) { + if (property_exists($is, 't') && $is->t !== null) { $value[] = (string)$is->t; } else { foreach ($is->r as $run) { diff --git a/library/Zend/Search/Lucene/Index/DictionaryLoader.php b/library/Zend/Search/Lucene/Index/DictionaryLoader.php index 969bd8dd9a..19299ff6e2 100644 --- a/library/Zend/Search/Lucene/Index/DictionaryLoader.php +++ b/library/Zend/Search/Lucene/Index/DictionaryLoader.php @@ -57,7 +57,7 @@ public static function load($data) // $tiVersion = $tiiFile->readInt(); $tiVersion = ord($data[0]) << 24 | ord($data[1]) << 16 | ord($data[2]) << 8 | ord($data[3]); $pos += 4; - if ($tiVersion != (int)0xFFFFFFFE /* pre-2.1 format */ && + if ($tiVersion !== (int)0xFFFFFFFE /* pre-2.1 format */ && $tiVersion != (int)0xFFFFFFFD /* 2.1+ format */) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Wrong TermInfoIndexFile file format'); @@ -74,10 +74,10 @@ public static function load($data) ord($data[$pos+6]) << 8 | ord($data[$pos+7]); } else { - if ((ord($data[$pos]) != 0) || - (ord($data[$pos+1]) != 0) || - (ord($data[$pos+2]) != 0) || - (ord($data[$pos+3]) != 0) || + if ((ord($data[$pos]) != 0) || + (ord($data[$pos+1]) != 0) || + (ord($data[$pos+2]) != 0) || + (ord($data[$pos+3]) != 0) || ((ord($data[$pos+4]) & 0x80) != 0)) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Largest supported segment size (for 32-bit mode) is 2Gb'); @@ -134,12 +134,12 @@ public static function load($data) for ($count1 = 0; $count1 < $len; $count1++ ) { if (( ord($termSuffix[$count1]) & 0xC0 ) == 0xC0) { $addBytes = 1; - if (ord($termSuffix[$count1]) & 0x20 ) { + if ((ord($termSuffix[$count1]) & 0x20) !== 0 ) { $addBytes++; // Never used for Java Lucene created index. // Java2 doesn't encode strings in four bytes - if (ord($termSuffix[$count1]) & 0x10 ) { + if ((ord($termSuffix[$count1]) & 0x10) !== 0 ) { $addBytes++; } } @@ -166,9 +166,9 @@ public static function load($data) $charBytes = 1; if ((ord($prevTerm[$pb]) & 0xC0) == 0xC0) { $charBytes++; - if (ord($prevTerm[$pb]) & 0x20 ) { + if ((ord($prevTerm[$pb]) & 0x20) !== 0 ) { $charBytes++; - if (ord($prevTerm[$pb]) & 0x10 ) { + if ((ord($prevTerm[$pb]) & 0x10) !== 0 ) { $charBytes++; } } @@ -252,7 +252,7 @@ public static function load($data) } // Check special index entry mark - if ($termDictionary[0][0] != (int)0xFFFFFFFF) { + if ($termDictionary[0][0] !== (int)0xFFFFFFFF) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Wrong TermInfoIndexFile file format'); } diff --git a/library/Zend/Search/Lucene/Index/SegmentInfo.php b/library/Zend/Search/Lucene/Index/SegmentInfo.php index f74454db53..78e64adfcc 100644 --- a/library/Zend/Search/Lucene/Index/SegmentInfo.php +++ b/library/Zend/Search/Lucene/Index/SegmentInfo.php @@ -314,7 +314,7 @@ public function __construct(Zend_Search_Lucene_Storage_Directory $directory, $na $fieldBits & 0x02 /* termvectors are stored */, $fieldBits & 0x10 /* norms are omitted */, $fieldBits & 0x20 /* payloads are stored */); - if ($fieldBits & 0x10) { + if (($fieldBits & 0x10) !== 0) { // norms are omitted for the indexed field $this->_norms[$count] = str_repeat(chr(Zend_Search_Lucene_Search_Similarity::encodeNorm(1.0)), $docCount); } @@ -348,7 +348,7 @@ private function _loadDelFile() if ($this->_delGen == -1) { // There is no delete file for this segment return null; - } else if ($this->_delGen == 0) { + } elseif ($this->_delGen == 0) { // It's a segment with pre-2.1 format delete file // Try to load deletions file return $this->_loadPre21DelFile(); @@ -378,11 +378,7 @@ private function _loadPre21DelFile() $byteCount = ceil($byteCount/8); $bitCount = $delFile->readInt(); - if ($bitCount == 0) { - $delBytes = ''; - } else { - $delBytes = $delFile->readBytes($byteCount); - } + $delBytes = $bitCount == 0 ? '' : $delFile->readBytes($byteCount); if (extension_loaded('bitset')) { return $delBytes; @@ -391,7 +387,7 @@ private function _loadPre21DelFile() for ($count = 0; $count < $byteCount; $count++) { $byte = ord($delBytes[$count]); for ($bit = 0; $bit < 8; $bit++) { - if ($byte & (1<<$bit)) { + if (($byte & (1<<$bit)) !== 0) { $deletions[$count*8 + $bit] = 1; } } @@ -423,12 +419,8 @@ private function _load21DelFile() $format = $delFile->readInt(); - if ($format == (int)0xFFFFFFFF) { - if (extension_loaded('bitset')) { - $deletions = bitset_empty(); - } else { - $deletions = array(); - } + if ($format === (int)0xFFFFFFFF) { + $deletions = extension_loaded('bitset') ? bitset_empty() : array(); $byteCount = $delFile->readInt(); $bitCount = $delFile->readInt(); @@ -445,14 +437,14 @@ private function _load21DelFile() if (extension_loaded('bitset')) { for ($bit = 0; $bit < 8; $bit++) { - if ($nonZeroByte & (1<<$bit)) { + if (($nonZeroByte & (1<<$bit)) !== 0) { bitset_incl($deletions, $byteNum*8 + $bit); } } return $deletions; } else { for ($bit = 0; $bit < 8; $bit++) { - if ($nonZeroByte & (1<<$bit)) { + if (($nonZeroByte & (1<<$bit)) !== 0) { $deletions[$byteNum*8 + $bit] = 1; } } @@ -465,11 +457,7 @@ private function _load21DelFile() $byteCount = ceil($format/8); $bitCount = $delFile->readInt(); - if ($bitCount == 0) { - $delBytes = ''; - } else { - $delBytes = $delFile->readBytes($byteCount); - } + $delBytes = $bitCount == 0 ? '' : $delFile->readBytes($byteCount); if (extension_loaded('bitset')) { return $delBytes; @@ -478,13 +466,13 @@ private function _load21DelFile() for ($count = 0; $count < $byteCount; $count++) { $byte = ord($delBytes[$count]); for ($bit = 0; $bit < 8; $bit++) { - if ($byte & (1<<$bit)) { + if (($byte & (1<<$bit)) !== 0) { $deletions[$count*8 + $bit] = 1; } } } - return (count($deletions) > 0) ? $deletions : null; + return ($deletions !== []) ? $deletions : null; } } } @@ -757,7 +745,7 @@ public function getName() private function _cleanUpTermInfoCache() { // Clean 256 term infos - foreach ($this->_termInfoCache as $key => $termInfo) { + foreach (array_keys($this->_termInfoCache) as $key) { unset($this->_termInfoCache[$key]); // leave 768 last used term infos @@ -877,7 +865,7 @@ public function getTermInfo(Zend_Search_Lucene_Index_Term $term) $tisFile = $this->openCompoundFile('.tis'); $tiVersion = $tisFile->readInt(); - if ($tiVersion != (int)0xFFFFFFFE /* pre-2.1 format */ && + if ($tiVersion !== (int)0xFFFFFFFE /* pre-2.1 format */ && $tiVersion != (int)0xFFFFFFFD /* 2.1+ format */) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Wrong TermInfoFile file format'); @@ -899,7 +887,7 @@ public function getTermInfo(Zend_Search_Lucene_Index_Term $term) for ($count = $prevPosition*$indexInterval + 1; $count <= $termCount && ( $this->_getFieldPosition($termFieldNum) < $searchDicField || - ($this->_getFieldPosition($termFieldNum) == $searchDicField && + ($this->_getFieldPosition($termFieldNum) === $searchDicField && strcmp($termValue, $term->text) < 0) ); $count++) { $termPrefixLength = $tisFile->readVInt(); @@ -910,11 +898,7 @@ public function getTermInfo(Zend_Search_Lucene_Index_Term $term) $docFreq = $tisFile->readVInt(); $freqPointer += $tisFile->readVInt(); $proxPointer += $tisFile->readVInt(); - if( $docFreq >= $skipInterval ) { - $skipOffset = $tisFile->readVInt(); - } else { - $skipOffset = 0; - } + $skipOffset = $docFreq >= $skipInterval ? $tisFile->readVInt() : 0; } if ($termFieldNum == $searchField && $termValue == $term->text) { @@ -1377,7 +1361,7 @@ private function _loadNorm($fieldNum) $header = $normfFile->readBytes(3); $headerFormatVersion = $normfFile->readByte(); - if ($header != 'NRM' || $headerFormatVersion != (int)0xFF) { + if ($header != 'NRM' || $headerFormatVersion !== (int)0xFF) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Wrong norms file format.'); } @@ -1458,7 +1442,7 @@ public function hasDeletions() */ public function hasSingleNormFile() { - return $this->_hasSingleNormFile ? true : false; + return $this->_hasSingleNormFile; } /** @@ -1530,7 +1514,7 @@ private function _detectLatestDelGen() if ($file == $this->_name . '.del') { // Matches .del file name $delFileList[] = 0; - } else if (preg_match('/^' . $this->_name . '_([a-zA-Z0-9]+)\.del$/i', (string) $file, $matches)) { + } elseif (preg_match('/^' . $this->_name . '_([a-zA-Z0-9]+)\.del$/i', (string) $file, $matches)) { // Matches _NNN.del file names $delFileList[] = (int)base_convert($matches[1], 36, 10); } @@ -1564,15 +1548,14 @@ public function writeChanges() if (!$this->_deletedDirty) { // There was no deletions by current process - if ($latestDelGen == $this->_delGen) { + if ($latestDelGen === $this->_delGen) { // Delete file hasn't been updated by any concurrent process return; - } else if ($latestDelGen > $this->_delGen) { + } elseif ($latestDelGen > $this->_delGen) { // Delete file has been updated by some concurrent process // Reload deletions file $this->_delGen = $latestDelGen; $this->_deleted = $this->_loadDelFile(); - return; } else { require_once 'Zend/Search/Lucene/Exception.php'; @@ -1767,21 +1750,15 @@ public function writeChanges() * @throws Zend_Search_Lucene_Exception * @return integer */ - public function resetTermsStream(/** $startId = 0, $mode = self::SM_TERMS_ONLY */) + public function resetTermsStream(...$argList/** $startId = 0, $mode = self::SM_TERMS_ONLY */) { - /** - * SegmentInfo->resetTermsStream() method actually takes two optional parameters: - * $startId (default value is 0) - * $mode (default value is self::SM_TERMS_ONLY) - */ - $argList = func_get_args(); if (count($argList) > 2) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Wrong number of arguments'); - } else if (count($argList) == 2) { + } elseif (count($argList) == 2) { $startId = $argList[0]; $mode = $argList[1]; - } else if (count($argList) == 1) { + } elseif (count($argList) == 1) { $startId = $argList[0]; $mode = self::SM_TERMS_ONLY; } else { @@ -1797,7 +1774,7 @@ public function resetTermsStream(/** $startId = 0, $mode = self::SM_TERMS_ONLY * $this->_tisFileOffset = $this->_tisFile->tell(); $tiVersion = $this->_tisFile->readInt(); - if ($tiVersion != (int)0xFFFFFFFE /* pre-2.1 format */ && + if ($tiVersion !== (int)0xFFFFFFFE /* pre-2.1 format */ && $tiVersion != (int)0xFFFFFFFD /* 2.1+ format */) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Wrong TermInfoFile file format'); @@ -1957,9 +1934,8 @@ public function skipTo(Zend_Search_Lucene_Index_Term $prefix) if ($highIndex == 0) { // skip start entry $this->nextTerm(); - } else if ($prefix->field == $this->_lastTerm->field && $prefix->text == $this->_lastTerm->text) { + } elseif ($prefix->field == $this->_lastTerm->field && $prefix->text === $this->_lastTerm->text) { // We got exact match in the dictionary index - if ($this->_termsScanMode == self::SM_FULL_INFO || $this->_termsScanMode == self::SM_MERGE_INFO) { $this->_lastTermPositions = array(); @@ -1990,7 +1966,6 @@ public function skipTo(Zend_Search_Lucene_Index_Term $prefix) } } } - return; } @@ -2038,11 +2013,7 @@ public function nextTerm() $docFreq = $this->_tisFile->readVInt(); $freqPointer = $this->_lastTermInfo->freqPointer + $this->_tisFile->readVInt(); $proxPointer = $this->_lastTermInfo->proxPointer + $this->_tisFile->readVInt(); - if ($docFreq >= $this->_skipInterval) { - $skipOffset = $this->_tisFile->readVInt(); - } else { - $skipOffset = 0; - } + $skipOffset = $docFreq >= $this->_skipInterval ? $this->_tisFile->readVInt() : 0; $this->_lastTermInfo = new Zend_Search_Lucene_Index_TermInfo($docFreq, $freqPointer, $proxPointer, $skipOffset); diff --git a/library/Zend/Search/Lucene/Index/SegmentMerger.php b/library/Zend/Search/Lucene/Index/SegmentMerger.php index 19d3590f06..9bf20ccc9c 100644 --- a/library/Zend/Search/Lucene/Index/SegmentMerger.php +++ b/library/Zend/Search/Lucene/Index/SegmentMerger.php @@ -189,7 +189,7 @@ private function _mergeStoredFields() $bits = $fdtFile->readByte(); $fieldInfo = $segmentInfo->getField($fieldNum); - if (!($bits & 2)) { // Text data + if (($bits & 2) === 0) { // Text data $storedFields[] = new Zend_Search_Lucene_Field($fieldInfo->name, $fdtFile->readString(), @@ -246,8 +246,7 @@ private function _mergeTerms() $termDocs += $segmentInfo->currentTermPositions(); if ($segmentInfoQueue->top() === null || - $segmentInfoQueue->top()->currentTerm()->key() != - $segmentInfo->currentTerm()->key()) { + $segmentInfoQueue->top()->currentTerm()->key() != $segmentInfo->currentTerm()->key()) { // We got new term ksort($termDocs, SORT_NUMERIC); diff --git a/library/Zend/Search/Lucene/Index/SegmentWriter.php b/library/Zend/Search/Lucene/Index/SegmentWriter.php index 442adeb85a..5589299c3f 100644 --- a/library/Zend/Search/Lucene/Index/SegmentWriter.php +++ b/library/Zend/Search/Lucene/Index/SegmentWriter.php @@ -225,7 +225,7 @@ public function getFieldInfos() */ public function addStoredFields($storedFields) { - if (!isset($this->_fdxFile)) { + if (!($this->_fdxFile !== null)) { $this->_fdxFile = $this->_directory->createFile($this->_name . '.fdx'); $this->_fdtFile = $this->_directory->createFile($this->_name . '.fdt'); @@ -459,15 +459,7 @@ public function addTerm($termEntry, $termDocs) } } - if (count($termDocs) >= self::$skipInterval) { - /** - * @todo Write Skip Data to a freq file. - * It's not used now, but make index more optimal - */ - $skipOffset = $this->_frqFile->tell() - $freqPointer; - } else { - $skipOffset = 0; - } + $skipOffset = count($termDocs) >= self::$skipInterval ? $this->_frqFile->tell() - $freqPointer : 0; $term = new Zend_Search_Lucene_Index_Term($termEntry->text, $this->_fields[$termEntry->field]->number); @@ -519,7 +511,7 @@ protected function _dumpTermDictEntry(Zend_Search_Lucene_Storage_File $dicFile, $matchedBytes = 0; $maxBytes = min(strlen($prevTerm->text), strlen($term->text)); while ($matchedBytes < $maxBytes && - $prevTerm->text[$matchedBytes] == $term->text[$matchedBytes]) { + $prevTerm->text[$matchedBytes] === $term->text[$matchedBytes]) { $matchedBytes++; } @@ -530,9 +522,9 @@ protected function _dumpTermDictEntry(Zend_Search_Lucene_Storage_File $dicFile, $charBytes = 1; if ((ord($term->text[$prefixBytes]) & 0xC0) == 0xC0) { $charBytes++; - if (ord($term->text[$prefixBytes]) & 0x20 ) { + if ((ord($term->text[$prefixBytes]) & 0x20) !== 0 ) { $charBytes++; - if (ord($term->text[$prefixBytes]) & 0x10 ) { + if ((ord($term->text[$prefixBytes]) & 0x10) !== 0 ) { $charBytes++; } } diff --git a/library/Zend/Search/Lucene/Index/SegmentWriter/DocumentWriter.php b/library/Zend/Search/Lucene/Index/SegmentWriter/DocumentWriter.php index 2c440e4718..362463ba1f 100644 --- a/library/Zend/Search/Lucene/Index/SegmentWriter/DocumentWriter.php +++ b/library/Zend/Search/Lucene/Index/SegmentWriter/DocumentWriter.php @@ -93,10 +93,8 @@ public function addDocument(Zend_Search_Lucene_Document $document) if ($field->isTokenized) { /** Zend_Search_Lucene_Analysis_Analyzer */ require_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; - $analyzer = Zend_Search_Lucene_Analysis_Analyzer::getDefault(); $analyzer->setInput($field->value, $field->encoding); - $position = 0; $tokenCounter = 0; while (($token = $analyzer->nextToken()) !== null) { @@ -110,14 +108,13 @@ public function addDocument(Zend_Search_Lucene_Document $document) $this->_termDictionary[$termKey] = $term; $this->_termDocs[$termKey] = array(); $this->_termDocs[$termKey][$this->_docCount] = array(); - } else if (!isset($this->_termDocs[$termKey][$this->_docCount])) { + } elseif (!isset($this->_termDocs[$termKey][$this->_docCount])) { // Existing term, but new term entry $this->_termDocs[$termKey][$this->_docCount] = array(); } $position += $token->getPositionIncrement(); $this->_termDocs[$termKey][$this->_docCount][] = $position; } - if ($tokenCounter == 0) { // Field contains empty value. Treat it as non-indexed and non-tokenized $field = clone($field); @@ -128,7 +125,7 @@ public function addDocument(Zend_Search_Lucene_Document $document) $document->boost* $field->boost )); } - } else if (($fieldUtf8Value = $field->getUtf8Value()) == '') { + } elseif (($fieldUtf8Value = $field->getUtf8Value()) == '') { // Field contains empty value. Treat it as non-indexed and non-tokenized $field = clone($field); $field->isIndexed = $field->isTokenized = false; @@ -141,7 +138,7 @@ public function addDocument(Zend_Search_Lucene_Document $document) $this->_termDictionary[$termKey] = $term; $this->_termDocs[$termKey] = array(); $this->_termDocs[$termKey][$this->_docCount] = array(); - } else if (!isset($this->_termDocs[$termKey][$this->_docCount])) { + } elseif (!isset($this->_termDocs[$termKey][$this->_docCount])) { // Existing term, but new term entry $this->_termDocs[$termKey][$this->_docCount] = array(); } diff --git a/library/Zend/Search/Lucene/Index/Term.php b/library/Zend/Search/Lucene/Index/Term.php index b2328384dc..9f66b4b2a3 100644 --- a/library/Zend/Search/Lucene/Index/Term.php +++ b/library/Zend/Search/Lucene/Index/Term.php @@ -87,9 +87,9 @@ public static function getPrefix($str, $length) $charBytes = 1; if ((ord($str[$prefixBytes]) & 0xC0) == 0xC0) { $charBytes++; - if (ord($str[$prefixBytes]) & 0x20 ) { + if ((ord($str[$prefixBytes]) & 0x20) !== 0 ) { $charBytes++; - if (ord($str[$prefixBytes]) & 0x10 ) { + if ((ord($str[$prefixBytes]) & 0x10) !== 0 ) { $charBytes++; } } @@ -121,9 +121,9 @@ public static function getLength($str) $charBytes = 1; if ((ord($str[$bytes]) & 0xC0) == 0xC0) { $charBytes++; - if (ord($str[$bytes]) & 0x20 ) { + if ((ord($str[$bytes]) & 0x20) !== 0 ) { $charBytes++; - if (ord($str[$bytes]) & 0x10 ) { + if ((ord($str[$bytes]) & 0x10) !== 0 ) { $charBytes++; } } diff --git a/library/Zend/Search/Lucene/Index/Writer.php b/library/Zend/Search/Lucene/Index/Writer.php index 7b08684ac5..6bdaef1f8d 100644 --- a/library/Zend/Search/Lucene/Index/Writer.php +++ b/library/Zend/Search/Lucene/Index/Writer.php @@ -289,12 +289,7 @@ private function _hasAnythingToMerge() $mergePool[] = $this->_segmentInfos[$segName]; $poolSize += $size; } - - if ($poolSize >= $sizeToMerge) { - return true; - } - - return false; + return $poolSize >= $sizeToMerge; } /** @@ -408,7 +403,7 @@ private function _updateSegments() $generation = Zend_Search_Lucene::getActualGeneration($this->_directory); $segmentsFile = $this->_directory->getFileObject(Zend_Search_Lucene::getSegmentFileName($generation), false); - $newSegmentFile = $this->_directory->createFile(Zend_Search_Lucene::getSegmentFileName(++$generation), false); + $newSegmentFile = $this->_directory->createFile(Zend_Search_Lucene::getSegmentFileName(++$generation)); try { $genFile = $this->_directory->getFileObject('segments.gen', false); @@ -428,17 +423,17 @@ private function _updateSegments() // Write format marker if ($this->_targetFormatVersion == Zend_Search_Lucene::FORMAT_2_1) { $newSegmentFile->writeInt((int)0xFFFFFFFD); - } else if ($this->_targetFormatVersion == Zend_Search_Lucene::FORMAT_2_3) { + } elseif ($this->_targetFormatVersion == Zend_Search_Lucene::FORMAT_2_3) { $newSegmentFile->writeInt((int)0xFFFFFFFC); } // Read src file format identifier $format = $segmentsFile->readInt(); - if ($format == (int)0xFFFFFFFF) { + if ($format === (int)0xFFFFFFFF) { $srcFormat = Zend_Search_Lucene::FORMAT_PRE_2_1; - } else if ($format == (int)0xFFFFFFFD) { + } elseif ($format == (int)0xFFFFFFFD) { $srcFormat = Zend_Search_Lucene::FORMAT_2_1; - } else if ($format == (int)0xFFFFFFFC) { + } elseif ($format == (int)0xFFFFFFFC) { $srcFormat = Zend_Search_Lucene::FORMAT_2_3; } else { throw new Zend_Search_Lucene_Exception('Unsupported segments file format'); @@ -477,7 +472,7 @@ private function _updateSegments() if ($srcFormat == Zend_Search_Lucene::FORMAT_2_3) { $docStoreOffset = $segmentsFile->readInt(); - if ($docStoreOffset != (int)0xFFFFFFFF) { + if ($docStoreOffset !== (int)0xFFFFFFFF) { $docStoreSegment = $segmentsFile->readString(); $docStoreIsCompoundFile = $segmentsFile->readByte(); @@ -495,7 +490,7 @@ private function _updateSegments() $numField = $segmentsFile->readInt(); $normGens = array(); - if ($numField != (int)0xFFFFFFFF) { + if ($numField !== (int)0xFFFFFFFF) { for ($count1 = 0; $count1 < $numField; $count1++) { $normGens[] = $segmentsFile->readLong(); } @@ -509,10 +504,10 @@ private function _updateSegments() if ($isCompoundByte == 0xFF) { // The segment is not a compound file $isCompound = false; - } else if ($isCompoundByte == 0x00) { + } elseif ($isCompoundByte == 0x00) { // The status is unknown $isCompound = null; - } else if ($isCompoundByte == 0x01) { + } elseif ($isCompoundByte == 0x01) { // The segment is a compound file $isCompound = true; } @@ -544,16 +539,15 @@ private function _updateSegments() // Set DocStoreOffset to -1 $newSegmentFile->writeInt((int)0xFFFFFFFF); } - } else if ($docStoreOptions !== null) { + } elseif ($docStoreOptions !== null) { // Release index write lock Zend_Search_Lucene_LockManager::releaseWriteLock($this->_directory); - throw new Zend_Search_Lucene_Exception('Index conversion to lower format version is not supported.'); } $newSegmentFile->writeByte($hasSingleNormFile); $newSegmentFile->writeInt($numField); - if ($numField != (int)0xFFFFFFFF) { + if ($numField !== (int)0xFFFFFFFF) { foreach ($normGens as $normGen) { $newSegmentFile->writeLong($normGen); } @@ -630,14 +624,16 @@ private function _updateSegments() if ($file == 'deletable') { // 'deletable' file $filesToDelete[] = $file; - $filesTypes[] = 0; // delete this file first, since it's not used starting from Lucene v2.1 + $filesTypes[] = 0; + // delete this file first, since it's not used starting from Lucene v2.1 $filesNumbers[] = 0; - } else if ($file == 'segments') { + } elseif ($file == 'segments') { // 'segments' file $filesToDelete[] = $file; - $filesTypes[] = 1; // second file to be deleted "zero" version of segments file (Lucene pre-2.1) + $filesTypes[] = 1; + // second file to be deleted "zero" version of segments file (Lucene pre-2.1) $filesNumbers[] = 0; - } else if (preg_match('/^segments_[a-zA-Z0-9]+$/i', (string) $file)) { + } elseif (preg_match('/^segments_[a-zA-Z0-9]+$/i', (string) $file)) { // 'segments_xxx' file // Check if it's not a just created generation file if ($file != Zend_Search_Lucene::getSegmentFileName($generation)) { @@ -645,7 +641,7 @@ private function _updateSegments() $filesTypes[] = 2; // first group of files for deletions $filesNumbers[] = (int)base_convert(substr($file, 9), 36, 10); // ordered by segment generation numbers } - } else if (preg_match('/(^_([a-zA-Z0-9]+))\.f\d+$/i', (string) $file, $matches)) { + } elseif (preg_match('/(^_([a-zA-Z0-9]+))\.f\d+$/i', (string) $file, $matches)) { // one of per segment files ('.f') // Check if it's not one of the segments in the current segments set if (!isset($segments[$matches[1]])) { @@ -653,7 +649,7 @@ private function _updateSegments() $filesTypes[] = 3; // second group of files for deletions $filesNumbers[] = (int)base_convert($matches[2], 36, 10); // order by segment number } - } else if (preg_match('/(^_([a-zA-Z0-9]+))(_([a-zA-Z0-9]+))\.del$/i', (string) $file, $matches)) { + } elseif (preg_match('/(^_([a-zA-Z0-9]+))(_([a-zA-Z0-9]+))\.del$/i', (string) $file, $matches)) { // one of per segment files ('_.del' where is '_') // Check if it's not one of the segments in the current segments set if (!isset($segments[$matches[1]])) { @@ -668,12 +664,12 @@ private function _updateSegments() } $delFiles[$segmentNumber][$delGeneration] = $file; } - } else if (isset(self::$_indexExtensions[substr($file, strlen((string) $file)-4)])) { + } elseif (isset(self::$_indexExtensions[substr($file, strlen((string) $file)-4)])) { // one of per segment files ('.') $segmentName = substr($file, 0, strlen((string) $file) - 4); // Check if it's not one of the segments in the current segments set if (!isset($segments[$segmentName]) && - ($this->_currentSegment === null || $this->_currentSegment->getName() != $segmentName)) { + ($this->_currentSegment === null || $this->_currentSegment->getName() !== $segmentName)) { $filesToDelete[] = $file; $filesTypes[] = 3; // second group of files for deletions $filesNumbers[] = (int)base_convert(substr($file, 1 /* skip '_' */, strlen((string) $file)-5), 36, 10); // order by segment number @@ -683,7 +679,7 @@ private function _updateSegments() $maxGenNumber = 0; // process .del files of currently used segments - foreach ($delFiles as $segmentNumber => $segmentDelFiles) { + foreach (array_keys($delFiles) as $segmentNumber) { ksort($delFiles[$segmentNumber], SORT_NUMERIC); array_pop($delFiles[$segmentNumber]); // remove last delete file generation from candidates for deleting @@ -741,7 +737,7 @@ private function _updateSegments() Zend_Search_Lucene_LockManager::releaseWriteLock($this->_directory); // Remove unused segments from segments list - foreach ($this->_segmentInfos as $segName => $segmentInfo) { + foreach (array_keys($this->_segmentInfos) as $segName) { if (!isset($segments[$segName])) { unset($this->_segmentInfos[$segName]); } diff --git a/library/Zend/Search/Lucene/Search/Query/Boolean.php b/library/Zend/Search/Lucene/Search/Query/Boolean.php index a245d3ef11..8469e14b5a 100644 --- a/library/Zend/Search/Lucene/Search/Query/Boolean.php +++ b/library/Zend/Search/Lucene/Search/Query/Boolean.php @@ -258,14 +258,12 @@ public function optimize(Zend_Search_Lucene_Interface $index) $terms[] = $subquery->getTerm(); $tsigns[] = $signs[$id]; $boostFactors[] = $subquery->getBoost(); - // remove subquery from a subqueries list unset($subqueries[$id]); unset($signs[$id]); - } else if ($subquery instanceof Zend_Search_Lucene_Search_Query_MultiTerm) { + } elseif ($subquery instanceof Zend_Search_Lucene_Search_Query_MultiTerm) { $subTerms = $subquery->getTerms(); $subSigns = $subquery->getSigns(); - if ($signs[$id] === true) { // It's a required multi-term subquery. // Something like '... +(+term1 -term2 term3 ...) ...' @@ -284,7 +282,7 @@ public function optimize(Zend_Search_Lucene_Interface $index) foreach ($subSigns as $sign) { if ($sign === true) { $hasRequired = true; - } else if ($sign === false) { + } elseif ($sign === false) { $hasProhibited = true; break; } @@ -384,21 +382,17 @@ public function optimize(Zend_Search_Lucene_Interface $index) require_once 'Zend/Search/Lucene/Search/Query/Term.php'; $clause = new Zend_Search_Lucene_Search_Query_Term(reset($terms)); $clause->setBoost(reset($boostFactors)); - $subqueries[] = $clause; $signs[] = reset($tsigns); - // Clear terms list $terms = array(); - } else if (count($terms) > 1 && count(array_unique($boostFactors)) == 1) { + } elseif (count($terms) > 1 && count(array_unique($boostFactors)) == 1) { require_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php'; $clause = new Zend_Search_Lucene_Search_Query_MultiTerm($terms, $tsigns); $clause->setBoost(reset($boostFactors)); - $subqueries[] = $clause; // Clause sign is 'required' if clause contains required terms. 'Optional' otherwise. $signs[] = (in_array(true, $tsigns))? true : null; - // Clear terms list $terms = array(); } @@ -408,23 +402,20 @@ public function optimize(Zend_Search_Lucene_Interface $index) require_once 'Zend/Search/Lucene/Search/Query/Term.php'; $subqueries[] = new Zend_Search_Lucene_Search_Query_Term(reset($prohibitedTerms)); $signs[] = false; - // Clear prohibited terms list $prohibitedTerms = array(); - } else if (count($prohibitedTerms) > 1) { + } elseif (count($prohibitedTerms) > 1) { // prepare signs array $prohibitedSigns = array(); - foreach ($prohibitedTerms as $id => $term) { + foreach (array_keys($prohibitedTerms) as $id) { // all prohibited term are grouped as optional into multi-term query $prohibitedSigns[$id] = null; } - // (boost factors are not significant for prohibited clauses) require_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php'; $subqueries[] = new Zend_Search_Lucene_Search_Query_MultiTerm($prohibitedTerms, $prohibitedSigns); // Clause sign is 'prohibited' $signs[] = false; - // Clear terms list $prohibitedTerms = array(); } @@ -512,11 +503,7 @@ private function _calculateConjunctionResult() * This code is used as workaround for array_intersect_key() slowness problem. */ $updatedVector = array(); - foreach ($this->_resVector as $id => $value) { - if (isset($nextResVector[$id])) { - $updatedVector[$id] = $value; - } - } + $updatedVector = array_filter($this->_resVector, fn($value) => isset($nextResVector[$id])); $this->_resVector = $updatedVector; } @@ -577,11 +564,7 @@ private function _calculateNonConjunctionResult() * This code is used as workaround for array_intersect_key() slowness problem. */ $updatedVector = array(); - foreach ($required as $id => $value) { - if (isset($nextResVector[$id])) { - $updatedVector[$id] = $value; - } - } + $updatedVector = array_filter($required, fn($value) => isset($nextResVector[$id])); $required = $updatedVector; } @@ -798,7 +781,7 @@ public function __toString() if ($this->_signs === null || $this->_signs[$id] === true) { $query .= '+'; - } else if ($this->_signs[$id] === false) { + } elseif ($this->_signs[$id] === false) { $query .= '-'; } diff --git a/library/Zend/Search/Lucene/Search/Query/Fuzzy.php b/library/Zend/Search/Lucene/Search/Query/Fuzzy.php index 99588b16f2..1bec68a991 100644 --- a/library/Zend/Search/Lucene/Search/Query/Fuzzy.php +++ b/library/Zend/Search/Lucene/Search/Query/Fuzzy.php @@ -186,12 +186,7 @@ public function rewrite(Zend_Search_Lucene_Interface $index) $this->_scores = array(); $this->_termKeys = array(); - if ($this->_term->field === null) { - // Search through all fields - $fields = $index->getFieldNames(true /* indexed fields list */); - } else { - $fields = array($this->_term->field); - } + $fields = $this->_term->field === null ? $index->getFieldNames(true /* indexed fields list */) : array($this->_term->field); require_once 'Zend/Search/Lucene/Index/Term.php'; $prefix = Zend_Search_Lucene_Index_Term::getPrefix($this->_term->text, $this->_prefixLength); @@ -217,7 +212,7 @@ public function rewrite(Zend_Search_Lucene_Interface $index) while ($index->currentTerm() !== null && $index->currentTerm()->field == $field && - substr($index->currentTerm()->text, 0, $prefixByteLength) == $prefix) { + substr($index->currentTerm()->text, 0, $prefixByteLength) === $prefix) { // Calculate similarity $target = substr($index->currentTerm()->text, $prefixByteLength); @@ -229,9 +224,9 @@ public function rewrite(Zend_Search_Lucene_Interface $index) // we don't have anything to compare. That means if we just add // the letters for current term we get the new word $similarity = (($prefixUtf8Length == 0)? 0 : 1 - strlen($target)/$prefixUtf8Length); - } else if (strlen($target) == 0) { + } elseif (strlen($target) == 0) { $similarity = (($prefixUtf8Length == 0)? 0 : 1 - $termRestLength/$prefixUtf8Length); - } else if ($maxDistance < abs($termRestLength - strlen($target))){ + } elseif ($maxDistance < abs($termRestLength - strlen($target))) { //just adding the characters of term to target or vice-versa results in too many edits //for example "pre" length is 3 and "prefixes" length is 8. We can see that //given this optimal circumstance, the edit distance cannot be less than 5. @@ -300,7 +295,7 @@ public function rewrite(Zend_Search_Lucene_Interface $index) if (count($this->_matches) == 0) { require_once 'Zend/Search/Lucene/Search/Query/Empty.php'; return new Zend_Search_Lucene_Search_Query_Empty(); - } else if (count($this->_matches) == 1) { + } elseif (count($this->_matches) == 1) { require_once 'Zend/Search/Lucene/Search/Query/Term.php'; return new Zend_Search_Lucene_Search_Query_Term(reset($this->_matches)); } else { @@ -441,7 +436,7 @@ protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Inter foreach ($tokens as $token) { $termText = $token->getTermText(); - if (substr($termText, 0, $prefixByteLength) == $prefix) { + if (substr($termText, 0, $prefixByteLength) === $prefix) { // Calculate similarity $target = substr($termText, $prefixByteLength); @@ -453,9 +448,9 @@ protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Inter // we don't have anything to compare. That means if we just add // the letters for current term we get the new word $similarity = (($prefixUtf8Length == 0)? 0 : 1 - strlen($target)/$prefixUtf8Length); - } else if (strlen($target) == 0) { + } elseif (strlen($target) == 0) { $similarity = (($prefixUtf8Length == 0)? 0 : 1 - $termRestLength/$prefixUtf8Length); - } else if ($maxDistance < abs($termRestLength - strlen($target))){ + } elseif ($maxDistance < abs($termRestLength - strlen($target))) { //just adding the characters of term to target or vice-versa results in too many edits //for example "pre" length is 3 and "prefixes" length is 8. We can see that //given this optimal circumstance, the edit distance cannot be less than 5. diff --git a/library/Zend/Search/Lucene/Search/Query/MultiTerm.php b/library/Zend/Search/Lucene/Search/Query/MultiTerm.php index c31cd67893..3d84fca320 100644 --- a/library/Zend/Search/Lucene/Search/Query/MultiTerm.php +++ b/library/Zend/Search/Lucene/Search/Query/MultiTerm.php @@ -423,11 +423,7 @@ private function _calculateNonConjunctionResult(Zend_Search_Lucene_Interface $re } } - if ($required !== null) { - $this->_resVector = $required; - } else { - $this->_resVector = $optional; - } + $this->_resVector = $required !== null ? $required : $optional; if (count($prohibited) != 0) { // $this->_resVector = array_diff_key($this->_resVector, $prohibited); @@ -437,7 +433,7 @@ private function _calculateNonConjunctionResult(Zend_Search_Lucene_Interface $re */ if (count($this->_resVector) < count($prohibited)) { $updatedVector = $this->_resVector; - foreach ($this->_resVector as $id => $value) { + foreach (array_keys($this->_resVector) as $id) { if (isset($prohibited[$id])) { unset($updatedVector[$id]); } @@ -445,7 +441,7 @@ private function _calculateNonConjunctionResult(Zend_Search_Lucene_Interface $re $this->_resVector = $updatedVector; } else { $updatedVector = $this->_resVector; - foreach ($prohibited as $id => $value) { + foreach (array_keys($prohibited) as $id) { unset($updatedVector[$id]); } $this->_resVector = $updatedVector; @@ -648,7 +644,7 @@ public function __toString() if ($this->_signs === null || $this->_signs[$id] === true) { $query .= '+'; - } else if ($this->_signs[$id] === false) { + } elseif ($this->_signs[$id] === false) { $query .= '-'; } diff --git a/library/Zend/Search/Lucene/Search/Query/Phrase.php b/library/Zend/Search/Lucene/Search/Query/Phrase.php index 06347af245..a0703f63e9 100644 --- a/library/Zend/Search/Lucene/Search/Query/Phrase.php +++ b/library/Zend/Search/Lucene/Search/Query/Phrase.php @@ -36,6 +36,10 @@ */ class Zend_Search_Lucene_Search_Query_Phrase extends Zend_Search_Lucene_Search_Query { + /** + * @var \Zend_Search_Lucene_Search_Weight_Term[] + */ + public array $_weights; /** * Terms to find. * Array of Zend_Search_Lucene_Index_Term objects. @@ -107,7 +111,7 @@ public function __construct($terms = null, $offsets = null, $field = null) $this->_terms[$termId] = ($field !== null)? new Zend_Search_Lucene_Index_Term($termText, $field): new Zend_Search_Lucene_Index_Term($termText); } - } else if ($terms === null) { + } elseif ($terms === null) { $this->_terms = array(); } else { require_once 'Zend/Search/Lucene/Exception.php'; @@ -115,14 +119,14 @@ public function __construct($terms = null, $offsets = null, $field = null) } if (is_array($offsets)) { - if (count($this->_terms) != count($offsets)) { + if (count($this->_terms) !== count($offsets)) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('terms and offsets arguments must have the same size.'); } $this->_offsets = $offsets; - } else if ($offsets === null) { + } elseif ($offsets === null) { $this->_offsets = array(); - foreach ($this->_terms as $termId => $term) { + foreach (array_keys($this->_terms) as $termId) { $position = count($this->_offsets); $this->_offsets[$termId] = $position; } @@ -172,11 +176,7 @@ public function addTerm(Zend_Search_Lucene_Index_Term $term, $position = null) { $this->_terms[] = $term; if ($position !== null) { $this->_offsets[] = $position; - } else if (count($this->_offsets) != 0) { - $this->_offsets[] = end($this->_offsets) + 1; - } else { - $this->_offsets[] = 0; - } + } else $this->_offsets[] = count($this->_offsets) != 0 ? end($this->_offsets) + 1 : 0; } @@ -191,7 +191,7 @@ public function rewrite(Zend_Search_Lucene_Interface $index) if (count($this->_terms) == 0) { require_once 'Zend/Search/Lucene/Search/Query/Empty.php'; return new Zend_Search_Lucene_Search_Query_Empty(); - } else if ($this->_terms[0]->field !== null) { + } elseif ($this->_terms[0]->field !== null) { return $this; } else { require_once 'Zend/Search/Lucene/Search/Query/Boolean.php'; @@ -301,7 +301,7 @@ public function _exactPhraseFreq($docId) $lowCardTermId = null; // Calculate $lowCardTermId - foreach ($this->_terms as $termId => $term) { + foreach (array_keys($this->_terms) as $termId) { if ($lowCardTermId === null || count($this->_termsPositions[$termId][$docId]) < count($this->_termsPositions[$lowCardTermId][$docId]) ) { @@ -315,7 +315,7 @@ public function _exactPhraseFreq($docId) $freq++; // Walk through other terms - foreach ($this->_terms as $termId => $term) { + foreach (array_keys($this->_terms) as $termId) { if ($termId != $lowCardTermId) { $expectedPosition = $lowCardPos + ($this->_offsets[$termId] - @@ -348,7 +348,7 @@ public function _sloppyPhraseFreq($docId, Zend_Search_Lucene_Interface $reader) $lastTerm = null; // Walk through the terms to create phrases. - foreach ($this->_terms as $termId => $term) { + foreach (array_keys($this->_terms) as $termId) { $queueSize = count($phraseQueue); $firstPass = true; @@ -387,7 +387,7 @@ public function _sloppyPhraseFreq($docId, Zend_Search_Lucene_Interface $reader) $distance = 0; $start = reset($phrasePos) - reset($this->_offsets) + $shift; - foreach ($this->_terms as $termId => $term) { + foreach (array_keys($this->_terms) as $termId) { $distance += abs($phrasePos[$termId] - $this->_offsets[$termId] - $start); if($distance > $this->_slop) { @@ -491,11 +491,7 @@ public function matchedDocs() public function score($docId, Zend_Search_Lucene_Interface $reader) { if (isset($this->_resVector[$docId])) { - if ($this->_slop == 0) { - $freq = $this->_exactPhraseFreq($docId); - } else { - $freq = $this->_sloppyPhraseFreq($docId, $reader); - } + $freq = $this->_slop == 0 ? $this->_exactPhraseFreq($docId) : $this->_sloppyPhraseFreq($docId, $reader); if ($freq != 0) { $tf = $reader->getSimilarity()->tf($freq); @@ -545,11 +541,7 @@ protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Inter public function __toString() { // It's used only for query visualisation, so we don't care about characters escaping - if (isset($this->_terms[0]) && $this->_terms[0]->field !== null) { - $query = $this->_terms[0]->field . ':'; - } else { - $query = ''; - } + $query = isset($this->_terms[0]) && $this->_terms[0]->field !== null ? $this->_terms[0]->field . ':' : ''; $query .= '"'; diff --git a/library/Zend/Search/Lucene/Search/Query/Preprocessing/Fuzzy.php b/library/Zend/Search/Lucene/Search/Query/Preprocessing/Fuzzy.php index a598de22a2..11e84c5b70 100644 --- a/library/Zend/Search/Lucene/Search/Query/Preprocessing/Fuzzy.php +++ b/library/Zend/Search/Lucene/Search/Query/Preprocessing/Fuzzy.php @@ -117,8 +117,7 @@ public function rewrite(Zend_Search_Lucene_Interface $index) $rewrittenSubquery = $subquery->rewrite($index); - if ( !($rewrittenSubquery instanceof Zend_Search_Lucene_Search_Query_Insignificant || - $rewrittenSubquery instanceof Zend_Search_Lucene_Search_Query_Empty) ) { + if ( !$rewrittenSubquery instanceof Zend_Search_Lucene_Search_Query_Insignificant && !$rewrittenSubquery instanceof Zend_Search_Lucene_Search_Query_Empty ) { $query->addSubquery($rewrittenSubquery); } @@ -270,11 +269,7 @@ protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Inter public function __toString() { // It's used only for query visualisation, so we don't care about characters escaping - if ($this->_field !== null) { - $query = $this->_field . ':'; - } else { - $query = ''; - } + $query = $this->_field !== null ? $this->_field . ':' : ''; $query .= $this->_word; diff --git a/library/Zend/Search/Lucene/Search/Query/Preprocessing/Phrase.php b/library/Zend/Search/Lucene/Search/Query/Preprocessing/Phrase.php index 0829a8eba4..10a74e01e3 100644 --- a/library/Zend/Search/Lucene/Search/Query/Preprocessing/Phrase.php +++ b/library/Zend/Search/Lucene/Search/Query/Preprocessing/Phrase.php @@ -249,11 +249,7 @@ protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Inter public function __toString() { // It's used only for query visualisation, so we don't care about characters escaping - if ($this->_field !== null) { - $query = $this->_field . ':'; - } else { - $query = ''; - } + $query = $this->_field !== null ? $this->_field . ':' : ''; $query .= '"' . $this->_phrase . '"'; diff --git a/library/Zend/Search/Lucene/Search/Query/Preprocessing/Term.php b/library/Zend/Search/Lucene/Search/Query/Preprocessing/Term.php index 2c34b54c41..f22b6f6f90 100644 --- a/library/Zend/Search/Lucene/Search/Query/Preprocessing/Term.php +++ b/library/Zend/Search/Lucene/Search/Query/Preprocessing/Term.php @@ -324,11 +324,7 @@ protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Inter public function __toString() { // It's used only for query visualisation, so we don't care about characters escaping - if ($this->_field !== null) { - $query = $this->_field . ':'; - } else { - $query = ''; - } + $query = $this->_field !== null ? $this->_field . ':' : ''; $query .= $this->_word; diff --git a/library/Zend/Search/Lucene/Search/Query/Range.php b/library/Zend/Search/Lucene/Search/Query/Range.php index 699ddb5d4f..4126f1240b 100644 --- a/library/Zend/Search/Lucene/Search/Query/Range.php +++ b/library/Zend/Search/Lucene/Search/Query/Range.php @@ -152,12 +152,7 @@ public function rewrite(Zend_Search_Lucene_Interface $index) { $this->_matches = array(); - if ($this->_field === null) { - // Search through all fields - $fields = $index->getFieldNames(true /* indexed fields list */); - } else { - $fields = array($this->_field); - } + $fields = $this->_field === null ? $index->getFieldNames(true /* indexed fields list */) : array($this->_field); require_once 'Zend/Search/Lucene.php'; $maxTerms = Zend_Search_Lucene::getTermsPerQueryLimit(); @@ -221,7 +216,7 @@ public function rewrite(Zend_Search_Lucene_Interface $index) if (count($this->_matches) == 0) { require_once 'Zend/Search/Lucene/Search/Query/Empty.php'; return new Zend_Search_Lucene_Search_Query_Empty(); - } else if (count($this->_matches) == 1) { + } elseif (count($this->_matches) == 1) { require_once 'Zend/Search/Lucene/Search/Query/Term.php'; return new Zend_Search_Lucene_Search_Query_Term(reset($this->_matches)); } else { diff --git a/library/Zend/Search/Lucene/Search/Query/Term.php b/library/Zend/Search/Lucene/Search/Query/Term.php index 434a268124..d9f104c4e0 100644 --- a/library/Zend/Search/Lucene/Search/Query/Term.php +++ b/library/Zend/Search/Lucene/Search/Query/Term.php @@ -210,11 +210,7 @@ protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Inter public function __toString() { // It's used only for query visualisation, so we don't care about characters escaping - if ($this->_term->field !== null) { - $query = $this->_term->field . ':'; - } else { - $query = ''; - } + $query = $this->_term->field !== null ? $this->_term->field . ':' : ''; $query .= $this->_term->text; diff --git a/library/Zend/Search/Lucene/Search/Query/Wildcard.php b/library/Zend/Search/Lucene/Search/Query/Wildcard.php index 82cd4557f8..74ddaf61f7 100644 --- a/library/Zend/Search/Lucene/Search/Query/Wildcard.php +++ b/library/Zend/Search/Lucene/Search/Query/Wildcard.php @@ -109,9 +109,8 @@ private static function _getPrefix($word) if ($astrericPosition !== false) { return substr($word, 0, min($questionMarkPosition, $astrericPosition)); } - return substr($word, 0, $questionMarkPosition); - } else if ($astrericPosition !== false) { + } elseif ($astrericPosition !== false) { return substr($word, 0, $astrericPosition); } @@ -129,12 +128,7 @@ public function rewrite(Zend_Search_Lucene_Interface $index) { $this->_matches = array(); - if ($this->_pattern->field === null) { - // Search through all fields - $fields = $index->getFieldNames(true /* indexed fields list */); - } else { - $fields = array($this->_pattern->field); - } + $fields = $this->_pattern->field === null ? $index->getFieldNames(true /* indexed fields list */) : array($this->_pattern->field); $prefix = self::_getPrefix($this->_pattern->text); $prefixLength = strlen($prefix); @@ -162,7 +156,7 @@ public function rewrite(Zend_Search_Lucene_Interface $index) while ($index->currentTerm() !== null && $index->currentTerm()->field == $field && - substr($index->currentTerm()->text, 0, $prefixLength) == $prefix) { + substr($index->currentTerm()->text, 0, $prefixLength) === $prefix) { if (preg_match($matchExpression, $index->currentTerm()->text) === 1) { $this->_matches[] = $index->currentTerm(); @@ -197,7 +191,7 @@ public function rewrite(Zend_Search_Lucene_Interface $index) if (count($this->_matches) == 0) { require_once 'Zend/Search/Lucene/Search/Query/Empty.php'; return new Zend_Search_Lucene_Search_Query_Empty(); - } else if (count($this->_matches) == 1) { + } elseif (count($this->_matches) == 1) { require_once 'Zend/Search/Lucene/Search/Query/Term.php'; return new Zend_Search_Lucene_Search_Query_Term(reset($this->_matches)); } else { @@ -344,11 +338,7 @@ protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Inter public function __toString() { // It's used only for query visualisation, so we don't care about characters escaping - if ($this->_pattern->field !== null) { - $query = $this->_pattern->field . ':'; - } else { - $query = ''; - } + $query = $this->_pattern->field !== null ? $this->_pattern->field . ':' : ''; $query .= $this->_pattern->text; diff --git a/library/Zend/Search/Lucene/Search/QueryLexer.php b/library/Zend/Search/Lucene/Search/QueryLexer.php index 78d8ab829e..c9a9aa84b2 100644 --- a/library/Zend/Search/Lucene/Search/QueryLexer.php +++ b/library/Zend/Search/Lucene/Search/QueryLexer.php @@ -308,14 +308,22 @@ public function __construct() */ private function _translateInput($char) { - if (strpos(self::QUERY_WHITE_SPACE_CHARS, $char) !== false) { return self::IN_WHITE_SPACE; - } else if (strpos(self::QUERY_SYNT_CHARS, $char) !== false) { return self::IN_SYNT_CHAR; - } else if (strpos(self::QUERY_MUTABLE_CHARS, $char) !== false) { return self::IN_MUTABLE_CHAR; - } else if (strpos(self::QUERY_LEXEMEMODIFIER_CHARS, $char) !== false) { return self::IN_LEXEME_MODIFIER; - } else if (strpos(self::QUERY_ASCIIDIGITS_CHARS, $char) !== false) { return self::IN_ASCII_DIGIT; - } else if ($char === '"' ) { return self::IN_QUOTE; - } else if ($char === '.' ) { return self::IN_DECIMAL_POINT; - } else if ($char === '\\') { return self::IN_ESCAPE_CHAR; + if (strpos(self::QUERY_WHITE_SPACE_CHARS, $char) !== false) { + return self::IN_WHITE_SPACE; + } elseif (strpos(self::QUERY_SYNT_CHARS, $char) !== false) { + return self::IN_SYNT_CHAR; + } elseif (strpos(self::QUERY_MUTABLE_CHARS, $char) !== false) { + return self::IN_MUTABLE_CHAR; + } elseif (strpos(self::QUERY_LEXEMEMODIFIER_CHARS, $char) !== false) { + return self::IN_LEXEME_MODIFIER; + } elseif (strpos(self::QUERY_ASCIIDIGITS_CHARS, $char) !== false) { + return self::IN_ASCII_DIGIT; + } elseif ($char === '"') { + return self::IN_QUOTE; + } elseif ($char === '.') { + return self::IN_DECIMAL_POINT; + } elseif ($char === '\\') { + return self::IN_ESCAPE_CHAR; } else { return self::IN_CHAR; } } @@ -348,9 +356,7 @@ public function tokenize($inputString, $encoding) $this->_queryString[$count] = iconv_substr($inputString, $count, 1, $encoding); } - for ($this->_queryStringPosition = 0; - $this->_queryStringPosition < count($this->_queryString); - $this->_queryStringPosition++) { + foreach (array_keys($this->_queryString) as $_queryStringPosition) { $this->process($this->_translateInput($this->_queryString[$this->_queryStringPosition])); } diff --git a/library/Zend/Search/Lucene/Search/QueryParser.php b/library/Zend/Search/Lucene/Search/QueryParser.php index 119cc07331..e79d03ed85 100644 --- a/library/Zend/Search/Lucene/Search/QueryParser.php +++ b/library/Zend/Search/Lucene/Search/QueryParser.php @@ -390,7 +390,7 @@ public static function parse($strQuery, $encoding = null) } } - if (count(self::$_instance->_contextStack) != 0) { + if (self::$_instance->_contextStack !== []) { throw new Zend_Search_Lucene_Search_QueryParserException('Syntax Error: mismatched parentheses, every opening must have closing.' ); } @@ -553,7 +553,7 @@ public function openedRQLastTerm() if (count($tokens) > 1) { require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; throw new Zend_Search_Lucene_Search_QueryParserException('Range query boundary terms must be non-multiple word terms'); - } else if (count($tokens) == 1) { + } elseif (count($tokens) == 1) { require_once 'Zend/Search/Lucene/Index/Term.php'; $from = new Zend_Search_Lucene_Index_Term(reset($tokens)->getTermText(), $this->_context->getField()); } else { @@ -564,7 +564,7 @@ public function openedRQLastTerm() if (count($tokens) > 1) { require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; throw new Zend_Search_Lucene_Search_QueryParserException('Range query boundary terms must be non-multiple word terms'); - } else if (count($tokens) == 1) { + } elseif (count($tokens) == 1) { require_once 'Zend/Search/Lucene/Index/Term.php'; $to = new Zend_Search_Lucene_Index_Term(reset($tokens)->getTermText(), $this->_context->getField()); } else { @@ -602,7 +602,7 @@ public function closedRQLastTerm() if (count($tokens) > 1) { require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; throw new Zend_Search_Lucene_Search_QueryParserException('Range query boundary terms must be non-multiple word terms'); - } else if (count($tokens) == 1) { + } elseif (count($tokens) == 1) { require_once 'Zend/Search/Lucene/Index/Term.php'; $from = new Zend_Search_Lucene_Index_Term(reset($tokens)->getTermText(), $this->_context->getField()); } else { @@ -613,7 +613,7 @@ public function closedRQLastTerm() if (count($tokens) > 1) { require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; throw new Zend_Search_Lucene_Search_QueryParserException('Range query boundary terms must be non-multiple word terms'); - } else if (count($tokens) == 1) { + } elseif (count($tokens) == 1) { require_once 'Zend/Search/Lucene/Index/Term.php'; $to = new Zend_Search_Lucene_Index_Term(reset($tokens)->getTermText(), $this->_context->getField()); } else { diff --git a/library/Zend/Search/Lucene/Search/QueryParserContext.php b/library/Zend/Search/Lucene/Search/QueryParserContext.php index ebbd332e87..e7d3b8e7bc 100644 --- a/library/Zend/Search/Lucene/Search/QueryParserContext.php +++ b/library/Zend/Search/Lucene/Search/QueryParserContext.php @@ -149,7 +149,7 @@ public function setNextEntrySign($sign) if ($sign == Zend_Search_Lucene_Search_QueryToken::TT_REQUIRED) { $this->_nextEntrySign = true; - } else if ($sign == Zend_Search_Lucene_Search_QueryToken::TT_PROHIBITED) { + } elseif ($sign == Zend_Search_Lucene_Search_QueryToken::TT_PROHIBITED) { $this->_nextEntrySign = false; } else { require_once 'Zend/Search/Lucene/Exception.php'; diff --git a/library/Zend/Search/Lucene/Search/QueryToken.php b/library/Zend/Search/Lucene/Search/QueryToken.php index 3eab279b89..d799ff84ec 100644 --- a/library/Zend/Search/Lucene/Search/QueryToken.php +++ b/library/Zend/Search/Lucene/Search/QueryToken.php @@ -129,17 +129,13 @@ public function __construct($tokenCategory, $tokenText, $position) switch ($tokenCategory) { case self::TC_WORD: - if ( strtolower($tokenText) == 'and') { + if (strtolower($tokenText) == 'and') { $this->type = self::TT_AND_LEXEME; - } else if (strtolower($tokenText) == 'or') { + } elseif (strtolower($tokenText) == 'or') { $this->type = self::TT_OR_LEXEME; - } else if (strtolower($tokenText) == 'not') { + } elseif (strtolower($tokenText) == 'not') { $this->type = self::TT_NOT_LEXEME; - } else if (strtolower($tokenText) == 'to') { - $this->type = self::TT_TO_LEXEME; - } else { - $this->type = self::TT_WORD; - } + } else $this->type = strtolower($tokenText) == 'to' ? self::TT_TO_LEXEME : self::TT_WORD; break; case self::TC_PHRASE: diff --git a/library/Zend/Search/Lucene/Search/Weight/Phrase.php b/library/Zend/Search/Lucene/Search/Weight/Phrase.php index d76a1ec2bb..bd2b94ab32 100644 --- a/library/Zend/Search/Lucene/Search/Weight/Phrase.php +++ b/library/Zend/Search/Lucene/Search/Weight/Phrase.php @@ -36,6 +36,10 @@ */ class Zend_Search_Lucene_Search_Weight_Phrase extends Zend_Search_Lucene_Search_Weight { + /** + * @var mixed + */ + public $_queryWeight; /** * IndexReader. * diff --git a/library/Zend/Search/Lucene/Storage/Directory/Filesystem.php b/library/Zend/Search/Lucene/Storage/Directory/Filesystem.php index 489f9c3d30..f700819559 100644 --- a/library/Zend/Search/Lucene/Storage/Directory/Filesystem.php +++ b/library/Zend/Search/Lucene/Storage/Directory/Filesystem.php @@ -92,7 +92,7 @@ public static function setDefaultFilePermissions($mode) public static function mkdirs($dir, $mode = 0775, $recursive = true) { - $mode = $mode & ~0002; + $mode &= ~0002; if (($dir === null) || $dir === '') { return false; @@ -120,11 +120,9 @@ public function __construct($path) if (file_exists($path)) { require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Path exists, but it\'s not a directory'); - } else { - if (!self::mkdirs($path)) { - require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception("Can't create directory '$path'."); - } + } elseif (!self::mkdirs($path)) { + require_once 'Zend/Search/Lucene/Exception.php'; + throw new Zend_Search_Lucene_Exception("Can't create directory '$path'."); } } $this->_dirPath = $path; @@ -297,11 +295,9 @@ public function renameFile($from, $to) } unset($this->_fileHandlers[$to]); - if (file_exists($this->_dirPath . '/' . $to)) { - if (!unlink($this->_dirPath . '/' . $to)) { - require_once 'Zend/Search/Lucene/Exception.php'; - throw new Zend_Search_Lucene_Exception('Delete operation failed'); - } + if (file_exists($this->_dirPath . '/' . $to) && !unlink($this->_dirPath . '/' . $to)) { + require_once 'Zend/Search/Lucene/Exception.php'; + throw new Zend_Search_Lucene_Exception('Delete operation failed'); } $trackErrors = ini_get('track_errors'); diff --git a/library/Zend/Search/Lucene/Storage/File.php b/library/Zend/Search/Lucene/Storage/File.php index 9eedb9b3d4..faa8d5bcf2 100644 --- a/library/Zend/Search/Lucene/Storage/File.php +++ b/library/Zend/Search/Lucene/Storage/File.php @@ -167,7 +167,7 @@ public function readInt() */ public function writeInt($value) { - settype($value, 'integer'); + $value = (int) $value; $this->_fwrite( chr($value>>24 & 0xFF) . chr($value>>16 & 0xFF) . chr($value>>8 & 0xFF) . @@ -217,7 +217,7 @@ public function writeLong($value) * fseek() and ftell() use long for offset. Thus, largest index segment file size in 32bit mode is 2Gb */ if (PHP_INT_SIZE > 4) { - settype($value, 'integer'); + $value = (int) $value; $this->_fwrite( chr($value>>56 & 0xFF) . chr($value>>48 & 0xFF) . chr($value>>40 & 0xFF) . @@ -244,9 +244,9 @@ public function readLong32Bit() $wordHigh = $this->readInt(); $wordLow = $this->readInt(); - if ($wordHigh & (int)0x80000000) { + if (($wordHigh & (int)0x80000000) !== 0) { // It's a negative value since the highest bit is set - if ($wordHigh == (int)0xFFFFFFFF && ($wordLow & (int)0x80000000)) { + if ($wordHigh === (int)0xFFFFFFFF && ($wordLow & (int)0x80000000)) { return $wordLow; } else { require_once 'Zend/Search/Lucene/Exception.php'; @@ -327,7 +327,7 @@ public function readVInt() */ public function writeVInt($value) { - settype($value, 'integer'); + $value = (int) $value; while ($value > 0x7F) { $this->_fwrite(chr( ($value & 0x7F)|0x80 )); $value >>= 7; @@ -366,11 +366,11 @@ public function readString() for ($count = 0; $count < $strlen; $count++ ) { if (( ord($str_val[$count]) & 0xC0 ) == 0xC0) { $addBytes = 1; - if (ord($str_val[$count]) & 0x20 ) { + if ((ord($str_val[$count]) & 0x20) !== 0 ) { $addBytes++; // Never used. Java2 doesn't encode strings in four bytes - if (ord($str_val[$count]) & 0x10 ) { + if ((ord($str_val[$count]) & 0x10) !== 0 ) { $addBytes++; } } @@ -415,7 +415,7 @@ public function writeString($str) */ // convert input to a string before iterating string characters - settype($str, 'string'); + $str = (string) $str; $chars = $strlen = strlen($str); $containNullChars = false; @@ -428,12 +428,12 @@ public function writeString($str) */ if ((ord($str[$count]) & 0xC0) == 0xC0) { $addBytes = 1; - if (ord($str[$count]) & 0x20 ) { + if ((ord($str[$count]) & 0x20) !== 0 ) { $addBytes++; // Never used. Java2 doesn't encode strings in four bytes // and we dont't support non-BMP characters - if (ord($str[$count]) & 0x10 ) { + if ((ord($str[$count]) & 0x10) !== 0 ) { $addBytes++; } } diff --git a/library/Zend/Search/Lucene/Storage/File/Memory.php b/library/Zend/Search/Lucene/Storage/File/Memory.php index 9df4c02e00..3d9a26711e 100644 --- a/library/Zend/Search/Lucene/Storage/File/Memory.php +++ b/library/Zend/Search/Lucene/Storage/File/Memory.php @@ -271,7 +271,7 @@ public function writeInt($value) // We do not need to check if file position points to the end of "file". // Only append operation is supported now - settype($value, 'integer'); + $value = (int) $value; $this->_data .= chr($value>>24 & 0xFF) . chr($value>>16 & 0xFF) . chr($value>>8 & 0xFF) . @@ -327,7 +327,7 @@ public function writeLong($value) * fseek() and ftell() use long for offset. Thus, largest index segment file size in 32bit mode is 2Gb */ if (PHP_INT_SIZE > 4) { - settype($value, 'integer'); + $value = (int) $value; $this->_data .= chr($value>>56 & 0xFF) . chr($value>>48 & 0xFF) . chr($value>>40 & 0xFF) . @@ -356,9 +356,9 @@ public function readLong32Bit() $wordHigh = $this->readInt(); $wordLow = $this->readInt(); - if ($wordHigh & (int)0x80000000) { + if (($wordHigh & (int)0x80000000) !== 0) { // It's a negative value since the highest bit is set - if ($wordHigh == (int)0xFFFFFFFF && ($wordLow & (int)0x80000000)) { + if ($wordHigh === (int)0xFFFFFFFF && ($wordLow & (int)0x80000000)) { return $wordLow; } else { require_once 'Zend/Search/Lucene/Exception.php'; @@ -441,7 +441,7 @@ public function writeVInt($value) // We do not need to check if file position points to the end of "file". // Only append operation is supported now - settype($value, 'integer'); + $value = (int) $value; while ($value > 0x7F) { $this->_data .= chr( ($value & 0x7F)|0x80 ); $value >>= 7; @@ -483,11 +483,11 @@ public function readString() for ($count = 0; $count < $strlen; $count++ ) { if (( ord($str_val[$count]) & 0xC0 ) == 0xC0) { $addBytes = 1; - if (ord($str_val[$count]) & 0x20 ) { + if ((ord($str_val[$count]) & 0x20) !== 0 ) { $addBytes++; // Never used. Java2 doesn't encode strings in four bytes - if (ord($str_val[$count]) & 0x10 ) { + if ((ord($str_val[$count]) & 0x10) !== 0 ) { $addBytes++; } } @@ -536,7 +536,7 @@ public function writeString($str) // Only append operation is supported now // convert input to a string before iterating string characters - settype($str, 'string'); + $str = (string) $str; $chars = $strlen = strlen($str); $containNullChars = false; @@ -549,12 +549,12 @@ public function writeString($str) */ if ((ord($str[$count]) & 0xC0) == 0xC0) { $addBytes = 1; - if (ord($str[$count]) & 0x20 ) { + if ((ord($str[$count]) & 0x20) !== 0 ) { $addBytes++; // Never used. Java2 doesn't encode strings in four bytes // and we dont't support non-BMP characters - if (ord($str[$count]) & 0x10 ) { + if ((ord($str[$count]) & 0x10) !== 0 ) { $addBytes++; } } diff --git a/library/Zend/Search/Lucene/TermStreamsPriorityQueue.php b/library/Zend/Search/Lucene/TermStreamsPriorityQueue.php index 2a1a9de908..f3249dd80b 100644 --- a/library/Zend/Search/Lucene/TermStreamsPriorityQueue.php +++ b/library/Zend/Search/Lucene/TermStreamsPriorityQueue.php @@ -120,8 +120,7 @@ public function nextTerm() { while (($termStream = $this->_termsStreamQueue->pop()) !== null) { if ($this->_termsStreamQueue->top() === null || - $this->_termsStreamQueue->top()->currentTerm()->key() != - $termStream->currentTerm()->key()) { + $this->_termsStreamQueue->top()->currentTerm()->key() != $termStream->currentTerm()->key()) { // We got new term $this->_lastTerm = $termStream->currentTerm(); diff --git a/library/Zend/Serializer/Adapter/AdapterAbstract.php b/library/Zend/Serializer/Adapter/AdapterAbstract.php index 1901d5bce4..c06bcc85e0 100644 --- a/library/Zend/Serializer/Adapter/AdapterAbstract.php +++ b/library/Zend/Serializer/Adapter/AdapterAbstract.php @@ -57,11 +57,7 @@ public function __construct($opts = array()) */ public function setOptions($opts) { - if ($opts instanceof Zend_Config) { - $opts = $opts->toArray(); - } else { - $opts = (array) $opts; - } + $opts = $opts instanceof Zend_Config ? $opts->toArray() : (array) $opts; foreach ($opts as $k => $v) { $this->setOption($k, $v); diff --git a/library/Zend/Serializer/Adapter/Json.php b/library/Zend/Serializer/Adapter/Json.php index f1c3d06b89..84f5549a21 100644 --- a/library/Zend/Serializer/Adapter/Json.php +++ b/library/Zend/Serializer/Adapter/Json.php @@ -54,7 +54,7 @@ class Zend_Serializer_Adapter_Json extends Zend_Serializer_Adapter_AdapterAbstra */ public function serialize($value, array $opts = array()) { - $opts = $opts + $this->_options; + $opts += $this->_options; try { return Zend_Json::encode($value, $opts['cycleCheck'], $opts); @@ -73,13 +73,13 @@ public function serialize($value, array $opts = array()) */ public function unserialize($json, array $opts = array()) { - $opts = $opts + $this->_options; + $opts += $this->_options; try { $ret = Zend_Json::decode($json, $opts['objectDecodeType']); } catch (Zend_Json_Exception $e) { require_once 'Zend/Serializer/Exception.php'; - throw new Zend_Serializer_Exception('Invalid json data'); + throw new Zend_Serializer_Exception('Invalid json data', $e->getCode(), $e); } catch (Exception $e) { require_once 'Zend/Serializer/Exception.php'; throw new Zend_Serializer_Exception('Unserialization failed by previous error', 0, $e); diff --git a/library/Zend/Serializer/Adapter/PythonPickle.php b/library/Zend/Serializer/Adapter/PythonPickle.php index aae13729f6..d2c890144d 100644 --- a/library/Zend/Serializer/Adapter/PythonPickle.php +++ b/library/Zend/Serializer/Adapter/PythonPickle.php @@ -164,10 +164,8 @@ public function __construct($opts=array()) */ public function setOption($name, $value) { - switch ($name) { - case 'protocol': - $value = $this->_checkProtocolNumber($value); - break; + if ($name === 'protocol') { + $value = $this->_checkProtocolNumber($value); } return parent::setOption($name, $value); @@ -201,7 +199,7 @@ protected function _checkProtocolNumber($number) */ public function serialize($value, array $opts = array()) { - $opts = $opts + $this->_options; + $opts += $this->_options; $this->_protocol = $this->_checkProtocolNumber($opts['protocol']); $this->_binary = $this->_protocol != 0; @@ -289,7 +287,7 @@ protected function _writeGet($id) } else { // LONG_BINGET + pack("_pickle .= self::OP_LONG_BINGET . $bin; @@ -314,7 +312,7 @@ protected function _writePut($id) } else { // LONG_BINPUT + pack("_pickle .= self::OP_LONG_BINPUT . $bin; @@ -389,7 +387,7 @@ protected function _writeInt($value) // fits in a 4-byte signed int. // self.write(BININT + pack("_pickle .= self::OP_BININT . $bin; @@ -411,7 +409,7 @@ protected function _writeFloat($value) if ($this->_binary) { // self.write(BINFLOAT + pack('>d', obj)) $bin = pack('d', $value); - if (self::$_isLittleEndian === true) { + if (self::$_isLittleEndian) { $bin = strrev($bin); } $this->_pickle .= self::OP_BINFLOAT . $bin; @@ -441,7 +439,7 @@ protected function _writeString($value) } else { // self.write(BINSTRING + pack("_pickle .= self::OP_BINSTRING . $binLen . $value; @@ -604,7 +602,7 @@ public function unserialize($pickle, array $opts = array()) $this->_load($op); } - if (!count($this->_stack)) { + if (count($this->_stack) === 0) { require_once 'Zend/Serializer/Exception.php'; throw new Zend_Serializer_Exception('No data found'); } @@ -799,7 +797,7 @@ protected function _loadBinPut() protected function _loadLongBinPut() { $bin = $this->_read(4); - if (self::$_isLittleEndian === false) { + if (!self::$_isLittleEndian) { $bin = strrev($bin); } list(, $id) = unpack('l', $bin); @@ -855,7 +853,7 @@ protected function _loadBinGet() protected function _loadLongBinGet() { $bin = $this->_read(4); - if (self::$_isLittleEndian === false) { + if (!self::$_isLittleEndian) { $bin = strrev($bin); } list(, $id) = unpack('l', $bin); @@ -922,7 +920,7 @@ protected function _loadInt() protected function _loadBinInt() { $bin = $this->_read(4); - if (self::$_isLittleEndian === false) { + if (!self::$_isLittleEndian) { $bin = strrev($bin); } list(, $int) = unpack('l', $bin); @@ -959,11 +957,7 @@ protected function _loadBinInt2() protected function _loadLong() { $data = rtrim($this->_readline(), 'L'); - if ($data === '') { - $this->_stack[] = 0; - } else { - $this->_stack[] = $data; - } + $this->_stack[] = $data === '' ? 0 : $data; } /** @@ -986,7 +980,7 @@ protected function _loadLong1() protected function _loadLong4() { $nBin = $this->_read(4); - if (self::$_isLittleEndian === false) { + if (!self::$_isLittleEndian) { $nBin = strrev($$nBin); } list(, $n) = unpack('l', $nBin); @@ -1014,7 +1008,7 @@ protected function _loadFloat() protected function _loadBinFloat() { $bin = $this->_read(8); - if (self::$_isLittleEndian === true) { + if (self::$_isLittleEndian) { $bin = strrev($bin); } list(, $float) = unpack('d', $bin); @@ -1066,7 +1060,7 @@ protected function _loadBinBytes() { // read byte length $nBin = $this->_read(4); - if (self::$_isLittleEndian === false) { + if (!self::$_isLittleEndian) { $nBin = strrev($$nBin); } list(, $n) = unpack('l', $nBin); @@ -1154,7 +1148,7 @@ protected function _loadBinUnicode() { // read byte length $n = $this->_read(4); - if (self::$_isLittleEndian === false) { + if (!self::$_isLittleEndian) { $n = strrev($n); } list(, $n) = unpack('l', $n); diff --git a/library/Zend/Serializer/Adapter/Wddx.php b/library/Zend/Serializer/Adapter/Wddx.php index 81902b2248..0ec814d353 100644 --- a/library/Zend/Serializer/Adapter/Wddx.php +++ b/library/Zend/Serializer/Adapter/Wddx.php @@ -74,7 +74,7 @@ public function __construct($opts = array()) */ public function serialize($value, array $opts = array()) { - $opts = $opts + $this->_options; + $opts += $this->_options; if (isset($opts['comment']) && $opts['comment']) { $wddx = wddx_serialize_value($value, (string)$opts['comment']); diff --git a/library/Zend/Server/Cache.php b/library/Zend/Server/Cache.php index 97264dfb09..20f27fd93f 100644 --- a/library/Zend/Server/Cache.php +++ b/library/Zend/Server/Cache.php @@ -67,12 +67,7 @@ public static function save($filename, Zend_Server_Interface $server) } $methods = $definition; } - - if (0 === @file_put_contents($filename, serialize($methods))) { - return false; - } - - return true; + return 0 !== @file_put_contents($filename, serialize($methods)); } /** diff --git a/library/Zend/Server/Reflection/Function/Abstract.php b/library/Zend/Server/Reflection/Function/Abstract.php index 69e11c5dfb..bd68dbcc08 100644 --- a/library/Zend/Server/Reflection/Function/Abstract.php +++ b/library/Zend/Server/Reflection/Function/Abstract.php @@ -210,11 +210,7 @@ protected function _buildSignatures($return, $returnDesc, $paramTypes, $paramDes $endPoints = array(); foreach ($signatureTrees as $root) { $tmp = $root->getEndPoints(); - if (empty($tmp)) { - $endPoints = array_merge($endPoints, array($root)); - } else { - $endPoints = array_merge($endPoints, $tmp); - } + $endPoints = empty($tmp) ? array_merge($endPoints, array($root)) : array_merge($endPoints, $tmp); } foreach ($endPoints as $node) { diff --git a/library/Zend/Server/Reflection/Node.php b/library/Zend/Server/Reflection/Node.php index d80abf342e..8e0107f2b6 100644 --- a/library/Zend/Server/Reflection/Node.php +++ b/library/Zend/Server/Reflection/Node.php @@ -92,9 +92,7 @@ public function setParent(Zend_Server_Reflection_Node $node, $new = false) */ public function createChild($value) { - $child = new self($value, $this); - - return $child; + return new self($value, $this); } /** @@ -129,7 +127,7 @@ public function getChildren() */ public function hasChildren() { - return count($this->_children) > 0; + return $this->_children !== []; } /** diff --git a/library/Zend/Server/Reflection/Prototype.php b/library/Zend/Server/Reflection/Prototype.php index cacd56ec72..78b219bec0 100644 --- a/library/Zend/Server/Reflection/Prototype.php +++ b/library/Zend/Server/Reflection/Prototype.php @@ -42,6 +42,14 @@ */ class Zend_Server_Reflection_Prototype { + /** + * @var mixed|\Zend_Server_Reflection_ReturnValue + */ + public $_return; + /** + * @var mixed[]|mixed|null + */ + public $_params; /** * Constructor * diff --git a/library/Zend/Service/Akismet.php b/library/Zend/Service/Akismet.php index 105314c70f..146676a5fd 100644 --- a/library/Zend/Service/Akismet.php +++ b/library/Zend/Service/Akismet.php @@ -331,12 +331,7 @@ public function isSpam($params) require_once 'Zend/Service/Exception.php'; throw new Zend_Service_Exception('Invalid API key'); } - - if ('true' == $return) { - return true; - } - - return false; + return 'true' == $return; } /** diff --git a/library/Zend/Service/Amazon/Authentication/S3.php b/library/Zend/Service/Amazon/Authentication/S3.php index d9a52d1958..9e44a27774 100644 --- a/library/Zend/Service/Amazon/Authentication/S3.php +++ b/library/Zend/Service/Amazon/Authentication/S3.php @@ -59,9 +59,9 @@ public function generateSignature($method, $path, &$headers) foreach ($headers as $key => $val) { if (strcasecmp($key, 'content-type') == 0) { $type = $val; - } else if (strcasecmp($key, 'content-md5') == 0) { + } elseif (strcasecmp($key, 'content-md5') == 0) { $md5 = $val; - } else if (strcasecmp($key, 'date') == 0) { + } elseif (strcasecmp($key, 'date') == 0) { $date = $val; } } @@ -96,13 +96,11 @@ public function generateSignature($method, $path, &$headers) $sig_str .= '/'.parse_url($path, PHP_URL_PATH); if (strpos($path, '?location') !== false) { $sig_str .= '?location'; - } else - if (strpos($path, '?acl') !== false) { - $sig_str .= '?acl'; - } else - if (strpos($path, '?torrent') !== false) { - $sig_str .= '?torrent'; - } + } elseif (strpos($path, '?acl') !== false) { + $sig_str .= '?acl'; + } elseif (strpos($path, '?torrent') !== false) { + $sig_str .= '?torrent'; + } $signature = base64_encode(Zend_Crypt_Hmac::compute($this->_secretKey, 'sha1', utf8_encode($sig_str), Zend_Crypt_Hmac::BINARY)); $headers['Authorization'] = 'AWS ' . $this->_accessKey . ':' . $signature; diff --git a/library/Zend/Service/Amazon/Authentication/V1.php b/library/Zend/Service/Amazon/Authentication/V1.php index c014a9f163..7aea803972 100644 --- a/library/Zend/Service/Amazon/Authentication/V1.php +++ b/library/Zend/Service/Amazon/Authentication/V1.php @@ -63,9 +63,7 @@ public function generateSignature($url, array &$parameters) $parameters['Timestamp'] = gmdate('Y-m-d\TH:i:s\Z', time()+10); } - $data = $this->_signParameters($url, $parameters); - - return $data; + return $this->_signParameters($url, $parameters); } /** diff --git a/library/Zend/Service/Amazon/Authentication/V2.php b/library/Zend/Service/Amazon/Authentication/V2.php index 58eb6fd6f7..61ea2c771c 100644 --- a/library/Zend/Service/Amazon/Authentication/V2.php +++ b/library/Zend/Service/Amazon/Authentication/V2.php @@ -70,9 +70,7 @@ public function generateSignature($url, array &$parameters) $parameters['Timestamp'] = gmdate('Y-m-d\TH:i:s\Z', time()+10); } - $data = $this->_signParameters($url, $parameters); - - return $data; + return $this->_signParameters($url, $parameters); } /** diff --git a/library/Zend/Service/Amazon/Ec2/Abstract.php b/library/Zend/Service/Amazon/Ec2/Abstract.php index 5030aa0cb3..c7c057f998 100644 --- a/library/Zend/Service/Amazon/Ec2/Abstract.php +++ b/library/Zend/Service/Amazon/Ec2/Abstract.php @@ -98,14 +98,11 @@ abstract class Zend_Service_Amazon_Ec2_Abstract extends Zend_Service_Amazon_Abst */ public function __construct($accessKey=null, $secretKey=null, $region=null) { - if(!$region) { + if (!$region) { $region = self::$_defaultRegion; - } else { - // make rue the region is valid - if(!empty($region) && !in_array(strtolower($region), self::$_validEc2Regions, true)) { - require_once 'Zend/Service/Amazon/Exception.php'; - throw new Zend_Service_Amazon_Exception('Invalid Amazon Ec2 Region'); - } + } elseif (!empty($region) && !in_array(strtolower($region), self::$_validEc2Regions, true)) { + require_once 'Zend/Service/Amazon/Exception.php'; + throw new Zend_Service_Amazon_Exception('Invalid Amazon Ec2 Region'); } $this->_region = $region; @@ -136,7 +133,7 @@ public static function setRegion($region) */ protected function _getRegion() { - return (!empty($this->_region)) ? $this->_region . '.' : ''; + return (empty($this->_region)) ? '' : $this->_region . '.'; } /** diff --git a/library/Zend/Service/Amazon/Ec2/Elasticip.php b/library/Zend/Service/Amazon/Ec2/Elasticip.php index 5c53bf0a1a..f3927e270d 100644 --- a/library/Zend/Service/Amazon/Ec2/Elasticip.php +++ b/library/Zend/Service/Amazon/Ec2/Elasticip.php @@ -50,9 +50,8 @@ public function allocate() $response = $this->sendRequest($params); $xpath = $response->getXPath(); - $ip = $xpath->evaluate('string(//ec2:publicIp/text())'); - return $ip; + return $xpath->evaluate('string(//ec2:publicIp/text())'); } /** diff --git a/library/Zend/Service/Amazon/Ec2/Image.php b/library/Zend/Service/Amazon/Ec2/Image.php index d9a1b18d9e..5d57a65d47 100644 --- a/library/Zend/Service/Amazon/Ec2/Image.php +++ b/library/Zend/Service/Amazon/Ec2/Image.php @@ -62,9 +62,7 @@ public function register($imageLocation) $response = $this->sendRequest($params); $xpath = $response->getXPath(); - $amiId = $xpath->evaluate('string(//ec2:imageId/text())'); - - return $amiId; + return $xpath->evaluate('string(//ec2:imageId/text())'); } /** diff --git a/library/Zend/Service/Amazon/Ec2/Instance/Reserved.php b/library/Zend/Service/Amazon/Ec2/Instance/Reserved.php index 00f5f657aa..075a59d30f 100644 --- a/library/Zend/Service/Amazon/Ec2/Instance/Reserved.php +++ b/library/Zend/Service/Amazon/Ec2/Instance/Reserved.php @@ -131,13 +131,12 @@ public function purchaseOffering($offeringId, $intanceCount = 1) $params = array(); $params['Action'] = 'PurchaseReservedInstancesOffering'; $params['OfferingId.1'] = $offeringId; - $params['instanceCount.1'] = intval($intanceCount); + $params['instanceCount.1'] = (int) $intanceCount; $response = $this->sendRequest($params); $xpath = $response->getXPath(); - $reservedInstancesId = $xpath->evaluate('string(//ec2:reservedInstancesId/text())'); - return $reservedInstancesId; + return $xpath->evaluate('string(//ec2:reservedInstancesId/text())'); } } diff --git a/library/Zend/Service/Amazon/Ec2/Instance/Windows.php b/library/Zend/Service/Amazon/Ec2/Instance/Windows.php index 39099feac4..0ac6830ad1 100644 --- a/library/Zend/Service/Amazon/Ec2/Instance/Windows.php +++ b/library/Zend/Service/Amazon/Ec2/Instance/Windows.php @@ -189,7 +189,6 @@ protected function _getS3UploadPolicy($bucketName, $prefix, $expireInMinutes = 1 */ protected function _signS3UploadPolicy($policy) { - $hmac = Zend_Crypt_Hmac::compute($this->_getSecretKey(), 'SHA1', $policy, Zend_Crypt_Hmac::BINARY); - return $hmac; + return Zend_Crypt_Hmac::compute($this->_getSecretKey(), 'SHA1', $policy, Zend_Crypt_Hmac::BINARY); } } diff --git a/library/Zend/Service/Amazon/Ec2/Keypair.php b/library/Zend/Service/Amazon/Ec2/Keypair.php index 6db09c7dc8..10c62a0c63 100644 --- a/library/Zend/Service/Amazon/Ec2/Keypair.php +++ b/library/Zend/Service/Amazon/Ec2/Keypair.php @@ -50,7 +50,7 @@ public function create($keyName) $params['Action'] = 'CreateKeyPair'; - if(!$keyName) { + if($keyName === '' || $keyName === '0') { require_once 'Zend/Service/Amazon/Ec2/Exception.php'; throw new Zend_Service_Amazon_Ec2_Exception('Invalid Key Name'); } @@ -120,7 +120,7 @@ public function delete($keyName) $params['Action'] = 'DeleteKeyPair'; - if(!$keyName) { + if($keyName === '' || $keyName === '0') { require_once 'Zend/Service/Amazon/Ec2/Exception.php'; throw new Zend_Service_Amazon_Ec2_Exception('Invalid Key Name'); } diff --git a/library/Zend/Service/Amazon/Item.php b/library/Zend/Service/Amazon/Item.php index 48a9b7e8a0..d54a622890 100644 --- a/library/Zend/Service/Amazon/Item.php +++ b/library/Zend/Service/Amazon/Item.php @@ -31,6 +31,14 @@ */ class Zend_Service_Amazon_Item { + public string $CurrencyCode; + public int $Amount; + public string $FormattedPrice; + /** + * @var mixed[]|mixed|string + */ + public $tagName; + public array $EditorialReviews; /** * @var string */ @@ -146,9 +154,9 @@ public function __construct($dom) $result = $xpath->query('./az:ItemAttributes/az:*/text()', $dom); if ($result->length >= 1) { foreach ($result as $v) { - if (isset($this->{$v->parentNode->tagName})) { + if (property_exists($this, 'tagName') && $this->{$v->parentNode->tagName} !== null) { if (is_array($this->{$v->parentNode->tagName})) { - array_push($this->{$v->parentNode->tagName}, (string) $v->data); + $this->{$v->parentNode->tagName}[] = (string) $v->data; } else { $this->{$v->parentNode->tagName} = array($this->{$v->parentNode->tagName}, (string) $v->data); } @@ -229,7 +237,7 @@ public function __construct($dom) $this->Tracks[] = (string) $t->data; } } - } else if ($result->length == 1) { + } elseif ($result->length == 1) { foreach ($xpath->query('./*/text()', $result->item(0)) as $t) { $this->Tracks[] = (string) $t->data; } diff --git a/library/Zend/Service/Amazon/Query.php b/library/Zend/Service/Amazon/Query.php index c8a65c5e62..a9664e4944 100644 --- a/library/Zend/Service/Amazon/Query.php +++ b/library/Zend/Service/Amazon/Query.php @@ -70,7 +70,7 @@ public function __call($method, $args) if (strtolower($method) === 'category') { $this->_searchIndex = $args[0]; $this->_search['SearchIndex'] = $args[0]; - } else if (isset($this->_search['SearchIndex']) || $this->_searchIndex !== null || $this->_searchIndex === 'asin') { + } elseif (isset($this->_search['SearchIndex']) || $this->_searchIndex !== null || $this->_searchIndex === 'asin') { $this->_search[$method] = $args[0]; } else { /** diff --git a/library/Zend/Service/Amazon/S3.php b/library/Zend/Service/Amazon/S3.php index 613c95045a..1cfd7ec360 100755 --- a/library/Zend/Service/Amazon/S3.php +++ b/library/Zend/Service/Amazon/S3.php @@ -255,7 +255,7 @@ public function getBuckets() $buckets = array(); foreach ($xml->Buckets->Bucket as $bucket) { - $buckets[] = (string)$bucket->Name; + $buckets[] = (string)$bucket->getName(); } return $buckets; @@ -311,7 +311,7 @@ public function getObjectsByBucket($bucket, $params = array()) $xml = new SimpleXMLElement($response->getBody()); $objects = array(); - if (isset($xml->Contents)) { + if (property_exists($xml, 'Contents') && $xml->Contents !== null) { foreach ($xml->Contents as $contents) { foreach ($contents->Key as $object) { $objects[] = (string)$object; @@ -346,7 +346,7 @@ public function getObjectsAndPrefixesByBucket($bucket, $params = array()) $xml = new SimpleXMLElement($response->getBody()); $objects = array(); - if (isset($xml->Contents)) { + if (property_exists($xml, 'Contents') && $xml->Contents !== null) { foreach ($xml->Contents as $contents) { foreach ($contents->Key as $object) { $objects[] = (string)$object; @@ -354,7 +354,7 @@ public function getObjectsAndPrefixesByBucket($bucket, $params = array()) } } $prefixes = array(); - if (isset($xml->CommonPrefixes)) { + if (property_exists($xml, 'CommonPrefixes') && $xml->CommonPrefixes !== null) { foreach ($xml->CommonPrefixes as $prefix) { foreach ($prefix->Prefix as $object) { $prefixes[] = (string)$object; @@ -384,7 +384,7 @@ protected function _fixupObjectName($object) return $firstpart; } - return $firstpart.'/'.join('/', array_map('rawurlencode', $nameparts)); + return $firstpart.'/'.implode('/', array_map('rawurlencode', $nameparts)); } /** @@ -575,12 +575,7 @@ public function copyObject($sourceObject, $destObject, $meta = null) $headers['x-amz-metadata-directive'] = $meta === null ? 'COPY' : 'REPLACE'; $response = $this->_makeRequest('PUT', $destObject, null, $headers); - - if ($response->getStatus() == 200 && !stristr($response->getBody(), '')) { - return true; - } - - return false; + return $response->getStatus() == 200 && !stristr($response->getBody(), ''); } /** @@ -638,7 +633,7 @@ public function _makeRequest($method, $path='', $params=null, $headers=array(), // build the end point out $parts = explode('/', $path, 2); $endpoint = clone($this->_endpoint); - if ($parts[0]) { + if ($parts[0] !== '' && $parts[0] !== '0') { // prepend bucket name to the hostname $endpoint->setHost($parts[0].'.'.$endpoint->getHost()); } @@ -651,7 +646,7 @@ public function _makeRequest($method, $path='', $params=null, $headers=array(), } else { $endpoint->setPath('/'); - if ($parts[0]) { + if ($parts[0] !== '' && $parts[0] !== '0') { $path = $parts[0].'/'; } } @@ -698,12 +693,10 @@ public function _makeRequest($method, $path='', $params=null, $headers=array(), $retry = true; $retry_count++; sleep($retry_count / 4 * $retry_count); - } - else if ($response_code == 307) { + } elseif ($response_code == 307) { // Need to redirect, new S3 endpoint given // This should never happen as Zend_Http_Client will redirect automatically - } - else if ($response_code == 100) { + } elseif ($response_code == 100) { // echo 'OK to Continue'; } } while ($retry); @@ -731,11 +724,9 @@ protected function addSignature($method, $path, &$headers) foreach ($headers as $key=>$val) { if (strcasecmp($key, 'content-type') == 0) { $type = $val; - } - else if (strcasecmp($key, 'content-md5') == 0) { + } elseif (strcasecmp($key, 'content-md5') == 0) { $md5 = $val; - } - else if (strcasecmp($key, 'date') == 0) { + } elseif (strcasecmp($key, 'date') == 0) { $date = $val; } } @@ -770,14 +761,11 @@ protected function addSignature($method, $path, &$headers) $sig_str .= '/'.parse_url($path, PHP_URL_PATH); if (strpos($path, '?location') !== false) { $sig_str .= '?location'; - } - else if (strpos($path, '?acl') !== false) { + } elseif (strpos($path, '?acl') !== false) { $sig_str .= '?acl'; - } - else if (strpos($path, '?torrent') !== false) { + } elseif (strpos($path, '?torrent') !== false) { $sig_str .= '?torrent'; - } - else if (strpos($path, '?versions') !== false) { + } elseif (strpos($path, '?versions') !== false) { $sig_str .= '?versions'; } @@ -797,7 +785,7 @@ public static function getMimeType($path) { $ext = substr(strrchr($path, '.'), 1); - if(!$ext) { + if($ext === '' || $ext === '0') { // shortcut return 'binary/octet-stream'; } diff --git a/library/Zend/Service/Amazon/S3/Stream.php b/library/Zend/Service/Amazon/S3/Stream.php index d3d9fa2a70..35328cc8d4 100755 --- a/library/Zend/Service/Amazon/S3/Stream.php +++ b/library/Zend/Service/Amazon/S3/Stream.php @@ -82,7 +82,7 @@ protected function _getS3Client($path) if ($this->_s3 === null) { $url = explode(':', $path); - if (!$url) { + if ($url === []) { /** * @see Zend_Service_Amazon_S3_Exception */ @@ -112,8 +112,8 @@ protected function _getS3Client($path) protected function _getNamePart($path) { $url = parse_url($path); - if ($url['host']) { - return !empty($url['path']) ? $url['host'].$url['path'] : $url['host']; + if ($url['host'] !== '' && $url['host'] !== '0') { + return empty($url['path']) ? $url['host'] : $url['host'].$url['path']; } return ''; @@ -183,7 +183,7 @@ public function stream_close() */ public function stream_read($count) { - if (!$this->_objectName) { + if ($this->_objectName === '' || $this->_objectName === '0') { return false; } @@ -223,7 +223,7 @@ public function stream_read($count) */ public function stream_write($data) { - if (!$this->_objectName) { + if ($this->_objectName === '' || $this->_objectName === '0') { return 0; } $len = strlen($data); @@ -240,7 +240,7 @@ public function stream_write($data) */ public function stream_eof() { - if (!$this->_objectName) { + if ($this->_objectName === '' || $this->_objectName === '0') { return true; } @@ -266,7 +266,7 @@ public function stream_tell() */ public function stream_seek($offset, $whence) { - if (!$this->_objectName) { + if ($this->_objectName === '' || $this->_objectName === '0') { return false; } @@ -318,7 +318,7 @@ public function stream_flush() */ public function stream_stat() { - if (!$this->_objectName) { + if ($this->_objectName === '' || $this->_objectName === '0') { return false; } @@ -337,7 +337,7 @@ public function stream_stat() $stat['blksize'] = 0; $stat['blocks'] = 0; - if(($slash = strchr($this->_objectName, '/')) === false || $slash == strlen($this->_objectName)-1) { + if(($slash = strstr($this->_objectName, '/')) === false || $slash == strlen($this->_objectName)-1) { /* bucket */ $stat['mode'] |= 040000; } else { @@ -448,7 +448,7 @@ public function url_stat($path, $flags) $stat['blocks'] = 0; $name = $this->_getNamePart($path); - if(($slash = strchr($name, '/')) === false || $slash == strlen($name)-1) { + if(($slash = strstr($name, '/')) === false || $slash == strlen($name)-1) { /* bucket */ $stat['mode'] |= 040000; } else { diff --git a/library/Zend/Service/Amazon/SimpleDb.php b/library/Zend/Service/Amazon/SimpleDb.php index 080672c4bb..4c4a488874 100644 --- a/library/Zend/Service/Amazon/SimpleDb.php +++ b/library/Zend/Service/Amazon/SimpleDb.php @@ -58,6 +58,10 @@ */ class Zend_Service_Amazon_SimpleDb extends Zend_Service_Amazon_Abstract { + /** + * @var mixed|\Zend_Uri + */ + public $_endpoint; /* Notes */ // TODO SSL is required @@ -158,7 +162,7 @@ public function getAttributes( // Return an array of arrays $attributes = array(); foreach($attributeNodes as $attributeNode) { - $name = (string)$attributeNode->Name; + $name = (string)$attributeNode->getName(); $valueNodes = $attributeNode->Value; $data = null; if (is_array($valueNodes) && !empty($valueNodes)) { @@ -391,10 +395,10 @@ public function select($selectExpression, $nextToken = null) $attributes = array(); foreach ($xml->SelectResult->Item as $item) { - $itemName = (string)$item->Name; + $itemName = (string)$item->getName(); foreach ($item->Attribute as $attribute) { - $attributeName = (string)$attribute->Name; + $attributeName = (string)$attribute->getName(); $values = array(); foreach ($attribute->Value as $value) { @@ -472,11 +476,11 @@ protected function _sendRequest(array $params = array()) foreach ($params as $key => $value) { $params_out[] = rawurlencode($key)."=".rawurlencode($value); } - $request->setRawData(join('&', $params_out), Zend_Http_Client::ENC_URLENCODED); + $request->setRawData(implode('&', $params_out), Zend_Http_Client::ENC_URLENCODED); $httpResponse = $request->request(); } catch (Zend_Http_Client_Exception $zhce) { $message = 'Error in request to AWS service: ' . $zhce->getMessage(); - throw new Zend_Service_Amazon_SimpleDb_Exception($message, $zhce->getCode()); + throw new Zend_Service_Amazon_SimpleDb_Exception($message, $zhce->getCode(), $zhce); } $response = new Zend_Service_Amazon_SimpleDb_Response($httpResponse); $this->_checkForErrors($response); diff --git a/library/Zend/Service/Amazon/SimpleDb/Attribute.php b/library/Zend/Service/Amazon/SimpleDb/Attribute.php index b8a7cca7e1..4c944402bc 100644 --- a/library/Zend/Service/Amazon/SimpleDb/Attribute.php +++ b/library/Zend/Service/Amazon/SimpleDb/Attribute.php @@ -46,11 +46,7 @@ function __construct($itemName, $name, $values) $this->_itemName = $itemName; $this->_name = $name; - if (!is_array($values)) { - $this->_values = array($values); - } else { - $this->_values = $values; - } + $this->_values = is_array($values) ? $values : array($values); } /** diff --git a/library/Zend/Service/Amazon/Sqs.php b/library/Zend/Service/Amazon/Sqs.php index 37fb2aef00..7dc6538338 100644 --- a/library/Zend/Service/Amazon/Sqs.php +++ b/library/Zend/Service/Amazon/Sqs.php @@ -182,7 +182,7 @@ public function create($queue_name, $timeout = null) $retry = false; $result = $this->_makeRequest(null, 'CreateQueue', $params); - if (!isset($result->CreateQueueResult->QueueUrl) + if (!(property_exists($result->CreateQueueResult, 'QueueUrl') && $result->CreateQueueResult->QueueUrl !== null) || empty($result->CreateQueueResult->QueueUrl) ) { if ($result->Error->Code == 'AWS.SimpleQueueService.QueueNameExists') { @@ -236,12 +236,12 @@ public function getQueues() { $result = $this->_makeRequest(null, 'ListQueues'); - if (isset($result->Error)) { + if (property_exists($result, 'Error') && $result->Error !== null) { require_once 'Zend/Service/Amazon/Sqs/Exception.php'; throw new Zend_Service_Amazon_Sqs_Exception($result->Error->Code); } - if (!isset($result->ListQueuesResult->QueueUrl) + if (!(property_exists($result->ListQueuesResult, 'QueueUrl') && $result->ListQueuesResult->QueueUrl !== null) || empty($result->ListQueuesResult->QueueUrl) ) { return array(); @@ -284,12 +284,11 @@ public function send($queue_url, $message) $result = $this->_makeRequest($queue_url, 'SendMessage', $params); - if (!isset($result->SendMessageResult->MessageId) - || empty($result->SendMessageResult->MessageId) - ) { + if (!(property_exists($result->SendMessageResult, 'MessageId') && $result->SendMessageResult->MessageId !== null) + || empty($result->SendMessageResult->MessageId)) { require_once 'Zend/Service/Amazon/Sqs/Exception.php'; throw new Zend_Service_Amazon_Sqs_Exception($result->Error->Code); - } else if ((string) $result->SendMessageResult->MD5OfMessageBody != $checksum) { + } elseif ((string) $result->SendMessageResult->MD5OfMessageBody !== $checksum) { require_once 'Zend/Service/Amazon/Sqs/Exception.php'; throw new Zend_Service_Amazon_Sqs_Exception('MD5 of body does not match message sent'); } @@ -322,12 +321,12 @@ public function receive($queue_url, $max_messages = null, $timeout = null) $result = $this->_makeRequest($queue_url, 'ReceiveMessage', $params); - if (isset($result->Error)) { + if (property_exists($result, 'Error') && $result->Error !== null) { require_once 'Zend/Service/Amazon/Sqs/Exception.php'; throw new Zend_Service_Amazon_Sqs_Exception($result->Error->Code); } - if (!isset($result->ReceiveMessageResult->Message) + if (!(property_exists($result->ReceiveMessageResult, 'Message') && $result->ReceiveMessageResult->Message !== null) || empty($result->ReceiveMessageResult->Message) ) { // no messages found @@ -364,15 +363,9 @@ public function deleteMessage($queue_url, $handle) $params['ReceiptHandle'] = (string)$handle; $result = $this->_makeRequest($queue_url, 'DeleteMessage', $params); - - if (isset($result->Error->Code) - && !empty($result->Error->Code) - ) { - return false; - } - // Will always return true unless ReceiptHandle is malformed - return true; + return !(property_exists($result->Error, 'Code') && $result->Error->Code !== null + && !empty($result->Error->Code)); } /** @@ -390,7 +383,7 @@ public function getAttribute($queue_url, $attribute = 'All') $result = $this->_makeRequest($queue_url, 'GetQueueAttributes', $params); - if (!isset($result->GetQueueAttributesResult->Attribute) + if (!(property_exists($result->GetQueueAttributesResult, 'Attribute') && $result->GetQueueAttributesResult->Attribute !== null) || empty($result->GetQueueAttributesResult->Attribute) ) { require_once 'Zend/Service/Amazon/Sqs/Exception.php'; diff --git a/library/Zend/Service/Console/Command.php b/library/Zend/Service/Console/Command.php index 5cd9bba9a2..2a4a6c8b42 100644 --- a/library/Zend/Service/Console/Command.php +++ b/library/Zend/Service/Console/Command.php @@ -94,7 +94,7 @@ public static function stderr($errorMessage, $newLine = true) if (error_reporting() === 0) { return; } - file_put_contents('php://stderr', $errorMessage . ($newLine ? "\r\n" : '')); + file_put_contents('php://stderr', $errorMessage . ($newLine !== '' && $newLine !== '0' ? "\r\n" : '')); } /** @@ -166,7 +166,7 @@ public static function bootstrap($argv) } if (is_null($value) && $parameter->required) { $missingParameterValues[] = $parameter->aliases[0]; - } else if (is_null($value)) { + } elseif (is_null($value)) { $value = $parameter->defaultvalue; } @@ -176,7 +176,7 @@ public static function bootstrap($argv) } // Mising parameters? - if (count($missingParameterValues) > 0) { + if ($missingParameterValues !== []) { self::stderr("Some parameters are missing:\r\n" . implode("\r\n", $missingParameterValues)); die(); } @@ -217,8 +217,9 @@ protected static function _buildModel() $handlerDescriptions = self::_findValueForDocComment('@command-handler-description', $type->getDocComment()); $handlerHeaders = self::_findValueForDocComment('@command-handler-header', $type->getDocComment()); $handlerFooters = self::_findValueForDocComment('@command-handler-footer', $type->getDocComment()); + $handlersCount = count($handlers); - for ($hi = 0; $hi < count($handlers); $hi++) { + for ($hi = 0; $hi < $handlersCount; $hi++) { $handler = $handlers[$hi]; $handlerDescription = isset($handlerDescriptions[$hi]) ? $handlerDescriptions[$hi] : (isset($handlerDescriptions[0]) ? $handlerDescriptions[0] : ''); $handlerDescription = str_replace('\r\n', "\r\n", $handlerDescription); @@ -241,14 +242,15 @@ protected static function _buildModel() // register it as a command. $commands[] = substr($method->getName(), 0, -7); } - for ($x = 0; $x < count($commands); $x++) { + $commandsCount = count($commands); + for ($x = 0; $x < $commandsCount; $x++) { $commands[$x] = strtolower($commands[$x]); } $commands = array_unique($commands); $commandDescriptions = self::_findValueForDocComment('@command-description', $method->getDocComment()); $commandExamples = self::_findValueForDocComment('@command-example', $method->getDocComment()); - if (count($commands) > 0) { + if ($commands !== []) { $command = $commands[0]; $commandDescription = isset($commandDescriptions[0]) ? $commandDescriptions[0] : ''; @@ -264,7 +266,8 @@ protected static function _buildModel() $parameters = $method->getParameters(); $parametersFor = self::_findValueForDocComment('@command-parameter-for', $method->getDocComment()); - for ($pi = 0; $pi < count($parameters); $pi++) { + $parametersCount = count($parameters); + for ($pi = 0; $pi < $parametersCount; $pi++) { // Initialize $parameter = $parameters[$pi]; $parameterFor = null; @@ -278,7 +281,7 @@ protected static function _buildModel() // Find the $parametersFor with the same name defined foreach ($parametersFor as $possibleParameterFor) { $possibleParameterFor = explode(' ', (string) $possibleParameterFor, 4); - if ($possibleParameterFor[0] == '$' . $parameter->getName()) { + if ($possibleParameterFor[0] === '$' . $parameter->getName()) { $parameterFor = $possibleParameterFor; break; } @@ -297,7 +300,7 @@ protected static function _buildModel() 'valueproviders' => explode('|', $parameterFor[1]), 'aliases' => explode('|', $parameterFor[2]), 'description' => (isset($parameterFor[3]) ? $parameterFor[3] : ''), - 'required' => (isset($parameterFor[3]) ? strpos(strtolower($parameterFor[3]), 'required') !== false && strpos(strtolower($parameterFor[3]), 'required if') === false : false), + 'required' => (isset($parameterFor[3]) ? stripos($parameterFor[3], 'required') !== false && stripos($parameterFor[3], 'required if') === false : false), ); // Add to model @@ -347,7 +350,8 @@ protected static function _findValueForDocComment($docCommentName, $docComment) protected function _displayObjectInformation($object, $propertiesToDump = array()) { foreach ($propertiesToDump as $property) { - printf('%-16s: %s' . "\r\n", $property, $object->$property); + printf('%-16s: %s +', $property, $object->$property); } printf("\r\n"); } @@ -376,7 +380,8 @@ public function helpCommand() { foreach ($handler->commands as $command) { $description = str_split($command->description, 50); printf(' %-25s %s%s', implode(', ', $command->aliases), $description[0], $newline); - for ($di = 1; $di < count($description); $di++) { + $descriptionCount = count($description); + for ($di = 1; $di < $descriptionCount; $di++) { printf(' %-25s %s%s', '', $description[$di], $newline); } printf($newline); @@ -385,7 +390,8 @@ public function helpCommand() { foreach ($command->parameters as $parameter) { $description = str_split($parameter->description, 50); printf(' %-23s %s%s', implode(', ', $parameter->aliases), $description[0], $newline); - for ($di = 1; $di < count($description); $di++) { + $descriptionCount = count($description); + for ($di = 1; $di < $descriptionCount; $di++) { printf(' %-23s %s%s', '', $description[$di], $newline); } printf($newline); diff --git a/library/Zend/Service/Console/Command/ParameterSource/Argv.php b/library/Zend/Service/Console/Command/ParameterSource/Argv.php index 1f665fdb1b..ce27cf920f 100644 --- a/library/Zend/Service/Console/Command/ParameterSource/Argv.php +++ b/library/Zend/Service/Console/Command/ParameterSource/Argv.php @@ -59,10 +59,10 @@ public function getValueForParameter($parameter, $argv = array()) break; } } - if (strtolower($parameterValue) == 'true') { - $parameterValue = true; - } else if (strtolower($parameterValue) == 'false') { - $parameterValue = false; + if (strtolower($parameterValue) == 'true') { + $parameterValue = true; + } elseif (strtolower($parameterValue) == 'false') { + $parameterValue = false; } // Done! diff --git a/library/Zend/Service/Console/Command/ParameterSource/ConfigFile.php b/library/Zend/Service/Console/Command/ParameterSource/ConfigFile.php index 468d431ef4..36aaf48eaa 100644 --- a/library/Zend/Service/Console/Command/ParameterSource/ConfigFile.php +++ b/library/Zend/Service/Console/Command/ParameterSource/ConfigFile.php @@ -81,21 +81,25 @@ public function getValueForParameter($parameter, $argv = array()) // Loop aliases foreach ($parameter->aliases as $alias) { - if (array_key_exists($alias, $iniValues)) { - $parameterValue = $iniValues[$alias]; break; - } else if (array_key_exists(strtolower($alias), $iniValues)) { - $parameterValue = $iniValues[strtolower($alias)]; break; - } else if (array_key_exists(str_replace('-', '', $alias), $iniValues)) { - $parameterValue = $iniValues[str_replace('-', '', $alias)]; break; - } else if (array_key_exists(strtolower(str_replace('-', '', $alias)), $iniValues)) { - $parameterValue = $iniValues[strtolower(str_replace('-', '', $alias))]; break; + if (array_key_exists($alias, $iniValues)) { + $parameterValue = $iniValues[$alias]; + break; + } elseif (array_key_exists(strtolower($alias), $iniValues)) { + $parameterValue = $iniValues[strtolower($alias)]; + break; + } elseif (array_key_exists(str_replace('-', '', $alias), $iniValues)) { + $parameterValue = $iniValues[str_replace('-', '', $alias)]; + break; + } elseif (array_key_exists(strtolower(str_replace('-', '', $alias)), $iniValues)) { + $parameterValue = $iniValues[strtolower(str_replace('-', '', $alias))]; + break; } } - if (strtolower($parameterValue) == 'true') { - $parameterValue = true; - } else if (strtolower($parameterValue) == 'false') { - $parameterValue = false; + if (strtolower($parameterValue) == 'true') { + $parameterValue = true; + } elseif (strtolower($parameterValue) == 'false') { + $parameterValue = false; } // Done! diff --git a/library/Zend/Service/Console/Command/ParameterSource/Env.php b/library/Zend/Service/Console/Command/ParameterSource/Env.php index 9fd3680ebf..c1e1a4a745 100644 --- a/library/Zend/Service/Console/Command/ParameterSource/Env.php +++ b/library/Zend/Service/Console/Command/ParameterSource/Env.php @@ -63,10 +63,10 @@ public function getValueForParameter($parameter, $argv = array()) } } - if (strtolower($parameterValue) == 'true') { - $parameterValue = true; - } else if (strtolower($parameterValue) == 'false') { - $parameterValue = false; + if (strtolower($parameterValue) == 'true') { + $parameterValue = true; + } elseif (strtolower($parameterValue) == 'false') { + $parameterValue = false; } // Done! diff --git a/library/Zend/Service/Console/Command/ParameterSource/StdIn.php b/library/Zend/Service/Console/Command/ParameterSource/StdIn.php index 439634c480..03ef7084f3 100644 --- a/library/Zend/Service/Console/Command/ParameterSource/StdIn.php +++ b/library/Zend/Service/Console/Command/ParameterSource/StdIn.php @@ -68,10 +68,10 @@ public function getValueForParameter($parameter, $argv = array()) // Remove ending \r\n $parameterValue = rtrim($parameterValue); - if (strtolower($parameterValue) == 'true') { - $parameterValue = true; - } else if (strtolower($parameterValue) == 'false') { - $parameterValue = false; + if (strtolower($parameterValue) == 'true') { + $parameterValue = true; + } elseif (strtolower($parameterValue) == 'false') { + $parameterValue = false; } } diff --git a/library/Zend/Service/Delicious.php b/library/Zend/Service/Delicious.php index 73957779c1..f4b1c8f1c0 100644 --- a/library/Zend/Service/Delicious.php +++ b/library/Zend/Service/Delicious.php @@ -296,7 +296,7 @@ public function getPosts($tag = null, Zend_Date $dt = null, $url = null) if ($url) { $parms['url'] = $url; } - if ($dt) { + if ($dt !== null) { $parms['dt'] = $dt->get('Y-m-d\TH:i:s\Z'); } @@ -336,7 +336,7 @@ public function getRecentPosts($tag = null, $count = 15) if ($tag) { $parms['tag'] = $tag; } - if ($count) { + if ($count !== '' && $count !== '0') { $parms['count'] = $count; } @@ -396,7 +396,7 @@ public function getUserTags($user, $atleast = null, $count = null, $sort = 'alph if ($count) { $parms['count'] = $count; } - if ($sort) { + if ($sort !== '' && $sort !== '0') { $parms['sort'] = $sort; } @@ -539,12 +539,12 @@ private static function _xmlResponseToArray(DOMDocument $response, $root, $child $rootNode = $response->documentElement; $arrOut = array(); - if ($rootNode->nodeName == $root) { + if ($rootNode->nodeName === $root) { $childNodes = $rootNode->childNodes; for ($i = 0; $i < $childNodes->length; $i++) { $currentNode = $childNodes->item($i); - if ($currentNode->nodeName == $child) { + if ($currentNode->nodeName === $child) { $arrOut[$currentNode->getAttribute($attKey)] = $currentNode->getAttribute($attValue); } } @@ -594,11 +594,7 @@ private static function _evalXmlResult(DOMDocument $response) if ($rootNode && $rootNode->nodeName == 'result') { - if ($rootNode->hasAttribute('code')) { - $strResponse = $rootNode->getAttribute('code'); - } else { - $strResponse = $rootNode->nodeValue; - } + $strResponse = $rootNode->hasAttribute('code') ? $rootNode->getAttribute('code') : $rootNode->nodeValue; if ($strResponse != 'done' && $strResponse != 'ok') { /** diff --git a/library/Zend/Service/Delicious/Post.php b/library/Zend/Service/Delicious/Post.php index 74798bec1e..d392605d90 100644 --- a/library/Zend/Service/Delicious/Post.php +++ b/library/Zend/Service/Delicious/Post.php @@ -92,8 +92,7 @@ public function __construct(Zend_Service_Delicious $service, $values) * @see Zend_Service_Delicious_Exception */ require_once 'Zend/Service/Delicious/Exception.php'; - throw new Zend_Service_Delicious_Exception("Second argument must be array with at least 2 keys ('url' and" - . " 'title')"); + throw new Zend_Service_Delicious_Exception('Second argument must be array with at least 2 keys (\'url\' and \'title\')'); } if (isset($values['date']) && ! $values['date'] instanceof Zend_Date) { @@ -285,7 +284,7 @@ protected static function _parsePostNode(DOMElement $node) * @todo replace strtotime() with Zend_Date equivalent */ 'date' => new Zend_Date(strtotime($node->getAttribute('time'))), - 'shared' => ($node->getAttribute('shared') == 'no' ? false : true), + 'shared' => ($node->getAttribute('shared') != 'no'), 'hash' => $node->getAttribute('hash') ); } diff --git a/library/Zend/Service/Delicious/PostList.php b/library/Zend/Service/Delicious/PostList.php index 5d7160b2da..00ec7e78b4 100644 --- a/library/Zend/Service/Delicious/PostList.php +++ b/library/Zend/Service/Delicious/PostList.php @@ -58,7 +58,7 @@ public function __construct(Zend_Service_Delicious $service, $posts = null) $this->_service = $service; if ($posts instanceof DOMNodeList) { $this->_constructFromNodeList($posts); - } else if (is_array($posts)) { + } elseif (is_array($posts)) { $this->_constructFromArray($posts); } } diff --git a/library/Zend/Service/Ebay/Abstract.php b/library/Zend/Service/Ebay/Abstract.php index 640475b33a..18c4fa7b89 100644 --- a/library/Zend/Service/Ebay/Abstract.php +++ b/library/Zend/Service/Ebay/Abstract.php @@ -114,7 +114,7 @@ public static function optionsToArray($options) { if (null === $options) { $options = array(); - } else if ($options instanceof Zend_Config) { + } elseif ($options instanceof Zend_Config) { $options = $options->toArray(); } @@ -199,7 +199,7 @@ protected function _optionsToNameValueSyntax($options) // parse an array value, check if it is associative $keyRaw = array_keys($value); $keyNumber = range(0, count($value) - 1); - $isAssoc = count(array_diff($keyRaw, $keyNumber)) > 0; + $isAssoc = array_diff($keyRaw, $keyNumber) !== []; // check for tag representation, like // empty key refers to text value // when there is a root tag, attributes receive flags @@ -254,13 +254,9 @@ public static function toEbayValue($value) { if (is_bool($value)) { $value = $value ? '1' : '0'; - } else if ($value instanceof Zend_Date) { + } elseif ($value instanceof Zend_Date) { $value = $value->getIso(); - } else if ($value instanceof DateTime) { - $value = $value->format(DateTime::ISO8601); - } else { - $value = (string) $value; - } + } else $value = $value instanceof DateTime ? $value->format(DateTime::ISO8601) : (string) $value; return $value; } diff --git a/library/Zend/Service/Ebay/Finding.php b/library/Zend/Service/Ebay/Finding.php index a5fd4ae64f..315e0769f6 100644 --- a/library/Zend/Service/Ebay/Finding.php +++ b/library/Zend/Service/Ebay/Finding.php @@ -390,18 +390,14 @@ protected function _parseResponse(Zend_Http_Response $response) $nsMs = self::XMLNS_MS; $expression = "//$nsMs:errorMessage[1]/$ns:error/$ns:severity[.='Error']"; $severityNode = $xpath->query($expression)->item(0); - if ($severityNode) { + if ($severityNode !== null) { $errorNode = $severityNode->parentNode; // ebay message $messageNode = $xpath->query("//$ns:message[1]", $errorNode)->item(0); - if ($messageNode) { - $message = 'eBay error: ' . $messageNode->nodeValue; - } else { - $message = 'eBay error: unknown'; - } + $message = $messageNode !== null ? 'eBay error: ' . $messageNode->nodeValue : 'eBay error: unknown'; // ebay error id $errorIdNode = $xpath->query("//$ns:errorId[1]", $errorNode)->item(0); - if ($errorIdNode) { + if ($errorIdNode !== null) { $message .= ' (#' . $errorIdNode->nodeValue . ')'; } } diff --git a/library/Zend/Service/Ebay/Finding/Abstract.php b/library/Zend/Service/Ebay/Finding/Abstract.php index be025a817b..e914ac1b24 100644 --- a/library/Zend/Service/Ebay/Finding/Abstract.php +++ b/library/Zend/Service/Ebay/Finding/Abstract.php @@ -108,7 +108,7 @@ protected function _init() protected function _initXPath() { $document = $this->_dom->ownerDocument; - if (!isset($document->ebayFindingXPath)) { + if (!(property_exists($document, 'ebayFindingXPath') && $document->ebayFindingXPath !== null)) { $xpath = new DOMXPath($document); foreach (Zend_Service_Ebay_Finding::getXmlNamespaces() as $alias => $uri) { $xpath->registerNamespace($alias, $uri); @@ -154,12 +154,12 @@ protected function _query($path, $type, $array = false) } // array - if ($array) { + if ($array !== '' && $array !== '0') { return $values; } // single value - if (count($values)) { + if ($values !== []) { return reset($values); } diff --git a/library/Zend/Service/Ebay/Finding/Aspect/Histogram/Value/Set.php b/library/Zend/Service/Ebay/Finding/Aspect/Histogram/Value/Set.php index 7b236267cd..2716f4aafe 100644 --- a/library/Zend/Service/Ebay/Finding/Aspect/Histogram/Value/Set.php +++ b/library/Zend/Service/Ebay/Finding/Aspect/Histogram/Value/Set.php @@ -44,7 +44,7 @@ public function current() { // check node $node = $this->_nodes->item($this->_key); - if (!$node) { + if (!$node instanceof \DOMNode) { return null; } diff --git a/library/Zend/Service/Ebay/Finding/Aspect/Set.php b/library/Zend/Service/Ebay/Finding/Aspect/Set.php index 1ba41bf70a..dfcdf63698 100644 --- a/library/Zend/Service/Ebay/Finding/Aspect/Set.php +++ b/library/Zend/Service/Ebay/Finding/Aspect/Set.php @@ -44,7 +44,7 @@ public function current() { // check node $node = $this->_nodes->item($this->_key); - if (!$node) { + if (!$node instanceof \DOMNode) { return null; } diff --git a/library/Zend/Service/Ebay/Finding/Category/Histogram/Set.php b/library/Zend/Service/Ebay/Finding/Category/Histogram/Set.php index 1415bc3b91..9dd835d5dd 100644 --- a/library/Zend/Service/Ebay/Finding/Category/Histogram/Set.php +++ b/library/Zend/Service/Ebay/Finding/Category/Histogram/Set.php @@ -44,7 +44,7 @@ public function current() { // check node $node = $this->_nodes->item($this->_key); - if (!$node) { + if (!$node instanceof \DOMNode) { return null; } diff --git a/library/Zend/Service/Ebay/Finding/Error/Data/Set.php b/library/Zend/Service/Ebay/Finding/Error/Data/Set.php index 5bafbf3158..896df12d6d 100644 --- a/library/Zend/Service/Ebay/Finding/Error/Data/Set.php +++ b/library/Zend/Service/Ebay/Finding/Error/Data/Set.php @@ -44,7 +44,7 @@ public function current() { // check node $node = $this->_nodes->item($this->_key); - if (!$node) { + if (!$node instanceof \DOMNode) { return null; } diff --git a/library/Zend/Service/Ebay/Finding/Response/Abstract.php b/library/Zend/Service/Ebay/Finding/Response/Abstract.php index bd7cb7c489..708f59a990 100644 --- a/library/Zend/Service/Ebay/Finding/Response/Abstract.php +++ b/library/Zend/Service/Ebay/Finding/Response/Abstract.php @@ -123,7 +123,7 @@ protected function _init() $this->version = $this->_query(".//$ns:version[1]", 'string'); $node = $this->_xPath->query(".//$ns:errorMessage[1]", $this->_dom)->item(0); - if ($node) { + if ($node !== null) { /** * @see Zend_Service_Ebay_Finding_Error_Message */ diff --git a/library/Zend/Service/Ebay/Finding/Response/Histograms.php b/library/Zend/Service/Ebay/Finding/Response/Histograms.php index 1e87b59891..94bf6f18e9 100644 --- a/library/Zend/Service/Ebay/Finding/Response/Histograms.php +++ b/library/Zend/Service/Ebay/Finding/Response/Histograms.php @@ -66,7 +66,7 @@ protected function _init() $node = $this->_xPath->query(".//$ns:aspectHistogramContainer[1]", $this->_dom)->item(0); - if ($node) { + if ($node !== null) { /** * @see Zend_Service_Ebay_Finding_Aspect_Histogram_Container */ @@ -75,7 +75,7 @@ protected function _init() } $node = $this->_xPath->query(".//$ns:categoryHistogramContainer[1]", $this->_dom)->item(0); - if ($node) { + if ($node !== null) { /** * @see Zend_Service_Ebay_Finding_Category_Histogram_Container */ diff --git a/library/Zend/Service/Ebay/Finding/Response/Items.php b/library/Zend/Service/Ebay/Finding/Response/Items.php index cb6108985b..441eadb163 100644 --- a/library/Zend/Service/Ebay/Finding/Response/Items.php +++ b/library/Zend/Service/Ebay/Finding/Response/Items.php @@ -81,7 +81,7 @@ protected function _init() ); $node = $this->_xPath->query(".//$ns:searchResult[1]", $this->_dom)->item(0); - if ($node) { + if ($node !== null) { /** * @see Zend_Service_Ebay_Finding_Search_Result */ @@ -90,7 +90,7 @@ protected function _init() } $node = $this->_xPath->query(".//$ns:paginationOutput[1]", $this->_dom)->item(0); - if ($node) { + if ($node !== null) { /** * @see Zend_Service_Ebay_Finding_PaginationOutput */ @@ -139,12 +139,8 @@ public function page(Zend_Service_Ebay_Finding $proxy, $number) if (!is_array($productId)) { $productId = array('' => $productId); } - $arguments[] = array_key_exists('', $productId) - ? $productId[''] - : null; - $arguments[] = array_key_exists('type', $productId) - ? $productId['type'] - : null; + $arguments[] = $productId[''] ?? null; + $arguments[] = $productId['type'] ?? null; break; case 'findItemsIneBayStores': diff --git a/library/Zend/Service/Ebay/Finding/Response/Keywords.php b/library/Zend/Service/Ebay/Finding/Response/Keywords.php index 7e992a5021..08697bdf52 100644 --- a/library/Zend/Service/Ebay/Finding/Response/Keywords.php +++ b/library/Zend/Service/Ebay/Finding/Response/Keywords.php @@ -70,7 +70,7 @@ public function findItems(Zend_Service_Ebay_Finding $proxy, $options = null) { // prepare options $options = Zend_Service_Ebay_Abstract::optionsToArray($options); - $options = $options + $this->_options; + $options += $this->_options; // find items return $proxy->findItemsByKeywords($this->keywords, $options); diff --git a/library/Zend/Service/Ebay/Finding/Search/Item.php b/library/Zend/Service/Ebay/Finding/Search/Item.php index 55c62e2c8a..45adb82b57 100644 --- a/library/Zend/Service/Ebay/Finding/Search/Item.php +++ b/library/Zend/Service/Ebay/Finding/Search/Item.php @@ -318,7 +318,7 @@ protected function _init() ); $node = $this->_xPath->query(".//$ns:listingInfo[1]", $this->_dom)->item(0); - if ($node) { + if ($node !== null) { /** * @see Zend_Service_Ebay_Finding_ListingInfo */ @@ -327,7 +327,7 @@ protected function _init() } $node = $this->_xPath->query(".//$ns:primaryCategory[1]", $this->_dom)->item(0); - if ($node) { + if ($node !== null) { /** * @see Zend_Service_Ebay_Finding_Category */ @@ -336,7 +336,7 @@ protected function _init() } $node = $this->_xPath->query(".//$ns:secondaryCategory[1]", $this->_dom)->item(0); - if ($node) { + if ($node !== null) { /** * @see Zend_Service_Ebay_Finding_Category */ @@ -345,7 +345,7 @@ protected function _init() } $node = $this->_xPath->query(".//$ns:sellerInfo[1]", $this->_dom)->item(0); - if ($node) { + if ($node !== null) { /** * @see Zend_Service_Ebay_Finding_SellerInfo */ @@ -354,7 +354,7 @@ protected function _init() } $node = $this->_xPath->query(".//$ns:sellingStatus[1]", $this->_dom)->item(0); - if ($node) { + if ($node !== null) { /** * @see Zend_Service_Ebay_Finding_SellingStatus */ @@ -363,7 +363,7 @@ protected function _init() } $node = $this->_xPath->query("./$ns:shippingInfo", $this->_dom)->item(0); - if ($node) { + if ($node !== null) { /** * @see Zend_Service_Ebay_Finding_ShippingInfo */ @@ -372,7 +372,7 @@ protected function _init() } $node = $this->_xPath->query(".//$ns:storeInfo[1]", $this->_dom)->item(0); - if ($node) { + if ($node !== null) { /** * @see Zend_Service_Ebay_Finding_Storefront */ diff --git a/library/Zend/Service/Ebay/Finding/Search/Item/Set.php b/library/Zend/Service/Ebay/Finding/Search/Item/Set.php index 57a3727fe5..43ecfaf942 100644 --- a/library/Zend/Service/Ebay/Finding/Search/Item/Set.php +++ b/library/Zend/Service/Ebay/Finding/Search/Item/Set.php @@ -44,7 +44,7 @@ public function current() { // check node $node = $this->_nodes->item($this->_key); - if (!$node) { + if (!$node instanceof \DOMNode) { return null; } diff --git a/library/Zend/Service/Flickr.php b/library/Zend/Service/Flickr.php index 76bcde68e9..585c6fbbcc 100644 --- a/library/Zend/Service/Flickr.php +++ b/library/Zend/Service/Flickr.php @@ -153,13 +153,7 @@ public function userSearch($query, array $options = null) // can't access by username, must get ID first - if (strchr($query, '@')) { - // optimistically hope this is an email - $options['user_id'] = $this->getIdByEmail($query); - } else { - // we can safely ignore this exception here - $options['user_id'] = $this->getIdByUsername($query); - } + $options['user_id'] = strstr($query, '@') ? $this->getIdByEmail($query) : $this->getIdByUsername($query); $options = $this->_prepareOptions($method, $options, $defaultOptions); $this->_validateUserSearch($options); @@ -612,7 +606,7 @@ protected function _prepareOptions($method, array $options, array $defaultOption protected function _compareOptions(array $options, array $validOptions) { $difference = array_diff(array_keys($options), $validOptions); - if ($difference) { + if ($difference !== []) { /** * @see Zend_Service_Exception */ diff --git a/library/Zend/Service/Flickr/Result.php b/library/Zend/Service/Flickr/Result.php index 8fad69a28a..28bf64472f 100644 --- a/library/Zend/Service/Flickr/Result.php +++ b/library/Zend/Service/Flickr/Result.php @@ -31,6 +31,7 @@ */ class Zend_Service_Flickr_Result { + public string $name; /** * The photo's Flickr ID. * diff --git a/library/Zend/Service/LiveDocx/MailMerge.php b/library/Zend/Service/LiveDocx/MailMerge.php index 0287e73f89..ce6f2726ef 100644 --- a/library/Zend/Service/LiveDocx/MailMerge.php +++ b/library/Zend/Service/LiveDocx/MailMerge.php @@ -149,11 +149,7 @@ public function setFieldValues($values) $this->logIn(); foreach ($values as $value) { - if (is_array($value)) { - $method = 'multiAssocArrayToArrayOfArrayOfString'; - } else { - $method = 'assocArrayToArrayOfArrayOfString'; - } + $method = is_array($value) ? 'multiAssocArrayToArrayOfArrayOfString' : 'assocArrayToArrayOfArrayOfString'; break; } @@ -332,7 +328,7 @@ public function createDocument() { $this->logIn(); - if (count($this->_fieldValues) > 0) { + if ($this->_fieldValues !== []) { $this->setFieldValues($this->_fieldValues); } @@ -397,7 +393,7 @@ public function getMetafiles($fromPage, $toPage) 'toPage' => (integer) $toPage, )); - if (isset($result->GetMetafilesResult->string)) { + if (property_exists($result->GetMetafilesResult, 'string') && $result->GetMetafilesResult->string !== null) { $pageCounter = (integer) $fromPage; if (is_array($result->GetMetafilesResult->string)) { foreach ($result->GetMetafilesResult->string as $string) { @@ -426,7 +422,7 @@ public function getAllMetafiles() $ret = array(); $result = $this->getSoapClient()->GetAllMetafiles(); - if (isset($result->GetAllMetafilesResult->string)) { + if (property_exists($result->GetAllMetafilesResult, 'string') && $result->GetAllMetafilesResult->string !== null) { $pageCounter = 1; if (is_array($result->GetAllMetafilesResult->string)) { foreach ($result->GetAllMetafilesResult->string as $string) { @@ -465,7 +461,7 @@ public function getBitmaps($fromPage, $toPage, $zoomFactor, $format) 'format' => (string) $format, )); - if (isset($result->GetBitmapsResult->string)) { + if (property_exists($result->GetBitmapsResult, 'string') && $result->GetBitmapsResult->string !== null) { $pageCounter = (integer) $fromPage; if (is_array($result->GetBitmapsResult->string)) { foreach ($result->GetBitmapsResult->string as $string) { @@ -499,7 +495,7 @@ public function getAllBitmaps($zoomFactor, $format) 'format' => (string) $format, )); - if (isset($result->GetAllBitmapsResult->string)) { + if (property_exists($result->GetAllBitmapsResult, 'string') && $result->GetAllBitmapsResult->string !== null) { $pageCounter = 1; if (is_array($result->GetAllBitmapsResult->string)) { foreach ($result->GetAllBitmapsResult->string as $string) { @@ -527,7 +523,7 @@ public function getFieldNames() $ret = array(); $result = $this->getSoapClient()->GetFieldNames(); - if (isset($result->GetFieldNamesResult->string)) { + if (property_exists($result->GetFieldNamesResult, 'string') && $result->GetFieldNamesResult->string !== null) { if (is_array($result->GetFieldNamesResult->string)) { $ret = $result->GetFieldNamesResult->string; } else { @@ -554,7 +550,7 @@ public function getBlockFieldNames($blockName) 'blockName' => $blockName )); - if (isset($result->GetBlockFieldNamesResult->string)) { + if (property_exists($result->GetBlockFieldNamesResult, 'string') && $result->GetBlockFieldNamesResult->string !== null) { if (is_array($result->GetBlockFieldNamesResult->string)) { $ret = $result->GetBlockFieldNamesResult->string; } else { @@ -578,7 +574,7 @@ public function getBlockNames() $ret = array(); $result = $this->getSoapClient()->GetBlockNames(); - if (isset($result->GetBlockNamesResult->string)) { + if (property_exists($result->GetBlockNamesResult, 'string') && $result->GetBlockNamesResult->string !== null) { if (is_array($result->GetBlockNamesResult->string)) { $ret = $result->GetBlockNamesResult->string; } else { @@ -670,7 +666,7 @@ public function listTemplates() $ret = array(); $result = $this->getSoapClient()->ListTemplates(); - if (isset($result->ListTemplatesResult)) { + if (property_exists($result, 'ListTemplatesResult') && $result->ListTemplatesResult !== null) { $ret = $this->_backendListArrayToMultiAssocArray($result->ListTemplatesResult); } @@ -708,7 +704,7 @@ public function shareDocument() $ret = null; $result = $this->getSoapClient()->ShareDocument(); - if (isset($result->ShareDocumentResult)) { + if (property_exists($result, 'ShareDocumentResult') && $result->ShareDocumentResult !== null) { $ret = (string) $result->ShareDocumentResult; } @@ -728,7 +724,7 @@ public function listSharedDocuments() $ret = array(); $result = $this->getSoapClient()->ListSharedDocuments(); - if (isset($result->ListSharedDocumentsResult)) { + if (property_exists($result, 'ListSharedDocumentsResult') && $result->ListSharedDocumentsResult !== null) { $ret = $this->_backendListArrayToMultiAssocArray( $result->ListSharedDocumentsResult ); @@ -817,7 +813,7 @@ public function getTemplateFormats() $ret = array(); $result = $this->getSoapClient()->GetTemplateFormats(); - if (isset($result->GetTemplateFormatsResult->string)) { + if (property_exists($result->GetTemplateFormatsResult, 'string') && $result->GetTemplateFormatsResult->string !== null) { $ret = $result->GetTemplateFormatsResult->string; $ret = array_map('strtolower', $ret); } @@ -838,7 +834,7 @@ public function getDocumentFormats() $ret = array(); $result = $this->getSoapClient()->GetDocumentFormats(); - if (isset($result->GetDocumentFormatsResult->string)) { + if (property_exists($result->GetDocumentFormatsResult, 'string') && $result->GetDocumentFormatsResult->string !== null) { $ret = $result->GetDocumentFormatsResult->string; $ret = array_map('strtolower', $ret); } @@ -859,7 +855,7 @@ public function getFontNames() $ret = array(); $result = $this->getSoapClient()->GetFontNames(); - if (isset($result->GetFontNamesResult->string)) { + if (property_exists($result->GetFontNamesResult, 'string') && $result->GetFontNamesResult->string !== null) { $ret = $result->GetFontNamesResult->string; } @@ -879,7 +875,7 @@ public function getDocumentAccessOptions() $ret = array(); $result = $this->getSoapClient()->GetDocumentAccessOptions(); - if (isset($result->GetDocumentAccessOptionsResult->string)) { + if (property_exists($result->GetDocumentAccessOptionsResult, 'string') && $result->GetDocumentAccessOptionsResult->string !== null) { $ret = $result->GetDocumentAccessOptionsResult->string; } @@ -899,7 +895,7 @@ public function getImageImportFormats() $ret = array(); $result = $this->getSoapClient()->GetImageImportFormats(); - if (isset($result->GetImageImportFormatsResult->string)) { + if (property_exists($result->GetImageImportFormatsResult, 'string') && $result->GetImageImportFormatsResult->string !== null) { $ret = $result->GetImageImportFormatsResult->string; $ret = array_map('strtolower', $ret); } @@ -920,7 +916,7 @@ public function getImageExportFormats() $ret = array(); $result = $this->getSoapClient()->GetImageExportFormats(); - if (isset($result->GetImageExportFormatsResult->string)) { + if (property_exists($result->GetImageExportFormatsResult, 'string') && $result->GetImageExportFormatsResult->string !== null) { $ret = $result->GetImageExportFormatsResult->string; $ret = array_map('strtolower', $ret); } @@ -1015,7 +1011,7 @@ public function listImages() $ret = array(); $result = $this->getSoapClient()->ListImages(); - if (isset($result->ListImagesResult)) { + if (property_exists($result, 'ListImagesResult') && $result->ListImagesResult !== null) { $ret = $this->_backendListArrayToMultiAssocArray($result->ListImagesResult); } @@ -1069,7 +1065,7 @@ protected function _backendListArrayToMultiAssocArray($list) $this->logIn(); $ret = array(); - if (isset($list->ArrayOfString)) { + if (property_exists($list, 'ArrayOfString') && $list->ArrayOfString !== null) { foreach ($list->ArrayOfString as $a) { if (is_array($a)) { // 1 template only $o = new stdClass(); @@ -1079,7 +1075,7 @@ protected function _backendListArrayToMultiAssocArray($list) } unset($a); - if (isset($o->string)) { + if (property_exists($o, 'string') && $o->string !== null) { $date1 = new Zend_Date($o->string[3], Zend_Date::RFC_1123); $date2 = new Zend_Date($o->string[1], Zend_Date::RFC_1123); diff --git a/library/Zend/Service/Rackspace/Abstract.php b/library/Zend/Service/Rackspace/Abstract.php index afec6a4e5d..487a49c01a 100644 --- a/library/Zend/Service/Rackspace/Abstract.php +++ b/library/Zend/Service/Rackspace/Abstract.php @@ -163,10 +163,8 @@ public function getAuthUrl() */ public function getStorageUrl() { - if (empty($this->storageUrl)) { - if (!$this->authenticate()) { - return false; - } + if (empty($this->storageUrl) && !$this->authenticate()) { + return false; } return $this->storageUrl; } @@ -177,10 +175,8 @@ public function getStorageUrl() */ public function getCdnUrl() { - if (empty($this->cdnUrl)) { - if (!$this->authenticate()) { - return false; - } + if (empty($this->cdnUrl) && !$this->authenticate()) { + return false; } return $this->cdnUrl; } @@ -191,10 +187,8 @@ public function getCdnUrl() */ public function getManagementUrl() { - if (empty($this->managementUrl)) { - if (!$this->authenticate()) { - return false; - } + if (empty($this->managementUrl) && !$this->authenticate()) { + return false; } return $this->managementUrl; } @@ -269,10 +263,8 @@ public function getServiceNet() */ public function getToken() { - if (empty($this->token)) { - if (!$this->authenticate()) { - return false; - } + if (empty($this->token) && !$this->authenticate()) { + return false; } return $this->token; } diff --git a/library/Zend/Service/Rackspace/Files.php b/library/Zend/Service/Rackspace/Files.php index fd4bc6036a..0f1dce0e01 100644 --- a/library/Zend/Service/Rackspace/Files.php +++ b/library/Zend/Service/Rackspace/Files.php @@ -147,12 +147,11 @@ public function getInfoAccount() { $result= $this->httpCall($this->getStorageUrl(),'HEAD'); if ($result->isSuccessful()) { - $output= array( + return array( 'tot_containers' => $result->getHeader(self::ACCOUNT_CONTAINER_COUNT), 'size_containers' => $result->getHeader(self::ACCOUNT_BYTES_USED), 'tot_objects' => $result->getHeader(self::ACCOUNT_OBJ_COUNT) ); - return $output; } return false; } @@ -278,13 +277,12 @@ public function getMetadataContainer($container) $metadata[strtolower(substr($type, $count))]= $value; } } - $data= array ( + return array ( 'name' => $container, 'count' => $result->getHeader(self::CONTAINER_OBJ_COUNT), 'bytes' => $result->getHeader(self::CONTAINER_BYTES_USE), 'metadata' => $metadata ); - return $data; case '404': $this->errorMsg= self::ERROR_CONTAINER_NOT_FOUND; break; @@ -524,7 +522,7 @@ public function getMetadataObject($container,$object) { $metadata[strtolower(substr($type, $count))]= $value; } } - $data= array ( + return array ( 'name' => $object, 'container' => $container, 'hash' => $result->getHeader(self::HEADER_HASH), @@ -533,7 +531,6 @@ public function getMetadataObject($container,$object) { 'last_modified' => $result->getHeader(self::HEADER_LAST_MODIFIED), 'metadata' => $metadata ); - return $data; case '404': $this->errorMsg= self::ERROR_OBJECT_NOT_FOUND; break; @@ -660,18 +657,10 @@ public function updateCdnContainer($container,$ttl=null,$cdn_enabled=null,$log=n } } if (isset($cdn_enabled)) { - if ($cdn_enabled===true) { - $headers[self::CDN_ENABLED]= 'true'; - } else { - $headers[self::CDN_ENABLED]= 'false'; - } + $headers[self::CDN_ENABLED] = $cdn_enabled ? 'true' : 'false'; } if (isset($log)) { - if ($log===true) { - $headers[self::CDN_LOG_RETENTION]= 'true'; - } else { - $headers[self::CDN_LOG_RETENTION]= 'false'; - } + $headers[self::CDN_LOG_RETENTION] = $log ? 'true' : 'false'; } $result= $this->httpCall($this->getCdnUrl().'/'.rawurlencode($container),'POST',$headers); $status= $result->getStatus(); diff --git a/library/Zend/Service/Rackspace/Files/Container.php b/library/Zend/Service/Rackspace/Files/Container.php index da6b704623..4023624307 100644 --- a/library/Zend/Service/Rackspace/Files/Container.php +++ b/library/Zend/Service/Rackspace/Files/Container.php @@ -24,6 +24,10 @@ class Zend_Service_Rackspace_Files_Container { + /** + * @var mixed|\Zend_Service_Rackspace_Files + */ + public $service; const ERROR_PARAM_FILE_CONSTRUCT = 'The Zend_Service_Rackspace_Files passed in construction is not valid'; const ERROR_PARAM_ARRAY_CONSTRUCT = 'The array passed in construction is not valid'; @@ -197,10 +201,8 @@ public function getMetadata($key = null) if (!empty($result) && is_array($result)) { if (empty($key)) { return $result['metadata']; - } else { - if (isset ($result['metadata'][$key])) { - return $result['metadata'][$key]; - } + } elseif (isset ($result['metadata'][$key])) { + return $result['metadata'][$key]; } } diff --git a/library/Zend/Service/Rackspace/Files/Object.php b/library/Zend/Service/Rackspace/Files/Object.php index 4b2714ba27..b495aaedb3 100644 --- a/library/Zend/Service/Rackspace/Files/Object.php +++ b/library/Zend/Service/Rackspace/Files/Object.php @@ -286,10 +286,8 @@ public function copyTo($container_dest,$name_dest,$metadata=array(),$content_typ public function getCdnUrl() { $result= $this->service->getInfoCdnContainer($this->container); - if ($result!==false) { - if ($result['cdn_enabled']) { - return $result['cdn_uri'].'/'.$this->name; - } + if ($result!==false && $result['cdn_enabled']) { + return $result['cdn_uri'].'/'.$this->name; } return false; } @@ -302,10 +300,8 @@ public function getCdnUrl() public function getCdnUrlSsl() { $result= $this->service->getInfoCdnContainer($this->container); - if ($result!==false) { - if ($result['cdn_enabled']) { - return $result['cdn_uri_ssl'].'/'.$this->name; - } + if ($result!==false && $result['cdn_enabled']) { + return $result['cdn_uri_ssl'].'/'.$this->name; } return false; } diff --git a/library/Zend/Service/Rackspace/Servers.php b/library/Zend/Service/Rackspace/Servers.php index c795190577..3a4ff2ada3 100644 --- a/library/Zend/Service/Rackspace/Servers.php +++ b/library/Zend/Service/Rackspace/Servers.php @@ -500,11 +500,7 @@ public function rebootServer($id,$hard=false) require_once 'Zend/Service/Rackspace/Exception.php'; throw new Zend_Service_Rackspace_Exception('You didn\'t specified the ID of the server'); } - if (!$hard) { - $type= 'SOFT'; - } else { - $type= 'HARD'; - } + $type = $hard ? 'HARD' : 'SOFT'; $data= array ( 'reboot' => array ( 'type' => $type diff --git a/library/Zend/Service/Rackspace/Servers/Server.php b/library/Zend/Service/Rackspace/Servers/Server.php index 5249a9732e..4ec8d22038 100644 --- a/library/Zend/Service/Rackspace/Servers/Server.php +++ b/library/Zend/Service/Rackspace/Servers/Server.php @@ -272,7 +272,7 @@ public function getMetadata($key=null) public function changeName($name) { $result= $this->service->changeServerName($this->id, $name); - if ($result!==false) { + if ($result) { $this->name= $name; return true; } @@ -287,7 +287,7 @@ public function changeName($name) public function changePassword($password) { $result= $this->service->changeServerPassword($this->id, $password); - if ($result!==false) { + if ($result) { $this->adminPass= $password; return true; } diff --git a/library/Zend/Service/ReCaptcha.php b/library/Zend/Service/ReCaptcha.php index 4993d201ea..9f7b25a67c 100644 --- a/library/Zend/Service/ReCaptcha.php +++ b/library/Zend/Service/ReCaptcha.php @@ -138,7 +138,7 @@ public function __construct($publicKey = null, $privateKey = null, if ($ip !== null) { $this->setIp($ip); - } else if (isset($_SERVER['REMOTE_ADDR'])) { + } elseif (isset($_SERVER['REMOTE_ADDR'])) { $this->setIp($_SERVER['REMOTE_ADDR']); } @@ -389,14 +389,14 @@ public function getHtml($name = null) $host = self::API_SERVER; - if ((bool) $this->_params['ssl'] === true) { + if ((bool) $this->_params['ssl']) { $host = self::API_SECURE_SERVER; } $htmlBreak = '
'; $htmlInputClosing = '>'; - if ((bool) $this->_params['xhtml'] === true) { + if ((bool) $this->_params['xhtml']) { $htmlBreak = '
'; $htmlInputClosing = '/>'; } diff --git a/library/Zend/Service/ReCaptcha/MailHide.php b/library/Zend/Service/ReCaptcha/MailHide.php index 6bbe6614f1..7311c69550 100644 --- a/library/Zend/Service/ReCaptcha/MailHide.php +++ b/library/Zend/Service/ReCaptcha/MailHide.php @@ -102,11 +102,7 @@ public function __construct($publicKey = null, $privateKey = null, $email = null } /* Merge if needed */ - if (is_array($options)) { - $options = array_merge($this->getDefaultOptions(), $options); - } else { - $options = $this->getDefaultOptions(); - } + $options = is_array($options) ? array_merge($this->getDefaultOptions(), $options) : $this->getDefaultOptions(); parent::__construct($publicKey, $privateKey, null, $options); @@ -235,11 +231,7 @@ public function setEmail($email) /* Decide on how much of the local part we want to reveal */ if (strlen($emailParts[0]) <= 4) { $emailParts[0] = substr($emailParts[0], 0, 1); - } else if (strlen($emailParts[0]) <= 6) { - $emailParts[0] = substr($emailParts[0], 0, 3); - } else { - $emailParts[0] = substr($emailParts[0], 0, 4); - } + } else $emailParts[0] = strlen($emailParts[0]) <= 6 ? substr($emailParts[0], 0, 3) : substr($emailParts[0], 0, 4); $this->_emailLocalPart = $emailParts[0]; $this->_emailDomainPart = $emailParts[1]; diff --git a/library/Zend/Service/ReCaptcha/Response.php b/library/Zend/Service/ReCaptcha/Response.php index d20318f1d4..8817080a96 100644 --- a/library/Zend/Service/ReCaptcha/Response.php +++ b/library/Zend/Service/ReCaptcha/Response.php @@ -80,11 +80,7 @@ public function __construct($status = null, $errorCode = null, Zend_Http_Respons */ public function setStatus($status) { - if ($status === 'true') { - $this->_status = true; - } else { - $this->_status = false; - } + $this->_status = $status === 'true'; return $this; } diff --git a/library/Zend/Service/SlideShare.php b/library/Zend/Service/SlideShare.php index 33577af8a2..86553b75e2 100644 --- a/library/Zend/Service/SlideShare.php +++ b/library/Zend/Service/SlideShare.php @@ -354,11 +354,7 @@ public function uploadSlideShow( ); } - if (!empty($description)) { - $params['slideshow_description'] = $description; - } else { - $params['slideshow_description'] = ""; - } + $params['slideshow_description'] = empty($description) ? "" : $description; if (!empty($tags)) { $tmp = array(); @@ -458,7 +454,7 @@ public function getSlideShow($ssId) ); } - if (!($sxe->getName() == 'Slideshow')) { + if ($sxe->getName() != 'Slideshow') { require_once 'Zend/Service/SlideShare/Exception.php'; throw new Zend_Service_SlideShare_Exception( 'Unknown XML Repsonse Received' diff --git a/library/Zend/Service/SqlAzure/Management/Client.php b/library/Zend/Service/SqlAzure/Management/Client.php index 5aec418b88..eced247366 100644 --- a/library/Zend/Service/SqlAzure/Management/Client.php +++ b/library/Zend/Service/SqlAzure/Management/Client.php @@ -398,22 +398,18 @@ public function listServers() if (!$xml->Server) { return array(); } - if (count($xml->Server) > 1) { - $xmlServices = $xml->Server; - } else { - $xmlServices = array($xml->Server); - } + $xmlServices = count($xml->Server) > 1 ? $xml->Server : array($xml->Server); $services = array(); if (!is_null($xmlServices)) { - for ($i = 0; $i < count($xmlServices); $i++) { - $services[] = new Zend_Service_SqlAzure_Management_ServerInstance( - (string)$xmlServices[$i]->Name, - (string)$xmlServices[$i]->AdministratorLogin, - (string)$xmlServices[$i]->Location + foreach ($xmlServices as $i => $xmlService) { + $services[] = new Zend_Service_SqlAzure_Management_ServerInstance( + (string)$xmlService->Name, + (string)$xmlService->AdministratorLogin, + (string)$xmlService->Location ); - } + } } return $services; } else { @@ -542,22 +538,18 @@ public function listFirewallRules($serverName) if (!$xml->FirewallRule) { return array(); } - if (count($xml->FirewallRule) > 1) { - $xmlServices = $xml->FirewallRule; - } else { - $xmlServices = array($xml->FirewallRule); - } + $xmlServices = count($xml->FirewallRule) > 1 ? $xml->FirewallRule : array($xml->FirewallRule); $services = array(); if (!is_null($xmlServices)) { - for ($i = 0; $i < count($xmlServices); $i++) { - $services[] = new Zend_Service_SqlAzure_Management_FirewallRuleInstance( - (string)$xmlServices[$i]->Name, - (string)$xmlServices[$i]->StartIpAddress, - (string)$xmlServices[$i]->EndIpAddress + foreach ($xmlServices as $i => $xmlService) { + $services[] = new Zend_Service_SqlAzure_Management_FirewallRuleInstance( + (string)$xmlService->Name, + (string)$xmlService->StartIpAddress, + (string)$xmlService->EndIpAddress ); - } + } } return $services; } else { diff --git a/library/Zend/Service/StrikeIron/Base.php b/library/Zend/Service/StrikeIron/Base.php index a2d35ef218..5f3ebccdfa 100644 --- a/library/Zend/Service/StrikeIron/Base.php +++ b/library/Zend/Service/StrikeIron/Base.php @@ -150,7 +150,7 @@ protected function _initSoapHeaders() */ require_once 'Zend/Service/StrikeIron/Exception.php'; throw new Zend_Service_StrikeIron_Exception('Header must be instance of SoapHeader'); - } else if ($header->name == 'LicenseInfo') { + } elseif ($header->name == 'LicenseInfo') { $foundLicenseInfo = true; break; } diff --git a/library/Zend/Service/Twitter.php b/library/Zend/Service/Twitter.php index 895f6706e7..af022b14c4 100755 --- a/library/Zend/Service/Twitter.php +++ b/library/Zend/Service/Twitter.php @@ -328,10 +328,7 @@ public function setUsername($value) */ public function isAuthorised() { - if ($this->getHttpClient() instanceof Zend_Oauth_Client) { - return true; - } - return false; + return $this->getHttpClient() instanceof Zend_Oauth_Client; } /** @@ -861,11 +858,7 @@ public function statusesHomeTimeline(array $options = array()) $params['max_id'] = $this->validInteger($value); break; case 'trim_user': - if (in_array($value, array(true, 'true', 't', 1, '1'))) { - $value = true; - } else { - $value = false; - } + $value = in_array($value, array(true, 'true', 't', 1, '1')); $params['trim_user'] = $value; break; case 'contributor_details:': @@ -918,11 +911,7 @@ public function statusesMentionsTimeline(array $options = array()) $params['max_id'] = $this->validInteger($value); break; case 'trim_user': - if (in_array($value, array(true, 'true', 't', 1, '1'))) { - $value = true; - } else { - $value = false; - } + $value = in_array($value, array(true, 'true', 't', 1, '1')); $params['trim_user'] = $value; break; case 'contributor_details:': @@ -1003,7 +992,7 @@ public function statusesUpdate($status, $inReplyToStatusId = null) $params = array('status' => $status); $inReplyToStatusId = $this->validInteger($inReplyToStatusId); - if ($inReplyToStatusId) { + if ($inReplyToStatusId !== 0) { $params['in_reply_to_status_id'] = $inReplyToStatusId; } $response = $this->post($path, $params); @@ -1051,11 +1040,7 @@ public function statusesUserTimeline(array $options = array()) $params['max_id'] = $this->validInteger($value); break; case 'trim_user': - if (in_array($value, array(true, 'true', 't', 1, '1'))) { - $value = true; - } else { - $value = false; - } + $value = in_array($value, array(true, 'true', 't', 1, '1')); $params['trim_user'] = $value; break; case 'contributor_details:': @@ -1243,8 +1228,7 @@ protected function get($path, array $query = array()) $client = $this->getHttpClient(); $this->prepare($path, $client); $client->setParameterGet($query); - $response = $client->request(Zend_Http_Client::GET); - return $response; + return $client->request(Zend_Http_Client::GET); } /** @@ -1259,8 +1243,7 @@ protected function post($path, $data = null) { $client = $this->getHttpClient(); $this->prepare($path, $client); - $response = $this->performPost(Zend_Http_Client::POST, $data, $client); - return $response; + return $this->performPost(Zend_Http_Client::POST, $data, $client); } /** @@ -1296,7 +1279,7 @@ protected function performPost($method, $data, Zend_Http_Client $client) */ protected function createUserParameter($id, array $params) { - if ($this->validInteger($id)) { + if ($this->validInteger($id) !== 0) { $params['user_id'] = $id; return $params; } diff --git a/library/Zend/Service/Twitter/Response.php b/library/Zend/Service/Twitter/Response.php index 23f994dab5..3590a604cc 100644 --- a/library/Zend/Service/Twitter/Response.php +++ b/library/Zend/Service/Twitter/Response.php @@ -147,7 +147,7 @@ public function getErrors() return array(); } if (null === $this->jsonBody - || !isset($this->jsonBody->errors) + || !(property_exists($this->jsonBody, 'errors') && $this->jsonBody->errors !== null) ) { require_once 'Zend/Service/Twitter/Exception.php'; throw new Zend_Service_Twitter_Exception( diff --git a/library/Zend/Service/WindowsAzure/CommandLine/PackageScaffolder/PackageScaffolderAbstract.php b/library/Zend/Service/WindowsAzure/CommandLine/PackageScaffolder/PackageScaffolderAbstract.php index 113e7beb32..4511f68dac 100644 --- a/library/Zend/Service/WindowsAzure/CommandLine/PackageScaffolder/PackageScaffolderAbstract.php +++ b/library/Zend/Service/WindowsAzure/CommandLine/PackageScaffolder/PackageScaffolderAbstract.php @@ -47,7 +47,7 @@ protected function log($message, $newLine = true) if (error_reporting() === 0) { return; } - file_put_contents('php://stderr', $message . ($newLine ? "\r\n" : '')); + file_put_contents('php://stderr', $message . ($newLine !== '' && $newLine !== '0' ? "\r\n" : '')); } /** @@ -143,7 +143,7 @@ protected function createDirectory($path, $abortIfExists = true, $recursive = tr * @return boolean */ protected function copyDirectory($sourcePath, $destinationPath, $abortIfExists = true, $mode = '0775') { - $mode = $mode & ~0002; + $mode &= ~0002; if (is_null($sourcePath) || !is_string($sourcePath) || empty($sourcePath)) { throw new InvalidArgumentException("Undefined \"sourcePath\""); @@ -158,44 +158,42 @@ protected function copyDirectory($sourcePath, $destinationPath, $abortIfExists = } if (is_dir($sourcePath)) { - if (!is_dir($destinationPath) && !mkdir($destinationPath, $mode)) { - throw new RuntimeException("Failed to create target directory \"{$destinationPath}\"" ); - } - $d = dir($sourcePath); - while ( false !== ( $entry = $d->read() ) ) { - if ( $entry == '.' || $entry == '..' ) { - continue; - } - $strSourceEntry = $sourcePath . '/' . $entry; - $strTargetEntry = $destinationPath . '/' . $entry; - if (is_dir($strSourceEntry) ) { - $this->copyDirectory( - $strSourceEntry, - $strTargetEntry, - false, - $mode - ); - continue; - } - if (!copy($strSourceEntry, $strTargetEntry) ) { - throw new RuntimeException ( - "Failed to copy" - . " file \"{$strSourceEntry}\"" - . " to \"{$strTargetEntry}\"" - ); - } - } - $d->close(); - } else { - if (!copy($sourcePath, $destinationPath)) { - throw new RuntimeException ( - "Failed to copy" - . " file \"{$sourcePath}\"" - . " to \"{$destinationPath}\"" - - ); - } - } + if (!is_dir($destinationPath) && !mkdir($destinationPath, $mode)) { + throw new RuntimeException("Failed to create target directory \"{$destinationPath}\"" ); + } + $d = dir($sourcePath); + while ( false !== ( $entry = $d->read() ) ) { + if ( $entry == '.' || $entry == '..' ) { + continue; + } + $strSourceEntry = $sourcePath . '/' . $entry; + $strTargetEntry = $destinationPath . '/' . $entry; + if (is_dir($strSourceEntry) ) { + $this->copyDirectory( + $strSourceEntry, + $strTargetEntry, + false, + $mode + ); + continue; + } + if (!copy($strSourceEntry, $strTargetEntry) ) { + throw new RuntimeException ( + "Failed to copy" + . " file \"{$strSourceEntry}\"" + . " to \"{$strTargetEntry}\"" + ); + } + } + $d->close(); + } elseif (!copy($sourcePath, $destinationPath)) { + throw new RuntimeException ( + "Failed to copy" + . " file \"{$sourcePath}\"" + . " to \"{$destinationPath}\"" + + ); + } return true; } diff --git a/library/Zend/Service/WindowsAzure/Credentials/CredentialsAbstract.php b/library/Zend/Service/WindowsAzure/Credentials/CredentialsAbstract.php index 76893c980a..a150f2df7f 100644 --- a/library/Zend/Service/WindowsAzure/Credentials/CredentialsAbstract.php +++ b/library/Zend/Service/WindowsAzure/Credentials/CredentialsAbstract.php @@ -180,7 +180,7 @@ protected function _prepareQueryStringForSigning($value) } // Return - if (count($returnValue) > 0) { + if ($returnValue !== []) { return '?' . implode('&', $returnValue); } else { return ''; diff --git a/library/Zend/Service/WindowsAzure/Credentials/SharedAccessSignature.php b/library/Zend/Service/WindowsAzure/Credentials/SharedAccessSignature.php index 17a444e6dd..8d647d493b 100644 --- a/library/Zend/Service/WindowsAzure/Credentials/SharedAccessSignature.php +++ b/library/Zend/Service/WindowsAzure/Credentials/SharedAccessSignature.php @@ -135,9 +135,8 @@ public function createSignature( $stringToSign[] = $identifier; $stringToSign = implode("\n", $stringToSign); - $signature = base64_encode(hash_hmac('sha256', $stringToSign, $this->_accountKey, true)); - return $signature; + return base64_encode(hash_hmac('sha256', $stringToSign, $this->_accountKey, true)); } /** @@ -178,9 +177,8 @@ public function createSignedQueryString( if ($queryString != '') { $queryString .= '&'; } - $queryString .= implode('&', $parts); - return $queryString; + return $queryString . implode('&', $parts); } /** @@ -249,7 +247,7 @@ public function signRequestUrl( ) { // Look for a matching permission foreach ($this->getPermissionSet() as $permittedUrl) { - if ($this->permissionMatchesRequest($permittedUrl, $requestUrl, $resourceType, $requiredPermission)) { + if ($this->permissionMatchesRequest($permittedUrl, $requestUrl, $resourceType, $requiredPermission) !== '' && $this->permissionMatchesRequest($permittedUrl, $requestUrl, $resourceType, $requiredPermission) !== '0') { // This matches, append signature data $parsedPermittedUrl = parse_url($permittedUrl); @@ -258,11 +256,9 @@ public function signRequestUrl( } else { $requestUrl .= '&'; } - - $requestUrl .= $parsedPermittedUrl['query']; // Return url - return $requestUrl; + return $requestUrl . $parsedPermittedUrl['query']; } } diff --git a/library/Zend/Service/WindowsAzure/Credentials/SharedKey.php b/library/Zend/Service/WindowsAzure/Credentials/SharedKey.php index f43987b921..ebec8a97b8 100644 --- a/library/Zend/Service/WindowsAzure/Credentials/SharedKey.php +++ b/library/Zend/Service/WindowsAzure/Credentials/SharedKey.php @@ -104,7 +104,7 @@ public function signRequestHeaders( if (!is_null($headers)) { foreach ($headers as $header => $value) { if (is_bool($value)) { - $value = $value === true ? 'True' : 'False'; + $value = $value ? 'True' : 'False'; } $headers[$header] = $value; @@ -155,7 +155,7 @@ public function signRequestHeaders( $stringToSign[] = $this->_issetOr($headers, 'If-Unmodified-Since', ''); // If-Unmodified-Since $stringToSign[] = $this->_issetOr($headers, 'Range', ''); // Range - if (!$forTableStorage && count($canonicalizedHeaders) > 0) { + if (!$forTableStorage && $canonicalizedHeaders !== []) { $stringToSign[] = implode("\n", $canonicalizedHeaders); // Canonicalized headers } diff --git a/library/Zend/Service/WindowsAzure/Diagnostics/ConfigurationInstance.php b/library/Zend/Service/WindowsAzure/Diagnostics/ConfigurationInstance.php index 8056cd3c30..c48ffb2f00 100644 --- a/library/Zend/Service/WindowsAzure/Diagnostics/ConfigurationInstance.php +++ b/library/Zend/Service/WindowsAzure/Diagnostics/ConfigurationInstance.php @@ -101,11 +101,7 @@ public function loadXml($configurationXml) if ($configurationXml->DataSources->WindowsEventLog->Subscriptions && $configurationXml->DataSources->WindowsEventLog->Subscriptions->string) { $subscriptions = $configurationXml->DataSources->WindowsEventLog->Subscriptions; - if (count($subscriptions->string) > 1) { - $subscriptions = $subscriptions->string; - } else { - $subscriptions = array($subscriptions->string); - } + $subscriptions = count($subscriptions->string) > 1 ? $subscriptions->string : array($subscriptions->string); foreach ($subscriptions as $subscription) { $this->DataSources->WindowsEventLog->addSubscription((string)$subscription); } diff --git a/library/Zend/Service/WindowsAzure/Management/Client.php b/library/Zend/Service/WindowsAzure/Management/Client.php index 69bd9e9626..983ebf3b6c 100644 --- a/library/Zend/Service/WindowsAzure/Management/Client.php +++ b/library/Zend/Service/WindowsAzure/Management/Client.php @@ -625,18 +625,14 @@ public function listStorageAccounts() if (!$result->StorageService) { return array(); } - if (count($result->StorageService) > 1) { - $xmlServices = $result->StorageService; - } else { - $xmlServices = array($result->StorageService); - } + $xmlServices = count($result->StorageService) > 1 ? $result->StorageService : array($result->StorageService); $services = array(); if (!is_null($xmlServices)) { - for ($i = 0; $i < count($xmlServices); $i++) { + foreach ($xmlServices as $i => $xmlService) { $services[] = new Zend_Service_WindowsAzure_Management_StorageServiceInstance( - (string)$xmlServices[$i]->Url, - (string)$xmlServices[$i]->ServiceName + (string)$xmlService->Url, + (string)$xmlService->ServiceName ); } } @@ -782,19 +778,15 @@ public function listHostedServices() if (!$result->HostedService) { return array(); } - if (count($result->HostedService) > 1) { - $xmlServices = $result->HostedService; - } else { - $xmlServices = array($result->HostedService); - } + $xmlServices = count($result->HostedService) > 1 ? $result->HostedService : array($result->HostedService); $services = array(); if (!is_null($xmlServices)) { - for ($i = 0; $i < count($xmlServices); $i++) { + foreach ($xmlServices as $i => $xmlService) { $services[] = new Zend_Service_WindowsAzure_Management_HostedServiceInstance( - (string)$xmlServices[$i]->Url, - (string)$xmlServices[$i]->ServiceName + (string)$xmlService->Url, + (string)$xmlService->ServiceName ); } } @@ -1309,11 +1301,11 @@ protected function _convertXmlElementToDeploymentInstance($xmlService) $roleInstances = array(); if (!is_null($xmlRoleInstances)) { - for ($i = 0; $i < count($xmlRoleInstances); $i++) { + foreach ($xmlRoleInstances as $i => $xmlRoleInstance) { $roleInstances[] = array( - 'rolename' => (string)$xmlRoleInstances[$i]->RoleName, - 'instancename' => (string)$xmlRoleInstances[$i]->InstanceName, - 'instancestatus' => (string)$xmlRoleInstances[$i]->InstanceStatus + 'rolename' => (string)$xmlRoleInstance->RoleName, + 'instancename' => (string)$xmlRoleInstance->InstanceName, + 'instancestatus' => (string)$xmlRoleInstance->InstanceStatus ); } } @@ -1330,10 +1322,10 @@ protected function _convertXmlElementToDeploymentInstance($xmlService) $roles = array(); if (!is_null($xmlRoles)) { - for ($i = 0; $i < count($xmlRoles); $i++) { + foreach ($xmlRoles as $i => $xmlRole) { $roles[] = array( - 'rolename' => (string)$xmlRoles[$i]->RoleName, - 'osversion' => (!is_null($xmlRoles[$i]->OsVersion) ? (string)$xmlRoles[$i]->OsVersion : (string)$xmlRoles[$i]->OperatingSystemVersion) + 'rolename' => (string)$xmlRole->RoleName, + 'osversion' => (is_null($xmlRole->OsVersion) ? (string)$xmlRole->OperatingSystemVersion : (string)$xmlRole->OsVersion) ); } } @@ -1435,21 +1427,17 @@ protected function _updateInstanceCountInConfiguration($roleName, $instanceCount // http://www.php.net/manual/en/simplexmlelement.xpath.php#97818 $namespaces = $xml->getDocNamespaces(); - $xml->registerXPathNamespace('__empty_ns', $namespaces['']); - - for ($i = 0; $i < count($roleName); $i++) { - $elements = $xml->xpath('//__empty_ns:Role[@name="' . $roleName[$i] . '"]/__empty_ns:Instances'); - - if (count($elements) == 1) { - $element = $elements[0]; - $element['count'] = $instanceCount[$i]; - } - } - - $configuration = $xml->asXML(); + $xml->registerXPathNamespace('__empty_ns', $namespaces['']); + foreach ($roleName as $i => $singleRoleName) { + $elements = $xml->xpath('//__empty_ns:Role[@name="' . $singleRoleName . '"]/__empty_ns:Instances'); + if (count($elements) == 1) { + $element = $elements[0]; + $element['count'] = $instanceCount[$i]; + } + } //$configuration = preg_replace('/(<\?xml[^?]+?)utf-8/i', '$1utf-16', $configuration); - return $configuration; + return $xml->asXML(); } /** @@ -1669,7 +1657,7 @@ protected function _upgradeDeployment($operationUrl, $label, $packageUrl, $confi $response = $this->_performRequest($operationUrl . '/', '?comp=upgrade', Zend_Http_Client::POST, array('Content-Type' => 'application/xml; charset=utf-8'), - '' . ucfirst($mode) . '' . $packageUrl . '' . base64_encode($conformingConfiguration) . '' . (!is_null($roleToUpgrade) ? '' . $roleToUpgrade . '' : '') . ''); + '' . ucfirst($mode) . '' . $packageUrl . '' . base64_encode($conformingConfiguration) . '' . (is_null($roleToUpgrade) ? '' : '' . $roleToUpgrade . '') . ''); if (!$response->isSuccessful()) { require_once 'Zend/Service/WindowsAzure/Management/Exception.php'; @@ -1900,21 +1888,17 @@ public function listCertificates($serviceName) if (!$result->Certificate) { return array(); } - if (count($result->Certificate) > 1) { - $xmlServices = $result->Certificate; - } else { - $xmlServices = array($result->Certificate); - } + $xmlServices = count($result->Certificate) > 1 ? $result->Certificate : array($result->Certificate); $services = array(); if (!is_null($xmlServices)) { - for ($i = 0; $i < count($xmlServices); $i++) { + foreach ($xmlServices as $i => $xmlService) { $services[] = new Zend_Service_WindowsAzure_Management_CertificateInstance( - (string)$xmlServices[$i]->CertificateUrl, - (string)$xmlServices[$i]->Thumbprint, - (string)$xmlServices[$i]->ThumbprintAlgorithm, - (string)$xmlServices[$i]->Data + (string)$xmlService->CertificateUrl, + (string)$xmlService->Thumbprint, + (string)$xmlService->ThumbprintAlgorithm, + (string)$xmlService->Data ); } } @@ -2060,21 +2044,17 @@ public function listAffinityGroups() if (!$result->AffinityGroup) { return array(); } - if (count($result->AffinityGroup) > 1) { - $xmlServices = $result->AffinityGroup; - } else { - $xmlServices = array($result->AffinityGroup); - } + $xmlServices = count($result->AffinityGroup) > 1 ? $result->AffinityGroup : array($result->AffinityGroup); $services = array(); if (!is_null($xmlServices)) { - for ($i = 0; $i < count($xmlServices); $i++) { + foreach ($xmlServices as $i => $xmlService) { $services[] = new Zend_Service_WindowsAzure_Management_AffinityGroupInstance( - (string)$xmlServices[$i]->Name, - (string)$xmlServices[$i]->Label, - (string)$xmlServices[$i]->Description, - (string)$xmlServices[$i]->Location + (string)$xmlService->Name, + (string)$xmlService->Label, + (string)$xmlService->Description, + (string)$xmlService->Location ); } } @@ -2221,10 +2201,10 @@ public function getAffinityGroupProperties($affinityGroupName) $services = array(); if (!is_null($xmlService)) { - for ($i = 0; $i < count($xmlService); $i++) { + foreach ($xmlService as $i => $singleXmlService) { $services[] = array( - 'url' => (string)$xmlService[$i]->Url, - 'name' => (string)$xmlService[$i]->ServiceName + 'url' => (string)$singleXmlService->Url, + 'name' => (string)$singleXmlService->ServiceName ); } } @@ -2239,10 +2219,10 @@ public function getAffinityGroupProperties($affinityGroupName) $services = array(); if (!is_null($xmlService)) { - for ($i = 0; $i < count($xmlService); $i++) { + foreach ($xmlService as $i => $singleXmlService) { $services[] = array( - 'url' => (string)$xmlService[$i]->Url, - 'name' => (string)$xmlService[$i]->ServiceName + 'url' => (string)$singleXmlService->Url, + 'name' => (string)$singleXmlService->ServiceName ); } } @@ -2272,18 +2252,14 @@ public function listLocations() if (!$result->Location) { return array(); } - if (count($result->Location) > 1) { - $xmlServices = $result->Location; - } else { - $xmlServices = array($result->Location); - } + $xmlServices = count($result->Location) > 1 ? $result->Location : array($result->Location); $services = array(); if (!is_null($xmlServices)) { - for ($i = 0; $i < count($xmlServices); $i++) { + foreach ($xmlServices as $i => $xmlService) { $services[] = new Zend_Service_WindowsAzure_Management_LocationInstance( - (string)$xmlServices[$i]->Name + (string)$xmlService->Name ); } } @@ -2316,23 +2292,19 @@ public function listOperatingSystems() if (!$result->OperatingSystem) { return array(); } - if (count($result->OperatingSystem) > 1) { - $xmlServices = $result->OperatingSystem; - } else { - $xmlServices = array($result->OperatingSystem); - } + $xmlServices = count($result->OperatingSystem) > 1 ? $result->OperatingSystem : array($result->OperatingSystem); $services = array(); if (!is_null($xmlServices)) { - for ($i = 0; $i < count($xmlServices); $i++) { + foreach ($xmlServices as $i => $xmlService) { $services[] = new Zend_Service_WindowsAzure_Management_OperatingSystemInstance( - (string)$xmlServices[$i]->Version, - (string)$xmlServices[$i]->Label, - ((string)$xmlServices[$i]->IsDefault == 'true'), - ((string)$xmlServices[$i]->IsActive == 'true'), - (string)$xmlServices[$i]->Family, - (string)$xmlServices[$i]->FamilyLabel + (string)$xmlService->Version, + (string)$xmlService->Label, + ((string)$xmlService->IsDefault == 'true'), + ((string)$xmlService->IsActive == 'true'), + (string)$xmlService->Family, + (string)$xmlService->FamilyLabel ); } } @@ -2374,29 +2346,27 @@ public function listOperatingSystemFamilies() $services = array(); if (!is_null($xmlServices)) { - for ($i = 0; $i < count($xmlServices); $i++) { + foreach ($xmlServices as $i => $xmlService) { $services[] = new Zend_Service_WindowsAzure_Management_OperatingSystemFamilyInstance( - (string)$xmlServices[$i]->Name, - (string)$xmlServices[$i]->Label + (string)$xmlService->Name, + (string)$xmlService->Label ); - - if (count($xmlServices[$i]->OperatingSystems->OperatingSystem) > 1) { - $xmlOperatingSystems = $xmlServices[$i]->OperatingSystems->OperatingSystem; + if (count($xmlService->OperatingSystems->OperatingSystem) > 1) { + $xmlOperatingSystems = $xmlService->OperatingSystems->OperatingSystem; } else { - $xmlOperatingSystems = array($xmlServices[$i]->OperatingSystems->OperatingSystem); + $xmlOperatingSystems = array($xmlService->OperatingSystems->OperatingSystem); } - $operatingSystems = array(); if (!is_null($xmlOperatingSystems)) { require_once 'Zend/Service/WindowsAzure/Management/OperatingSystemInstance.php'; - for ($i = 0; $i < count($xmlOperatingSystems); $i++) { + foreach ($xmlOperatingSystems as $i => $xmlOperatingSystem) { $operatingSystems[] = new Zend_Service_WindowsAzure_Management_OperatingSystemInstance( - (string)$xmlOperatingSystems[$i]->Version, - (string)$xmlOperatingSystems[$i]->Label, - ((string)$xmlOperatingSystems[$i]->IsDefault == 'true'), - ((string)$xmlOperatingSystems[$i]->IsActive == 'true'), - (string)$xmlServices[$i]->Name, - (string)$xmlServices[$i]->Label + (string)$xmlOperatingSystem->Version, + (string)$xmlOperatingSystem->Label, + ((string)$xmlOperatingSystem->IsDefault == 'true'), + ((string)$xmlOperatingSystem->IsActive == 'true'), + (string)$xmlService->Name, + (string)$xmlService->Label ); } } @@ -2419,8 +2389,7 @@ public function listOperatingSystemFamilies() public function _cleanConfiguration($configuration) { $configuration = str_replace('?_retryCount; $retriesLeft >= 0; --$retriesLeft) { try { - $returnValue = call_user_func_array($function, $parameters); - return $returnValue; + return call_user_func_array($function, $parameters); } catch (Exception $ex) { if ($retriesLeft == 1) { require_once 'Zend/Service/WindowsAzure/RetryPolicy/Exception.php'; - throw new Zend_Service_WindowsAzure_RetryPolicy_Exception("Exceeded retry count of " . $this->_retryCount . ". " . $ex->getMessage()); + throw new Zend_Service_WindowsAzure_RetryPolicy_Exception("Exceeded retry count of " . $this->_retryCount . ". " . $ex->getMessage(), $ex->getCode(), $ex); } usleep($this->_retryInterval * 1000); diff --git a/library/Zend/Service/WindowsAzure/SessionHandler.php b/library/Zend/Service/WindowsAzure/SessionHandler.php index d2044d5748..82f9349f63 100644 --- a/library/Zend/Service/WindowsAzure/SessionHandler.php +++ b/library/Zend/Service/WindowsAzure/SessionHandler.php @@ -79,7 +79,7 @@ class Zend_Service_WindowsAzure_SessionHandler public function __construct(Zend_Service_WindowsAzure_Storage $storage, $sessionContainer = 'phpsessions', $sessionContainerPartition = 'sessions') { // Validate $storage - if (!($storage instanceof Zend_Service_WindowsAzure_Storage_Table || $storage instanceof Zend_Service_WindowsAzure_Storage_Blob)) { + if (!$storage instanceof Zend_Service_WindowsAzure_Storage_Table && !$storage instanceof Zend_Service_WindowsAzure_Storage_Blob) { require_once 'Zend/Service/WindowsAzure/Exception.php'; throw new Zend_Service_WindowsAzure_Exception('Invalid storage back-end given. Storage back-end should be of type Zend_Service_WindowsAzure_Storage_Table or Zend_Service_WindowsAzure_Storage_Blob.'); } @@ -128,10 +128,10 @@ public function open() { // Make sure storage container exists if ($this->_storageType == self::STORAGE_TYPE_TABLE) { - $this->_storage->createTableIfNotExists($this->_sessionContainer); - } else if ($this->_storageType == self::STORAGE_TYPE_BLOB) { - $this->_storage->createContainerIfNotExists($this->_sessionContainer); - } + $this->_storage->createTableIfNotExists($this->_sessionContainer); + } elseif ($this->_storageType == self::STORAGE_TYPE_BLOB) { + $this->_storage->createContainerIfNotExists($this->_sessionContainer); + } // Ok! return true; @@ -157,8 +157,8 @@ public function read($id) { // Read data if ($this->_storageType == self::STORAGE_TYPE_TABLE) { - // In table storage - try + // In table storage + try { $sessionRecord = $this->_storage->retrieveEntityById( $this->_sessionContainer, @@ -171,9 +171,9 @@ public function read($id) { return ''; } - } else if ($this->_storageType == self::STORAGE_TYPE_BLOB) { - // In blob storage - try + } elseif ($this->_storageType == self::STORAGE_TYPE_BLOB) { + // In blob storage + try { $data = $this->_storage->getBlobData( $this->_sessionContainer, @@ -185,7 +185,7 @@ public function read($id) { return false; } - } + } } /** @@ -205,14 +205,12 @@ public function write($id, $serializedData) // Store data if ($this->_storageType == self::STORAGE_TYPE_TABLE) { - // In table storage - $sessionRecord = new Zend_Service_WindowsAzure_Storage_DynamicTableEntity($this->_sessionContainerPartition, $id); - $sessionRecord->sessionExpires = time(); - $sessionRecord->serializedData = $serializedData; - - $sessionRecord->setAzurePropertyType('sessionExpires', 'Edm.Int32'); - - try + // In table storage + $sessionRecord = new Zend_Service_WindowsAzure_Storage_DynamicTableEntity($this->_sessionContainerPartition, $id); + $sessionRecord->sessionExpires = time(); + $sessionRecord->serializedData = $serializedData; + $sessionRecord->setAzurePropertyType('sessionExpires', 'Edm.Int32'); + try { $this->_storage->updateEntity($this->_sessionContainer, $sessionRecord); } @@ -220,15 +218,15 @@ public function write($id, $serializedData) { $this->_storage->insertEntity($this->_sessionContainer, $sessionRecord); } - } else if ($this->_storageType == self::STORAGE_TYPE_BLOB) { - // In blob storage - $this->_storage->putBlobData( - $this->_sessionContainer, - $this->_sessionContainerPartition . '/' . $id, - $serializedData, - array('sessionexpires' => time()) - ); - } + } elseif ($this->_storageType == self::STORAGE_TYPE_BLOB) { + // In blob storage + $this->_storage->putBlobData( + $this->_sessionContainer, + $this->_sessionContainerPartition . '/' . $id, + $serializedData, + array('sessionexpires' => time()) + ); + } } /** @@ -241,8 +239,8 @@ public function destroy($id) { // Destroy data if ($this->_storageType == self::STORAGE_TYPE_TABLE) { - // In table storage - try + // In table storage + try { $sessionRecord = $this->_storage->retrieveEntityById( $this->_sessionContainer, @@ -257,9 +255,9 @@ public function destroy($id) { return false; } - } else if ($this->_storageType == self::STORAGE_TYPE_BLOB) { - // In blob storage - try + } elseif ($this->_storageType == self::STORAGE_TYPE_BLOB) { + // In blob storage + try { $this->_storage->deleteBlob( $this->_sessionContainer, @@ -272,7 +270,7 @@ public function destroy($id) { return false; } - } + } } /** @@ -288,8 +286,8 @@ public function destroy($id) public function gc($lifeTime) { if ($this->_storageType == self::STORAGE_TYPE_TABLE) { - // In table storage - try + // In table storage + try { $result = $this->_storage->retrieveEntities($this->_sessionContainer, 'PartitionKey eq \'' . $this->_sessionContainerPartition . '\' and sessionExpires lt ' . (time() - $lifeTime)); foreach ($result as $sessionRecord) @@ -302,9 +300,9 @@ public function gc($lifeTime) { return false; } - } else if ($this->_storageType == self::STORAGE_TYPE_BLOB) { - // In blob storage - try + } elseif ($this->_storageType == self::STORAGE_TYPE_BLOB) { + // In blob storage + try { $result = $this->_storage->listBlobs($this->_sessionContainer, $this->_sessionContainerPartition, '', null, null, 'metadata'); foreach ($result as $sessionRecord) @@ -319,6 +317,6 @@ public function gc($lifeTime) { return false; } - } + } } } diff --git a/library/Zend/Service/WindowsAzure/Storage.php b/library/Zend/Service/WindowsAzure/Storage.php index 2e8111913f..c1f949cfec 100644 --- a/library/Zend/Service/WindowsAzure/Storage.php +++ b/library/Zend/Service/WindowsAzure/Storage.php @@ -494,7 +494,7 @@ protected function _parseMetadataHeaders($headers = array()) protected function _parseMetadataElement($element = null) { // Metadata present? - if (!is_null($element) && isset($element->Metadata) && !is_null($element->Metadata)) { + if (!is_null($element) && (property_exists($element, 'Metadata') && $element->Metadata !== null) && !is_null($element->Metadata)) { return get_object_vars($element->Metadata); } @@ -543,12 +543,7 @@ public static function isValidMetadataName($metadataName = '') if (preg_match("/^[a-zA-Z0-9_@][a-zA-Z0-9_]*$/", $metadataName) === 0) { return false; } - - if ($metadataName == '') { - return false; - } - - return true; + return !($metadataName == ''); } /** diff --git a/library/Zend/Service/WindowsAzure/Storage/BatchStorageAbstract.php b/library/Zend/Service/WindowsAzure/Storage/BatchStorageAbstract.php index d1af80c9bb..7e579228a8 100644 --- a/library/Zend/Service/WindowsAzure/Storage/BatchStorageAbstract.php +++ b/library/Zend/Service/WindowsAzure/Storage/BatchStorageAbstract.php @@ -133,7 +133,9 @@ public function performBatch($operations = array(), $forTableStorage = false, $i $operation = $operations[0]; $rawData .= '--' . $batchBoundary . "\n"; $rawData .= 'Content-Type: application/http' . "\n"; - $rawData .= 'Content-Transfer-Encoding: binary' . "\n\n"; + $rawData .= 'Content-Transfer-Encoding: binary + +'; $rawData .= $operation; $rawData .= '--' . $batchBoundary . '--'; } else { @@ -145,7 +147,9 @@ public function performBatch($operations = array(), $forTableStorage = false, $i { $rawData .= '--' . $changesetBoundary . "\n"; $rawData .= 'Content-Type: application/http' . "\n"; - $rawData .= 'Content-Transfer-Encoding: binary' . "\n\n"; + $rawData .= 'Content-Transfer-Encoding: binary + +'; $rawData .= $operation; } $rawData .= '--' . $changesetBoundary . '--' . "\n"; diff --git a/library/Zend/Service/WindowsAzure/Storage/Blob.php b/library/Zend/Service/WindowsAzure/Storage/Blob.php index e16b81982b..b9b4de8b40 100644 --- a/library/Zend/Service/WindowsAzure/Storage/Blob.php +++ b/library/Zend/Service/WindowsAzure/Storage/Blob.php @@ -305,11 +305,7 @@ public function getContainerAcl($containerName = '', $signedIdentifiers = false) $entries = null; if ($result->SignedIdentifier) { - if (count($result->SignedIdentifier) > 1) { - $entries = $result->SignedIdentifier; - } else { - $entries = array($result->SignedIdentifier); - } + $entries = count($result->SignedIdentifier) > 1 ? $result->SignedIdentifier : array($result->SignedIdentifier); } require_once 'Zend/Service/WindowsAzure/Storage/SignedIdentifier.php'; @@ -362,24 +358,31 @@ public function setContainerAcl($containerName = '', $acl = self::ACL_PRIVATE, $ // Policies $policies = null; - if (is_array($signedIdentifiers) && count($signedIdentifiers) > 0) { + if (is_array($signedIdentifiers) && $signedIdentifiers !== []) { $policies = ''; - $policies .= '' . "\r\n"; - $policies .= '' . "\r\n"; + $policies .= ' +'; + $policies .= ' +'; foreach ($signedIdentifiers as $signedIdentifier) { - $policies .= ' ' . "\r\n"; + $policies .= ' +'; $policies .= ' ' . $signedIdentifier->Id . '' . "\r\n"; - $policies .= ' ' . "\r\n"; + $policies .= ' +'; if ($signedIdentifier->Start != '') $policies .= ' ' . $signedIdentifier->Start . '' . "\r\n"; if ($signedIdentifier->Expiry != '') $policies .= ' ' . $signedIdentifier->Expiry . '' . "\r\n"; if ($signedIdentifier->Permissions != '') $policies .= ' ' . $signedIdentifier->Permissions . '' . "\r\n"; - $policies .= ' ' . "\r\n"; - $policies .= ' ' . "\r\n"; + $policies .= ' +'; + $policies .= ' +'; } - $policies .= '' . "\r\n"; + $policies .= ' +'; } // Perform request @@ -562,21 +565,18 @@ public function listContainers($prefix = null, $maxResults = null, $marker = nul $containers = array(); if (!is_null($xmlContainers)) { - for ($i = 0; $i < count($xmlContainers); $i++) { - + foreach ($xmlContainers as $i => $xmlContainer) { $containers[] = new Zend_Service_WindowsAzure_Storage_BlobContainer( - (string)$xmlContainers[$i]->Name, - (string)$xmlContainers[$i]->Etag, - (string)$xmlContainers[$i]->LastModified, - $this->_parseMetadataElement($xmlContainers[$i]) + (string)$xmlContainer->Name, + (string)$xmlContainer->Etag, + (string)$xmlContainer->LastModified, + $this->_parseMetadataElement($xmlContainer) ); } } - $currentResultCount = $currentResultCount + count($containers); - if (!is_null($maxResults) && $currentResultCount < $maxResults) { - if (!is_null($xmlMarker) && $xmlMarker != '') { - $containers = array_merge($containers, $this->listContainers($prefix, $maxResults, $xmlMarker, $include, $currentResultCount)); - } + $currentResultCount += count($containers); + if (!is_null($maxResults) && $currentResultCount < $maxResults && (!is_null($xmlMarker) && $xmlMarker != '')) { + $containers = array_merge($containers, $this->listContainers($prefix, $maxResults, $xmlMarker, $include, $currentResultCount)); } if (!is_null($maxResults) && count($containers) > $maxResults) { $containers = array_slice($containers, 0, $maxResults); @@ -1215,19 +1215,15 @@ public function getPageRegions($containerName = '', $blobName = '', $startByteOf if ($response->isSuccessful()) { $result = $this->_parseResponse($response); $xmlRanges = null; - if (count($result->PageRange) > 1) { - $xmlRanges = $result->PageRange; - } else { - $xmlRanges = array($result->PageRange); - } + $xmlRanges = count($result->PageRange) > 1 ? $result->PageRange : array($result->PageRange); $ranges = array(); - for ($i = 0; $i < count($xmlRanges); $i++) { + foreach ($xmlRanges as $i => $xmlRange) { $ranges[] = new Zend_Service_WindowsAzure_Storage_PageRegionInstance( - (int)$xmlRanges[$i]->Start, - (int)$xmlRanges[$i]->End + (int)$xmlRange->Start, + (int)$xmlRange->End ); } @@ -1887,16 +1883,15 @@ public function listBlobs($containerName = '', $prefix = '', $delimiter = '', $m $xmlBlobs = $this->_parseResponse($response)->Blobs->Blob; if (!is_null($xmlBlobs)) { - for ($i = 0; $i < count($xmlBlobs); $i++) { - $properties = (array)$xmlBlobs[$i]->Properties; - + foreach ($xmlBlobs as $i => $xmlBlob) { + $properties = (array)$xmlBlob->Properties; $blobs[] = new Zend_Service_WindowsAzure_Storage_BlobInstance( $containerName, - (string)$xmlBlobs[$i]->Name, - (string)$xmlBlobs[$i]->Snapshot, + (string)$xmlBlob->Name, + (string)$xmlBlob->Snapshot, (string)$properties['Etag'], (string)$properties['Last-Modified'], - (string)$xmlBlobs[$i]->Url, + (string)$xmlBlob->Url, (string)$properties['Content-Length'], (string)$properties['Content-Type'], (string)$properties['Content-Encoding'], @@ -1905,7 +1900,7 @@ public function listBlobs($containerName = '', $prefix = '', $delimiter = '', $m (string)$properties['BlobType'], (string)$properties['LeaseStatus'], false, - $this->_parseMetadataElement($xmlBlobs[$i]) + $this->_parseMetadataElement($xmlBlob) ); } } @@ -1915,10 +1910,10 @@ public function listBlobs($containerName = '', $prefix = '', $delimiter = '', $m if (!is_null($xmlBlobs)) { - for ($i = 0; $i < count($xmlBlobs); $i++) { + foreach ($xmlBlobs as $i => $xmlBlob) { $blobs[] = new Zend_Service_WindowsAzure_Storage_BlobInstance( $containerName, - (string)$xmlBlobs[$i]->Name, + (string)$xmlBlob->Name, null, '', '', @@ -1931,18 +1926,16 @@ public function listBlobs($containerName = '', $prefix = '', $delimiter = '', $m '', '', true, - $this->_parseMetadataElement($xmlBlobs[$i]) + $this->_parseMetadataElement($xmlBlob) ); } } // More blobs? $xmlMarker = (string)$this->_parseResponse($response)->NextMarker; - $currentResultCount = $currentResultCount + count($blobs); - if (!is_null($maxResults) && $currentResultCount < $maxResults) { - if (!is_null($xmlMarker) && $xmlMarker != '') { - $blobs = array_merge($blobs, $this->listBlobs($containerName, $prefix, $delimiter, $maxResults, $marker, $include, $currentResultCount)); - } + $currentResultCount += count($blobs); + if (!is_null($maxResults) && $currentResultCount < $maxResults && (!is_null($xmlMarker) && $xmlMarker != '')) { + $blobs = array_merge($blobs, $this->listBlobs($containerName, $prefix, $delimiter, $maxResults, $marker, $include, $currentResultCount)); } if (!is_null($maxResults) && count($blobs) > $maxResults) { $blobs = array_slice($blobs, 0, $maxResults); @@ -2092,19 +2085,14 @@ public static function isValidContainerName($containerName = '') return false; } - if (strtolower($containerName) != $containerName) { + if (strtolower($containerName) !== $containerName) { return false; } if (strlen($containerName) < 3 || strlen($containerName) > 63) { return false; } - - if (substr($containerName, -1) == '-') { - return false; - } - - return true; + return !(substr($containerName, -1) == '-'); } /** diff --git a/library/Zend/Service/WindowsAzure/Storage/Blob/Stream.php b/library/Zend/Service/WindowsAzure/Storage/Blob/Stream.php index 7083ef08db..f1de55461b 100644 --- a/library/Zend/Service/WindowsAzure/Storage/Blob/Stream.php +++ b/library/Zend/Service/WindowsAzure/Storage/Blob/Stream.php @@ -81,7 +81,7 @@ protected function _getStorageClient($path = '') { if (is_null($this->_storageClient)) { $url = explode(':', $path); - if (!$url) { + if ($url === []) { throw new Zend_Service_WindowsAzure_Exception('Could not parse path "' . $path . '".'); } @@ -103,7 +103,7 @@ protected function _getStorageClient($path = '') protected function _getContainerName($path) { $url = parse_url($path); - if ($url['host']) { + if ($url['host'] !== '' && $url['host'] !== '0') { return $url['host']; } @@ -119,7 +119,7 @@ protected function _getContainerName($path) protected function _getFileName($path) { $url = parse_url($path); - if ($url['host']) { + if ($url['host'] !== '' && $url['host'] !== '0') { $fileName = isset($url['path']) ? $url['path'] : $url['host']; if (strpos($fileName, '/') === 0) { $fileName = substr($fileName, 1); @@ -152,11 +152,7 @@ public function stream_open($path, $mode, $options, &$opened_path) fclose($fh); // Write mode? - if (strpbrk($mode, 'wax+')) { - $this->_writeMode = true; - } else { - $this->_writeMode = false; - } + $this->_writeMode = (bool) strpbrk($mode, 'wax+'); // If read/append, fetch the file if (!$this->_writeMode || strpbrk($mode, 'ra+')) { @@ -366,11 +362,11 @@ public function unlink($path) */ public function rename($path_from, $path_to) { - if ($this->_getContainerName($path_from) != $this->_getContainerName($path_to)) { + if ($this->_getContainerName($path_from) !== $this->_getContainerName($path_to)) { throw new Zend_Service_WindowsAzure_Exception('Container name can not be changed.'); } - if ($this->_getFileName($path_from) == $this->_getContainerName($path_to)) { + if ($this->_getFileName($path_from) === $this->_getContainerName($path_to)) { return true; } @@ -448,7 +444,7 @@ public function url_stat($path, $flags) */ public function mkdir($path, $mode, $options) { - if ($this->_getContainerName($path) == $this->_getFileName($path)) { + if ($this->_getContainerName($path) === $this->_getFileName($path)) { // Create container try { $this->_getStorageClient($path)->createContainer( @@ -472,7 +468,7 @@ public function mkdir($path, $mode, $options) */ public function rmdir($path, $options) { - if ($this->_getContainerName($path) == $this->_getFileName($path)) { + if ($this->_getContainerName($path) === $this->_getFileName($path)) { // Clear the stat cache so that affected paths are refreshed. clearstatcache(); diff --git a/library/Zend/Service/WindowsAzure/Storage/DynamicTableEntity.php b/library/Zend/Service/WindowsAzure/Storage/DynamicTableEntity.php index 7a2f49d34b..5ea3429892 100644 --- a/library/Zend/Service/WindowsAzure/Storage/DynamicTableEntity.php +++ b/library/Zend/Service/WindowsAzure/Storage/DynamicTableEntity.php @@ -72,9 +72,9 @@ public function setAzureProperty($name, $value = '', $type = null) { if (strtolower($name) == 'partitionkey') { $this->setPartitionKey($value); - } else if (strtolower($name) == 'rowkey') { + } elseif (strtolower($name) == 'rowkey') { $this->setRowKey($value); - } else if (strtolower($name) == 'etag') { + } elseif (strtolower($name) == 'etag') { $this->setEtag($value); } else { if (!array_key_exists(strtolower($name), $this->_dynamicProperties)) { @@ -83,11 +83,11 @@ public function setAzureProperty($name, $value = '', $type = null) $type = 'Edm.String'; if (is_int($value)) { $type = 'Edm.Int32'; - } else if (is_float($value)) { + } elseif (is_float($value)) { $type = 'Edm.Double'; - } else if (is_bool($value)) { + } elseif (is_bool($value)) { $type = 'Edm.Boolean'; - } else if ($value instanceof DateTime || $this->_convertToDateTime($value) !== false) { + } elseif ($value instanceof DateTime || $this->_convertToDateTime($value) !== false) { if (!$value instanceof DateTime) { $value = $this->_convertToDateTime($value); } @@ -109,18 +109,16 @@ public function setAzureProperty($name, $value = '', $type = null) // Try to convert the type if ($type == 'Edm.Int32' || $type == 'Edm.Int64') { - $value = intval($value); - } else if ($type == 'Edm.Double') { - $value = floatval($value); - } else if ($type == 'Edm.Boolean') { - if (!is_bool($value)) { - $value = strtolower($value) == 'true'; - } - } else if ($type == 'Edm.DateTime') { - if (!$value instanceof DateTime) { - $value = $this->_convertToDateTime($value); - } - } + $value = (int) $value; + } elseif ($type == 'Edm.Double') { + $value = floatval($value); + } elseif ($type == 'Edm.Boolean') { + if (!is_bool($value)) { + $value = strtolower($value) == 'true'; + } + } elseif ($type == 'Edm.DateTime' && !$value instanceof DateTime) { + $value = $this->_convertToDateTime($value); + } } // Set value diff --git a/library/Zend/Service/WindowsAzure/Storage/Queue.php b/library/Zend/Service/WindowsAzure/Storage/Queue.php index 8a461761cf..b4ba79d5eb 100644 --- a/library/Zend/Service/WindowsAzure/Storage/Queue.php +++ b/library/Zend/Service/WindowsAzure/Storage/Queue.php @@ -179,7 +179,7 @@ public function getQueue($queueName = '') $queueName, $metadata ); - $queue->ApproximateMessageCount = intval($response->getHeader('x-ms-approximate-message-count')); + $queue->ApproximateMessageCount = (int) $response->getHeader('x-ms-approximate-message-count'); return $queue; } else { require_once 'Zend/Service/WindowsAzure/Exception.php'; @@ -307,18 +307,16 @@ public function listQueues($prefix = null, $maxResults = null, $marker = null, $ $queues = array(); if (!is_null($xmlQueues)) { - for ($i = 0; $i < count($xmlQueues); $i++) { + foreach ($xmlQueues as $i => $xmlQueue) { $queues[] = new Zend_Service_WindowsAzure_Storage_QueueInstance( - (string)$xmlQueues[$i]->Name, - $this->_parseMetadataElement($xmlQueues[$i]) + (string)$xmlQueue->Name, + $this->_parseMetadataElement($xmlQueue) ); } } - $currentResultCount = $currentResultCount + count($queues); - if (!is_null($maxResults) && $currentResultCount < $maxResults) { - if (!is_null($xmlMarker) && $xmlMarker != '') { - $queues = array_merge($queues, $this->listQueues($prefix, $maxResults, $xmlMarker, $include, $currentResultCount)); - } + $currentResultCount += count($queues); + if (!is_null($maxResults) && $currentResultCount < $maxResults && (!is_null($xmlMarker) && $xmlMarker != '')) { + $queues = array_merge($queues, $this->listQueues($prefix, $maxResults, $xmlMarker, $include, $currentResultCount)); } if (!is_null($maxResults) && count($queues) > $maxResults) { $queues = array_slice($queues, 0, $maxResults); @@ -404,7 +402,7 @@ public function getMessages($queueName = '', $numOfMessages = 1, $visibilityTime require_once 'Zend/Service/WindowsAzure/Exception.php'; throw new Zend_Service_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.'); } - if ($numOfMessages < 1 || $numOfMessages > 32 || intval($numOfMessages) != $numOfMessages) { + if ($numOfMessages < 1 || $numOfMessages > 32 || (int) $numOfMessages != $numOfMessages) { require_once 'Zend/Service/WindowsAzure/Exception.php'; throw new Zend_Service_WindowsAzure_Exception('Invalid number of messages to retrieve.'); } @@ -415,7 +413,7 @@ public function getMessages($queueName = '', $numOfMessages = 1, $visibilityTime // Build query string $queryString = array(); - if ($peek) { + if ($peek !== '' && $peek !== '0') { $queryString[] = 'peekonly=true'; } if ($numOfMessages > 1) { @@ -436,22 +434,18 @@ public function getMessages($queueName = '', $numOfMessages = 1, $visibilityTime } $xmlMessages = null; - if (count($result->QueueMessage) > 1) { - $xmlMessages = $result->QueueMessage; - } else { - $xmlMessages = array($result->QueueMessage); - } + $xmlMessages = count($result->QueueMessage) > 1 ? $result->QueueMessage : array($result->QueueMessage); $messages = array(); - for ($i = 0; $i < count($xmlMessages); $i++) { + foreach ($xmlMessages as $i => $xmlMessage) { $messages[] = new Zend_Service_WindowsAzure_Storage_QueueMessage( - (string)$xmlMessages[$i]->MessageId, - (string)$xmlMessages[$i]->InsertionTime, - (string)$xmlMessages[$i]->ExpirationTime, - ($peek ? '' : (string)$xmlMessages[$i]->PopReceipt), - ($peek ? '' : (string)$xmlMessages[$i]->TimeNextVisible), - (string)$xmlMessages[$i]->DequeueCount, - base64_decode((string)$xmlMessages[$i]->MessageText) + (string)$xmlMessage->MessageId, + (string)$xmlMessage->InsertionTime, + (string)$xmlMessage->ExpirationTime, + ($peek !== '' && $peek !== '0' ? '' : (string)$xmlMessage->PopReceipt), + ($peek !== '' && $peek !== '0' ? '' : (string)$xmlMessage->TimeNextVisible), + (string)$xmlMessage->DequeueCount, + base64_decode((string)$xmlMessage->MessageText) ); } @@ -484,7 +478,7 @@ public function peekMessages($queueName = '', $numOfMessages = 1) */ public function hasMessages($queueName = '') { - return count($this->peekMessages($queueName)) > 0; + return $this->peekMessages($queueName) !== []; } /** @@ -558,19 +552,14 @@ public static function isValidQueueName($queueName = '') return false; } - if (strtolower($queueName) != $queueName) { + if (strtolower($queueName) !== $queueName) { return false; } if (strlen($queueName) < 3 || strlen($queueName) > 63) { return false; } - - if (substr($queueName, -1) == '-') { - return false; - } - - return true; + return !(substr($queueName, -1) == '-'); } /** diff --git a/library/Zend/Service/WindowsAzure/Storage/Table.php b/library/Zend/Service/WindowsAzure/Storage/Table.php index 05e59ab731..ab2cd26abc 100644 --- a/library/Zend/Service/WindowsAzure/Storage/Table.php +++ b/library/Zend/Service/WindowsAzure/Storage/Table.php @@ -153,11 +153,7 @@ public function listTables($nextTableName = '') } $entries = null; - if (count($result->entry) > 1) { - $entries = $result->entry; - } else { - $entries = array($result->entry); - } + $entries = count($result->entry) > 1 ? $result->entry : array($result->entry); // Create return value $returnValue = array(); @@ -389,11 +385,7 @@ public function deleteEntity($tableName = '', Zend_Service_WindowsAzure_Storage_ $headers['Content-Type'] = 'application/atom+xml'; } $headers['Content-Length'] = 0; - if (!$verifyEtag) { - $headers['If-Match'] = '*'; - } else { - $headers['If-Match'] = $entity->getEtag(); - } + $headers['If-Match'] = $verifyEtag ? $entity->getEtag() : '*'; // Perform request $response = null; @@ -513,33 +505,27 @@ public function retrieveEntities($tableName = '', $filter = '', $entityClass = ' // Determine query if (is_string($tableName)) { - // Option 1: $tableName is a string - - // Append parentheses - if (strpos($tableName, '()') === false) { + // Option 1: $tableName is a string + // Append parentheses + if (strpos($tableName, '()') === false) { $tableName .= '()'; } - - // Build query - $query = array(); - - // Filter? - if ($filter !== '') { - $query[] = '$filter=' . Zend_Service_WindowsAzure_Storage_TableEntityQuery::encodeQuery($filter); - } - - // Build queryString - if (count($query) > 0) { + // Build query + $query = array(); + // Filter? + if ($filter !== '') { + $query[] = '$filter=' . Zend_Service_WindowsAzure_Storage_TableEntityQuery::encodeQuery($filter); + } + // Build queryString + if (count($query) > 0) { $queryString = '?' . implode('&', $query); } - } else if (get_class($tableName) == 'Zend_Service_WindowsAzure_Storage_TableEntityQuery') { - // Option 2: $tableName is a Zend_Service_WindowsAzure_Storage_TableEntityQuery instance - - // Build queryString - $queryString = $tableName->assembleQueryString(true); - - // Change $tableName - $tableName = $tableName->assembleFrom(true); + } elseif (get_class($tableName) == 'Zend_Service_WindowsAzure_Storage_TableEntityQuery') { + // Option 2: $tableName is a Zend_Service_WindowsAzure_Storage_TableEntityQuery instance + // Build queryString + $queryString = $tableName->assembleQueryString(true); + // Change $tableName + $tableName = $tableName->assembleFrom(true); } else { require_once 'Zend/Service/WindowsAzure/Exception.php'; throw new Zend_Service_WindowsAzure_Exception('Invalid argument: $tableName'); @@ -580,11 +566,7 @@ public function retrieveEntities($tableName = '', $filter = '', $entityClass = ' $entries = null; if ($result->entry) { - if (count($result->entry) > 1) { - $entries = $result->entry; - } else { - $entries = array($result->entry); - } + $entries = count($result->entry) > 1 ? $result->entry : array($result->entry); } else { // This one is tricky... If we have properties defined, we have an entity. $properties = $result->xpath('//m:properties'); @@ -627,10 +609,8 @@ public function retrieveEntities($tableName = '', $filter = '', $entityClass = ' } // More entities? - if (!is_null($response->getHeader('x-ms-continuation-NextPartitionKey')) && !is_null($response->getHeader('x-ms-continuation-NextRowKey'))) { - if (strpos($queryString, '$top') === false) { - $returnValue = array_merge($returnValue, $this->retrieveEntities($tableName, $filter, $entityClass, $response->getHeader('x-ms-continuation-NextPartitionKey'), $response->getHeader('x-ms-continuation-NextRowKey'))); - } + if (!is_null($response->getHeader('x-ms-continuation-NextPartitionKey')) && !is_null($response->getHeader('x-ms-continuation-NextRowKey')) && strpos($queryString, '$top') === false) { + $returnValue = array_merge($returnValue, $this->retrieveEntities($tableName, $filter, $entityClass, $response->getHeader('x-ms-continuation-NextPartitionKey'), $response->getHeader('x-ms-continuation-NextRowKey'))); } // Return @@ -666,7 +646,7 @@ public function updateEntity($tableName = '', Zend_Service_WindowsAzure_Storage_ public function mergeEntity($tableName = '', Zend_Service_WindowsAzure_Storage_TableEntity $entity = null, $verifyEtag = false, $properties = array()) { $mergeEntity = null; - if (is_array($properties) && count($properties) > 0) { + if (is_array($properties) && $properties !== []) { // Build a new object $mergeEntity = new Zend_Service_WindowsAzure_Storage_DynamicTableEntity($entity->getPartitionKey(), $entity->getRowKey()); @@ -729,11 +709,7 @@ protected function _changeEntity($httpVerb = Zend_Http_Client::PUT, $tableName = $headers = array(); $headers['Content-Type'] = 'application/atom+xml'; $headers['Content-Length'] = 0; - if (!$verifyEtag) { - $headers['If-Match'] = '*'; - } else { - $headers['If-Match'] = $entity->getEtag(); - } + $headers['If-Match'] = $verifyEtag ? $entity->getEtag() : '*'; // Generate request body $requestBody = ' @@ -762,11 +738,7 @@ protected function _changeEntity($httpVerb = Zend_Http_Client::PUT, $tableName = // Add header information $headers = array(); $headers['Content-Type'] = 'application/atom+xml'; - if (!$verifyEtag) { - $headers['If-Match'] = '*'; - } else { - $headers['If-Match'] = $entity->getEtag(); - } + $headers['If-Match'] = $verifyEtag ? $entity->getEtag() : '*'; // Perform request $response = null; @@ -837,10 +809,10 @@ protected function _generateAzureRepresentation(Zend_Service_WindowsAzure_Storag if (!is_null($azureValue->Value)) { if (strtolower($azureValue->Type) == 'edm.boolean') { - $value[] = ($azureValue->Value == true ? '1' : '0'); - } else if (strtolower($azureValue->Type) == 'edm.datetime') { - $value[] = $this->_convertToEdmDateTime($azureValue->Value); - } else { + $value[] = ($azureValue->Value == true ? '1' : '0'); + } elseif (strtolower($azureValue->Type) == 'edm.datetime') { + $value[] = $this->_convertToEdmDateTime($azureValue->Value); + } else { $value[] = htmlspecialchars($azureValue->Value); } } @@ -922,7 +894,7 @@ protected function _convertToDateTime($value = '') * @param DateTime $value * @return string */ - protected function _convertToEdmDateTime(DateTime $value) + protected function _convertToEdmDateTime(\DateTimeInterface $value) { $cloned = clone $value; $cloned->setTimezone(new DateTimeZone('UTC')); diff --git a/library/Zend/Service/WindowsAzure/Storage/TableEntity.php b/library/Zend/Service/WindowsAzure/Storage/TableEntity.php index 860b2a072f..39e7a481fa 100644 --- a/library/Zend/Service/WindowsAzure/Storage/TableEntity.php +++ b/library/Zend/Service/WindowsAzure/Storage/TableEntity.php @@ -133,7 +133,7 @@ public function getTimestamp() * @azure Timestamp Edm.DateTime * @param DateTime $value */ - public function setTimestamp(DateTime $value) + public function setTimestamp(\DateTimeInterface $value) { $this->_timestamp = $value; } @@ -172,20 +172,20 @@ public function getAzureValues() $returnValue = array(); foreach ($accessors as $accessor) { if ($accessor->EntityType == 'ReflectionProperty') { - $property = $accessor->EntityAccessor; - $returnValue[] = (object)array( - 'Name' => $accessor->AzurePropertyName, - 'Type' => $accessor->AzurePropertyType, - 'Value' => $this->$property, - ); - } else if ($accessor->EntityType == 'ReflectionMethod' && substr(strtolower($accessor->EntityAccessor), 0, 3) == 'get') { - $method = $accessor->EntityAccessor; - $returnValue[] = (object)array( - 'Name' => $accessor->AzurePropertyName, - 'Type' => $accessor->AzurePropertyType, - 'Value' => $this->$method(), - ); - } + $property = $accessor->EntityAccessor; + $returnValue[] = (object)array( + 'Name' => $accessor->AzurePropertyName, + 'Type' => $accessor->AzurePropertyType, + 'Value' => $this->$property, + ); + } elseif ($accessor->EntityType == 'ReflectionMethod' && substr(strtolower($accessor->EntityAccessor), 0, 3) == 'get') { + $method = $accessor->EntityAccessor; + $returnValue[] = (object)array( + 'Name' => $accessor->AzurePropertyName, + 'Type' => $accessor->AzurePropertyType, + 'Value' => $this->$method(), + ); + } } // Return @@ -208,37 +208,36 @@ public function setAzureValues($values = array(), $throwOnError = false) $returnValue = array(); foreach ($accessors as $accessor) { if (isset($values[$accessor->AzurePropertyName])) { - // Cast to correct type - if ($accessor->AzurePropertyType != '') { - switch (strtolower($accessor->AzurePropertyType)) { - case 'edm.int32': - case 'edm.int64': - $values[$accessor->AzurePropertyName] = intval($values[$accessor->AzurePropertyName]); break; - case 'edm.boolean': - if ($values[$accessor->AzurePropertyName] == 'true' || $values[$accessor->AzurePropertyName] == '1') - $values[$accessor->AzurePropertyName] = true; - else - $values[$accessor->AzurePropertyName] = false; - break; - case 'edm.double': - $values[$accessor->AzurePropertyName] = floatval($values[$accessor->AzurePropertyName]); break; - case 'edm.datetime': - $values[$accessor->AzurePropertyName] = $this->_convertToDateTime($values[$accessor->AzurePropertyName]); break; - } - } - - // Assign value - if ($accessor->EntityType == 'ReflectionProperty') { - $property = $accessor->EntityAccessor; - $this->$property = $values[$accessor->AzurePropertyName]; - } else if ($accessor->EntityType == 'ReflectionMethod' && substr(strtolower($accessor->EntityAccessor), 0, 3) == 'set') { - $method = $accessor->EntityAccessor; - $this->$method($values[$accessor->AzurePropertyName]); - } - } else if ($throwOnError) { - require_once 'Zend/Service/WindowsAzure/Exception.php'; - throw new Zend_Service_WindowsAzure_Exception("Property '" . $accessor->AzurePropertyName . "' was not found in \$values array"); - } + // Cast to correct type + if ($accessor->AzurePropertyType != '') { + switch (strtolower($accessor->AzurePropertyType)) { + case 'edm.int32': + case 'edm.int64': + $values[$accessor->AzurePropertyName] = (int) $values[$accessor->AzurePropertyName]; break; + case 'edm.boolean': + if ($values[$accessor->AzurePropertyName] == 'true' || $values[$accessor->AzurePropertyName] == '1') + $values[$accessor->AzurePropertyName] = true; + else + $values[$accessor->AzurePropertyName] = false; + break; + case 'edm.double': + $values[$accessor->AzurePropertyName] = floatval($values[$accessor->AzurePropertyName]); break; + case 'edm.datetime': + $values[$accessor->AzurePropertyName] = $this->_convertToDateTime($values[$accessor->AzurePropertyName]); break; + } + } + // Assign value + if ($accessor->EntityType == 'ReflectionProperty') { + $property = $accessor->EntityAccessor; + $this->$property = $values[$accessor->AzurePropertyName]; + } elseif ($accessor->EntityType == 'ReflectionMethod' && substr(strtolower($accessor->EntityAccessor), 0, 3) == 'set') { + $method = $accessor->EntityAccessor; + $this->$method($values[$accessor->AzurePropertyName]); + } + } elseif ($throwOnError) { + require_once 'Zend/Service/WindowsAzure/Exception.php'; + throw new Zend_Service_WindowsAzure_Exception("Property '" . $accessor->AzurePropertyName . "' was not found in \$values array"); + } } // Return diff --git a/library/Zend/Service/WindowsAzure/Storage/TableEntityQuery.php b/library/Zend/Service/WindowsAzure/Storage/TableEntityQuery.php index f7904d2ef2..165f965334 100644 --- a/library/Zend/Service/WindowsAzure/Storage/TableEntityQuery.php +++ b/library/Zend/Service/WindowsAzure/Storage/TableEntityQuery.php @@ -135,7 +135,7 @@ public function where($condition, $value = null, $cond = '') if (count($this->_where) == 0) { $cond = ''; - } else if ($cond !== '') { + } elseif ($cond !== '') { $cond = ' ' . strtolower(trim($cond)) . ' '; } @@ -309,9 +309,8 @@ protected function _replaceOperators($text) $text = str_replace('&&', 'and', $text); $text = str_replace('||', 'or', $text); - $text = str_replace('!', 'not', $text); - return $text; + return str_replace('!', 'not', $text); } /** @@ -333,10 +332,8 @@ public static function encodeQuery($query) $query = str_replace('$', '%24', $query); $query = str_replace('{', '%7B', $query); $query = str_replace('}', '%7D', $query); - - $query = str_replace(' ', '%20', $query); - return $query; + return str_replace(' ', '%20', $query); } /** diff --git a/library/Zend/Service/Yahoo.php b/library/Zend/Service/Yahoo.php index 8a13d8ab0f..c188fc3b00 100644 --- a/library/Zend/Service/Yahoo.php +++ b/library/Zend/Service/Yahoo.php @@ -896,12 +896,12 @@ protected function _validateLanguage($lang) protected function _compareOptions(array $options, array $validOptions) { $difference = array_diff(array_keys($options), $validOptions); - if ($difference) { + if ($difference !== []) { /** * @see Zend_Service_Exception */ require_once 'Zend/Service/Exception.php'; - throw new Zend_Service_Exception('The following parameters are invalid: ' . join(', ', $difference)); + throw new Zend_Service_Exception('The following parameters are invalid: ' . implode(', ', $difference)); } } diff --git a/library/Zend/Service/Yahoo/Result.php b/library/Zend/Service/Yahoo/Result.php index fcd73d29d1..91d205a4b6 100644 --- a/library/Zend/Service/Yahoo/Result.php +++ b/library/Zend/Service/Yahoo/Result.php @@ -31,6 +31,8 @@ */ class Zend_Service_Yahoo_Result { + public $_namespace; + public ?\Zend_Service_Yahoo_Image $Thumbnail; /** * The title of the search entry * diff --git a/library/Zend/Service/Yahoo/ResultSet.php b/library/Zend/Service/Yahoo/ResultSet.php index 163cafb68b..66f6477900 100644 --- a/library/Zend/Service/Yahoo/ResultSet.php +++ b/library/Zend/Service/Yahoo/ResultSet.php @@ -31,6 +31,7 @@ */ class Zend_Service_Yahoo_ResultSet implements SeekableIterator { + public $_namespace; /** * Total number of results available * @@ -127,8 +128,7 @@ public function current() * @see Zend_Service_Exception */ require_once 'Zend/Service/Exception.php'; - throw new Zend_Service_Exception('Zend_Service_Yahoo_ResultSet::current() must be implemented by child ' - . 'classes'); + throw new Zend_Service_Exception('Zend_Service_Yahoo_ResultSet::current() must be implemented by child classes'); } diff --git a/library/Zend/Session.php b/library/Zend/Session.php index 5bf201781c..d01e636687 100644 --- a/library/Zend/Session.php +++ b/library/Zend/Session.php @@ -637,7 +637,7 @@ public static function isStarted() */ public static function isRegenerated() { - return ( (self::$_regenerateIdState > 0) ? true : false ); + return ( self::$_regenerateIdState > 0 ); } @@ -867,7 +867,7 @@ public static function namespaceGet($namespace) */ public static function getIterator() { - if (parent::$_readable === false) { + if (!parent::$_readable) { /** @see Zend_Session_Exception */ require_once 'Zend/Session/Exception.php'; throw new Zend_Session_Exception(parent::_THROW_NOT_READABLE_MSG); diff --git a/library/Zend/Session/Abstract.php b/library/Zend/Session/Abstract.php index 127905c5e0..f1176633a1 100644 --- a/library/Zend/Session/Abstract.php +++ b/library/Zend/Session/Abstract.php @@ -78,7 +78,7 @@ abstract class Zend_Session_Abstract */ protected static function _namespaceIsset($namespace, $name = null) { - if (self::$_readable === false) { + if (!self::$_readable) { /** * @see Zend_Session_Exception */ @@ -104,7 +104,7 @@ protected static function _namespaceIsset($namespace, $name = null) */ protected static function _namespaceUnset($namespace, $name = null) { - if (self::$_writable === false) { + if (!self::$_writable) { /** * @see Zend_Session_Exception */ @@ -139,7 +139,7 @@ protected static function _namespaceUnset($namespace, $name = null) */ protected static function & _namespaceGet($namespace, $name = null) { - if (self::$_readable === false) { + if (!self::$_readable) { /** * @see Zend_Session_Exception */ @@ -155,14 +155,13 @@ protected static function & _namespaceGet($namespace, $name = null) } else { return $_SESSION[$namespace]; // satisfy return by reference } + } elseif (isset($_SESSION[$namespace][$name])) { + // check session first + return $_SESSION[$namespace][$name]; + } elseif (isset(self::$_expiringData[$namespace][$name])) { // check expiring data + return self::$_expiringData[$namespace][$name]; } else { - if (isset($_SESSION[$namespace][$name])) { // check session first - return $_SESSION[$namespace][$name]; - } elseif (isset(self::$_expiringData[$namespace][$name])) { // check expiring data - return self::$_expiringData[$namespace][$name]; - } else { - return $_SESSION[$namespace][$name]; // satisfy return by reference - } + return $_SESSION[$namespace][$name]; // satisfy return by reference } } diff --git a/library/Zend/Session/Namespace.php b/library/Zend/Session/Namespace.php index 2b2daeeb25..f6a9970204 100644 --- a/library/Zend/Session/Namespace.php +++ b/library/Zend/Session/Namespace.php @@ -133,7 +133,7 @@ public function __construct($namespace = 'Default', $singleInstance = false) throw new Zend_Session_Exception("A session namespace object already exists for this namespace ('$namespace'), and no additional accessors (session namespace objects) for this namespace are permitted."); } - if ($singleInstance === true) { + if ($singleInstance) { self::$_singleInstances[$namespace] = true; } @@ -142,7 +142,7 @@ public function __construct($namespace = 'Default', $singleInstance = false) // Process metadata specific only to this namespace. Zend_Session::start(true); // attempt auto-start (throws exception if strict option set) - if (self::$_readable === false) { + if (!self::$_readable) { /** * @see Zend_Session_Exception */ @@ -155,7 +155,7 @@ public function __construct($namespace = 'Default', $singleInstance = false) } // do not allow write access to namespaces, after stop() or writeClose() - if (parent::$_writable === true) { + if (parent::$_writable) { if (isset($_SESSION['__ZF'][$namespace])) { // Expire Namespace by Namespace Hop (ENNH) @@ -207,6 +207,7 @@ public function __construct($namespace = 'Default', $singleInstance = false) * * @return ArrayObject - iteratable container of the namespace contents */ + #[\ReturnTypeWillChange] public function getIterator() { return new ArrayObject(parent::_namespaceGetAll($this->_namespace)); @@ -312,7 +313,7 @@ public function __set($name, $value) throw new Zend_Session_Exception("The '$name' key must be a non-empty string"); } - if (parent::$_writable === false) { + if (!parent::$_writable) { /** * @see Zend_Session_Exception */ @@ -425,7 +426,7 @@ public function __unset($name) */ public function setExpirationSeconds($seconds, $variables = null) { - if (parent::$_writable === false) { + if (!parent::$_writable) { /** * @see Zend_Session_Exception */ @@ -473,7 +474,7 @@ public function setExpirationSeconds($seconds, $variables = null) */ public function setExpirationHops($hops, $variables = null, $hopCountOnUsageOnly = false) { - if (parent::$_writable === false) { + if (!parent::$_writable) { /** * @see Zend_Session_Exception */ @@ -492,7 +493,7 @@ public function setExpirationHops($hops, $variables = null, $hopCountOnUsageOnly if ($variables === null) { // apply expiration to entire namespace - if ($hopCountOnUsageOnly === false) { + if (!$hopCountOnUsageOnly) { $_SESSION['__ZF'][$this->_namespace]['ENGH'] = $hops; } else { $_SESSION['__ZF'][$this->_namespace]['ENNH'] = $hops; @@ -506,7 +507,7 @@ public function setExpirationHops($hops, $variables = null, $hopCountOnUsageOnly foreach ($variables as $variable) { if (!empty($variable)) { - if ($hopCountOnUsageOnly === false) { + if (!$hopCountOnUsageOnly) { $_SESSION['__ZF'][$this->_namespace]['ENVGH'][$variable] = $hops; } else { $_SESSION['__ZF'][$this->_namespace]['ENVNH'][$variable] = $hops; diff --git a/library/Zend/Session/SaveHandler/DbTable.php b/library/Zend/Session/SaveHandler/DbTable.php index e423a18d4c..d9c8193a41 100644 --- a/library/Zend/Session/SaveHandler/DbTable.php +++ b/library/Zend/Session/SaveHandler/DbTable.php @@ -164,12 +164,11 @@ public function __construct($config) { if ($config instanceof Zend_Config) { $config = $config->toArray(); - } else if (!is_array($config)) { + } elseif (!is_array($config)) { /** * @see Zend_Session_SaveHandler_Exception */ require_once 'Zend/Session/SaveHandler/Exception.php'; - throw new Zend_Session_SaveHandler_Exception( '$config must be an instance of Zend_Config or array of key/value pairs containing ' . 'configuration options for Zend_Session_SaveHandler_DbTable and Zend_Db_Table_Abstract.'); @@ -234,11 +233,7 @@ public function setLifetime($lifetime, $overrideLifetime = null) */ require_once 'Zend/Session/SaveHandler/Exception.php'; throw new Zend_Session_SaveHandler_Exception(); - } else if (empty($lifetime)) { - $this->_lifetime = (int) ini_get('session.gc_maxlifetime'); - } else { - $this->_lifetime = (int) $lifetime; - } + } else $this->_lifetime = empty($lifetime) ? (int) ini_get('session.gc_maxlifetime') : (int) $lifetime; if ($overrideLifetime != null) { $this->setOverrideLifetime($overrideLifetime); @@ -317,7 +312,7 @@ public function read($id) $rows = call_user_func_array(array(&$this, 'find'), $this->_getPrimary($id)); - if (count($rows)) { + if (count($rows) > 0) { if ($this->_getExpirationTime($row = $rows->current()) > time()) { $return = $row->{$this->_dataColumn}; } else { @@ -344,10 +339,10 @@ public function write($id, $data) $rows = call_user_func_array(array(&$this, 'find'), $this->_getPrimary($id)); - if (count($rows)) { + if (count($rows) > 0) { $data[$this->_lifetimeColumn] = $this->_getLifetime($rows->current()); - if ($this->update($data, $this->_getPrimary($id, self::PRIMARY_TYPE_WHERECLAUSE))) { + if ($this->update($data, $this->_getPrimary($id, self::PRIMARY_TYPE_WHERECLAUSE)) !== 0) { $return = true; } } else { @@ -371,7 +366,7 @@ public function destroy($id) { $return = false; - if ($this->delete($this->_getPrimary($id, self::PRIMARY_TYPE_WHERECLAUSE))) { + if ($this->delete($this->_getPrimary($id, self::PRIMARY_TYPE_WHERECLAUSE)) !== 0) { $return = true; } @@ -440,11 +435,10 @@ protected function _setupPrimaryAssignment() { if ($this->_primaryAssignment === null) { $this->_primaryAssignment = array(1 => self::PRIMARY_ASSIGNMENT_SESSION_ID); - } else if (!is_array($this->_primaryAssignment)) { + } elseif (!is_array($this->_primaryAssignment)) { $this->_primaryAssignment = array(1 => (string) $this->_primaryAssignment); - } else if (isset($this->_primaryAssignment[0])) { + } elseif (isset($this->_primaryAssignment[0])) { array_unshift($this->_primaryAssignment, null); - unset($this->_primaryAssignment[0]); } @@ -453,16 +447,14 @@ protected function _setupPrimaryAssignment() * @see Zend_Session_SaveHandler_Exception */ require_once 'Zend/Session/SaveHandler/Exception.php'; - throw new Zend_Session_SaveHandler_Exception( "Value for configuration option '" . self::PRIMARY_ASSIGNMENT . "' must have an assignment " . "for each session table primary key."); - } else if (!in_array(self::PRIMARY_ASSIGNMENT_SESSION_ID, $this->_primaryAssignment)) { + } elseif (!in_array(self::PRIMARY_ASSIGNMENT_SESSION_ID, $this->_primaryAssignment)) { /** * @see Zend_Session_SaveHandler_Exception */ require_once 'Zend/Session/SaveHandler/Exception.php'; - throw new Zend_Session_SaveHandler_Exception( "Value for configuration option '" . self::PRIMARY_ASSIGNMENT . "' must have an assignment " . "for the session id ('" . self::PRIMARY_ASSIGNMENT_SESSION_ID . "')."); @@ -482,25 +474,22 @@ protected function _checkRequiredColumns() * @see Zend_Session_SaveHandler_Exception */ require_once 'Zend/Session/SaveHandler/Exception.php'; - throw new Zend_Session_SaveHandler_Exception( "Configuration must define '" . self::MODIFIED_COLUMN . "' which names the " . "session table last modification time column."); - } else if ($this->_lifetimeColumn === null) { + } elseif ($this->_lifetimeColumn === null) { /** * @see Zend_Session_SaveHandler_Exception */ require_once 'Zend/Session/SaveHandler/Exception.php'; - throw new Zend_Session_SaveHandler_Exception( "Configuration must define '" . self::LIFETIME_COLUMN . "' which names the " . "session table lifetime column."); - } else if ($this->_dataColumn === null) { + } elseif ($this->_dataColumn === null) { /** * @see Zend_Session_SaveHandler_Exception */ require_once 'Zend/Session/SaveHandler/Exception.php'; - throw new Zend_Session_SaveHandler_Exception( "Configuration must define '" . self::DATA_COLUMN . "' which names the " . "session table data column."); diff --git a/library/Zend/Soap/AutoDiscover.php b/library/Zend/Soap/AutoDiscover.php index 2cce09e016..8773e4f6f7 100644 --- a/library/Zend/Soap/AutoDiscover.php +++ b/library/Zend/Soap/AutoDiscover.php @@ -253,11 +253,7 @@ protected function getSchema() */ protected function getHostName() { - if(isset($_SERVER['HTTP_HOST'])) { - $host = $_SERVER['HTTP_HOST']; - } else { - $host = $_SERVER['SERVER_NAME']; - } + $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME']; return $host; } @@ -457,7 +453,7 @@ protected function _addFunctionToWsdl($function, $wsdl, $port, $binding) ); // Add the wrapper element part, which must be named 'parameters' $args['parameters'] = array('element' => $wsdl->addElement($element)); - } else if ($prototype->getReturnType() != "void") { + } elseif ($prototype->getReturnType() != "void") { // RPC style: add the return value as a typed part $args['return'] = array('type' => $wsdl->getType($prototype->getReturnType())); } diff --git a/library/Zend/Soap/Client.php b/library/Zend/Soap/Client.php index 9a3b754c35..382da21b7d 100644 --- a/library/Zend/Soap/Client.php +++ b/library/Zend/Soap/Client.php @@ -330,10 +330,8 @@ public function getOptions() if ($value === null) { unset($options[$key]); } - } else { - if ($value == null) { - unset($options[$key]); - } + } elseif ($value == null) { + unset($options[$key]); } } @@ -777,11 +775,7 @@ public function getHttpsCertPassphrase() */ public function setCompressionOptions($compressionOptions) { - if ($compressionOptions === null) { - $this->_compression = null; - } else { - $this->_compression = (int)$compressionOptions; - } + $this->_compression = $compressionOptions === null ? null : (int)$compressionOptions; $this->_soapClient = null; return $this; } @@ -869,11 +863,7 @@ public function getSoapFeatures() */ public function setWsdlCache($caching) { - if ($caching === null) { - $this->_cache_wsdl = null; - } else { - $this->_cache_wsdl = (int)$caching; - } + $this->_cache_wsdl = $caching === null ? null : (int)$caching; return $this; } @@ -895,11 +885,7 @@ public function getWsdlCache() */ public function setUserAgent($userAgent) { - if ($userAgent === null) { - $this->_user_agent = null; - } else { - $this->_user_agent = (string)$userAgent; - } + $this->_user_agent = $userAgent === null ? null : (string)$userAgent; return $this; } @@ -1030,9 +1016,9 @@ public function _doRequest(Zend_Soap_Client_Common $client, $request, $location, { // Perform request as is if ($one_way == null) { - return call_user_func(array($client,'SoapClient::__doRequest'), $request, $location, $action, $version); + return $client->SoapClient::__doRequest($request, $location, $action, $version); } else { - return call_user_func(array($client,'SoapClient::__doRequest'), $request, $location, $action, $version, $one_way); + return $client->SoapClient::__doRequest($request, $location, $action, $version, $one_way); } } @@ -1155,7 +1141,7 @@ public function __call($name, $arguments) $result = $soapClient->__soapCall($name, $this->_preProcessArguments($arguments), null, /* Options are already set to the SOAP client object */ - (count($soapHeaders) > 0)? $soapHeaders : null, + ($soapHeaders !== [])? $soapHeaders : null, $this->_soapOutputHeaders); // Reset non-permanent input headers diff --git a/library/Zend/Soap/Client/Local.php b/library/Zend/Soap/Client/Local.php index 11444fc5cb..2d0f34e6d4 100644 --- a/library/Zend/Soap/Client/Local.php +++ b/library/Zend/Soap/Client/Local.php @@ -42,6 +42,7 @@ */ class Zend_Soap_Client_Local extends Zend_Soap_Client { + public $server; /** * Server object * diff --git a/library/Zend/Soap/Server.php b/library/Zend/Soap/Server.php index ee2b6039c3..ab1b113806 100644 --- a/library/Zend/Soap/Server.php +++ b/library/Zend/Soap/Server.php @@ -590,7 +590,7 @@ public function addFunction($function, $namespace = '') */ public function setClass($class, $namespace = '', $argv = null) { - if (isset($this->_class)) { + if ($this->_class !== null) { require_once 'Zend/Soap/Server/Exception.php'; throw new Zend_Soap_Server_Exception('A class has already been registered with this soap server instance'); } @@ -630,7 +630,7 @@ public function setObject($object) throw new Zend_Soap_Server_Exception('Invalid object argument ('.gettype($object).')'); } - if(isset($this->_object)) { + if($this->_object !== null) { require_once 'Zend/Soap/Server/Exception.php'; throw new Zend_Soap_Server_Exception('An object has already been registered with this soap server instance'); } @@ -729,11 +729,7 @@ protected function _setRequest($request) } elseif ($request instanceof SimpleXMLElement) { $xml = $request->asXML(); } elseif (is_object($request) || is_string($request)) { - if (is_object($request)) { - $xml = $request->__toString(); - } else { - $xml = $request; - } + $xml = is_object($request) ? $request->__toString() : $request; $dom = new DOMDocument(); try { @@ -743,9 +739,7 @@ protected function _setRequest($request) } } catch (Zend_Xml_Exception $e) { require_once 'Zend/Soap/Server/Exception.php'; - throw new Zend_Soap_Server_Exception( - $e->getMessage() - ); + throw new Zend_Soap_Server_Exception($e->getMessage(), $e->getCode(), $e); } } $this->_request = $xml; @@ -775,7 +769,7 @@ public function getLastRequest() */ public function setReturnResponse($flag) { - $this->_returnResponse = ($flag) ? true : false; + $this->_returnResponse = $flag; return $this; } diff --git a/library/Zend/Soap/Server/Proxy.php b/library/Zend/Soap/Server/Proxy.php index 93b6ab4e6a..2fb5a3be48 100644 --- a/library/Zend/Soap/Server/Proxy.php +++ b/library/Zend/Soap/Server/Proxy.php @@ -39,11 +39,7 @@ public function __construct($className, $classArgs = array()) { $class = new ReflectionClass($className); $constructor = $class->getConstructor(); - if ($constructor === null) { - $this->_classInstance = $class->newInstance(); - } else { - $this->_classInstance = $class->newInstanceArgs($classArgs); - } + $this->_classInstance = $constructor instanceof \ReflectionMethod ? $class->newInstanceArgs($classArgs) : $class->newInstance(); $this->_className = $className; } /** diff --git a/library/Zend/Soap/Wsdl.php b/library/Zend/Soap/Wsdl.php index afc5f687ca..3b3516222f 100644 --- a/library/Zend/Soap/Wsdl.php +++ b/library/Zend/Soap/Wsdl.php @@ -143,13 +143,13 @@ public function setUri($uri) */ public function setComplexTypeStrategy($strategy) { - if($strategy === true) { + if ($strategy === true) { require_once "Zend/Soap/Wsdl/Strategy/DefaultComplexType.php"; $strategy = new Zend_Soap_Wsdl_Strategy_DefaultComplexType(); - } else if($strategy === false) { + } elseif ($strategy === false) { require_once "Zend/Soap/Wsdl/Strategy/AnyType.php"; $strategy = new Zend_Soap_Wsdl_Strategy_AnyType(); - } else if(is_string($strategy)) { + } elseif (is_string($strategy)) { if(class_exists($strategy)) { $strategy = new $strategy(); } else { @@ -194,7 +194,7 @@ public function addMessage($name, $parts) $message->setAttribute('name', $name); - if (sizeof($parts) > 0) { + if ($parts !== []) { foreach ($parts as $name => $type) { $part = $this->_dom->createElement('part'); $part->setAttribute('name', $name); @@ -425,11 +425,7 @@ public function addService($name, $port_name, $binding, $location) */ public function addDocumentation($input_node, $documentation) { - if ($input_node === $this) { - $node = $this->_dom->documentElement; - } else { - $node = $input_node; - } + $node = $input_node === $this ? $this->_dom->documentElement : $input_node; $doc = $this->_dom->createElement('documentation'); $doc_cdata = $this->_dom->createTextNode(str_replace(array("\r\n", "\r"), "\n", $documentation)); @@ -625,7 +621,7 @@ private function _parseElement($element) if (in_array($key, array('sequence', 'all', 'choice'))) { if (is_array($value)) { $complexType = $this->_dom->createElement('xsd:complexType'); - if (count($value) > 0) { + if ($value !== []) { $container = $this->_dom->createElement('xsd:' . $key); foreach ($value as $subelement) { $subelementXml = $this->_parseElement($subelement); diff --git a/library/Zend/Soap/Wsdl/Strategy/ArrayOfTypeComplex.php b/library/Zend/Soap/Wsdl/Strategy/ArrayOfTypeComplex.php index 3e7d6acbb6..04ab99a4d1 100644 --- a/library/Zend/Soap/Wsdl/Strategy/ArrayOfTypeComplex.php +++ b/library/Zend/Soap/Wsdl/Strategy/ArrayOfTypeComplex.php @@ -71,12 +71,7 @@ public function addComplexType($type) )); } - if($nestingLevel == 1) { - // The following blocks define the Array of Object structure - $xsdComplexTypeName = $this->_addArrayOfComplexType($singularType, $type); - } else { - $xsdComplexTypeName = $singularType; - } + $xsdComplexTypeName = $nestingLevel == 1 ? $this->_addArrayOfComplexType($singularType, $type) : $singularType; // The array for the objects has been created, now build the object definition: if(!in_array($singularType, $this->getContext()->getTypes())) { diff --git a/library/Zend/Soap/Wsdl/Strategy/ArrayOfTypeSequence.php b/library/Zend/Soap/Wsdl/Strategy/ArrayOfTypeSequence.php index 0c04221a33..619b0d5389 100644 --- a/library/Zend/Soap/Wsdl/Strategy/ArrayOfTypeSequence.php +++ b/library/Zend/Soap/Wsdl/Strategy/ArrayOfTypeSequence.php @@ -45,9 +45,8 @@ public function addComplexType($type) { $nestedCounter = $this->_getNestedCount($type); - if($nestedCounter > 0) { + if ($nestedCounter > 0) { $singularType = $this->_getSingularType($type); - for($i = 1; $i <= $nestedCounter; $i++) { $complexTypeName = substr($this->_getTypeNameBasedOnNestingLevel($singularType, $i), 4); $childTypeName = $this->_getTypeNameBasedOnNestingLevel($singularType, $i-1); @@ -56,9 +55,8 @@ public function addComplexType($type) } // adding the PHP type which is resolved to a nested XSD type. therefore add only once. $this->getContext()->addType($complexTypeName); - return "tns:$complexTypeName"; - } else if (!in_array($type, $this->getContext()->getTypes())) { + } elseif (!in_array($type, $this->getContext()->getTypes())) { // New singular complex type return parent::addComplexType($type); } else { @@ -107,8 +105,7 @@ protected function _getStrippedXsdType($singularType) */ protected function _getSingularType($type) { - $singulartype = $this->getContext()->getType(str_replace("[]", "", $type)); - return $singulartype; + return $this->getContext()->getType(str_replace("[]", "", $type)); } /** diff --git a/library/Zend/Stdlib/SplPriorityQueue.php b/library/Zend/Stdlib/SplPriorityQueue.php index 60cb8727a3..7b96a7d7ee 100644 --- a/library/Zend/Stdlib/SplPriorityQueue.php +++ b/library/Zend/Stdlib/SplPriorityQueue.php @@ -120,7 +120,7 @@ public function current() if (!$this->preparedQueue) { $this->rewind(); } - if (!$this->count) { + if ($this->count === 0) { throw new OutOfBoundsException('Cannot iterate SplPriorityQueue; no elements present'); } @@ -160,7 +160,7 @@ public function current() */ public function extract() { - if (!$this->count) { + if ($this->count === 0) { return null; } @@ -422,10 +422,8 @@ public function insert($datum, $priority) // hack around it to ensure that items registered at the same priority // return in the order registered. In the userland version, this is not // necessary. - if ($this->isPhp53) { - if (!is_array($priority)) { - $priority = array($priority, $this->serial--); - } + if ($this->isPhp53 && !is_array($priority)) { + $priority = array($priority, $this->serial--); } parent::insert($datum, $priority); } diff --git a/library/Zend/Tag/Cloud.php b/library/Zend/Tag/Cloud.php index 2e788e057f..6c32796220 100644 --- a/library/Zend/Tag/Cloud.php +++ b/library/Zend/Tag/Cloud.php @@ -147,7 +147,7 @@ public function setTags(array $tags) foreach ($tags as $tag) { if ($tag instanceof Zend_Tag_Taggable) { $itemList[] = $tag; - } else if (is_array($tag)) { + } elseif (is_array($tag)) { $itemList[] = new Zend_Tag_Item($tag); } else { require_once 'Zend/Tag/Cloud/Exception.php'; @@ -169,7 +169,7 @@ public function appendTag($tag) $tags = $this->getItemList(); if ($tag instanceof Zend_Tag_Taggable) { $tags[] = $tag; - } else if (is_array($tag)) { + } elseif (is_array($tag)) { $tags[] = new Zend_Tag_Item($tag); } else { require_once 'Zend/Tag/Cloud/Exception.php'; @@ -385,9 +385,8 @@ public function render() } $tagsResult = $this->getTagDecorator()->render($tags); - $cloudResult = $this->getCloudDecorator()->render($tagsResult); - return $cloudResult; + return $this->getCloudDecorator()->render($tagsResult); } /** @@ -398,8 +397,7 @@ public function render() public function __toString() { try { - $result = $this->render(); - return $result; + return $this->render(); } catch (Exception $e) { $message = "Exception caught by tag cloud: " . $e->getMessage() . "\nStack Trace:\n" . $e->getTraceAsString(); diff --git a/library/Zend/Tag/Cloud/Decorator/HtmlTag.php b/library/Zend/Tag/Cloud/Decorator/HtmlTag.php index 5bb44d0e8a..b846d550af 100644 --- a/library/Zend/Tag/Cloud/Decorator/HtmlTag.php +++ b/library/Zend/Tag/Cloud/Decorator/HtmlTag.php @@ -97,7 +97,7 @@ class Zend_Tag_Cloud_Decorator_HtmlTag extends Zend_Tag_Cloud_Decorator_Tag public function setClassList(array $classList = null) { if (is_array($classList)) { - if (count($classList) === 0) { + if ($classList === []) { require_once 'Zend/Tag/Cloud/Decorator/Exception.php'; throw new Zend_Tag_Cloud_Decorator_Exception('Classlist is empty'); } diff --git a/library/Zend/Tag/ItemList.php b/library/Zend/Tag/ItemList.php index dfc8cddfca..f1b3004c82 100644 --- a/library/Zend/Tag/ItemList.php +++ b/library/Zend/Tag/ItemList.php @@ -60,7 +60,7 @@ public function count() public function spreadWeightValues(array $values) { // Don't allow an empty value list - if (count($values) === 0) { + if ($values === []) { require_once 'Zend/Tag/Exception.php'; throw new Zend_Tag_Exception('Value list may not be empty'); } diff --git a/library/Zend/Test/DbAdapter.php b/library/Zend/Test/DbAdapter.php index 31198944fd..5001a2242d 100644 --- a/library/Zend/Test/DbAdapter.php +++ b/library/Zend/Test/DbAdapter.php @@ -94,7 +94,7 @@ public function __construct() */ public function appendStatementToStack(Zend_Test_DbStatement $stmt) { - array_push($this->_statementStack, $stmt); + $this->_statementStack[] = $stmt; return $this; } @@ -106,7 +106,7 @@ public function appendStatementToStack(Zend_Test_DbStatement $stmt) */ public function appendLastInsertIdToStack($id) { - array_push($this->_lastInsertIdStack, $id); + $this->_lastInsertIdStack[] = $id; return $this; } @@ -236,11 +236,7 @@ public function prepare($sql) { $queryId = $this->getProfiler()->queryStart($sql); - if(count($this->_statementStack)) { - $stmt = array_pop($this->_statementStack); - } else { - $stmt = new Zend_Test_DbStatement(); - } + $stmt = count($this->_statementStack) ? array_pop($this->_statementStack) : new Zend_Test_DbStatement(); if($this->getProfiler()->getEnabled() == true) { $qp = $this->getProfiler()->getQueryProfile($queryId); @@ -266,7 +262,7 @@ public function prepare($sql) */ public function lastInsertId($tableName = null, $primaryKey = null) { - if(count($this->_lastInsertIdStack)) { + if($this->_lastInsertIdStack !== []) { return array_pop($this->_lastInsertIdStack); } else { return false; diff --git a/library/Zend/Test/DbStatement.php b/library/Zend/Test/DbStatement.php index cf36a8fac6..a5af656890 100644 --- a/library/Zend/Test/DbStatement.php +++ b/library/Zend/Test/DbStatement.php @@ -266,9 +266,8 @@ public function execute(array $params = array()) */ public function fetch($style = null, $cursor = null, $offset = null) { - if(count($this->_fetchStack)) { - $row = array_shift($this->_fetchStack); - return $row; + if($this->_fetchStack !== []) { + return array_shift($this->_fetchStack); } else { return false; } diff --git a/library/Zend/Test/PHPUnit/Db/DataSet/DbRowset.php b/library/Zend/Test/PHPUnit/Db/DataSet/DbRowset.php index d8437528d5..1c62e2e3c5 100644 --- a/library/Zend/Test/PHPUnit/Db/DataSet/DbRowset.php +++ b/library/Zend/Test/PHPUnit/Db/DataSet/DbRowset.php @@ -37,6 +37,7 @@ */ class Zend_Test_PHPUnit_Db_DataSet_DbRowset extends PHPUnit_Extensions_Database_DataSet_AbstractTable { + public $tableName; /** * Construct Table object from a Zend_Db_Table_Rowset * @@ -61,9 +62,9 @@ public function __construct(Zend_Db_Table_Rowset_Abstract $rowset, $tableName = $this->data = $rowset->toArray(); $columns = array(); - if(isset($this->data[0]) > 0) { + if (isset($this->data[0]) > 0) { $columns = array_keys($this->data[0]); - } else if($rowset->getTable() != null) { + } elseif ($rowset->getTable() != null) { $columns = $rowset->getTable()->info('cols'); } diff --git a/library/Zend/Test/PHPUnit/Db/DataSet/DbTable.php b/library/Zend/Test/PHPUnit/Db/DataSet/DbTable.php index 37eaf430ca..97fd30949f 100644 --- a/library/Zend/Test/PHPUnit/Db/DataSet/DbTable.php +++ b/library/Zend/Test/PHPUnit/Db/DataSet/DbTable.php @@ -37,6 +37,10 @@ */ class Zend_Test_PHPUnit_Db_DataSet_DbTable extends PHPUnit_Extensions_Database_DataSet_QueryTable { + /** + * @var mixed|string|null + */ + public $_order; /** * Zend_Db_Table object * diff --git a/library/Zend/Test/PHPUnit/Db/DataSet/QueryTable.php b/library/Zend/Test/PHPUnit/Db/DataSet/QueryTable.php index 6100e80577..674dd7143e 100644 --- a/library/Zend/Test/PHPUnit/Db/DataSet/QueryTable.php +++ b/library/Zend/Test/PHPUnit/Db/DataSet/QueryTable.php @@ -71,7 +71,7 @@ protected function createTableMetaData() { $this->loadData(); $keys = array(); - if(count($this->data) > 0) { + if($this->data !== []) { $keys = array_keys($this->data[0]); } $this->tableMetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( diff --git a/library/Zend/Test/PHPUnit/Db/Metadata/Generic.php b/library/Zend/Test/PHPUnit/Db/Metadata/Generic.php index d4b414494a..64fa203a9d 100644 --- a/library/Zend/Test/PHPUnit/Db/Metadata/Generic.php +++ b/library/Zend/Test/PHPUnit/Db/Metadata/Generic.php @@ -105,8 +105,7 @@ protected function getTableDescription($tableName) public function getTableColumns($tableName) { $tableMeta = $this->getTableDescription($tableName); - $columns = array_keys($tableMeta); - return $columns; + return array_keys($tableMeta); } /** diff --git a/library/Zend/Test/PHPUnit/Db/Operation/Truncate.php b/library/Zend/Test/PHPUnit/Db/Operation/Truncate.php index da7c643b76..8a651588ef 100644 --- a/library/Zend/Test/PHPUnit/Db/Operation/Truncate.php +++ b/library/Zend/Test/PHPUnit/Db/Operation/Truncate.php @@ -70,22 +70,22 @@ public function execute(PHPUnit_Extensions_Database_DB_IDatabaseConnection $conn protected function _truncate(Zend_Db_Adapter_Abstract $db, $tableName) { $tableName = $db->quoteIdentifier($tableName, true); - if($db instanceof Zend_Db_Adapter_Pdo_Sqlite) { + if ($db instanceof Zend_Db_Adapter_Pdo_Sqlite) { $db->query('DELETE FROM '.$tableName); - } else if($db instanceof Zend_Db_Adapter_Db2) { + } elseif ($db instanceof Zend_Db_Adapter_Db2) { /*if(strstr(PHP_OS, "WIN")) { - $file = tempnam(sys_get_temp_dir(), "zendtestdbibm_"); - file_put_contents($file, ""); - $db->query('IMPORT FROM '.$file.' OF DEL REPLACE INTO '.$tableName); - unlink($file); - } else { - $db->query('IMPORT FROM /dev/null OF DEL REPLACE INTO '.$tableName); - }*/ + $file = tempnam(sys_get_temp_dir(), "zendtestdbibm_"); + file_put_contents($file, ""); + $db->query('IMPORT FROM '.$file.' OF DEL REPLACE INTO '.$tableName); + unlink($file); + } else { + $db->query('IMPORT FROM /dev/null OF DEL REPLACE INTO '.$tableName); + }*/ require_once "Zend/Exception.php"; throw Zend_Exception("IBM Db2 TRUNCATE not supported."); - } else if($this->_isMssqlOrOracle($db)) { + } elseif ($this->_isMssqlOrOracle($db)) { $db->query('TRUNCATE TABLE '.$tableName); - } else if($db instanceof Zend_Db_Adapter_Pdo_Pgsql) { + } elseif ($db instanceof Zend_Db_Adapter_Pdo_Pgsql) { $db->query('TRUNCATE '.$tableName.' CASCADE'); } else { $db->query('TRUNCATE '.$tableName); diff --git a/library/Zend/Text/Figlet.php b/library/Zend/Text/Figlet.php index 04b24688c9..2fbe0ae107 100644 --- a/library/Zend/Text/Figlet.php +++ b/library/Zend/Text/Figlet.php @@ -278,7 +278,7 @@ public function __construct($options = null) // Set options if (is_array($options)) { $this->setOptions($options); - } else if ($options instanceof Zend_Config) { + } elseif ($options instanceof Zend_Config) { $this->setConfig($options); } @@ -401,11 +401,7 @@ public function setSmushMode($smushMode) } else { if ($smushMode === 0) { $this->_userSmush = self::SM_KERN; - } else if ($smushMode === -1) { - $this->_userSmush = 0; - } else { - $this->_userSmush = (($smushMode & 63) | self::SM_SMUSH); - } + } else $this->_userSmush = $smushMode === -1 ? 0 : ($smushMode & 63) | self::SM_SMUSH; $this->_smushOverride = self::SMO_YES; } @@ -485,7 +481,7 @@ public function render($text, $encoding = 'UTF-8') if ($wordBreakMode === -1) { if ($char === ' ') { break; - } else if ($char === "\n") { + } elseif ($char === "\n") { $wordBreakMode = 0; break; } @@ -496,13 +492,13 @@ public function render($text, $encoding = 'UTF-8') if ($char === "\n") { $this->_appendLine(); $wordBreakMode = false; - } else if ($this->_addChar($char)) { + } elseif ($this->_addChar($char)) { if ($char !== ' ') { $wordBreakMode = ($wordBreakMode >= 2) ? 3: 1; } else { $wordBreakMode = ($wordBreakMode > 0) ? 2: 0; } - } else if ($this->_outlineLength === 0) { + } elseif ($this->_outlineLength === 0) { for ($i = 0; $i < $this->_charHeight; $i++) { if ($this->_rightToLeft === 1 && $this->_outputWidth > 1) { $offset = (strlen((string) $this->_currentChar[$i]) - $this->_outlineLengthLimit); @@ -511,15 +507,13 @@ public function render($text, $encoding = 'UTF-8') $this->_putString($this->_currentChar[$i]); } } - $wordBreakMode = -1; - } else if ($char === ' ') { + } elseif ($char === ' ') { if ($wordBreakMode === 2) { $this->_splitLine(); } else { $this->_appendLine(); } - $wordBreakMode = -1; } else { if ($wordBreakMode >= 2) { @@ -688,11 +682,7 @@ protected function _addChar($char) } $position = ($this->_outlineLength - $smushAmount + $k); - if (isset($this->_outputLine[$row][$position])) { - $leftChar = $this->_outputLine[$row][$position]; - } else { - $leftChar = null; - } + $leftChar = isset($this->_outputLine[$row][$position]) ? $this->_outputLine[$row][$position] : null; $this->_outputLine[$row][$position] = $this->_smushem($leftChar, $this->_currentChar[$row][$k]); } @@ -743,11 +733,7 @@ protected function _smushAmount() if ($this->_rightToLeft === 1) { $charbd = strlen((string) $this->_currentChar[$row]); while (true) { - if (!isset($this->_currentChar[$row][$charbd])) { - $leftChar = null; - } else { - $leftChar = $this->_currentChar[$row][$charbd]; - } + $leftChar = isset($this->_currentChar[$row][$charbd]) ? $this->_currentChar[$row][$charbd] : null; if ($charbd > 0 && ($leftChar === null || $leftChar == ' ')) { $charbd--; @@ -758,11 +744,7 @@ protected function _smushAmount() $linebd = 0; while (true) { - if (!isset($this->_outputLine[$row][$linebd])) { - $rightChar = null; - } else { - $rightChar = $this->_outputLine[$row][$linebd]; - } + $rightChar = isset($this->_outputLine[$row][$linebd]) ? $this->_outputLine[$row][$linebd] : null; if ($rightChar === ' ') { $linebd++; @@ -775,11 +757,7 @@ protected function _smushAmount() } else { $linebd = strlen((string) $this->_outputLine[$row]); while (true) { - if (!isset($this->_outputLine[$row][$linebd])) { - $leftChar = null; - } else { - $leftChar = $this->_outputLine[$row][$linebd]; - } + $leftChar = isset($this->_outputLine[$row][$linebd]) ? $this->_outputLine[$row][$linebd] : null; if ($linebd > 0 && ($leftChar === null || $leftChar == ' ')) { $linebd--; @@ -790,11 +768,7 @@ protected function _smushAmount() $charbd = 0; while (true) { - if (!isset($this->_currentChar[$row][$charbd])) { - $rightChar = null; - } else { - $rightChar = $this->_currentChar[$row][$charbd]; - } + $rightChar = isset($this->_currentChar[$row][$charbd]) ? $this->_currentChar[$row][$charbd] : null; if ($rightChar === ' ') { $charbd++; @@ -808,10 +782,8 @@ protected function _smushAmount() if (empty($leftChar) || $leftChar === ' ') { $amount++; - } else if (!empty($rightChar)) { - if ($this->_smushem($leftChar, $rightChar) !== null) { - $amount++; - } + } elseif (!empty($rightChar) && $this->_smushem($leftChar, $rightChar) !== null) { + $amount++; } $maxSmush = min($amount, $maxSmush); @@ -864,13 +836,13 @@ protected function _smushem($leftChar, $rightChar) // This is smushing by universal overlapping if ($leftChar === ' ') { return $rightChar; - } else if ($rightChar === ' ') { + } elseif ($rightChar === ' ') { return $leftChar; - } else if ($leftChar === $this->_hardBlank) { + } elseif ($leftChar === $this->_hardBlank) { return $rightChar; - } else if ($rightChar === $this->_hardBlank) { + } elseif ($rightChar === $this->_hardBlank) { return $rightChar; - } else if ($this->_rightToLeft === 1) { + } elseif ($this->_rightToLeft === 1) { return $leftChar; } else { // Occurs in the absence of above exceptions @@ -878,50 +850,46 @@ protected function _smushem($leftChar, $rightChar) } } - if (($this->_smushMode & self::SM_HARDBLANK) > 0) { - if ($leftChar === $this->_hardBlank && $rightChar === $this->_hardBlank) { - return $leftChar; - } + if (($this->_smushMode & self::SM_HARDBLANK) > 0 && ($leftChar === $this->_hardBlank && $rightChar === $this->_hardBlank)) { + return $leftChar; } if ($leftChar === $this->_hardBlank && $rightChar === $this->_hardBlank) { return null; } - if (($this->_smushMode & self::SM_EQUAL) > 0) { - if ($leftChar === $rightChar) { - return $leftChar; - } + if (($this->_smushMode & self::SM_EQUAL) > 0 && $leftChar === $rightChar) { + return $leftChar; } if (($this->_smushMode & self::SM_LOWLINE) > 0) { - if ($leftChar === '_' && strchr('|/\\[]{}()<>', $rightChar) !== false) { + if ($leftChar === '_' && strstr('|/\\[]{}()<>', $rightChar) !== false) { return $rightChar; - } else if ($rightChar === '_' && strchr('|/\\[]{}()<>', $leftChar) !== false) { + } elseif ($rightChar === '_' && strstr('|/\\[]{}()<>', $leftChar) !== false) { return $leftChar; } } if (($this->_smushMode & self::SM_HIERARCHY) > 0) { - if ($leftChar === '|' && strchr('/\\[]{}()<>', $rightChar) !== false) { + if ($leftChar === '|' && strstr('/\\[]{}()<>', $rightChar) !== false) { return $rightChar; - } else if ($rightChar === '|' && strchr('/\\[]{}()<>', $leftChar) !== false) { + } elseif ($rightChar === '|' && strstr('/\\[]{}()<>', $leftChar) !== false) { return $leftChar; - } else if (strchr('/\\', $leftChar) && strchr('[]{}()<>', $rightChar) !== false) { + } elseif (strstr('/\\', $leftChar) && strstr('[]{}()<>', $rightChar) !== false) { return $rightChar; - } else if (strchr('/\\', $rightChar) && strchr('[]{}()<>', $leftChar) !== false) { + } elseif (strstr('/\\', $rightChar) && strstr('[]{}()<>', $leftChar) !== false) { return $leftChar; - } else if (strchr('[]', $leftChar) && strchr('{}()<>', $rightChar) !== false) { + } elseif (strstr('[]', $leftChar) && strstr('{}()<>', $rightChar) !== false) { return $rightChar; - } else if (strchr('[]', $rightChar) && strchr('{}()<>', $leftChar) !== false) { + } elseif (strstr('[]', $rightChar) && strstr('{}()<>', $leftChar) !== false) { return $leftChar; - } else if (strchr('{}', $leftChar) && strchr('()<>', $rightChar) !== false) { + } elseif (strstr('{}', $leftChar) && strstr('()<>', $rightChar) !== false) { return $rightChar; - } else if (strchr('{}', $rightChar) && strchr('()<>', $leftChar) !== false) { + } elseif (strstr('{}', $rightChar) && strstr('()<>', $leftChar) !== false) { return $leftChar; - } else if (strchr('()', $leftChar) && strchr('<>', $rightChar) !== false) { + } elseif (strstr('()', $leftChar) && strstr('<>', $rightChar) !== false) { return $rightChar; - } else if (strchr('()', $rightChar) && strchr('<>', $leftChar) !== false) { + } elseif (strstr('()', $rightChar) && strstr('<>', $leftChar) !== false) { return $leftChar; } } @@ -929,15 +897,15 @@ protected function _smushem($leftChar, $rightChar) if (($this->_smushMode & self::SM_PAIR) > 0) { if ($leftChar === '[' && $rightChar === ']') { return '|'; - } else if ($rightChar === '[' && $leftChar === ']') { + } elseif ($rightChar === '[' && $leftChar === ']') { return '|'; - } else if ($leftChar === '{' && $rightChar === '}') { + } elseif ($leftChar === '{' && $rightChar === '}') { return '|'; - } else if ($rightChar === '{' && $leftChar === '}') { + } elseif ($rightChar === '{' && $leftChar === '}') { return '|'; - } else if ($leftChar === '(' && $rightChar === ')') { + } elseif ($leftChar === '(' && $rightChar === ')') { return '|'; - } else if ($rightChar === '(' && $leftChar === ')') { + } elseif ($rightChar === '(' && $leftChar === ')') { return '|'; } } @@ -945,9 +913,9 @@ protected function _smushem($leftChar, $rightChar) if (($this->_smushMode & self::SM_BIGX) > 0) { if ($leftChar === '/' && $rightChar === '\\') { return '|'; - } else if ($rightChar === '/' && $leftChar === '\\') { + } elseif ($rightChar === '/' && $leftChar === '\\') { return 'Y'; - } else if ($leftChar === '>' && $rightChar === '<') { + } elseif ($leftChar === '>' && $rightChar === '<') { return 'X'; } } @@ -976,8 +944,7 @@ protected function _loadFont($fontFile) if (substr($fontFile, -3) === '.gz') { if (!function_exists('gzcompress')) { require_once 'Zend/Text/Figlet/Exception.php'; - throw new Zend_Text_Figlet_Exception('GZIP library is required for ' - . 'gzip compressed font files'); + throw new Zend_Text_Figlet_Exception('GZIP library is required for gzip compressed font files'); } $fontFile = 'compress.zlib://' . $fontFile; @@ -1026,11 +993,7 @@ protected function _loadFont($fontFile) if ($numsRead < 7) { if ($smush === 2) { $this->_fontSmush = self::SM_KERN; - } else if ($smush < 0) { - $this->_fontSmush = 0; - } else { - $this->_fontSmush = (($smush & 31) | self::SM_SMUSH); - } + } else $this->_fontSmush = $smush < 0 ? 0 : ($smush & 31) | self::SM_SMUSH; } // Correct char height && maxlength @@ -1089,9 +1052,7 @@ protected function _loadFont($fontFile) // Convert it if required if (substr($uniCode, 0, 2) === '0x') { $uniCode = hexdec(substr($uniCode, 2)); - } else if (substr($uniCode, 0, 1) === '0' and - $uniCode !== '0' or - substr($uniCode, 0, 2) === '-0') { + } elseif (substr($uniCode, 0, 1) === '0' && $uniCode !== '0' || substr($uniCode, 0, 2) === '-0') { $uniCode = octdec($uniCode); } else { $uniCode = (int) $uniCode; @@ -1123,9 +1084,9 @@ protected function _setUsedSmush() { if ($this->_smushOverride === self::SMO_NO) { $this->_smushMode = $this->_fontSmush; - } else if ($this->_smushOverride === self::SMO_YES) { + } elseif ($this->_smushOverride === self::SMO_YES) { $this->_smushMode = $this->_userSmush; - } else if ($this->_smushOverride === self::SMO_FORCE) { + } elseif ($this->_smushOverride === self::SMO_FORCE) { $this->_smushMode = ($this->_fontSmush | $this->_userSmush); } } @@ -1214,18 +1175,14 @@ protected function _uniOrd($c) if ($h <= 0x7F) { $ord = $h; - } else if ($h < 0xC2) { + } elseif ($h < 0xC2) { $ord = 0; - } else if ($h <= 0xDF) { + } elseif ($h <= 0xDF) { $ord = (($h & 0x1F) << 6 | (ord($c[1]) & 0x3F)); - } else if ($h <= 0xEF) { + } elseif ($h <= 0xEF) { $ord = (($h & 0x0F) << 12 | (ord($c[1]) & 0x3F) << 6 | (ord($c[2]) & 0x3F)); - } else if ($h <= 0xF4) { - $ord = (($h & 0x0F) << 18 | (ord($c[1]) & 0x3F) << 12 | - (ord($c[2]) & 0x3F) << 6 | (ord($c[3]) & 0x3F)); - } else { - $ord = 0; - } + } else $ord = $h <= 0xF4 ? ($h & 0x0F) << 18 | (ord($c[1]) & 0x3F) << 12 | + (ord($c[2]) & 0x3F) << 6 | (ord($c[3]) & 0x3F) : 0; return $ord; } diff --git a/library/Zend/Text/MultiByte.php b/library/Zend/Text/MultiByte.php index ad6a916562..b2198dc16e 100644 --- a/library/Zend/Text/MultiByte.php +++ b/library/Zend/Text/MultiByte.php @@ -44,7 +44,7 @@ public static function wordWrap($string, $width = 75, $break = "\n", $cut = fals $stringWidth = iconv_strlen($string, $charset); $breakWidth = iconv_strlen($break, $charset); - if (strlen($string) === 0) { + if ((string) $string === '') { return ''; } elseif ($breakWidth === null) { throw new Zend_Text_Exception('Break string cannot be empty'); @@ -58,11 +58,7 @@ public static function wordWrap($string, $width = 75, $break = "\n", $cut = fals for ($current = 0; $current < $stringWidth; $current++) { $char = iconv_substr($string, $current, 1, $charset); - if ($breakWidth === 1) { - $possibleBreak = $char; - } else { - $possibleBreak = iconv_substr($string, $current, $breakWidth, $charset); - } + $possibleBreak = $breakWidth === 1 ? $char : iconv_substr($string, $current, $breakWidth, $charset); if ($possibleBreak === $break) { $result .= iconv_substr($string, $lastStart, $current - $lastStart + $breakWidth, $charset); @@ -80,7 +76,7 @@ public static function wordWrap($string, $width = 75, $break = "\n", $cut = fals $lastStart = $lastSpace = $current; } elseif ($current - $lastStart >= $width && $lastStart < $lastSpace) { $result .= iconv_substr($string, $lastStart, $lastSpace - $lastStart, $charset) . $break; - $lastStart = $lastSpace = $lastSpace + 1; + $lastStart = $lastSpace += 1; } } diff --git a/library/Zend/Text/Table.php b/library/Zend/Text/Table.php index 9f09802325..b5b87155c8 100644 --- a/library/Zend/Text/Table.php +++ b/library/Zend/Text/Table.php @@ -123,7 +123,7 @@ public function __construct($options = null) // Set options if (is_array($options)) { $this->setOptions($options); - } else if ($options instanceof Zend_Config) { + } elseif ($options instanceof Zend_Config) { $this->setConfig($options); } @@ -187,13 +187,13 @@ public function setConfig(Zend_Config $config) */ public function setColumnWidths(array $columnWidths) { - if (count($columnWidths) === 0) { + if ($columnWidths === []) { require_once 'Zend/Text/Table/Exception.php'; throw new Zend_Text_Table_Exception('You must supply at least one column'); } foreach ($columnWidths as $columnNum => $columnWidth) { - if (is_int($columnWidth) === false or $columnWidth < 1) { + if (!is_int($columnWidth) || $columnWidth < 1) { require_once 'Zend/Text/Table/Exception.php'; throw new Zend_Text_Table_Exception('Column ' . $columnNum . ' has an invalid' . ' column width'); @@ -347,11 +347,7 @@ public function appendRow($row) $row = new Zend_Text_Table_Row(); $colNum = 0; foreach ($data as $columnData) { - if (isset($this->_defaultColumnAligns[$colNum])) { - $align = $this->_defaultColumnAligns[$colNum]; - } else { - $align = null; - } + $align = isset($this->_defaultColumnAligns[$colNum]) ? $this->_defaultColumnAligns[$colNum] : null; $row->appendColumn(new Zend_Text_Table_Column($columnData, $align)); $colNum++; @@ -372,7 +368,7 @@ public function appendRow($row) public function render() { // There should be at least one row - if (count($this->_rows) === 0) { + if ($this->_rows === []) { require_once 'Zend/Text/Table/Exception.php'; throw new Zend_Text_Table_Exception('No rows were added to the table yet'); } @@ -387,7 +383,7 @@ public function render() $numRows = count($this->_rows); foreach ($this->_rows as $rowNum => $row) { // Get all column widths - if (isset($columnWidths) === true) { + if (isset($columnWidths)) { $lastColumnWidths = $columnWidths; } @@ -414,15 +410,11 @@ public function render() $result .= "\n"; } else { // Else check if we have to draw the row separator - if ($this->_autoSeparate & self::AUTO_SEPARATE_ALL) { - $drawSeparator = true; - } else if ($rowNum === 1 && $this->_autoSeparate & self::AUTO_SEPARATE_HEADER) { + if (($this->_autoSeparate & self::AUTO_SEPARATE_ALL) !== 0) { $drawSeparator = true; - } else if ($rowNum === ($numRows - 1) && $this->_autoSeparate & self::AUTO_SEPARATE_FOOTER) { + } elseif ($rowNum === 1 && $this->_autoSeparate & self::AUTO_SEPARATE_HEADER) { $drawSeparator = true; - } else { - $drawSeparator = false; - } + } else $drawSeparator = $rowNum === ($numRows - 1) && $this->_autoSeparate & self::AUTO_SEPARATE_FOOTER; if ($drawSeparator) { $result .= $this->_decorator->getVerticalRight(); diff --git a/library/Zend/Text/Table/Column.php b/library/Zend/Text/Table/Column.php index cd1547062a..b0b3a3f57e 100644 --- a/library/Zend/Text/Table/Column.php +++ b/library/Zend/Text/Table/Column.php @@ -111,24 +111,18 @@ public function __construct($content = null, $align = null, $colSpan = null, $ch */ public function setContent($content, $charset = null) { - if (is_string($content) === false) { + if (!is_string($content)) { require_once 'Zend/Text/Table/Exception.php'; throw new Zend_Text_Table_Exception('$content must be a string'); } - if ($charset === null) { - $inputCharset = Zend_Text_Table::getInputCharset(); - } else { - $inputCharset = strtolower($charset); - } + $inputCharset = $charset === null ? Zend_Text_Table::getInputCharset() : strtolower($charset); $outputCharset = Zend_Text_Table::getOutputCharset(); - if ($inputCharset !== $outputCharset) { - if (PHP_OS !== 'AIX') { - // AIX does not understand these character sets - $content = iconv($inputCharset, $outputCharset, $content); - } + if ($inputCharset !== $outputCharset && PHP_OS !== 'AIX') { + // AIX does not understand these character sets + $content = iconv($inputCharset, $outputCharset, $content); } @@ -146,7 +140,7 @@ public function setContent($content, $charset = null) */ public function setAlign($align) { - if (in_array($align, $this->_allowedAligns) === false) { + if (!in_array($align, $this->_allowedAligns)) { require_once 'Zend/Text/Table/Exception.php'; throw new Zend_Text_Table_Exception('Invalid align supplied'); } @@ -165,7 +159,7 @@ public function setAlign($align) */ public function setColSpan($colSpan) { - if (is_int($colSpan) === false or $colSpan < 1) { + if (!is_int($colSpan) || $colSpan < 1) { require_once 'Zend/Text/Table/Exception.php'; throw new Zend_Text_Table_Exception('$colSpan must be an integer and greater than 0'); } @@ -196,7 +190,7 @@ public function getColSpan() */ public function render($columnWidth, $padding = 0) { - if (is_int($columnWidth) === false or $columnWidth < 1) { + if (!is_int($columnWidth) || $columnWidth < 1) { require_once 'Zend/Text/Table/Exception.php'; throw new Zend_Text_Table_Exception('$columnWidth must be an integer and greater than 0'); } @@ -236,8 +230,6 @@ public function render($columnWidth, $padding = 0) . str_repeat(' ', $padding); } - $result = implode("\n", $paddedLines); - - return $result; + return implode("\n", $paddedLines); } } diff --git a/library/Zend/Text/Table/Decorator/Unicode.php b/library/Zend/Text/Table/Decorator/Unicode.php index e736afdd11..795a0bf36f 100644 --- a/library/Zend/Text/Table/Decorator/Unicode.php +++ b/library/Zend/Text/Table/Decorator/Unicode.php @@ -155,14 +155,14 @@ protected function _uniChar($code) { if ($code <= 0x7F) { $char = chr($code); - } else if ($code <= 0x7FF) { + } elseif ($code <= 0x7FF) { $char = chr(0xC0 | $code >> 6) . chr(0x80 | $code & 0x3F); - } else if ($code <= 0xFFFF) { + } elseif ($code <= 0xFFFF) { $char = chr(0xE0 | $code >> 12) . chr(0x80 | $code >> 6 & 0x3F) . chr(0x80 | $code & 0x3F); - } else if ($code <= 0x10FFFF) { + } elseif ($code <= 0x10FFFF) { $char = chr(0xF0 | $code >> 18) . chr(0x80 | $code >> 12 & 0x3F) . chr(0x80 | $code >> 6 & 0x3F) diff --git a/library/Zend/Text/Table/Row.php b/library/Zend/Text/Table/Row.php index e8cc195d71..0e49e92b51 100644 --- a/library/Zend/Text/Table/Row.php +++ b/library/Zend/Text/Table/Row.php @@ -143,7 +143,7 @@ public function render(array $columnWidths, // If there is no single column, create a column which spans over the // entire row - if (count($this->_columns) === 0) { + if ($this->_columns === []) { require_once 'Zend/Text/Table/Column.php'; $this->appendColumn(new Zend_Text_Table_Column(null, null, count($columnWidths))); } @@ -198,7 +198,7 @@ public function render(array $columnWidths, $result .= $decorator->getVertical(); foreach ($renderedColumns as $index => $renderedColumn) { - if (isset($renderedColumn[$line]) === true) { + if (isset($renderedColumn[$line])) { $result .= $renderedColumn[$line]; } else { $result .= str_repeat(' ', $this->_columnWidths[$index]); diff --git a/library/Zend/TimeSync.php b/library/Zend/TimeSync.php index bf56fe25a0..30d26923b0 100644 --- a/library/Zend/TimeSync.php +++ b/library/Zend/TimeSync.php @@ -161,7 +161,7 @@ public static function setOptions(array $options) */ public function setServer($alias) { - if (isset($this->_timeservers[$alias]) === true) { + if (isset($this->_timeservers[$alias])) { $this->_current = $this->_timeservers[$alias]; } else { require_once 'Zend/TimeSync/Exception.php'; @@ -182,7 +182,7 @@ public static function getOptions($key = null) return Zend_TimeSync::$options; } - if (isset(Zend_TimeSync::$options[$key]) === true) { + if (isset(Zend_TimeSync::$options[$key])) { return Zend_TimeSync::$options[$key]; } else { require_once 'Zend/TimeSync/Exception.php'; @@ -201,14 +201,14 @@ public static function getOptions($key = null) public function getServer($alias = null) { if ($alias === null) { - if (isset($this->_current) && $this->_current !== false) { + if ($this->_current !== null && $this->_current !== false) { return $this->_current; } else { require_once 'Zend/TimeSync/Exception.php'; throw new Zend_TimeSync_Exception('there is no timeserver set'); } } - if (isset($this->_timeservers[$alias]) === true) { + if (isset($this->_timeservers[$alias])) { return $this->_timeservers[$alias]; } else { require_once 'Zend/TimeSync/Exception.php'; @@ -273,10 +273,10 @@ protected function _addServer($target, $alias) if ($pos = strrpos($adress, ':')) { $posbr = strpos($adress, ']'); - if ($posbr and ($pos > $posbr)) { + if ($posbr && $pos > $posbr) { $port = substr($adress, $pos + 1); $adress = substr($adress, 0, $pos); - } else if (!$posbr and $pos) { + } elseif (!$posbr && $pos) { $port = substr($adress, $pos + 1); $adress = substr($adress, 0, $pos); } else { diff --git a/library/Zend/TimeSync/Ntp.php b/library/Zend/TimeSync/Ntp.php index a0f26b43a9..77325e1e7f 100644 --- a/library/Zend/TimeSync/Ntp.php +++ b/library/Zend/TimeSync/Ntp.php @@ -206,7 +206,7 @@ protected function _read() $flags = ord(fread($this->_socket, 1)); $info = stream_get_meta_data($this->_socket); - if ($info['timed_out'] === true) { + if ($info['timed_out']) { fclose($this->_socket); throw new Zend_TimeSync_Exception('could not connect to ' . "'$this->_timeserver' on port '$this->_port', reason: 'server timed out'"); @@ -331,11 +331,11 @@ protected function _extract($binary) case 0: if (substr($refid, 0, 3) === 'DCN') { $ntpserviceid = 'DCN routing protocol'; - } else if (substr($refid, 0, 4) === 'NIST') { + } elseif (substr($refid, 0, 4) === 'NIST') { $ntpserviceid = 'NIST public modem'; - } else if (substr($refid, 0, 3) === 'TSP') { + } elseif (substr($refid, 0, 3) === 'TSP') { $ntpserviceid = 'TSP time protocol'; - } else if (substr($refid, 0, 3) === 'DTS') { + } elseif (substr($refid, 0, 3) === 'DTS') { $ntpserviceid = 'Digital Time Service'; } break; @@ -343,15 +343,15 @@ protected function _extract($binary) case 1: if (substr($refid, 0, 4) === 'ATOM') { $ntpserviceid = 'Atomic Clock (calibrated)'; - } else if (substr($refid, 0, 3) === 'VLF') { + } elseif (substr($refid, 0, 3) === 'VLF') { $ntpserviceid = 'VLF radio'; - } else if ($refid === 'CALLSIGN') { + } elseif ($refid === 'CALLSIGN') { $ntpserviceid = 'Generic radio'; - } else if (substr($refid, 0, 4) === 'LORC') { + } elseif (substr($refid, 0, 4) === 'LORC') { $ntpserviceid = 'LORAN-C radionavigation'; - } else if (substr($refid, 0, 4) === 'GOES') { + } elseif (substr($refid, 0, 4) === 'GOES') { $ntpserviceid = 'GOES UHF environment satellite'; - } else if (substr($refid, 0, 3) === 'GPS') { + } elseif (substr($refid, 0, 3) === 'GPS') { $ntpserviceid = 'GPS UHF satellite positioning'; } break; @@ -424,8 +424,7 @@ protected function _extract($binary) $this->_info['offset'] += $binary['transmitstamp']; $this->_info['offset'] -= $binary['clientreceived']; $this->_info['offset'] /= 2; - $time = (time() - $this->_info['offset']); - return $time; + return time() - $this->_info['offset']; } } diff --git a/library/Zend/TimeSync/Protocol.php b/library/Zend/TimeSync/Protocol.php index 12dc6d9f9e..b562358467 100644 --- a/library/Zend/TimeSync/Protocol.php +++ b/library/Zend/TimeSync/Protocol.php @@ -29,6 +29,7 @@ */ abstract class Zend_TimeSync_Protocol { + public $_port; /** * Holds the current socket connection * @@ -123,7 +124,7 @@ protected function _disconnect() */ public function getInfo() { - if (empty($this->_info) === true) { + if (empty($this->_info)) { $this->_write($this->_prepare()); $timestamp = $this->_extract($this->_read()); } @@ -141,8 +142,6 @@ public function getDate($locale = null) { $this->_write($this->_prepare()); $timestamp = $this->_extract($this->_read()); - - $date = new Zend_Date($this, null, $locale); - return $date; + return new Zend_Date($this, null, $locale); } } diff --git a/library/Zend/TimeSync/Sntp.php b/library/Zend/TimeSync/Sntp.php index e49d929324..13a6c8a52c 100644 --- a/library/Zend/TimeSync/Sntp.php +++ b/library/Zend/TimeSync/Sntp.php @@ -95,7 +95,7 @@ protected function _write($data) { $this->_connect(); $this->_delay = time(); - fputs($this->_socket, $data); + fwrite($this->_socket, $data); } /** diff --git a/library/Zend/Tool/Framework/Action/Base.php b/library/Zend/Tool/Framework/Action/Base.php index 817c06c998..15a845e147 100644 --- a/library/Zend/Tool/Framework/Action/Base.php +++ b/library/Zend/Tool/Framework/Action/Base.php @@ -88,8 +88,7 @@ public function getName() protected function _parseName() { $className = get_class($this); - $actionName = substr($className, strrpos($className, '_')+1); - return $actionName; + return substr($className, strrpos($className, '_')+1); } } diff --git a/library/Zend/Tool/Framework/Client/Config.php b/library/Zend/Tool/Framework/Client/Config.php index 4cc726e783..20b8efb076 100644 --- a/library/Zend/Tool/Framework/Client/Config.php +++ b/library/Zend/Tool/Framework/Client/Config.php @@ -41,7 +41,7 @@ class Zend_Tool_Framework_Client_Config */ public function __config($options = array()) { - if ($options) { + if ($options !== []) { $this->setOptions($options); } } diff --git a/library/Zend/Tool/Framework/Client/Console.php b/library/Zend/Tool/Framework/Client/Console.php index ed4338a601..5fb3cc9788 100644 --- a/library/Zend/Tool/Framework/Client/Console.php +++ b/library/Zend/Tool/Framework/Client/Console.php @@ -163,9 +163,9 @@ protected function _preInit() } // add classes to the basic loader from the config file basicloader.classes.1 .. - if (isset($config->basicloader) && isset($config->basicloader->classes)) { + if (property_exists($config, 'basicloader') && $config->basicloader !== null && (property_exists($config->basicloader, 'classes') && $config->basicloader->classes !== null)) { foreach ($config->basicloader->classes as $classKey => $className) { - array_push($classesToLoad, $className); + $classesToLoad[] = $className; } } diff --git a/library/Zend/Tool/Framework/Client/Console/ArgumentParser.php b/library/Zend/Tool/Framework/Client/Console/ArgumentParser.php index 373ccc62c9..1521bda13e 100644 --- a/library/Zend/Tool/Framework/Client/Console/ArgumentParser.php +++ b/library/Zend/Tool/Framework/Client/Console/ArgumentParser.php @@ -462,7 +462,7 @@ protected function _parseProviderOptionsPart() } - if (!$getoptOptions) { + if ($getoptOptions === []) { // no options to parse here, return return; } @@ -471,7 +471,7 @@ protected function _parseProviderOptionsPart() $wordStack = array(); while (($wordOnTop = array_shift($this->_argumentsWorking))) { if (substr($wordOnTop, 0, 1) != '-') { - array_push($wordStack, $wordOnTop); + $wordStack[] = $wordOnTop; } else { // put word back on stack and move on array_unshift($this->_argumentsWorking, $wordOnTop); @@ -487,7 +487,8 @@ protected function _parseProviderOptionsPart() } if ($wordStack && $wordArguments) { - for ($wordIndex = 1; $wordIndex <= count($wordArguments); $wordIndex++) { + $wordArgumentsCount = count($wordArguments); + for ($wordIndex = 1; $wordIndex <= $wordArgumentsCount; $wordIndex++) { if (!array_key_exists($wordIndex-1, $wordStack) || !array_key_exists($wordIndex, $wordArguments)) { break; } diff --git a/library/Zend/Tool/Framework/Client/Console/HelpSystem.php b/library/Zend/Tool/Framework/Client/Console/HelpSystem.php index 42edea90b9..a97be738c3 100644 --- a/library/Zend/Tool/Framework/Client/Console/HelpSystem.php +++ b/library/Zend/Tool/Framework/Client/Console/HelpSystem.php @@ -202,8 +202,8 @@ protected function _respondWithSystemInformation($providerNameFilter = null, $ac $displayActionMetadatas = $manifest->getMetadatas($actionMetadatasSearch); // create index of actionNames - for ($i = 0; $i < count($displayActionMetadatas); $i++) { - $displayActionNames[] = $displayActionMetadatas[$i]->getActionName(); + foreach ($displayActionMetadatas as $i => $displayActionMetadata) { + $displayActionNames[] = $displayActionMetadata->getActionName(); } foreach ($displayProviderMetadatas as $providerMetadata) { diff --git a/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/AlignCenter.php b/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/AlignCenter.php index 09285d24e6..3a1d087bc5 100644 --- a/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/AlignCenter.php +++ b/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/AlignCenter.php @@ -53,7 +53,7 @@ public function decorate($content, $lineLength) $len = strlen($content); for($i = $len; $i < $lineLength; $i++) { if($append == true) { - $content = $content." "; + $content .= " "; $append = false; } else { $content = " ".$content; diff --git a/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/Blockize.php b/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/Blockize.php index a116bf5ab7..e1eb44af4e 100644 --- a/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/Blockize.php +++ b/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/Blockize.php @@ -47,7 +47,7 @@ public function getName() */ public function decorate($content, $lineLength) { - if(intval(strval($lineLength)) != $lineLength) { + if((int) strval($lineLength) !== $lineLength) { $lineLength = 72; } diff --git a/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/Colorizer.php b/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/Colorizer.php index 5d83feaee1..27c4eb6ab3 100644 --- a/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/Colorizer.php +++ b/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/Colorizer.php @@ -83,9 +83,7 @@ public function decorate($content, $color) } } - $newContent .= $content . "\033[m"; - - return $newContent; + return $newContent . ($content . "\033[m"); } diff --git a/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/Indention.php b/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/Indention.php index a1372af97e..8b7726df57 100644 --- a/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/Indention.php +++ b/library/Zend/Tool/Framework/Client/Console/ResponseDecorator/Indention.php @@ -41,7 +41,7 @@ public function getName() */ public function decorate($content, $indention) { - if(strval(intval($indention)) != $indention) { + if(strval((int) $indention) != $indention) { return $content; } diff --git a/library/Zend/Tool/Framework/Client/Response.php b/library/Zend/Tool/Framework/Client/Response.php index 97998da891..17ff128718 100644 --- a/library/Zend/Tool/Framework/Client/Response.php +++ b/library/Zend/Tool/Framework/Client/Response.php @@ -137,7 +137,7 @@ public function getContent() */ public function isException() { - return isset($this->_exception); + return $this->_exception !== null; } /** @@ -208,7 +208,7 @@ protected function _applyDecorators($content, Array $decoratorOptions) $options = array_change_key_case($options, CASE_LOWER); - if ($options) { + if ($options !== []) { foreach ($this->_decorators as $decoratorName => $decorator) { if (array_key_exists($decoratorName, $options)) { $content = $decorator->decorate($content, $options[$decoratorName]); diff --git a/library/Zend/Tool/Framework/Client/Response/ContentDecorator/Separator.php b/library/Zend/Tool/Framework/Client/Response/ContentDecorator/Separator.php index b6aa34fe8d..84d9cf80e9 100644 --- a/library/Zend/Tool/Framework/Client/Response/ContentDecorator/Separator.php +++ b/library/Zend/Tool/Framework/Client/Response/ContentDecorator/Separator.php @@ -75,7 +75,7 @@ public function getSeparator() public function decorate($content, $decoratorValue) { $run = 1; - if (is_bool($decoratorValue) && $decoratorValue === false) { + if (is_bool($decoratorValue) && !$decoratorValue) { return $content; } diff --git a/library/Zend/Tool/Framework/Loader/IncludePathLoader.php b/library/Zend/Tool/Framework/Loader/IncludePathLoader.php index 237483538c..f290e24bda 100644 --- a/library/Zend/Tool/Framework/Loader/IncludePathLoader.php +++ b/library/Zend/Tool/Framework/Loader/IncludePathLoader.php @@ -68,7 +68,7 @@ protected function _getFiles() // ensure that we only traverse a single version of Zend Framework on all include paths if (file_exists($realIncludePath . '/Zend/Tool/Framework/Loader/IncludePathLoader.php')) { - if ($isZendTraversed === false) { + if (!$isZendTraversed) { $isZendTraversed = true; } else { // use the deny directory pattern that includes the path to 'Zend', it will not be accepted diff --git a/library/Zend/Tool/Framework/Loader/IncludePathLoader/RecursiveFilterIterator.php b/library/Zend/Tool/Framework/Loader/IncludePathLoader/RecursiveFilterIterator.php index e0dc82ba5d..51195af7bc 100644 --- a/library/Zend/Tool/Framework/Loader/IncludePathLoader/RecursiveFilterIterator.php +++ b/library/Zend/Tool/Framework/Loader/IncludePathLoader/RecursiveFilterIterator.php @@ -29,6 +29,10 @@ class Zend_Tool_Framework_Loader_IncludePathLoader_RecursiveFilterIterator extends RecursiveFilterIterator { + /** + * @var mixed|\ReflectionClass + */ + public $ref; protected $_denyDirectoryPattern = null; protected $_acceptFilePattern = null; @@ -63,7 +67,7 @@ public function accept() } // if the file matches the accept file pattern, accept - $acceptable = (preg_match('#' . $this->_acceptFilePattern . '#', (string) $currentNodeRealPath)) ? true : false; + $acceptable = (bool) preg_match('#' . $this->_acceptFilePattern . '#', (string) $currentNodeRealPath); return $acceptable; } diff --git a/library/Zend/Tool/Framework/Metadata/Basic.php b/library/Zend/Tool/Framework/Metadata/Basic.php index 4e59a9812b..46e5f816b7 100644 --- a/library/Zend/Tool/Framework/Metadata/Basic.php +++ b/library/Zend/Tool/Framework/Metadata/Basic.php @@ -67,7 +67,7 @@ class Zend_Tool_Framework_Metadata_Basic */ public function __construct(Array $options = array()) { - if ($options) { + if ($options !== []) { $this->setOptions($options); } } diff --git a/library/Zend/Tool/Framework/Metadata/Tool.php b/library/Zend/Tool/Framework/Metadata/Tool.php index 24c73c63cb..31d8898a5d 100644 --- a/library/Zend/Tool/Framework/Metadata/Tool.php +++ b/library/Zend/Tool/Framework/Metadata/Tool.php @@ -207,12 +207,11 @@ public function getProviderReference() public function __toString() { $string = parent::__toString(); - $string .= ' (ProviderName: ' . $this->_providerName + + return $string . (' (ProviderName: ' . $this->_providerName . ', ActionName: ' . $this->_actionName . ', SpecialtyName: ' . $this->_specialtyName - . ')'; - - return $string; + . ')'); } } diff --git a/library/Zend/Tool/Framework/Provider/Repository.php b/library/Zend/Tool/Framework/Provider/Repository.php index b5aa53d35a..3cf8ea7979 100644 --- a/library/Zend/Tool/Framework/Provider/Repository.php +++ b/library/Zend/Tool/Framework/Provider/Repository.php @@ -101,11 +101,7 @@ public function addProvider(Zend_Tool_Framework_Provider_Interface $provider, $o $provider->setRegistry($this->_registry); } - if (method_exists($provider, 'getName')) { - $providerName = $provider->getName(); - } else { - $providerName = $this->_parseName($provider); - } + $providerName = method_exists($provider, 'getName') ? $provider->getName() : $this->_parseName($provider); // if a provider by the given name already exist, and its not set as overwritable, throw exception if (!$overwriteExistingProvider && diff --git a/library/Zend/Tool/Framework/Provider/Signature.php b/library/Zend/Tool/Framework/Provider/Signature.php index 3dd2e3e9e7..438ce5b8bb 100644 --- a/library/Zend/Tool/Framework/Provider/Signature.php +++ b/library/Zend/Tool/Framework/Provider/Signature.php @@ -365,7 +365,8 @@ protected function _processActionableMethods() if (($docComment = $method->getDocComment()) != '' && (preg_match_all('/@param\s+(\w+)+\s+(\$\S+)\s+(.*?)(?=(?:\*\s*@)|(?:\*\/))/s', (string) $docComment, $matches))) { - for ($i=0; $i <= count($matches[0])-1; $i++) { + $itemsCount = count($matches[0]); + for ($i=0; $i <= $itemsCount-1; $i++) { $currentParam = ltrim($matches[2][$i], '$'); if ($currentParam != '' && isset($parameterInfo[$currentParam])) { diff --git a/library/Zend/Tool/Framework/System/Manifest.php b/library/Zend/Tool/Framework/System/Manifest.php index 632b549e34..595a546e1c 100644 --- a/library/Zend/Tool/Framework/System/Manifest.php +++ b/library/Zend/Tool/Framework/System/Manifest.php @@ -41,23 +41,19 @@ class Zend_Tool_Framework_System_Manifest public function getProviders() { - $providers = array( + return array( new Zend_Tool_Framework_System_Provider_Version(), new Zend_Tool_Framework_System_Provider_Config(), new Zend_Tool_Framework_System_Provider_Phpinfo(), new Zend_Tool_Framework_System_Provider_Manifest() ); - - return $providers; } public function getActions() { - $actions = array( + return array( new Zend_Tool_Framework_System_Action_Create(), new Zend_Tool_Framework_System_Action_Delete() ); - - return $actions; } } diff --git a/library/Zend/Tool/Framework/System/Provider/Config.php b/library/Zend/Tool/Framework/System/Provider/Config.php index 685a60789f..69e7b68f9e 100644 --- a/library/Zend/Tool/Framework/System/Provider/Config.php +++ b/library/Zend/Tool/Framework/System/Provider/Config.php @@ -129,7 +129,7 @@ public function show() $tree = ""; foreach($configArray AS $k => $v) { $i++; - $tree .= $this->_printTree($k, $v, 1, count($configArray)==$i); + $tree .= $this->_printTree($k, $v, 1, count($configArray) === $i); } $resp->appendContent("User Configuration: ".$userConfig->getConfigFilepath(), array("color" => "green")); $resp->appendContent($tree, array("indention" => 2)); @@ -154,11 +154,7 @@ protected function _printTree($key, $value, $level=1, $isLast=false) $prefix .= "| "; } } - if ($isLast) { - $pointer = "`-- "; - } else { - $pointer = "|-- "; - } + $pointer = $isLast ? "`-- " : "|-- "; $tree = ""; if (is_array($value)) { @@ -211,20 +207,16 @@ protected function _doEnable($className) $userConfig = $this->_loadUserConfigIfExists(); - if (!isset($userConfig->basicloader)) { + if (!(property_exists($userConfig, 'basicloader') && $userConfig->basicloader !== null)) { $userConfig->basicloader = array(); } - if (!isset($userConfig->basicloader->classes)) { + if (!(property_exists($userConfig->basicloader, 'classes') && $userConfig->basicloader->classes !== null)) { $userConfig->basicloader->classes = array(); } $providerClasses = $userConfig->basicloader->classes->toArray(); if (!in_array($className, $providerClasses)) { - if (count($providerClasses)) { - $pos = max(array_keys($providerClasses))+1; - } else { - $pos = 0; - } + $pos = count($providerClasses) > 0 ? max(array_keys($providerClasses))+1 : 0; $userConfig->basicloader->classes->$pos = $className; if ($userConfig->save()) { @@ -275,10 +267,10 @@ public function disableProvider($className) { $userConfig = $this->_loadUserConfigIfExists(); - if (!isset($userConfig->basicloader)) { + if (!(property_exists($userConfig, 'basicloader') && $userConfig->basicloader !== null)) { $userConfig->basicloader = array(); } - if (!isset($userConfig->basicloader->classes)) { + if (!(property_exists($userConfig->basicloader, 'classes') && $userConfig->basicloader->classes !== null)) { $userConfig->basicloader->classes = array(); } diff --git a/library/Zend/Tool/Framework/System/Provider/Manifest.php b/library/Zend/Tool/Framework/System/Provider/Manifest.php index 83f903523f..e6d40f96e0 100644 --- a/library/Zend/Tool/Framework/System/Provider/Manifest.php +++ b/library/Zend/Tool/Framework/System/Provider/Manifest.php @@ -40,6 +40,10 @@ class Zend_Tool_Framework_System_Provider_Manifest implements Zend_Tool_Framework_Provider_Interface, Zend_Tool_Framework_Registry_EnabledInterface { + /** + * @var mixed|\Zend_Tool_Framework_Registry_Interface + */ + public $_registry; public function setRegistry(Zend_Tool_Framework_Registry_Interface $registry) { $this->_registry = $registry; @@ -66,11 +70,7 @@ public function show() $metadataName = $metadata->getName(); $metadataAttrs = $metadata->getAttributes('attributesParent'); - if (!$metadataAttrs) { - $metadataAttrs = '(None)'; - } else { - $metadataAttrs = urldecode(http_build_query($metadataAttrs, null, ', ')); - } + $metadataAttrs = $metadataAttrs ? urldecode(http_build_query($metadataAttrs, null, ', ')) : '(None)'; if (!array_key_exists($metadataType, $metadataTree)) { $metadataTree[$metadataType] = array(); @@ -87,7 +87,7 @@ public function show() $longestAttrNameLen = (strlen($metadataAttrs) > $longestAttrNameLen) ? strlen($metadataAttrs) : $longestAttrNameLen; $metadataValue = $metadata->getValue(); - if (is_array($metadataValue) && count($metadataValue) > 0) { + if (is_array($metadataValue) && $metadataValue !== []) { $metadataValue = urldecode(http_build_query($metadataValue, null, ', ')); } elseif (is_array($metadataValue)) { $metadataValue = '(empty array)'; diff --git a/library/Zend/Tool/Project/Context/Content/Engine/Phtml.php b/library/Zend/Tool/Project/Context/Content/Engine/Phtml.php index 7a7cbef0a2..485f017453 100644 --- a/library/Zend/Tool/Project/Context/Content/Engine/Phtml.php +++ b/library/Zend/Tool/Project/Context/Content/Engine/Phtml.php @@ -81,9 +81,8 @@ public function getContent(Zend_Tool_Project_Context_Interface $context, $method ob_start(); include $streamUri; - $content = ob_get_clean(); - return $content; + return ob_get_clean(); } } diff --git a/library/Zend/Tool/Project/Context/Filesystem/Abstract.php b/library/Zend/Tool/Project/Context/Filesystem/Abstract.php index 23e2d8aab4..7b6a3edb11 100644 --- a/library/Zend/Tool/Project/Context/Filesystem/Abstract.php +++ b/library/Zend/Tool/Project/Context/Filesystem/Abstract.php @@ -130,7 +130,7 @@ public function getFilesystemName() public function getPath() { $path = $this->_baseDirectory; - if ($this->_filesystemName) { + if ($this->_filesystemName !== '' && $this->_filesystemName !== '0') { $path .= '/' . $this->_filesystemName; } return $path; diff --git a/library/Zend/Tool/Project/Context/Filesystem/Directory.php b/library/Zend/Tool/Project/Context/Filesystem/Directory.php index 12e9435b35..98582d0370 100644 --- a/library/Zend/Tool/Project/Context/Filesystem/Directory.php +++ b/library/Zend/Tool/Project/Context/Filesystem/Directory.php @@ -57,11 +57,9 @@ public function getName() public function create() { // check to ensure the parent exists, if not, call it and create it - if (($parentResource = $this->_resource->getParentResource()) instanceof Zend_Tool_Project_Profile_Resource) { - if ((($parentContext = $parentResource->getContext()) instanceof Zend_Tool_Project_Context_Filesystem_Abstract) - && (!$parentContext->exists())) { - $parentResource->create(); - } + if (($parentResource = $this->_resource->getParentResource()) instanceof Zend_Tool_Project_Profile_Resource && ((($parentContext = $parentResource->getContext()) instanceof Zend_Tool_Project_Context_Filesystem_Abstract) + && (!$parentContext->exists()))) { + $parentResource->create(); } if (!file_exists($this->getPath())) { diff --git a/library/Zend/Tool/Project/Context/Filesystem/File.php b/library/Zend/Tool/Project/Context/Filesystem/File.php index 645a4b7634..da354be1a3 100644 --- a/library/Zend/Tool/Project/Context/Filesystem/File.php +++ b/library/Zend/Tool/Project/Context/Filesystem/File.php @@ -120,11 +120,9 @@ public function getResource() public function create() { // check to ensure the parent exists, if not, call it and create it - if (($parentResource = $this->_resource->getParentResource()) instanceof Zend_Tool_Project_Profile_Resource) { - if ((($parentContext = $parentResource->getContext()) instanceof Zend_Tool_Project_Context_Filesystem_Abstract) - && (!$parentContext->exists())) { - $parentResource->create(); - } + if (($parentResource = $this->_resource->getParentResource()) instanceof Zend_Tool_Project_Profile_Resource && ((($parentContext = $parentResource->getContext()) instanceof Zend_Tool_Project_Context_Filesystem_Abstract) + && (!$parentContext->exists()))) { + $parentResource->create(); } diff --git a/library/Zend/Tool/Project/Context/Repository.php b/library/Zend/Tool/Project/Context/Repository.php index 8a9d8f4c18..958e71b299 100644 --- a/library/Zend/Tool/Project/Context/Repository.php +++ b/library/Zend/Tool/Project/Context/Repository.php @@ -107,7 +107,7 @@ public function addContext(Zend_Tool_Project_Context_Interface $context) $isTopLevel = ($context instanceof Zend_Tool_Project_Context_System_TopLevelRestrictable); $isOverwritable = !($context instanceof Zend_Tool_Project_Context_System_NotOverwritable); - $index = (count($this->_contexts)) ? max(array_keys($this->_contexts)) + 1 : 1; + $index = (count($this->_contexts) > 0) ? max(array_keys($this->_contexts)) + 1 : 1; $normalName = $this->_normalizeName($context->getName()); @@ -142,7 +142,7 @@ public function getContext($name) public function hasContext($name) { $name = $this->_normalizeName($name); - return (isset($this->_shortContextNames[$name]) ? true : false); + return (isset($this->_shortContextNames[$name])); } public function isSystemContext($name) diff --git a/library/Zend/Tool/Project/Context/System/ProjectProfileFile.php b/library/Zend/Tool/Project/Context/System/ProjectProfileFile.php index dfaa573afa..d9556d9575 100644 --- a/library/Zend/Tool/Project/Context/System/ProjectProfileFile.php +++ b/library/Zend/Tool/Project/Context/System/ProjectProfileFile.php @@ -111,8 +111,7 @@ public function getContents() { $parser = new Zend_Tool_Project_Profile_FileParser_Xml(); $profile = $this->_resource->getProfile(); - $xml = $parser->serialize($profile); - return $xml; + return $parser->serialize($profile); } } diff --git a/library/Zend/Tool/Project/Context/Zf/AbstractClassFile.php b/library/Zend/Tool/Project/Context/Zf/AbstractClassFile.php index dc58b24192..0d13ed6ad0 100644 --- a/library/Zend/Tool/Project/Context/Zf/AbstractClassFile.php +++ b/library/Zend/Tool/Project/Context/Zf/AbstractClassFile.php @@ -76,9 +76,8 @@ public function getFullClassName($localClassName, $classContextName = null) if ($classContextName) { $fullClassName .= rtrim($classContextName, '_') . '_'; } - $fullClassName .= $localClassName; - return $fullClassName; + return $fullClassName . $localClassName; } } diff --git a/library/Zend/Tool/Project/Context/Zf/ActionMethod.php b/library/Zend/Tool/Project/Context/Zf/ActionMethod.php index 0ff7a95399..45bade147d 100644 --- a/library/Zend/Tool/Project/Context/Zf/ActionMethod.php +++ b/library/Zend/Tool/Project/Context/Zf/ActionMethod.php @@ -159,7 +159,7 @@ public function getActionName() */ public function create() { - if (self::createActionMethod($this->_controllerPath, $this->_actionName) === false) { + if (!self::createActionMethod($this->_controllerPath, $this->_actionName)) { require_once 'Zend/Tool/Project/Context/Exception.php'; throw new Zend_Tool_Project_Context_Exception( 'Could not create action within controller ' . $this->_controllerPath diff --git a/library/Zend/Tool/Project/Context/Zf/ApplicationConfigFile.php b/library/Zend/Tool/Project/Context/Zf/ApplicationConfigFile.php index 488d354f54..dbdc48a771 100644 --- a/library/Zend/Tool/Project/Context/Zf/ApplicationConfigFile.php +++ b/library/Zend/Tool/Project/Context/Zf/ApplicationConfigFile.php @@ -39,6 +39,10 @@ class Zend_Tool_Project_Context_Zf_ApplicationConfigFile extends Zend_Tool_Project_Context_Filesystem_File { + /** + * @var mixed|\Zend_Tool_Project_Profile_Resource_Container + */ + public $_type; /** * @var string */ @@ -89,11 +93,7 @@ public function getPersistentAttributes() public function getContents() { if ($this->_content === null) { - if (file_exists($this->getPath())) { - $this->_content = file_get_contents($this->getPath()); - } else { - $this->_content = $this->_getDefaultContents(); - } + $this->_content = file_exists($this->getPath()) ? file_get_contents($this->getPath()) : $this->_getDefaultContents(); } @@ -118,7 +118,7 @@ public function addStringItem($key, $value, $section = 'production', $quoteValue { // null quote value means to auto-detect if ($quoteValue === null) { - $quoteValue = preg_match('#[\"\']#', $value) ? false : true; + $quoteValue = !(bool) preg_match('#[\"\']#', $value); } if ($quoteValue == true) { @@ -142,7 +142,7 @@ public function addStringItem($key, $value, $section = 'production', $quoteValue if (isset($contentLines[$contentLineIndex + 1][0]) && $contentLines[$contentLineIndex + 1][0] == '[') { $newLines[] = $key . ' = ' . $value; $insideSection = null; - } else if (!isset($contentLines[$contentLineIndex + 1])){ + } elseif (!isset($contentLines[$contentLineIndex + 1])) { $newLines[] = $key . ' = ' . $value; $insideSection = null; } @@ -178,7 +178,7 @@ public function addItem($item, $section = 'production', $quoteValue = true) $lastDepth = $rii->getDepth(); if (is_array($value)) { - array_push($configKeyNames, $name); + $configKeyNames[] = $name; } else { $stringItems[] = implode('.', $configKeyNames) . '.' . $name; $stringValues[] = $value; @@ -205,11 +205,9 @@ public function removeStringItem($key, $section = 'production') $insideSection = true; } - if ($insideSection) { - // if its blank, or a section heading - if ((trim($contentLine) == null) || ($contentLines[$contentLineIndex + 1][0] == '[')) { - $insideSection = null; - } + // if its blank, or a section heading + if ($insideSection && ((trim($contentLine) == null) || ($contentLines[$contentLineIndex + 1][0] == '['))) { + $insideSection = null; } if (!preg_match('#' . $key . '\s?=.*#', (string) $contentLine)) { @@ -238,7 +236,7 @@ public function removeItem($item, $section = 'production') $lastDepth = $rii->getDepth(); if (is_array($value)) { - array_push($configKeyNames, $name); + $configKeyNames[] = $name; } else { $stringItems[] = implode('.', $configKeyNames) . '.' . $name; $stringValues[] = $value; @@ -255,7 +253,7 @@ public function removeItem($item, $section = 'production') protected function _getDefaultContents() { - $contents =<<_applicationInstance == null) { - if ($this->_applicationConfigFile->getContext()->exists()) { - define('APPLICATION_PATH', $this->_applicationDirectory->getPath()); - $applicationOptions = array(); - $applicationOptions['config'] = $this->_applicationConfigFile->getPath(); - - $this->_applicationInstance = new Zend_Application( - 'development', - $applicationOptions - ); - } + if ($this->_applicationInstance == null && $this->_applicationConfigFile->getContext()->exists()) { + define('APPLICATION_PATH', $this->_applicationDirectory->getPath()); + $applicationOptions = array(); + $applicationOptions['config'] = $this->_applicationConfigFile->getPath(); + $this->_applicationInstance = new Zend_Application( + 'development', + $applicationOptions + ); } return $this->_applicationInstance; diff --git a/library/Zend/Tool/Project/Context/Zf/ControllerFile.php b/library/Zend/Tool/Project/Context/Zf/ControllerFile.php index d6df9711a0..cc7ca43faa 100644 --- a/library/Zend/Tool/Project/Context/Zf/ControllerFile.php +++ b/library/Zend/Tool/Project/Context/Zf/ControllerFile.php @@ -102,7 +102,7 @@ public function getContents() { $filter = new Zend_Filter_Word_DashToCamelCase(); - $className = ($this->_moduleName) ? $filter->filter(ucfirst($this->_moduleName)) . '_' : ''; + $className = ($this->_moduleName !== '' && $this->_moduleName !== '0') ? $filter->filter(ucfirst($this->_moduleName)) . '_' : ''; $className .= ucfirst($this->_controllerName) . 'Controller'; $codeGenFile = new Zend_CodeGenerator_Php_File(array( @@ -216,8 +216,7 @@ public function getCodeGenerator() { $codeGenFile = Zend_CodeGenerator_Php_File::fromReflectedFileName($this->getPath()); $codeGenFileClasses = $codeGenFile->getClasses(); - $class = array_shift($codeGenFileClasses); - return $class; + return array_shift($codeGenFileClasses); } } diff --git a/library/Zend/Tool/Project/Context/Zf/HtaccessFile.php b/library/Zend/Tool/Project/Context/Zf/HtaccessFile.php index fa6753f59b..ed09c3a6d8 100644 --- a/library/Zend/Tool/Project/Context/Zf/HtaccessFile.php +++ b/library/Zend/Tool/Project/Context/Zf/HtaccessFile.php @@ -61,7 +61,7 @@ public function getName() */ public function getContents() { - $output = <<_layoutName) { + if ($this->_layoutName !== '' && $this->_layoutName !== '0') { $attributes['layoutName'] = $this->_layoutName; } @@ -99,11 +99,9 @@ public function getPersistentAttributes() */ public function getContents() { - $contents = <<layout()->content; ?> EOS; - - return $contents; } } diff --git a/library/Zend/Tool/Project/Context/Zf/ProjectProviderFile.php b/library/Zend/Tool/Project/Context/Zf/ProjectProviderFile.php index 3be55036aa..57e73cfce8 100644 --- a/library/Zend/Tool/Project/Context/Zf/ProjectProviderFile.php +++ b/library/Zend/Tool/Project/Context/Zf/ProjectProviderFile.php @@ -134,7 +134,7 @@ public function getContents() )); } - if ($methods) { + if ($methods !== []) { $class->setMethods($methods); } diff --git a/library/Zend/Tool/Project/Context/Zf/TestApplicationControllerFile.php b/library/Zend/Tool/Project/Context/Zf/TestApplicationControllerFile.php index 4515b80756..76b34bbca9 100644 --- a/library/Zend/Tool/Project/Context/Zf/TestApplicationControllerFile.php +++ b/library/Zend/Tool/Project/Context/Zf/TestApplicationControllerFile.php @@ -76,7 +76,7 @@ public function getPersistentAttributes() { $attributes = array(); - if ($this->_forControllerName) { + if ($this->_forControllerName !== '' && $this->_forControllerName !== '0') { $attributes['forControllerName'] = $this->getForControllerName(); } diff --git a/library/Zend/Tool/Project/Context/Zf/ViewScriptFile.php b/library/Zend/Tool/Project/Context/Zf/ViewScriptFile.php index 943bd3831d..a13046d64f 100644 --- a/library/Zend/Tool/Project/Context/Zf/ViewScriptFile.php +++ b/library/Zend/Tool/Project/Context/Zf/ViewScriptFile.php @@ -110,11 +110,11 @@ public function getPersistentAttributes() { $attributes = array(); - if ($this->_forActionName) { + if ($this->_forActionName !== '' && $this->_forActionName !== '0') { $attributes['forActionName'] = $this->_forActionName; } - if ($this->_scriptName) { + if ($this->_scriptName !== '' && $this->_scriptName !== '0') { $attributes['scriptName'] = $this->_scriptName; } diff --git a/library/Zend/Tool/Project/Profile.php b/library/Zend/Tool/Project/Profile.php index 6429e3e816..b9146b5a0e 100644 --- a/library/Zend/Tool/Project/Profile.php +++ b/library/Zend/Tool/Project/Profile.php @@ -44,6 +44,7 @@ class Zend_Tool_Project_Profile extends Zend_Tool_Project_Profile_Resource_Container { + public \Zend_Tool_Project_Profile_Resource_Container $_topResources; /** * @var bool */ @@ -211,8 +212,7 @@ public function storeToFile() public function storeToData() { $parser = new Zend_Tool_Project_Profile_FileParser_Xml(); - $xml = $parser->serialize($this); - return $xml; + return $parser->serialize($this); } /** diff --git a/library/Zend/Tool/Project/Profile/FileParser/Xml.php b/library/Zend/Tool/Project/Profile/FileParser/Xml.php index 828e7daee2..828b8b50bb 100644 --- a/library/Zend/Tool/Project/Profile/FileParser/Xml.php +++ b/library/Zend/Tool/Project/Profile/FileParser/Xml.php @@ -194,7 +194,7 @@ protected function _unserializeRecurser(SimpleXMLIterator $xmlIterator, Zend_Too $subResource = new Zend_Tool_Project_Profile_Resource($contextName); $subResource->setProfile($this->_profile); - if ($resourceAttributes = $resourceData->attributes()) { + if (($resourceAttributes = $resourceData->attributes()) !== null) { $attributes = array(); foreach ($resourceAttributes as $attrName => $attrValue) { $attributes[$attrName] = (string) $attrValue; @@ -202,7 +202,7 @@ protected function _unserializeRecurser(SimpleXMLIterator $xmlIterator, Zend_Too $subResource->setAttributes($attributes); } - if ($resource) { + if ($resource !== null) { $resource->append($subResource, false); } else { $this->_profile->append($subResource); diff --git a/library/Zend/Tool/Project/Profile/Iterator/ContextFilter.php b/library/Zend/Tool/Project/Profile/Iterator/ContextFilter.php index b074614e43..7ef5a6d939 100644 --- a/library/Zend/Tool/Project/Profile/Iterator/ContextFilter.php +++ b/library/Zend/Tool/Project/Profile/Iterator/ContextFilter.php @@ -31,6 +31,10 @@ class Zend_Tool_Project_Profile_Iterator_ContextFilter extends RecursiveFilterIterator { + /** + * @var mixed|\ReflectionClass + */ + public $ref; /** * @var array */ @@ -66,7 +70,7 @@ public function __construct(RecursiveIterator $iterator, $options = array()) { parent::__construct($iterator); $this->_rawOptions = $options; - if ($options) { + if ($options !== []) { $this->setOptions($options); } } diff --git a/library/Zend/Tool/Project/Profile/Resource.php b/library/Zend/Tool/Project/Profile/Resource.php index 58b08cd5d8..f24494b7b8 100644 --- a/library/Zend/Tool/Project/Profile/Resource.php +++ b/library/Zend/Tool/Project/Profile/Resource.php @@ -168,7 +168,7 @@ public function getPersistentAttributes() public function setEnabled($enabled = true) { // convert fuzzy types to bool - $this->_enabled = (!in_array($enabled, array('false', 'disabled', 0, -1, false), true)) ? true : false; + $this->_enabled = !in_array($enabled, array('false', 'disabled', 0, -1, false), true); return $this; } diff --git a/library/Zend/Tool/Project/Profile/Resource/Container.php b/library/Zend/Tool/Project/Profile/Resource/Container.php index 4f06f6f55d..64c329e041 100644 --- a/library/Zend/Tool/Project/Profile/Resource/Container.php +++ b/library/Zend/Tool/Project/Profile/Resource/Container.php @@ -36,6 +36,10 @@ class Zend_Tool_Project_Profile_Resource_Container implements RecursiveIterator, Countable { + /** + * @var mixed|\Zend_Tool_Project_Profile_Resource_Container + */ + public $_parentResource; /** * @var array */ @@ -97,7 +101,7 @@ public function search($matchSearchConstraints, $nonMatchSearchConstraints = nul break; } - if (strtolower($currentResource->getName()) == strtolower($currentConstraint->name)) { + if (strtolower($currentResource->getName()) === strtolower($currentConstraint->name)) { $paramsMatch = true; @@ -181,7 +185,7 @@ public function createResource($context, Array $attributes = array()) $newResource = new Zend_Tool_Project_Profile_Resource($context); - if ($attributes) { + if ($attributes !== []) { $newResource->setAttributes($attributes); } @@ -251,7 +255,7 @@ public function setAttribute($name, $value) */ public function getAttribute($name) { - return (array_key_exists($name, $this->_attributes)) ? $this->_attributes[$name] : null; + return $this->_attributes[$name] ?? null; } /** @@ -320,7 +324,7 @@ public function append(Zend_Tool_Project_Profile_Resource_Container $resource) if (!$this->isAppendable()) { throw new Exception('Resource by name ' . (string) $this . ' is not appendable'); } - array_push($this->_subResources, $resource); + $this->_subResources[] = $resource; $resource->setParentResource($this); return $this; @@ -383,7 +387,7 @@ public function valid() */ public function hasChildren() { - return (count($this->_subResources > 0)) ? true : false; + return (bool) count($this->_subResources > 0); } /** diff --git a/library/Zend/Tool/Project/Profile/Resource/SearchConstraints.php b/library/Zend/Tool/Project/Profile/Resource/SearchConstraints.php index e43bbeb77f..eaffad6df7 100644 --- a/library/Zend/Tool/Project/Profile/Resource/SearchConstraints.php +++ b/library/Zend/Tool/Project/Profile/Resource/SearchConstraints.php @@ -87,7 +87,7 @@ public function addConstraint($constraint) $constraint = $this->_makeConstraint($name, $params); - array_push($this->_constraints, $constraint); + $this->_constraints[] = $constraint; return $this; } diff --git a/library/Zend/Tool/Project/Provider/Abstract.php b/library/Zend/Tool/Project/Provider/Abstract.php index 66bf1e239a..8f4393258a 100644 --- a/library/Zend/Tool/Project/Provider/Abstract.php +++ b/library/Zend/Tool/Project/Provider/Abstract.php @@ -200,10 +200,8 @@ protected function _loadProfileRequired() */ protected function _getProfile($loadProfileFlag = self::NO_PROFILE_THROW_EXCEPTION) { - if (!$this->_loadedProfile) { - if (($this->_loadProfile($loadProfileFlag) === false) && ($loadProfileFlag === self::NO_PROFILE_RETURN_FALSE)) { - return false; - } + if (!$this->_loadedProfile && (($this->_loadProfile($loadProfileFlag) === false) && ($loadProfileFlag === self::NO_PROFILE_RETURN_FALSE))) { + return false; } return $this->_loadedProfile; @@ -253,12 +251,7 @@ protected function _hasProjectProviderDirectory($pathToProfileFile) if (strstr($contents, 'createResource('ActionMethod', array('actionName' => $actionName)); - - return $actionMethod; + return $controllerFile->createResource('ActionMethod', array('actionName' => $actionName)); } /** diff --git a/library/Zend/Tool/Project/Provider/Controller.php b/library/Zend/Tool/Project/Provider/Controller.php index 606eea0c95..1c9aec6242 100644 --- a/library/Zend/Tool/Project/Provider/Controller.php +++ b/library/Zend/Tool/Project/Provider/Controller.php @@ -56,12 +56,10 @@ public static function createResource(Zend_Tool_Project_Profile $profile, $contr throw new Zend_Tool_Project_Provider_Exception($exceptionMessage); } - $newController = $controllersDirectory->createResource( + return $controllersDirectory->createResource( 'controllerFile', array('controllerName' => $controllerName, 'moduleName' => $moduleName) ); - - return $newController; } /** diff --git a/library/Zend/Tool/Project/Provider/DbAdapter.php b/library/Zend/Tool/Project/Provider/DbAdapter.php index 61e77084b4..916c88b02b 100644 --- a/library/Zend/Tool/Project/Provider/DbAdapter.php +++ b/library/Zend/Tool/Project/Provider/DbAdapter.php @@ -65,11 +65,11 @@ public function configure($dsn = null, /* $interactivelyPrompt = false, */ $sect $this->_sectionName = $sectionName; } - if (!isset($this->_config->{$this->_sectionName})) { + if (!(property_exists($this->_config, '_sectionName') && $this->_config->{$this->_sectionName} !== null)) { throw new Zend_Tool_Project_Exception('The config does not have a ' . $this->_sectionName . ' section.'); } - if (isset($this->_config->{$this->_sectionName}->resources->db)) { + if (property_exists($this->_config->{$this->_sectionName}->resources, 'db') && $this->_config->{$this->_sectionName}->resources->db !== null) { throw new Zend_Tool_Project_Exception('The config already has a db resource configured in section ' . $this->_sectionName . '.'); } diff --git a/library/Zend/Tool/Project/Provider/DbTable.php b/library/Zend/Tool/Project/Provider/DbTable.php index 72149e01fc..57962260fa 100644 --- a/library/Zend/Tool/Project/Provider/DbTable.php +++ b/library/Zend/Tool/Project/Provider/DbTable.php @@ -61,9 +61,7 @@ public static function createResource(Zend_Tool_Project_Profile $profile, $dbTab $dbTableDirectory = $modelsDirectory->createResource('DbTableDirectory'); } - $dbTableFile = $dbTableDirectory->createResource('DbTableFile', array('dbTableName' => $dbTableName, 'actualTableName' => $actualTableName)); - - return $dbTableFile; + return $dbTableDirectory->createResource('DbTableFile', array('dbTableName' => $dbTableName, 'actualTableName' => $actualTableName)); } public static function hasResource(Zend_Tool_Project_Profile $profile, $dbTableName, $moduleName = null) @@ -85,7 +83,7 @@ public static function hasResource(Zend_Tool_Project_Profile $profile, $dbTableN $dbTableFile = $dbTableDirectory->search(array('DbTableFile' => array('dbTableName' => $dbTableName))); - return ($dbTableFile instanceof Zend_Tool_Project_Profile_Resource) ? true : false; + return $dbTableFile instanceof Zend_Tool_Project_Profile_Resource; } @@ -160,7 +158,7 @@ public function createFromDatabase($module = null, $forceOverwrite = false) try { $zendApp->bootstrap('db'); } catch (Zend_Application_Exception $e) { - throw new Zend_Tool_Project_Provider_Exception('Db resource not available, you might need to configure a DbAdapter.'); + throw new Zend_Tool_Project_Provider_Exception('Db resource not available, you might need to configure a DbAdapter.', $e->getCode(), $e); return; } diff --git a/library/Zend/Tool/Project/Provider/Form.php b/library/Zend/Tool/Project/Provider/Form.php index 69534d3ea5..8aa6769e74 100644 --- a/library/Zend/Tool/Project/Provider/Form.php +++ b/library/Zend/Tool/Project/Provider/Form.php @@ -44,12 +44,10 @@ public static function createResource(Zend_Tool_Project_Profile $profile, $formN throw new Zend_Tool_Project_Provider_Exception($exceptionMessage); } - $newForm = $formsDirectory->createResource( + return $formsDirectory->createResource( 'formFile', array('formName' => $formName, 'moduleName' => $moduleName) ); - - return $newForm; } /** @@ -101,16 +99,13 @@ public function enable($module = null) if ($formDirectoryResource->isEnabled()) { throw new Zend_Tool_Project_Provider_Exception('This project already has forms enabled.'); + } elseif ($this->_registry->getRequest()->isPretend()) { + $this->_registry->getResponse()->appendContent('Would enable forms directory at ' . $formDirectoryResource->getContext()->getPath()); } else { - if ($this->_registry->getRequest()->isPretend()) { - $this->_registry->getResponse()->appendContent('Would enable forms directory at ' . $formDirectoryResource->getContext()->getPath()); - } else { - $this->_registry->getResponse()->appendContent('Enabling forms directory at ' . $formDirectoryResource->getContext()->getPath()); - $formDirectoryResource->setEnabled(true); - $formDirectoryResource->create(); - $this->_storeProfile(); - } - + $this->_registry->getResponse()->appendContent('Enabling forms directory at ' . $formDirectoryResource->getContext()->getPath()); + $formDirectoryResource->setEnabled(true); + $formDirectoryResource->create(); + $this->_storeProfile(); } } diff --git a/library/Zend/Tool/Project/Provider/Layout.php b/library/Zend/Tool/Project/Provider/Layout.php index 320de1e398..1fa376fe77 100644 --- a/library/Zend/Tool/Project/Provider/Layout.php +++ b/library/Zend/Tool/Project/Provider/Layout.php @@ -74,7 +74,7 @@ public function enable() $zc = $applicationConfigResource->getAsZendConfig(); - if (isset($zc->resources) && isset($zc->resources->layout)) { + if (property_exists($zc, 'resources') && $zc->resources !== null && (property_exists($zc->resources, 'layout') && $zc->resources->layout !== null)) { $this->_registry->getResponse()->appendContent('A layout resource already exists in this project\'s application configuration file.'); return; } @@ -108,7 +108,7 @@ public function disable() $applicationConfigResource = $this->_getApplicationConfigResource($profile); $zc = $applicationConfigResource->getAsZendConfig(); - if (isset($zc->resources) && !isset($zc->resources->layout)) { + if (property_exists($zc, 'resources') && $zc->resources !== null && !(property_exists($zc->resources, 'layout') && $zc->resources->layout !== null)) { $this->_registry->getResponse()->appendContent('No layout configuration exists in application config file.'); return; } diff --git a/library/Zend/Tool/Project/Provider/Model.php b/library/Zend/Tool/Project/Provider/Model.php index 71f8015e48..617ce3862d 100644 --- a/library/Zend/Tool/Project/Provider/Model.php +++ b/library/Zend/Tool/Project/Provider/Model.php @@ -44,12 +44,10 @@ public static function createResource(Zend_Tool_Project_Profile $profile, $model throw new Zend_Tool_Project_Provider_Exception($exceptionMessage); } - $newModel = $modelsDirectory->createResource( + return $modelsDirectory->createResource( 'modelFile', array('modelName' => $modelName, 'moduleName' => $moduleName) ); - - return $newModel; } /** diff --git a/library/Zend/Tool/Project/Provider/Module.php b/library/Zend/Tool/Project/Provider/Module.php index 44898ce875..5ce25c09fd 100644 --- a/library/Zend/Tool/Project/Provider/Module.php +++ b/library/Zend/Tool/Project/Provider/Module.php @@ -99,7 +99,7 @@ public static function createResources(Zend_Tool_Project_Profile $profile, $modu if ($depthDifference === 1) { // if we went down into a child, make note - array_push($parentResources, $currentResource); + $parentResources[] = $currentResource; // this will have always been set previously by another loop $currentResource = $currentChildResource; } elseif ($depthDifference < 0) { diff --git a/library/Zend/Tool/Project/Provider/Project.php b/library/Zend/Tool/Project/Provider/Project.php index 30d04b60ce..e348182f23 100644 --- a/library/Zend/Tool/Project/Provider/Project.php +++ b/library/Zend/Tool/Project/Provider/Project.php @@ -131,8 +131,7 @@ protected function _getDefaultProfile() } $version = Zend_Version::VERSION; - - $data = << @@ -204,7 +203,6 @@ protected function _getDefaultProfile() EOS; - return $data; } public static function getDefaultReadmeContents($caller = null) diff --git a/library/Zend/Tool/Project/Provider/ProjectProvider.php b/library/Zend/Tool/Project/Provider/ProjectProvider.php index 440080679e..6378a34016 100644 --- a/library/Zend/Tool/Project/Provider/ProjectProvider.php +++ b/library/Zend/Tool/Project/Provider/ProjectProvider.php @@ -53,9 +53,7 @@ public static function createResource(Zend_Tool_Project_Profile $profile, $proje $profileSearchParams = array(); $profileSearchParams[] = 'projectProvidersDirectory'; - $projectProvider = $profile->createResourceAt($profileSearchParams, 'projectProviderFile', array('projectProviderName' => $projectProviderName, 'actionNames' => $actionNames)); - - return $projectProvider; + return $profile->createResourceAt($profileSearchParams, 'projectProviderFile', array('projectProviderName' => $projectProviderName, 'actionNames' => $actionNames)); } /** diff --git a/library/Zend/Tool/Project/Provider/Test.php b/library/Zend/Tool/Project/Provider/Test.php index 31316027b7..345c045966 100644 --- a/library/Zend/Tool/Project/Provider/Test.php +++ b/library/Zend/Tool/Project/Provider/Test.php @@ -137,20 +137,14 @@ public static function createLibraryResource(Zend_Tool_Project_Profile $profile, while ($nameOrNamespacePart = array_shift($fsParts)) { - if (count($fsParts) > 0) { - + if ($fsParts !== []) { if (($libraryDirectoryResource = $currentDirectoryResource->search(array('TestLibraryNamespaceDirectory' => array('namespaceName' => $nameOrNamespacePart)))) === false) { $currentDirectoryResource = $currentDirectoryResource->createResource('TestLibraryNamespaceDirectory', array('namespaceName' => $nameOrNamespacePart)); } else { $currentDirectoryResource = $libraryDirectoryResource; } - - } else { - - if (($libraryFileResource = $currentDirectoryResource->search(array('TestLibraryFile' => array('forClassName' => $libraryClassName)))) === false) { - $libraryFileResource = $currentDirectoryResource->createResource('TestLibraryFile', array('forClassName' => $libraryClassName)); - } - + } elseif (($libraryFileResource = $currentDirectoryResource->search(array('TestLibraryFile' => array('forClassName' => $libraryClassName)))) === false) { + $libraryFileResource = $currentDirectoryResource->createResource('TestLibraryFile', array('forClassName' => $libraryClassName)); } } diff --git a/library/Zend/Tool/Project/Provider/View.php b/library/Zend/Tool/Project/Provider/View.php index 6ecccf1db6..32b732efbb 100644 --- a/library/Zend/Tool/Project/Provider/View.php +++ b/library/Zend/Tool/Project/Provider/View.php @@ -79,9 +79,7 @@ public static function createResource(Zend_Tool_Project_Profile $profile, $actio $viewControllerScriptsDirectory = $viewScriptsDirectory->createResource('viewControllerScriptsDirectory', array('forControllerName' => $controllerName)); } - $newViewScriptFile = $viewControllerScriptsDirectory->createResource('ViewScriptFile', array('forActionName' => $actionName)); - - return $newViewScriptFile; + return $viewControllerScriptsDirectory->createResource('ViewScriptFile', array('forActionName' => $actionName)); } /** diff --git a/library/Zend/Translate.php b/library/Zend/Translate.php index 46bec43dc1..d779a51efa 100644 --- a/library/Zend/Translate.php +++ b/library/Zend/Translate.php @@ -72,23 +72,21 @@ public function __construct($options = array()) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (func_num_args() > 1) { + } elseif (func_num_args() > 1) { $args = func_get_args(); $options = array(); $options['adapter'] = array_shift($args); if (!empty($args)) { $options['content'] = array_shift($args); } - if (!empty($args)) { $options['locale'] = array_shift($args); } - if (!empty($args)) { $opt = array_shift($args); $options = array_merge($opt, $options); } - } else if (!is_array($options)) { + } elseif (!is_array($options)) { $options = array('adapter' => $options); } @@ -107,23 +105,21 @@ public function setAdapter($options = array()) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (func_num_args() > 1) { + } elseif (func_num_args() > 1) { $args = func_get_args(); $options = array(); $options['adapter'] = array_shift($args); if (!empty($args)) { $options['content'] = array_shift($args); } - if (!empty($args)) { $options['locale'] = array_shift($args); } - if (!empty($args)) { $opt = array_shift($args); $options = array_merge($opt, $options); } - } else if (!is_array($options)) { + } elseif (!is_array($options)) { $options = array('adapter' => $options); } diff --git a/library/Zend/Translate/Adapter.php b/library/Zend/Translate/Adapter.php index 9fcf8c61d4..ef50ee8d64 100644 --- a/library/Zend/Translate/Adapter.php +++ b/library/Zend/Translate/Adapter.php @@ -129,20 +129,18 @@ public function __construct($options = array()) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (func_num_args() > 1) { + } elseif (func_num_args() > 1) { $args = func_get_args(); $options = array(); $options['content'] = array_shift($args); - if (!empty($args)) { $options['locale'] = array_shift($args); } - if (!empty($args)) { $opt = array_shift($args); $options = array_merge($opt, $options); } - } else if (!is_array($options)) { + } elseif (!is_array($options)) { $options = array('content' => $options); } @@ -159,11 +157,7 @@ public function __construct($options = array()) } } - if (empty($options['locale']) || ($options['locale'] === "auto")) { - $this->_automatic = true; - } else { - $this->_automatic = false; - } + $this->_automatic = empty($options['locale']) || ($options['locale'] === "auto"); $locale = null; if (!empty($options['locale'])) { @@ -198,20 +192,18 @@ public function addTranslation($options = array()) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (func_num_args() > 1) { + } elseif (func_num_args() > 1) { $args = func_get_args(); $options = array(); $options['content'] = array_shift($args); - if (!empty($args)) { $options['locale'] = array_shift($args); } - if (!empty($args)) { $opt = array_shift($args); $options = array_merge($opt, $options); } - } else if (!is_array($options)) { + } elseif (!is_array($options)) { $options = array('content' => $options); } @@ -243,8 +235,8 @@ public function addTranslation($options = array()) throw new Zend_Translate_Exception("The given Language '{$options['locale']}' does not exist", 0, $e); } - $options = $options + $this->_options; - if (is_string($options['content']) and is_dir($options['content'])) { + $options += $this->_options; + if (is_string($options['content']) && is_dir($options['content'])) { $options['content'] = realpath($options['content']); $prev = ''; $iterator = new RecursiveIteratorIterator( @@ -264,25 +256,23 @@ public function addTranslation($options = array()) // ignore files matching the given regex from option 'ignore' and all files below continue 2; } - } else if (strpos($directory, DIRECTORY_SEPARATOR . $ignore) !== false) { + } elseif (strpos($directory, DIRECTORY_SEPARATOR . $ignore) !== false) { // ignore files matching first characters from option 'ignore' and all files below continue 2; } } - } else { - if (strpos($directory, DIRECTORY_SEPARATOR . $options['ignore']) !== false) { - // ignore files matching first characters from option 'ignore' and all files below - continue; - } + } elseif (strpos($directory, DIRECTORY_SEPARATOR . $options['ignore']) !== false) { + // ignore files matching first characters from option 'ignore' and all files below + continue; } if ($info->isDir()) { // pathname as locale - if (($options['scan'] === self::LOCALE_DIRECTORY) and (Zend_Locale::isLocale($file, true, false))) { + if ($options['scan'] === self::LOCALE_DIRECTORY && Zend_Locale::isLocale($file, true, false)) { $options['locale'] = $file; $prev = (string) $options['locale']; } - } else if ($info->isFile()) { + } elseif ($info->isFile()) { // filename as locale if ($options['scan'] === self::LOCALE_FILENAME) { $filename = explode('.', (string) $file); @@ -305,16 +295,13 @@ public function addTranslation($options = array()) $parts = array_unique($parts); $prev = ''; foreach($parts as $token) { - if (Zend_Locale::isLocale($token, true, false)) { - if (strlen($prev) <= strlen($token)) { - $options['locale'] = $token; - $prev = $token; - } + if (Zend_Locale::isLocale($token, true, false) && strlen($prev) <= strlen($token)) { + $options['locale'] = $token; + $prev = $token; } } } } - try { $options['content'] = $info->getPathname(); $this->_addTranslationData($options); @@ -329,7 +316,7 @@ public function addTranslation($options = array()) $this->_addTranslationData($options); } - if ((isset($this->_translate[$originate]) === true) and (count($this->_translate[$originate]) > 0)) { + if (isset($this->_translate[$originate]) && count($this->_translate[$originate]) > 0) { $this->setLocale($originate); } @@ -350,18 +337,15 @@ public function setOptions(array $options = array()) foreach ($options as $key => $option) { if ($key == 'locale') { $locale = $option; - } else if ((isset($this->_options[$key]) and ($this->_options[$key] != $option)) or - !isset($this->_options[$key])) { + } elseif (isset($this->_options[$key]) && $this->_options[$key] != $option || !isset($this->_options[$key])) { if (($key == 'log') && !($option instanceof Zend_Log)) { require_once 'Zend/Translate/Exception.php'; throw new Zend_Translate_Exception('Instance of Zend_Log expected for option log'); } - if ($key == 'cache') { self::setCache($option); continue; } - $this->_options[$key] = $option; $change = true; } @@ -371,7 +355,7 @@ public function setOptions(array $options = array()) $this->setLocale($locale); } - if (isset(self::$_cache) and ($change == true)) { + if (isset(self::$_cache) && $change == true) { $id = 'Zend_Translate_' . $this->toString() . '_Options'; if (self::$_cacheTags) { self::$_cache->save($this->_options, $id, array($this->_options['tag'])); @@ -396,7 +380,7 @@ public function getOptions($optionKey = null) return $this->_options; } - if (isset($this->_options[$optionKey]) === true) { + if (isset($this->_options[$optionKey])) { return $this->_options[$optionKey]; } @@ -422,11 +406,7 @@ public function getLocale() */ public function setLocale($locale) { - if (($locale === "auto") or ($locale === null)) { - $this->_automatic = true; - } else { - $this->_automatic = false; - } + $this->_automatic = ($locale === "auto" || $locale === null); try { $locale = Zend_Locale::findLocale($locale); @@ -437,26 +417,22 @@ public function setLocale($locale) if (!isset($this->_translate[$locale])) { $temp = explode('_', $locale); - if (!isset($this->_translate[$temp[0]]) and !isset($this->_translate[$locale])) { - if (!$this->_options['disableNotices']) { - if ($this->_options['log']) { - $this->_options['log']->log("The language '{$locale}' has to be added before it can be used.", $this->_options['logPriority']); - } else { - trigger_error("The language '{$locale}' has to be added before it can be used.", E_USER_NOTICE); - } + if ((!isset($this->_translate[$temp[0]]) && !isset($this->_translate[$locale])) && !$this->_options['disableNotices']) { + if ($this->_options['log']) { + $this->_options['log']->log("The language '{$locale}' has to be added before it can be used.", $this->_options['logPriority']); + } else { + trigger_error("The language '{$locale}' has to be added before it can be used.", E_USER_NOTICE); } } $locale = $temp[0]; } - if (empty($this->_translate[$locale])) { - if (!$this->_options['disableNotices']) { - if ($this->_options['log']) { - $this->_options['log']->log("No translation for the language '{$locale}' available.", $this->_options['logPriority']); - } else { - trigger_error("No translation for the language '{$locale}' available.", E_USER_NOTICE); - } + if (empty($this->_translate[$locale]) && !$this->_options['disableNotices']) { + if ($this->_options['log']) { + $this->_options['log']->log("No translation for the language '{$locale}' available.", $this->_options['logPriority']); + } else { + trigger_error("No translation for the language '{$locale}' available.", E_USER_NOTICE); } } @@ -503,7 +479,7 @@ public function getList() */ public function getMessageId($message, $locale = null) { - if (empty($locale) or !$this->isAvailable($locale)) { + if (empty($locale) || !$this->isAvailable($locale)) { $locale = $this->_options['locale']; } @@ -519,7 +495,7 @@ public function getMessageId($message, $locale = null) */ public function getMessageIds($locale = null) { - if (empty($locale) or !$this->isAvailable($locale)) { + if (empty($locale) || !$this->isAvailable($locale)) { $locale = $this->_options['locale']; } @@ -540,7 +516,7 @@ public function getMessages($locale = null) return $this->_translate; } - if ((empty($locale) === true) or ($this->isAvailable($locale) === false)) { + if (empty($locale) || !$this->isAvailable($locale)) { $locale = $this->_options['locale']; } @@ -557,8 +533,7 @@ public function getMessages($locale = null) */ public function isAvailable($locale) { - $return = isset($this->_translate[(string) $locale]); - return $return; + return isset($this->_translate[(string) $locale]); } /** @@ -587,14 +562,12 @@ private function _addTranslationData($options = array()) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (func_num_args() > 1) { + } elseif (func_num_args() > 1) { $args = func_get_args(); $options['content'] = array_shift($args); - if (!empty($args)) { $options['locale'] = array_shift($args); } - if (!empty($args)) { $options += array_shift($args); } @@ -664,11 +637,11 @@ private function _addTranslationData($options = array()) } } - if ($this->_automatic === true) { + if ($this->_automatic) { $find = new Zend_Locale($options['locale']); $browser = $find->getEnvironment() + $find->getBrowser(); arsort($browser); - foreach($browser as $language => $quality) { + foreach(array_keys($browser) as $language) { if (isset($this->_translate[$language])) { $this->_options['locale'] = $language; break; @@ -676,7 +649,7 @@ private function _addTranslationData($options = array()) } } - if (($read) and (isset(self::$_cache))) { + if ($read && isset(self::$_cache)) { $id = 'Zend_Translate_' . md5(serialize($options['content'])) . '_' . $this->toString(); if (self::$_cacheTags) { self::$_cache->save($temp, $id, array($this->_options['tag'])); @@ -727,12 +700,10 @@ public function translate($messageId, $locale = null) // language does not exist, return original string $this->_log($messageId, $locale); // use rerouting when enabled - if (!empty($this->_options['route'])) { - if (array_key_exists($locale, $this->_options['route']) && - !array_key_exists($locale, $this->_routed)) { - $this->_routed[$locale] = true; - return $this->translate($messageId, $this->_options['route'][$locale]); - } + if (!empty($this->_options['route']) && (array_key_exists($locale, $this->_options['route']) && + !array_key_exists($locale, $this->_routed))) { + $this->_routed[$locale] = true; + return $this->translate($messageId, $this->_options['route'][$locale]); } $this->_routed = array(); @@ -758,16 +729,14 @@ public function translate($messageId, $locale = null) $this->_routed = array(); return $this->_translate[$locale][$messageId]; } - $rule = Zend_Translate_Plural::getPlural($number, $locale); if (isset($this->_translate[$locale][$plural[0]][$rule])) { $this->_routed = array(); return $this->_translate[$locale][$plural[0]][$rule]; } - } else if (strlen($locale) != 2) { + } elseif (strlen($locale) != 2) { // faster than creating a new locale and separate the leading part $locale = substr($locale, 0, -strlen((string) strrchr($locale, '_'))); - if ((is_string($messageId) || is_int($messageId)) && isset($this->_translate[$locale][$messageId])) { // return regionless translation (en_US -> en) if ($plural === null) { @@ -785,12 +754,10 @@ public function translate($messageId, $locale = null) $this->_log($messageId, $locale); // use rerouting when enabled - if (!empty($this->_options['route'])) { - if (array_key_exists($locale, $this->_options['route']) && - !array_key_exists($locale, $this->_routed)) { - $this->_routed[$locale] = true; - return $this->translate($messageId, $this->_options['route'][$locale]); - } + if (!empty($this->_options['route']) && (array_key_exists($locale, $this->_options['route']) && + !array_key_exists($locale, $this->_routed))) { + $this->_routed[$locale] = true; + return $this->translate($messageId, $this->_options['route'][$locale]); } $this->_routed = array(); @@ -869,7 +836,7 @@ public function _($messageId, $locale = null) */ public function isTranslated($messageId, $original = false, $locale = null) { - if (($original !== false) and ($original !== true)) { + if ($original && !$original) { $locale = $original; $original = false; } @@ -891,10 +858,9 @@ public function isTranslated($messageId, $original = false, $locale = null) if ((is_string($messageId) || is_int($messageId)) && isset($this->_translate[$locale][$messageId])) { // return original translation return true; - } else if ((strlen($locale) != 2) and ($original === false)) { + } elseif (strlen($locale) != 2 && !$original) { // faster than creating a new locale and separate the leading part $locale = substr($locale, 0, -strlen((string) strrchr($locale, '_'))); - if ((is_string($messageId) || is_int($messageId)) && isset($this->_translate[$locale][$messageId])) { // return regionless translation (en_US -> en) return true; @@ -933,11 +899,7 @@ public static function setCache(Zend_Cache_Core $cache) */ public static function hasCache() { - if (self::$_cache !== null) { - return true; - } - - return false; + return self::$_cache !== null; } /** diff --git a/library/Zend/Translate/Adapter/Array.php b/library/Zend/Translate/Adapter/Array.php index 2dd298eb03..b3eb8e3603 100644 --- a/library/Zend/Translate/Adapter/Array.php +++ b/library/Zend/Translate/Adapter/Array.php @@ -49,12 +49,10 @@ class Zend_Translate_Adapter_Array extends Zend_Translate_Adapter protected function _loadTranslationData($data, $locale, array $options = array()) { $this->_data = array(); - if (!is_array($data)) { - if (file_exists($data)) { - ob_start(); - $data = include($data); - ob_end_clean(); - } + if (!is_array($data) && file_exists($data)) { + ob_start(); + $data = include($data); + ob_end_clean(); } if (!is_array($data)) { require_once 'Zend/Translate/Exception.php'; diff --git a/library/Zend/Translate/Adapter/Csv.php b/library/Zend/Translate/Adapter/Csv.php index 300de27686..b3e63ee47d 100644 --- a/library/Zend/Translate/Adapter/Csv.php +++ b/library/Zend/Translate/Adapter/Csv.php @@ -35,6 +35,10 @@ */ class Zend_Translate_Adapter_Csv extends Zend_Translate_Adapter { + /** + * @var bool|mixed|resource + */ + public $_file; private $_data = array(); /** @@ -50,20 +54,18 @@ public function __construct($options = array()) if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (func_num_args() > 1) { + } elseif (func_num_args() > 1) { $args = func_get_args(); $options = array(); $options['content'] = array_shift($args); - if (!empty($args)) { $options['locale'] = array_shift($args); } - if (!empty($args)) { $opt = array_shift($args); $options = array_merge($opt, $options); } - } else if (!is_array($options)) { + } elseif (!is_array($options)) { $options = array('content' => $options); } @@ -82,7 +84,7 @@ public function __construct($options = array()) protected function _loadTranslationData($filename, $locale, array $options = array()) { $this->_data = array(); - $options = $options + $this->_options; + $options += $this->_options; $this->_file = @fopen($filename, 'rb'); if (!$this->_file) { require_once 'Zend/Translate/Exception.php'; diff --git a/library/Zend/Translate/Adapter/Gettext.php b/library/Zend/Translate/Adapter/Gettext.php index eb8a508672..3aa78bba55 100644 --- a/library/Zend/Translate/Adapter/Gettext.php +++ b/library/Zend/Translate/Adapter/Gettext.php @@ -81,7 +81,7 @@ protected function _loadTranslationData($filename, $locale, array $options = arr $input = $this->_readMOData(1); if (strtolower(substr(dechex($input[1]), -8)) == "950412de") { $this->_bigEndian = false; - } else if (strtolower(substr(dechex($input[1]), -8)) == "de120495") { + } elseif (strtolower(substr(dechex($input[1]), -8)) == "de120495") { $this->_bigEndian = true; } else { @fclose($this->_file); diff --git a/library/Zend/Translate/Adapter/Qt.php b/library/Zend/Translate/Adapter/Qt.php index db543ff64e..9de511e734 100644 --- a/library/Zend/Translate/Adapter/Qt.php +++ b/library/Zend/Translate/Adapter/Qt.php @@ -82,12 +82,10 @@ protected function _loadTranslationData($filename, $locale, array $options = arr Zend_Xml_Security::scanFile($filename); } catch (Zend_Xml_Exception $e) { require_once 'Zend/Translate/Exception.php'; - throw new Zend_Translate_Exception( - $e->getMessage() - ); + throw new Zend_Translate_Exception($e->getMessage(), $e->getCode(), $e); } - if (!xml_parse($this->_file, file_get_contents($filename))) { + if (xml_parse($this->_file, file_get_contents($filename)) === 0) { $ex = sprintf('XML error: %s at line %d of file %s', xml_error_string(xml_get_error_code($this->_file)), xml_get_current_line_number($this->_file), @@ -129,8 +127,7 @@ private function _endElement($file, $name) break; case 'translation': - if (!empty($this->_scontent) and !empty($this->_tcontent) or - (isset($this->_data[$this->_target][$this->_scontent]) === false)) { + if (!empty($this->_scontent) && !empty($this->_tcontent) || !isset($this->_data[$this->_target][$this->_scontent])) { $this->_data[$this->_target][$this->_scontent] = $this->_tcontent; } $this->_ttag = false; @@ -157,8 +154,7 @@ private function _findEncoding($filename) $file = file_get_contents($filename, null, null, 0, 100); if (strpos($file, "encoding") !== false) { $encoding = substr($file, strpos($file, "encoding") + 9); - $encoding = substr($encoding, 1, strpos($encoding, $encoding[0], 1) - 1); - return $encoding; + return substr($encoding, 1, strpos($encoding, $encoding[0], 1) - 1); } return 'UTF-8'; } diff --git a/library/Zend/Translate/Adapter/Tbx.php b/library/Zend/Translate/Adapter/Tbx.php index 107107c4e6..4a75118fd8 100644 --- a/library/Zend/Translate/Adapter/Tbx.php +++ b/library/Zend/Translate/Adapter/Tbx.php @@ -77,12 +77,10 @@ protected function _loadTranslationData($filename, $locale, array $options = arr Zend_Xml_Security::scanFile($filename); } catch (Zend_Xml_Exception $e) { require_once 'Zend/Translate/Exception.php'; - throw new Zend_Translate_Exception( - $e->getMessage() - ); + throw new Zend_Translate_Exception($e->getMessage(), $e->getCode(), $e); } - if (!xml_parse($this->_file, file_get_contents($filename))) { + if (xml_parse($this->_file, file_get_contents($filename)) === 0) { $ex = sprintf('XML error: %s at line %d of file %s', xml_error_string(xml_get_error_code($this->_file)), xml_get_current_line_number($this->_file), @@ -109,9 +107,9 @@ private function _startElement($file, $name, $attrib) $this->_termentry = null; break; case 'langset': - if (isset($attrib['xml:lang']) === true) { + if (isset($attrib['xml:lang'])) { $this->_langset = $attrib['xml:lang']; - if (isset($this->_data[$this->_langset]) === false) { + if (!isset($this->_data[$this->_langset])) { $this->_data[$this->_langset] = array(); } } @@ -128,7 +126,7 @@ private function _startElement($file, $name, $attrib) private function _endElement($file, $name) { - if (($this->_term !== null) and ($name != "term")) { + if ($this->_term !== null && $name != "term") { $this->_content .= ""; } else { switch (strtolower($name)) { @@ -140,7 +138,7 @@ private function _endElement($file, $name) if (empty($this->_termentry)) { $this->_termentry = $this->_content; } - if (!empty($this->_content) or (isset($this->_data[$this->_langset][$this->_termentry]) === false)) { + if (!empty($this->_content) || !isset($this->_data[$this->_langset][$this->_termentry])) { $this->_data[$this->_langset][$this->_termentry] = $this->_content; } break; @@ -162,8 +160,7 @@ private function _findEncoding($filename) $file = file_get_contents($filename, null, null, 0, 100); if (strpos($file, "encoding") !== false) { $encoding = substr($file, strpos($file, "encoding") + 9); - $encoding = substr($encoding, 1, strpos($encoding, $encoding[0], 1) - 1); - return $encoding; + return substr($encoding, 1, strpos($encoding, $encoding[0], 1) - 1); } return 'UTF-8'; } diff --git a/library/Zend/Translate/Adapter/Tmx.php b/library/Zend/Translate/Adapter/Tmx.php index d6572592df..f85883f3a5 100644 --- a/library/Zend/Translate/Adapter/Tmx.php +++ b/library/Zend/Translate/Adapter/Tmx.php @@ -82,12 +82,10 @@ protected function _loadTranslationData($filename, $locale, array $options = arr Zend_Xml_Security::scanFile($filename); } catch (Zend_Xml_Exception $e) { require_once 'Zend/Translate/Exception.php'; - throw new Zend_Translate_Exception( - $e->getMessage() - ); + throw new Zend_Translate_Exception($e->getMessage(), $e->getCode(), $e); } - if (!xml_parse($this->_file, file_get_contents($filename))) { + if (xml_parse($this->_file, file_get_contents($filename)) === 0) { $ex = sprintf('XML error: %s at line %d of file %s', xml_error_string(xml_get_error_code($this->_file)), xml_get_current_line_number($this->_file), @@ -179,7 +177,7 @@ protected function _startElement($file, $name, $attrib) */ protected function _endElement($file, $name) { - if (($this->_seg !== null) and ($name !== 'seg')) { + if ($this->_seg !== null && $name !== 'seg') { $this->_content .= ""; } else { switch (strtolower($name)) { @@ -195,7 +193,7 @@ protected function _endElement($file, $name) $this->_tu = $this->_content; } - if (!empty($this->_content) or (!isset($this->_data[$this->_tuv][$this->_tu]))) { + if (!empty($this->_content) || !isset($this->_data[$this->_tuv][$this->_tu])) { $this->_data[$this->_tuv][$this->_tu] = $this->_content; } break; @@ -213,7 +211,7 @@ protected function _endElement($file, $name) */ protected function _contentElement($file, $data) { - if (($this->_seg !== null) and ($this->_tu !== null) and ($this->_tuv !== null)) { + if ($this->_seg !== null && $this->_tu !== null && $this->_tuv !== null) { $this->_content .= $data; } } @@ -230,8 +228,7 @@ protected function _findEncoding($filename) $file = file_get_contents($filename, null, null, 0, 100); if (strpos($file, "encoding") !== false) { $encoding = substr($file, strpos($file, "encoding") + 9); - $encoding = substr($encoding, 1, strpos($encoding, $encoding[0], 1) - 1); - return $encoding; + return substr($encoding, 1, strpos($encoding, $encoding[0], 1) - 1); } return 'UTF-8'; } diff --git a/library/Zend/Translate/Adapter/Xliff.php b/library/Zend/Translate/Adapter/Xliff.php index e8c664bd5b..b0738e8b87 100644 --- a/library/Zend/Translate/Adapter/Xliff.php +++ b/library/Zend/Translate/Adapter/Xliff.php @@ -71,11 +71,7 @@ protected function _loadTranslationData($filename, $locale, array $options = arr throw new Zend_Translate_Exception('Translation file \'' . $filename . '\' is not readable.'); } - if (empty($options['useId'])) { - $this->_useId = false; - } else { - $this->_useId = true; - } + $this->_useId = !empty($options['useId']); $encoding = $this->_findEncoding($filename); $this->_target = $locale; @@ -89,12 +85,10 @@ protected function _loadTranslationData($filename, $locale, array $options = arr Zend_Xml_Security::scanFile($filename); } catch (Zend_Xml_Exception $e) { require_once 'Zend/Translate/Exception.php'; - throw new Zend_Translate_Exception( - $e->getMessage() - ); + throw new Zend_Translate_Exception($e->getMessage(), $e->getCode(), $e); } - if (!xml_parse($this->_file, file_get_contents($filename))) { + if (xml_parse($this->_file, file_get_contents($filename)) === 0) { $ex = sprintf('XML error: %s at line %d of file %s', xml_error_string(xml_get_error_code($this->_file)), xml_get_current_line_number($this->_file), @@ -115,7 +109,7 @@ private function _startElement($file, $name, $attrib) $this->_scontent .= " $key=\"$value\""; } $this->_scontent .= ">"; - } else if ($this->_ttag === true) { + } elseif ($this->_ttag === true) { $this->_tcontent .= "<".$name; foreach($attrib as $key => $value) { $this->_tcontent .= " $key=\"$value\""; @@ -164,9 +158,9 @@ private function _startElement($file, $name, $attrib) private function _endElement($file, $name) { - if (($this->_stag === true) and ($name !== 'source')) { + if ($this->_stag === true && $name !== 'source') { $this->_scontent .= ""; - } else if (($this->_ttag === true) and ($name !== 'target')) { + } elseif ($this->_ttag === true && $name !== 'target') { $this->_tcontent .= ""; } else { switch (strtolower($name)) { @@ -182,11 +176,9 @@ private function _endElement($file, $name) !isset($this->_data[$this->_source][$this->_langId])) { $this->_data[$this->_source][$this->_langId] = $this->_scontent; } - } else { - if (!empty($this->_scontent) && - !isset($this->_data[$this->_source][$this->_scontent])) { - $this->_data[$this->_source][$this->_scontent] = $this->_scontent; - } + } elseif (!empty($this->_scontent) && + !isset($this->_data[$this->_source][$this->_scontent])) { + $this->_data[$this->_source][$this->_scontent] = $this->_scontent; } $this->_stag = false; break; @@ -196,11 +188,9 @@ private function _endElement($file, $name) !isset($this->_data[$this->_target][$this->_langId])) { $this->_data[$this->_target][$this->_langId] = $this->_tcontent; } - } else { - if (!empty($this->_tcontent) && !empty($this->_scontent) && - !isset($this->_data[$this->_target][$this->_scontent])) { - $this->_data[$this->_target][$this->_scontent] = $this->_tcontent; - } + } elseif (!empty($this->_tcontent) && !empty($this->_scontent) && + !isset($this->_data[$this->_target][$this->_scontent])) { + $this->_data[$this->_target][$this->_scontent] = $this->_tcontent; } $this->_ttag = false; break; @@ -212,11 +202,11 @@ private function _endElement($file, $name) private function _contentElement($file, $data) { - if (($this->_transunit !== null) and ($this->_source !== null) and ($this->_stag === true)) { + if ($this->_transunit !== null && $this->_source !== null && $this->_stag === true) { $this->_scontent .= $data; } - if (($this->_transunit !== null) and ($this->_target !== null) and ($this->_ttag === true)) { + if ($this->_transunit !== null && $this->_target !== null && $this->_ttag === true) { $this->_tcontent .= $data; } } @@ -226,8 +216,7 @@ private function _findEncoding($filename) $file = file_get_contents($filename, null, null, 0, 100); if (strpos($file, "encoding") !== false) { $encoding = substr($file, strpos($file, "encoding") + 9); - $encoding = substr($encoding, 1, strpos($encoding, $encoding[0], 1) - 1); - return $encoding; + return substr($encoding, 1, strpos($encoding, $encoding[0], 1) - 1); } return 'UTF-8'; } diff --git a/library/Zend/Translate/Adapter/XmlTm.php b/library/Zend/Translate/Adapter/XmlTm.php index 87d22695e0..f688c35c0b 100644 --- a/library/Zend/Translate/Adapter/XmlTm.php +++ b/library/Zend/Translate/Adapter/XmlTm.php @@ -77,12 +77,10 @@ protected function _loadTranslationData($filename, $locale, array $options = arr Zend_Xml_Security::scanFile($filename); } catch (Zend_Xml_Exception $e) { require_once 'Zend/Translate/Exception.php'; - throw new Zend_Translate_Exception( - $e->getMessage() - ); + throw new Zend_Translate_Exception($e->getMessage(), $e->getCode(), $e); } - if (!xml_parse($this->_file, file_get_contents($filename))) { + if (xml_parse($this->_file, file_get_contents($filename)) === 0) { $ex = sprintf('XML error: %s at line %d of file %s', xml_error_string(xml_get_error_code($this->_file)), xml_get_current_line_number($this->_file), @@ -111,8 +109,7 @@ private function _endElement($file, $name) { switch (strtolower($name)) { case 'tm:tu': - if (!empty($this->_tag) and !empty($this->_content) or - (isset($this->_data[$this->_lang][$this->_tag]) === false)) { + if (!empty($this->_tag) && !empty($this->_content) || !isset($this->_data[$this->_lang][$this->_tag])) { $this->_data[$this->_lang][$this->_tag] = $this->_content; } $this->_tag = null; @@ -136,8 +133,7 @@ private function _findEncoding($filename) $file = file_get_contents($filename, null, null, 0, 100); if (strpos($file, "encoding") !== false) { $encoding = substr($file, strpos($file, "encoding") + 9); - $encoding = substr($encoding, 1, strpos($encoding, $encoding[0], 1) - 1); - return $encoding; + return substr($encoding, 1, strpos($encoding, $encoding[0], 1) - 1); } return 'UTF-8'; } diff --git a/library/Zend/Uri.php b/library/Zend/Uri.php index e1660d8bf1..dfa319b552 100644 --- a/library/Zend/Uri.php +++ b/library/Zend/Uri.php @@ -98,15 +98,15 @@ public static function factory($uri = 'http', $className = null) // Separate the scheme from the scheme-specific parts $uri = explode(':', $uri, 2); $scheme = strtolower($uri[0]); - $schemeSpecific = isset($uri[1]) === true ? $uri[1] : ''; + $schemeSpecific = isset($uri[1]) ? $uri[1] : ''; - if (strlen($scheme) === 0) { + if ($scheme === '') { require_once 'Zend/Uri/Exception.php'; throw new Zend_Uri_Exception('An empty string was supplied for the scheme'); } // Security check: $scheme is used to load a class file, so only alphanumerics are allowed. - if (ctype_alnum($scheme) === false) { + if (!ctype_alnum($scheme)) { require_once 'Zend/Uri/Exception.php'; throw new Zend_Uri_Exception('Illegal scheme supplied, only alphanumeric characters are permitted'); } @@ -137,7 +137,7 @@ public static function factory($uri = 'http', $className = null) Zend_Loader::loadClass($className); } catch (Exception $e) { require_once 'Zend/Uri/Exception.php'; - throw new Zend_Uri_Exception("\"$className\" not found"); + throw new Zend_Uri_Exception("\"$className\" not found", $e->getCode(), $e); } $schemeHandler = new $className($scheme, $schemeSpecific); @@ -157,7 +157,7 @@ public static function factory($uri = 'http', $className = null) */ public function getScheme() { - if (empty($this->_scheme) === false) { + if (!empty($this->_scheme)) { return $this->_scheme; } else { return false; diff --git a/library/Zend/Uri/Http.php b/library/Zend/Uri/Http.php index f05416e7be..8678226803 100644 --- a/library/Zend/Uri/Http.php +++ b/library/Zend/Uri/Http.php @@ -143,7 +143,7 @@ protected function __construct($scheme, $schemeSpecific = '') // If no scheme-specific part was supplied, the user intends to create // a new URI with this object. No further parsing is required. - if (strlen($schemeSpecific) === 0) { + if ((string) $schemeSpecific === '') { return; } @@ -151,7 +151,7 @@ protected function __construct($scheme, $schemeSpecific = '') $this->_parseUri($schemeSpecific); // Validate the URI - if ($this->valid() === false) { + if (!$this->valid()) { require_once 'Zend/Uri/Exception.php'; throw new Zend_Uri_Exception('Invalid URI supplied'); } @@ -169,22 +169,20 @@ protected function __construct($scheme, $schemeSpecific = '') */ public static function fromString($uri) { - if (is_string($uri) === false) { + if (!is_string($uri)) { require_once 'Zend/Uri/Exception.php'; throw new Zend_Uri_Exception('$uri is not a string'); } $uri = explode(':', $uri, 2); $scheme = strtolower($uri[0]); - $schemeSpecific = isset($uri[1]) === true ? $uri[1] : ''; + $schemeSpecific = isset($uri[1]) ? $uri[1] : ''; - if (in_array($scheme, array('http', 'https')) === false) { + if (!in_array($scheme, array('http', 'https'))) { require_once 'Zend/Uri/Exception.php'; throw new Zend_Uri_Exception("Invalid scheme: '$scheme'"); } - - $schemeHandler = new Zend_Uri_Http($scheme, $schemeSpecific); - return $schemeHandler; + return new Zend_Uri_Http($scheme, $schemeSpecific); } /** @@ -211,12 +209,12 @@ protected function _parseUri($schemeSpecific) } // Save URI components that need no further decomposition - $this->_path = isset($matches[4]) === true ? $matches[4] : ''; - $this->_query = isset($matches[6]) === true ? $matches[6] : ''; - $this->_fragment = isset($matches[8]) === true ? $matches[8] : ''; + $this->_path = isset($matches[4]) ? $matches[4] : ''; + $this->_query = isset($matches[6]) ? $matches[6] : ''; + $this->_fragment = isset($matches[8]) ? $matches[8] : ''; // Additional decomposition to get username, password, host, and port - $combo = isset($matches[3]) === true ? $matches[3] : ''; + $combo = isset($matches[3]) ? $matches[3] : ''; $pattern = '~^(([^:@]*)(:([^@]*))?@)?((?(?=[[])[[][^]]+[]]|[^:]+))(:(.*))?$~'; $status = @preg_match($pattern, (string) $combo, $matches); if ($status === false) { @@ -225,12 +223,12 @@ protected function _parseUri($schemeSpecific) } // Save remaining URI components - $this->_username = isset($matches[2]) === true ? $matches[2] : ''; - $this->_password = isset($matches[4]) === true ? $matches[4] : ''; - $this->_host = isset($matches[5]) === true + $this->_username = isset($matches[2]) ? $matches[2] : ''; + $this->_password = isset($matches[4]) ? $matches[4] : ''; + $this->_host = isset($matches[5]) ? preg_replace('~^\[([^]]+)\]$~', '\1', $matches[5]) // Strip wrapper [] from IPv6 literal : ''; - $this->_port = isset($matches[7]) === true ? $matches[7] : ''; + $this->_port = isset($matches[7]) ? $matches[7] : ''; } /** @@ -242,7 +240,7 @@ protected function _parseUri($schemeSpecific) */ public function getUri() { - if ($this->valid() === false) { + if (!$this->valid()) { require_once 'Zend/Uri/Exception.php'; throw new Zend_Uri_Exception('One or more parts of the URI are invalid'); } @@ -272,13 +270,7 @@ public function getUri() public function valid() { // Return true if and only if all parts of the URI have passed validation - return $this->validateUsername() - and $this->validatePassword() - and $this->validateHost() - and $this->validatePort() - and $this->validatePath() - and $this->validateQuery() - and $this->validateFragment(); + return $this->validateUsername() && $this->validatePassword() && $this->validateHost() && $this->validatePort() && $this->validatePath() && $this->validateQuery() && $this->validateFragment(); } /** @@ -307,7 +299,7 @@ public function validateUsername($username = null) } // If the username is empty, then it is considered valid - if (strlen($username) === 0) { + if ((string) $username === '') { return true; } @@ -332,7 +324,7 @@ public function validateUsername($username = null) */ public function setUsername($username) { - if ($this->validateUsername($username) === false) { + if (!$this->validateUsername($username)) { require_once 'Zend/Uri/Exception.php'; throw new Zend_Uri_Exception("Username \"$username\" is not a valid HTTP username"); } @@ -369,12 +361,12 @@ public function validatePassword($password = null) } // If the password is empty, then it is considered valid - if (strlen($password) === 0) { + if ((string) $password === '') { return true; } // If the password is nonempty, but there is no username, then it is considered invalid - if (strlen($password) > 0 and strlen($this->_username) === 0) { + if (strlen($password) > 0 && $this->_username === '') { return false; } @@ -399,7 +391,7 @@ public function validatePassword($password = null) */ public function setPassword($password) { - if ($this->validatePassword($password) === false) { + if (!$this->validatePassword($password)) { require_once 'Zend/Uri/Exception.php'; throw new Zend_Uri_Exception("Password \"$password\" is not a valid HTTP password."); } @@ -435,7 +427,7 @@ public function validateHost($host = null) } // If the host is empty, then it is considered invalid - if (strlen($host) === 0) { + if ((string) $host === '') { return false; } @@ -454,7 +446,7 @@ public function validateHost($host = null) */ public function setHost($host) { - if ($this->validateHost($host) === false) { + if (!$this->validateHost($host)) { require_once 'Zend/Uri/Exception.php'; throw new Zend_Uri_Exception("Host \"$host\" is not a valid HTTP host"); } @@ -489,12 +481,12 @@ public function validatePort($port = null) } // If the port is empty, then it is considered valid - if (strlen($port) === 0) { + if ((string) $port === '') { return true; } // Check the port against the allowed values - return ctype_digit((string) $port) and 1 <= $port and $port <= 65535; + return ctype_digit((string) $port) && 1 <= $port && $port <= 65535; } /** @@ -506,7 +498,7 @@ public function validatePort($port = null) */ public function setPort($port) { - if ($this->validatePort($port) === false) { + if (!$this->validatePort($port)) { require_once 'Zend/Uri/Exception.php'; throw new Zend_Uri_Exception("Port \"$port\" is not a valid HTTP port."); } @@ -542,7 +534,7 @@ public function validatePath($path = null) } // If the path is empty, then it is considered valid - if (strlen($path) === 0) { + if ((string) $path === '') { return true; } @@ -566,7 +558,7 @@ public function validatePath($path = null) */ public function setPath($path) { - if ($this->validatePath($path) === false) { + if (!$this->validatePath($path)) { require_once 'Zend/Uri/Exception.php'; throw new Zend_Uri_Exception("Path \"$path\" is not a valid HTTP path"); } @@ -620,7 +612,7 @@ public function validateQuery($query = null) } // If query is empty, it is considered to be valid - if (strlen($query) === 0) { + if ((string) $query === '') { return true; } @@ -674,25 +666,25 @@ public function setQuery($query) $oldQuery = $this->_query; // If query is empty, set an empty string - if (empty($query) === true) { + if (empty($query)) { $this->_query = ''; return $oldQuery; } // If query is an array, make a string out of it - if (is_array($query) === true) { + if (is_array($query)) { $query = http_build_query($query, '', '&'); } else { // If it is a string, make sure it is valid. If not parse and encode it $query = (string) $query; - if ($this->validateQuery($query) === false) { + if (!$this->validateQuery($query)) { parse_str($query, $queryArray); $query = http_build_query($queryArray, '', '&'); } } // Make sure the query is valid, and set it - if ($this->validateQuery($query) === false) { + if (!$this->validateQuery($query)) { require_once 'Zend/Uri/Exception.php'; throw new Zend_Uri_Exception("'$query' is not a valid query string"); } @@ -728,7 +720,7 @@ public function validateFragment($fragment = null) } // If fragment is empty, it is considered to be valid - if (strlen($fragment) === 0) { + if ((string) $fragment === '') { return true; } @@ -752,7 +744,7 @@ public function validateFragment($fragment = null) */ public function setFragment($fragment) { - if ($this->validateFragment($fragment) === false) { + if (!$this->validateFragment($fragment)) { require_once 'Zend/Uri/Exception.php'; throw new Zend_Uri_Exception("Fragment \"$fragment\" is not a valid HTTP fragment"); } diff --git a/library/Zend/Validate.php b/library/Zend/Validate.php index 956d3119dc..dc91f38b91 100644 --- a/library/Zend/Validate.php +++ b/library/Zend/Validate.php @@ -222,11 +222,7 @@ public static function is($value, $classBaseName, array $args = array(), $namesp } } - if ($numeric) { - $object = $class->newInstanceArgs($args); - } else { - $object = $class->newInstance($args); - } + $object = $numeric ? $class->newInstanceArgs($args) : $class->newInstance($args); } else { $object = $class->newInstance(); } diff --git a/library/Zend/Validate/Abstract.php b/library/Zend/Validate/Abstract.php index 7e2420a0a4..8ab1cc22ff 100644 --- a/library/Zend/Validate/Abstract.php +++ b/library/Zend/Validate/Abstract.php @@ -224,11 +224,7 @@ protected function _createMessage($messageKey, $value) } if (is_object($value)) { - if (!in_array('__toString', get_class_methods($value))) { - $value = get_class($value) . ' object'; - } else { - $value = $value->__toString(); - } + $value = in_array('__toString', get_class_methods($value)) ? $value->__toString() : get_class($value) . ' object'; } elseif (is_array($value)) { $value = $this->_implodeRecursive($value); } else { @@ -266,11 +262,7 @@ protected function _implodeRecursive(array $pieces) { $values = array(); foreach ($pieces as $item) { - if (is_array($item)) { - $values[] = $this->_implodeRecursive($item); - } else { - $values[] = $item; - } + $values[] = is_array($item) ? $this->_implodeRecursive($item) : $item; } return implode(', ', $values); @@ -372,7 +364,7 @@ public function getTranslator() return null; } - if (null === $this->_translator) { + if (!$this->_translator instanceof \Zend_Translate_Adapter) { return self::getDefaultTranslator(); } @@ -414,7 +406,7 @@ public static function setDefaultTranslator($translator = null) */ public static function getDefaultTranslator() { - if (null === self::$_defaultTranslator) { + if (!self::$_defaultTranslator instanceof \Zend_Translate_Adapter) { require_once 'Zend/Registry.php'; if (Zend_Registry::isRegistered('Zend_Translate')) { $translator = Zend_Registry::get('Zend_Translate'); diff --git a/library/Zend/Validate/Alnum.php b/library/Zend/Validate/Alnum.php index 5091830215..e5d824b37e 100644 --- a/library/Zend/Validate/Alnum.php +++ b/library/Zend/Validate/Alnum.php @@ -74,11 +74,7 @@ public function __construct($allowWhiteSpace = false) } if (is_array($allowWhiteSpace)) { - if (array_key_exists('allowWhiteSpace', $allowWhiteSpace)) { - $allowWhiteSpace = $allowWhiteSpace['allowWhiteSpace']; - } else { - $allowWhiteSpace = false; - } + $allowWhiteSpace = array_key_exists('allowWhiteSpace', $allowWhiteSpace) ? $allowWhiteSpace['allowWhiteSpace'] : false; } $this->allowWhiteSpace = (boolean) $allowWhiteSpace; @@ -138,7 +134,7 @@ public function isValid($value) self::$_filter->allowWhiteSpace = $this->allowWhiteSpace; - if ($value != self::$_filter->filter($value)) { + if ($value !== self::$_filter->filter($value)) { $this->_error(self::NOT_ALNUM); return false; } diff --git a/library/Zend/Validate/Alpha.php b/library/Zend/Validate/Alpha.php index c9ea9828f5..2eb76e7a3e 100644 --- a/library/Zend/Validate/Alpha.php +++ b/library/Zend/Validate/Alpha.php @@ -74,11 +74,7 @@ public function __construct($allowWhiteSpace = false) } if (is_array($allowWhiteSpace)) { - if (array_key_exists('allowWhiteSpace', $allowWhiteSpace)) { - $allowWhiteSpace = $allowWhiteSpace['allowWhiteSpace']; - } else { - $allowWhiteSpace = false; - } + $allowWhiteSpace = array_key_exists('allowWhiteSpace', $allowWhiteSpace) ? $allowWhiteSpace['allowWhiteSpace'] : false; } $this->allowWhiteSpace = (boolean) $allowWhiteSpace; diff --git a/library/Zend/Validate/Barcode/AdapterAbstract.php b/library/Zend/Validate/Barcode/AdapterAbstract.php index 05dc2b9faf..46b320bf57 100644 --- a/library/Zend/Validate/Barcode/AdapterAbstract.php +++ b/library/Zend/Validate/Barcode/AdapterAbstract.php @@ -88,10 +88,10 @@ public function checkLength($value) $found = true; } elseif ($length == 'even') { $count = $fixum % 2; - $found = ($count == 0) ? true : false; + $found = $count == 0; } elseif ($length == 'odd') { $count = $fixum % 2; - $found = ($count == 1) ? true : false; + $found = $count == 1; } return $found; @@ -120,12 +120,7 @@ public function checkChars($value) $value = str_replace($char, '', $value); } } - - if (strlen($value) > 0) { - return false; - } - - return true; + return !(strlen($value) > 0); } /** @@ -137,10 +132,8 @@ public function checkChars($value) public function checksum($value) { $checksum = $this->getChecksum(); - if (!empty($checksum)) { - if (method_exists($this, $checksum)) { - return call_user_func(array($this, $checksum), $value); - } + if (!empty($checksum) && method_exists($this, $checksum)) { + return call_user_func(array($this, $checksum), $value); } return false; @@ -306,10 +299,6 @@ protected function _postnet($value) $check %= 10; $check = 10 - $check; - if ($check == $checksum) { - return true; - } - - return false; + return $check == $checksum; } } diff --git a/library/Zend/Validate/Barcode/Code39.php b/library/Zend/Validate/Barcode/Code39.php index 37b2f13afd..100805b67a 100644 --- a/library/Zend/Validate/Barcode/Code39.php +++ b/library/Zend/Validate/Barcode/Code39.php @@ -89,10 +89,6 @@ protected function _code39($value) } $mod = $count % 43; - if ($mod == $this->_check[$checksum]) { - return true; - } - - return false; + return $mod == $this->_check[$checksum]; } } diff --git a/library/Zend/Validate/Barcode/Code93.php b/library/Zend/Validate/Barcode/Code93.php index e09ba17ec1..a1bc16c58b 100644 --- a/library/Zend/Validate/Barcode/Code93.php +++ b/library/Zend/Validate/Barcode/Code93.php @@ -108,11 +108,6 @@ protected function _code93($value) --$length; } $check .= array_search(($count % 47), $this->_check); - - if ($check == $checksum) { - return true; - } - - return false; + return $check === $checksum; } } diff --git a/library/Zend/Validate/Barcode/Issn.php b/library/Zend/Validate/Barcode/Issn.php index a74fa5379e..2e0f1c6df3 100644 --- a/library/Zend/Validate/Barcode/Issn.php +++ b/library/Zend/Validate/Barcode/Issn.php @@ -58,10 +58,8 @@ class Zend_Validate_Barcode_Issn extends Zend_Validate_Barcode_AdapterAbstract */ public function checkChars($value) { - if (strlen($value) != 8) { - if (strpos($value, 'X') !== false) { - return false; - } + if (strlen($value) != 8 && strpos($value, 'X') !== false) { + return false; } return parent::checkChars($value); @@ -75,11 +73,7 @@ public function checkChars($value) */ public function checksum($value) { - if (strlen($value) == 8) { - $this->_checksum = '_issn'; - } else { - $this->_checksum = '_gtin'; - } + $this->_checksum = strlen($value) == 8 ? '_issn' : '_gtin'; return parent::checksum($value); } @@ -110,7 +104,7 @@ protected function _issn($value) $check = 11 - $check; if ($check == $checksum) { return true; - } else if (($check == 10) && ($checksum == 'X')) { + } elseif (($check == 10) && ($checksum == 'X')) { return true; } diff --git a/library/Zend/Validate/Barcode/Royalmail.php b/library/Zend/Validate/Barcode/Royalmail.php index 98fa38e64e..caa2ee8c4b 100644 --- a/library/Zend/Validate/Barcode/Royalmail.php +++ b/library/Zend/Validate/Barcode/Royalmail.php @@ -91,11 +91,7 @@ protected function _royalmail($value) $rowchkvalue = array_keys($this->_rows, $rowvalue); $colchkvalue = array_keys($this->_columns, $colvalue); $chkvalue = current(array_intersect($rowchkvalue, $colchkvalue)); - if ($chkvalue == $checksum) { - return true; - } - - return false; + return $chkvalue == $checksum; } /** diff --git a/library/Zend/Validate/Between.php b/library/Zend/Validate/Between.php index 53b68261dd..a20d8ae060 100644 --- a/library/Zend/Validate/Between.php +++ b/library/Zend/Validate/Between.php @@ -100,17 +100,15 @@ public function __construct($options) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (!is_array($options)) { + } elseif (!is_array($options)) { $options = func_get_args(); $temp['min'] = array_shift($options); if (!empty($options)) { $temp['max'] = array_shift($options); } - if (!empty($options)) { $temp['inclusive'] = array_shift($options); } - $options = $temp; } @@ -212,11 +210,9 @@ public function isValid($value) $this->_error(self::NOT_BETWEEN); return false; } - } else { - if ($this->_min >= $value || $value >= $this->_max) { - $this->_error(self::NOT_BETWEEN_STRICT); - return false; - } + } elseif ($this->_min >= $value || $value >= $this->_max) { + $this->_error(self::NOT_BETWEEN_STRICT); + return false; } return true; } diff --git a/library/Zend/Validate/CreditCard.php b/library/Zend/Validate/CreditCard.php index 8dfeff1d7d..3dbbc84e9c 100644 --- a/library/Zend/Validate/CreditCard.php +++ b/library/Zend/Validate/CreditCard.php @@ -142,13 +142,12 @@ public function __construct($options = array()) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (!is_array($options)) { + } elseif (!is_array($options)) { $options = func_get_args(); $temp['type'] = array_shift($options); if (!empty($options)) { $temp['service'] = array_shift($options); } - $options = $temp; } diff --git a/library/Zend/Validate/Date.php b/library/Zend/Validate/Date.php index e875aaf550..285ac36743 100644 --- a/library/Zend/Validate/Date.php +++ b/library/Zend/Validate/Date.php @@ -77,13 +77,12 @@ public function __construct($options = array()) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (!is_array($options)) { + } elseif (!is_array($options)) { $options = func_get_args(); $temp['format'] = array_shift($options); if (!empty($options)) { $temp['locale'] = array_shift($options); } - $options = $temp; } @@ -172,7 +171,7 @@ public function isValid($value) $value instanceof Zend_Date) { require_once 'Zend/Date.php'; if (!Zend_Date::isDate($value, $this->_format, $this->_locale)) { - if ($this->_checkFormat($value) === false) { + if (!$this->_checkFormat($value)) { $this->_error(self::FALSEFORMAT); } else { $this->_error(self::INVALID_DATE); @@ -211,8 +210,7 @@ private function _checkFormat($value) $parsed = Zend_Locale_Format::getDate($value, array( 'date_format' => $this->_format, 'format_type' => 'iso', 'fix_date' => false)); - if (isset($parsed['year']) and ((strpos(strtoupper($this->_format), 'YY') !== false) and - (strpos(strtoupper($this->_format), 'YYYY') === false))) { + if (isset($parsed['year']) && (strpos(strtoupper($this->_format), 'YY') !== false && strpos(strtoupper($this->_format), 'YYYY') === false)) { $parsed['year'] = Zend_Date::getFullYear($parsed['year']); } } catch (Exception $e) { @@ -220,34 +218,32 @@ private function _checkFormat($value) return false; } - if (((strpos($this->_format, 'Y') !== false) or (strpos($this->_format, 'y') !== false)) and - (!isset($parsed['year']))) { + if ((strpos($this->_format, 'Y') !== false || strpos($this->_format, 'y') !== false) && !isset($parsed['year'])) { // Year expected but not found return false; } - if ((strpos($this->_format, 'M') !== false) and (!isset($parsed['month']))) { + if (strpos($this->_format, 'M') !== false && !isset($parsed['month'])) { // Month expected but not found return false; } - if ((strpos($this->_format, 'd') !== false) and (!isset($parsed['day']))) { + if (strpos($this->_format, 'd') !== false && !isset($parsed['day'])) { // Day expected but not found return false; } - if (((strpos($this->_format, 'H') !== false) or (strpos($this->_format, 'h') !== false)) and - (!isset($parsed['hour']))) { + if ((strpos($this->_format, 'H') !== false || strpos($this->_format, 'h') !== false) && !isset($parsed['hour'])) { // Hour expected but not found return false; } - if ((strpos($this->_format, 'm') !== false) and (!isset($parsed['minute']))) { + if (strpos($this->_format, 'm') !== false && !isset($parsed['minute'])) { // Minute expected but not found return false; } - if ((strpos($this->_format, 's') !== false) and (!isset($parsed['second']))) { + if (strpos($this->_format, 's') !== false && !isset($parsed['second'])) { // Second expected but not found return false; } diff --git a/library/Zend/Validate/Db/Abstract.php b/library/Zend/Validate/Db/Abstract.php index ffee51f267..13c1609b4a 100644 --- a/library/Zend/Validate/Db/Abstract.php +++ b/library/Zend/Validate/Db/Abstract.php @@ -107,18 +107,16 @@ public function __construct($options) } if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (func_num_args() > 1) { + } elseif (func_num_args() > 1) { $options = func_get_args(); $temp['table'] = array_shift($options); $temp['field'] = array_shift($options); if (!empty($options)) { $temp['exclude'] = array_shift($options); } - if (!empty($options)) { $temp['adapter'] = array_shift($options); } - $options = $temp; } @@ -287,8 +285,7 @@ public function setSchema($schema) public function setSelect($select) { if (!$select instanceof Zend_Db_Select) { - throw new Zend_Validate_Exception('Select option must be a valid ' . - 'Zend_Db_Select object'); + throw new Zend_Validate_Exception('Select option must be a valid Zend_Db_Select object'); } $this->_select = $select; return $this; diff --git a/library/Zend/Validate/Db/NoRecordExists.php b/library/Zend/Validate/Db/NoRecordExists.php index 4dba8bc631..227b0c820b 100644 --- a/library/Zend/Validate/Db/NoRecordExists.php +++ b/library/Zend/Validate/Db/NoRecordExists.php @@ -41,7 +41,7 @@ public function isValid($value) $this->_setValue($value); $result = $this->_query($value); - if ($result) { + if ($result !== []) { $valid = false; $this->_error(self::ERROR_RECORD_FOUND); } diff --git a/library/Zend/Validate/Db/RecordExists.php b/library/Zend/Validate/Db/RecordExists.php index 540af13bc6..5843aacbd0 100644 --- a/library/Zend/Validate/Db/RecordExists.php +++ b/library/Zend/Validate/Db/RecordExists.php @@ -41,7 +41,7 @@ public function isValid($value) $this->_setValue($value); $result = $this->_query($value); - if (!$result) { + if ($result === []) { $valid = false; $this->_error(self::ERROR_NO_RECORD_FOUND); } diff --git a/library/Zend/Validate/EmailAddress.php b/library/Zend/Validate/EmailAddress.php index 53d9e3db24..c008d3dcd8 100644 --- a/library/Zend/Validate/EmailAddress.php +++ b/library/Zend/Validate/EmailAddress.php @@ -138,17 +138,15 @@ public function __construct($options = array()) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (!is_array($options)) { + } elseif (!is_array($options)) { $options = func_get_args(); $temp['allow'] = array_shift($options); if (!empty($options)) { $temp['mx'] = array_shift($options); } - if (!empty($options)) { $temp['hostname'] = array_shift($options); } - $options = $temp; } @@ -245,7 +243,7 @@ public function getHostnameValidator() */ public function setHostnameValidator(Zend_Validate_Hostname $hostnameValidator = null, $allow = Zend_Validate_Hostname::ALLOW_DNS) { - if (!$hostnameValidator) { + if ($hostnameValidator === null) { $hostnameValidator = new Zend_Validate_Hostname($allow); } @@ -355,7 +353,7 @@ private function _isReserved($host){ $octet = explode('.',$host); if ((int)$octet[0] >= 224) { return true; - } else if (array_key_exists($octet[0], $this->_invalidIp)) { + } elseif (array_key_exists($octet[0], $this->_invalidIp)) { foreach ((array)$this->_invalidIp[$octet[0]] as $subnetData) { // we skip the first loop as we already know that octet matches for ($i = 1; $i < 4; $i++) { @@ -383,7 +381,6 @@ private function _isReserved($host){ } } } - return true; } else { return false; @@ -459,7 +456,7 @@ private function _validateMXRecords() $result = getmxrr($hostname, $mxHosts); if (!$result) { $this->_error(self::INVALID_MX_RECORD); - } else if ($this->_options['deep'] && function_exists('checkdnsrr')) { + } elseif ($this->_options['deep'] && function_exists('checkdnsrr')) { $validAddress = false; $reserved = true; foreach ($mxHosts as $hostname) { @@ -476,7 +473,6 @@ private function _validateMXRecords() break; } } - if (!$validAddress) { $result = false; if ($reserved) { @@ -501,16 +497,14 @@ private function _validateHostnamePart() ->isValid($this->_hostname); if (!$hostname) { $this->_error(self::INVALID_HOSTNAME); - // Get messages and errors from hostnameValidator foreach ($this->_options['hostname']->getMessages() as $code => $message) { $this->_messages[$code] = $message; } - foreach ($this->_options['hostname']->getErrors() as $error) { $this->_errors[] = $error; } - } else if ($this->_options['mx']) { + } elseif ($this->_options['mx']) { // MX check on hostname $hostname = $this->_validateMXRecords(); } @@ -541,8 +535,7 @@ public function isValid($value) $this->_setValue($value); // Split email address up and disallow '..' - if ((strpos($value, '..') !== false) or - (!preg_match('/^(.+)@([^@]+)$/', $value, $matches))) { + if (strpos($value, '..') !== false || !preg_match('/^(.+)@([^@]+)$/', $value, $matches)) { $this->_error(self::INVALID_FORMAT); return false; } @@ -561,14 +554,7 @@ public function isValid($value) } $local = $this->_validateLocalPart(); - // If both parts valid, return true - if ($local && $length) { - if (($this->_options['domain'] && $hostname) || !$this->_options['domain']) { - return true; - } - } - - return false; + return $local && $length && (($this->_options['domain'] && $hostname) || !$this->_options['domain']); } } diff --git a/library/Zend/Validate/File/Count.php b/library/Zend/Validate/File/Count.php index aa822dfb14..cc080cef0f 100644 --- a/library/Zend/Validate/File/Count.php +++ b/library/Zend/Validate/File/Count.php @@ -147,11 +147,11 @@ public function getMin() */ public function setMin($min) { - if (is_array($min) and isset($min['min'])) { + if (is_array($min) && isset($min['min'])) { $min = $min['min']; } - if (!is_string($min) and !is_numeric($min)) { + if (!is_string($min) && !is_numeric($min)) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception ('Invalid options to validator provided'); } @@ -186,11 +186,11 @@ public function getMax() */ public function setMax($max) { - if (is_array($max) and isset($max['max'])) { + if (is_array($max) && isset($max['max'])) { $max = $max['max']; } - if (!is_string($max) and !is_numeric($max)) { + if (!is_string($max) && !is_numeric($max)) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception ('Invalid options to validator provided'); } diff --git a/library/Zend/Validate/File/ExcludeExtension.php b/library/Zend/Validate/File/ExcludeExtension.php index e894af6a34..f5144ef8c5 100644 --- a/library/Zend/Validate/File/ExcludeExtension.php +++ b/library/Zend/Validate/File/ExcludeExtension.php @@ -74,16 +74,15 @@ public function isValid($value, $file = null) $extensions = $this->getExtension(); - if ($this->_case and (!in_array($info['extension'], $extensions))) { + if ($this->_case && !in_array($info['extension'], $extensions)) { return true; - } else if (!$this->_case) { + } elseif (!$this->_case) { $found = false; foreach ($extensions as $extension) { - if (strtolower($extension) == strtolower($info['extension'])) { + if (strtolower($extension) === strtolower($info['extension'])) { $found = true; } } - if (!$found) { return true; } diff --git a/library/Zend/Validate/File/Exists.php b/library/Zend/Validate/File/Exists.php index 8da1ccdd7d..48f840ef41 100644 --- a/library/Zend/Validate/File/Exists.php +++ b/library/Zend/Validate/File/Exists.php @@ -69,9 +69,9 @@ public function __construct($directory = array()) { if ($directory instanceof Zend_Config) { $directory = $directory->toArray(); - } else if (is_string($directory)) { + } elseif (is_string($directory)) { $directory = explode(',', $directory); - } else if (!is_array($directory)) { + } elseif (!is_array($directory)) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception ('Invalid options to validator provided'); } @@ -122,7 +122,7 @@ public function addDirectory($directory) if (is_string($directory)) { $directory = explode(',', $directory); - } else if (!is_array($directory)) { + } elseif (!is_array($directory)) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception ('Invalid options to validator provided'); } @@ -160,9 +160,9 @@ public function addDirectory($directory) public function isValid($value, $file = null) { $directories = $this->getDirectory(true); - if (($file !== null) and (!empty($file['destination']))) { + if ($file !== null && !empty($file['destination'])) { $directories[] = $file['destination']; - } else if (!isset($file['name'])) { + } elseif (!isset($file['name'])) { $file['name'] = $value; } diff --git a/library/Zend/Validate/File/Extension.php b/library/Zend/Validate/File/Extension.php index 92f9f06a87..c71e69d676 100644 --- a/library/Zend/Validate/File/Extension.php +++ b/library/Zend/Validate/File/Extension.php @@ -84,7 +84,7 @@ public function __construct($options) $this->setCase($case); } - if (is_array($options) and isset($options['case'])) { + if (is_array($options) && isset($options['case'])) { $this->setCase($options['case']); unset($options['case']); } @@ -121,9 +121,7 @@ public function setCase($case) */ public function getExtension() { - $extension = explode(',', $this->_extension); - - return $extension; + return explode(',', $this->_extension); } /** @@ -207,9 +205,9 @@ public function isValid($value, $file = null) if ($this->_case && (in_array($info['extension'], $extensions))) { return true; - } else if (!$this->getCase()) { + } elseif (!$this->getCase()) { foreach ($extensions as $extension) { - if (strtolower($extension) == strtolower($info['extension'])) { + if (strtolower($extension) === strtolower($info['extension'])) { return true; } } diff --git a/library/Zend/Validate/File/FilesSize.php b/library/Zend/Validate/File/FilesSize.php index b648133416..05689674cb 100644 --- a/library/Zend/Validate/File/FilesSize.php +++ b/library/Zend/Validate/File/FilesSize.php @@ -154,11 +154,6 @@ public function isValid($value, $file = null) $this->_throw($file, self::TOO_SMALL); } } - - if (count($this->_messages) > 0) { - return false; - } - - return true; + return !($this->_messages !== []); } } diff --git a/library/Zend/Validate/File/Hash.php b/library/Zend/Validate/File/Hash.php index 54b036756f..5c5cb2044f 100644 --- a/library/Zend/Validate/File/Hash.php +++ b/library/Zend/Validate/File/Hash.php @@ -116,7 +116,7 @@ public function addHash($options) { if (is_string($options)) { $options = array($options); - } else if (!is_array($options)) { + } elseif (!is_array($options)) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception("False parameter given"); } diff --git a/library/Zend/Validate/File/ImageSize.php b/library/Zend/Validate/File/ImageSize.php index 871fef84ff..2bfd32bfbb 100644 --- a/library/Zend/Validate/File/ImageSize.php +++ b/library/Zend/Validate/File/ImageSize.php @@ -139,7 +139,7 @@ public function __construct($options) $options['maxheight'] = array_shift($argv); } } - } else if (!is_array($options)) { + } elseif (!is_array($options)) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception ('Invalid options to validator provided'); } @@ -203,20 +203,16 @@ public function getImageHeight() */ public function setImageMin($options) { - if (isset($options['minwidth'])) { - if (($this->_maxwidth !== null) and ($options['minwidth'] > $this->_maxwidth)) { - require_once 'Zend/Validate/Exception.php'; - throw new Zend_Validate_Exception("The minimum image width must be less than or equal to the " - . " maximum image width, but {$options['minwidth']} > {$this->_maxwidth}"); - } + if (isset($options['minwidth']) && ($this->_maxwidth !== null && $options['minwidth'] > $this->_maxwidth)) { + require_once 'Zend/Validate/Exception.php'; + throw new Zend_Validate_Exception("The minimum image width must be less than or equal to the " + . " maximum image width, but {$options['minwidth']} > {$this->_maxwidth}"); } - if (isset($options['maxheight'])) { - if (($this->_maxheight !== null) and ($options['minheight'] > $this->_maxheight)) { - require_once 'Zend/Validate/Exception.php'; - throw new Zend_Validate_Exception("The minimum image height must be less than or equal to the " - . " maximum image height, but {$options['minheight']} > {$this->_maxheight}"); - } + if (isset($options['maxheight']) && ($this->_maxheight !== null && $options['minheight'] > $this->_maxheight)) { + require_once 'Zend/Validate/Exception.php'; + throw new Zend_Validate_Exception("The minimum image height must be less than or equal to the " + . " maximum image height, but {$options['minheight']} > {$this->_maxheight}"); } if (isset($options['minwidth'])) { @@ -240,20 +236,16 @@ public function setImageMin($options) */ public function setImageMax($options) { - if (isset($options['maxwidth'])) { - if (($this->_minwidth !== null) and ($options['maxwidth'] < $this->_minwidth)) { - require_once 'Zend/Validate/Exception.php'; - throw new Zend_Validate_Exception("The maximum image width must be greater than or equal to the " - . "minimum image width, but {$options['maxwidth']} < {$this->_minwidth}"); - } + if (isset($options['maxwidth']) && ($this->_minwidth !== null && $options['maxwidth'] < $this->_minwidth)) { + require_once 'Zend/Validate/Exception.php'; + throw new Zend_Validate_Exception("The maximum image width must be greater than or equal to the " + . "minimum image width, but {$options['maxwidth']} < {$this->_minwidth}"); } - if (isset($options['maxheight'])) { - if (($this->_minheight !== null) and ($options['maxheight'] < $this->_minheight)) { - require_once 'Zend/Validate/Exception.php'; - throw new Zend_Validate_Exception("The maximum image height must be greater than or equal to the " - . "minimum image height, but {$options['maxheight']} < {$this->_minwidth}"); - } + if (isset($options['maxheight']) && ($this->_minheight !== null && $options['maxheight'] < $this->_minheight)) { + require_once 'Zend/Validate/Exception.php'; + throw new Zend_Validate_Exception("The maximum image height must be greater than or equal to the " + . "minimum image height, but {$options['maxheight']} < {$this->_minwidth}"); } if (isset($options['maxwidth'])) { @@ -316,7 +308,7 @@ public function isValid($value, $file = null) $size = @getimagesize($value); $this->_setValue($file); - if (empty($size) or ($size[0] === 0) or ($size[1] === 0)) { + if (empty($size) || $size[0] === 0 || $size[1] === 0) { return $this->_throw($file, self::NOT_DETECTED); } @@ -326,7 +318,7 @@ public function isValid($value, $file = null) $this->_throw($file, self::WIDTH_TOO_SMALL); } - if (($this->_maxwidth !== null) and ($this->_maxwidth < $this->_width)) { + if ($this->_maxwidth !== null && $this->_maxwidth < $this->_width) { $this->_throw($file, self::WIDTH_TOO_BIG); } @@ -334,15 +326,10 @@ public function isValid($value, $file = null) $this->_throw($file, self::HEIGHT_TOO_SMALL); } - if (($this->_maxheight !== null) and ($this->_maxheight < $this->_height)) { + if ($this->_maxheight !== null && $this->_maxheight < $this->_height) { $this->_throw($file, self::HEIGHT_TOO_BIG); } - - if (count($this->_messages) > 0) { - return false; - } - - return true; + return !($this->_messages !== []); } /** diff --git a/library/Zend/Validate/File/MimeType.php b/library/Zend/Validate/File/MimeType.php index 61a8e26772..6065d77b39 100644 --- a/library/Zend/Validate/File/MimeType.php +++ b/library/Zend/Validate/File/MimeType.php @@ -169,7 +169,7 @@ public function getMagicFile() if (!empty($_ENV['MAGIC'])) { $this->setMagicFile($_ENV['MAGIC']); } elseif ( - !(@ini_get("safe_mode") == 'On' || @ini_get("safe_mode") === 1) + @ini_get("safe_mode") != 'On' && @ini_get("safe_mode") !== 1 && $this->shouldTryCommonMagicFiles() // @see ZF-11784 ) { require_once 'Zend/Validate/Exception.php'; @@ -207,11 +207,11 @@ public function setMagicFile($file) { if (empty($file)) { $this->_magicfile = null; - } else if (!(class_exists('finfo', false))) { + } elseif (!(class_exists('finfo', false))) { $this->_magicfile = null; require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('Magicfile can not be set. There is no finfo extension installed'); - } else if (!is_file($file) || !is_readable($file)) { + } elseif (!is_file($file) || !is_readable($file)) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('The given magicfile can not be read'); } else { diff --git a/library/Zend/Validate/File/NotExists.php b/library/Zend/Validate/File/NotExists.php index bf58dce229..995ff575a5 100644 --- a/library/Zend/Validate/File/NotExists.php +++ b/library/Zend/Validate/File/NotExists.php @@ -58,9 +58,9 @@ class Zend_Validate_File_NotExists extends Zend_Validate_File_Exists public function isValid($value, $file = null) { $directories = $this->getDirectory(true); - if (($file !== null) and (!empty($file['destination']))) { + if ($file !== null && !empty($file['destination'])) { $directories[] = $file['destination']; - } else if (!isset($file['name'])) { + } elseif (!isset($file['name'])) { $file['name'] = $value; } diff --git a/library/Zend/Validate/File/Size.php b/library/Zend/Validate/File/Size.php index bc9dea0d23..38afe1223c 100644 --- a/library/Zend/Validate/File/Size.php +++ b/library/Zend/Validate/File/Size.php @@ -181,7 +181,7 @@ public function getMin($raw = false) */ public function setMin($min) { - if (!is_string($min) and !is_numeric($min)) { + if (!is_string($min) && !is_numeric($min)) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception ('Invalid options to validator provided'); } @@ -311,12 +311,7 @@ public function isValid($value, $file = null) $this->_throw($file, self::TOO_BIG); } } - - if (count($this->_messages) > 0) { - return false; - } - - return true; + return !($this->_messages !== []); } /** diff --git a/library/Zend/Validate/File/Upload.php b/library/Zend/Validate/File/Upload.php index 5eae769846..acbe2adb4c 100644 --- a/library/Zend/Validate/File/Upload.php +++ b/library/Zend/Validate/File/Upload.php @@ -110,7 +110,7 @@ public function getFiles($file = null) } } - if (count($return) === 0) { + if ($return === []) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception("The file '$file' was not found"); } @@ -129,11 +129,7 @@ public function getFiles($file = null) */ public function setFiles($files = array()) { - if (count($files) === 0) { - $this->_files = $_FILES; - } else { - $this->_files = $files; - } + $this->_files = $files === [] ? $_FILES : $files; // see ZF-10738 if (is_null($this->_files)) { @@ -239,10 +235,8 @@ public function isValid($value, $file = null) */ protected function _throw($file, $errorType) { - if ($file !== null) { - if (is_array($file) and !empty($file['name'])) { - $this->_value = $file['name']; - } + if ($file !== null && (is_array($file) && !empty($file['name']))) { + $this->_value = $file['name']; } $this->_error($errorType); diff --git a/library/Zend/Validate/Float.php b/library/Zend/Validate/Float.php index f0879a5410..461e2dde45 100644 --- a/library/Zend/Validate/Float.php +++ b/library/Zend/Validate/Float.php @@ -62,11 +62,7 @@ public function __construct($locale = null) } if (is_array($locale)) { - if (array_key_exists('locale', $locale)) { - $locale = $locale['locale']; - } else { - $locale = null; - } + $locale = $locale['locale'] ?? null; } if (empty($locale)) { diff --git a/library/Zend/Validate/Hostname.php b/library/Zend/Validate/Hostname.php index cba3a88078..112ffdfa24 100644 --- a/library/Zend/Validate/Hostname.php +++ b/library/Zend/Validate/Hostname.php @@ -1521,21 +1521,18 @@ public function __construct($options = array()) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (!is_array($options)) { + } elseif (!is_array($options)) { $options = func_get_args(); $temp['allow'] = array_shift($options); if (!empty($options)) { $temp['idn'] = array_shift($options); } - if (!empty($options)) { $temp['tld'] = array_shift($options); } - if (!empty($options)) { $temp['ip'] = array_shift($options); } - $options = $temp; } @@ -1694,7 +1691,7 @@ public function isValid($value) // Check input against IP address schema if (preg_match('/^[0-9a-f:.]*$/i', $value) && $this->_options['ip']->setTranslator($this->getTranslator())->isValid($value)) { - if (!($this->_options['allow'] & self::ALLOW_IP)) { + if (($this->_options['allow'] & self::ALLOW_IP) === 0) { $this->_error(self::IP_ADDRESS_NOT_ALLOWED); return false; } else { @@ -1712,14 +1709,12 @@ public function isValid($value) // (see ZF-6363) // Local hostnames are allowed to be partitial (ending '.') - if ($this->_options['allow'] & self::ALLOW_LOCAL) { + if (($this->_options['allow'] & self::ALLOW_LOCAL) !== 0 && substr($value, -1) === '.') { + $value = substr($value, 0, -1); if (substr($value, -1) === '.') { - $value = substr($value, 0, -1); - if (substr($value, -1) === '.') { - // Empty hostnames (ending '..') are not allowed - $this->_error(self::INVALID_LOCAL_NAME); - return false; - } + // Empty hostnames (ending '..') are not allowed + $this->_error(self::INVALID_LOCAL_NAME); + return false; } } @@ -1734,7 +1729,6 @@ public function isValid($value) // Check input against DNS hostname schema if ((count($domainParts) > 1) && (strlen($value) >= 4) && (strlen($value) <= 254)) { $status = false; - $origenc = PHP_VERSION_ID < 50600 ? iconv_get_encoding('internal_encoding') : ini_get('default_charset'); @@ -1845,7 +1839,6 @@ public function isValid($value) $status = false; } } while (false); - if (PHP_VERSION_ID < 50600) { iconv_set_encoding('internal_encoding', $origenc); } else { @@ -1856,12 +1849,12 @@ public function isValid($value) if ($status && ($this->_options['allow'] & self::ALLOW_DNS)) { return true; } - } else if ($this->_options['allow'] & self::ALLOW_DNS) { + } elseif (($this->_options['allow'] & self::ALLOW_DNS) !== 0) { $this->_error(self::INVALID_HOSTNAME); } // Check for URI Syntax (RFC3986) - if ($this->_options['allow'] & self::ALLOW_URI) { + if (($this->_options['allow'] & self::ALLOW_URI) !== 0) { if (preg_match("/^([a-zA-Z0-9-._~!$&\'()*+,;=]|%[[:xdigit:]]{2}){1,254}$/i", $value)) { return true; } else { @@ -1943,13 +1936,13 @@ protected function decodePunycode($encoded) $pos = (int) ($pos * (36 - $tag)); } - $delta = intval($init ? (($index - $old_index) / 700) : (($index - $old_index) / 2)); - $delta += intval($delta / ($lengthd + 1)); + $delta = (int) ($init ? (($index - $old_index) / 700) : (($index - $old_index) / 2)); + $delta += (int) ($delta / ($lengthd + 1)); for ($key = 0; $delta > 910 / 2; $key += 36) { - $delta = intval($delta / 35); + $delta = (int) ($delta / 35); } - $base = intval($key + 36 * $delta / ($delta + 38)); + $base = (int) ($key + 36 * $delta / ($delta + 38)); $init = false; $char += (int) ($index / ($lengthd + 1)); $index %= ($lengthd + 1); diff --git a/library/Zend/Validate/Iban.php b/library/Zend/Validate/Iban.php index eea78aae34..203b4294d9 100644 --- a/library/Zend/Validate/Iban.php +++ b/library/Zend/Validate/Iban.php @@ -141,11 +141,7 @@ public function __construct($locale = null) } if (is_array($locale)) { - if (array_key_exists('locale', $locale)) { - $locale = $locale['locale']; - } else { - $locale = null; - } + $locale = $locale['locale'] ?? null; } if (empty($locale)) { @@ -232,11 +228,11 @@ public function isValid($value) '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35'), $format); - $temp = intval(substr($format, 0, 1)); + $temp = (int) substr($format, 0, 1); $len = strlen($format); for ($x = 1; $x < $len; ++$x) { $temp *= 10; - $temp += intval(substr($format, $x, 1)); + $temp += (int) substr($format, $x, 1); $temp %= 97; } diff --git a/library/Zend/Validate/Identical.php b/library/Zend/Validate/Identical.php index 97f3b8cce7..14aca2952a 100644 --- a/library/Zend/Validate/Identical.php +++ b/library/Zend/Validate/Identical.php @@ -76,9 +76,8 @@ public function __construct($token = null) if (array_key_exists('strict', $token)) { $this->setStrict($token['strict']); } - $this->setToken($token['token']); - } else if (null !== $token) { + } elseif (null !== $token) { $this->setToken($token); } } diff --git a/library/Zend/Validate/InArray.php b/library/Zend/Validate/InArray.php index 3f3ec243a2..d0d586a333 100644 --- a/library/Zend/Validate/InArray.php +++ b/library/Zend/Validate/InArray.php @@ -72,7 +72,7 @@ public function __construct($options) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (!is_array($options)) { + } elseif (!is_array($options)) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('Array expected as parameter'); } else { @@ -188,14 +188,12 @@ public function isValid($value) if ($element === $value) { return true; } - } else if ($element == $value) { + } elseif ($element == $value) { return true; } } - } else { - if (in_array($value, $this->_haystack, $this->_strict)) { - return true; - } + } elseif (in_array($value, $this->_haystack, $this->_strict)) { + return true; } $this->_error(self::NOT_IN_ARRAY); diff --git a/library/Zend/Validate/Int.php b/library/Zend/Validate/Int.php index 1bcf31dba0..6e47bef546 100644 --- a/library/Zend/Validate/Int.php +++ b/library/Zend/Validate/Int.php @@ -62,11 +62,7 @@ public function __construct($locale = null) } if (is_array($locale)) { - if (array_key_exists('locale', $locale)) { - $locale = $locale['locale']; - } else { - $locale = null; - } + $locale = $locale['locale'] ?? null; } if (empty($locale)) { @@ -127,7 +123,7 @@ public function isValid($value) $valueFiltered = str_replace($locale['decimal_point'], '.', $value); $valueFiltered = str_replace($locale['thousands_sep'], '', $valueFiltered); - if (strval(intval($valueFiltered)) != $valueFiltered) { + if (strval((int) $valueFiltered) != $valueFiltered) { $this->_error(self::NOT_INT); return false; } diff --git a/library/Zend/Validate/Ip.php b/library/Zend/Validate/Ip.php index ede95e92c0..859381fab7 100644 --- a/library/Zend/Validate/Ip.php +++ b/library/Zend/Validate/Ip.php @@ -62,13 +62,12 @@ public function __construct($options = array()) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (!is_array($options)) { + } elseif (!is_array($options)) { $options = func_get_args(); $temp['allowipv6'] = array_shift($options); if (!empty($options)) { $temp['allowipv4'] = array_shift($options); } - $options = $temp; } diff --git a/library/Zend/Validate/Ldap/Dn.php b/library/Zend/Validate/Ldap/Dn.php index 3033cec1ef..4341d775dc 100644 --- a/library/Zend/Validate/Ldap/Dn.php +++ b/library/Zend/Validate/Ldap/Dn.php @@ -56,7 +56,7 @@ class Zend_Validate_Ldap_Dn extends Zend_Validate_Abstract public function isValid($value) { $valid = Zend_Ldap_Dn::checkDn($value); - if ($valid === false) { + if (!$valid) { $this->_error(self::MALFORMED); return false; } diff --git a/library/Zend/Validate/NotEmpty.php b/library/Zend/Validate/NotEmpty.php index 1bb3ceb82e..8bc64e4887 100644 --- a/library/Zend/Validate/NotEmpty.php +++ b/library/Zend/Validate/NotEmpty.php @@ -89,13 +89,12 @@ public function __construct($options = null) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (!is_array($options)) { + } elseif (!is_array($options)) { $options = func_get_args(); $temp = array(); if (!empty($options)) { $temp['type'] = array_shift($options); } - $options = $temp; } @@ -128,13 +127,12 @@ public function setType($type = null) foreach($type as $value) { if (is_int($value)) { $detected += $value; - } else if (in_array($value, $this->_constants)) { + } elseif (in_array($value, $this->_constants)) { $detected += array_search($value, $this->_constants); } } - $type = $detected; - } else if (is_string($type) && in_array($type, $this->_constants)) { + } elseif (is_string($type) && in_array($type, $this->_constants)) { $type = array_search($type, $this->_constants); } @@ -194,12 +192,9 @@ public function isValid($value) if ($type >= self::OBJECT) { $type -= self::OBJECT; // fall trough, objects are always not empty - } else if ($object === false) { - // object not allowed but object given -> return false - if (is_object($value)) { - $this->_error(self::IS_EMPTY); - return false; - } + } elseif (!$object && is_object($value)) { + $this->_error(self::IS_EMPTY); + return false; } // SPACE (' ') diff --git a/library/Zend/Validate/Sitemap/Loc.php b/library/Zend/Validate/Sitemap/Loc.php index 24c78ed8a9..a148945a92 100644 --- a/library/Zend/Validate/Sitemap/Loc.php +++ b/library/Zend/Validate/Sitemap/Loc.php @@ -77,7 +77,7 @@ public function isValid($value) $this->_setValue($value); $result = Zend_Uri::check($value); - if ($result !== true) { + if (!$result) { $this->_error(self::NOT_VALID); return false; } diff --git a/library/Zend/Validate/StringLength.php b/library/Zend/Validate/StringLength.php index 23dcac8413..5df80a2c09 100644 --- a/library/Zend/Validate/StringLength.php +++ b/library/Zend/Validate/StringLength.php @@ -85,17 +85,15 @@ public function __construct($options = array()) { if ($options instanceof Zend_Config) { $options = $options->toArray(); - } else if (!is_array($options)) { + } elseif (!is_array($options)) { $options = func_get_args(); $temp['min'] = array_shift($options); if (!empty($options)) { $temp['max'] = array_shift($options); } - if (!empty($options)) { $temp['encoding'] = array_shift($options); } - $options = $temp; } @@ -165,7 +163,7 @@ public function setMax($max) { if (null === $max) { $this->_max = null; - } else if ($max < $this->_min) { + } elseif ($max < $this->_min) { /** * @see Zend_Validate_Exception */ @@ -203,11 +201,7 @@ public function setEncoding($encoding = null) ? iconv_get_encoding('internal_encoding') : ini_get('default_charset'); if (PHP_VERSION_ID < 50600) { - if ($encoding) { - $result = iconv_set_encoding('internal_encoding', $encoding); - } else { - $result = false; - } + $result = $encoding !== '' && $encoding !== '0' ? iconv_set_encoding('internal_encoding', $encoding) : false; } else { ini_set('default_charset', $encoding); $result = ini_get('default_charset'); @@ -244,11 +238,7 @@ public function isValid($value) } $this->_setValue($value); - if ($this->_encoding !== null) { - $length = iconv_strlen($value, $this->_encoding); - } else { - $length = iconv_strlen($value); - } + $length = $this->_encoding !== null ? iconv_strlen($value, $this->_encoding) : iconv_strlen($value); if ($length < $this->_min) { $this->_error(self::TOO_SHORT); @@ -258,7 +248,7 @@ public function isValid($value) $this->_error(self::TOO_LONG); } - if (count($this->_messages)) { + if ($this->_messages !== []) { return false; } else { return true; diff --git a/library/Zend/View.php b/library/Zend/View.php index 6b8f3e5650..a76bdd73d1 100644 --- a/library/Zend/View.php +++ b/library/Zend/View.php @@ -107,12 +107,10 @@ class Zend_View extends Zend_View_Abstract */ public function __construct($config = array()) { - $this->_useViewStream = (bool) ini_get('short_open_tag') ? false : true; - if ($this->_useViewStream) { - if (!in_array('zend.view', stream_get_wrappers())) { - require_once 'Zend/View/Stream.php'; - stream_wrapper_register('zend.view', 'Zend_View_Stream'); - } + $this->_useViewStream = !(bool) ini_get('short_open_tag'); + if ($this->_useViewStream && !in_array('zend.view', stream_get_wrappers())) { + require_once 'Zend/View/Stream.php'; + stream_wrapper_register('zend.view', 'Zend_View_Stream'); } if (array_key_exists('useStreamWrapper', $config)) { diff --git a/library/Zend/View/Abstract.php b/library/Zend/View/Abstract.php index af2171ab93..780ce7a035 100644 --- a/library/Zend/View/Abstract.php +++ b/library/Zend/View/Abstract.php @@ -441,8 +441,7 @@ public function setScriptPath($path) public function getScriptPath($name) { try { - $path = $this->_script($name); - return $path; + return $this->_script($name); } catch (Zend_View_Exception $e) { if (strstr($e->getMessage(), 'no view script directory set')) { throw $e; @@ -573,7 +572,7 @@ public function getHelperPaths() /** * Registers a helper object, bypassing plugin loader * - * @param Zend_View_Helper_Abstract|object $helper + * @param Zend_View_Helper_Abstract $helper * @param string $name * @return Zend_View_Abstract * @throws Zend_View_Exception @@ -587,15 +586,13 @@ public function registerHelper($helper, $name) throw $e; } - if (!$helper instanceof Zend_View_Interface) { - if (!method_exists($helper, $name)) { - require_once 'Zend/View/Exception.php'; - $e = new Zend_View_Exception( - 'View helper must implement Zend_View_Interface or have a method matching the name provided' - ); - $e->setView($this); - throw $e; - } + if (!$helper instanceof Zend_View_Interface && !method_exists($helper, $name)) { + require_once 'Zend/View/Exception.php'; + $e = new Zend_View_Exception( + 'View helper must implement Zend_View_Interface or have a method matching the name provided' + ); + $e->setView($this); + throw $e; } if (method_exists($helper, 'setView')) { @@ -845,7 +842,7 @@ public function assign($spec, $value = null) public function getVars() { $vars = get_object_vars($this); - foreach ($vars as $key => $value) { + foreach (array_keys($vars) as $key) { if ('_' == substr($key, 0, 1)) { unset($vars[$key]); } @@ -865,7 +862,7 @@ public function getVars() public function clearVars() { $vars = get_object_vars($this); - foreach ($vars as $key => $value) { + foreach (array_keys($vars) as $key) { if ('_' != substr($key, 0, 1)) { unset($this->$key); } @@ -902,7 +899,7 @@ public function render($name) public function escape($var) { if (in_array($this->_escape, array('htmlspecialchars', 'htmlentities'))) { - return call_user_func($this->_escape, $var, ENT_COMPAT, $this->_encoding); + return call_user_func($this->_escape, (string) $var, ENT_COMPAT, $this->_encoding); } if (1 == func_num_args()) { @@ -948,7 +945,7 @@ public function getEncoding() */ public function strictVars($flag = true) { - $this->_strictVars = ($flag) ? true : false; + $this->_strictVars = $flag; return $this; } diff --git a/library/Zend/View/Helper/Cycle.php b/library/Zend/View/Helper/Cycle.php index eb5fd5132b..4fbccb0084 100644 --- a/library/Zend/View/Helper/Cycle.php +++ b/library/Zend/View/Helper/Cycle.php @@ -157,10 +157,7 @@ public function __toString() public function next() { $count = count($this->_data[$this->_name]); - if ($this->_pointers[$this->_name] == ($count - 1)) - $this->_pointers[$this->_name] = 0; - else - $this->_pointers[$this->_name] = ++$this->_pointers[$this->_name]; + $this->_pointers[$this->_name] = $this->_pointers[$this->_name] == ($count - 1) ? 0 : ++$this->_pointers[$this->_name]; return $this; } @@ -172,10 +169,7 @@ public function next() public function prev() { $count = count($this->_data[$this->_name]); - if ($this->_pointers[$this->_name] <= 0) - $this->_pointers[$this->_name] = $count - 1; - else - $this->_pointers[$this->_name] = --$this->_pointers[$this->_name]; + $this->_pointers[$this->_name] = $this->_pointers[$this->_name] <= 0 ? $count - 1 : --$this->_pointers[$this->_name]; return $this; } diff --git a/library/Zend/View/Helper/DeclareVars.php b/library/Zend/View/Helper/DeclareVars.php index 4663d4a41c..17b05cb9fa 100644 --- a/library/Zend/View/Helper/DeclareVars.php +++ b/library/Zend/View/Helper/DeclareVars.php @@ -63,15 +63,14 @@ class Zend_View_Helper_DeclareVars extends Zend_View_Helper_Abstract * @param string|array variable number of arguments, all string names of variables to test * @return void */ - public function declareVars() + public function declareVars(...$args) { - $args = func_get_args(); foreach($args as $key) { if (is_array($key)) { foreach ($key as $name => $value) { $this->_declareVar($name, $value); } - } else if (!isset($view->$key)) { + } elseif (!isset($view->$key)) { $this->_declareVar($key); } } diff --git a/library/Zend/View/Helper/Doctype.php b/library/Zend/View/Helper/Doctype.php index ca63b4dea7..6462714de4 100644 --- a/library/Zend/View/Helper/Doctype.php +++ b/library/Zend/View/Helper/Doctype.php @@ -137,11 +137,7 @@ public function doctype($doctype = null) $e->setView($this->view); throw $e; } - if (stristr($doctype, 'xhtml')) { - $type = self::CUSTOM_XHTML; - } else { - $type = self::CUSTOM; - } + $type = stristr($doctype, 'xhtml') ? self::CUSTOM_XHTML : self::CUSTOM; $this->setDoctype($type); $this->_registry['doctypes'][$type] = $doctype; break; @@ -190,7 +186,7 @@ public function getDoctypes() */ public function isXhtml() { - return (stristr($this->getDoctype(), 'xhtml') ? true : false); + return ((bool) stristr($this->getDoctype(), 'xhtml')); } /** @@ -217,7 +213,7 @@ public function isStrict() * @return booleean */ public function isHtml5() { - return (stristr($this->doctype(), '') ? true : false); + return ((bool) stristr($this->doctype(), '')); } /** @@ -226,7 +222,7 @@ public function isHtml5() { * @return booleean */ public function isRdfa() { - return (stristr($this->getDoctype(), 'rdfa') ? true : false); + return ((bool) stristr($this->getDoctype(), 'rdfa')); } /** diff --git a/library/Zend/View/Helper/Fieldset.php b/library/Zend/View/Helper/Fieldset.php index fce37b9341..8e0642f8eb 100644 --- a/library/Zend/View/Helper/Fieldset.php +++ b/library/Zend/View/Helper/Fieldset.php @@ -59,11 +59,7 @@ public function fieldset($name, $content, $attribs = null) } // get id - if (!empty($id)) { - $id = ' id="' . $this->view->escape($id) . '"'; - } else { - $id = ''; - } + $id = empty($id) ? '' : ' id="' . $this->view->escape($id) . '"'; // render fieldset $xhtml = '_getInfo($name, $content, $attribs); extract($info); - if (!empty($id)) { - $id = ' id="' . $this->view->escape($id) . '"'; - } else { - $id = ''; - } + $id = empty($id) ? '' : ' id="' . $this->view->escape($id) . '"'; if (array_key_exists('id', $attribs) && empty($attribs['id'])) { unset($attribs['id']); diff --git a/library/Zend/View/Helper/FormCheckbox.php b/library/Zend/View/Helper/FormCheckbox.php index fd6f4ae5b5..74f1598979 100644 --- a/library/Zend/View/Helper/FormCheckbox.php +++ b/library/Zend/View/Helper/FormCheckbox.php @@ -93,16 +93,14 @@ public function formCheckbox($name, $value = null, $attribs = null, array $check unset($attribs['disableHidden']); } - $xhtml .= '_htmlAttribs($attribs) - . $this->getClosingBracket(); - - return $xhtml; + . $this->getClosingBracket()); } /** diff --git a/library/Zend/View/Helper/FormElement.php b/library/Zend/View/Helper/FormElement.php index 8c1373b38c..31d61e5594 100644 --- a/library/Zend/View/Helper/FormElement.php +++ b/library/Zend/View/Helper/FormElement.php @@ -109,7 +109,7 @@ protected function _getInfo($name, $value = null, $attribs = null, // override with named args if (is_array($name)) { // only set keys that are already in info - foreach ($info as $key => $val) { + foreach (array_keys($info) as $key) { if (isset($name[$key])) { $info[$key] = $name[$key]; } @@ -132,17 +132,17 @@ protected function _getInfo($name, $value = null, $attribs = null, // Disable attribute if (array_key_exists('disable', $attribs)) { if (is_scalar($attribs['disable'])) { - // disable the element - $info['disable'] = (bool)$attribs['disable']; - } else if (is_array($attribs['disable'])) { - $info['disable'] = $attribs['disable']; - } + // disable the element + $info['disable'] = (bool)$attribs['disable']; + } elseif (is_array($attribs['disable'])) { + $info['disable'] = $attribs['disable']; + } } // Set ID for element if (array_key_exists('id', $attribs)) { $info['id'] = (string)$attribs['id']; - } else if ('' !== $info['name']) { + } elseif ('' !== $info['name']) { $info['id'] = trim(strtr($info['name'], array('[' => '-', ']' => '')), '-'); } @@ -169,7 +169,7 @@ protected function _getInfo($name, $value = null, $attribs = null, // Remove attribs that might overwrite the other keys. We do this LAST // because we needed the other attribs values earlier. - foreach ($info as $key => $val) { + foreach (array_keys($info) as $key) { if (array_key_exists($key, $attribs)) { unset($attribs[$key]); } diff --git a/library/Zend/View/Helper/FormErrors.php b/library/Zend/View/Helper/FormErrors.php index 4e092b1157..e4c8f7e7f0 100644 --- a/library/Zend/View/Helper/FormErrors.php +++ b/library/Zend/View/Helper/FormErrors.php @@ -91,11 +91,9 @@ public function formErrors($errors, array $options = null) } } - $html = $start + return $start . implode($this->getElementSeparator(), (array) $errors) . $this->getElementEnd(); - - return $html; } /** diff --git a/library/Zend/View/Helper/FormImage.php b/library/Zend/View/Helper/FormImage.php index be3daa3d07..aee397b9c4 100644 --- a/library/Zend/View/Helper/FormImage.php +++ b/library/Zend/View/Helper/FormImage.php @@ -68,11 +68,7 @@ public function formImage($name, $value = null, $attribs = null) } // Do we have a value? - if (isset($value) && !empty($value)) { - $value = ' value="' . $this->view->escape($value) . '"'; - } else { - $value = ''; - } + $value = isset($value) && !empty($value) ? ' value="' . $this->view->escape($value) . '"' : ''; // Disabled? $disabled = ''; diff --git a/library/Zend/View/Helper/FormRadio.php b/library/Zend/View/Helper/FormRadio.php index 193c264cb4..767e5927a7 100644 --- a/library/Zend/View/Helper/FormRadio.php +++ b/library/Zend/View/Helper/FormRadio.php @@ -96,14 +96,12 @@ public function formRadio($name, $value = null, $attribs = null, $labelPlacement = 'append'; foreach ($label_attribs as $key => $val) { - switch (strtolower($key)) { - case 'placement': - unset($label_attribs[$key]); - $val = strtolower($val); - if (in_array($val, array('prepend', 'append'))) { - $labelPlacement = $val; - } - break; + if (strtolower($key) === 'placement') { + unset($label_attribs[$key]); + $val = strtolower($val); + if (in_array($val, array('prepend', 'append'))) { + $labelPlacement = $val; + } } } diff --git a/library/Zend/View/Helper/FormSelect.php b/library/Zend/View/Helper/FormSelect.php index 8654f3d0e7..51a8d1158c 100644 --- a/library/Zend/View/Helper/FormSelect.php +++ b/library/Zend/View/Helper/FormSelect.php @@ -192,9 +192,7 @@ protected function _build($value, $label, $selected, $disable, $optionClasses = $opt .= ' disabled="disabled"'; } - $opt .= '>' . $this->view->escape($label) . ""; - - return $opt; + return $opt . ('>' . $this->view->escape($label) . ""); } } diff --git a/library/Zend/View/Helper/FormText.php b/library/Zend/View/Helper/FormText.php index 9b9f58135e..dd119e508d 100644 --- a/library/Zend/View/Helper/FormText.php +++ b/library/Zend/View/Helper/FormText.php @@ -65,14 +65,12 @@ public function formText($name, $value = null, $attribs = null) $disabled = ' disabled="disabled"'; } - $xhtml = '_htmlAttribs($attribs) . $this->getClosingBracket(); - - return $xhtml; } } diff --git a/library/Zend/View/Helper/Gravatar.php b/library/Zend/View/Helper/Gravatar.php index dab1f799f6..b54cf94c01 100644 --- a/library/Zend/View/Helper/Gravatar.php +++ b/library/Zend/View/Helper/Gravatar.php @@ -298,7 +298,7 @@ public function setAttribs(array $attribs) */ protected function _getGravatarUrl() { - return ($this->getSecure() === false) ? self::GRAVATAR_URL : self::GRAVATAR_URL_SECURE; + return ($this->getSecure()) ? self::GRAVATAR_URL_SECURE : self::GRAVATAR_URL; } /** @@ -308,7 +308,7 @@ protected function _getGravatarUrl() */ protected function _getAvatarUrl() { - $src = $this->_getGravatarUrl() + return $this->_getGravatarUrl() . '/' . md5(strtolower(trim($this->getEmail()))) . '?s=' @@ -317,7 +317,6 @@ protected function _getAvatarUrl() . $this->getDefaultImg() . '&r=' . $this->getRating(); - return $src; } /** @@ -343,11 +342,10 @@ protected function _setSrcAttribForImg() public function getImgTag() { $this->_setSrcAttribForImg(); - $html = '_htmlAttribs($this->getAttribs()) . $this->getClosingBracket(); - - return $html; } /** diff --git a/library/Zend/View/Helper/HeadLink.php b/library/Zend/View/Helper/HeadLink.php index c8a44bce3b..6b311f8aa2 100644 --- a/library/Zend/View/Helper/HeadLink.php +++ b/library/Zend/View/Helper/HeadLink.php @@ -151,11 +151,9 @@ public function __call($method, $args) $type = $matches['type']; $index = null; - if ('offsetSet' == $action) { - if (0 < $argc) { - $index = array_shift($args); - --$argc; - } + if ('offsetSet' == $action && 0 < $argc) { + $index = array_shift($args); + --$argc; } if (1 > $argc) { @@ -201,11 +199,7 @@ protected function _isValid($value) $vars = get_object_vars($value); $keys = array_keys($vars); $intersection = array_intersect($this->_itemKeys, $keys); - if (empty($intersection)) { - return false; - } - - return true; + return !empty($intersection); } /** @@ -357,8 +351,7 @@ public function toString($indent = null) */ public function createData(array $attributes) { - $data = (object) $attributes; - return $data; + return (object) $attributes; } /** @@ -379,15 +372,11 @@ public function createDataStylesheet(array $args) return false; } - if (0 < count($args)) { + if ([] !== $args) { $media = array_shift($args); - if(is_array($media)) { - $media = implode(',', $media); - } else { - $media = (string) $media; - } + $media = is_array($media) ? implode(',', $media) : (string) $media; } - if (0 < count($args)) { + if ([] !== $args) { $conditionalStylesheet = array_shift($args); if(!empty($conditionalStylesheet) && is_string($conditionalStylesheet)) { $conditionalStylesheet = (string) $conditionalStylesheet; @@ -396,12 +385,12 @@ public function createDataStylesheet(array $args) } } - if(0 < count($args) && is_array($args[0])) { + if([] !== $args && is_array($args[0])) { $extras = array_shift($args); $extras = (array) $extras; } - $attributes = compact('rel', 'type', 'href', 'media', 'conditionalStylesheet', 'extras'); + $attributes = ['rel' => $rel, 'type' => $type, 'href' => $href, 'media' => $media, 'conditionalStylesheet' => $conditionalStylesheet, 'extras' => $extras]; return $this->createData($this->_applyExtras($attributes)); } @@ -441,7 +430,7 @@ public function createDataAlternate(array $args) $type = array_shift($args); $title = array_shift($args); - if(0 < count($args) && is_array($args[0])) { + if([] !== $args && is_array($args[0])) { $extras = array_shift($args); $extras = (array) $extras; @@ -454,7 +443,7 @@ public function createDataAlternate(array $args) $type = (string) $type; $title = (string) $title; - $attributes = compact('rel', 'href', 'type', 'title', 'extras'); + $attributes = ['rel' => $rel, 'href' => $href, 'type' => $type, 'title' => $title, 'extras' => $extras]; return $this->createData($this->_applyExtras($attributes)); } @@ -466,12 +455,7 @@ public function createDataAlternate(array $args) protected function _applyExtras($attributes) { if (isset($attributes['extras'])) { - foreach ($attributes['extras'] as $eKey=>$eVal) { - if (isset($attributes[$eKey])) { - $attributes[$eKey] = $eVal; - unset($attributes['extras'][$eKey]); - } - } + $attributes = array_filter($attributes['extras'], fn($eVal) => isset($attributes[$eKey])); } return $attributes; } diff --git a/library/Zend/View/Helper/HeadMeta.php b/library/Zend/View/Helper/HeadMeta.php index 90a70fbe81..c3d2f614e0 100644 --- a/library/Zend/View/Helper/HeadMeta.php +++ b/library/Zend/View/Helper/HeadMeta.php @@ -149,11 +149,9 @@ public function __call($method, $args) $argc = count($args); $index = null; - if ('offsetSet' == $action) { - if (0 < $argc) { - $index = array_shift($args); - --$argc; - } + if ('offsetSet' == $action && 0 < $argc) { + $index = array_shift($args); + --$argc; } if (2 > $argc) { @@ -208,26 +206,21 @@ public function setCharset($charset) protected function _isValid($item) { if ((!$item instanceof stdClass) - || !isset($item->type) - || !isset($item->modifiers)) + || !(property_exists($item, 'type') && $item->type !== null) + || !(property_exists($item, 'modifiers') && $item->modifiers !== null)) { return false; } $isHtml5 = is_null($this->view) ? false : $this->view->doctype()->isHtml5(); - if (!isset($item->content) + if (!(property_exists($item, 'content') && $item->content !== null) && (! $isHtml5 || (! $isHtml5 && $item->type !== 'charset'))) { return false; } - // is only supported with doctype RDFa - if ( !is_null($this->view) && !$this->view->doctype()->isRdfa() - && $item->type === 'property') { - return false; - } - - return true; + return !(!is_null($this->view) && !$this->view->doctype()->isRdfa() + && $item->type === 'property'); } /** @@ -356,8 +349,7 @@ public function itemToString(stdClass $item) if (!is_null($this->view) && $this->view->doctype()->isHtml5() && $key == 'scheme') { require_once 'Zend/View/Exception.php'; - throw new Zend_View_Exception('Invalid modifier ' - . '"scheme" provided; not supported by HTML5'); + throw new Zend_View_Exception('Invalid modifier "scheme" provided; not supported by HTML5'); } if (!in_array($key, $this->_modifierKeys)) { continue; diff --git a/library/Zend/View/Helper/HeadScript.php b/library/Zend/View/Helper/HeadScript.php index 062bed1b0c..006e1364fb 100644 --- a/library/Zend/View/Helper/HeadScript.php +++ b/library/Zend/View/Helper/HeadScript.php @@ -299,14 +299,9 @@ protected function _isDuplicate($file) */ protected function _isValid($value) { - if ((!$value instanceof stdClass) - || !isset($value->type) - || (!isset($value->source) && !isset($value->attributes))) - { - return false; - } - - return true; + return !((!$value instanceof stdClass) + || !(property_exists($value, 'type') && $value->type !== null) + || (!(property_exists($value, 'source') && $value->source !== null) && !(property_exists($value, 'attributes') && $value->attributes !== null))); } /** @@ -479,11 +474,7 @@ public function toString($indent = null) ? $this->getWhitespace($indent) : $this->getIndent(); - if ($this->view) { - $useCdata = $this->view->doctype()->isXhtml() ? true : false; - } else { - $useCdata = $this->useCdata ? true : false; - } + $useCdata = $this->view ? (bool) $this->view->doctype()->isXhtml() : $this->useCdata; $escapeStart = ($useCdata) ? '//' : '//-->'; @@ -496,9 +487,7 @@ public function toString($indent = null) $items[] = $this->itemToString($item, $indent, $escapeStart, $escapeEnd); } - - $return = implode($this->getSeparator(), $items); - return $return; + return implode($this->getSeparator(), $items); } /** diff --git a/library/Zend/View/Helper/HeadStyle.php b/library/Zend/View/Helper/HeadStyle.php index e81e9ed211..d1d0b1d005 100644 --- a/library/Zend/View/Helper/HeadStyle.php +++ b/library/Zend/View/Helper/HeadStyle.php @@ -142,11 +142,9 @@ public function __call($method, $args) $argc = count($args); $action = $matches['action']; - if ('offsetSet' == $action) { - if (0 < $argc) { - $index = array_shift($args); - --$argc; - } + if ('offsetSet' == $action && 0 < $argc) { + $index = array_shift($args); + --$argc; } if (1 > $argc) { @@ -185,14 +183,9 @@ public function __call($method, $args) */ protected function _isValid($value) { - if ((!$value instanceof stdClass) - || !isset($value->content) - || !isset($value->attributes)) - { - return false; - } - - return true; + return !((!$value instanceof stdClass) + || !(property_exists($value, 'content') && $value->content !== null) + || !(property_exists($value, 'attributes') && $value->attributes !== null)); } /** @@ -405,8 +398,7 @@ public function toString($indent = null) } $return = $indent . implode($this->getSeparator() . $indent, $items); - $return = preg_replace("/(\r\n?|\n)/", '$1' . $indent, $return); - return $return; + return preg_replace("/(\r\n?|\n)/", '$1' . $indent, $return); } /** @@ -420,7 +412,7 @@ public function createData($content, array $attributes) { if (!isset($attributes['media'])) { $attributes['media'] = 'screen'; - } else if(is_array($attributes['media'])) { + } elseif (is_array($attributes['media'])) { $attributes['media'] = implode(',', $attributes['media']); } diff --git a/library/Zend/View/Helper/HtmlElement.php b/library/Zend/View/Helper/HtmlElement.php index 263fcd32d2..818cd7486d 100644 --- a/library/Zend/View/Helper/HtmlElement.php +++ b/library/Zend/View/Helper/HtmlElement.php @@ -53,12 +53,8 @@ abstract class Zend_View_Helper_HtmlElement extends Zend_View_Helper_Abstract */ public function getClosingBracket() { - if (!$this->_closingBracket) { - if ($this->_isXhtml()) { - $this->_closingBracket = ' />'; - } else { - $this->_closingBracket = '>'; - } + if ($this->_closingBracket === '' || $this->_closingBracket === '0') { + $this->_closingBracket = $this->_isXhtml() ? ' />' : '>'; } return $this->_closingBracket; diff --git a/library/Zend/View/Helper/HtmlList.php b/library/Zend/View/Helper/HtmlList.php index 471ade4808..68a6e33bdc 100644 --- a/library/Zend/View/Helper/HtmlList.php +++ b/library/Zend/View/Helper/HtmlList.php @@ -64,21 +64,15 @@ public function htmlList(array $items, $ordered = false, $attribs = false, $esca $item = $this->view->escape($item); } $list .= '
  • ' . $item . '
  • ' . self::EOL; + } elseif (6 < strlen($list)) { + $list = substr($list, 0, strlen($list) - 6) + . $this->htmlList($item, $ordered, $attribs, $escape) . '' . self::EOL; } else { - if (6 < strlen($list)) { - $list = substr($list, 0, strlen($list) - 6) - . $this->htmlList($item, $ordered, $attribs, $escape) . '' . self::EOL; - } else { - $list .= '
  • ' . $this->htmlList($item, $ordered, $attribs, $escape) . '
  • ' . self::EOL; - } + $list .= '
  • ' . $this->htmlList($item, $ordered, $attribs, $escape) . '
  • ' . self::EOL; } } - if ($attribs) { - $attribs = $this->_htmlAttribs($attribs); - } else { - $attribs = ''; - } + $attribs = $attribs !== [] ? $this->_htmlAttribs($attribs) : ''; $tag = 'ul'; if ($ordered) { diff --git a/library/Zend/View/Helper/Layout.php b/library/Zend/View/Helper/Layout.php index 286a9e38e7..8f97597eb0 100644 --- a/library/Zend/View/Helper/Layout.php +++ b/library/Zend/View/Helper/Layout.php @@ -43,7 +43,7 @@ class Zend_View_Helper_Layout extends Zend_View_Helper_Abstract */ public function getLayout() { - if (null === $this->_layout) { + if (!$this->_layout instanceof \Zend_Layout) { require_once 'Zend/Layout.php'; $this->_layout = Zend_Layout::getMvcInstance(); if (null === $this->_layout) { diff --git a/library/Zend/View/Helper/Navigation.php b/library/Zend/View/Helper/Navigation.php index 2e82ef6a29..4a3db4b60f 100644 --- a/library/Zend/View/Helper/Navigation.php +++ b/library/Zend/View/Helper/Navigation.php @@ -188,8 +188,7 @@ public function findHelper($proxy, $strict = true) if ($strict) { require_once 'Zend/View/Exception.php'; $e = new Zend_View_Exception(sprintf( - 'Proxy helper "%s" is not an instance of ' . - 'Zend_View_Helper_Navigation_Helper', + 'Proxy helper "%s" is not an instance of Zend_View_Helper_Navigation_Helper', get_class($helper))); $e->setView($this->view); throw $e; diff --git a/library/Zend/View/Helper/Navigation/Breadcrumbs.php b/library/Zend/View/Helper/Navigation/Breadcrumbs.php index cad01751f8..cef34e7d78 100644 --- a/library/Zend/View/Helper/Navigation/Breadcrumbs.php +++ b/library/Zend/View/Helper/Navigation/Breadcrumbs.php @@ -221,7 +221,7 @@ public function renderStraight(Zend_Navigation_Container $container = null) $active = $parent; } - return strlen((string) $html) ? $this->getIndent() . $html : ''; + return strlen((string) $html) !== 0 ? $this->getIndent() . $html : ''; } /** diff --git a/library/Zend/View/Helper/Navigation/HelperAbstract.php b/library/Zend/View/Helper/Navigation/HelperAbstract.php index 2e733e4423..426a9ee492 100644 --- a/library/Zend/View/Helper/Navigation/HelperAbstract.php +++ b/library/Zend/View/Helper/Navigation/HelperAbstract.php @@ -218,11 +218,7 @@ public function getContainer() */ public function setMinDepth($minDepth = null) { - if (null === $minDepth || is_int($minDepth)) { - $this->_minDepth = $minDepth; - } else { - $this->_minDepth = (int) $minDepth; - } + $this->_minDepth = null === $minDepth || is_int($minDepth) ? $minDepth : (int) $minDepth; return $this; } @@ -251,11 +247,7 @@ public function getMinDepth() */ public function setMaxDepth($maxDepth = null) { - if (null === $maxDepth || is_int($maxDepth)) { - $this->_maxDepth = $maxDepth; - } else { - $this->_maxDepth = (int) $maxDepth; - } + $this->_maxDepth = null === $maxDepth || is_int($maxDepth) ? $maxDepth : (int) $maxDepth; return $this; } @@ -291,7 +283,7 @@ public function setIndent($indent) */ public function getIndent() { - if (false === $this->getFormatOutput()) { + if (!$this->getFormatOutput()) { return ''; } @@ -308,7 +300,7 @@ public function getIndent() */ public function getEOL() { - if (false === $this->getFormatOutput()) { + if (!$this->getFormatOutput()) { return ''; } @@ -459,7 +451,7 @@ public function setAcl(Zend_Acl $acl = null) */ public function getAcl() { - if ($this->_acl === null && self::$_defaultAcl !== null) { + if (!$this->_acl instanceof \Zend_Acl && self::$_defaultAcl !== null) { return self::$_defaultAcl; } @@ -490,8 +482,7 @@ public function setRole($role = null) } else { require_once 'Zend/View/Exception.php'; $e = new Zend_View_Exception(sprintf( - '$role must be a string, null, or an instance of ' - . 'Zend_Acl_Role_Interface; %s given', + '$role must be a string, null, or an instance of Zend_Acl_Role_Interface; %s given', gettype($role) )); $e->setView($this->view); @@ -858,7 +849,7 @@ public function accept(Zend_Navigation_Page $page, $recursive = true) */ protected function _acceptAcl(Zend_Navigation_Page $page) { - if (!$acl = $this->getAcl()) { + if (($acl = $this->getAcl()) === null) { // no acl registered means don't use acl return true; } @@ -923,10 +914,10 @@ protected function _htmlAttribs($attribs) */ protected function _normalizeId($value) { - if (false === $this->_skipPrefixForId) { + if (!$this->_skipPrefixForId) { $prefix = $this->getPrefixForId(); - if (strlen($prefix)) { + if (strlen($prefix) !== 0) { return $prefix . $value; } } diff --git a/library/Zend/View/Helper/Navigation/Links.php b/library/Zend/View/Helper/Navigation/Links.php index 5d05c1008b..54da9f76c8 100644 --- a/library/Zend/View/Helper/Navigation/Links.php +++ b/library/Zend/View/Helper/Navigation/Links.php @@ -297,20 +297,16 @@ public function findRelation(Zend_Navigation_Page $page, $rel, $type) protected function _findFromProperty(Zend_Navigation_Page $page, $rel, $type) { $method = 'get' . ucfirst($rel); - if ($result = $page->$method($type)) { - if ($result = $this->_convertToPages($result)) { - if (!is_array($result)) { - $result = array($result); - } - - foreach ($result as $key => $page) { - if (!$this->accept($page)) { - unset($result[$key]); - } + if (($result = $page->$method($type)) && ($result = $this->_convertToPages($result))) { + if (!is_array($result)) { + $result = array($result); + } + foreach ($result as $key => $page) { + if (!$this->accept($page)) { + unset($result[$key]); } - - return count($result) == 1 ? $result[0] : $result; } + return count($result) == 1 ? $result[0] : $result; } return null; @@ -561,11 +557,9 @@ public function searchRevSection(Zend_Navigation_Page $page) { $found = null; - if ($parent = $page->getParent()) { - if ($parent instanceof Zend_Navigation_Page && - $this->_findRoot($page)->hasPage($parent)) { - $found = $parent; - } + if (($parent = $page->getParent()) !== null && ($parent instanceof Zend_Navigation_Page && + $this->_findRoot($page)->hasPage($parent))) { + $found = $parent; } return $found; @@ -586,14 +580,12 @@ public function searchRevSubsection(Zend_Navigation_Page $page) { $found = null; - if ($parent = $page->getParent()) { - if ($parent instanceof Zend_Navigation_Page) { - $root = $this->_findRoot($page); - foreach ($root as $chapter) { - if ($chapter->hasPage($parent)) { - $found = $parent; - break; - } + if (($parent = $page->getParent()) !== null && $parent instanceof Zend_Navigation_Page) { + $root = $this->_findRoot($page); + foreach ($root as $chapter) { + if ($chapter->hasPage($parent)) { + $found = $parent; + break; } } } @@ -678,8 +670,7 @@ protected function _convertToPages($mixed, $recursive = true) } else { // pass array to factory directly try { - $page = Zend_Navigation_Page::factory($mixed); - return $page; + return Zend_Navigation_Page::factory($mixed); } catch (Exception $e) { } } @@ -717,7 +708,7 @@ public function renderLink(Zend_Navigation_Page $page, $attrib, $relation) throw $e; } - if (!$href = $page->getHref()) { + if (($href = $page->getHref()) === '' || ($href = $page->getHref()) === '0') { return ''; } @@ -768,7 +759,7 @@ public function render(Zend_Navigation_Container $container = null) foreach ($result as $attrib => $types) { foreach ($types as $relation => $pages) { foreach ($pages as $page) { - if ($r = $this->renderLink($page, $attrib, $relation)) { + if (($r = $this->renderLink($page, $attrib, $relation)) !== '' && ($r = $this->renderLink($page, $attrib, $relation)) !== '0') { $output .= $indent . $r . $this->getEOL(); } } @@ -778,6 +769,6 @@ public function render(Zend_Navigation_Container $container = null) $this->_root = null; // return output (trim last newline by spec) - return strlen($output) ? rtrim($output, self::EOL) : ''; + return strlen($output) !== 0 ? rtrim($output, self::EOL) : ''; } } diff --git a/library/Zend/View/Helper/Navigation/Menu.php b/library/Zend/View/Helper/Navigation/Menu.php index da3faee84a..632a83719f 100644 --- a/library/Zend/View/Helper/Navigation/Menu.php +++ b/library/Zend/View/Helper/Navigation/Menu.php @@ -436,7 +436,7 @@ public function setInnerIndent($indent) */ public function getInnerIndent() { - if (false === $this->getFormatOutput()) { + if (!$this->getFormatOutput()) { return ''; } @@ -476,12 +476,12 @@ public function htmlify(Zend_Navigation_Page $page) 'title' => $title, ); - if (false === $this->getAddPageClassToLi()) { + if (!$this->getAddPageClassToLi()) { $attribs['class'] = $page->getClass(); } // does page have a href? - if ($href = $page->getHref()) { + if (($href = $page->getHref()) !== '' && ($href = $page->getHref()) !== '0') { $element = 'a'; $attribs['href'] = $href; $attribs['target'] = $page->getTarget(); @@ -507,11 +507,7 @@ public function htmlify(Zend_Navigation_Page $page) protected function _normalizeOptions(array $options = array()) { // Ident - if (isset($options['indent'])) { - $options['indent'] = $this->_getWhitespace($options['indent']); - } else { - $options['indent'] = $this->getIndent(); - } + $options['indent'] = isset($options['indent']) ? $this->_getWhitespace($options['indent']) : $this->getIndent(); // Inner ident if (isset($options['innerIndent'])) { @@ -529,11 +525,7 @@ protected function _normalizeOptions(array $options = array()) } // UL id - if (isset($options['ulId']) && $options['ulId'] !== null) { - $options['ulId'] = (string) $options['ulId']; - } else { - $options['ulId'] = $this->getUlId(); - } + $options['ulId'] = isset($options['ulId']) && $options['ulId'] !== null ? (string) $options['ulId'] : $this->getUlId(); // Active class if (isset($options['activeClass']) && $options['activeClass'] !== null @@ -644,10 +636,10 @@ protected function _renderDeepestMenu(Zend_Navigation_Container $container, if (!$active['page']->hasPages()) { return ''; } - } else if (!$active['page']->hasPages()) { + } elseif (!$active['page']->hasPages()) { // found pages has no children; render siblings $active['page'] = $active['page']->getParent(); - } else if (is_int($maxDepth) && $active['depth'] + 1 > $maxDepth) { + } elseif (is_int($maxDepth) && $active['depth'] + 1 > $maxDepth) { // children are below max depth; render siblings $active['page'] = $active['page']->getParent(); } @@ -679,9 +671,9 @@ protected function _renderDeepestMenu(Zend_Navigation_Container $container, $liClass = $this->_htmlAttribs( array('class' => $activeClass . ' ' . $subPage->getClass()) ); - } else if ($subPage->isActive(true)) { + } elseif ($subPage->isActive(true)) { $liClass = $this->_htmlAttribs(array('class' => $activeClass)); - } else if ($addPageClassToLi) { + } elseif ($addPageClassToLi) { $liClass = $this->_htmlAttribs( array('class' => $subPage->getClass()) ); @@ -692,9 +684,7 @@ protected function _renderDeepestMenu(Zend_Navigation_Container $container, $html .= $indent . $innerIndent . '' . $this->getEOL(); } - $html .= $indent . ''; - - return $html; + return $html . ($indent . ''); } /** @@ -759,14 +749,14 @@ protected function _renderMenu(Zend_Navigation_Container $container, if ($depth < $minDepth || !$this->accept($page)) { // page is below minDepth or not accepted by acl/visibilty continue; - } else if ($expandSibs && $depth > $minDepth) { + } elseif ($expandSibs && $depth > $minDepth) { // page is not active itself, but might be in the active branch $accept = false; if ($foundPage) { if ($foundPage->hasPage($page)) { // accept if page is a direct child of the active page $accept = true; - } else if ($page->getParent()->isActive(true)) { + } elseif ($page->getParent()->isActive(true)) { // page is a sibling of the active branch... $accept = true; } @@ -774,24 +764,20 @@ protected function _renderMenu(Zend_Navigation_Container $container, if (!$isActive && !$accept) { continue; } - } else if ($onlyActive && !$isActive) { + } elseif ($onlyActive && !$isActive) { // page is not active itself, but might be in the active branch $accept = false; if ($foundPage) { if ($foundPage->hasPage($page)) { // accept if page is a direct child of the active page $accept = true; - } else if ($foundPage->getParent()->hasPage($page)) { - // page is a sibling of the active page... - if (!$foundPage->hasPages() || - is_int($maxDepth) && $foundDepth + 1 > $maxDepth) { - // accept if active page has no children, or the - // children are too deep to be rendered - $accept = true; - } + } elseif ($foundPage->getParent()->hasPage($page) && (!$foundPage->hasPages() || + is_int($maxDepth) && $foundDepth + 1 > $maxDepth)) { + // accept if active page has no children, or the + // children are too deep to be rendered + $accept = true; } } - if (!$accept) { continue; } @@ -803,7 +789,6 @@ protected function _renderMenu(Zend_Navigation_Container $container, if ($depth > $prevDepth) { $attribs = array(); - // start new ul tag if (0 == $depth) { $attribs = array( @@ -811,19 +796,16 @@ protected function _renderMenu(Zend_Navigation_Container $container, 'id' => $ulId, ); } - // We don't need a prefix for the menu ID (backup) $skipValue = $this->_skipPrefixForId; $this->skipPrefixForId(); - $html .= $myIndent . '_htmlAttribs($attribs) . '>' . $this->getEOL(); - // Reset prefix for IDs $this->_skipPrefixForId = $skipValue; - } else if ($prevDepth > $depth) { + } elseif ($prevDepth > $depth) { // close li/ul tags until we're at current depth for ($i = $prevDepth; $i > $depth; $i--) { $ind = $indent . str_repeat($innerIndent, $i * 2); @@ -848,13 +830,10 @@ protected function _renderMenu(Zend_Navigation_Container $container, $liClasses[] = $page->getClass(); } // Add CSS class for parents to LI? - if ($renderParentClass && $page->hasChildren()) { - // Check max depth - if ((is_int($maxDepth) && ($depth + 1 < $maxDepth)) - || !is_int($maxDepth) - ) { - $liClasses[] = $parentClass; - } + // Check max depth + if ($renderParentClass && $page->hasChildren() && ((is_int($maxDepth) && ($depth + 1 < $maxDepth)) + || !is_int($maxDepth))) { + $liClasses[] = $parentClass; } $html .= $myIndent . $innerIndent . ' 0; $i--) { $myIndent = $indent . str_repeat($innerIndent . $innerIndent, $i - 1); diff --git a/library/Zend/View/Helper/Navigation/Sitemap.php b/library/Zend/View/Helper/Navigation/Sitemap.php index 4df6dc38d1..f9bae5a2ad 100644 --- a/library/Zend/View/Helper/Navigation/Sitemap.php +++ b/library/Zend/View/Helper/Navigation/Sitemap.php @@ -213,7 +213,7 @@ public function setServerUrl($serverUrl) */ public function getServerUrl() { - if (!isset($this->_serverUrl)) { + if (!($this->_serverUrl !== null)) { $this->_serverUrl = $this->view->serverUrl(); } @@ -337,7 +337,7 @@ public function getDomSitemap(Zend_Navigation_Container $container = null) } // get absolute url from page - if (!$url = $this->url($page)) { + if (($url = $this->url($page)) === '' || ($url = $this->url($page)) === '0') { // skip page if it has no url (rare case) continue; } @@ -361,7 +361,7 @@ public function getDomSitemap(Zend_Navigation_Container $container = null) 'loc', $url)); // add 'lastmod' element if a valid lastmod is set in page - if (isset($page->lastmod)) { + if (property_exists($page, 'lastmod') && $page->lastmod !== null) { $lastmod = strtotime((string) $page->lastmod); // prevent 1970-01-01... @@ -379,7 +379,7 @@ public function getDomSitemap(Zend_Navigation_Container $container = null) } // add 'changefreq' element if a valid changefreq is set in page - if (isset($page->changefreq)) { + if (property_exists($page, 'changefreq') && $page->changefreq !== null) { $changefreq = $page->changefreq; if (!$this->getUseSitemapValidators() || $changefreqValidator->isValid($changefreq)) { @@ -391,7 +391,7 @@ public function getDomSitemap(Zend_Navigation_Container $container = null) } // add 'priority' element if a valid priority is set in page - if (isset($page->priority)) { + if (property_exists($page, 'priority') && $page->priority !== null) { $priority = $page->priority; if (!$this->getUseSitemapValidators() || $priorityValidator->isValid($priority)) { @@ -404,15 +404,13 @@ public function getDomSitemap(Zend_Navigation_Container $container = null) } // validate using schema if specified - if ($this->getUseSchemaValidation()) { - if (!@$dom->schemaValidate(self::SITEMAP_XSD)) { - require_once 'Zend/View/Exception.php'; - $e = new Zend_View_Exception(sprintf( - 'Sitemap is invalid according to XML Schema at "%s"', - self::SITEMAP_XSD)); - $e->setView($this->view); - throw $e; - } + if ($this->getUseSchemaValidation() && !@$dom->schemaValidate(self::SITEMAP_XSD)) { + require_once 'Zend/View/Exception.php'; + $e = new Zend_View_Exception(sprintf( + 'Sitemap is invalid according to XML Schema at "%s"', + self::SITEMAP_XSD)); + $e->setView($this->view); + throw $e; } return $dom; diff --git a/library/Zend/View/Helper/PaginationControl.php b/library/Zend/View/Helper/PaginationControl.php index 6f5929a22d..efa4c5a23e 100644 --- a/library/Zend/View/Helper/PaginationControl.php +++ b/library/Zend/View/Helper/PaginationControl.php @@ -88,7 +88,7 @@ public static function getDefaultViewPartial() public function paginationControl(Zend_Paginator $paginator = null, $scrollingStyle = null, $partial = null, $params = null) { if ($paginator === null) { - if (isset($this->view->paginator) and $this->view->paginator !== null and $this->view->paginator instanceof Zend_Paginator) { + if (isset($this->view->paginator) && $this->view->paginator !== null && $this->view->paginator instanceof Zend_Paginator) { $paginator = $this->view->paginator; } else { /** diff --git a/library/Zend/View/Helper/Partial.php b/library/Zend/View/Helper/Partial.php index 733f563b9b..ac9c187ed4 100644 --- a/library/Zend/View/Helper/Partial.php +++ b/library/Zend/View/Helper/Partial.php @@ -33,6 +33,14 @@ */ class Zend_View_Helper_Partial extends Zend_View_Helper_Abstract { + /** + * @var mixed + */ + public $partialCounter; + /** + * @var mixed + */ + public $partialTotalCount; /** * Variable to which object will be assigned * @var string @@ -68,10 +76,10 @@ public function partial($name = null, $module = null, $model = null) } $view = $this->cloneView(); - if (isset($this->partialCounter)) { + if (property_exists($this, 'partialCounter') && $this->partialCounter !== null) { $view->partialCounter = $this->partialCounter; } - if (isset($this->partialTotalCount)) { + if (property_exists($this, 'partialTotalCount') && $this->partialTotalCount !== null) { $view->partialTotalCount = $this->partialTotalCount; } @@ -129,11 +137,7 @@ public function cloneView() */ public function setObjectKey($key) { - if (null === $key) { - $this->_objectKey = null; - } else { - $this->_objectKey = (string) $key; - } + $this->_objectKey = null === $key ? null : (string) $key; return $this; } diff --git a/library/Zend/View/Helper/PartialLoop.php b/library/Zend/View/Helper/PartialLoop.php index 4f90da1918..e0e3358a39 100644 --- a/library/Zend/View/Helper/PartialLoop.php +++ b/library/Zend/View/Helper/PartialLoop.php @@ -35,6 +35,7 @@ class Zend_View_Helper_PartialLoop extends Zend_View_Helper_Partial { + public int $partialTotalCount; /** * Marker to where the pointer is at in the loop * @var integer diff --git a/library/Zend/View/Helper/Placeholder/Container/Abstract.php b/library/Zend/View/Helper/Placeholder/Container/Abstract.php index 0f9cbab476..1f186882a3 100644 --- a/library/Zend/View/Helper/Placeholder/Container/Abstract.php +++ b/library/Zend/View/Helper/Placeholder/Container/Abstract.php @@ -30,6 +30,7 @@ */ abstract class Zend_View_Helper_Placeholder_Container_Abstract extends ArrayObject { + public $view; /** * Whether or not to override all contents of placeholder * @const string @@ -369,8 +370,7 @@ public function toString($indent = null) . $this->getPrefix() . implode($this->getSeparator(), $items) . $this->getPostfix(); - $return = preg_replace("/(\r\n?|\n)/", '$1' . $indent, $return); - return $return; + return preg_replace("/(\r\n?|\n)/", '$1' . $indent, $return); } /** diff --git a/library/Zend/View/Helper/Placeholder/Container/Standalone.php b/library/Zend/View/Helper/Placeholder/Container/Standalone.php index deeca4de31..330c11b5c1 100644 --- a/library/Zend/View/Helper/Placeholder/Container/Standalone.php +++ b/library/Zend/View/Helper/Placeholder/Container/Standalone.php @@ -100,7 +100,7 @@ public function setRegistry(Zend_View_Helper_Placeholder_Registry $registry) */ public function setAutoEscape($autoEscape = true) { - $this->_autoEscape = ($autoEscape) ? true : false; + $this->_autoEscape = $autoEscape; return $this; } @@ -261,7 +261,7 @@ public function __toString() * * @return int */ - public function count() + public function count(): int { $container = $this->getContainer(); return count($container); @@ -273,7 +273,7 @@ public function count() * @param string|int $offset * @return bool */ - public function offsetExists($offset) + public function offsetExists($offset): bool { return $this->getContainer()->offsetExists($offset); } @@ -284,7 +284,7 @@ public function offsetExists($offset) * @param string|int $offset * @return mixed */ - public function offsetGet($offset) + public function offsetGet($offset): mixed { return $this->getContainer()->offsetGet($offset); } @@ -296,6 +296,7 @@ public function offsetGet($offset) * @param mixed $value * @return void */ + #[\ReturnTypeWillChange] public function offsetSet($offset, $value) { return $this->getContainer()->offsetSet($offset, $value); @@ -307,6 +308,7 @@ public function offsetSet($offset, $value) * @param string|int $offset * @return void */ + #[\ReturnTypeWillChange] public function offsetUnset($offset) { return $this->getContainer()->offsetUnset($offset); @@ -317,7 +319,7 @@ public function offsetUnset($offset) * * @return Iterator */ - public function getIterator() + public function getIterator(): Traversable { return $this->getContainer()->getIterator(); } diff --git a/library/Zend/View/Helper/Placeholder/Registry.php b/library/Zend/View/Helper/Placeholder/Registry.php index 3d7ee3b50c..6ea474ac2b 100644 --- a/library/Zend/View/Helper/Placeholder/Registry.php +++ b/library/Zend/View/Helper/Placeholder/Registry.php @@ -39,6 +39,7 @@ */ class Zend_View_Helper_Placeholder_Registry { + public $view; /** * Zend_Registry key under which placeholder registry exists * @const string @@ -100,9 +101,7 @@ public function getContainer($key) return $this->_items[$key]; } - $container = $this->createContainer($key); - - return $container; + return $this->createContainer($key); } /** @@ -114,8 +113,7 @@ public function getContainer($key) public function containerExists($key) { $key = (string) $key; - $return = array_key_exists($key, $this->_items); - return $return; + return array_key_exists($key, $this->_items); } /** diff --git a/library/Zend/View/Helper/ServerUrl.php b/library/Zend/View/Helper/ServerUrl.php index c38ec8bc86..ac7a5089d6 100644 --- a/library/Zend/View/Helper/ServerUrl.php +++ b/library/Zend/View/Helper/ServerUrl.php @@ -65,10 +65,9 @@ public function __construct() if (isset($_SERVER['HTTP_HOST']) && !empty($_SERVER['HTTP_HOST'])) { $this->setHost($_SERVER['HTTP_HOST']); - } else if (isset($_SERVER['SERVER_NAME'], $_SERVER['SERVER_PORT'])) { + } elseif (isset($_SERVER['SERVER_NAME'], $_SERVER['SERVER_PORT'])) { $name = $_SERVER['SERVER_NAME']; $port = $_SERVER['SERVER_PORT']; - if (($scheme == 'http' && $port == 80) || ($scheme == 'https' && $port == 443)) { $this->setHost($name); @@ -93,11 +92,7 @@ public function serverUrl($requestUri = null) { if ($requestUri === true) { $path = $_SERVER['REQUEST_URI']; - } else if (is_string($requestUri)) { - $path = $requestUri; - } else { - $path = ''; - } + } else $path = is_string($requestUri) ? $requestUri : ''; return $this->getScheme() . '://' . $this->getHost() . $path; } diff --git a/library/Zend/View/Helper/Translate.php b/library/Zend/View/Helper/Translate.php index f66a560b0d..04733c7962 100644 --- a/library/Zend/View/Helper/Translate.php +++ b/library/Zend/View/Helper/Translate.php @@ -77,13 +77,11 @@ public function translate($messageid = null) array_shift($options); $count = count($options); $locale = null; - if ($count > 0) { - if (Zend_Locale::isLocale($options[($count - 1)], null, false) !== false) { - $locale = array_pop($options); - } + if ($count > 0 && Zend_Locale::isLocale($options[($count - 1)], null, false)) { + $locale = array_pop($options); } - if ((count($options) === 1) and (is_array($options[0]) === true)) { + if (count($options) === 1 && is_array($options[0])) { $options = $options[0]; } @@ -91,7 +89,7 @@ public function translate($messageid = null) $messageid = $translate->translate($messageid, $locale); } - if (count($options) === 0) { + if ($options === []) { return $messageid; } @@ -109,7 +107,7 @@ public function setTranslator($translate) { if ($translate instanceof Zend_Translate_Adapter) { $this->_translator = $translate; - } else if ($translate instanceof Zend_Translate) { + } elseif ($translate instanceof Zend_Translate) { $this->_translator = $translate->getAdapter(); } else { require_once 'Zend/View/Exception.php'; @@ -148,7 +146,7 @@ public function getTranslator() public function setLocale($locale = null) { $translate = $this->getTranslator(); - if ($translate === null) { + if (!$translate instanceof \Zend_Translate_Adapter) { require_once 'Zend/View/Exception.php'; $e = new Zend_View_Exception('You must set an instance of Zend_Translate or Zend_Translate_Adapter'); $e->setView($this->view); @@ -168,7 +166,7 @@ public function setLocale($locale = null) public function getLocale() { $translate = $this->getTranslator(); - if ($translate === null) { + if (!$translate instanceof \Zend_Translate_Adapter) { require_once 'Zend/View/Exception.php'; $e = new Zend_View_Exception('You must set an instance of Zend_Translate or Zend_Translate_Adapter'); $e->setView($this->view); diff --git a/library/Zend/Wildfire/Channel/HttpHeaders.php b/library/Zend/Wildfire/Channel/HttpHeaders.php index b76d12e919..7617cd7029 100644 --- a/library/Zend/Wildfire/Channel/HttpHeaders.php +++ b/library/Zend/Wildfire/Channel/HttpHeaders.php @@ -120,7 +120,7 @@ public static function init($class = null) */ public static function getInstance($skipCreate=false) { - if (self::$_instance===null && $skipCreate!==true) { + if (self::$_instance===null && !$skipCreate) { return self::init(); } return self::$_instance; @@ -164,9 +164,8 @@ public function getProtocol($uri) */ protected function _initProtocol($uri) { - switch ($uri) { - case Zend_Wildfire_Protocol_JsonStream::PROTOCOL_URI; - return new Zend_Wildfire_Protocol_JsonStream(); + if ($uri === Zend_Wildfire_Protocol_JsonStream::PROTOCOL_URI) { + return new Zend_Wildfire_Protocol_JsonStream(); } require_once 'Zend/Wildfire/Exception.php'; throw new Zend_Wildfire_Exception('Tyring to initialize unknown protocol for URI "'.$uri.'".'); @@ -330,7 +329,7 @@ public function getResponse() { if (!$this->_response) { $response = Zend_Controller_Front::getInstance()->getResponse(); - if ($response) { + if ($response !== null) { $this->setResponse($response); } } diff --git a/library/Zend/Wildfire/Plugin/FirePhp.php b/library/Zend/Wildfire/Plugin/FirePhp.php index 0ccc747cb8..08e7fd8c37 100644 --- a/library/Zend/Wildfire/Plugin/FirePhp.php +++ b/library/Zend/Wildfire/Plugin/FirePhp.php @@ -46,6 +46,7 @@ */ class Zend_Wildfire_Plugin_FirePhp implements Zend_Wildfire_Plugin_Interface { + public array $objectFilters; /** * Plain log style. */ @@ -219,7 +220,7 @@ protected function __construct() */ public static function getInstance($skipCreate=false) { - if (self::$_instance===null && $skipCreate!==true) { + if (self::$_instance===null && !$skipCreate) { return self::init(); } return self::$_instance; @@ -398,34 +399,25 @@ public static function send($var, $label=null, $style=null, $options=array()) $meta['Type'] = $style; if ($var instanceof Exception) { - $eTrace = $var->getTrace(); $eTrace = array_splice($eTrace, 0, $options['maxTraceDepth']); - $var = array('Class'=>get_class($var), 'Message'=>$var->getMessage(), 'File'=>$var->getFile(), 'Line'=>$var->getLine(), 'Type'=>'throw', 'Trace'=>$firephp->_encodeTrace($eTrace)); - $meta['Type'] = self::EXCEPTION; - $skipFinalEncode = true; - - } else - if ($meta['Type']==self::TRACE) { - + } elseif ($meta['Type']==self::TRACE) { if (!$label && $var) { $label = $var; $var = null; } - if (!$trace) { $trace = $firephp->_getStackTrace(array_merge($options, array('maxTraceDepth'=>$options['maxTraceDepth']+1))); } - $var = array('Class'=>$trace[0]['class'], 'Type'=>$trace[0]['type'], 'Function'=>$trace[0]['function'], @@ -434,23 +426,15 @@ public static function send($var, $label=null, $style=null, $options=array()) 'Line'=>isset($trace[0]['line'])?$trace[0]['line']:'', 'Args'=>isset($trace[0]['args'])?$firephp->_encodeObject($trace[0]['args']):'', 'Trace'=>$firephp->_encodeTrace(array_splice($trace,1))); - - $skipFinalEncode = true; - - } else - if ($meta['Type']==self::TABLE) { - - $var = $firephp->_encodeTable($var); - - $skipFinalEncode = true; - - } else { - if ($meta['Type']===null) { - $meta['Type'] = self::LOG; - } + $skipFinalEncode = true; + } elseif ($meta['Type']==self::TABLE) { + $var = $firephp->_encodeTable($var); + $skipFinalEncode = true; + } elseif ($meta['Type']===null) { + $meta['Type'] = self::LOG; } - if ($label!=null) { + if ($label != null) { $meta['Label'] = $label; } @@ -489,10 +473,8 @@ public static function send($var, $label=null, $style=null, $options=array()) unset($meta['Line']); } - if ($meta['Type'] == self::GROUP_START) { - if (isset($options['Collapsed'])) { - $meta['Collapsed'] = ($options['Collapsed'])?'true':'false'; - } + if ($meta['Type'] == self::GROUP_START && isset($options['Collapsed'])) { + $meta['Collapsed'] = ($options['Collapsed'])?'true':'false'; } if ($meta['Type'] == self::DUMP) { @@ -523,22 +505,19 @@ protected function _getStackTrace($options) $trace = array_splice($trace, $options['traceOffset']); - if (!count($trace)) { + if ($trace === []) { return $trace; } - if (isset($options['fixZendLogOffsetIfApplicable']) && $options['fixZendLogOffsetIfApplicable']) { - if (count($trace) >=3 && - isset($trace[0]['file']) && substr($trace[0]['file'], -7, 7)=='Log.php' && - isset($trace[1]['function']) && $trace[1]['function']=='__call') { - - $spliceOffset = 2; - //Debug backtrace changed in PHP 7.0.0 - if (version_compare(PHP_VERSION, '7.0.0', '>=')) { - $spliceOffset = 1; - } - $trace = array_splice($trace, $spliceOffset); + if (isset($options['fixZendLogOffsetIfApplicable']) && $options['fixZendLogOffsetIfApplicable'] && (count($trace) >=3 && + isset($trace[0]['file']) && substr($trace[0]['file'], -7, 7)=='Log.php' && + isset($trace[1]['function']) && $trace[1]['function']=='__call')) { + $spliceOffset = 2; + //Debug backtrace changed in PHP 7.0.0 + if (version_compare(PHP_VERSION, '7.0.0', '>=')) { + $spliceOffset = 1; } + $trace = array_splice($trace, $spliceOffset); } return array_splice($trace, 0, $options['maxTraceDepth']); @@ -622,13 +601,14 @@ protected function _encodeTable($table) if (!$table) { return $table; } - for ($i=0 ; $i_encodeObject($table[$i][$j]); + foreach ($table as $i => $singleTable) { + if (is_array($singleTable)) { + $itemsCount = count($table[$i]); + for ($j=0 ; $j<$itemsCount ; $j++) { + $table[$i][$j] = $this->_encodeObject($singleTable[$j]); } } - } + } return $table; } @@ -643,7 +623,8 @@ protected function _encodeTrace($trace) if (!$trace) { return $trace; } - for ($i=0 ; $i_encodeObject($trace[$i]['args']); } @@ -665,33 +646,24 @@ protected function _encodeObject($object, $objectDepth = 1, $arrayDepth = 1) $return = array(); if (is_resource($object)) { - return '** '.(string)$object.' **'; - - } else - if (is_object($object)) { - + } elseif (is_object($object)) { if ($objectDepth > $this->_options['maxObjectDepth']) { return '** Max Object Depth ('.$this->_options['maxObjectDepth'].') **'; } - foreach ($this->_objectStack as $refVal) { if ($refVal === $object) { return '** Recursion ('.get_class($object).') **'; } } - array_push($this->_objectStack, $object); - + $this->_objectStack[] = $object; $return['__className'] = $class = get_class($object); - $reflectionClass = new ReflectionClass($class); $properties = array(); foreach ( $reflectionClass->getProperties() as $property) { $properties[$property->getName()] = $property; } - $members = (array)$object; - foreach ($properties as $just_name => $property) { $name = $raw_name = $just_name; @@ -701,12 +673,10 @@ protected function _encodeObject($object, $objectDepth = 1, $arrayDepth = 1) } if ($property->isPublic()) { $name = 'public:'.$name; - } else - if ($property->isPrivate()) { + } elseif ($property->isPrivate()) { $name = 'private:'.$name; $raw_name = "\0".$class."\0".$raw_name; - } else - if ($property->isProtected()) { + } elseif ($property->isProtected()) { $name = 'protected:'.$name; $raw_name = "\0".'*'."\0".$raw_name; } @@ -717,25 +687,19 @@ protected function _encodeObject($object, $objectDepth = 1, $arrayDepth = 1) if (array_key_exists($raw_name,$members) && !$property->isStatic()) { - $return[$name] = $this->_encodeObject($members[$raw_name], $objectDepth + 1, 1); - + } elseif (method_exists($property,'setAccessible')) { + $property->setAccessible(true); + $return[$name] = $this->_encodeObject($property->getValue($object), $objectDepth + 1, 1); + } elseif ($property->isPublic()) { + $return[$name] = $this->_encodeObject($property->getValue($object), $objectDepth + 1, 1); } else { - if (method_exists($property,'setAccessible')) { - $property->setAccessible(true); - $return[$name] = $this->_encodeObject($property->getValue($object), $objectDepth + 1, 1); - } else - if ($property->isPublic()) { - $return[$name] = $this->_encodeObject($property->getValue($object), $objectDepth + 1, 1); - } else { - $return[$name] = '** Need PHP 5.3 to get value **'; - } + $return[$name] = '** Need PHP 5.3 to get value **'; } } else { $return[$name] = '** Excluded by Filter **'; } } - // Include all members that are not defined in the class // but exist in the object foreach($members as $just_name => $value) { @@ -759,9 +723,7 @@ protected function _encodeObject($object, $objectDepth = 1, $arrayDepth = 1) } } } - array_pop($this->_objectStack); - } elseif (is_array($object)) { if ($arrayDepth > $this->_options['maxArrayDepth']) { @@ -810,7 +772,7 @@ public function getUri() */ public function flushMessages($protocolUri) { - if (!$this->_messages || $protocolUri!=self::PROTOCOL_URI) { + if (!$this->_messages || $protocolUri != self::PROTOCOL_URI) { return; } diff --git a/library/Zend/Wildfire/Protocol/JsonStream.php b/library/Zend/Wildfire/Protocol/JsonStream.php index dcf893a647..0ee509b188 100644 --- a/library/Zend/Wildfire/Protocol/JsonStream.php +++ b/library/Zend/Wildfire/Protocol/JsonStream.php @@ -107,7 +107,7 @@ public function clearMessages(Zend_Wildfire_Plugin_Interface $plugin) $uri = $plugin->getUri(); $present = false; - foreach ($this->_messages as $structure => $messages) { + foreach (array_keys($this->_messages) as $structure) { if(!isset($this->_messages[$structure][$uri])) { continue; @@ -193,10 +193,9 @@ public function getPayload(Zend_Wildfire_Channel_Interface $channel) $parts = explode("\n",chunk_split($message, 5000, "\n")); - for ($i=0 ; $i $part) { + $part = $part; + if ($part !== '' && $part !== '0') { $msg = ''; diff --git a/library/Zend/Xml/Security.php b/library/Zend/Xml/Security.php index f66f42cd92..526526b218 100644 --- a/library/Zend/Xml/Security.php +++ b/library/Zend/Xml/Security.php @@ -54,10 +54,7 @@ protected static function heuristicScan($xml) */ public static function loadXmlErrorHandler($errno, $errstr, $errfile, $errline) { - if (substr_count($errstr, 'DOMDocument::loadXML()') > 0) { - return true; - } - return false; + return substr_count($errstr, 'DOMDocument::loadXML()') > 0; } /** @@ -83,7 +80,6 @@ public static function scan($xml, DOMDocument $dom = null) } if (!self::isPhpFpm()) { - $loadEntities = libxml_disable_entity_loader(true); $useInternalXmlErrors = libxml_use_internal_errors(true); } @@ -97,7 +93,6 @@ public static function scan($xml, DOMDocument $dom = null) if (!$result) { // Entity load to previous setting if (!self::isPhpFpm()) { - libxml_disable_entity_loader($loadEntities); libxml_use_internal_errors($useInternalXmlErrors); } return false; @@ -106,18 +101,15 @@ public static function scan($xml, DOMDocument $dom = null) // Scan for potential XEE attacks using ENTITY, if not PHP-FPM if (!self::isPhpFpm()) { foreach ($dom->childNodes as $child) { - if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) { - if ($child->entities->length > 0) { - require_once 'Exception.php'; - throw new Zend_Xml_Exception(self::ENTITY_DETECT); - } + if ($child->nodeType === XML_DOCUMENT_TYPE_NODE && $child->entities->length > 0) { + require_once 'Exception.php'; + throw new Zend_Xml_Exception(self::ENTITY_DETECT); } } } // Entity load to previous setting if (!self::isPhpFpm()) { - libxml_disable_entity_loader($loadEntities); libxml_use_internal_errors($useInternalXmlErrors); } @@ -167,17 +159,13 @@ public static function scanFile($file, DOMDocument $dom = null) public static function isPhpFpm() { $isVulnerableVersion = ( - version_compare(PHP_VERSION, '5.5.22', 'lt') + PHP_VERSION_ID < 50522 || ( - version_compare(PHP_VERSION, '5.6', 'gte') - && version_compare(PHP_VERSION, '5.6.6', 'lt') + PHP_VERSION_ID >= 50600 + && PHP_VERSION_ID < 50606 ) ); - - if (substr(php_sapi_name(), 0, 3) === 'fpm' && $isVulnerableVersion) { - return true; - } - return false; + return substr(php_sapi_name(), 0, 3) === 'fpm' && $isVulnerableVersion; } /** @@ -239,7 +227,7 @@ protected static function detectBom($string) protected static function detectXmlStringEncoding($xml) { foreach (self::getAsciiEncodingMap() as $encoding => $generator) { - $prefix = call_user_func($generator, '<' . '?xml'); + $prefix = call_user_func($generator, '_httpClient = new Zend_Http_Client(); - } else { - $this->_httpClient = $httpClient; - } + $this->_httpClient = $httpClient === null ? new Zend_Http_Client() : $httpClient; $this->_introspector = new Zend_XmlRpc_Client_ServerIntrospection($this); $this->_serverAddress = $server; @@ -352,10 +348,8 @@ public function call($method, $params=array()) if (!is_array($signature)) { continue; } - if (isset($signature['parameters'][$key])) { - if ($signature['parameters'][$key] == $type) { - break; - } + if (isset($signature['parameters'][$key]) && $signature['parameters'][$key] == $type) { + break; } } } elseif (isset($signatures[0]['parameters'][$key])) { diff --git a/library/Zend/XmlRpc/Client/ServerIntrospection.php b/library/Zend/XmlRpc/Client/ServerIntrospection.php index 68848d1112..b58c5e9678 100644 --- a/library/Zend/XmlRpc/Client/ServerIntrospection.php +++ b/library/Zend/XmlRpc/Client/ServerIntrospection.php @@ -99,7 +99,7 @@ public function getSignatureForEachMethodByMulticall($methods = null) throw new Zend_XmlRpc_Client_IntrospectException($error); } - if (count($serverSignatures) != count($methods)) { + if (count($serverSignatures) !== count($methods)) { $error = 'Bad number of signatures received from multicall'; require_once 'Zend/XmlRpc/Client/IntrospectException.php'; throw new Zend_XmlRpc_Client_IntrospectException($error); diff --git a/library/Zend/XmlRpc/Fault.php b/library/Zend/XmlRpc/Fault.php index 25a5b7d010..8e1aff568e 100644 --- a/library/Zend/XmlRpc/Fault.php +++ b/library/Zend/XmlRpc/Fault.php @@ -207,12 +207,12 @@ public function loadXml($fault) } // Check for fault - if (!$xml->fault) { + if ($xml->fault === null) { // Not a fault return false; } - if (!$xml->fault->value->struct) { + if ($xml->fault->value->struct === null) { // not a proper fault require_once 'Zend/XmlRpc/Exception.php'; throw new Zend_XmlRpc_Exception('Invalid fault structure', 500); @@ -239,11 +239,7 @@ public function loadXml($fault) } if (empty($message)) { - if (isset($this->_internal[$code])) { - $message = $this->_internal[$code]; - } else { - $message = 'Unknown Error'; - } + $message = isset($this->_internal[$code]) ? $this->_internal[$code] : 'Unknown Error'; } $this->setCode($code); diff --git a/library/Zend/XmlRpc/Generator/XmlWriter.php b/library/Zend/XmlRpc/Generator/XmlWriter.php index a84e11d3bf..e4c0346ee9 100644 --- a/library/Zend/XmlRpc/Generator/XmlWriter.php +++ b/library/Zend/XmlRpc/Generator/XmlWriter.php @@ -87,7 +87,6 @@ protected function _closeElement($name) public function saveXml() { - $xml = $this->_xmlWriter->flush(false); - return $xml; + return $this->_xmlWriter->flush(false); } } diff --git a/library/Zend/XmlRpc/Request.php b/library/Zend/XmlRpc/Request.php index 73bb9670a3..a48b26c53b 100644 --- a/library/Zend/XmlRpc/Request.php +++ b/library/Zend/XmlRpc/Request.php @@ -211,10 +211,9 @@ public function addParam($value, $type = null) * @access public * @return void */ - public function setParams() + public function setParams(...$argv) { $argc = func_num_args(); - $argv = func_get_args(); if (0 == $argc) { return; } @@ -333,7 +332,7 @@ public function loadXml($request) $types = array(); $argv = array(); foreach ($xml->params->children() as $param) { - if (!isset($param->value)) { + if (!(property_exists($param, 'value') && $param->value !== null)) { $this->_fault = new Zend_XmlRpc_Fault(633); $this->_fault->setEncoding($this->getEncoding()); return false; diff --git a/library/Zend/XmlRpc/Request/Http.php b/library/Zend/XmlRpc/Request/Http.php index df058a1a84..e6721d723b 100644 --- a/library/Zend/XmlRpc/Request/Http.php +++ b/library/Zend/XmlRpc/Request/Http.php @@ -117,8 +117,6 @@ public function getFullRequest() $request .= $key . ': ' . $value . "\n"; } - $request .= $this->_xml; - - return $request; + return $request . $this->_xml; } } diff --git a/library/Zend/XmlRpc/Response.php b/library/Zend/XmlRpc/Response.php index be5a6cbb4e..50a24d38c1 100644 --- a/library/Zend/XmlRpc/Response.php +++ b/library/Zend/XmlRpc/Response.php @@ -207,7 +207,7 @@ public function loadXml($response) } try { - if (!isset($xml->params) || !isset($xml->params->param) || !isset($xml->params->param->value)) { + if (!(property_exists($xml, 'params') && $xml->params !== null) || !(property_exists($xml->params, 'param') && $xml->params->param !== null) || !(property_exists($xml->params->param, 'value') && $xml->params->param->value !== null)) { require_once 'Zend/XmlRpc/Value/Exception.php'; throw new Zend_XmlRpc_Value_Exception('Missing XML-RPC value in XML'); } diff --git a/library/Zend/XmlRpc/Server.php b/library/Zend/XmlRpc/Server.php index 4d02df30f1..5e7db43e34 100644 --- a/library/Zend/XmlRpc/Server.php +++ b/library/Zend/XmlRpc/Server.php @@ -116,6 +116,10 @@ */ class Zend_XmlRpc_Server extends Zend_Server_Abstract { + /** + * @var mixed|\Zend_XmlRpc_Server_System + */ + public $_system; /** * Character encoding * @var string @@ -358,11 +362,7 @@ public function handle($request = false) public function loadFunctions($definition) { if (!is_array($definition) && (!$definition instanceof Zend_Server_Definition)) { - if (is_object($definition)) { - $type = get_class($definition); - } else { - $type = gettype($definition); - } + $type = is_object($definition) ? get_class($definition) : gettype($definition); require_once 'Zend/XmlRpc/Server/Exception.php'; throw new Zend_XmlRpc_Server_Exception('Unable to load server definition; must be an array or Zend_Server_Definition, received ' . $type, 612); } @@ -458,8 +458,7 @@ public function getRequest() */ public function setResponseClass($class) { - if (!class_exists($class) or - ($c = new ReflectionClass($class) and !$c->isSubclassOf('Zend_XmlRpc_Response'))) { + if (!class_exists($class) || ($c = new ReflectionClass($class)) && !$c->isSubclassOf('Zend_XmlRpc_Response')) { require_once 'Zend/XmlRpc/Server/Exception.php'; throw new Zend_XmlRpc_Server_Exception('Invalid response class'); @@ -565,7 +564,7 @@ protected function _handle(Zend_XmlRpc_Request $request) $info = $this->_table->getMethod($method); $params = $request->getParams(); $argv = $info->getInvokeArguments(); - if (0 < count($argv) and $this->sendArgumentsToAllMethods()) { + if ([] !== $argv && $this->sendArgumentsToAllMethods()) { $params = array_merge($params, $argv); } diff --git a/library/Zend/XmlRpc/Server/System.php b/library/Zend/XmlRpc/Server/System.php index 340eb1cd73..665543a9e3 100644 --- a/library/Zend/XmlRpc/Server/System.php +++ b/library/Zend/XmlRpc/Server/System.php @@ -124,11 +124,9 @@ public function multicall($methods) $fault = $this->_server->fault('Missing params', 603); } elseif (!is_array($method['params'])) { $fault = $this->_server->fault('Params must be an array', 604); - } else { - if ('system.multicall' == $method['methodName']) { - // don't allow recursive calls to multicall - $fault = $this->_server->fault('Recursive system.multicall forbidden', 605); - } + } elseif ('system.multicall' == $method['methodName']) { + // don't allow recursive calls to multicall + $fault = $this->_server->fault('Recursive system.multicall forbidden', 605); } if (!$fault) { diff --git a/library/Zend/XmlRpc/Value.php b/library/Zend/XmlRpc/Value.php index 5d45d652b4..0ce6c5bc65 100644 --- a/library/Zend/XmlRpc/Value.php +++ b/library/Zend/XmlRpc/Value.php @@ -275,7 +275,7 @@ public static function getXmlRpcTypeByValue($value) return self::XMLRPC_TYPE_ARRAY; } elseif (is_int($value)) { return ($value > PHP_INT_MAX) ? self::XMLRPC_TYPE_I8 : self::XMLRPC_TYPE_INTEGER; - } elseif (is_double($value)) { + } elseif (is_float($value)) { return self::XMLRPC_TYPE_DOUBLE; } elseif (is_bool($value)) { return self::XMLRPC_TYPE_BOOLEAN; @@ -442,7 +442,7 @@ protected static function _xmlStringToNativeXmlRpc($xml) foreach ($value->member as $member) { // @todo? If a member doesn't have a tag, we don't add it to the struct // Maybe we want to throw an exception here ? - if (!isset($member->value) or !isset($member->name)) { + if (!(property_exists($member, 'value') && $member->value !== null) || !(property_exists($member, 'name') && $member->name !== null)) { continue; //throw new Zend_XmlRpc_Value_Exception('Member of the '. self::XMLRPC_TYPE_STRUCT .' XML-RPC native type must contain a VALUE tag'); } @@ -490,7 +490,7 @@ protected static function _extractTypeAndValue(SimpleXMLElement $xml, &$type, &$ $value = current($xml); next($xml); - if (!$type and $value === null) { + if (!$type && $value === null) { $namespaces = array('ex' => 'http://ws.apache.org/xmlrpc/namespaces/extensions'); foreach ($namespaces as $namespaceName => $namespaceUri) { $namespaceXml = $xml->children($namespaceUri);