1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\DependencyInjection;
4:
5: use Attribute;
6: use PHPStan\ShouldNotHappenException;
7: use function is_array;
8:
9: /**
10: * Registers the class with the wrapped attribute, but adds the tags only when the condition is met:
11: * the rule tag for RegisteredRule, the collector tag for RegisteredCollector,
12: * and the tags of the implemented extension interfaces for AutowiredService.
13: * The service is always registered so that it can still be autowired.
14: *
15: * The condition has the same syntax as values in the conditionalTags config section:
16: * a parameter reference like '%featureToggles.foo%', its negation 'not(%featureToggles.foo%)',
17: * or a list of them that all must be met.
18: *
19: * Works thanks to https://github.com/ondrejmirtes/composer-attribute-collector
20: * and AutowiredAttributeServicesExtension, and in the attributeServicesDirectories
21: * config section thanks to AttributeServicesDiscoverer.
22: *
23: * @api
24: */
25: #[Attribute(flags: Attribute::TARGET_CLASS)]
26: final class Conditional
27: {
28:
29: public AutowiredService|RegisteredCollector|RegisteredRule $attribute;
30:
31: /**
32: * On PHP < 8.1, simple-downgrader writes `new` in attribute arguments as the array,
33: * and composer-attribute-collector turns it back into the object in vendor/attributes.php.
34: * Code running on PHP 8.0 in the attributeServicesDirectories section can write the array by hand,
35: * AttributeServicesDiscoverer turns it into the object.
36: *
37: * @api
38: * @param AutowiredService|RegisteredCollector|RegisteredRule|array{
39: * 'olvlvl\ComposerAttributeCollector\NewExpression': array{
40: * class-string<AutowiredService>,
41: * array{0?: string|null, 1?: string|null, 2?: true|list<class-string>|class-string, 3?: bool}
42: * |array{name?: string|null, factory?: string|null, as?: true|list<class-string>|class-string, autoTag?: bool},
43: * }|array{
44: * class-string<RegisteredCollector>|class-string<RegisteredRule>,
45: * array{int}|array{level: int},
46: * },
47: * } $attribute
48: * @param string|non-empty-list<string> $if
49: */
50: public function __construct(
51: AutowiredService|RegisteredCollector|RegisteredRule|array $attribute,
52: public string|array $if,
53: )
54: {
55: if (is_array($attribute)) {
56: throw new ShouldNotHappenException('The attribute should have been instantiated in vendor/attributes.php.');
57: }
58:
59: $this->attribute = $attribute;
60: }
61:
62: }
63: