From fdb26672eaaac4f404d484d7e09e0e8e7044cf4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Bedn=C3=A1=C5=99?= Date: Mon, 4 Jan 2021 14:45:03 +0100 Subject: [PATCH] fix: compatibility with PHP 7.1 and 7.2 (#60) * Added PHP 8 to CI * Added code style checking --- .circleci/config.yml | 13 ++ .gitignore | 5 +- .php_cs.dist | 11 ++ CHANGELOG.md | 4 + composer.json | 4 +- examples/WriteBatchingExample.php | 4 +- spec/InfluxDB2/ApiClientSpec.php | 66 ---------- spec/InfluxDB2/PointSpec.php | 73 ----------- spec/InfluxDB2/WriteClientSpec.php | 31 ----- src/InfluxDB2/Client.php | 1 - src/InfluxDB2/DefaultApi.php | 10 +- src/InfluxDB2/FluxColumn.php | 2 +- src/InfluxDB2/FluxCsvParser.php | 15 +-- src/InfluxDB2/FluxCsvParserException.php | 1 - src/InfluxDB2/FluxRecord.php | 2 - src/InfluxDB2/FluxTable.php | 6 +- src/InfluxDB2/Point.php | 80 +++++------- src/InfluxDB2/PointSettings.php | 6 +- src/InfluxDB2/QueryApi.php | 13 +- src/InfluxDB2/UdpWriter.php | 2 - src/InfluxDB2/Worker.php | 15 +-- src/InfluxDB2/WriteApi.php | 44 +++---- src/InfluxDB2/WriteOptions.php | 1 - src/InfluxDB2/WritePayloadSerializer.php | 3 - src/InfluxDB2/Writer.php | 3 - tests/BasicTest.php | 5 +- tests/DefaultApiTest.php | 6 +- tests/FluxCsvParserTest.php | 59 ++++----- tests/ITBucketServiceTest.php | 48 +++++--- tests/ITUsersServiceTest.php | 1 - tests/IntegrationBaseTestCase.php | 3 +- tests/PointSettingsTest.php | 3 +- tests/PointTest.php | 28 +++-- tests/QueryApiIntegrationTest.php | 7 +- tests/QueryApiStreamTest.php | 18 ++- tests/QueryApiTest.php | 4 +- tests/WriteApiBatchingTest.php | 147 ++++++++++++++++------- tests/WriteApiIntegrationTest.php | 7 +- tests/WriteApiTest.php | 85 ++++++++----- tests/WriteUdpTest.php | 1 - 40 files changed, 359 insertions(+), 478 deletions(-) create mode 100644 .php_cs.dist delete mode 100644 spec/InfluxDB2/ApiClientSpec.php delete mode 100644 spec/InfluxDB2/PointSpec.php delete mode 100644 spec/InfluxDB2/WriteClientSpec.php diff --git a/.circleci/config.yml b/.circleci/config.yml index 59ff2c0f..782204ab 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -110,6 +110,15 @@ jobs: export PATH=/c/tools/php/:$PATH ./vendor/bin/phpunit --exclude-group "integration" --log-junit build/junit.xml - storing-test-results + check-code-style: + docker: + - image: *default-php-image + steps: + - checkout + - run: | + mkdir -p tools/php-cs-fixer + composer require --working-dir=tools/php-cs-fixer friendsofphp/php-cs-fixer + tools/php-cs-fixer/vendor/bin/php-cs-fixer fix --dry-run --verbose --show-progress=estimating --using-cache=no --diff workflows: version: 2 @@ -117,6 +126,9 @@ workflows: jobs: - tests-php: name: php-7.4 + - tests-php: + name: php-8.0 + php-image: "circleci/php:8.0" - tests-php: name: php-7.4-guzzle-7 guzzle-version: "7.0.1" @@ -134,6 +146,7 @@ workflows: php-image: "circleci/php:7.1" - tests-windows: name: php-windows + - check-code-style nightly: triggers: diff --git a/.gitignore b/.gitignore index 9b951ecf..2e409ea2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,6 @@ bin/ vendor/ -composer.lock +composer.lock* build/ .idea/ coverage.xml @@ -8,3 +8,6 @@ coverage.xml /generated/ /*.iml log_test.txt +tree.txt +/.php_cs.cache +/tools/ diff --git a/.php_cs.dist b/.php_cs.dist new file mode 100644 index 00000000..22859441 --- /dev/null +++ b/.php_cs.dist @@ -0,0 +1,11 @@ +setFinder( + PhpCsFixer\Finder::create() + ->exclude('src/InfluxDB2/Model') + ->exclude('src/InfluxDB2/Service') + ->notPath('src/InfluxDB2/HeaderSelector.php') + ->notPath('src/InfluxDB2/ObjectSerializer.php') + ->in(__DIR__) + ) +; \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ca80a7c..782828d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,8 +4,12 @@ 1. [#53](https://github.com/influxdata/influxdb-client-php/pull/53): Ability to write via UDP protocol 1. [#57](https://github.com/influxdata/influxdb-client-php/pull/57): Added possibility to disable verification of SSL certificate +### Bug Fixes +1. [#60](https://github.com/influxdata/influxdb-client-php/pull/60): Compatibility with PHP 7.1 and 7.2 + ### CI 1. [#58](https://github.com/influxdata/influxdb-client-php/pull/58): Updated default docker image to v2.0.3 +1. [#60](https://github.com/influxdata/influxdb-client-php/pull/60): Added PHP 8 to CI, Added code style checking to CI ## 1.9.0 [2020-12-04] diff --git a/composer.json b/composer.json index 6982681b..5181f0bc 100644 --- a/composer.json +++ b/composer.json @@ -14,9 +14,7 @@ "guzzlehttp/guzzle": "^6.2|^7.0.1" }, "require-dev": { - "friendsofphp/php-cs-fixer": "~2.12", - "phpspec/phpspec": ">5.0", - "phpunit/phpunit": "^7.4", + "phpunit/phpunit": "^7.4|^9.1", "squizlabs/php_codesniffer": "~2.6" }, "autoload": { diff --git a/examples/WriteBatchingExample.php b/examples/WriteBatchingExample.php index edff011c..bef05d23 100644 --- a/examples/WriteBatchingExample.php +++ b/examples/WriteBatchingExample.php @@ -23,7 +23,8 @@ print "*** Write by batching ***\n"; $writeApi = $client->createWriteApi( - ["writeType" => WriteType::BATCHING, 'batchSize' => 1000]); + ["writeType" => WriteType::BATCHING, 'batchSize' => 1000] +); foreach (range(1, 10000) as $number) { $writeApi->write("mem,host=aws_europe,type=batch value=1i $number"); @@ -46,4 +47,3 @@ print "Count: $value\n"; $client->close(); - diff --git a/spec/InfluxDB2/ApiClientSpec.php b/spec/InfluxDB2/ApiClientSpec.php deleted file mode 100644 index b3e082cb..00000000 --- a/spec/InfluxDB2/ApiClientSpec.php +++ /dev/null @@ -1,66 +0,0 @@ -setHost("my_host:8086"); - $configuration->setAccessToken("my_access_token"); - - $this->beConstructedWith($configuration); - - $this->shouldHaveType(Client::class); - $this->getConfig()->shouldEqual($configuration); - } - - function it_supports_creation_from_environment() - { - $configuration = new Configuration(); - $configuration->setHost("my_host:8086"); - $configuration->setUsername("user"); - $configuration->setPassword("password"); - - putenv("INFLUXDB_CLIENT_HOST=my_host:8086"); - putenv("INFLUXDB_CLIENT_USERNAME=user"); - putenv("INFLUXDB_CLIENT_PASSWORD=password"); - - $this->beConstructedThrough("createFromEnvironment", []); - - $this->shouldHaveType(Client::class); - $this->getConfig()->shouldBeLike($configuration); - } - - function it_supports_creation_with_credentials() - { - $configuration = new Configuration(); - $configuration->setHost("my_host:8086"); - $configuration->setUsername("username"); - $configuration->setPassword("password"); - - $this->beConstructedThrough("createWithCredentials", ["my_host:8086", "username", "password"]); - - $this->shouldHaveType(Client::class); - $this->getConfig()->shouldBeLike($configuration); - } - - function it_creates_a_write_client() - { - $configuration = new Configuration(); - $configuration->setHost("my_host:8086"); - $configuration->setAccessToken("my_access_token"); - - $this->beConstructedWith($configuration); - - $this->getWriteClient()->shouldHaveType(WriteApi::class); - $this->getWriteClient()->getConfig()->shouldBeLike($configuration); - } -} diff --git a/spec/InfluxDB2/PointSpec.php b/spec/InfluxDB2/PointSpec.php deleted file mode 100644 index 30eacc42..00000000 --- a/spec/InfluxDB2/PointSpec.php +++ /dev/null @@ -1,73 +0,0 @@ - "php", - ]; - - $fields = [ - "_value" => 1, - ]; - - $this->beConstructedWith($measurement, $tags, $fields); - - $this->shouldHaveType(Point::class); - - $this->getTags()->shouldEqual($tags); - - $this->getTag("language")->shouldEqual("php"); - $this->getTag("unknown")->shouldEqual(null); - - $this->getFields()->shouldEqual($fields); - $this->getField("_value")->shouldEqual(1); - $this->getField("unknown")->shouldEqual(null); - } - - function it_can_produce_line_protocol_with_no_time() - { - $measurement = "measurement"; - - $tags = [ - "language" => "php", - ]; - - $fields = [ - "_value" => 1, - ]; - - $this->beConstructedWith($measurement, $tags, $fields); - - $this->lineProtocol()->shouldEqual("measurement,language=php _value=1"); - } - - function it_can_produce_line_protocol_with_time() - { - $measurement = "measurement"; - - $tags = [ - "language" => "php", - ]; - - $fields = [ - "_value" => 1, - ]; - - list($usec, $sec) = explode(' ', microtime()); - $timestamp = sprintf('%d%06d', $sec, $usec*1000000); - - $this->beConstructedWith($measurement, $tags, $fields, $timestamp); - - $this->lineProtocol()->shouldEqual("measurement,language=php _value=1 ${timestamp}"); - } -} diff --git a/spec/InfluxDB2/WriteClientSpec.php b/spec/InfluxDB2/WriteClientSpec.php deleted file mode 100644 index 8bca4a81..00000000 --- a/spec/InfluxDB2/WriteClientSpec.php +++ /dev/null @@ -1,31 +0,0 @@ -setHost("my_host:8086"); - $configuration->setAccessToken("my_access_token"); - - $this->beConstructedWith($client, $configuration); - - $this->shouldHaveType(WriteApi::class); - $this->getClient()->shouldEqual($client); - $this->getConfig()->shouldEqual($configuration); - } - - function it_can_write_a_single_point() - { - // ??? - } -} diff --git a/src/InfluxDB2/Client.php b/src/InfluxDB2/Client.php index dd04a555..adbe2b53 100644 --- a/src/InfluxDB2/Client.php +++ b/src/InfluxDB2/Client.php @@ -102,7 +102,6 @@ public function close() public function getConfiguration() { - $config = Configuration::getDefaultConfiguration() ->setUserAgent('influxdb-client-php/' . Client::VERSION) ->setDebug(isset($this->options['debug']) ? $this->options['debug'] : null) diff --git a/src/InfluxDB2/DefaultApi.php b/src/InfluxDB2/DefaultApi.php index 5937af8a..b8563070 100644 --- a/src/InfluxDB2/DefaultApi.php +++ b/src/InfluxDB2/DefaultApi.php @@ -89,7 +89,6 @@ private function request($payload, $uriPath, $queryParams, $method, $timeout = s ); } return $response; - } catch (RequestException $e) { throw new ApiException( "[{$e->getCode()}] {$e->getMessage()}", @@ -109,14 +108,14 @@ private function request($payload, $uriPath, $queryParams, $method, $timeout = s } } - function check($key, $value) + protected function check($key, $value) { if ((!isset($value) || trim($value) === '')) { $options = implode(', ', array_map( function ($v, $k) { - if(is_array($v)){ + if (is_array($v)) { return $k.'[]='.implode('&'.$k.'[]=', $v); - }else{ + } else { return $k.'='.$v; } }, @@ -133,7 +132,7 @@ function ($v, $k) { * @param string $level log severity * @param string $message log message */ - function log(string $level, string $message): void + protected function log(string $level, string $message): void { $logFile = isset($this->options['logFile']) ? $this->options['logFile'] : "php://output"; $logDate = date('H:i:s d-M-Y'); @@ -141,4 +140,3 @@ function log(string $level, string $message): void file_put_contents($logFile, "[{$logDate}]: [{$level}] - {$message}", FILE_APPEND); } } - diff --git a/src/InfluxDB2/FluxColumn.php b/src/InfluxDB2/FluxColumn.php index 8f24beda..3ceaf403 100644 --- a/src/InfluxDB2/FluxColumn.php +++ b/src/InfluxDB2/FluxColumn.php @@ -1,6 +1,7 @@ group = $group; $this->defaultValue = $defaultValue; } - } diff --git a/src/InfluxDB2/FluxCsvParser.php b/src/InfluxDB2/FluxCsvParser.php index aa24c8d4..65469e45 100644 --- a/src/InfluxDB2/FluxCsvParser.php +++ b/src/InfluxDB2/FluxCsvParser.php @@ -59,7 +59,7 @@ public function __construct($response, $stream = false) private function stringToStream(string $string) { - $stream = fopen('php://memory','r+'); + $stream = fopen('php://memory', 'r+'); fwrite($stream, $string); rewind($stream); return $stream; @@ -92,8 +92,10 @@ public function each() if ($this->parsingStateError) { $error = $csv[1]; $referenceValue = $csv[2]; - throw new FluxQueryError($error, - !isset($referenceValue) || trim($referenceValue) === '' ? 0 : $referenceValue); + throw new FluxQueryError( + $error, + !isset($referenceValue) || trim($referenceValue) === '' ? 0 : $referenceValue + ); } $result = $this->parseLine($csv); @@ -102,9 +104,7 @@ public function each() yield $result; } } - } - finally - { + } finally { $this->closeConnection(); } } @@ -270,7 +270,6 @@ private function toValue($strVal, FluxColumn $column) } return $strVal; - } private function readline(StreamInterface $stream) @@ -278,7 +277,6 @@ private function readline(StreamInterface $stream) $buffer = null; while (null !== ($byte = $stream->read(1))) { - if ($byte === "") { break; } @@ -308,5 +306,4 @@ private function closeConnection() class FluxQueryError extends RuntimeException { - } diff --git a/src/InfluxDB2/FluxCsvParserException.php b/src/InfluxDB2/FluxCsvParserException.php index ef62c132..d51dee2d 100644 --- a/src/InfluxDB2/FluxCsvParserException.php +++ b/src/InfluxDB2/FluxCsvParserException.php @@ -3,7 +3,6 @@ namespace InfluxDB2; - class FluxCsvParserException extends \RuntimeException { /** diff --git a/src/InfluxDB2/FluxRecord.php b/src/InfluxDB2/FluxRecord.php index 9ca04ae1..1fcad723 100644 --- a/src/InfluxDB2/FluxRecord.php +++ b/src/InfluxDB2/FluxRecord.php @@ -10,7 +10,6 @@ */ class FluxRecord { - public $table; public $values; @@ -54,5 +53,4 @@ public function getMeasurement():string { return $this->values['_measurement']; } - } diff --git a/src/InfluxDB2/FluxTable.php b/src/InfluxDB2/FluxTable.php index c01de434..089e8d67 100644 --- a/src/InfluxDB2/FluxTable.php +++ b/src/InfluxDB2/FluxTable.php @@ -19,7 +19,6 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. namespace InfluxDB2; -use phpDocumentor\Reflection\Types\This; /** * This class represents the table structure of the Flux CSV Response. @@ -43,7 +42,8 @@ public function __construct() public function getGroupKey() { - return array_values(array_filter($this->columns, function ($column) { return $column->group; })); + return array_values(array_filter($this->columns, function ($column) { + return $column->group; + })); } - } diff --git a/src/InfluxDB2/Point.php b/src/InfluxDB2/Point.php index db58769c..c82afda6 100644 --- a/src/InfluxDB2/Point.php +++ b/src/InfluxDB2/Point.php @@ -28,9 +28,13 @@ class Point * @param [Integer] time the timestamp for the point * @param [WritePrecision] precision the precision for the unix timestamps within the body line-protocol */ - public function __construct($name, $tags = null, $fields = null, $time = null, - $precision = Point::DEFAULT_WRITE_PRECISION) - { + public function __construct( + $name, + $tags = null, + $fields = null, + $time = null, + $precision = Point::DEFAULT_WRITE_PRECISION + ) { $this->name = $name; $this->tags = $tags; $this->fields = $fields; @@ -58,15 +62,14 @@ public static function measurement($name): Point */ public static function fromArray($data): ?Point { - if (!array_key_exists('name' ,$data)) - { + if (!array_key_exists('name', $data)) { return null; } - $tags = array_key_exists('tags' ,$data) ? $data['tags'] : null; - $fields = array_key_exists('fields' ,$data) ? $data['fields'] : null; - $time = array_key_exists('time' ,$data) ? $data['time'] : null; - $precision = array_key_exists('precision' ,$data) ? $data['precision'] : null; + $tags = array_key_exists('tags', $data) ? $data['tags'] : null; + $fields = array_key_exists('fields', $data) ? $data['fields'] : null; + $time = array_key_exists('time', $data) ? $data['time'] : null; + $precision = array_key_exists('precision', $data) ? $data['precision'] : null; return new Point($data['name'], $tags, $fields, $time, $precision); } @@ -123,19 +126,15 @@ public function toLineProtocol() $tags = $this->appendTags(); - if (!$this->isNullOrEmptyString($tags)) - { + if (!$this->isNullOrEmptyString($tags)) { $lineProtocol .= $tags; - } - else - { + } else { $lineProtocol .= ' '; } $fields = $this->appendFields(); - if ($this->isNullOrEmptyString($fields)) - { + if ($this->isNullOrEmptyString($fields)) { return null; } @@ -143,8 +142,7 @@ public function toLineProtocol() $time = $this->appendTime(); - if (!$this->isNullOrEmptyString($time)) - { + if (!$this->isNullOrEmptyString($time)) { $lineProtocol .= $time; } @@ -155,19 +153,16 @@ private function appendTags() { $tags = ''; - if ($this->tags == null) - { + if ($this->tags == null) { return null; } ksort($this->tags); - foreach (array_keys($this->tags) as $key) - { + foreach (array_keys($this->tags) as $key) { $value = $this->tags[$key]; - if ($this->isNullOrEmptyString($key) || $this->isNullOrEmptyString($value)) - { + if ($this->isNullOrEmptyString($key) || $this->isNullOrEmptyString($value)) { continue; } @@ -182,38 +177,28 @@ private function appendFields() { $fields = ''; - if ($this->fields == null) - { + if ($this->fields == null) { return null; } ksort($this->fields); - foreach (array_keys($this->fields) as $key) - { + foreach (array_keys($this->fields) as $key) { $value = $this->fields[$key]; - if (!isset($value)) - { + if (!isset($value)) { continue; } $fields .= $this->escapeKey($key) . '='; - if (is_integer($value) || is_long($value)) - { + if (is_integer($value) || is_long($value)) { $fields .= $value . 'i'; - } - else if (is_string($value)) - { + } elseif (is_string($value)) { $fields .= '"' . $this->escapeValue($value) . '"'; - } - else if (is_bool($value)) - { + } elseif (is_bool($value)) { $fields .= $value ? 'true' : 'false'; - } - else - { + } else { $fields .= $value; } @@ -225,23 +210,18 @@ private function appendFields() private function appendTime() { - if (!isset($this->time)) - { + if (!isset($this->time)) { return null; } $time = $this->time; - if (is_double($time) || is_float($time)) - { + if (is_double($time) || is_float($time)) { $time = round($time); - } - else if ($time instanceof DateTime) - { + } elseif ($time instanceof DateTime) { $seconds = $time->getTimestamp(); - switch ($this->precision) - { + switch ($this->precision) { case WritePrecision::MS: $time = strval(round($seconds) . '000'); break; diff --git a/src/InfluxDB2/PointSettings.php b/src/InfluxDB2/PointSettings.php index 5716be58..a95c42dd 100644 --- a/src/InfluxDB2/PointSettings.php +++ b/src/InfluxDB2/PointSettings.php @@ -3,7 +3,6 @@ namespace InfluxDB2; - class PointSettings { private $defaultTags; @@ -20,9 +19,8 @@ public function addDefaultTag(string $key, string $expression) public static function getValue(string $value): string { - if (substr( $value, 0, 6 ) === '${env.') - { - return getenv(substr( $value, 6, strlen($value) - 7)); + if (substr($value, 0, 6) === '${env.') { + return getenv(substr($value, 6, strlen($value) - 7)); } return $value; diff --git a/src/InfluxDB2/QueryApi.php b/src/InfluxDB2/QueryApi.php index affabaaf..cf700a60 100644 --- a/src/InfluxDB2/QueryApi.php +++ b/src/InfluxDB2/QueryApi.php @@ -8,7 +8,6 @@ class QueryApi extends DefaultApi { - private $DEFAULT_DIALECT; /** @@ -37,8 +36,7 @@ public function queryRaw(string $query, $org = null, $dialect = null): ?string { $result = $this->postQuery($query, $org, $dialect ?: $this->DEFAULT_DIALECT); - if ($result == null) - { + if ($result == null) { return null; } @@ -75,8 +73,7 @@ public function queryStream($query, $org = null, $dialect = null): ?FluxCsvParse { $response = $this->postQuery($query, $org, $dialect ?: $this->DEFAULT_DIALECT); - if ($response == null) - { + if ($response == null) { return null; } @@ -91,8 +88,7 @@ private function postQuery($query, $org, $dialect): ?ResponseInterface $payload = $this->generatePayload($query, $dialect); $queryParams = ["org" => $orgParam]; - if ($payload == null) - { + if ($payload == null) { return null; } @@ -114,7 +110,4 @@ private function generatePayload($query, $dialect) 'type' => null ]); } - } - - diff --git a/src/InfluxDB2/UdpWriter.php b/src/InfluxDB2/UdpWriter.php index fe8431d8..e11ca39e 100644 --- a/src/InfluxDB2/UdpWriter.php +++ b/src/InfluxDB2/UdpWriter.php @@ -26,7 +26,6 @@ */ class UdpWriter implements Writer { - public $options = []; /** @@ -103,5 +102,4 @@ public function close() socket_close($this->socket); } } - } diff --git a/src/InfluxDB2/Worker.php b/src/InfluxDB2/Worker.php index ba07a40c..5c5be62d 100644 --- a/src/InfluxDB2/Worker.php +++ b/src/InfluxDB2/Worker.php @@ -2,7 +2,6 @@ namespace InfluxDB2; - use Exception; use SplQueue; @@ -26,16 +25,14 @@ public function push($payload) { $this->queue->enqueue($payload); - if ($this->queue->count() >= $this->writeOptions->batchSize) - { + if ($this->queue->count() >= $this->writeOptions->batchSize) { $this->checkBackgroundQueue(true); } } public function flush() { - while ($this->queue->count() != 0) - { + while ($this->queue->count() != 0) { $this->checkBackgroundQueue(false); } } @@ -58,7 +55,7 @@ private function checkBackgroundQueue(bool $size) if ($index === null) { $data[] = array('key' => $key, 'data' => array()); - $index = array_key_last($data); + $index = array_keys($data)[count($data)-1]; } $data[$index]['data'][] = $item->data; @@ -75,13 +72,11 @@ private function checkBackgroundQueue(bool $size) private function existsKey($key, $data): ?int { - foreach ($data as $item) - { + foreach ($data as $item) { $itemKey = $item['key']; if ($key->precision === $itemKey->precision && $key->bucket === $itemKey->bucket && - $key->org === $itemKey->org) - { + $key->org === $itemKey->org) { return array_search($item, $data); } } diff --git a/src/InfluxDB2/WriteApi.php b/src/InfluxDB2/WriteApi.php index 3c9d4bb2..0eef6b6a 100644 --- a/src/InfluxDB2/WriteApi.php +++ b/src/InfluxDB2/WriteApi.php @@ -2,7 +2,6 @@ namespace InfluxDB2; - use GuzzleHttp\Exception\ConnectException; use InfluxDB2\Model\WritePrecision; @@ -31,10 +30,8 @@ public function __construct($options, array $writeOptions = null, array $pointSe $this->writeOptions = new WriteOptions($writeOptions) ?: new WriteOptions(); $this->pointSettings = new PointSettings($pointSettings) ?: new PointSettings(); - if (array_key_exists('tags', $options)) - { - foreach (array_keys($options['tags']) as $key) - { + if (array_key_exists('tags', $options)) { + foreach (array_keys($options['tags']) as $key) { $this->pointSettings->addDefaultTag($key, $options['tags'][$key]); } } @@ -86,8 +83,7 @@ public function write($data, string $precision = null, string $bucket = null, st return; } - if (WriteType::BATCHING == $this->writeOptions->writeType) - { + if (WriteType::BATCHING == $this->writeOptions->writeType) { $this->worker()->push($payload); } else { $this->writeRaw($payload, $precisionParam, $bucketParam, $orgParam); @@ -98,27 +94,18 @@ private function addDefaultTags(&$data) { $defaultTags = $this->pointSettings->getDefaultTags(); - if (is_array($data)) - { - if (array_key_exists('name', $data)) - { - foreach (array_keys($defaultTags) as $key) - { + if (is_array($data)) { + if (array_key_exists('name', $data)) { + foreach (array_keys($defaultTags) as $key) { $data['tags'][$key] = PointSettings::getValue($defaultTags[$key]); } - } - else - { - foreach ($data as &$item) - { + } else { + foreach ($data as &$item) { $this->addDefaultTags($item); } } - } - elseif ($data instanceof Point) - { - foreach (array_keys($defaultTags) as $key) - { + } elseif ($data instanceof Point) { + foreach (array_keys($defaultTags) as $key) { $data->addTag($key, PointSettings::getValue($defaultTags[$key])); } } @@ -187,8 +174,12 @@ private function writeRawInternal(string $data, array $queryParams, int $attempt usleep($timeout); - $this->writeRawInternal($data, $queryParams, $attempts + 1, - $retryInterval * $this->writeOptions->exponentialBase); + $this->writeRawInternal( + $data, + $queryParams, + $attempts + 1, + $retryInterval * $this->writeOptions->exponentialBase + ); } } @@ -201,8 +192,7 @@ public function close() private function worker(): Worker { - if (!isset($this->worker)) - { + if (!isset($this->worker)) { $this->worker = new Worker($this); } diff --git a/src/InfluxDB2/WriteOptions.php b/src/InfluxDB2/WriteOptions.php index 0849384b..79a1baa9 100644 --- a/src/InfluxDB2/WriteOptions.php +++ b/src/InfluxDB2/WriteOptions.php @@ -46,4 +46,3 @@ public function __construct(array $writeOptions = null) $this->jitterInterval = $writeOptions["jitterInterval"] ?? self::DEFAULT_JITTER_INTERVAL; } } - diff --git a/src/InfluxDB2/WritePayloadSerializer.php b/src/InfluxDB2/WritePayloadSerializer.php index 2dd58327..3aa339a6 100644 --- a/src/InfluxDB2/WritePayloadSerializer.php +++ b/src/InfluxDB2/WritePayloadSerializer.php @@ -3,7 +3,6 @@ namespace InfluxDB2; - class WritePayloadSerializer { /** @@ -22,7 +21,6 @@ public static function generatePayload($data, string $precision = null, string $ return null; } if (is_string($data)) { - if (WriteType::BATCHING == $writeType) { return new BatchItem(new BatchItemKey($bucket, $org, $precision), $data); } else { @@ -57,4 +55,3 @@ public static function generatePayload($data, string $precision = null, string $ return null; } } - diff --git a/src/InfluxDB2/Writer.php b/src/InfluxDB2/Writer.php index 77bb0298..0804b87e 100644 --- a/src/InfluxDB2/Writer.php +++ b/src/InfluxDB2/Writer.php @@ -3,7 +3,6 @@ namespace InfluxDB2; - interface Writer { @@ -33,6 +32,4 @@ interface Writer * @throws \Throwable */ public function write($data); - - } diff --git a/tests/BasicTest.php b/tests/BasicTest.php index 3da23a80..ca1fc63a 100644 --- a/tests/BasicTest.php +++ b/tests/BasicTest.php @@ -2,7 +2,6 @@ namespace InfluxDB2Test; - use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\HandlerStack; use GuzzleHttp\Middleware; @@ -34,7 +33,7 @@ abstract class BasicTest extends TestCase * @param string $url * @param string $logFile default log file */ - public function setUp($url = "http://localhost:8086", $logFile = "php://output") + public function setUp($url = "http://localhost:8086", $logFile = "php://output"): void { $this->client = new Client([ "url" => $url, @@ -68,7 +67,7 @@ public function setUp($url = "http://localhost:8086", $logFile = "php://output") ]); } - public function tearDown() + public function tearDown(): void { $this->client->close(); } diff --git a/tests/DefaultApiTest.php b/tests/DefaultApiTest.php index d40d2aa2..a52d8249 100644 --- a/tests/DefaultApiTest.php +++ b/tests/DefaultApiTest.php @@ -19,8 +19,10 @@ public function testUserAgent() $request = $this->mockHandler->getLastRequest(); - $this->assertStringStartsWith('influxdb-client-php/', - strval($request->getHeader("User-Agent")[0])); + $this->assertStringStartsWith( + 'influxdb-client-php/', + strval($request->getHeader("User-Agent")[0]) + ); } public function testTrailingSlashInUrl() diff --git a/tests/FluxCsvParserTest.php b/tests/FluxCsvParserTest.php index 36f0d3fb..ff7fe98e 100644 --- a/tests/FluxCsvParserTest.php +++ b/tests/FluxCsvParserTest.php @@ -56,7 +56,6 @@ public function testParseShortCut() $this->assertEquals(10, sizeof($record->values)); $this->assertEquals("free", $record->getField()); $this->assertEquals("mem", $record->getMeasurement()); - } public function testMappingBoolean() @@ -218,15 +217,13 @@ public function testError() try { $fluxCsvParser->parse(); $this->fail(); - } - catch (FluxQueryError $e) - { - $this->assertEquals('failed to create physical plan: invalid time bounds from procedure from: bounds contain zero time', - $e->getMessage()); + } catch (FluxQueryError $e) { + $this->assertEquals( + 'failed to create physical plan: invalid time bounds from procedure from: bounds contain zero time', + $e->getMessage() + ); $this->assertEquals(897, $e->getCode()); - } - catch (\Exception $e) - { + } catch (\Exception $e) { $this->fail(); } } @@ -244,15 +241,13 @@ public function testErrorWithoutReference() try { $fluxCsvParser->parse(); $this->fail(); - } - catch (FluxQueryError $e) - { - $this->assertEquals('failed to create physical plan: invalid time bounds from procedure from: bounds contain zero time', - $e->getMessage()); + } catch (FluxQueryError $e) { + $this->assertEquals( + 'failed to create physical plan: invalid time bounds from procedure from: bounds contain zero time', + $e->getMessage() + ); $this->assertEquals(0, $e->getCode()); - } - catch (\Exception $e) - { + } catch (\Exception $e) { $this->fail(); } } @@ -268,14 +263,12 @@ public function testWithoutTableReference() try { $fluxCsvParser->parse(); $this->fail(); - } - catch (FluxCsvParserException $e) - { - $this->assertEquals('Unable to parse CSV response. FluxTable definition was not found.', - $e->getMessage()); - } - catch (\Exception $e) - { + } catch (FluxCsvParserException $e) { + $this->assertEquals( + 'Unable to parse CSV response. FluxTable definition was not found.', + $e->getMessage() + ); + } catch (\Exception $e) { $this->fail(); } } @@ -348,15 +341,13 @@ public function testResponseWithError() try { $fluxCsvParser->parse(); $this->fail(); - } - catch (FluxQueryError $e) - { - $this->assertEquals('engine: unknown field type for value: xyz', - $e->getMessage()); + } catch (FluxQueryError $e) { + $this->assertEquals( + 'engine: unknown field type for value: xyz', + $e->getMessage() + ); $this->assertEquals(0, $e->getCode()); - } - catch (\Exception $e) - { + } catch (\Exception $e) { $this->fail(); } } @@ -427,7 +418,6 @@ private function assertMultipleRecords(array $tables) 'value_str' => 'test']; $this->assertRecord($tableRecords[0], $values, 11); - } private function assertRecord(FluxRecord $fluxRecord, array $values, $size = 0, $value = null) @@ -449,5 +439,4 @@ private function parseTime(string $timestamp) //TODO datetime parsing return $timestamp; } - } diff --git a/tests/ITBucketServiceTest.php b/tests/ITBucketServiceTest.php index 5ccd7bd2..b21b920f 100644 --- a/tests/ITBucketServiceTest.php +++ b/tests/ITBucketServiceTest.php @@ -24,23 +24,35 @@ public function testHealthService() public function testFixNanosTimeSerialization() { - self::assertEquals("2020-09-18T08:03:48.12345Z", - ObjectSerializer::fixDatetimeNanos("2020-09-18T08:03:48.12345Z")); - - self::assertEquals("2020-09-18T08:03:48.123456Z", - ObjectSerializer::fixDatetimeNanos("2020-09-18T08:03:48.123456Z")); - - self::assertEquals("2020-09-18T08:03:48.1234567Z", - ObjectSerializer::fixDatetimeNanos("2020-09-18T08:03:48.1234567Z")); - - self::assertEquals("2020-09-18T08:03:48.12345678Z", - ObjectSerializer::fixDatetimeNanos("2020-09-18T08:03:48.12345678Z")); - - self::assertEquals("2020-09-18T08:03:48.12345678Z", - ObjectSerializer::fixDatetimeNanos("2020-09-18T08:03:48.123456789Z")); - - self::assertEquals("2020-09-18T08:03:48.12345678Z", - ObjectSerializer::fixDatetimeNanos("2020-09-18T08:03:48.1234567899Z")); + self::assertEquals( + "2020-09-18T08:03:48.12345Z", + ObjectSerializer::fixDatetimeNanos("2020-09-18T08:03:48.12345Z") + ); + + self::assertEquals( + "2020-09-18T08:03:48.123456Z", + ObjectSerializer::fixDatetimeNanos("2020-09-18T08:03:48.123456Z") + ); + + self::assertEquals( + "2020-09-18T08:03:48.1234567Z", + ObjectSerializer::fixDatetimeNanos("2020-09-18T08:03:48.1234567Z") + ); + + self::assertEquals( + "2020-09-18T08:03:48.12345678Z", + ObjectSerializer::fixDatetimeNanos("2020-09-18T08:03:48.12345678Z") + ); + + self::assertEquals( + "2020-09-18T08:03:48.12345678Z", + ObjectSerializer::fixDatetimeNanos("2020-09-18T08:03:48.123456789Z") + ); + + self::assertEquals( + "2020-09-18T08:03:48.12345678Z", + ObjectSerializer::fixDatetimeNanos("2020-09-18T08:03:48.1234567899Z") + ); } public function testBucketService() @@ -94,6 +106,4 @@ public function testBucketServiceCreateBucket() $this->expectExceptionMessage("bucket not found"); $bucketsService->getBucketsID($findBucket->getId()); } - } - diff --git a/tests/ITUsersServiceTest.php b/tests/ITUsersServiceTest.php index 860b8d72..23dde430 100644 --- a/tests/ITUsersServiceTest.php +++ b/tests/ITUsersServiceTest.php @@ -20,5 +20,4 @@ public function testUserService() self::assertNotEmpty($user->getLinks()->getSelf()); } } - } diff --git a/tests/IntegrationBaseTestCase.php b/tests/IntegrationBaseTestCase.php index cdaea18f..b7579b0a 100644 --- a/tests/IntegrationBaseTestCase.php +++ b/tests/IntegrationBaseTestCase.php @@ -1,4 +1,5 @@ options = [ "url" => "http://localhost:8086", diff --git a/tests/PointSettingsTest.php b/tests/PointSettingsTest.php index ab4f1d01..e81ce531 100644 --- a/tests/PointSettingsTest.php +++ b/tests/PointSettingsTest.php @@ -2,7 +2,6 @@ namespace InfluxDB2Test; - use InfluxDB2\Client; use InfluxDB2\Model\WritePrecision; use PHPUnit\Framework\TestCase; @@ -15,7 +14,7 @@ class PointSettingsTest extends TestCase /** @var Client */ private $client; - public function setUp() + public function setUp(): void { $this->client = new Client([ "url" => "http://localhost:8086", diff --git a/tests/PointTest.php b/tests/PointTest.php index b1e2df4a..8f19f46d 100644 --- a/tests/PointTest.php +++ b/tests/PointTest.php @@ -11,21 +11,27 @@ class PointTest extends TestCase { public function testToLineProtocol() { - $pointArgs = new Point('h2o', + $pointArgs = new Point( + 'h2o', array('host' => 'aws', 'region' => 'us'), array('level' => 5, 'saturation' => '99%'), - 123); + 123 + ); - $this->assertEquals('h2o,host=aws,region=us level=5i,saturation="99%" 123', - $pointArgs->toLineProtocol()); + $this->assertEquals( + 'h2o,host=aws,region=us level=5i,saturation="99%" 123', + $pointArgs->toLineProtocol() + ); $pointArray = Point::fromArray(array('name' => 'h2o', 'tags' => array('host' => 'aws', 'region' => 'us'), 'fields' => array('level' => 5, 'saturation' => '99%'), 'time' => 123)); - $this->assertEquals('h2o,host=aws,region=us level=5i,saturation="99%" 123', - $pointArray->toLineProtocol()); + $this->assertEquals( + 'h2o,host=aws,region=us level=5i,saturation="99%" 123', + $pointArray->toLineProtocol() + ); } public function testMeasurementEscape() @@ -65,12 +71,14 @@ public function testTagEscapingKeyAndValue() ->addTag("t\tab", "t\tab") ->addField("level", 2); - $this->assertEquals("h\\n2\\ro\\t_data,carriage\\rreturn=carriage\\nreturn,new\\nline=new\\nline,t\\tab=t\\tab level=2i", - $point->toLineProtocol()); + $this->assertEquals( + "h\\n2\\ro\\t_data,carriage\\rreturn=carriage\\nreturn,new\\nline=new\\nline,t\\tab=t\\tab level=2i", + $point->toLineProtocol() + ); } - public function testEqualSignEscaping() { - + public function testEqualSignEscaping() + { $point = Point::measurement("h=2o") ->addTag("l=ocation", "e=urope") ->addField("l=evel", 2); diff --git a/tests/QueryApiIntegrationTest.php b/tests/QueryApiIntegrationTest.php index 5f7dbed0..b80bd321 100644 --- a/tests/QueryApiIntegrationTest.php +++ b/tests/QueryApiIntegrationTest.php @@ -20,7 +20,7 @@ class QueryApiIntegrationTest extends TestCase /** * @before */ - public function setUp() + public function setUp(): void { $this->client = new Client([ "url" => "http://localhost:8086", @@ -50,8 +50,8 @@ public function testQueryRaw() $result = $this->queryApi->queryRaw($query); - $this->assertContains(',result,table,_start,_stop,_time,_value,_field,_measurement,location', $result); - $this->assertContains($measurement, $result); + $this->assertStringContainsString(',result,table,_start,_stop,_time,_value,_field,_measurement,location', $result); + $this->assertStringContainsString($measurement, $result); } public function testQuery() @@ -92,5 +92,4 @@ public function prepareData(string $measurement, DateTime $now): string |> filter(fn: (r) => r._measurement == "' . $measurement . '")'; return $query; } - } diff --git a/tests/QueryApiStreamTest.php b/tests/QueryApiStreamTest.php index b9ac28f5..410cbd0d 100644 --- a/tests/QueryApiStreamTest.php +++ b/tests/QueryApiStreamTest.php @@ -2,7 +2,6 @@ namespace InfluxDB2Test; - use DateTime; use InfluxDB2\Client; use InfluxDB2\Model\WritePrecision; @@ -22,7 +21,7 @@ class QueryApiStreamTest extends TestCase /** * @before */ - public function setUp() + public function setUp(): void { $this->client = new Client([ "url" => "http://localhost:8086", @@ -51,8 +50,7 @@ public function testQueryStream() $parser = $this->queryApi->queryStream($query); - foreach ($parser->each() as $record) - { + foreach ($parser->each() as $record) { $this->assertNotNull($record); $this->assertEquals($measurement, $record->getMeasurement()); @@ -82,10 +80,8 @@ public function testQueryStreamBreak() $this->assertFalse($parser->closed); - foreach ($parser->each() as $record) - { - if ($count >= 5) - { + foreach ($parser->each() as $record) { + if ($count >= 5) { break; } @@ -108,11 +104,13 @@ public function testQueryEmptyData() private function write($values, $measurement) { for ($ii = 0; $ii < $values; $ii++) { - $this->writeApi->write(Point::measurement($measurement) + $this->writeApi->write( + Point::measurement($measurement) ->addTag('location', 'europe') ->addField('level', $ii) ->time($this->now->getTimestamp() - $values + $ii, WritePrecision::S), - WritePrecision::S); + WritePrecision::S + ); } } } diff --git a/tests/QueryApiTest.php b/tests/QueryApiTest.php index 3cfb3fbb..7dc10797 100644 --- a/tests/QueryApiTest.php +++ b/tests/QueryApiTest.php @@ -2,7 +2,6 @@ namespace InfluxDB2Test; - use GuzzleHttp\Psr7\Response; require_once('BasicTest.php'); @@ -27,7 +26,8 @@ public function testQueryRaw() $this->mockHandler->append(new Response(204, [], QueryApiTest::SUCCESS_DATA)); $result = $this->queryApi->queryRaw( - 'from(bucket:"my-bucket") |> range(start: 1970-01-01T00:00:00.000000001Z) |> last()'); + 'from(bucket:"my-bucket") |> range(start: 1970-01-01T00:00:00.000000001Z) |> last()' + ); $this->assertEquals(QueryApiTest::SUCCESS_DATA, $result); } diff --git a/tests/WriteApiBatchingTest.php b/tests/WriteApiBatchingTest.php index 41702b4a..050e8fa7 100644 --- a/tests/WriteApiBatchingTest.php +++ b/tests/WriteApiBatchingTest.php @@ -22,8 +22,10 @@ protected function getWriteOptions(): ?array public function testBatchSize() { - $this->mockHandler->append(new Response(204), - new Response(204)); + $this->mockHandler->append( + new Response(204), + new Response(204) + ); $this->writeApi->write('h2o_feet,location=coyote_creek level\\ water_level=1.0 1'); $this->writeApi->write('h2o_feet,location=coyote_creek level\\ water_level=2.0 2'); @@ -43,59 +45,95 @@ public function testBatchSize() public function testBatchSizeGroupBy() { - $this->mockHandler->append(new Response(204), + $this->mockHandler->append( new Response(204), new Response(204), new Response(204), - new Response(204)); + new Response(204), + new Response(204) + ); $bucket = 'my-bucket'; $bucket2 = 'my-bucket2'; - $this->writeApi->write('h2o_feet,location=coyote_creek level\\ water_level=1.0 1', 'ns', - $bucket, 'my-org'); - $this->writeApi->write('h2o_feet,location=coyote_creek level\\ water_level=2.0 2', 's', - $bucket, 'my-org'); - $this->writeApi->write('h2o_feet,location=coyote_creek level\\ water_level=3.0 3', 'ns', - $bucket, 'my-org-a'); - $this->writeApi->write('h2o_feet,location=coyote_creek level\\ water_level=4.0 4', 'ns', - $bucket, 'my-org-a'); - $this->writeApi->write('h2o_feet,location=coyote_creek level\\ water_level=5.0 5', 'ns', - $bucket2, 'my-org-a'); - $this->writeApi->write('h2o_feet,location=coyote_creek level\\ water_level=6.0 6', 'ns', - $bucket, 'my-org-a'); + $this->writeApi->write( + 'h2o_feet,location=coyote_creek level\\ water_level=1.0 1', + 'ns', + $bucket, + 'my-org' + ); + $this->writeApi->write( + 'h2o_feet,location=coyote_creek level\\ water_level=2.0 2', + 's', + $bucket, + 'my-org' + ); + $this->writeApi->write( + 'h2o_feet,location=coyote_creek level\\ water_level=3.0 3', + 'ns', + $bucket, + 'my-org-a' + ); + $this->writeApi->write( + 'h2o_feet,location=coyote_creek level\\ water_level=4.0 4', + 'ns', + $bucket, + 'my-org-a' + ); + $this->writeApi->write( + 'h2o_feet,location=coyote_creek level\\ water_level=5.0 5', + 'ns', + $bucket2, + 'my-org-a' + ); + $this->writeApi->write( + 'h2o_feet,location=coyote_creek level\\ water_level=6.0 6', + 'ns', + $bucket, + 'my-org-a' + ); $this->assertEquals(5, count($this->container)); $request = $this->container[0]['request']; - $this->assertEquals('http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', - strval($request->getUri())); + $this->assertEquals( + 'http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', + strval($request->getUri()) + ); $this->assertEquals('h2o_feet,location=coyote_creek level\\ water_level=1.0 1', $request->getBody()); $request = $this->container[1]['request']; - $this->assertEquals('http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=s', - strval($request->getUri())); + $this->assertEquals( + 'http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=s', + strval($request->getUri()) + ); $this->assertEquals('h2o_feet,location=coyote_creek level\\ water_level=2.0 2', $request->getBody()); $request = $this->container[2]['request']; - $this->assertEquals('http://localhost:8086/api/v2/write?org=my-org-a&bucket=my-bucket&precision=ns', - strval($request->getUri())); + $this->assertEquals( + 'http://localhost:8086/api/v2/write?org=my-org-a&bucket=my-bucket&precision=ns', + strval($request->getUri()) + ); $this->assertEquals("h2o_feet,location=coyote_creek level\\ water_level=3.0 3\n" . 'h2o_feet,location=coyote_creek level\\ water_level=4.0 4', $request->getBody()); $request = $this->container[3]['request']; - $this->assertEquals('http://localhost:8086/api/v2/write?org=my-org-a&bucket=my-bucket2&precision=ns', - strval($request->getUri())); + $this->assertEquals( + 'http://localhost:8086/api/v2/write?org=my-org-a&bucket=my-bucket2&precision=ns', + strval($request->getUri()) + ); $this->assertEquals('h2o_feet,location=coyote_creek level\\ water_level=5.0 5', $request->getBody()); $request = $this->container[4]['request']; - $this->assertEquals('http://localhost:8086/api/v2/write?org=my-org-a&bucket=my-bucket&precision=ns', - strval($request->getUri())); + $this->assertEquals( + 'http://localhost:8086/api/v2/write?org=my-org-a&bucket=my-bucket&precision=ns', + strval($request->getUri()) + ); $this->assertEquals('h2o_feet,location=coyote_creek level\\ water_level=6.0 6', $request->getBody()); } @@ -115,8 +153,10 @@ public function testFlushAllByCloseClient() $request = $this->mockHandler->getLastRequest(); - $this->assertEquals('http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', - strval($request->getUri())); + $this->assertEquals( + 'http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', + strval($request->getUri()) + ); $this->assertEquals("h2o_feet,location=coyote_creek level\\ water_level=1.0 1\n" . "h2o_feet,location=coyote_creek level\\ water_level=2.0 2\n" . 'h2o_feet,location=coyote_creek level\\ water_level=3.0 3', $request->getBody()); @@ -127,8 +167,11 @@ public function testRetryIntervalByConfig() $errorBody = '{"code":"temporarily unavailable","message":"Token is temporarily over quota.' . 'The Retry-After header describes when to try the write again."}'; - $this->mockHandler->append(new Response(429, ['X-Platform-Error-Code' => 'temporarily unavailable'], - $errorBody), new Response(204)); + $this->mockHandler->append(new Response( + 429, + ['X-Platform-Error-Code' => 'temporarily unavailable'], + $errorBody + ), new Response(204)); $this->writeApi->write('h2o_feet,location=coyote_creek water_level=1.0 1'); $this->writeApi->write('h2o_feet,location=coyote_creek water_level=2.0 2'); @@ -136,8 +179,10 @@ public function testRetryIntervalByConfig() $this->assertEquals(2, count($this->container)); $request = $this->mockHandler->getLastRequest(); - $this->assertEquals('http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', - strval($request->getUri())); + $this->assertEquals( + 'http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', + strval($request->getUri()) + ); $this->assertEquals("h2o_feet,location=coyote_creek water_level=1.0 1\n" . "h2o_feet,location=coyote_creek water_level=2.0 2", $request->getBody()->getContents()); } @@ -147,9 +192,12 @@ public function testRetryIntervalByHeader() $errorBody = '{"code":"temporarily unavailable","message":"Token is temporarily over quota.' . 'The Retry-After header describes when to try the write again."}'; - $this->mockHandler->append(new Response(429, ['X-Platform-Error-Code' => 'temporarily unavailable', + $this->mockHandler->append(new Response( + 429, + ['X-Platform-Error-Code' => 'temporarily unavailable', 'Retry-After' => '3'], - $errorBody), new Response(204)); + $errorBody + ), new Response(204)); $this->writeApi->write('h2o_feet,location=coyote_creek water_level=1.0 1'); $this->writeApi->write('h2o_feet,location=coyote_creek water_level=2.0 2'); @@ -157,8 +205,10 @@ public function testRetryIntervalByHeader() $this->assertEquals(2, count($this->container)); $request = $this->mockHandler->getLastRequest(); - $this->assertEquals('http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', - strval($request->getUri())); + $this->assertEquals( + 'http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', + strval($request->getUri()) + ); $this->assertEquals("h2o_feet,location=coyote_creek water_level=1.0 1\n" . "h2o_feet,location=coyote_creek water_level=2.0 2", $request->getBody()->getContents()); } @@ -173,7 +223,8 @@ public function testRetryIntervalMaxRetries() $this->mockHandler->append( new Response(429, ['X-Platform-Error-Code' => 'temporarily unavailable'], $errorBody), new Response(429, ['X-Platform-Error-Code' => 'temporarily unavailable'], $errorBody), - new Response(429, ['X-Platform-Error-Code' => 'temporarily unavailable'], $errorBody)); + new Response(429, ['X-Platform-Error-Code' => 'temporarily unavailable'], $errorBody) + ); $this->expectException(ApiException::class); @@ -195,7 +246,8 @@ public function testRetryCount() // retry new Response(429), // not called - new Response(429)); + new Response(429) + ); $this->writeApi->writeOptions->batchSize = 1; $this->writeApi->writeOptions->retryInterval = 1000; @@ -231,7 +283,8 @@ public function testRetryConnectionError() $this->mockHandler->append( new ConnectException($errorMessage, new Request('POST', '')), new ConnectException($errorMessage, new Request('POST', '')), - new ConnectException($errorMessage, new Request('POST', ''))); + new ConnectException($errorMessage, new Request('POST', '')) + ); $this->expectException(ApiException::class); @@ -243,8 +296,10 @@ public function testRetryConnectionError() public function testJitterInterval() { - $this->mockHandler->append(new Response(204), - new Response(204)); + $this->mockHandler->append( + new Response(204), + new Response(204) + ); $this->writeApi->writeOptions->jitterInterval = 2000; @@ -274,10 +329,14 @@ public function testRetryContainsMessage() $this->setUp("http://localhost:8086", "log_test.txt"); $this->mockHandler->append( - new Response(429, ['X-Platform-Error-Code' => 'temporarily unavailable', + new Response( + 429, + ['X-Platform-Error-Code' => 'temporarily unavailable', 'Retry-After' => '3'], - 'org 04014de4ed590000 has exceeded limited_write plan limit'), - new Response(204)); + 'org 04014de4ed590000 has exceeded limited_write plan limit' + ), + new Response(204) + ); $this->writeApi->write('h2o_feet,location=coyote_creek water_level=1.0 1'); $this->writeApi->write('h2o_feet,location=coyote_creek water_level=2.0 2'); diff --git a/tests/WriteApiIntegrationTest.php b/tests/WriteApiIntegrationTest.php index 27d8b169..c139ae81 100644 --- a/tests/WriteApiIntegrationTest.php +++ b/tests/WriteApiIntegrationTest.php @@ -22,7 +22,7 @@ class WriteApiIntegrationTest extends TestCase /** * @before */ - public function setUp() + public function setUp(): void { $this->client = new Client([ "url" => "http://localhost:8086", @@ -67,14 +67,15 @@ public function testWriteArray() public function testBatchingWrite() { $writeApi = $this->client->createWriteApi( - ["writeType"=>WriteType::BATCHING, 'batchSize'=>3]); + ["writeType"=>WriteType::BATCHING, 'batchSize'=>3] + ); $data = ['name' => 'cpu', 'tags' => ['host' => 'server_nl', 'region' => 'us'], 'fields' => ['internal' => 5, 'external' => 6], 'time' => microtime(true)]; - $writeApi->write($data,WritePrecision::MS); + $writeApi->write($data, WritePrecision::MS); $p1 = ['name' => "h2o", 'tags' => ['host' => 'aws', 'region' => 'us'], 'fields' => ['level' => 1, 'saturation' => 99], 'time' => 1]; $p2 = ['name' => "h2o", 'tags' => ['host' => 'aws', 'region' => 'us'], 'fields' => ['level' => 2, 'saturation' => 98], 'time' => 2]; diff --git a/tests/WriteApiTest.php b/tests/WriteApiTest.php index e45b8fc7..9786881b 100644 --- a/tests/WriteApiTest.php +++ b/tests/WriteApiTest.php @@ -17,7 +17,7 @@ class WriteApiTest extends BasicTest private const ID_TAG = "132-987-655"; private const CUSTOMER_TAG = "California Miner"; - public function setUp($url = "http://localhost:8086", $logFile = "php://output") + public function setUp($url = "http://localhost:8086", $logFile = "php://output"): void { parent::setUp($url, $logFile); @@ -31,8 +31,10 @@ public function testWriteLineProtocol() $request = $this->mockHandler->getLastRequest(); - $this->assertEquals('http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', - strval($request->getUri())); + $this->assertEquals( + 'http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', + strval($request->getUri()) + ); $this->assertEquals('h2o,location=west value=33i 15', $request->getBody()); } @@ -48,8 +50,10 @@ public function testWritePoint() $request = $this->mockHandler->getLastRequest(); - $this->assertEquals('http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', - strval($request->getUri())); + $this->assertEquals( + 'http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', + strval($request->getUri()) + ); $this->assertEquals('h2o,location=europe level=2i', $request->getBody()); } @@ -66,8 +70,10 @@ public function testWriteArray() $request = $this->mockHandler->getLastRequest(); - $this->assertEquals('http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', - strval($request->getUri())); + $this->assertEquals( + 'http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', + strval($request->getUri()) + ); $this->assertEquals('h2o,host=aws,region=us level=5i,saturation="99%" 123', $request->getBody()); } @@ -92,8 +98,10 @@ public function testWriteCollection() . "h2o,location=europe level=2i\n" . "h2o,host=aws,region=us level=5i,saturation=\"99%\" 123"; - $this->assertEquals('http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', - strval($request->getUri())); + $this->assertEquals( + 'http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', + strval($request->getUri()) + ); $this->assertEquals($expected, strval($request->getBody())); } @@ -104,8 +112,10 @@ public function testAuthorizationHeader() $request = $this->mockHandler->getLastRequest(); - $this->assertEquals('http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', - strval($request->getUri())); + $this->assertEquals( + 'http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', + strval($request->getUri()) + ); $this->assertEquals('Token my-token', implode(' ', $request->getHeaders()['Authorization'])); } @@ -128,15 +138,11 @@ public function testInfluxException() try { $this->writeApi->write('h2o,location=west value=33i 15'); $this->fail(); - } - catch (ApiException $e) - { + } catch (ApiException $e) { $this->assertEquals(400, $e->getCode()); $this->assertEquals('invalid', implode($e->getResponseHeaders()['X-Platform-Error-Code'])); $this->assertEquals($errorBody, strval($e->getResponseBody())); - } - catch (\Exception $e) - { + } catch (\Exception $e) { $this->fail(); } } @@ -157,10 +163,14 @@ public function testWritePointWithDefaultTags() $request = $this->mockHandler->getLastRequest(); - $this->assertEquals('http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', - strval($request->getUri())); - $this->assertEquals('h2o,customer=California\ Miner,data_center=LA,id=132-987-655,location=europe level=2i', - strval($request->getBody())); + $this->assertEquals( + 'http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', + strval($request->getUri()) + ); + $this->assertEquals( + 'h2o,customer=California\ Miner,data_center=LA,id=132-987-655,location=europe level=2i', + strval($request->getBody()) + ); } public function testWriteArrayWithDefaultTags() @@ -180,10 +190,14 @@ public function testWriteArrayWithDefaultTags() $request = $this->mockHandler->getLastRequest(); - $this->assertEquals('http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', - strval($request->getUri())); - $this->assertEquals('h2o,customer=California\ Miner,data_center=LA,host=aws,id=132-987-655,region=us level=5i,saturation="99%" 123', - strval($request->getBody())); + $this->assertEquals( + 'http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', + strval($request->getUri()) + ); + $this->assertEquals( + 'h2o,customer=California\ Miner,data_center=LA,host=aws,id=132-987-655,region=us level=5i,saturation="99%" 123', + strval($request->getBody()) + ); } public function testWriteCollectionWithDefaultTags() @@ -211,8 +225,10 @@ public function testWriteCollectionWithDefaultTags() . "h2o,customer=California\ Miner,data_center=LA,id=132-987-655,location=europe level=2i\n" . "h2o,customer=California\ Miner,data_center=LA,host=aws,id=132-987-655,region=us level=5i,saturation=\"99%\" 123"; - $this->assertEquals('http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', - strval($request->getUri())); + $this->assertEquals( + 'http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', + strval($request->getUri()) + ); $this->assertEquals($expected, strval($request->getBody())); } @@ -232,10 +248,14 @@ public function testWriteArrayWithoutTagsWithDefaultTags() $request = $this->mockHandler->getLastRequest(); - $this->assertEquals('http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', - strval($request->getUri())); - $this->assertEquals('h2o,customer=California\ Miner,data_center=LA,id=132-987-655 level=5i,saturation="99%" 123', - strval($request->getBody())); + $this->assertEquals( + 'http://localhost:8086/api/v2/write?org=my-org&bucket=my-bucket&precision=ns', + strval($request->getUri()) + ); + $this->assertEquals( + 'h2o,customer=California\ Miner,data_center=LA,id=132-987-655 level=5i,saturation="99%" 123', + strval($request->getBody()) + ); } public function testRetryCount() @@ -250,7 +270,8 @@ public function testRetryCount() // retry new Response(429), // not called - new Response(429)); + new Response(429) + ); $this->writeApi->writeOptions->retryInterval = 1000; $this->writeApi->writeOptions->maxRetries = 3; diff --git a/tests/WriteUdpTest.php b/tests/WriteUdpTest.php index 55906862..8775a0e4 100644 --- a/tests/WriteUdpTest.php +++ b/tests/WriteUdpTest.php @@ -108,5 +108,4 @@ public function testWriteCollection() . "h2o,host=aws,region=us level=5i,saturation=\"99%\" 123"; $this->assertEquals($expected, $buffer); } - }