RpTestUtil::mkdir()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 2
nc 2
nop 1
dl 0
loc 4
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Facile\OpenIDClient\ConformanceTest;
6
7
use Http\Client\Common\HttpMethodsClientInterface;
8
use Http\Discovery\Psr17FactoryDiscovery;
9
use Http\Discovery\Psr18ClientDiscovery;
10
use Psr\Http\Client\ClientInterface;
11
use Psr\Http\Message\RequestFactoryInterface;
12
use Psr\Http\Message\ResponseInterface;
13
14
class RpTestUtil
15
{
16
    /** @var ClientInterface */
17
    private $client;
18
19
    /** @var RequestFactoryInterface */
20
    private $requestFactory;
21
22
    /** @var string */
23
    private $logDir;
24
25
    public function __construct(
26
        ?ClientInterface $client = null,
27
        ?RequestFactoryInterface $requestFactory = null,
28
        string $logDir = __DIR__ . '/../log'
29
    )
30
    {
31
        $this->client = $client ?? Psr18ClientDiscovery::find();
32
        $this->requestFactory = $requestFactory ?? Psr17FactoryDiscovery::findRequestFactory();
33
        $this->logDir = $logDir;
34
    }
35
36
    private function mkdir(string $dirname): void
37
    {
38
        if (! \file_exists($dirname) && ! mkdir($concurrentDirectory = $dirname, 0777, true) && ! is_dir($concurrentDirectory)) {
39
            throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
40
        }
41
    }
42
43
    private function get(string $uri): ResponseInterface
44
    {
45
        $request = $this->requestFactory->createRequest('GET', $uri);
46
47
        return $this->client->sendRequest($request);
48
    }
49
50
    public function clearLogs(string $root, string $rpId): void
51
    {
52
        $response = $this->get($root . '/log/' . $rpId);
53
54
        if (! \preg_match('/Clear all test logs/', (string) $response->getBody())) {
55
            return;
56
        }
57
58
        $this->get($root . '/clear/' . $rpId);
59
    }
60
61
    public function downloadLogs(TestInfo $testInfo, string $profile, string $responseType): void
62
    {
63
        $response = $this->get($testInfo->getRpLogsUri());
64
65
        if (! \preg_match('/Download tar file/', (string) $response->getBody())) {
66
            return;
67
        }
68
69
        $logDir = $this->logDir . '/' . ltrim($profile, '@');
70
        $this->mkdir($logDir);
71
72
        $response = $this->get($testInfo->getRoot() . '/mktar/' . $testInfo->getRpUri());
73
        $handle = \fopen($logDir . '/log-' . $responseType . '.tar', 'wb+');
74
75
        while (! $response->getBody()->eof()) {
76
            \fwrite($handle, $response->getBody()->getContents());
77
        }
78
        \fclose($handle);
79
    }
80
}
81