Bind.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. namespace Illuminate\Container\Attributes;
  3. use Attribute;
  4. use BackedEnum;
  5. use InvalidArgumentException;
  6. use UnitEnum;
  7. #[Attribute(Attribute::TARGET_CLASS | Attribute::IS_REPEATABLE)]
  8. class Bind
  9. {
  10. /**
  11. * The concrete class to bind to.
  12. *
  13. * @var class-string
  14. */
  15. public string $concrete;
  16. /**
  17. * The environments the binding should apply for.
  18. *
  19. * @var non-empty-array<int, string>
  20. */
  21. public array $environments = [];
  22. /**
  23. * Create a new attribute instance.
  24. *
  25. * @param class-string $concrete
  26. * @param non-empty-array<int, \BackedEnum|\UnitEnum|non-empty-string>|non-empty-string|\UnitEnum $environments
  27. *
  28. * @throws \InvalidArgumentException
  29. */
  30. public function __construct(
  31. string $concrete,
  32. string|array|UnitEnum $environments = ['*'],
  33. ) {
  34. $environments = array_filter(is_array($environments) ? $environments : [$environments]);
  35. if ($environments === []) {
  36. throw new InvalidArgumentException('The environment property must be set and cannot be empty.');
  37. }
  38. $this->concrete = $concrete;
  39. $this->environments = array_map(fn ($environment) => match (true) {
  40. $environment instanceof BackedEnum => $environment->value,
  41. $environment instanceof UnitEnum => $environment->name,
  42. default => $environment,
  43. }, $environments);
  44. }
  45. }