Skip to content

Commit a353ed1

Browse files
authored
Improve TypeHinting (#3)
Signed-off-by: Lukas Kämmerling <lukas.kaemmerling@hetzner-cloud.de>
1 parent 09e7574 commit a353ed1

File tree

10 files changed

+100
-34
lines changed

10 files changed

+100
-34
lines changed

.github/workflows/checks.yml

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
name: Code Checks
2+
3+
on: [ push, pull_request ]
4+
5+
jobs:
6+
test:
7+
runs-on: ubuntu-latest
8+
strategy:
9+
fail-fast: true
10+
11+
name: Code Checks
12+
steps:
13+
- name: Checkout code
14+
uses: actions/checkout@v2
15+
16+
- name: Cache dependencies
17+
uses: actions/cache@v2
18+
with:
19+
path: ~/.composer/cache/files
20+
key: dependencies-code-checks
21+
22+
- name: Setup PHP
23+
uses: shivammathur/setup-php@v2
24+
with:
25+
php-version: 7.4
26+
coverage: none
27+
28+
- name: Install dependencies
29+
run: composer install --prefer-dist --no-interaction --no-suggest
30+
- name: Run PHP Code Sniffer
31+
run: ./vendor/bin/phpcs
32+
- name: Run PHPStan
33+
run: php vendor/bin/phpstan analyse --autoload-file tests/bootstrap.php

.github/workflows/tests.yml

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,5 @@ jobs:
3232

3333
- name: Install dependencies
3434
run: composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction --no-suggest
35-
- name: Run PHP Code Sniffer
36-
run: ./vendor/bin/phpcs
3735
- name: Execute tests
3836
run: vendor/bin/phpunit

composer.json

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,11 @@
99
},
1010
"require-dev": {
1111
"phpunit/phpunit": "^8.4",
12-
"squizlabs/php_codesniffer": "^3.5"
12+
"squizlabs/php_codesniffer": "^3.5",
13+
"phpstan/extension-installer": "^1.0",
14+
"phpstan/phpstan": "^0.12.50",
15+
"phpstan/phpstan-phpunit": "^0.12.16",
16+
"phpstan/phpstan-strict-rules": "^0.12.5"
1317
},
1418
"license": "Apache-2.0",
1519
"authors": [

examples/pushgateway.php

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,17 @@
55
use Prometheus\CollectorRegistry;
66
use Prometheus\Storage\Redis;
77
use PrometheusPushGateway\PushGateway;
8-
8+
use Prometheus\Storage\APC;
9+
use Prometheus\Storage\InMemory;
910
$adapter = $_GET['adapter'];
1011

1112
if ($adapter === 'redis') {
1213
Redis::setDefaultOptions(['host' => $_SERVER['REDIS_HOST'] ?? '127.0.0.1']);
13-
$adapter = new Prometheus\Storage\Redis();
14+
$adapter = new Redis();
1415
} elseif ($adapter === 'apc') {
15-
$adapter = new Prometheus\Storage\APC();
16+
$adapter = new APC();
1617
} elseif ($adapter === 'in-memory') {
17-
$adapter = new Prometheus\Storage\InMemory();
18+
$adapter = new InMemory();
1819
}
1920

2021
$registry = new CollectorRegistry($adapter);

php-fpm/Dockerfile

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
FROM php:7.2-fpm
1+
FROM php:7.4-fpm
22

3-
RUN pecl install redis-5.3.1 && docker-php-ext-enable redis
3+
RUN pecl install redis-5.3.2 && docker-php-ext-enable redis
44
RUN pecl install apcu-5.1.19 && docker-php-ext-enable apcu
55

66
COPY www.conf /usr/local/etc/php-fpm.d/

phpstan.neon.dist

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
parameters:
2+
level: 8
3+
paths:
4+
- src
5+
- tests
6+
reportUnmatchedIgnoredErrors: false
7+
ignoreErrors:
8+
-
9+
# REDIS stuff only runs with it available
10+
'#Constant REDIS_HOST not found\.#'

src/PrometheusPushGateway/PushGateway.php

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@
1313

1414
class PushGateway
1515
{
16+
const HTTP_PUT = "PUT";
17+
const HTTP_POST = "POST";
18+
const HTTP_DELETE = "DELETE";
1619
/**
1720
* @var string
1821
*/
@@ -26,9 +29,9 @@ class PushGateway
2629
/**
2730
* PushGateway constructor.
2831
* @param string $address (http|https)://host:port of the push gateway
29-
* @param ClientInterface $client
32+
* @param ClientInterface|null $client
3033
*/
31-
public function __construct($address, ClientInterface $client = null)
34+
public function __construct(string $address, ?ClientInterface $client = null)
3235
{
3336
$this->address = strpos($address, 'http') === false ? 'http://' . $address : $address;
3437
$this->client = $client ?? new Client();
@@ -39,50 +42,50 @@ public function __construct($address, ClientInterface $client = null)
3942
* Uses HTTP PUT.
4043
* @param CollectorRegistry $collectorRegistry
4144
* @param string $job
42-
* @param array $groupingKey
45+
* @param array<string> $groupingKey
4346
* @throws GuzzleException
4447
*/
4548
public function push(CollectorRegistry $collectorRegistry, string $job, array $groupingKey = []): void
4649
{
47-
$this->doRequest($collectorRegistry, $job, $groupingKey, 'put');
50+
$this->doRequest($collectorRegistry, $job, $groupingKey, self::HTTP_PUT);
4851
}
4952

5053
/**
5154
* Pushes all metrics in a Collector, replacing only previously pushed metrics of the same name and job.
5255
* Uses HTTP POST.
5356
* @param CollectorRegistry $collectorRegistry
54-
* @param $job
55-
* @param $groupingKey
57+
* @param string $job
58+
* @param array<string> $groupingKey
5659
* @throws GuzzleException
5760
*/
5861
public function pushAdd(CollectorRegistry $collectorRegistry, string $job, array $groupingKey = []): void
5962
{
60-
$this->doRequest($collectorRegistry, $job, $groupingKey, 'post');
63+
$this->doRequest($collectorRegistry, $job, $groupingKey, self::HTTP_POST);
6164
}
6265

6366
/**
6467
* Deletes metrics from the Push Gateway.
6568
* Uses HTTP POST.
6669
* @param string $job
67-
* @param array $groupingKey
70+
* @param array<string> $groupingKey
6871
* @throws GuzzleException
6972
*/
7073
public function delete(string $job, array $groupingKey = []): void
7174
{
72-
$this->doRequest(null, $job, $groupingKey, 'delete');
75+
$this->doRequest(null, $job, $groupingKey, self::HTTP_DELETE);
7376
}
7477

7578
/**
7679
* @param CollectorRegistry|null $collectorRegistry
7780
* @param string $job
78-
* @param array $groupingKey
81+
* @param array<string> $groupingKey
7982
* @param string $method
8083
* @throws GuzzleException
8184
*/
82-
private function doRequest(?CollectorRegistry $collectorRegistry, string $job, array $groupingKey, $method): void
85+
private function doRequest(?CollectorRegistry $collectorRegistry, string $job, array $groupingKey, string $method): void
8386
{
8487
$url = $this->address . "/metrics/job/" . $job;
85-
if (!empty($groupingKey)) {
88+
if ($groupingKey !== []) {
8689
foreach ($groupingKey as $label => $value) {
8790
$url .= "/" . $label . "/" . $value;
8891
}
@@ -96,13 +99,13 @@ private function doRequest(?CollectorRegistry $collectorRegistry, string $job, a
9699
'timeout' => 20,
97100
];
98101

99-
if ($method != 'delete') {
102+
if ($method !== self::HTTP_DELETE && $collectorRegistry !== null) {
100103
$renderer = new RenderTextFormat();
101104
$requestOptions['body'] = $renderer->render($collectorRegistry->getMetricFamilySamples());
102105
}
103106
$response = $this->client->request($method, $url, $requestOptions);
104107
$statusCode = $response->getStatusCode();
105-
if (!in_array($statusCode, [200, 202])) {
108+
if (!in_array($statusCode, [200, 202], true)) {
106109
$msg = "Unexpected status code "
107110
. $statusCode
108111
. " received from push gateway "

tests/Test/BlackBoxPushGatewayTest.php

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
<?php
22

3+
declare(strict_types=1);
4+
35
namespace Test;
46

57
use GuzzleHttp\Client;
@@ -13,7 +15,7 @@ class BlackBoxPushGatewayTest extends TestCase
1315
/**
1416
* @test
1517
*/
16-
public function pushGatewayShouldWork()
18+
public function pushGatewayShouldWork(): void
1719
{
1820
$adapter = new InMemory();
1921
$registry = new CollectorRegistry($adapter);
@@ -26,7 +28,7 @@ public function pushGatewayShouldWork()
2628

2729
$httpClient = new Client();
2830
$metrics = $httpClient->get("http://pushgateway:9091/metrics")->getBody()->getContents();
29-
$this->assertStringContainsString(
31+
self::assertStringContainsString(
3032
'# HELP test_some_counter it increases
3133
# TYPE test_some_counter counter
3234
test_some_counter{instance="foo",job="my_job",type="blue"} 6',
@@ -38,7 +40,7 @@ public function pushGatewayShouldWork()
3840

3941
$httpClient = new Client();
4042
$metrics = $httpClient->get("http://pushgateway:9091/metrics")->getBody()->getContents();
41-
$this->assertStringNotContainsString(
43+
self::assertStringNotContainsString(
4244
'# HELP test_some_counter it increases
4345
# TYPE test_some_counter counter
4446
test_some_counter{instance="foo",job="my_job",type="blue"} 6',

tests/Test/PrometheusPushGateway/PushGatewayTest.php

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
<?php
22

3+
declare(strict_types=1);
4+
35
namespace Test\PrometheusPushGateway;
46

57
use GuzzleHttp\Client;
@@ -43,7 +45,7 @@ public function validResponseShouldNotThrowException(): void
4345
*/
4446
public function invalidResponseShouldThrowRuntimeException(): void
4547
{
46-
$this->expectException(\RuntimeException::class);
48+
self::expectException(\RuntimeException::class);
4749

4850
$mockedCollectorRegistry = $this->createMock(CollectorRegistry::class);
4951
$mockedCollectorRegistry->method('getMetricFamilySamples')->with()->willReturn([
@@ -81,6 +83,11 @@ public function clientGetsDefinedIfNotSpecified(): void
8183
* @test
8284
*
8385
* @dataProvider validAddressAndRequestsProvider
86+
* @param string $address
87+
* @param string $scheme
88+
* @param string $host
89+
* @param int $port
90+
* @throws \GuzzleHttp\Exception\GuzzleException
8491
*/
8592
public function validAddressShouldCreateValidRequests(string $address, string $scheme, string $host, int $port): void
8693
{
@@ -97,15 +104,21 @@ public function validAddressShouldCreateValidRequests(string $address, string $s
97104

98105
$pushGateway = new PushGateway($address, $client);
99106
$pushGateway->push($mockedCollectorRegistry, 'foo');
100-
101-
$uri = $mockHandler->getLastRequest()->getUri();
102-
$this->assertEquals($scheme, $uri->getScheme());
103-
$this->assertEquals($host, $uri->getHost());
104-
$this->assertEquals($port, $uri->getPort());
105-
$this->assertEquals('/metrics/job/foo', $uri->getPath());
107+
if ($mockHandler->getLastRequest() !== null) {
108+
$uri = $mockHandler->getLastRequest()->getUri();
109+
self::assertEquals($scheme, $uri->getScheme());
110+
self::assertEquals($host, $uri->getHost());
111+
self::assertEquals($port, $uri->getPort());
112+
self::assertEquals('/metrics/job/foo', $uri->getPath());
113+
} else {
114+
self::fail("No request performed");
115+
}
106116
}
107117

108-
public function validAddressAndRequestsProvider()
118+
/**
119+
* @return array[]
120+
*/
121+
public function validAddressAndRequestsProvider(): array
109122
{
110123
return [
111124
['foo.bar:123', 'http', 'foo.bar', 123],

tests/bootstrap.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
<?php
22

3+
declare(strict_types=1);
4+
35
error_reporting(-1);
46
date_default_timezone_set('UTC');
57
$autoload = __DIR__ . '/../vendor/autoload.php';

0 commit comments

Comments
 (0)