ConfigFactory.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Config;
  12. use Hyperf\Collection\Arr;
  13. use Psr\Container\ContainerInterface;
  14. use Symfony\Component\Finder\Finder;
  15. class ConfigFactory
  16. {
  17. public function __invoke(ContainerInterface $container)
  18. {
  19. $configPath = BASE_PATH . '/config';
  20. $config = $this->readConfig($configPath . '/config.php');
  21. $autoloadConfig = $this->readPaths([$configPath . '/autoload']);
  22. $merged = array_merge_recursive(ProviderConfig::load(), $config, ...$autoloadConfig);
  23. return new Config($merged);
  24. }
  25. private function readConfig(string $configPath): array
  26. {
  27. $config = [];
  28. if (file_exists($configPath) && is_readable($configPath)) {
  29. $config = require $configPath;
  30. }
  31. return is_array($config) ? $config : [];
  32. }
  33. private function readPaths(array $paths): array
  34. {
  35. $configs = [];
  36. $finder = new Finder();
  37. $finder->files()->in($paths)->name('*.php');
  38. foreach ($finder as $file) {
  39. $config = [];
  40. $key = implode('.', array_filter([
  41. str_replace('/', '.', $file->getRelativePath()),
  42. $file->getBasename('.php'),
  43. ]));
  44. Arr::set($config, $key, require $file->getRealPath());
  45. $configs[] = $config;
  46. }
  47. return $configs;
  48. }
  49. }