judahnator/trait-aware

Makes your classes aware of the traits they use

v1.0.1 2019-01-15 18:05 UTC

README

pipeline status

This package, quite simply, allows you to find all the traits a class uses recursively. It was inspired by a snippet added to this comment on the php.net documentation.

Installation

Use composer.

composer install judahnator/trait-aware

Usage

This library provides a function you may use that is very similar to the class_uses() function, except it is recursive including both parent classes and trait traits.

You may also "use" a trait \judahnator\TraitAware\TraitAware. It provides a public static getTraits() method which will return all the traits that class uses.

Examples

trait foo 
{
}
trait bar
{
    use foo;
}
class baz
{
    use bar, \judahnator\TraitAware\TraitAware;
}
class bing extends baz
{
}

class_uses(baz::class);
// can see bar and the TraitAware traits, but not bar
[
    "bar" => "bar",
    "judahnator\TraitAware\TraitAware" => "judahnator\TraitAware\TraitAware",
];

class_uses(bing::class);
// can not see any traits
[];

class_uses_deep(bing::class);
// can see foo, plus all the traits used by the baz class
[
    "foo" => "foo",
    "bar" => "bar",
    "judahnator\TraitAware\TraitAware" => "judahnator\TraitAware\TraitAware",
];

baz::getTraits();
// same as above but just the values
[
    "foo",
    "bar",
    "judahnator\TraitAware\TraitAware",
];