Last active
November 27, 2023 11:00
-
-
Save ziadoz/ec06c0165f0a88ad4b0448203e15a535 to your computer and use it in GitHub Desktop.
Using PHP 8.0 Attributes/Annotations To Decorate Functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Attributes (AKA Annotations). | |
#[Attribute(Attribute::IS_REPEATABLE | Attribute::TARGET_FUNCTION)] | |
class CharDecoratorAttribute | |
{ | |
public function __construct(protected string $char) // Constructor Property Promotion | |
{ | |
} | |
public function decorate(Closure $fn): Closure | |
{ | |
return fn(string $str): string => $this->char . $fn($str) . $this->char; | |
} | |
} | |
// Function decorated using Attributes with Named Parameters. | |
$xmas = | |
#[CharDecoratorAttribute(char: '🎄')] | |
#[CharDecoratorAttribute(char: '⛄️')] | |
#[CharDecoratorAttribute(char: '🎅')] | |
fn (string $str): string => $str; | |
// Use Reflection to get and instantiate Attributes, and then decorate the function. | |
function decorateFn(Closure $fn) { | |
return array_reduce( | |
array: (new ReflectionFunction($fn))->getAttributes(CharDecoratorAttribute::class), | |
callback: fn($fn, $attribute) => $attribute->newInstance()->decorate($fn), | |
initial: $fn, | |
); | |
} | |
echo decorateFn($xmas)(str: 'Merry Christmas'); // 🎅⛄️🎄Merry Christmas🎄⛄️🎅 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment