|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * Copyright © 2016-present Spryker Systems GmbH. All rights reserved. |
| 5 | + * Use of this software requires acceptance of the Evaluation License Agreement. See LICENSE file. |
| 6 | + */ |
| 7 | + |
| 8 | +namespace Spryker\Zed\Development\Business\Phpstan\Config; |
| 9 | + |
| 10 | +use InvalidArgumentException; |
| 11 | +use Nette\DI\Config\Adapter; |
| 12 | +use RuntimeException; |
| 13 | + |
| 14 | +class PhpstanConfigFileSaver implements PhpstanConfigFileSaverInterface |
| 15 | +{ |
| 16 | + /** |
| 17 | + * @var string |
| 18 | + */ |
| 19 | + protected const ERROR_CANNOT_WRITE_FILE = "Cannot write file '%s'."; |
| 20 | + |
| 21 | + /** |
| 22 | + * @var string |
| 23 | + */ |
| 24 | + protected const ERROR_UNKNOWN_FILE_EXTENSION = "Unknown file extension '%s'."; |
| 25 | + |
| 26 | + /** |
| 27 | + * @var array<string, string> |
| 28 | + */ |
| 29 | + protected array $fileAdapters; |
| 30 | + |
| 31 | + /** |
| 32 | + * @param array<string, string> $fileAdapters |
| 33 | + */ |
| 34 | + public function __construct(array $fileAdapters = []) |
| 35 | + { |
| 36 | + $this->fileAdapters = $fileAdapters; |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * @param string $configFilePath |
| 41 | + * @param array<mixed> $data |
| 42 | + * |
| 43 | + * @throws \RuntimeException |
| 44 | + * |
| 45 | + * @return void |
| 46 | + */ |
| 47 | + public function save(string $configFilePath, array $data): void |
| 48 | + { |
| 49 | + if (file_put_contents($configFilePath, $this->getAdapter($configFilePath)->dump($data)) === false) { |
| 50 | + throw new RuntimeException(sprintf(static::ERROR_CANNOT_WRITE_FILE, $configFilePath)); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * @param string $filePath |
| 56 | + * |
| 57 | + * @throws \InvalidArgumentException |
| 58 | + * |
| 59 | + * @return \Nette\DI\Config\Adapter |
| 60 | + */ |
| 61 | + protected function getAdapter(string $filePath): Adapter |
| 62 | + { |
| 63 | + $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION)); |
| 64 | + if (!isset($this->fileAdapters[$extension])) { |
| 65 | + throw new InvalidArgumentException(sprintf(static::ERROR_UNKNOWN_FILE_EXTENSION, $filePath)); |
| 66 | + } |
| 67 | + |
| 68 | + if ($this->fileAdapters[$extension] instanceof Adapter) { |
| 69 | + return $this->fileAdapters[$extension]; |
| 70 | + } |
| 71 | + |
| 72 | + /** @var \Nette\DI\Config\Adapter $adapter */ |
| 73 | + $adapter = new $this->fileAdapters[$extension](); |
| 74 | + |
| 75 | + return $adapter; |
| 76 | + } |
| 77 | +} |
0 commit comments