ProviderConfig.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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\Di\Definition\PriorityDefinition;
  13. use Hyperf\Support\Composer;
  14. use function class_exists;
  15. use function is_string;
  16. use function method_exists;
  17. /**
  18. * Provider config allow the components set the configs to application.
  19. */
  20. class ProviderConfig
  21. {
  22. private static array $providerConfigs = [];
  23. /**
  24. * Load and merge all provider configs from components.
  25. * Notice that this method will cached the config result into a static property,
  26. * call ProviderConfig::clear() method if you want to reset the static property.
  27. */
  28. public static function load(): array
  29. {
  30. if (! static::$providerConfigs) {
  31. $providers = Composer::getMergedExtra('hyperf')['config'] ?? [];
  32. static::$providerConfigs = static::loadProviders($providers);
  33. }
  34. return static::$providerConfigs;
  35. }
  36. public static function clear(): void
  37. {
  38. static::$providerConfigs = [];
  39. }
  40. protected static function loadProviders(array $providers): array
  41. {
  42. $providerConfigs = [];
  43. foreach ($providers as $provider) {
  44. if (is_string($provider) && class_exists($provider) && method_exists($provider, '__invoke')) {
  45. $providerConfigs[] = (new $provider())();
  46. }
  47. }
  48. return static::merge(...$providerConfigs);
  49. }
  50. protected static function merge(...$arrays): array
  51. {
  52. if (empty($arrays)) {
  53. return [];
  54. }
  55. $result = array_merge_recursive(...$arrays);
  56. if (isset($result['dependencies'])) {
  57. $result['dependencies'] = [];
  58. foreach ($arrays as $item) {
  59. foreach ($item['dependencies'] ?? [] as $key => $value) {
  60. $depend = $result['dependencies'][$key] ?? null;
  61. if (! $depend instanceof PriorityDefinition) {
  62. $result['dependencies'][$key] = $value;
  63. continue;
  64. }
  65. if ($value instanceof PriorityDefinition) {
  66. $depend->merge($value);
  67. }
  68. }
  69. }
  70. }
  71. return $result;
  72. }
  73. }