|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * This file is part of the tarantool/phpunit-extras package. |
| 5 | + * |
| 6 | + * (c) Eugene Leonovich <[email protected]> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +declare(strict_types=1); |
| 13 | + |
| 14 | +namespace Tarantool\PhpUnit\Annotation; |
| 15 | + |
| 16 | +use PHPUnit\Exception; |
| 17 | +use PHPUnitExtras\Annotation\AnnotationExtension as BaseAnnotationExtension; |
| 18 | +use Tarantool\Client\Client; |
| 19 | + |
| 20 | +class AnnotationExtension extends BaseAnnotationExtension |
| 21 | +{ |
| 22 | + use Annotations; |
| 23 | + |
| 24 | + /** @var array<string, string|int|bool>|string */ |
| 25 | + private $clientConfig; |
| 26 | + |
| 27 | + /** @var Client|null */ |
| 28 | + private $client; |
| 29 | + |
| 30 | + /** |
| 31 | + * @param array<string, string|int|bool>|string $clientConfig |
| 32 | + */ |
| 33 | + public function __construct($clientConfig = 'tcp://127.0.0.1:3301') |
| 34 | + { |
| 35 | + $this->clientConfig = $clientConfig; |
| 36 | + } |
| 37 | + |
| 38 | + protected function getClient() : Client |
| 39 | + { |
| 40 | + if ($this->client) { |
| 41 | + return $this->client; |
| 42 | + } |
| 43 | + |
| 44 | + $config = $this->getClientConfig(); |
| 45 | + |
| 46 | + return $this->client = \is_string($config) |
| 47 | + ? Client::fromDsn($config) |
| 48 | + : Client::fromOptions($config); |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * @return array<string, string|int|bool>|string |
| 53 | + */ |
| 54 | + final protected function getClientConfig(bool $resolveEnvVars = true) |
| 55 | + { |
| 56 | + if (!$resolveEnvVars) { |
| 57 | + return $this->clientConfig; |
| 58 | + } |
| 59 | + |
| 60 | + if (\is_string($this->clientConfig)) { |
| 61 | + return self::resolveEnvValues($this->clientConfig); |
| 62 | + } |
| 63 | + |
| 64 | + $clientConfig = $this->clientConfig; |
| 65 | + foreach ($clientConfig as $key => $value) { |
| 66 | + $clientConfig[$key] = \is_string($value) ? self::resolveEnvValues($value) : $value; |
| 67 | + } |
| 68 | + |
| 69 | + return $clientConfig; |
| 70 | + } |
| 71 | + |
| 72 | + private static function resolveEnvValues(string $configValue) : string |
| 73 | + { |
| 74 | + return preg_replace_callback('/%env\((?P<name>.+?)\)%/', static function (array $matches) : string { |
| 75 | + if (false !== $value = getenv($matches['name'])) { |
| 76 | + return $value; |
| 77 | + } |
| 78 | + |
| 79 | + $errorMessage = sprintf('Environment variable "%s" does not exist', $matches['name']); |
| 80 | + throw new class($errorMessage) extends \RuntimeException implements Exception { |
| 81 | + }; |
| 82 | + }, $configValue); |
| 83 | + } |
| 84 | +} |
0 commit comments