Utility classes for PHP

1.8.3 2024-04-02 16:49 UTC

This package is auto-updated.

Last update: 2024-12-03 05:54:35 UTC


README

Latest Stable Version Minimum PHP Version License: MIT Scrutinizer Code Quality

util

Utility classes for PHP

Installation

Install library, using Composer:

composer require bingo-soft/util

Proxy class

/* Original class */

interface BusinessServiceInterface
{
}

class BusinessServiceImpl
{
    public function doSomething(int $id, string $name)
    {
        return "$id - $name";
    }
}

/* Handler */

use Util\Proxy\MethodHandlerInterface;

class DoSomethingMethodHandler implements MethodHandlerInterface
{
    public function invoke($proxy, \ReflectionMethod $thisMethod, \ReflectionMethod $proceed, array $args)
    {
        return 'prepend - ' . $proceed->invoke($proxy, ...$args);
    }
}

/* Custom proxy factory*/

use Util\Proxy\{
    MethodHandlerInterface,
    ProxyFactory
};

class MyProxyFactory
{
    public static function createProxy(string $type, MethodHandlerInterface $method, array $args = [])
    {
        $enhancer = new ProxyFactory();
        $enhancer->setSuperclass($type);
        $enhancer->setInterfaces([ BusinessServiceInterface::class ]);
        return $enhancer->create($args);
    }
}

/* Creation and test of proxy class*/

$method = new DoSomethingMethodHandler();
$proxy = MyProxyFactory::createProxy(BusinessServiceImpl::class, $method);
$proxy->setHandler($method);
echo $proxy->doSomething(1, "curitis"); // will print "prepend - 1 - curitis"

Enhanced reflection

/* Set nested property */

use Tests\Domain\Misc\RichType;
use Util\Reflection\SystemMetaObject;

$rich = new RichType();
$meta = SystemMetaObject::forObject($rich);
$meta->setValue("richType.richField", "foo");

echo $meta->getValue("richType.richField"); // new RichType( richType => new RichType ( richField => "foo" )) 

/* Create meta object from array */

$map = [];
$metaMap = SystemMetaObject::forObject($map);
$metaMap->setValue("id", "100");
$metaMap->setValue("name.first", "Clinton");
print_r($map); // [ "id" => 100, "name" => [ "first" => "Clinton" ]]

Running tests

./vendor/bin/phpunit ./tests