Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
77.78% covered (warning)
77.78%
7 / 9
0.00% covered (danger)
0.00%
0 / 1
CRAP
0.00% covered (danger)
0.00%
0 / 1
TestKeys
77.78% covered (warning)
77.78%
7 / 9
0.00% covered (danger)
0.00%
0 / 1
7.54
0.00% covered (danger)
0.00%
0 / 1
 pair
77.78% covered (warning)
77.78%
7 / 9
0.00% covered (danger)
0.00%
0 / 1
7.54
1<?php
2
3declare(strict_types=1);
4
5namespace LambdaTwelve\OneRecord\Testing;
6
7use RuntimeException;
8
9/**
10 * RSA key pairs for tests, generated once per process: key generation is the
11 * slow part of these tests, and the keys carry no secret worth protecting.
12 */
13final class TestKeys
14{
15    /** @var array<string, array{private: string, public: string}> */
16    private static array $pairs = [];
17
18    /**
19     * @return array{private: string, public: string}
20     */
21    public static function pair(string $name = 'default'): array
22    {
23        if (!isset(self::$pairs[$name])) {
24            $key = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]);
25            if ($key === false || !openssl_pkey_export($key, $private)) {
26                throw new RuntimeException('Cannot generate a test key.');
27            }
28            $details = openssl_pkey_get_details($key);
29            if ($details === false || !\is_string($details['key'] ?? null) || !\is_string($private)) {
30                throw new RuntimeException('Cannot read the test key.');
31            }
32            self::$pairs[$name] = ['private' => $private, 'public' => $details['key']];
33        }
34
35        return self::$pairs[$name];
36    }
37}