Skip to content

Instantly share code, notes, and snippets.

@makomweb
Last active November 30, 2023 12:04
Show Gist options
  • Select an option

  • Save makomweb/7d1090984a99bbc4cc83b3dc2df74223 to your computer and use it in GitHub Desktop.

Select an option

Save makomweb/7d1090984a99bbc4cc83b3dc2df74223 to your computer and use it in GitHub Desktop.

Revisions

  1. makomweb renamed this gist Nov 30, 2023. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. makomweb created this gist Nov 27, 2023.
    100 changes: 100 additions & 0 deletions test.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,100 @@
    <?php

    declare(strict_types=1);

    namespace App\Tests\Unit\Playground;

    use Attribute;
    use PHPUnit\Framework\TestCase;
    use ReflectionAttribute;
    use ReflectionClass;
    use ReflectionProperty;

    class MyTest extends TestCase
    {
    public function testClass(): void
    {
    $reflection = new ReflectionClass(Thing::class);
    $data = self::getData($reflection);
    self::assertIsArray($data);
    }

    public function testObject(): void
    {
    $reflection = new ReflectionClass(new Thing(new Bam()));
    $data = self::getData($reflection);
    self::assertIsArray($data);
    }

    private static function getData(ReflectionClass $reflection): array
    {
    return [
    'attributes' => self::traverseAttributes($reflection->getAttributes()),
    'properties' => array_map(
    static fn(ReflectionProperty $p) => [
    'name' => $p->getName(),
    'type' => $p->getType()->getName(),
    'attributes' => self::traverseAttributes($p->getAttributes())
    ],
    $reflection->getProperties()
    ),
    ];
    }

    private static function traverseAttributes(array $attributes): array
    {
    return array_map(
    static fn (ReflectionAttribute $a) => [
    'name' => $a->getName(),
    'arguments' => $a->getArguments(),
    'target' => $a->getTarget(),
    'new_instance' => $a->newInstance(),
    ],
    $attributes
    );
    }
    }

    #[Attribute]
    class AttachedInteger
    {
    public int $value;

    public function __construct(int $value)
    {
    $this->value = $value;
    }
    }

    #[Attribute]
    class AttachedString
    {
    public string $value;

    public function __construct(string $value)
    {
    $this->value = $value;
    }
    }


    #[AttachedString(value: 'this is my baam!')]
    class Bam
    {
    #[AttachedString(value: 'this is my noise!')]
    public string $noise;
    }

    #[AttachedInteger(value: 1234)]
    class Thing
    {
    #[AttachedString(value: 'foobar')]
    public string $name;

    public Bam $bam;

    public function __construct(Bam $bam)
    {
    $this->bam = $bam;
    }
    }