From e02dd0e97e0331b71ece54ecd006deedbe831158 Mon Sep 17 00:00:00 2001 From: Koopzington Date: Sun, 13 Nov 2016 16:12:57 +0100 Subject: [PATCH 1/9] Remove CS dependencies and add zend-coding-standard to require-dev --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 740349ac9f..e2e4f43ade 100644 --- a/composer.json +++ b/composer.json @@ -21,9 +21,9 @@ "zendframework/zend-validator": "^2.5" }, "require-dev": { - "fabpot/php-cs-fixer": "1.7.*", "phpunit/PHPUnit": "^4.0", - "zendframework/zend-config": "^2.5" + "zendframework/zend-config": "^2.5", + "zendframework/zend-coding-standard": "~1.0.0" }, "autoload": { "psr-4": { From fc4da6e2729d0a4102c7a346780cb7f15f6ed2f9 Mon Sep 17 00:00:00 2001 From: Koopzington Date: Sun, 13 Nov 2016 20:04:19 +0100 Subject: [PATCH 2/9] Delete .php_cs --- .php_cs | 45 --------------------------------------------- 1 file changed, 45 deletions(-) delete mode 100644 .php_cs diff --git a/.php_cs b/.php_cs deleted file mode 100644 index 8f4dd5aac9..0000000000 --- a/.php_cs +++ /dev/null @@ -1,45 +0,0 @@ -in('src') - ->in('test') - ->notPath('TestAsset') - ->notPath('_files') - ->filter(function (SplFileInfo $file) { - if (strstr($file->getPath(), 'compatibility')) { - return false; - } - }); -$config = Symfony\CS\Config\Config::create(); -$config->level(null); -$config->fixers( - array( - 'braces', - 'duplicate_semicolon', - 'elseif', - 'empty_return', - 'encoding', - 'eof_ending', - 'function_call_space', - 'function_declaration', - 'indentation', - 'join_function', - 'line_after_namespace', - 'linefeed', - 'lowercase_keywords', - 'parenthesis', - 'multiple_use', - 'method_argument_space', - 'object_operator', - 'php_closing_tag', - 'remove_lines_between_uses', - 'short_array_syntax', - 'short_tag', - 'standardize_not_equal', - 'trailing_spaces', - 'unused_use', - 'visibility', - 'whitespacy_lines', - ) -); -$config->finder($finder); -return $config; From 8e899b853e5aa3f1feed181a0f9486f7e0257d1c Mon Sep 17 00:00:00 2001 From: Koopzington Date: Sun, 13 Nov 2016 20:07:04 +0100 Subject: [PATCH 3/9] add/update phpcs.xml --- phpcs.xml | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 phpcs.xml diff --git a/phpcs.xml b/phpcs.xml new file mode 100644 index 0000000000..561c28e4a5 --- /dev/null +++ b/phpcs.xml @@ -0,0 +1,8 @@ + + + + + + src + test + \ No newline at end of file From 9c9d620d767961e2b153c12c9598cb340b2c74c2 Mon Sep 17 00:00:00 2001 From: Koopzington Date: Sun, 13 Nov 2016 20:28:16 +0100 Subject: [PATCH 4/9] add/update composer scripts --- composer.json | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/composer.json b/composer.json index e2e4f43ade..15dfaa02af 100644 --- a/composer.json +++ b/composer.json @@ -34,5 +34,16 @@ "psr-4": { "ZendTest\\Http\\": "test/" } + }, + "scripts": { + "check": [ + "@cs-check", + "@test" + ], + "cs-check": "phpcs", + "cs-fix": "phpcbf", + "test": "phpunit --colors=always", + "test-coverage": "phpunit --colors=always --coverage-clover clover.xml", + "upload-coverage": "coveralls -v" } } From 135c5933d2eb5ac4643e459bdfd5ae82c0aa99b9 Mon Sep 17 00:00:00 2001 From: Koopzington Date: Sun, 13 Nov 2016 20:41:40 +0100 Subject: [PATCH 5/9] Use composer scripts in .travis.yml --- .travis.yml | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/.travis.yml b/.travis.yml index 7995517e78..574c3604d2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -28,10 +28,10 @@ matrix: include: - php: 5.5 env: - - EXECUTE_CS_CHECK=true + - CS_CHECK=true - php: 5.6 env: - - EXECUTE_TEST_COVERALLS=true + - TEST_COVERAGE=true - DEPLOY_DOCS="$(if [[ $TRAVIS_BRANCH == 'master' && $TRAVIS_PULL_REQUEST == 'false' ]]; then echo -n 'true' ; else echo -n 'false' ; fi)" - PATH="$HOME/.local/bin:$PATH" - php: 7 @@ -44,21 +44,20 @@ notifications: email: false before_install: - - if [[ $EXECUTE_TEST_COVERALLS != 'true' ]]; then phpenv config-rm xdebug.ini || return 0 ; fi + - if [[ $TEST_COVERAGE != 'true' ]]; then phpenv config-rm xdebug.ini || return 0 ; fi - composer self-update - - if [[ $EXECUTE_TEST_COVERALLS == 'true' ]]; then composer require --dev --no-update satooshi/php-coveralls ; fi + - if [[ $TEST_COVERAGE == 'true' ]]; then composer require --dev --no-update satooshi/php-coveralls ; fi install: - travis_retry composer install --no-interaction --ignore-platform-reqs script: - - if [[ $EXECUTE_TEST_COVERALLS == 'true' ]]; then ./vendor/bin/phpunit --coverage-clover clover.xml ; fi - - if [[ $EXECUTE_TEST_COVERALLS != 'true' ]]; then ./vendor/bin/phpunit ; fi - - if [[ $EXECUTE_CS_CHECK == 'true' ]]; then ./vendor/bin/php-cs-fixer fix -v --diff --dry-run ; fi + - if [[ $TEST_COVERAGE == 'true' ]]; then composer test-coverage ; else composer test ; fi + - if [[ $CS_CHECK == 'true' ]]; then composer cs-check ; fi - if [[ $DEPLOY_DOCS == "true" && "$TRAVIS_TEST_RESULT" == "0" ]]; then wget -O theme-installer.sh "https://raw.githubusercontent.com/zendframework/zf-mkdoc-theme/master/theme-installer.sh" ; chmod 755 theme-installer.sh ; ./theme-installer.sh ; fi after_success: - if [[ $DEPLOY_DOCS == "true" ]]; then echo "Preparing to build and deploy documentation" ; ./zf-mkdoc-theme/deploy.sh ; echo "Completed deploying documentation" ; fi after_script: - - if [[ $EXECUTE_TEST_COVERALLS == 'true' ]]; then ./vendor/bin/coveralls ; fi + - if [[ $TEST_COVERAGE == 'true' ]]; then composer upload-coverage ; fi From 40717898ec9bd0763d4439e327aef46863b542a2 Mon Sep 17 00:00:00 2001 From: Koopzington Date: Sun, 13 Nov 2016 20:43:27 +0100 Subject: [PATCH 6/9] Replace mentions of php-cs-fixer with phpcs --- CONTRIBUTING.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c5ef81db44..0988627a30 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -77,24 +77,24 @@ To do so: ## Running Coding Standards Checks -This component uses [php-cs-fixer](http://cs.sensiolabs.org/) for coding +This component uses [phpcs](https://github.com/squizlabs/PHP_CodeSniffer) for coding standards checks, and provides configuration for our selected checks. -`php-cs-fixer` is installed by default via Composer. +`phpcs` is installed by default via Composer. To run checks only: ```console -$ ./vendor/bin/php-cs-fixer fix . -v --diff --dry-run --config-file=.php_cs +$ ./vendor/bin/phpcs ``` -To have `php-cs-fixer` attempt to fix problems for you, omit the `--dry-run` -flag: +`phpcs` also includes a tool for fixing most CS violations, `phpcbf`: + ```console -$ ./vendor/bin/php-cs-fixer fix . -v --diff --config-file=.php_cs +$ ./vendor/bin/phpcbf ``` -If you allow php-cs-fixer to fix CS issues, please re-run the tests to ensure +If you allow `phpcbf` to fix CS issues, please re-run the tests to ensure they pass, and make sure you add and commit the changes after verification. ## Recommended Workflow for Contributions From d960ff5583a86ac833295fac45236ed551927594 Mon Sep 17 00:00:00 2001 From: Koopzington Date: Tue, 15 Nov 2016 19:32:41 +0100 Subject: [PATCH 7/9] Replace mentions of phpcs and phpcbf with composer scripts --- CONTRIBUTING.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0988627a30..975e8abbc5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -84,14 +84,14 @@ standards checks, and provides configuration for our selected checks. To run checks only: ```console -$ ./vendor/bin/phpcs +$ composer cs-check ``` `phpcs` also includes a tool for fixing most CS violations, `phpcbf`: ```console -$ ./vendor/bin/phpcbf +$ composer cs-fix ``` If you allow `phpcbf` to fix CS issues, please re-run the tests to ensure From 4dc58dbaae187b650ede0405af3ecee54cee0c3a Mon Sep 17 00:00:00 2001 From: Koopzington Date: Sun, 20 Nov 2016 02:37:05 +0100 Subject: [PATCH 8/9] Automated CS fixes --- src/Client.php | 69 +++++----- src/Client/Adapter/Curl.php | 20 +-- src/Client/Adapter/Proxy.php | 10 +- src/Client/Adapter/Socket.php | 30 ++--- src/Client/Adapter/Test.php | 3 +- src/ClientStatic.php | 20 +-- src/Cookies.php | 8 +- src/Header/AbstractAccept.php | 17 +-- src/Header/AbstractDate.php | 6 +- src/Header/AbstractLocation.php | 2 +- src/Header/AcceptLanguage.php | 2 +- src/Header/CacheControl.php | 1 - src/Header/ContentSecurityPolicy.php | 2 +- src/Header/ContentType.php | 6 +- src/Header/GenericHeader.php | 4 +- src/Header/GenericMultiHeader.php | 2 +- src/Header/Origin.php | 2 +- src/Header/ProxyAuthenticate.php | 2 +- src/Header/SetCookie.php | 20 +-- src/Header/WWWAuthenticate.php | 2 +- src/Headers.php | 6 +- src/PhpEnvironment/RemoteAddress.php | 6 +- src/PhpEnvironment/Request.php | 20 +-- src/PhpEnvironment/Response.php | 2 +- src/Request.php | 6 +- src/Response.php | 16 +-- src/Response/Stream.php | 8 +- test/Client/CommonHttpTests.php | 124 ++++++++++-------- test/Client/CurlTest.php | 25 ++-- test/Client/SocketTest.php | 6 +- test/Client/StaticClientTest.php | 28 ++-- test/Client/StaticTest.php | 78 +++++++---- test/Client/TestAdapterTest.php | 3 +- test/Client/UseCaseTest.php | 8 +- test/Client/_files/testRedirections.php | 8 +- .../_files/testRelativeRedirections.php | 4 +- test/ClientTest.php | 6 +- test/Header/AcceptTest.php | 2 +- test/Header/SetCookieTest.php | 32 ++--- test/PhpEnvironment/RequestTest.php | 4 +- test/Response/ResponseStreamTest.php | 4 +- 41 files changed, 342 insertions(+), 282 deletions(-) diff --git a/src/Client.php b/src/Client.php index 8549db624b..f814776880 100644 --- a/src/Client.php +++ b/src/Client.php @@ -151,7 +151,7 @@ public function setOptions($options = []) if ($options instanceof Traversable) { $options = ArrayUtils::iteratorToArray($options); } - if (!is_array($options)) { + if (! is_array($options)) { throw new Client\Exception\InvalidArgumentException('Config parameter is not valid'); } @@ -181,7 +181,7 @@ public function setOptions($options = []) public function setAdapter($adapter) { if (is_string($adapter)) { - if (!class_exists($adapter)) { + if (! class_exists($adapter)) { throw new Client\Exception\InvalidArgumentException('Unable to locate adapter class "' . $adapter . '"'); } $adapter = new $adapter; @@ -301,7 +301,7 @@ public function getRedirectionsCount() */ public function setUri($uri) { - if (!empty($uri)) { + if (! empty($uri)) { // remember host of last request $lastHost = $this->getRequest()->getUri()->getHost(); $this->getRequest()->setUri($uri); @@ -310,7 +310,7 @@ public function setUri($uri) // reasons, see #4215 for a discussion - currently authentication is also // cleared for peer subdomains due to technical limits $nextHost = $this->getRequest()->getUri()->getHost(); - if (!preg_match('/' . preg_quote($lastHost, '/') . '$/i', $nextHost)) { + if (! preg_match('/' . preg_quote($lastHost, '/') . '$/i', $nextHost)) { $this->clearAuth(); } @@ -686,7 +686,7 @@ protected function openTempStream() { $this->streamName = $this->config['outputstream']; - if (!is_string($this->streamName)) { + if (! is_string($this->streamName)) { // If name is not given, create temp name $this->streamName = tempnam( isset($this->config['streamtmpdir']) ? $this->config['streamtmpdir'] : sys_get_temp_dir(), @@ -719,7 +719,7 @@ protected function openTempStream() */ public function setAuth($user, $password, $type = self::AUTH_BASIC) { - if (!defined('static::AUTH_' . strtoupper($type))) { + if (! defined('static::AUTH_' . strtoupper($type))) { throw new Exception\InvalidArgumentException("Invalid or not supported authentication type: '$type'"); } @@ -758,24 +758,24 @@ public function clearAuth() */ protected function calcAuthDigest($user, $password, $type = self::AUTH_BASIC, $digest = [], $entityBody = null) { - if (!defined('self::AUTH_' . strtoupper($type))) { + if (! defined('self::AUTH_' . strtoupper($type))) { throw new Exception\InvalidArgumentException("Invalid or not supported authentication type: '$type'"); } $response = false; switch (strtolower($type)) { - case self::AUTH_BASIC : + case self::AUTH_BASIC: // In basic authentication, the user name cannot contain ":" if (strpos($user, ':') !== false) { throw new Exception\InvalidArgumentException("The user name cannot contain ':' in Basic HTTP authentication"); } $response = base64_encode($user . ':' . $password); break; - case self::AUTH_DIGEST : + case self::AUTH_DIGEST: if (empty($digest)) { throw new Exception\InvalidArgumentException("The digest cannot be empty"); } foreach ($digest as $key => $value) { - if (!defined('self::DIGEST_' . strtoupper($key))) { + if (! defined('self::DIGEST_' . strtoupper($key))) { throw new Exception\InvalidArgumentException("Invalid or not supported digest authentication parameter: '$key'"); } } @@ -838,10 +838,10 @@ public function send(Request $request = null) // query $query = $this->getRequest()->getQuery(); - if (!empty($query)) { + if (! empty($query)) { $queryArray = $query->toArray(); - if (!empty($queryArray)) { + if (! empty($queryArray)) { $newUri = $uri->toString(); $queryString = http_build_query($queryArray, null, $this->getArgSeparator()); @@ -859,7 +859,7 @@ public function send(Request $request = null) } } // If we have no ports, set the defaults - if (!$uri->getPort()) { + if (! $uri->getPort()) { $uri->setPort($uri->getScheme() == 'https' ? 443 : 80); } @@ -884,7 +884,7 @@ public function send(Request $request = null) } // check that adapter supports streaming before using it - if (is_resource($body) && !($adapter instanceof Client\Adapter\StreamInterface)) { + if (is_resource($body) && ! ($adapter instanceof Client\Adapter\StreamInterface)) { throw new Client\Exception\RuntimeException('Adapter does not support streaming'); } @@ -904,7 +904,7 @@ public function send(Request $request = null) if ($this->config['outputstream']) { $stream = $this->getStream(); - if (!is_resource($stream) && is_string($stream)) { + if (! is_resource($stream) && is_string($stream)) { $stream = fopen($stream, 'r'); } $streamMetaData = stream_get_meta_data($stream); @@ -915,7 +915,7 @@ public function send(Request $request = null) $adapter->setOutputStream(null); $response = Response\Stream::fromStream($response, $stream); $response->setStreamName($this->streamName); - if (!is_string($this->config['outputstream'])) { + if (! is_string($this->config['outputstream'])) { // we used temp name, will need to clean up $response->setCleanup(true); } @@ -925,7 +925,7 @@ public function send(Request $request = null) // Get the cookies from response (if any) $setCookies = $response->getCookie(); - if (!empty($setCookies)) { + if (! empty($setCookies)) { $this->addCookie($setCookies); } @@ -1023,7 +1023,7 @@ public function setFileUpload($filename, $formname, $data = null, $ctype = null) if ($data === false) { throw new Exception\RuntimeException("Unable to read file '{$filename}' for upload", 0, $error); } - if (!$ctype) { + if (! $ctype) { $ctype = $this->detectFileMimeType($filename); } } @@ -1047,7 +1047,7 @@ public function setFileUpload($filename, $formname, $data = null, $ctype = null) public function removeFileUpload($filename) { $file = $this->getRequest()->getFiles()->get($filename); - if (!empty($file)) { + if (! empty($file)) { $this->getRequest()->getFiles()->set($filename, null); return true; } @@ -1066,7 +1066,7 @@ protected function prepareCookies($domain, $path, $secure) { $validCookies = []; - if (!empty($this->cookies)) { + if (! empty($this->cookies)) { foreach ($this->cookies as $id => $cookie) { if ($cookie->isExpired()) { unset($this->cookies[$id]); @@ -1102,7 +1102,7 @@ protected function prepareHeaders($body, $uri) if ($this->config['httpversion'] == Request::VERSION_11) { $host = $uri->getHost(); // If the port is not default, add it - if (!(($uri->getScheme() == 'http' && $uri->getPort() == 80) || + if (! (($uri->getScheme() == 'http' && $uri->getPort() == 80) || ($uri->getScheme() == 'https' && $uri->getPort() == 443))) { $host .= ':' . $uri->getPort(); } @@ -1111,15 +1111,15 @@ protected function prepareHeaders($body, $uri) } // Set the connection header - if (!$this->getRequest()->getHeaders()->has('Connection')) { - if (!$this->config['keepalive']) { + if (! $this->getRequest()->getHeaders()->has('Connection')) { + if (! $this->config['keepalive']) { $headers['Connection'] = 'close'; } } // Set the Accept-encoding header if not set - depending on whether // zlib is available or not. - if (!$this->getRequest()->getHeaders()->has('Accept-Encoding')) { + if (! $this->getRequest()->getHeaders()->has('Accept-Encoding')) { if (function_exists('gzinflate')) { $headers['Accept-Encoding'] = 'gzip, deflate'; } else { @@ -1129,21 +1129,21 @@ protected function prepareHeaders($body, $uri) // Set the user agent header - if (!$this->getRequest()->getHeaders()->has('User-Agent') && isset($this->config['useragent'])) { + if (! $this->getRequest()->getHeaders()->has('User-Agent') && isset($this->config['useragent'])) { $headers['User-Agent'] = $this->config['useragent']; } // Set HTTP authentication if needed - if (!empty($this->auth)) { + if (! empty($this->auth)) { switch ($this->auth['type']) { - case self::AUTH_BASIC : + case self::AUTH_BASIC: $auth = $this->calcAuthDigest($this->auth['user'], $this->auth['password'], $this->auth['type']); if ($auth !== false) { $headers['Authorization'] = 'Basic ' . $auth; } break; - case self::AUTH_DIGEST : - if (!$this->adapter instanceof Client\Adapter\Curl) { + case self::AUTH_DIGEST: + if (! $this->adapter instanceof Client\Adapter\Curl) { throw new Exception\RuntimeException("The digest authentication is only available for curl adapters (Zend\\Http\\Client\\Adapter\\Curl)"); } @@ -1154,11 +1154,11 @@ protected function prepareHeaders($body, $uri) // Content-type $encType = $this->getEncType(); - if (!empty($encType)) { + if (! empty($encType)) { $headers['Content-Type'] = $encType; } - if (!empty($body)) { + if (! empty($body)) { if (is_resource($body)) { $fstat = fstat($body); $headers['Content-Length'] = $fstat['size']; @@ -1191,14 +1191,14 @@ protected function prepareBody() } $rawBody = $this->getRequest()->getContent(); - if (!empty($rawBody)) { + if (! empty($rawBody)) { return $rawBody; } $body = ''; $totalFiles = 0; - if (!$this->getRequest()->getHeaders()->has('Content-Type')) { + if (! $this->getRequest()->getHeaders()->has('Content-Type')) { $totalFiles = count($this->getRequest()->getFiles()->toArray()); // If we have files to upload, force encType to multipart/form-data if ($totalFiles > 0) { @@ -1324,7 +1324,7 @@ public function encodeFormData($boundary, $name, $value, $filename = null, $head */ protected function flattenParametersArray($parray, $prefix = null) { - if (!is_array($parray)) { + if (! is_array($parray)) { return $parray; } @@ -1419,7 +1419,6 @@ public static function encodeAuthHeader($user, $password, $type = self::AUTH_BAS default: throw new Client\Exception\InvalidArgumentException("Not a supported HTTP authentication type: '$type'"); - } return; diff --git a/src/Client/Adapter/Curl.php b/src/Client/Adapter/Curl.php index 552b781890..a12e647193 100644 --- a/src/Client/Adapter/Curl.php +++ b/src/Client/Adapter/Curl.php @@ -71,7 +71,7 @@ class Curl implements HttpAdapter, StreamInterface */ public function __construct() { - if (!extension_loaded('curl')) { + if (! extension_loaded('curl')) { throw new AdapterException\InitializationException( 'cURL extension has to be loaded to use this Zend\Http\Client adapter' ); @@ -104,7 +104,7 @@ public function setOptions($options = []) if ($options instanceof Traversable) { $options = ArrayUtils::iteratorToArray($options); } - if (!is_array($options)) { + if (! is_array($options)) { throw new AdapterException\InvalidArgumentException( 'Array or Traversable object expected, got ' . gettype($options) ); @@ -166,7 +166,7 @@ public function getConfig() */ public function setCurlOption($option, $value) { - if (!isset($this->config['curloptions'])) { + if (! isset($this->config['curloptions'])) { $this->config['curloptions'] = []; } $this->config['curloptions'][$option] = $value; @@ -214,7 +214,7 @@ public function connect($host, $port = 80, $secure = false) curl_setopt($this->curl, CURLOPT_MAXREDIRS, $this->config['maxredirects']); } - if (!$this->curl) { + if (! $this->curl) { $this->close(); throw new AdapterException\RuntimeException('Unable to Connect to ' . $host . ':' . $port); @@ -251,7 +251,7 @@ public function connect($host, $port = 80, $secure = false) public function write($method, $uri, $httpVersion = 1.1, $headers = [], $body = '') { // Make sure we're properly connected - if (!$this->curl) { + if (! $this->curl) { throw new AdapterException\RuntimeException("Trying to write but we are not connected"); } @@ -282,8 +282,8 @@ public function write($method, $uri, $httpVersion = 1.1, $headers = [], $body = if (isset($this->config['curloptions'][CURLOPT_INFILE])) { // Now we will probably already have Content-Length set, so that we have to delete it // from $headers at this point: - if (!isset($headers['Content-Length']) - && !isset($this->config['curloptions'][CURLOPT_INFILESIZE]) + if (! isset($headers['Content-Length']) + && ! isset($this->config['curloptions'][CURLOPT_INFILESIZE]) ) { throw new AdapterException\RuntimeException( 'Cannot set a file-handle for cURL option CURLOPT_INFILE' @@ -373,7 +373,7 @@ public function write($method, $uri, $httpVersion = 1.1, $headers = [], $body = } // set additional headers - if (!isset($headers['Accept'])) { + if (! isset($headers['Accept'])) { $headers['Accept'] = ''; } $curlHeaders = []; @@ -402,7 +402,7 @@ public function write($method, $uri, $httpVersion = 1.1, $headers = [], $body = // set additional curl options if (isset($this->config['curloptions'])) { foreach ((array) $this->config['curloptions'] as $k => $v) { - if (!in_array($k, $this->invalidOverwritableCurlOptions)) { + if (! in_array($k, $this->invalidOverwritableCurlOptions)) { if (curl_setopt($this->curl, $k, $v) == false) { throw new AdapterException\RuntimeException(sprintf( 'Unknown or erroreous cURL option "%s" set', @@ -417,7 +417,7 @@ public function write($method, $uri, $httpVersion = 1.1, $headers = [], $body = $response = curl_exec($this->curl); // if we used streaming, headers are already there - if (!is_resource($this->outputStream)) { + if (! is_resource($this->outputStream)) { $this->response = $response; } diff --git a/src/Client/Adapter/Proxy.php b/src/Client/Adapter/Proxy.php index a2b06e1515..44e6742cc7 100644 --- a/src/Client/Adapter/Proxy.php +++ b/src/Client/Adapter/Proxy.php @@ -136,7 +136,9 @@ public function write($method, $uri, $httpVer = '1.1', $headers = [], $body = '' // Add Proxy-Authorization header if ($this->config['proxy_user'] && ! isset($headers['proxy-authorization'])) { $headers['proxy-authorization'] = Client::encodeAuthHeader( - $this->config['proxy_user'], $this->config['proxy_pass'], $this->config['proxy_auth'] + $this->config['proxy_user'], + $this->config['proxy_pass'], + $this->config['proxy_auth'] ); } @@ -179,7 +181,7 @@ public function write($method, $uri, $httpVer = '1.1', $headers = [], $body = '' ErrorHandler::start(); $test = fwrite($this->socket, $request); $error = ErrorHandler::stop(); - if (!$test) { + if (! $test) { throw new AdapterException\RuntimeException("Error writing request to proxy server", 0, $error); } @@ -224,7 +226,7 @@ protected function connectHandshake($host, $port = 443, $httpVer = '1.1', array ErrorHandler::start(); $test = fwrite($this->socket, $request); $error = ErrorHandler::stop(); - if (!$test) { + if (! $test) { throw new AdapterException\RuntimeException("Error writing request to proxy server", 0, $error); } @@ -236,7 +238,7 @@ protected function connectHandshake($host, $port = 443, $httpVer = '1.1', array $gotStatus = $gotStatus || (strpos($line, 'HTTP') !== false); if ($gotStatus) { $response .= $line; - if (!rtrim($line)) { + if (! rtrim($line)) { break; } } diff --git a/src/Client/Adapter/Socket.php b/src/Client/Adapter/Socket.php index 07b7a3ef69..9795a5dd2e 100644 --- a/src/Client/Adapter/Socket.php +++ b/src/Client/Adapter/Socket.php @@ -105,7 +105,7 @@ public function setOptions($options = []) if ($options instanceof Traversable) { $options = ArrayUtils::iteratorToArray($options); } - if (!is_array($options)) { + if (! is_array($options)) { throw new AdapterException\InvalidArgumentException( 'Array or Zend\Config object expected, got ' . gettype($options) ); @@ -194,42 +194,42 @@ public function connect($host, $port = 80, $secure = false) } // Now, if we are not connected, connect - if (!is_resource($this->socket) || ! $this->config['keepalive']) { + if (! is_resource($this->socket) || ! $this->config['keepalive']) { $context = $this->getStreamContext(); if ($secure || $this->config['sslusecontext']) { if ($this->config['sslverifypeer'] !== null) { - if (!stream_context_set_option($context, 'ssl', 'verify_peer', $this->config['sslverifypeer'])) { + if (! stream_context_set_option($context, 'ssl', 'verify_peer', $this->config['sslverifypeer'])) { throw new AdapterException\RuntimeException('Unable to set sslverifypeer option'); } } if ($this->config['sslcafile']) { - if (!stream_context_set_option($context, 'ssl', 'cafile', $this->config['sslcafile'])) { + if (! stream_context_set_option($context, 'ssl', 'cafile', $this->config['sslcafile'])) { throw new AdapterException\RuntimeException('Unable to set sslcafile option'); } } if ($this->config['sslcapath']) { - if (!stream_context_set_option($context, 'ssl', 'capath', $this->config['sslcapath'])) { + if (! stream_context_set_option($context, 'ssl', 'capath', $this->config['sslcapath'])) { throw new AdapterException\RuntimeException('Unable to set sslcapath option'); } } if ($this->config['sslallowselfsigned'] !== null) { - if (!stream_context_set_option($context, 'ssl', 'allow_self_signed', $this->config['sslallowselfsigned'])) { + if (! stream_context_set_option($context, 'ssl', 'allow_self_signed', $this->config['sslallowselfsigned'])) { throw new AdapterException\RuntimeException('Unable to set sslallowselfsigned option'); } } if ($this->config['sslcert'] !== null) { - if (!stream_context_set_option($context, 'ssl', 'local_cert', $this->config['sslcert'])) { + if (! stream_context_set_option($context, 'ssl', 'local_cert', $this->config['sslcert'])) { throw new AdapterException\RuntimeException('Unable to set sslcert option'); } } if ($this->config['sslpassphrase'] !== null) { - if (!stream_context_set_option($context, 'ssl', 'passphrase', $this->config['sslpassphrase'])) { + if (! stream_context_set_option($context, 'ssl', 'passphrase', $this->config['sslpassphrase'])) { throw new AdapterException\RuntimeException('Unable to set sslpassphrase option'); } } @@ -251,7 +251,7 @@ public function connect($host, $port = 80, $secure = false) ); $error = ErrorHandler::stop(); - if (!$this->socket) { + if (! $this->socket) { $this->close(); throw new AdapterException\RuntimeException( sprintf( @@ -266,7 +266,7 @@ public function connect($host, $port = 80, $secure = false) } // Set the stream timeout - if (!stream_set_timeout($this->socket, (int) $this->config['timeout'])) { + if (! stream_set_timeout($this->socket, (int) $this->config['timeout'])) { throw new AdapterException\RuntimeException('Unable to set the connection timeout'); } @@ -280,7 +280,7 @@ public function connect($host, $port = 80, $secure = false) ErrorHandler::start(); $test = stream_socket_enable_crypto($this->socket, true, $sslCryptoMethod); $error = ErrorHandler::stop(); - if (!$test || $error) { + if (! $test || $error) { // Error handling is kind of difficult when it comes to SSL $errorString = ''; if (extension_loaded('openssl')) { @@ -294,9 +294,9 @@ public function connect($host, $port = 80, $secure = false) // There's good chance our error is due to sslcapath not being properly set if (! ($this->config['sslcafile'] || $this->config['sslcapath'])) { $errorString = 'make sure the "sslcafile" or "sslcapath" option are properly set for the environment.'; - } elseif ($this->config['sslcafile'] && !is_file($this->config['sslcafile'])) { + } elseif ($this->config['sslcafile'] && ! is_file($this->config['sslcafile'])) { $errorString = 'make sure the "sslcafile" option points to a valid SSL certificate file'; - } elseif ($this->config['sslcapath'] && !is_dir($this->config['sslcapath'])) { + } elseif ($this->config['sslcapath'] && ! is_dir($this->config['sslcapath'])) { $errorString = 'make sure the "sslcapath" option points to a valid SSL certificate directory'; } } @@ -411,7 +411,7 @@ public function read() $this->_checkSocketReadTimeout(); - $responseObj= Response::fromString($response); + $responseObj = Response::fromString($response); $statusCode = $responseObj->getStatusCode(); @@ -488,7 +488,7 @@ public function read() ErrorHandler::stop(); $this->_checkSocketReadTimeout(); - if (!$this->outStream) { + if (! $this->outStream) { $response .= $chunk; } } while ($chunksize > 0); diff --git a/src/Client/Adapter/Test.php b/src/Client/Adapter/Test.php index ec1d1bdcf8..afd21251bb 100644 --- a/src/Client/Adapter/Test.php +++ b/src/Client/Adapter/Test.php @@ -209,7 +209,8 @@ public function setResponseIndex($index) { if ($index < 0 || $index >= count($this->responses)) { throw new Exception\OutOfRangeException( - 'Index out of range of response buffer size'); + 'Index out of range of response buffer size' + ); } $this->responseIndex = $index; } diff --git a/src/ClientStatic.php b/src/ClientStatic.php index acdc1fc6f1..08803dffd0 100644 --- a/src/ClientStatic.php +++ b/src/ClientStatic.php @@ -27,7 +27,7 @@ class ClientStatic */ protected static function getStaticClient($options = null) { - if (!isset(static::$client) || $options !== null) { + if (! isset(static::$client) || $options !== null) { static::$client = new Client(null, $options); } return static::$client; @@ -49,19 +49,19 @@ public static function get($url, $query = [], $headers = [], $body = null, $clie return false; } - $request= new Request(); + $request = new Request(); $request->setUri($url); $request->setMethod(Request::METHOD_GET); - if (!empty($query) && is_array($query)) { + if (! empty($query) && is_array($query)) { $request->getQuery()->fromArray($query); } - if (!empty($headers) && is_array($headers)) { + if (! empty($headers) && is_array($headers)) { $request->getHeaders()->addHeaders($headers); } - if (!empty($body)) { + if (! empty($body)) { $request->setContent($body); } @@ -85,25 +85,25 @@ public static function post($url, $params, $headers = [], $body = null, $clientO return false; } - $request= new Request(); + $request = new Request(); $request->setUri($url); $request->setMethod(Request::METHOD_POST); - if (!empty($params) && is_array($params)) { + if (! empty($params) && is_array($params)) { $request->getPost()->fromArray($params); } else { throw new Exception\InvalidArgumentException('The array of post parameters is empty'); } - if (!isset($headers['Content-Type'])) { + if (! isset($headers['Content-Type'])) { $headers['Content-Type'] = Client::ENC_URLENCODED; } - if (!empty($headers) && is_array($headers)) { + if (! empty($headers) && is_array($headers)) { $request->getHeaders()->addHeaders($headers); } - if (!empty($body)) { + if (! empty($body)) { $request->setContent($body); } diff --git a/src/Cookies.php b/src/Cookies.php index ab6310d7f1..93062ab0b5 100644 --- a/src/Cookies.php +++ b/src/Cookies.php @@ -104,10 +104,10 @@ public function addCookie($cookie, $refUri = null) if ($cookie instanceof SetCookie) { $domain = $cookie->getDomain(); $path = $cookie->getPath(); - if (!isset($this->cookies[$domain])) { + if (! isset($this->cookies[$domain])) { $this->cookies[$domain] = []; } - if (!isset($this->cookies[$domain][$path])) { + if (! isset($this->cookies[$domain][$path])) { $this->cookies[$domain][$path] = []; } $this->cookies[$domain][$path][$cookie->getName()] = $cookie; @@ -168,7 +168,7 @@ public function getMatchingCookies( ) { if (is_string($uri)) { $uri = Uri\UriFactory::factory($uri, 'http'); - } elseif (!$uri instanceof Uri\Uri) { + } elseif (! $uri instanceof Uri\Uri) { throw new Exception\InvalidArgumentException("Invalid URI string or object passed"); } @@ -208,7 +208,7 @@ public function getCookie($uri, $cookieName, $retAs = self::COOKIE_OBJECT) { if (is_string($uri)) { $uri = Uri\UriFactory::factory($uri, 'http'); - } elseif (!$uri instanceof Uri\Uri) { + } elseif (! $uri instanceof Uri\Uri) { throw new Exception\InvalidArgumentException('Invalid URI specified'); } diff --git a/src/Header/AbstractAccept.php b/src/Header/AbstractAccept.php index c2eac3d35c..5aa697bf8a 100644 --- a/src/Header/AbstractAccept.php +++ b/src/Header/AbstractAccept.php @@ -99,8 +99,8 @@ public static function fromString($headerLine) public function getFieldValuePartsFromHeaderLine($headerLine) { // process multiple accept values, they may be between quotes - if (!preg_match_all('/(?:[^,"]|"(?:[^\\\"]|\\\.)*")+/', $headerLine, $values) - || !isset($values[0]) + if (! preg_match_all('/(?:[^,"]|"(?:[^\\\"]|\\\.)*")+/', $headerLine, $values) + || ! isset($values[0]) ) { throw new Exception\InvalidArgumentException( 'Invalid header line for ' . $this->getFieldName() . ' header string' @@ -230,7 +230,7 @@ function ($v) { $value ); - if ($escaped == $value && !array_intersect(str_split($value), $separators)) { + if ($escaped == $value && ! array_intersect(str_split($value), $separators)) { $value = $key . ($value ? '=' . $value : ''); } else { $value = $key . ($value ? '="' . $escaped . '"' : ''); @@ -250,7 +250,7 @@ function ($v) { */ protected function addType($type, $priority = 1, array $params = []) { - if (!preg_match($this->regexAddType, $type)) { + if (! preg_match($this->regexAddType, $type)) { throw new Exception\InvalidArgumentException(sprintf( '%s expects a valid type; received "%s"', __METHOD__, @@ -258,7 +258,7 @@ protected function addType($type, $priority = 1, array $params = []) )); } - if (!is_int($priority) && !is_float($priority) && !is_numeric($priority) + if (! is_int($priority) && ! is_float($priority) && ! is_numeric($priority) || $priority > 1 || $priority < 0 ) { throw new Exception\InvalidArgumentException(sprintf( @@ -366,7 +366,7 @@ protected function matchAcceptParams($match1, $match2) } } - if (!$good) { + if (! $good) { return false; } } elseif ($match1->params[$key] != $value) { @@ -411,7 +411,8 @@ protected function addFieldValuePartToQueue($value) */ protected function sortFieldValueParts() { - $sort = function ($a, $b) { // If A has higher precedence than B, return -1. + $sort = function ($a, $b) { + // If A has higher precedence than B, return -1. if ($a->priority > $b->priority) { return -1; } elseif ($a->priority < $b->priority) { @@ -452,7 +453,7 @@ protected function sortFieldValueParts() */ public function getPrioritized() { - if (!$this->sorted) { + if (! $this->sorted) { $this->sortFieldValueParts(); } diff --git a/src/Header/AbstractDate.php b/src/Header/AbstractDate.php index b45cfb1563..577db0e05b 100644 --- a/src/Header/AbstractDate.php +++ b/src/Header/AbstractDate.php @@ -134,7 +134,7 @@ public static function fromTimestamp($time) */ public static function setDateFormat($format) { - if (!isset(static::$dateFormats[$format])) { + if (! isset(static::$dateFormats[$format])) { throw new Exception\InvalidArgumentException( "No constant defined for provided date format: {$format}" ); @@ -172,7 +172,7 @@ public function setDate($date) $e ); } - } elseif (!($date instanceof DateTime)) { + } elseif (! ($date instanceof DateTime)) { throw new Exception\InvalidArgumentException('Date must be an instance of \DateTime or a string'); } @@ -226,7 +226,7 @@ public function compareTo($date) $e ); } - } elseif (!($date instanceof DateTime)) { + } elseif (! ($date instanceof DateTime)) { throw new Exception\InvalidArgumentException('Date must be an instance of \DateTime or a string'); } diff --git a/src/Header/AbstractLocation.php b/src/Header/AbstractLocation.php index d493be3bad..5b9823766d 100644 --- a/src/Header/AbstractLocation.php +++ b/src/Header/AbstractLocation.php @@ -79,7 +79,7 @@ public function setUri($uri) $e ); } - } elseif (!($uri instanceof UriInterface)) { + } elseif (! ($uri instanceof UriInterface)) { throw new Exception\InvalidArgumentException('URI must be an instance of Zend\Uri\Http or a string'); } $this->uri = $uri; diff --git a/src/Header/AcceptLanguage.php b/src/Header/AcceptLanguage.php index 62a4da0e09..1942ac8cdb 100644 --- a/src/Header/AcceptLanguage.php +++ b/src/Header/AcceptLanguage.php @@ -86,7 +86,7 @@ protected function parseFieldValuePart($fieldValuePart) } if (strpos($fieldValuePart, '-')) { - $subtypeWhole = $format = $subtype = trim(substr($fieldValuePart, strpos($fieldValuePart, '-')+1)); + $subtypeWhole = $format = $subtype = trim(substr($fieldValuePart, strpos($fieldValuePart, '-') + 1)); } else { $subtypeWhole = ''; $format = '*'; diff --git a/src/Header/CacheControl.php b/src/Header/CacheControl.php index 7513fc1df6..75b3cc1471 100644 --- a/src/Header/CacheControl.php +++ b/src/Header/CacheControl.php @@ -223,7 +223,6 @@ protected static function parseValue($value) default: throw new Exception\InvalidArgumentException('expected SEPARATOR or END'); - } } diff --git a/src/Header/ContentSecurityPolicy.php b/src/Header/ContentSecurityPolicy.php index 540e0f38b9..bff06239c8 100644 --- a/src/Header/ContentSecurityPolicy.php +++ b/src/Header/ContentSecurityPolicy.php @@ -109,7 +109,7 @@ public static function fromString($headerLine) $token = trim($token); if ($token) { list($directiveName, $directiveValue) = explode(' ', $token, 2); - if (!isset($header->directives[$directiveName])) { + if (! isset($header->directives[$directiveName])) { $header->setDirective($directiveName, [$directiveValue]); } } diff --git a/src/Header/ContentType.php b/src/Header/ContentType.php index ffa5c7f13f..eb899539f7 100644 --- a/src/Header/ContentType.php +++ b/src/Header/ContentType.php @@ -58,7 +58,7 @@ public static function fromString($headerLine) $parameters = []; foreach ($parts as $parameter) { $parameter = trim($parameter); - if (!preg_match('/^(?P[^\s\=]+)\="?(?P[^\s\"]*)"?$/', $parameter, $matches)) { + if (! preg_match('/^(?P[^\s\=]+)\="?(?P[^\s\"]*)"?$/', $parameter, $matches)) { continue; } $parameters[$matches['key']] = $matches['value']; @@ -282,7 +282,7 @@ function (&$value) { */ protected function getMediaTypeObjectFromString($string) { - if (!is_string($string)) { + if (! is_string($string)) { throw new Exception\InvalidArgumentException(sprintf( 'Non-string mediatype "%s" provided', (is_object($string) ? get_class($string) : gettype($string)) @@ -337,7 +337,7 @@ protected function validateSubtype($right, $left) // Is the right side a partial wildcard? if ('*' == substr($right->subtype, -1)) { // validate partial-wildcard subtype - if (!$this->validatePartialWildcard($right->subtype, $left->subtype)) { + if (! $this->validatePartialWildcard($right->subtype, $left->subtype)) { return false; } // Finally, verify format is valid diff --git a/src/Header/GenericHeader.php b/src/Header/GenericHeader.php index d17c8e161c..4222646af8 100644 --- a/src/Header/GenericHeader.php +++ b/src/Header/GenericHeader.php @@ -88,7 +88,7 @@ public function __construct($fieldName = null, $fieldValue = null) */ public function setFieldName($fieldName) { - if (!is_string($fieldName) || empty($fieldName)) { + if (! is_string($fieldName) || empty($fieldName)) { throw new Exception\InvalidArgumentException('Header name must be a string'); } @@ -101,7 +101,7 @@ public function setFieldName($fieldName) * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / * "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA */ - if (!preg_match('/^[!#$%&\'*+\-\.\^_`|~0-9a-zA-Z]+$/', $fieldName)) { + if (! preg_match('/^[!#$%&\'*+\-\.\^_`|~0-9a-zA-Z]+$/', $fieldName)) { throw new Exception\InvalidArgumentException( 'Header name must be a valid RFC 7230 (section 3.2) field-name.' ); diff --git a/src/Header/GenericMultiHeader.php b/src/Header/GenericMultiHeader.php index c45c3023e8..8f9490f1dd 100644 --- a/src/Header/GenericMultiHeader.php +++ b/src/Header/GenericMultiHeader.php @@ -32,7 +32,7 @@ public function toStringMultipleHeaders(array $headers) $name = $this->getFieldName(); $values = [$this->getFieldValue()]; foreach ($headers as $header) { - if (!$header instanceof static) { + if (! $header instanceof static) { throw new Exception\InvalidArgumentException('This method toStringMultipleHeaders was expecting an array of headers of the same type'); } $values[] = $header->getFieldValue(); diff --git a/src/Header/Origin.php b/src/Header/Origin.php index 01b95b94d7..6294f65c42 100644 --- a/src/Header/Origin.php +++ b/src/Header/Origin.php @@ -32,7 +32,7 @@ public static function fromString($headerLine) } $uri = UriFactory::factory($value); - if (!$uri->isValid()) { + if (! $uri->isValid()) { throw new Exception\InvalidArgumentException('Invalid header value for Origin key: "' . $name . '"'); } diff --git a/src/Header/ProxyAuthenticate.php b/src/Header/ProxyAuthenticate.php index a423224210..55fb29432c 100644 --- a/src/Header/ProxyAuthenticate.php +++ b/src/Header/ProxyAuthenticate.php @@ -65,7 +65,7 @@ public function toStringMultipleHeaders(array $headers) { $strings = [$this->toString()]; foreach ($headers as $header) { - if (!$header instanceof ProxyAuthenticate) { + if (! $header instanceof ProxyAuthenticate) { throw new Exception\RuntimeException( 'The ProxyAuthenticate multiple header implementation can only accept' . ' an array of ProxyAuthenticate headers' diff --git a/src/Header/SetCookie.php b/src/Header/SetCookie.php index 6efde4671f..707c1f3507 100644 --- a/src/Header/SetCookie.php +++ b/src/Header/SetCookie.php @@ -107,7 +107,7 @@ public static function fromString($headerLine, $bypassHeaderFieldName = false) foreach ($keyValuePairs as $keyValue) { if (preg_match('#^(?P[^=]+)=\s*("?)(?P[^"]*)\2#', $keyValue, $matches)) { $headerKey = $matches['headerKey']; - $headerValue= $matches['headerValue']; + $headerValue = $matches['headerValue']; } else { $headerKey = $keyValue; $headerValue = null; @@ -156,7 +156,7 @@ public static function fromString($headerLine, $bypassHeaderFieldName = false) HeaderValue::assertValid($value); // some sites return set-cookie::value, this is to get rid of the second : - $name = (strtolower($name) =='set-cookie:') ? 'set-cookie' : $name; + $name = (strtolower($name) == 'set-cookie:') ? 'set-cookie' : $name; // check to ensure proper header type for this factory if (strtolower($name) !== 'set-cookie') { @@ -246,7 +246,7 @@ public function getFieldValue() } $maxAge = $this->getMaxAge(); - if ($maxAge!==null) { + if ($maxAge !== null) { $fieldValue .= '; Max-Age=' . $maxAge; } @@ -323,7 +323,7 @@ public function getValue() */ public function setVersion($version) { - if ($version !== null && !is_int($version)) { + if ($version !== null && ! is_int($version)) { throw new Exception\InvalidArgumentException('Invalid Version number specified'); } $this->version = $version; @@ -349,7 +349,7 @@ public function getVersion() */ public function setMaxAge($maxAge) { - if ($maxAge !== null && (!is_int($maxAge) || ($maxAge < 0))) { + if ($maxAge !== null && (! is_int($maxAge) || ($maxAge < 0))) { throw new Exception\InvalidArgumentException('Invalid Max-Age number specified'); } $this->maxAge = $maxAge; @@ -392,7 +392,7 @@ public function setExpires($expires) $tsExpires = strtotime($expires); // if $tsExpires is invalid and PHP is compiled as 32bit. Check if it fail reason is the 2038 bug - if (!is_int($tsExpires) && PHP_INT_SIZE === 4) { + if (! is_int($tsExpires) && PHP_INT_SIZE === 4) { $dateTime = new DateTime($expires); if ($dateTime->format('Y') > 2038) { $tsExpires = PHP_INT_MAX; @@ -400,7 +400,7 @@ public function setExpires($expires) } } - if (!is_int($tsExpires) || $tsExpires < 0) { + if (! is_int($tsExpires) || $tsExpires < 0) { throw new Exception\InvalidArgumentException('Invalid expires time specified'); } @@ -567,7 +567,7 @@ public function isValidForRequest($requestDomain, $path, $isSecure = false) return false; } - if ($this->secure && $this->isSecure()!==$isSecure) { + if ($this->secure && $this->isSecure() !== $isSecure) { return false; } @@ -590,7 +590,7 @@ public function match($uri, $matchSessionCookies = true, $now = null) } // Make sure we have a valid Zend_Uri_Http object - if (! ($uri->isValid() && ($uri->getScheme() == 'http' || $uri->getScheme() =='https'))) { + if (! ($uri->isValid() && ($uri->getScheme() == 'http' || $uri->getScheme() == 'https'))) { throw new Exception\InvalidArgumentException('Passed URI is not a valid HTTP or HTTPS URI'); } @@ -662,7 +662,7 @@ public function toStringMultipleHeaders(array $headers) $headerLine = $this->toString(); /* @var $header SetCookie */ foreach ($headers as $header) { - if (!$header instanceof SetCookie) { + if (! $header instanceof SetCookie) { throw new Exception\RuntimeException( 'The SetCookie multiple header implementation can only accept an array of SetCookie headers' ); diff --git a/src/Header/WWWAuthenticate.php b/src/Header/WWWAuthenticate.php index 2d9681f31c..6d959d4692 100644 --- a/src/Header/WWWAuthenticate.php +++ b/src/Header/WWWAuthenticate.php @@ -65,7 +65,7 @@ public function toStringMultipleHeaders(array $headers) { $strings = [$this->toString()]; foreach ($headers as $header) { - if (!$header instanceof WWWAuthenticate) { + if (! $header instanceof WWWAuthenticate) { throw new Exception\RuntimeException( 'The WWWAuthenticate multiple header implementation can only' . ' accept an array of WWWAuthenticate headers' diff --git a/src/Headers.php b/src/Headers.php index e09e109512..c85fd0784b 100644 --- a/src/Headers.php +++ b/src/Headers.php @@ -142,7 +142,7 @@ public function getPluginClassLoader() */ public function addHeaders($headers) { - if (!is_array($headers) && !$headers instanceof Traversable) { + if (! is_array($headers) && ! $headers instanceof Traversable) { throw new Exception\InvalidArgumentException(sprintf( 'Expected array or Traversable; received "%s"', (is_object($headers) ? get_class($headers) : gettype($headers)) @@ -259,7 +259,7 @@ public function clearHeaders() public function get($name) { $key = static::createKey($name); - if (!in_array($key, $this->headersKeys)) { + if (! in_array($key, $this->headersKeys)) { return false; } @@ -403,7 +403,7 @@ public function toArray() foreach ($this->headers as $header) { if ($header instanceof Header\MultipleHeaderInterface) { $name = $header->getFieldName(); - if (!isset($headers[$name])) { + if (! isset($headers[$name])) { $headers[$name] = []; } $headers[$name][] = $header->getFieldValue(); diff --git a/src/PhpEnvironment/RemoteAddress.php b/src/PhpEnvironment/RemoteAddress.php index 883f76ed66..31f24a8ff2 100644 --- a/src/PhpEnvironment/RemoteAddress.php +++ b/src/PhpEnvironment/RemoteAddress.php @@ -118,14 +118,14 @@ public function getIpAddress() */ protected function getIpAddressFromProxy() { - if (!$this->useProxy - || (isset($_SERVER['REMOTE_ADDR']) && !in_array($_SERVER['REMOTE_ADDR'], $this->trustedProxies)) + if (! $this->useProxy + || (isset($_SERVER['REMOTE_ADDR']) && ! in_array($_SERVER['REMOTE_ADDR'], $this->trustedProxies)) ) { return false; } $header = $this->proxyHeader; - if (!isset($_SERVER[$header]) || empty($_SERVER[$header])) { + if (! isset($_SERVER[$header]) || empty($_SERVER[$header])) { return false; } diff --git a/src/PhpEnvironment/Request.php b/src/PhpEnvironment/Request.php index 01e0bde59d..2cbef7e93d 100644 --- a/src/PhpEnvironment/Request.php +++ b/src/PhpEnvironment/Request.php @@ -207,7 +207,7 @@ public function setServer(ParametersInterface $server) // This seems to be the only way to get the Authorization header on Apache if (function_exists('apache_request_headers')) { $apacheRequestHeaders = apache_request_headers(); - if (!isset($this->serverParams['HTTP_AUTHORIZATION'])) { + if (! isset($this->serverParams['HTTP_AUTHORIZATION'])) { if (isset($apacheRequestHeaders['Authorization'])) { $this->serverParams->set('HTTP_AUTHORIZATION', $apacheRequestHeaders['Authorization']); } elseif (isset($apacheRequestHeaders['authorization'])) { @@ -220,7 +220,7 @@ public function setServer(ParametersInterface $server) $headers = []; foreach ($server as $key => $value) { - if ($value || (!is_array($value) && strlen($value))) { + if ($value || (! is_array($value) && strlen($value))) { if (strpos($key, 'HTTP_') === 0) { if (strpos($key, 'HTTP_COOKIE') === 0) { // Cookies are handled using the $_COOKIE superglobal @@ -253,8 +253,8 @@ public function setServer(ParametersInterface $server) $uri = new HttpUri(); // URI scheme - if ((!empty($this->serverParams['HTTPS']) && strtolower($this->serverParams['HTTPS']) !== 'off') - || (!empty($this->serverParams['HTTP_X_FORWARDED_PROTO']) + if ((! empty($this->serverParams['HTTPS']) && strtolower($this->serverParams['HTTPS']) !== 'off') + || (! empty($this->serverParams['HTTP_X_FORWARDED_PROTO']) && $this->serverParams['HTTP_X_FORWARDED_PROTO'] == 'https') ) { $scheme = 'https'; @@ -284,13 +284,13 @@ public function setServer(ParametersInterface $server) 'useTldCheck' => false, ]); // If invalid. Reset the host & port - if (!$hostnameValidator->isValid($host)) { + if (! $hostnameValidator->isValid($host)) { $host = null; $port = null; } } - if (!$host && isset($this->serverParams['SERVER_NAME'])) { + if (! $host && isset($this->serverParams['SERVER_NAME'])) { $host = $this->serverParams['SERVER_NAME']; if (isset($this->serverParams['SERVER_PORT'])) { $port = (int) $this->serverParams['SERVER_PORT']; @@ -299,7 +299,7 @@ public function setServer(ParametersInterface $server) // Reported at least for Safari on Windows if (isset($this->serverParams['SERVER_ADDR']) && preg_match('/^\[[0-9a-fA-F\:]+\]$/', $host)) { $host = '[' . $this->serverParams['SERVER_ADDR'] . ']'; - if ($port . ']' == substr($host, strrpos($host, ':')+1)) { + if ($port . ']' == substr($host, strrpos($host, ':') + 1)) { // The last digit of the IPv6-Address has been taken as port // Unset the port so the default port can be used $port = null; @@ -393,7 +393,7 @@ protected function mapPhpFiles() foreach ($_FILES as $fileName => $fileParams) { $files[$fileName] = []; foreach ($fileParams as $param => $data) { - if (!is_array($data)) { + if (! is_array($data)) { $files[$fileName][$param] = $data; } else { foreach ($data as $i => $v) { @@ -414,7 +414,7 @@ protected function mapPhpFiles() */ protected function mapPhpFileParam(&$array, $paramName, $index, $value) { - if (!is_array($value)) { + if (! is_array($value)) { $array[$index][$paramName] = $value; } else { foreach ($value as $i => $v) { @@ -458,7 +458,7 @@ protected function detectRequestUri() // HTTP proxy requests setup request URI with scheme and host [and port] // + the URL path, only use URL path. - if (!$httpXRewriteUrl) { + if (! $httpXRewriteUrl) { $requestUri = $server->get('REQUEST_URI'); } diff --git a/src/PhpEnvironment/Response.php b/src/PhpEnvironment/Response.php index 1a3dc5ab1c..a9b17a2e24 100644 --- a/src/PhpEnvironment/Response.php +++ b/src/PhpEnvironment/Response.php @@ -38,7 +38,7 @@ class Response extends HttpResponse */ public function getVersion() { - if (!$this->version) { + if (! $this->version) { $this->version = $this->detectVersion(); } return $this->version; diff --git a/src/Request.php b/src/Request.php index 3fe23310fd..9de0c69a02 100644 --- a/src/Request.php +++ b/src/Request.php @@ -103,7 +103,7 @@ public static function fromString($string, $allowCustomMethods = true) $regex = '#^(?P' . $methods . ')\s(?P[^ ]*)(?:\sHTTP\/(?P\d+\.\d+)){0,1}#'; $firstLine = array_shift($lines); - if (!preg_match($regex, $firstLine, $matches)) { + if (! preg_match($regex, $firstLine, $matches)) { throw new Exception\InvalidArgumentException( 'A valid request line was not found in the provided string' ); @@ -175,7 +175,7 @@ public static function fromString($string, $allowCustomMethods = true) public function setMethod($method) { $method = strtoupper($method); - if (!defined('static::METHOD_' . $method) && ! $this->getAllowCustomMethods()) { + if (! defined('static::METHOD_' . $method) && ! $this->getAllowCustomMethods()) { throw new Exception\InvalidArgumentException('Invalid HTTP method passed'); } $this->method = $method; @@ -211,7 +211,7 @@ public function setUri($uri) $e ); } - } elseif (!($uri instanceof HttpUri)) { + } elseif (! ($uri instanceof HttpUri)) { throw new Exception\InvalidArgumentException( 'URI must be an instance of Zend\Uri\Http or a string' ); diff --git a/src/Response.php b/src/Response.php index f8a2788205..d326c4292c 100644 --- a/src/Response.php +++ b/src/Response.php @@ -170,7 +170,7 @@ class Response extends AbstractMessage implements ResponseInterface public static function fromString($string) { $lines = explode("\r\n", $string); - if (!is_array($lines) || count($lines) === 1) { + if (! is_array($lines) || count($lines) === 1) { $lines = explode("\n", $string); } @@ -180,7 +180,7 @@ public static function fromString($string) $regex = '/^HTTP\/(?P1\.[01]) (?P\d{3})(?:[ ]+(?P.*))?$/'; $matches = []; - if (!preg_match($regex, $firstLine, $matches)) { + if (! preg_match($regex, $firstLine, $matches)) { throw new Exception\InvalidArgumentException( 'A valid response status line was not found in the provided string' ); @@ -249,7 +249,7 @@ public function getCookie() public function setStatusCode($code) { $const = get_class($this) . '::STATUS_CODE_' . $code; - if (!is_numeric($code) || !defined($const)) { + if (! is_numeric($code) || ! defined($const)) { $code = is_scalar($code) ? $code : gettype($code); throw new Exception\InvalidArgumentException(sprintf( 'Invalid status code provided: "%s"', @@ -279,7 +279,7 @@ public function getStatusCode() */ public function setCustomStatusCode($code) { - if (!is_numeric($code)) { + if (! is_numeric($code)) { $code = is_scalar($code) ? $code : gettype($code); throw new Exception\InvalidArgumentException(sprintf( 'Invalid status code provided: "%s"', @@ -337,7 +337,7 @@ public function getBody() $transferEncoding = $this->getHeaders()->get('Transfer-Encoding'); - if (!empty($transferEncoding)) { + if (! empty($transferEncoding)) { if (strtolower($transferEncoding->getFieldValue()) === 'chunked') { $body = $this->decodeChunkedBody($body); } @@ -345,7 +345,7 @@ public function getBody() $contentEncoding = $this->getHeaders()->get('Content-Encoding'); - if (!empty($contentEncoding)) { + if (! empty($contentEncoding)) { $contentEncoding = $contentEncoding->getFieldValue(); if ($contentEncoding === 'gzip') { $body = $this->decodeGzip($body); @@ -510,7 +510,7 @@ protected function decodeChunkedBody($body) */ protected function decodeGzip($body) { - if (!function_exists('gzinflate')) { + if (! function_exists('gzinflate')) { throw new Exception\RuntimeException( 'zlib extension is required in order to decode "gzip" encoding' ); @@ -540,7 +540,7 @@ protected function decodeGzip($body) */ protected function decodeDeflate($body) { - if (!function_exists('gzuncompress')) { + if (! function_exists('gzuncompress')) { throw new Exception\RuntimeException( 'zlib extension is required in order to decode "deflate" encoding' ); diff --git a/src/Response/Stream.php b/src/Response/Stream.php index c5ce0ba581..261d687148 100644 --- a/src/Response/Stream.php +++ b/src/Response/Stream.php @@ -150,7 +150,7 @@ public function setStreamName($streamName) */ public static function fromStream($responseString, $stream) { - if (!is_resource($stream) || get_resource_type($stream) !== 'stream') { + if (! is_resource($stream) || get_resource_type($stream) !== 'stream') { throw new Exception\InvalidArgumentException('A valid stream is required'); } @@ -172,7 +172,7 @@ public static function fromStream($responseString, $stream) } } - if (!$headerComplete) { + if (! $headerComplete) { while (false !== ($nextLine = fgets($stream))) { $headersString .= trim($nextLine)."\r\n"; if ($nextLine == "\r\n" || $nextLine == "\n") { @@ -182,7 +182,7 @@ public static function fromStream($responseString, $stream) } } - if (!$headerComplete) { + if (! $headerComplete) { throw new Exception\OutOfRangeException('End of header not found'); } @@ -268,7 +268,7 @@ protected function readStream() $bytes = -1; // Read the whole buffer } - if (!is_resource($this->stream) || $bytes == 0) { + if (! is_resource($this->stream) || $bytes == 0) { return ''; } diff --git a/test/Client/CommonHttpTests.php b/test/Client/CommonHttpTests.php index bb84bdbb75..a6bbcc27ad 100644 --- a/test/Client/CommonHttpTests.php +++ b/test/Client/CommonHttpTests.php @@ -303,16 +303,22 @@ public function testResetParameters() $res = $this->client->send(); - $this->assertContains(serialize($params) . "\n" . serialize($params), - $res->getBody(), "returned body does not contain all GET and POST parameters (it should!)"); + $this->assertContains( + serialize($params) . "\n" . serialize($params), + $res->getBody(), + "returned body does not contain all GET and POST parameters (it should!)" + ); $this->client->resetParameters(); $this->client->setMethod('POST'); $res = $this->client->send(); - $this->assertNotContains(serialize($params), $res->getBody(), - "returned body contains GET or POST parameters (it shouldn't!)"); - $headerXFoo= $this->client->getHeader("X-Foo"); + $this->assertNotContains( + serialize($params), + $res->getBody(), + "returned body contains GET or POST parameters (it shouldn't!)" + ); + $headerXFoo = $this->client->getHeader("X-Foo"); $this->assertEmpty($headerXFoo, "Header not preserved by reset"); } @@ -418,40 +424,40 @@ public function testHeadersArray() * Test we can set a set of values for one header * */ - public function testMultipleHeader() - { - $this->client->setUri($this->baseuri . 'testHeaders.php'); - $headers = [ - 'Accept-encoding' => 'gzip,deflate', - 'X-baz' => 'Foo', - 'X-powered-by' => [ - 'A large wooden badger', - 'My Shiny Metal Ass', - 'Dark Matter' - ], - 'Cookie' => [ - 'foo=bar', - 'baz=waka' - ] + public function testMultipleHeader() + { + $this->client->setUri($this->baseuri . 'testHeaders.php'); + $headers = [ + 'Accept-encoding' => 'gzip,deflate', + 'X-baz' => 'Foo', + 'X-powered-by' => [ + 'A large wooden badger', + 'My Shiny Metal Ass', + 'Dark Matter' + ], + 'Cookie' => [ + 'foo=bar', + 'baz=waka' + ] ]; - $this->client->setHeaders($headers); - $this->client->setMethod('TRACE'); + $this->client->setHeaders($headers); + $this->client->setMethod('TRACE'); - $res = $this->client->send(); - if ($res->getStatusCode() == 405 || $res->getStatusCode() == 501) { - $this->markTestSkipped("Server does not allow the TRACE method"); - } - $body = strtolower($res->getBody()); + $res = $this->client->send(); + if ($res->getStatusCode() == 405 || $res->getStatusCode() == 501) { + $this->markTestSkipped("Server does not allow the TRACE method"); + } + $body = strtolower($res->getBody()); - foreach ($headers as $key => $val) { - if (is_array($val)) { - $val = implode(', ', $val); - } + foreach ($headers as $key => $val) { + if (is_array($val)) { + $val = implode(', ', $val); + } - $this->assertContains(strtolower("$key: $val"), $body); - } - } + $this->assertContains(strtolower("$key: $val"), $body); + } + } /** * Redirection tests @@ -558,16 +564,20 @@ public function testMaxRedirectsExceeded() $this->client->setMethod('POST'); $res = $this->client->send(); - $this->assertTrue($res->isRedirect(), - "Last response was not a redirection as expected. Response code: {$res->getStatusCode()}. Redirections counter: {$this->client->getRedirectionsCount()} (when strict redirects are on)"); + $this->assertTrue( + $res->isRedirect(), + "Last response was not a redirection as expected. Response code: {$res->getStatusCode()}. Redirections counter: {$this->client->getRedirectionsCount()} (when strict redirects are on)" + ); // Then try with normal redirections $this->client->setParameterGet(['redirection' => '0']); $this->client->setOptions(['strictredirects' => false]); $this->client->setMethod('POST'); $res = $this->client->send(); - $this->assertTrue($res->isRedirect(), - "Last response was not a redirection as expected. Response code: {$res->getStatusCode()}. Redirections counter: {$this->client->getRedirectionsCount()} (when strict redirects are off)"); + $this->assertTrue( + $res->isRedirect(), + "Last response was not a redirection as expected. Response code: {$res->getStatusCode()}. Redirections counter: {$this->client->getRedirectionsCount()} (when strict redirects are off)" + ); } /** @@ -586,8 +596,11 @@ public function testAbsolutePathRedirect() $res = $this->client->send(); - $this->assertEquals("{$uri}/path/to/fake/file.ext?redirect=abpath", $this->client->getUri()->toString(), - "The new location is not as expected: {$this->client->getUri()->toString()}"); + $this->assertEquals( + "{$uri}/path/to/fake/file.ext?redirect=abpath", + $this->client->getUri()->toString(), + "The new location is not as expected: {$this->client->getUri()->toString()}" + ); } /** @@ -607,8 +620,11 @@ public function testRelativePathRedirect() $res = $this->client->send(); - $this->assertEquals("{$uri}?redirect=relpath", $this->client->getUri()->toString(), - "The new location is not as expected: {$this->client->getUri()->toString()}"); + $this->assertEquals( + "{$uri}?redirect=relpath", + $this->client->getUri()->toString(), + "The new location is not as expected: {$this->client->getUri()->toString()}" + ); } /** @@ -746,7 +762,7 @@ public function testSetCookieStringArray() */ public function testUploadRawData() { - if (!ini_get('file_uploads')) { + if (! ini_get('file_uploads')) { $this->markTestSkipped('File uploads disabled.'); } @@ -767,7 +783,7 @@ public function testUploadRawData() */ public function testUploadLocalFile() { - if (!ini_get('file_uploads')) { + if (! ini_get('file_uploads')) { $this->markTestSkipped('File uploads disabled.'); } @@ -784,7 +800,7 @@ public function testUploadLocalFile() public function testUploadLocalDetectMime() { - if (!ini_get('file_uploads')) { + if (! ini_get('file_uploads')) { $this->markTestSkipped('File uploads disabled.'); } @@ -818,7 +834,7 @@ public function testUploadLocalDetectMime() public function testUploadNameWithSpecialChars() { - if (!ini_get('file_uploads')) { + if (! ini_get('file_uploads')) { $this->markTestSkipped('File uploads disabled.'); } @@ -851,7 +867,7 @@ public function testStaticLargeFileDownload() */ public function testMutipleFilesWithSameFormNameZF5744() { - if (!ini_get('file_uploads')) { + if (! ini_get('file_uploads')) { $this->markTestSkipped('File uploads disabled.'); } @@ -890,7 +906,7 @@ public function testZF4238FalseLinesInResponse() public function testStreamResponse() { - if (!($this->client->getAdapter() instanceof Adapter\StreamInterface)) { + if (! ($this->client->getAdapter() instanceof Adapter\StreamInterface)) { $this->markTestSkipped('Current adapter does not support streaming'); return; } @@ -917,7 +933,7 @@ public function testStreamResponseBody() { $this->markTestSkipped('To check with the new ZF2 implementation'); - if (!($this->client->getAdapter() instanceof Adapter\StreamInterface)) { + if (! ($this->client->getAdapter() instanceof Adapter\StreamInterface)) { $this->markTestSkipped('Current adapter does not support streaming'); return; } @@ -937,7 +953,7 @@ public function testStreamResponseBody() public function testStreamResponseNamed() { - if (!($this->client->getAdapter() instanceof Adapter\StreamInterface)) { + if (! ($this->client->getAdapter() instanceof Adapter\StreamInterface)) { $this->markTestSkipped('Current adapter does not support streaming'); return; } @@ -963,7 +979,7 @@ public function testStreamResponseNamed() public function testStreamRequest() { - if (!($this->client->getAdapter() instanceof Adapter\StreamInterface)) { + if (! ($this->client->getAdapter() instanceof Adapter\StreamInterface)) { $this->markTestSkipped('Current adapter does not support streaming'); return; } @@ -1019,8 +1035,10 @@ public function testContentTypeAdditionlInfo($params) $this->client->send(); $request = Request::fromString($this->client->getLastRawRequest()); - $this->assertEquals($content_type, - $request->getHeaders()->get('Content-Type')->getFieldValue()); + $this->assertEquals( + $content_type, + $request->getHeaders()->get('Content-Type')->getFieldValue() + ); } /** diff --git a/test/Client/CurlTest.php b/test/Client/CurlTest.php index 014dc47d07..878d5b62be 100644 --- a/test/Client/CurlTest.php +++ b/test/Client/CurlTest.php @@ -44,7 +44,7 @@ class CurlTest extends CommonHttpTests protected function setUp() { - if (!extension_loaded('curl')) { + if (! extension_loaded('curl')) { $this->markTestSkipped('cURL is not installed, marking all Http Client Curl Adapter tests skipped.'); } parent::setUp(); @@ -103,7 +103,8 @@ public function testSetConfigInvalidConfig($config) { $this->setExpectedException( 'Zend\Http\Client\Adapter\Exception\InvalidArgumentException', - 'Array or Traversable object expected'); + 'Array or Traversable object expected' + ); $this->_adapter->setOptions($config); } @@ -129,7 +130,7 @@ public function testSettingInvalidCurlOption() $this->setExpectedException( 'Zend\Http\Client\Adapter\Exception\RuntimeException', 'Unknown or erroreous cURL option' - ); + ); $this->client->send(); } @@ -167,8 +168,7 @@ public function testRedirectPostToGetWithCurlFollowLocationOptionLeadsToTimeout( 'curloptions' => [ CURLOPT_FOLLOWLOCATION => true, CURLOPT_TIMEOUT => 1, - ]] - ); + ]]); $this->client->setUri($this->baseuri . 'testRedirections.php'); @@ -178,7 +178,8 @@ public function testRedirectPostToGetWithCurlFollowLocationOptionLeadsToTimeout( $this->client->setMethod('POST'); $this->setExpectedException( 'Zend\Http\Client\Adapter\Exception\RuntimeException', - 'Error in cURL request: Operation timed out after 1000 milliseconds with 0 bytes received'); + 'Error in cURL request: Operation timed out after 1000 milliseconds with 0 bytes received' + ); $this->client->send(); } @@ -228,8 +229,10 @@ public function testPutFileHandleWithHttpClient() public function testWritingAndNotConnectedWithCurlHandleThrowsException() { $adapter = new Adapter\Curl(); - $this->setExpectedException('Zend\Http\Client\Adapter\Exception\RuntimeException', - 'Trying to write but we are not connected'); + $this->setExpectedException( + 'Zend\Http\Client\Adapter\Exception\RuntimeException', + 'Trying to write but we are not connected' + ); $adapter->write("GET", "someUri"); } @@ -296,7 +299,8 @@ public function testWorkWithProxyConfiguration() ]; $this->assertEquals( - $expected, $this->readAttribute($adapter, 'config') + $expected, + $this->readAttribute($adapter, 'config') ); } @@ -314,7 +318,8 @@ public function testSslVerifyPeerCanSetOverOption() ]; $this->assertEquals( - $expected, $this->readAttribute($adapter, 'config') + $expected, + $this->readAttribute($adapter, 'config') ); } diff --git a/test/Client/SocketTest.php b/test/Client/SocketTest.php index ab4b7f7dd4..be3e99cafb 100644 --- a/test/Client/SocketTest.php +++ b/test/Client/SocketTest.php @@ -139,7 +139,8 @@ public function testSetConfigInvalidConfig($config) { $this->setExpectedException( 'Zend\Http\Client\Adapter\Exception\InvalidArgumentException', - 'Array or Zend\Config object expected'); + 'Array or Zend\Config object expected' + ); $this->_adapter->setOptions($config); } @@ -197,7 +198,8 @@ public function testSetInvalidContextOptions($invalid) { $this->setExpectedException( 'Zend\Http\Client\Adapter\Exception\InvalidArgumentException', - 'Expecting either a stream context resource or array'); + 'Expecting either a stream context resource or array' + ); $adapterClass = $this->config['adapter']; $adapter = new $adapterClass; diff --git a/test/Client/StaticClientTest.php b/test/Client/StaticClientTest.php index 5dc8a1ce4f..29f6dce2e2 100644 --- a/test/Client/StaticClientTest.php +++ b/test/Client/StaticClientTest.php @@ -81,10 +81,12 @@ public function testHttpGetWithBody() { $getBody = 'baz'; - $response = HTTPClient::get($this->baseuri . 'testRawGetData.php', - ['foo' => 'bar'], - [], - $getBody); + $response = HTTPClient::get( + $this->baseuri . 'testRawGetData.php', + ['foo' => 'bar'], + [], + $getBody + ); $this->assertTrue($response->isSuccess()); $this->assertContains('foo', $response->getBody()); @@ -108,9 +110,11 @@ public function testHttpSimplePost() */ public function testHttpPostContentType() { - $response = HTTPClient::post($this->baseuri . 'testPostData.php', - ['foo' => 'bar'], - ['Content-Type' => Client::ENC_URLENCODED]); + $response = HTTPClient::post( + $this->baseuri . 'testPostData.php', + ['foo' => 'bar'], + ['Content-Type' => Client::ENC_URLENCODED] + ); $this->assertTrue($response->isSuccess()); $this->assertContains('foo', $response->getBody()); $this->assertContains('bar', $response->getBody()); @@ -123,10 +127,12 @@ public function testHttpPostWithBody() { $postBody = 'foo'; - $response = HTTPClient::post($this->baseuri . 'testRawPostData.php', - ['foo' => 'bar'], - ['Content-Type' => Client::ENC_URLENCODED], - $postBody); + $response = HTTPClient::post( + $this->baseuri . 'testRawPostData.php', + ['foo' => 'bar'], + ['Content-Type' => Client::ENC_URLENCODED], + $postBody + ); $this->assertTrue($response->isSuccess()); $this->assertContains($postBody, $response->getBody()); diff --git a/test/Client/StaticTest.php b/test/Client/StaticTest.php index 07bf0b98cc..01440e82e7 100644 --- a/test/Client/StaticTest.php +++ b/test/Client/StaticTest.php @@ -102,8 +102,11 @@ public function testDoubleGetParameter() $this->_client->setMethod('GET'); $res = $this->_client->send(); - $this->assertContains($qstr, $this->_client->getLastRawRequest(), - 'Request is expected to contain the entire query string'); + $this->assertContains( + $qstr, + $this->_client->getLastRawRequest(), + 'Request is expected to contain the entire query string' + ); } /** @@ -138,7 +141,8 @@ public function testExceptUnsupportedAuthDynamic() { $this->setExpectedException( 'Zend\Http\Exception\InvalidArgumentException', - 'Invalid or not supported authentication type: \'SuperStrongAlgo\''); + 'Invalid or not supported authentication type: \'SuperStrongAlgo\'' + ); $this->_client->setAuth('shahar', '1234', 'SuperStrongAlgo'); } @@ -189,7 +193,8 @@ public function testSetInvalidCookies() { $this->setExpectedException( 'Zend\Http\Exception\InvalidArgumentException', - 'Invalid parameter type passed as Cookie'); + 'Invalid parameter type passed as Cookie' + ); $this->_client->addCookie('cookie'); } @@ -248,7 +253,8 @@ public function testConfigSetInvalid($config) { $this->setExpectedException( 'Zend\Http\Client\Exception\InvalidArgumentException', - 'Config parameter is not valid'); + 'Config parameter is not valid' + ); $this->_client->setOptions($config); } @@ -286,16 +292,22 @@ public function testConfigPassToAdapterZF4557() public function testGetLastRawResponse() { // First, make sure we get null before the request - $this->assertEquals(null, $this->_client->getLastRawResponse(), - 'getLastRawResponse() is still expected to return null'); + $this->assertEquals( + null, + $this->_client->getLastRawResponse(), + 'getLastRawResponse() is still expected to return null' + ); // Now, test we get a proper response after the request $this->_client->setUri('http://example.com/foo/bar'); $this->_client->setAdapter('Zend\Http\Client\Adapter\Test'); $response = $this->_client->send(); - $this->assertSame($response, $this->_client->getResponse(), - 'Response is expected to be identical to the result of getResponse()'); + $this->assertSame( + $response, + $this->_client->getResponse(), + 'Response is expected to be identical to the result of getResponse()' + ); } /** @@ -311,8 +323,10 @@ public function testGetLastRawResponseWhenNotStoring() $response = $this->_client->send(); - $this->assertNull($this->_client->getLastRawResponse(), - 'getLastRawResponse is expected to be null when not storing'); + $this->assertNull( + $this->_client->getLastRawResponse(), + 'getLastRawResponse is expected to be null when not storing' + ); } /** @@ -322,12 +336,13 @@ public function testGetLastRawResponseWhenNotStoring() */ public function testInvalidPostContentType() { - if (!getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) { + if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) { $this->markTestSkipped('Zend\Http\Client online tests are not enabled'); } $this->setExpectedException( 'Zend\Http\Exception\RuntimeException', - 'Cannot handle content type \'x-foo/something-fake\' automatically'); + 'Cannot handle content type \'x-foo/something-fake\' automatically' + ); $this->_client->setEncType('x-foo/something-fake'); $this->_client->setParameterPost(['parameter' => 'value']); @@ -342,12 +357,13 @@ public function testInvalidPostContentType() */ public function testSocketErrorException() { - if (!getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) { + if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) { $this->markTestSkipped('Zend\Http\Client online tests are not enabled'); } $this->setExpectedException( 'Zend\Http\Client\Adapter\Exception\RuntimeException', - 'Unable to connect to 255.255.255.255:80'); + 'Unable to connect to 255.255.255.255:80' + ); // Try to connect to an invalid host $this->_client->setUri('http://255.255.255.255'); @@ -369,7 +385,8 @@ public function testSettingInvalidMethodThrowsException($method) { $this->setExpectedException( 'Zend\Http\Exception\InvalidArgumentException', - 'Invalid HTTP method passed'); + 'Invalid HTTP method passed' + ); $this->_client->setMethod($method); } @@ -381,7 +398,7 @@ public function testSettingInvalidMethodThrowsException($method) */ public function testFormDataEncodingWithMultiArrayZF7038() { - if (!getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) { + if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) { $this->markTestSkipped('Zend\Http\Client online tests are not enabled'); } $this->_client->setAdapter('Zend\Http\Client\Adapter\Test'); @@ -427,7 +444,7 @@ public function testFormDataEncodingWithMultiArrayZF7038() */ public function testMultibyteRawPostDataZF2098() { - if (!getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) { + if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) { $this->markTestSkipped('Zend\Http\Client online tests are not enabled'); } $this->_client->setAdapter('Zend\Http\Client\Adapter\Test'); @@ -455,7 +472,7 @@ public function testMultibyteRawPostDataZF2098() */ public function testOpenTempStreamWithValidFileDoesntThrowsException() { - if (!getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) { + if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) { $this->markTestSkipped('Zend\Http\Client online tests are not enabled'); } $url = 'http://www.example.com/'; @@ -478,12 +495,13 @@ public function testOpenTempStreamWithValidFileDoesntThrowsException() */ public function testOpenTempStreamWithBogusFileClosesTheConnection() { - if (!getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) { + if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) { $this->markTestSkipped('Zend\Http\Client online tests are not enabled'); } $this->setExpectedException( 'Zend\Http\Exception\RuntimeException', - 'Could not open temp file /path/to/bogus/file.ext'); + 'Could not open temp file /path/to/bogus/file.ext' + ); $url = 'http://www.example.com'; $config = [ @@ -501,14 +519,17 @@ public function testOpenTempStreamWithBogusFileClosesTheConnection() */ public function testEncodedCookiesInRequestHeaders() { - if (!getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) { + if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) { $this->markTestSkipped('Zend\Http\Client online tests are not enabled'); } $this->_client->addCookie('foo', 'bar=baz'); $this->_client->send(); $cookieValue = 'Cookie: foo='.urlencode('bar=baz'); - $this->assertContains($cookieValue, $this->_client->getLastRawRequest(), - 'Request is expected to contain the entire cookie "keyname=encoded_value"'); + $this->assertContains( + $cookieValue, + $this->_client->getLastRawRequest(), + 'Request is expected to contain the entire cookie "keyname=encoded_value"' + ); } /** @@ -518,15 +539,18 @@ public function testEncodedCookiesInRequestHeaders() */ public function testRawCookiesInRequestHeaders() { - if (!getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) { + if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) { $this->markTestSkipped('Zend\Http\Client online tests are not enabled'); } $this->_client->setOptions(['encodecookies' => false]); $this->_client->addCookie('foo', 'bar=baz'); $this->_client->send(); $cookieValue = 'Cookie: foo=bar=baz'; - $this->assertContains($cookieValue, $this->_client->getLastRawRequest(), - 'Request is expected to contain the entire cookie "keyname=raw_value"'); + $this->assertContains( + $cookieValue, + $this->_client->getLastRawRequest(), + 'Request is expected to contain the entire cookie "keyname=raw_value"' + ); } /** diff --git a/test/Client/TestAdapterTest.php b/test/Client/TestAdapterTest.php index 15d489a5e8..215de3a764 100644 --- a/test/Client/TestAdapterTest.php +++ b/test/Client/TestAdapterTest.php @@ -50,7 +50,8 @@ public function testSetConfigThrowsOnInvalidConfig() { $this->setExpectedException( 'Zend\Http\Client\Adapter\Exception\InvalidArgumentException', - 'Array or Traversable object expected'); + 'Array or Traversable object expected' + ); $this->adapter->setOptions('foo'); } diff --git a/test/Client/UseCaseTest.php b/test/Client/UseCaseTest.php index 5f1c4aeee7..3d4529cba7 100644 --- a/test/Client/UseCaseTest.php +++ b/test/Client/UseCaseTest.php @@ -80,7 +80,7 @@ protected function tearDown() public function testHttpGet() { $this->client->setMethod(Request::METHOD_GET); - $response= $this->client->send(); + $response = $this->client->send(); $this->assertTrue($response->isSuccess()); } @@ -92,11 +92,11 @@ public function testStaticHttpGet() public function testRequestHttpGet() { - $client= new HTTPClient(); - $request= new Request(); + $client = new HTTPClient(); + $request = new Request(); $request->setUri($this->baseuri); $request->setMethod(Request::METHOD_GET); - $response= $client->send($request); + $response = $client->send($request); $this->assertTrue($response->isSuccess()); } } diff --git a/test/Client/_files/testRedirections.php b/test/Client/_files/testRedirections.php index 0cb9c30583..3ed9b8dc51 100644 --- a/test/Client/_files/testRedirections.php +++ b/test/Client/_files/testRedirections.php @@ -13,23 +13,23 @@ /** * Create session cookie, but only on first redirect */ - setcookie('zf2testSessionCookie','positive'); + setcookie('zf2testSessionCookie', 'positive'); /** * Create a long living cookie */ - setcookie('zf2testLongLivedCookie','positive',time()+2678400); + setcookie('zf2testLongLivedCookie', 'positive', time() + 2678400); /** * Create a cookie that should be invalid on arrival */ - setcookie('zf2testExpiredCookie','negative',time()-2400); + setcookie('zf2testExpiredCookie', 'negative', time() - 2400); } $_GET['redirection']++; $https = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off'; -if (!isset($_GET['redirection']) || $_GET['redirection'] < 4) { +if (! isset($_GET['redirection']) || $_GET['redirection'] < 4) { $target = 'http' . ($https ? 's://' : '://') . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; header('Location: ' . $target . '?redirection=' . $_GET['redirection']); } else { diff --git a/test/Client/_files/testRelativeRedirections.php b/test/Client/_files/testRelativeRedirections.php index 7a2863e8a0..b7f414528f 100644 --- a/test/Client/_files/testRelativeRedirections.php +++ b/test/Client/_files/testRelativeRedirections.php @@ -7,7 +7,9 @@ * @license http://framework.zend.com/license/new-bsd New BSD License */ -if (! isset($_GET['redirect'])) $_GET['redirect'] = null; +if (! isset($_GET['redirect'])) { + $_GET['redirect'] = null; +} switch ($_GET['redirect']) { case 'abpath': diff --git a/test/ClientTest.php b/test/ClientTest.php index 42b8eaba80..ffd8892736 100644 --- a/test/ClientTest.php +++ b/test/ClientTest.php @@ -350,13 +350,13 @@ public function testAdapterAlwaysReachableIfSpecified() public function testPrepareHeadersCreateRightHttpField() { - $body = json_encode(['foofoo'=>'barbar']); + $body = json_encode(['foofoo' => 'barbar']); $client = new Client(); $prepareHeadersReflection = new \ReflectionMethod($client, 'prepareHeaders'); $prepareHeadersReflection->setAccessible(true); - $request= new Request(); + $request = new Request(); $request->getHeaders()->addHeaderLine('content-type', 'application/json'); $request->getHeaders()->addHeaderLine('content-length', strlen($body)); $client->setRequest($request); @@ -376,7 +376,7 @@ public function testPrepareHeadersCreateRightHttpField() public function testPrepareHeadersCurlDigestAuthentication() { - $body = json_encode(['foofoo'=>'barbar']); + $body = json_encode(['foofoo' => 'barbar']); $client = new Client(); $prepareHeadersReflection = new \ReflectionMethod($client, 'prepareHeaders'); diff --git a/test/Header/AcceptTest.php b/test/Header/AcceptTest.php index 88e7299bd1..0d34562d2e 100644 --- a/test/Header/AcceptTest.php +++ b/test/Header/AcceptTest.php @@ -144,7 +144,7 @@ public function testPrios() foreach ($values as $prio => $shouldPass) { try { $header->addMediaType('text/html', $prio); - if (!$shouldPass) { + if (! $shouldPass) { $this->fail('Exception expected'); } } catch (\Zend\Http\Header\Exception\InvalidArgumentException $e) { diff --git a/test/Header/SetCookieTest.php b/test/Header/SetCookieTest.php index 7db05eee67..f165a07f44 100644 --- a/test/Header/SetCookieTest.php +++ b/test/Header/SetCookieTest.php @@ -188,8 +188,8 @@ public function testSetCookieCanAppendOtherHeadersInWhenCreatingString() $target = 'Set-Cookie: myname=myvalue; Expires=Wed, 13-Jan-2021 22:23:01 GMT;' . ' Domain=docs.foo.com; Path=/accounts;' . ' Secure; HttpOnly'; - $target.= "\n"; - $target.= 'Set-Cookie: othername=othervalue'; + $target .= "\n"; + $target .= 'Set-Cookie: othername=othervalue'; $this->assertEquals($target, $headerLine); } @@ -397,18 +397,18 @@ public function testRfcCompatibility() public function testSetJsonValue() { - $cookieName ="fooCookie"; - $jsonData = json_encode(['foo'=>'bar']); + $cookieName = "fooCookie"; + $jsonData = json_encode(['foo' => 'bar']); - $cookie= new SetCookie($cookieName, $jsonData); + $cookie = new SetCookie($cookieName, $jsonData); $regExp = sprintf('#^%s=%s#', $cookieName, urlencode($jsonData)); $this->assertRegExp($regExp, $cookie->getFieldValue()); - $cookieName ="fooCookie"; - $jsonData = json_encode(['foo'=>'bar']); + $cookieName = "fooCookie"; + $jsonData = json_encode(['foo' => 'bar']); - $cookie= new SetCookie($cookieName, $jsonData); + $cookie = new SetCookie($cookieName, $jsonData); $cookie->setDomain('example.org'); $regExp = sprintf('#^%s=%s; Domain=#', $cookieName, urlencode($jsonData)); @@ -483,7 +483,7 @@ public static function validCookieWithInfoProvider() 'path' => '/', 'expires' => null, 'secure' => false, - 'httponly'=> false + 'httponly' => false ], 'justacookie=foo; Domain=example.com' ], @@ -496,7 +496,7 @@ public static function validCookieWithInfoProvider() 'path' => '/Space Out/', 'expires' => strtotime('Tue, 21-Nov-2006 08:33:44 GMT'), 'secure' => true, - 'httponly'=> false + 'httponly' => false ], 'expires=tomorrow; Expires=Tue, 21-Nov-2006 08:33:44 GMT; Domain=.example.com; Path=/Space Out/; Secure' ], @@ -509,7 +509,7 @@ public static function validCookieWithInfoProvider() 'path' => '/some%20value/', 'expires' => $now, 'secure' => false, - 'httponly'=> false + 'httponly' => false ], 'domain=unittests; Expires=' . gmdate('D, d-M-Y H:i:s', $now) . ' GMT; Domain=example.com; Path=/some%20value/' ], @@ -522,7 +522,7 @@ public static function validCookieWithInfoProvider() 'path' => '/', 'expires' => $yesterday, 'secure' => false, - 'httponly'=> false + 'httponly' => false ], 'path=indexAction; Expires=' . gmdate('D, d-M-Y H:i:s', $yesterday) . ' GMT; Domain=.foo.com; Path=/' ], @@ -536,7 +536,7 @@ public static function validCookieWithInfoProvider() 'path' => '/', 'expires' => null, 'secure' => true, - 'httponly'=> false + 'httponly' => false ], 'secure=sha1; Domain=some.really.deep.domain.com; Secure' ], @@ -549,7 +549,7 @@ public static function validCookieWithInfoProvider() 'path' => '/', 'expires' => null, 'secure' => false, - 'httponly'=> true + 'httponly' => true ], 'justacookie=foo; Domain=example.com; HttpOnly' ], @@ -562,7 +562,7 @@ public static function validCookieWithInfoProvider() 'path' => '/foo/baz', 'expires' => 'Tue, 21-Nov-2006 08:33:44 GMT', 'secure' => true, - 'httponly'=> false + 'httponly' => false ], 'PHPSESSID=123456789+abcd%2Cef; Expires=Tue, 21-Nov-2006 08:33:44 GMT; Domain=.localdomain; Path=/foo/baz; Secure' ], @@ -575,7 +575,7 @@ public static function validCookieWithInfoProvider() 'path' => '/accounts', 'expires' => 'Wed, 13-Jan-2021 22:23:01 GMT', 'secure' => true, - 'httponly'=> true + 'httponly' => true ], 'myname=myvalue; Expires=Wed, 13-Jan-2021 22:23:01 GMT; Domain=docs.foo.com; Path=/accounts; Secure; HttpOnly' ], diff --git a/test/PhpEnvironment/RequestTest.php b/test/PhpEnvironment/RequestTest.php index 2a75d984b6..dbcd57e854 100644 --- a/test/PhpEnvironment/RequestTest.php +++ b/test/PhpEnvironment/RequestTest.php @@ -168,7 +168,7 @@ public static function baseUrlAndPathProvider() 'REQUEST_URI' => '/~username/public/', 'PHP_SELF' => '/~username/public/index.php', 'SCRIPT_FILENAME' => '/Users/username/Sites/public/index.php', - 'ORIG_SCRIPT_NAME'=> null + 'ORIG_SCRIPT_NAME' => null ], '/~username/public', '/~username/public' @@ -180,7 +180,7 @@ public static function baseUrlAndPathProvider() 'REQUEST_URI' => '/zf2tut/', 'PHP_SELF' => '/zf2tut/index.php', 'SCRIPT_FILENAME' => 'c:/ZF2Tutorial/public/index.php', - 'ORIG_SCRIPT_NAME'=> null + 'ORIG_SCRIPT_NAME' => null ], '/zf2tut', '/zf2tut' diff --git a/test/Response/ResponseStreamTest.php b/test/Response/ResponseStreamTest.php index e7da08426a..0abf16771b 100644 --- a/test/Response/ResponseStreamTest.php +++ b/test/Response/ResponseStreamTest.php @@ -46,7 +46,7 @@ public function testGzipResponse() $stream = fopen(__DIR__ . '/../_files/response_gzip', 'rb'); $headers = ''; - while (false!== ($newLine = fgets($stream))) { + while (false !== ($newLine = fgets($stream))) { $headers .= $newLine; if ($headers == "\n" || $headers == "\r\n") { break; @@ -91,7 +91,7 @@ protected function readResponse($response) $stream = fopen(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . $response, 'rb'); $data = ''; - while (false!== ($newLine = fgets($stream))) { + while (false !== ($newLine = fgets($stream))) { $data .= $newLine; if ($newLine == "\n" || $newLine == "\r\n") { break; From 8bf2c19273aec1efea6bffdcb1ccb6f2fd97a7ee Mon Sep 17 00:00:00 2001 From: Koopzington Date: Sun, 20 Nov 2016 03:01:04 +0100 Subject: [PATCH 9/9] CS fixes --- phpcs.xml | 1 + src/Client.php | 66 ++++++++++++++++++++++----- src/Client/Adapter/Proxy.php | 8 +++- src/Client/Adapter/Socket.php | 15 ++++-- src/Cookies.php | 6 +++ src/Header/GenericMultiHeader.php | 4 +- test/Client/CommonHttpTests.php | 56 ++++++++++++++++++----- test/Client/CurlTest.php | 6 ++- test/Client/ProxyAdapterTest.php | 6 ++- test/Client/StaticTest.php | 46 ++++++++----------- test/Client/TestAsset/MockAdapter.php | 8 ++++ test/Client/TestAsset/MockClient.php | 22 +++++++++ test/ClientTest.php | 8 ++++ test/Header/AllowTest.php | 5 +- test/Header/CookieTest.php | 3 +- test/Header/SetCookieTest.php | 20 ++++++++ test/Response/ResponseStreamTest.php | 3 +- test/ResponseTest.php | 48 +++++++++++++++---- 18 files changed, 262 insertions(+), 69 deletions(-) create mode 100644 test/Client/TestAsset/MockAdapter.php create mode 100644 test/Client/TestAsset/MockClient.php diff --git a/phpcs.xml b/phpcs.xml index 561c28e4a5..0289e02100 100644 --- a/phpcs.xml +++ b/phpcs.xml @@ -5,4 +5,5 @@ src test + */_files/* \ No newline at end of file diff --git a/src/Client.php b/src/Client.php index f814776880..9ef9e9db85 100644 --- a/src/Client.php +++ b/src/Client.php @@ -182,7 +182,9 @@ public function setAdapter($adapter) { if (is_string($adapter)) { if (! class_exists($adapter)) { - throw new Client\Exception\InvalidArgumentException('Unable to locate adapter class "' . $adapter . '"'); + throw new Client\Exception\InvalidArgumentException( + 'Unable to locate adapter class "' . $adapter . '"' + ); } $adapter = new $adapter; } @@ -546,8 +548,17 @@ protected function getCookieId($cookie) * @throws Exception\InvalidArgumentException * @return Client */ - public function addCookie($cookie, $value = null, $expire = null, $path = null, $domain = null, $secure = false, $httponly = true, $maxAge = null, $version = null) - { + public function addCookie( + $cookie, + $value = null, + $expire = null, + $path = null, + $domain = null, + $secure = false, + $httponly = true, + $maxAge = null, + $version = null + ) { if (is_array($cookie) || $cookie instanceof ArrayIterator) { foreach ($cookie as $setCookie) { if ($setCookie instanceof Header\SetCookie) { @@ -557,7 +568,17 @@ public function addCookie($cookie, $value = null, $expire = null, $path = null, } } } elseif (is_string($cookie) && $value !== null) { - $setCookie = new Header\SetCookie($cookie, $value, $expire, $path, $domain, $secure, $httponly, $maxAge, $version); + $setCookie = new Header\SetCookie( + $cookie, + $value, + $expire, + $path, + $domain, + $secure, + $httponly, + $maxAge, + $version + ); $this->cookies[$this->getCookieId($setCookie)] = $setCookie; } elseif ($cookie instanceof Header\SetCookie) { $this->cookies[$this->getCookieId($cookie)] = $cookie; @@ -766,7 +787,9 @@ protected function calcAuthDigest($user, $password, $type = self::AUTH_BASIC, $d case self::AUTH_BASIC: // In basic authentication, the user name cannot contain ":" if (strpos($user, ':') !== false) { - throw new Exception\InvalidArgumentException("The user name cannot contain ':' in Basic HTTP authentication"); + throw new Exception\InvalidArgumentException( + "The user name cannot contain ':' in Basic HTTP authentication" + ); } $response = base64_encode($user . ':' . $password); break; @@ -776,7 +799,9 @@ protected function calcAuthDigest($user, $password, $type = self::AUTH_BASIC, $d } foreach ($digest as $key => $value) { if (! defined('self::DIGEST_' . strtoupper($key))) { - throw new Exception\InvalidArgumentException("Invalid or not supported digest authentication parameter: '$key'"); + throw new Exception\InvalidArgumentException( + "Invalid or not supported digest authentication parameter: '$key'" + ); } } $ha1 = md5($user . ':' . $digest['realm'] . ':' . $password); @@ -784,7 +809,9 @@ protected function calcAuthDigest($user, $password, $type = self::AUTH_BASIC, $d $ha2 = md5($this->getMethod() . ':' . $this->getUri()->getPath()); } elseif (strtolower($digest['qop']) == 'auth-int') { if (empty($entityBody)) { - throw new Exception\InvalidArgumentException("I cannot use the auth-int digest authentication without the entity body"); + throw new Exception\InvalidArgumentException( + "I cannot use the auth-int digest authentication without the entity body" + ); } $ha2 = md5($this->getMethod() . ':' . $this->getUri()->getPath() . ':' . md5($entityBody)); } @@ -1144,7 +1171,10 @@ protected function prepareHeaders($body, $uri) break; case self::AUTH_DIGEST: if (! $this->adapter instanceof Client\Adapter\Curl) { - throw new Exception\RuntimeException("The digest authentication is only available for curl adapters (Zend\\Http\\Client\\Adapter\\Curl)"); + throw new Exception\RuntimeException( + "The digest authentication is only available for curl adapters " + . "(Zend\\Http\\Client\\Adapter\\Curl)" + ); } $this->adapter->setCurlOption(CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); @@ -1223,14 +1253,22 @@ protected function prepareBody() // Encode files foreach ($this->getRequest()->getFiles()->toArray() as $file) { $fhead = ['Content-Type' => $file['ctype']]; - $body .= $this->encodeFormData($boundary, $file['formname'], $file['data'], $file['filename'], $fhead); + $body .= $this->encodeFormData( + $boundary, + $file['formname'], + $file['data'], + $file['filename'], + $fhead + ); } $body .= "--{$boundary}--\r\n"; } elseif (stripos($this->getEncType(), self::ENC_URLENCODED) === 0) { // Encode body as application/x-www-form-urlencoded $body = http_build_query($this->getRequest()->getPost()->toArray()); } else { - throw new Client\Exception\RuntimeException("Cannot handle content type '{$this->encType}' automatically"); + throw new Client\Exception\RuntimeException( + "Cannot handle content type '{$this->encType}' automatically" + ); } } @@ -1406,7 +1444,9 @@ public static function encodeAuthHeader($user, $password, $type = self::AUTH_BAS case self::AUTH_BASIC: // In basic authentication, the user name cannot contain ":" if (strpos($user, ':') !== false) { - throw new Client\Exception\InvalidArgumentException("The user name cannot contain ':' in 'Basic' HTTP authentication"); + throw new Client\Exception\InvalidArgumentException( + "The user name cannot contain ':' in 'Basic' HTTP authentication" + ); } return 'Basic ' . base64_encode($user . ':' . $password); @@ -1418,7 +1458,9 @@ public static function encodeAuthHeader($user, $password, $type = self::AUTH_BAS // break; default: - throw new Client\Exception\InvalidArgumentException("Not a supported HTTP authentication type: '$type'"); + throw new Client\Exception\InvalidArgumentException( + "Not a supported HTTP authentication type: '$type'" + ); } return; diff --git a/src/Client/Adapter/Proxy.php b/src/Client/Adapter/Proxy.php index 44e6742cc7..78136ee045 100644 --- a/src/Client/Adapter/Proxy.php +++ b/src/Client/Adapter/Proxy.php @@ -130,7 +130,9 @@ public function write($method, $uri, $httpVer = '1.1', $headers = [], $body = '' $port = $this->config['proxy_port']; if ($this->connectedTo[0] != "tcp://$host" || $this->connectedTo[1] != $port) { - throw new AdapterException\RuntimeException("Trying to write but we are connected to the wrong proxy server"); + throw new AdapterException\RuntimeException( + "Trying to write but we are connected to the wrong proxy server" + ); } // Add Proxy-Authorization header @@ -247,7 +249,9 @@ protected function connectHandshake($host, $port = 443, $httpVer = '1.1', array // Check that the response from the proxy is 200 if (Response::fromString($response)->getStatusCode() != 200) { - throw new AdapterException\RuntimeException("Unable to connect to HTTPS proxy. Server response: " . $response); + throw new AdapterException\RuntimeException( + "Unable to connect to HTTPS proxy. Server response: " . $response + ); } // If all is good, switch socket to secure mode. We have to fall back diff --git a/src/Client/Adapter/Socket.php b/src/Client/Adapter/Socket.php index 9795a5dd2e..d6cda8dbce 100644 --- a/src/Client/Adapter/Socket.php +++ b/src/Client/Adapter/Socket.php @@ -217,7 +217,12 @@ public function connect($host, $port = 80, $secure = false) } if ($this->config['sslallowselfsigned'] !== null) { - if (! stream_context_set_option($context, 'ssl', 'allow_self_signed', $this->config['sslallowselfsigned'])) { + if (! stream_context_set_option( + $context, + 'ssl', + 'allow_self_signed', + $this->config['sslallowselfsigned'] + )) { throw new AdapterException\RuntimeException('Unable to set sslallowselfsigned option'); } } @@ -293,11 +298,13 @@ public function connect($host, $port = 80, $secure = false) if ((! $errorString) && $this->config['sslverifypeer']) { // There's good chance our error is due to sslcapath not being properly set if (! ($this->config['sslcafile'] || $this->config['sslcapath'])) { - $errorString = 'make sure the "sslcafile" or "sslcapath" option are properly set for the environment.'; + $errorString = 'make sure the "sslcafile" or "sslcapath" option are properly set for the ' + . 'environment.'; } elseif ($this->config['sslcafile'] && ! is_file($this->config['sslcafile'])) { $errorString = 'make sure the "sslcafile" option points to a valid SSL certificate file'; } elseif ($this->config['sslcapath'] && ! is_dir($this->config['sslcapath'])) { - $errorString = 'make sure the "sslcapath" option points to a valid SSL certificate directory'; + $errorString = 'make sure the "sslcapath" option points to a valid SSL certificate ' + . 'directory'; } } @@ -590,8 +597,10 @@ public function close() * * @throws AdapterException\TimeoutException with READ_TIMEOUT code */ + // @codingStandardsIgnoreStart protected function _checkSocketReadTimeout() { + // @codingStandardsIgnoreEnd if ($this->socket) { $info = stream_get_meta_data($this->socket); $timedout = $info['timed_out']; diff --git a/src/Cookies.php b/src/Cookies.php index 93062ab0b5..d146e89254 100644 --- a/src/Cookies.php +++ b/src/Cookies.php @@ -252,8 +252,10 @@ public function getCookie($uri, $cookieName, $retAs = self::COOKIE_OBJECT) * @param int $retAs What value to return * @return array|string */ + // @codingStandardsIgnoreStart protected function _flattenCookiesArray($ptr, $retAs = self::COOKIE_OBJECT) { + // @codingStandardsIgnoreEnd if (is_array($ptr)) { $ret = ($retAs == self::COOKIE_STRING_CONCAT ? '' : []); foreach ($ptr as $item) { @@ -287,8 +289,10 @@ protected function _flattenCookiesArray($ptr, $retAs = self::COOKIE_OBJECT) * @param string $domain * @return array */ + // @codingStandardsIgnoreStart protected function _matchDomain($domain) { + // @codingStandardsIgnoreEnd $ret = []; foreach (array_keys($this->cookies) as $cdom) { @@ -307,8 +311,10 @@ protected function _matchDomain($domain) * @param string $path * @return array */ + // @codingStandardsIgnoreStart protected function _matchPath($domains, $path) { + // @codingStandardsIgnoreEnd $ret = []; foreach ($domains as $dom => $pathsArray) { diff --git a/src/Header/GenericMultiHeader.php b/src/Header/GenericMultiHeader.php index 8f9490f1dd..63b62d2bfd 100644 --- a/src/Header/GenericMultiHeader.php +++ b/src/Header/GenericMultiHeader.php @@ -33,7 +33,9 @@ public function toStringMultipleHeaders(array $headers) $values = [$this->getFieldValue()]; foreach ($headers as $header) { if (! $header instanceof static) { - throw new Exception\InvalidArgumentException('This method toStringMultipleHeaders was expecting an array of headers of the same type'); + throw new Exception\InvalidArgumentException( + 'This method toStringMultipleHeaders was expecting an array of headers of the same type' + ); } $values[] = $header->getFieldValue(); } diff --git a/test/Client/CommonHttpTests.php b/test/Client/CommonHttpTests.php index a6bbcc27ad..6cf8bf53d8 100644 --- a/test/Client/CommonHttpTests.php +++ b/test/Client/CommonHttpTests.php @@ -50,12 +50,14 @@ abstract class CommonHttpTests extends \PHPUnit_Framework_TestCase */ protected $client = null; + // @codingStandardsIgnoreStart /** * Common HTTP client adapter * * @var \Zend\Http\Client\Adapter\AdapterInterface */ protected $_adapter = null; + // @codingStandardsIgnoreEnd /** * Configuration array @@ -151,7 +153,11 @@ public function testGetLastRawRequest() $this->markTestSkipped("Server does not allow the TRACE method"); } - $this->assertEquals($this->client->getLastRawRequest(), $res->getBody(), 'Response body should be exactly like the last request'); + $this->assertEquals( + $this->client->getLastRawRequest(), + $res->getBody(), + 'Response body should be exactly like the last request' + ); } /** @@ -566,7 +572,8 @@ public function testMaxRedirectsExceeded() $res = $this->client->send(); $this->assertTrue( $res->isRedirect(), - "Last response was not a redirection as expected. Response code: {$res->getStatusCode()}. Redirections counter: {$this->client->getRedirectionsCount()} (when strict redirects are on)" + "Last response was not a redirection as expected. Response code: {$res->getStatusCode()}. " + . "Redirections counter: {$this->client->getRedirectionsCount()} (when strict redirects are on)" ); // Then try with normal redirections @@ -576,7 +583,8 @@ public function testMaxRedirectsExceeded() $res = $this->client->send(); $this->assertTrue( $res->isRedirect(), - "Last response was not a redirection as expected. Response code: {$res->getStatusCode()}. Redirections counter: {$this->client->getRedirectionsCount()} (when strict redirects are off)" + "Last response was not a redirection as expected. Response code: {$res->getStatusCode()}. " + . "Redirections counter: {$this->client->getRedirectionsCount()} (when strict redirects are off)" ); } @@ -706,7 +714,11 @@ public function testCookiesStringNoJar() $res = $this->client->send(); - $this->assertEquals($res->getBody(), serialize($cookies), 'Response body does not contain the expected cookies'); + $this->assertEquals( + $res->getBody(), + serialize($cookies), + 'Response body does not contain the expected cookies' + ); } @@ -728,7 +740,11 @@ public function testSetCookieObjectArray() $this->client->setCookies($cookies); $res = $this->client->send(); - $this->assertEquals($res->getBody(), serialize($cookies), 'Response body does not contain the expected cookies'); + $this->assertEquals( + $res->getBody(), + serialize($cookies), + 'Response body does not contain the expected cookies' + ); } /** @@ -748,7 +764,11 @@ public function testSetCookieStringArray() $this->client->setCookies($cookies); $res = $this->client->send(); - $this->assertEquals($res->getBody(), serialize($cookies), 'Response body does not contain the expected cookies'); + $this->assertEquals( + $res->getBody(), + serialize($cookies), + 'Response body does not contain the expected cookies' + ); } /** @@ -817,7 +837,9 @@ public function testUploadLocalDetectMime() } if (! $detect) { - $this->markTestSkipped('No MIME type detection capability (fileinfo or mime_magic extensions) is available'); + $this->markTestSkipped( + 'No MIME type detection capability (fileinfo or mime_magic extensions) is available' + ); } $file = dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'staticFile.jpg'; @@ -829,7 +851,11 @@ public function testUploadLocalDetectMime() $size = filesize($file); $body = "uploadfile " . basename($file) . " image/jpeg $size\n"; - $this->assertEquals($body, $res->getBody(), 'Response body does not include expected upload parameters (detect: ' . $detect . ')'); + $this->assertEquals( + $body, + $res->getBody(), + 'Response body does not include expected upload parameters (detect: ' . $detect . ')' + ); } public function testUploadNameWithSpecialChars() @@ -886,7 +912,11 @@ public function testMutipleFilesWithSameFormNameZF5744() $res = $this->client->send(); - $this->assertEquals($expectedBody, $res->getBody(), 'Response body does not include expected upload parameters'); + $this->assertEquals( + $expectedBody, + $res->getBody(), + 'Response body does not include expected upload parameters' + ); } /** @@ -983,7 +1013,8 @@ public function testStreamRequest() $this->markTestSkipped('Current adapter does not support streaming'); return; } - $data = fopen(dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'staticFile.jpg', "r"); + $data = fopen(dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR + . 'staticFile.jpg', "r"); $this->client->setRawBody($data); $this->client->setEncType('image/jpeg'); $this->client->setMethod('PUT'); @@ -1000,7 +1031,8 @@ public function testStreamRequest() public function testZF9404DoubleContentLengthHeader() { $this->client->setUri($this->baseuri . 'ZF9404-doubleContentLength.php'); - $expect = filesize(dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'ZF9404-doubleContentLength.php'); + $expect = filesize(dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR + . 'ZF9404-doubleContentLength.php'); $response = $this->client->send(); if (! $response->isSuccess()) { @@ -1062,8 +1094,10 @@ public function testUsesProvidedArgSeparator() * @param string $file * @return string */ + // @codingStandardsIgnoreStart protected function _getTestFileContents($file) { + // @codingStandardsIgnoreEnd return file_get_contents(dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . $file); } diff --git a/test/Client/CurlTest.php b/test/Client/CurlTest.php index 878d5b62be..06486423de 100644 --- a/test/Client/CurlTest.php +++ b/test/Client/CurlTest.php @@ -365,7 +365,11 @@ public function testAuthorizeHeader() $res = $this->client->send(); $curlInfo = curl_getinfo($adapter->getHandle()); - $this->assertArrayHasKey('request_header', $curlInfo, 'Expecting request_header in curl_getinfo() return value'); + $this->assertArrayHasKey( + 'request_header', + $curlInfo, + 'Expecting request_header in curl_getinfo() return value' + ); $this->assertContains($header, $curlInfo['request_header'], 'Expecting valid basic authorization header'); } diff --git a/test/Client/ProxyAdapterTest.php b/test/Client/ProxyAdapterTest.php index 142de62e9a..e2bc120861 100644 --- a/test/Client/ProxyAdapterTest.php +++ b/test/Client/ProxyAdapterTest.php @@ -97,7 +97,11 @@ public function testFallbackToSocket() $this->markTestSkipped('Server does not allow the TRACE method'); } - $this->assertEquals($this->client->getLastRawRequest(), $res->getBody(), 'Response body should be exactly like the last request'); + $this->assertEquals( + $this->client->getLastRawRequest(), + $res->getBody(), + 'Response body should be exactly like the last request' + ); } public function testGetLastRequest() diff --git a/test/Client/StaticTest.php b/test/Client/StaticTest.php index 01440e82e7..9594050d4d 100644 --- a/test/Client/StaticTest.php +++ b/test/Client/StaticTest.php @@ -11,8 +11,8 @@ use Zend\Uri\Http as UriHttp; use Zend\Http\Client as HTTPClient; -use Zend\Http; -use Zend\Http\Request; +use ZendTest\Http\Client\TestAsset\MockAdapter; +use ZendTest\Http\Client\TestAsset\MockClient; /** * This Testsuite includes all Zend_Http_Client tests that do not rely @@ -25,12 +25,14 @@ */ class StaticTest extends \PHPUnit_Framework_TestCase { + // @codingStandardsIgnoreStart /** * Common HTTP client * * @var \Zend\Http\Client */ protected $_client = null; + // @codingStandardsIgnoreEnd /** * Set up the test suite before each test @@ -69,7 +71,11 @@ public function testSetGetUriString() $this->assertEquals($uri->__toString(), $uristr, 'Returned Uri object does not hold the expected URI'); $uri = $this->_client->getUri()->toString(); - $this->assertInternalType('string', $uri, 'Returned value expected to be a string, ' . gettype($uri) . ' returned'); + $this->assertInternalType( + 'string', + $uri, + 'Returned value expected to be a string, ' . gettype($uri) . ' returned' + ); $this->assertEquals($uri, $uristr, 'Returned string is not the expected URI'); } @@ -124,8 +130,16 @@ public function testGetHeader() 'Accept-language' => 'en,de,*', ]); - $this->assertEquals($this->_client->getHeader('Accept-encoding'), 'gzip, deflate', 'Returned value of header is not as expected'); - $this->assertEquals($this->_client->getHeader('X-Fake-Header'), null, 'Non-existing header should not return a value'); + $this->assertEquals( + $this->_client->getHeader('Accept-encoding'), + 'gzip, deflate', + 'Returned value of header is not as expected' + ); + $this->assertEquals( + $this->_client->getHeader('X-Fake-Header'), + null, + 'Non-existing header should not return a value' + ); } /** @@ -605,25 +619,3 @@ public static function invalidConfigProvider() ]; } } - -class MockClient extends HTTPClient -{ - public $config = [ - 'maxredirects' => 5, - 'strictredirects' => false, - 'useragent' => 'Zend_Http_Client', - 'timeout' => 10, - 'adapter' => 'Zend\\Http\\Client\\Adapter\\Socket', - 'httpversion' => Request::VERSION_11, - 'keepalive' => false, - 'storeresponse' => true, - 'strict' => true, - 'outputstream' => false, - 'encodecookies' => true, - ]; -} - -class MockAdapter extends \Zend\Http\Client\Adapter\Test -{ - public $config = []; -} diff --git a/test/Client/TestAsset/MockAdapter.php b/test/Client/TestAsset/MockAdapter.php new file mode 100644 index 0000000000..e8547b0777 --- /dev/null +++ b/test/Client/TestAsset/MockAdapter.php @@ -0,0 +1,8 @@ + 5, + 'strictredirects' => false, + 'useragent' => 'Zend_Http_Client', + 'timeout' => 10, + 'adapter' => 'Zend\\Http\\Client\\Adapter\\Socket', + 'httpversion' => Request::VERSION_11, + 'keepalive' => false, + 'storeresponse' => true, + 'strict' => true, + 'outputstream' => false, + 'encodecookies' => true, + ]; +} diff --git a/test/ClientTest.php b/test/ClientTest.php index ffd8892736..477b17a8a8 100644 --- a/test/ClientTest.php +++ b/test/ClientTest.php @@ -28,7 +28,9 @@ public function testIfCookiesAreSticky() new SetCookie('bar', 'biz', null, '/', 'www.domain.com') ]; + // @codingStandardsIgnoreStart $requestString = "GET http://www.domain.com/index.php HTTP/1.1\r\nHost: domain.com\r\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:16.0) Gecko/20100101 Firefox/16.0\r\nAccept: */*\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\n"; + // @codingStandardsIgnoreEnd $request = Request::fromString($requestString); $client = new Client('http://www.domain.com/'); @@ -36,7 +38,9 @@ public function testIfCookiesAreSticky() $client->addCookie($initialCookies); $cookies = new Cookies($client->getRequest()->getHeaders()); + // @codingStandardsIgnoreStart $rawHeaders = "HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-Encoding: gzip\r\nContent-Type: application/javascript\r\nDate: Sun, 18 Nov 2012 16:16:08 GMT\r\nServer: nginx/1.1.19\r\nSet-Cookie: baz=bah; domain=www.domain.com; path=/\r\nSet-Cookie: joe=test; domain=www.domain.com; path=/\r\nVary: Accept-Encoding\r\nX-Powered-By: PHP/5.3.10-1ubuntu3.4\r\nConnection: keep-alive\r\n"; + // @codingStandardsIgnoreEnd $response = Response::fromString($rawHeaders); $client->setResponse($response); @@ -59,7 +63,9 @@ public function testAcceptEncodingHeaderWorksProperly() $method = new \ReflectionMethod('\Zend\Http\Client', 'prepareHeaders'); $method->setAccessible(true); + // @codingStandardsIgnoreStart $requestString = "GET http://www.domain.com/index.php HTTP/1.1\r\nHost: domain.com\r\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:16.0) Gecko/20100101 Firefox/16.0\r\nAccept: */*\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\n"; + // @codingStandardsIgnoreEnd $request = Request::fromString($requestString); $adapter = new \Zend\Http\Client\Adapter\Test(); @@ -68,7 +74,9 @@ public function testAcceptEncodingHeaderWorksProperly() $client->setAdapter($adapter); $client->setRequest($request); + // @codingStandardsIgnoreStart $rawHeaders = "HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-Encoding: gzip, deflate\r\nContent-Type: application/javascript\r\nDate: Sun, 18 Nov 2012 16:16:08 GMT\r\nServer: nginx/1.1.19\r\nVary: Accept-Encoding\r\nX-Powered-By: PHP/5.3.10-1ubuntu3.4\r\nConnection: keep-alive\r\n"; + // @codingStandardsIgnoreEnd $response = Response::fromString($rawHeaders); $client->getAdapter()->setResponse($response); diff --git a/test/Header/AllowTest.php b/test/Header/AllowTest.php index 0ef90d6739..ecc2bae066 100644 --- a/test/Header/AllowTest.php +++ b/test/Header/AllowTest.php @@ -89,7 +89,10 @@ public function testAllowChecksAllowedMethod() */ public function testPreventsCRLFAttackViaFromString() { - $this->setExpectedException('Zend\Http\Header\Exception\InvalidArgumentException', 'Invalid header value detected'); + $this->setExpectedException( + 'Zend\Http\Header\Exception\InvalidArgumentException', + 'Invalid header value detected' + ); $header = Allow::fromString("Allow: GET\r\n\r\nevilContent"); } diff --git a/test/Header/CookieTest.php b/test/Header/CookieTest.php index 3931c8d0c2..fca76e31b0 100644 --- a/test/Header/CookieTest.php +++ b/test/Header/CookieTest.php @@ -97,7 +97,7 @@ public function valuesProvider() 'CRLF characters' => ["foo=bar\r\n\r\nevilContent", '0=foo%3Dbar%0D%0A%0D%0AevilContent'], ]; } - +// @codingStandardsIgnoreStart // /** // * Cookie creation and data accessors tests // */ @@ -666,4 +666,5 @@ public function valuesProvider() // // array('cookie=foo;domain=example.com;expires=Fri, 06-Jun-1966 00:19:21 GMT', true), // ); // } +// @codingStandardsIgnoreEnd } diff --git a/test/Header/SetCookieTest.php b/test/Header/SetCookieTest.php index f165a07f44..039436ff64 100644 --- a/test/Header/SetCookieTest.php +++ b/test/Header/SetCookieTest.php @@ -328,7 +328,9 @@ public function testIsValidForRequestSubdomainMatch() */ public function test169() { + // @codingStandardsIgnoreStart $cookie = 'Set-Cookie: leo_auth_token=example; Version=1; Max-Age=1799; Expires=Mon, 20-Feb-2012 02:49:57 GMT; Path=/'; + // @codingStandardsIgnoreEnd $setCookieHeader = SetCookie::fromString($cookie); $this->assertEquals($cookie, $setCookieHeader->toString()); } @@ -338,7 +340,9 @@ public function test169() */ public function testDoesNotAcceptCookieNameFromArbitraryLocationInHeaderValue() { + // @codingStandardsIgnoreStart $cookie = 'Set-Cookie: Version=1; Max-Age=1799; Expires=Mon, 20-Feb-2012 02:49:57 GMT; Path=/; leo_auth_token=example'; + // @codingStandardsIgnoreEnd $setCookieHeader = SetCookie::fromString($cookie); $this->assertNotEquals('leo_auth_token', $setCookieHeader->getName()); } @@ -488,7 +492,9 @@ public static function validCookieWithInfoProvider() 'justacookie=foo; Domain=example.com' ], [ + // @codingStandardsIgnoreStart 'Set-Cookie: expires=tomorrow; secure; path=/Space Out/; expires=Tue, 21-Nov-2006 08:33:44 GMT; domain=.example.com', + // @codingStandardsIgnoreEnd [ 'name' => 'expires', 'value' => 'tomorrow', @@ -501,7 +507,9 @@ public static function validCookieWithInfoProvider() 'expires=tomorrow; Expires=Tue, 21-Nov-2006 08:33:44 GMT; Domain=.example.com; Path=/Space Out/; Secure' ], [ + // @codingStandardsIgnoreStart 'Set-Cookie: domain=unittests; expires=' . gmdate('D, d-M-Y H:i:s', $now) . ' GMT; domain=example.com; path=/some%20value/', + // @codingStandardsIgnoreEnd [ 'name' => 'domain', 'value' => 'unittests', @@ -511,10 +519,14 @@ public static function validCookieWithInfoProvider() 'secure' => false, 'httponly' => false ], + // @codingStandardsIgnoreStart 'domain=unittests; Expires=' . gmdate('D, d-M-Y H:i:s', $now) . ' GMT; Domain=example.com; Path=/some%20value/' + // @codingStandardsIgnoreEnd ], [ + // @codingStandardsIgnoreStart 'Set-Cookie: path=indexAction; path=/; domain=.foo.com; expires=' . gmdate('D, d-M-Y H:i:s', $yesterday) . ' GMT', + // @codingStandardsIgnoreEnd [ 'name' => 'path', 'value' => 'indexAction', @@ -554,7 +566,9 @@ public static function validCookieWithInfoProvider() 'justacookie=foo; Domain=example.com; HttpOnly' ], [ + // @codingStandardsIgnoreStart 'Set-Cookie: PHPSESSID=123456789+abcd%2Cef; secure; domain=.localdomain; path=/foo/baz; expires=Tue, 21-Nov-2006 08:33:44 GMT;', + // @codingStandardsIgnoreEnd [ 'name' => 'PHPSESSID', 'value' => '123456789+abcd%2Cef', @@ -564,10 +578,14 @@ public static function validCookieWithInfoProvider() 'secure' => true, 'httponly' => false ], + // @codingStandardsIgnoreStart 'PHPSESSID=123456789+abcd%2Cef; Expires=Tue, 21-Nov-2006 08:33:44 GMT; Domain=.localdomain; Path=/foo/baz; Secure' + // @codingStandardsIgnoreEnd ], [ + // @codingStandardsIgnoreStart 'Set-Cookie: myname=myvalue; Domain=docs.foo.com; Path=/accounts; Expires=Wed, 13-Jan-2021 22:23:01 GMT; Secure; HttpOnly', + // @codingStandardsIgnoreEnd [ 'name' => 'myname', 'value' => 'myvalue', @@ -577,7 +595,9 @@ public static function validCookieWithInfoProvider() 'secure' => true, 'httponly' => true ], + // @codingStandardsIgnoreStart 'myname=myvalue; Expires=Wed, 13-Jan-2021 22:23:01 GMT; Domain=docs.foo.com; Path=/accounts; Secure; HttpOnly' + // @codingStandardsIgnoreEnd ], [ 'Set-Cookie:', diff --git a/test/Response/ResponseStreamTest.php b/test/Response/ResponseStreamTest.php index 0abf16771b..8210f4386f 100644 --- a/test/Response/ResponseStreamTest.php +++ b/test/Response/ResponseStreamTest.php @@ -88,7 +88,8 @@ public function test300isRedirect() */ protected function readResponse($response) { - $stream = fopen(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . $response, 'rb'); + $stream = fopen(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR + . $response, 'rb'); $data = ''; while (false !== ($newLine = fgets($stream))) { diff --git a/test/ResponseTest.php b/test/ResponseTest.php index cb1b67f801..df198539b7 100644 --- a/test/ResponseTest.php +++ b/test/ResponseTest.php @@ -184,7 +184,11 @@ public function testLineBreaksCompatibility() $response_text_crlf = $this->readResponse('response_crlf'); $res_crlf = Response::fromString($response_text_crlf); - $this->assertEquals($res_lf->getHeaders()->toString(), $res_crlf->getHeaders()->toString(), 'Responses headers do not match'); + $this->assertEquals( + $res_lf->getHeaders()->toString(), + $res_crlf->getHeaders()->toString(), + 'Responses headers do not match' + ); $this->markTestIncomplete('Something is fishy with the response bodies in the test responses'); $this->assertEquals($res_lf->getBody(), $res_crlf->getBody(), 'Response bodies do not match'); @@ -276,7 +280,11 @@ public function testAutoMessageSet() $response = Response::fromString($this->readResponse('response_403_nomessage')); $this->assertEquals(403, $response->getStatusCode(), 'Response status is expected to be 403, but it isn\'t'); - $this->assertEquals('Forbidden', $response->getReasonPhrase(), 'Response is 403, but message is not "Forbidden" as expected'); + $this->assertEquals( + 'Forbidden', + $response->getReasonPhrase(), + 'Response is 403, but message is not "Forbidden" as expected' + ); // While we're here, make sure it's classified as error... $this->assertTrue($response->isClientError(), 'Response is an error, but isClientError() returned false'); @@ -294,8 +302,16 @@ public function testToString() $response_str = $this->readResponse('response_404'); $response = Response::fromString($response_str); - $this->assertEquals(strtolower(str_replace("\n", "\r\n", $response_str)), strtolower($response->toString()), 'Response convertion to string does not match original string'); - $this->assertEquals(strtolower(str_replace("\n", "\r\n", $response_str)), strtolower((string)$response), 'Response convertion to string does not match original string'); + $this->assertEquals( + strtolower(str_replace("\n", "\r\n", $response_str)), + strtolower($response->toString()), + 'Response convertion to string does not match original string' + ); + $this->assertEquals( + strtolower(str_replace("\n", "\r\n", $response_str)), + strtolower((string)$response), + 'Response convertion to string does not match original string' + ); } public function testToStringGzip() @@ -303,8 +319,16 @@ public function testToStringGzip() $response_str = $this->readResponse('response_gzip'); $response = Response::fromString($response_str); - $this->assertEquals(strtolower($response_str), strtolower($response->toString()), 'Response convertion to string does not match original string'); - $this->assertEquals(strtolower($response_str), strtolower((string)$response), 'Response convertion to string does not match original string'); + $this->assertEquals( + strtolower($response_str), + strtolower($response->toString()), + 'Response convertion to string does not match original string' + ); + $this->assertEquals( + strtolower($response_str), + strtolower((string)$response), + 'Response convertion to string does not match original string' + ); } public function testGetHeaders() @@ -314,7 +338,11 @@ public function testGetHeaders() $this->assertEquals(8, count($headers), 'Header count is not as expected'); $this->assertEquals('Apache', $headers->get('Server')->getFieldValue(), 'Server header is not as expected'); - $this->assertEquals('deflate', $headers->get('Content-encoding')->getFieldValue(), 'Content-type header is not as expected'); + $this->assertEquals( + 'deflate', + $headers->get('Content-encoding')->getFieldValue(), + 'Content-type header is not as expected' + ); } public function testGetVersion() @@ -339,7 +367,11 @@ public function testUnknownCode() public function testLeadingWhitespaceBody() { $response = Response::fromString($this->readResponse('response_leadingws')); - $this->assertEquals($response->getContent(), "\r\n\t \n\r\tx", 'Extracted body is not identical to expected body'); + $this->assertEquals( + $response->getContent(), + "\r\n\t \n\r\tx", + 'Extracted body is not identical to expected body' + ); } /**