Class luya\helpers\ObjectHelper

Inheritanceluya\helpers\ObjectHelper
Available since version1.0.0
Source Code https://github.com/luyadev/luya/blob/master/core/helpers/ObjectHelper.php

Helper methods when dealing with Objects.

Public Methods

Hide inherited methods

Method Description Defined By
callMethodSanitizeArguments() Call a method and ensure arguments. luya\helpers\ObjectHelper
getActions() Get all actions from a given controller. luya\helpers\ObjectHelper
getControllers() Get all controllers for a given luya Module luya\helpers\ObjectHelper
isInstanceOf() Checks a given variable if its an instance of an element in the $instances list. luya\helpers\ObjectHelper
isTraitInstanceOf() Check whether a given object contains a trait. luya\helpers\ObjectHelper
toArray() Convert Object to Array luya\helpers\ObjectHelper
traitsList() Get an array with all traits for a given object luya\helpers\ObjectHelper

Method Details

Hide inherited methods

callMethodSanitizeArguments() public static method

Call a method and ensure arguments.

Call a class method with arguments and verify the arguments if they are in the list of method arguments or not.

ObjectHelper::callMethodSanitizeArguments(new MyClass(), 'methodToCall', ['paramName' => 'paramValue']);

The response is the return value from the called method of the object.

public static mixed callMethodSanitizeArguments ( $object, $method, array $argumentsList = [] )
$object object

The class object where the method must be found.

$method string

The class method to call inside the object.

$argumentsList array

A massiv assigned list of array items, where the key is bind to the method argument and the value to be passed in the method on call.

throws luya\Exception

Throws an exception if a argument coult not be found.

                public static function callMethodSanitizeArguments($object, $method, array $argumentsList = [])
{
    // get class reflection object
    $reflection = new ReflectionMethod($object, $method);
    // array where the sanitized arguemnts will be stored
    $methodArgs = [];
    foreach ($reflection->getParameters() as $param) {
        // add the argument into the method list when existing
        if (array_key_exists($param->name, $argumentsList)) {
            $methodArgs[] = $argumentsList[$param->name];
        }
        // check if the provided arguemnt is optional or not
        if (!$param->isOptional() && !array_key_exists($param->name, $argumentsList)) {
            throw new Exception(sprintf("The argument '%s' is required for method '%s' in class '%s'.", $param->name, $method, get_class($object)));
        }
    }
    return call_user_func_array([$object, $method], $methodArgs);
}

            
getActions() public static method (available since version 1.0.19)

Get all actions from a given controller.

public static array getActions ( yii\base\Controller $controller )
$controller yii\base\Controller

                public static function getActions(Controller $controller)
{
    $actions = array_keys($controller->actions());
    $class = new ReflectionClass($controller);
    foreach ($class->getMethods() as $method) {
        $name = $method->getName();
        if ($name !== 'actions' && $method->isPublic() && !$method->isStatic() && strncmp($name, 'action', 6) === 0) {
            $actions[] = Inflector::camel2id(substr($name, 6), '-', true);
        }
    }
    sort($actions);
    return array_unique($actions);
}

            
getControllers() public static method (available since version 1.0.19)

Get all controllers for a given luya Module

public static array getControllers ( luya\base\Module $module )
$module luya\base\Module

                public static function getControllers(Module $module)
{
    $files = [];
    try { // https://github.com/yiisoft/yii2/blob/master/framework/base/Module.php#L253
        if (is_dir($module->controllerPath)) {
            foreach (FileHelper::findFiles($module->controllerPath) as $file) {
                $files[self::fileToName($module->controllerPath, $file)] = $file;
            }
        }
    } catch (InvalidParamException $e) {
    };
    $staticPath = $module::staticBasePath() . DIRECTORY_SEPARATOR . 'controllers';
    if (is_dir($staticPath)) {
        foreach (FileHelper::findFiles($staticPath) as $file) {
            $files[self::fileToName($staticPath, $file)] = $file;
        }
    }
    
    return $files;
}

            
isInstanceOf() public static method (available since version 1.0.3)

Checks a given variable if its an instance of an element in the $instances list.

$object = new \Exception();

ObjectHelper::isInstanceOf($object, '\Exception');

In order to check if an object is at least an instance of one given resourcese use:

ObjectHelper::isInstanceOf($object, ['not\this\Object', 'maybe\this\Object', '\Exception']);

If at least one of the given exception names in the array is an instance of the given object, true is returned.

public static boolean isInstanceOf ( $object, $haystack, $throwException true )
$object object

The object to type check against haystack.

$haystack string|array|object

A list of classes, a string for a given class, or an object.

$throwException boolean

Whether an exception should be thrown or not.

throws luya\Exception

                public static function isInstanceOf($object, $haystack, $throwException = true)
{
    // if instances is an object (compare object directly) we have to get the class name to compare with instanceof later
    if (is_object($haystack)) {
        $haystack = get_class($haystack);
    }
    
    $haystack = (array) $haystack;
    
    foreach ($haystack as $class) {
        if ($object instanceof $class) {
            return true;
        }
    }
    
    if ($throwException) {
        throw new Exception("The given object must be an instance of: " . implode(",", $haystack));
    }
    
    return false;
}

            
isTraitInstanceOf() public static method (available since version 1.0.17)

Check whether a given object contains a trait.

trait XYZ {

}

class ABC {
   use XYZ;
}

$object = new ABC();

ObjectHelper::isTraitInstanceOf($object, XYZ::class);
public static boolean isTraitInstanceOf ( $object, $haystack )
$object object
$haystack string|array|object

                public static function isTraitInstanceOf($object, $haystack)
{
    $traits = static::traitsList($object);
    // if its an object, the all traits for the given object.
    if (is_object($haystack)) {
        $haystack = static::traitsList($haystack);
    }
    foreach ((array) $haystack as $stack) {
        if (in_array($stack, $traits)) {
            return true;
        }
    }
    return false;
}

            
toArray() public static method

Convert Object to Array

public static array toArray ( $object )
$object object

                public static function toArray($object)
{
    return (array) $object;
}

            
traitsList() public static method (available since version 1.0.17)

Get an array with all traits for a given object

See also https://www.php.net/manual/en/function.class-uses.php#122427.

public static array traitsList ( $object, $autoload true )
$object object
$autoload boolean

                public static function traitsList($object, $autoload = true)
{
    $traits = [];
    // Get traits of all parent classes
    do {
        $traits = array_merge(class_uses($object, $autoload), $traits);
    } while ($object = get_parent_class($object));
    // Get traits of all parent traits
    $traitsToSearch = $traits;
    while (!empty($traitsToSearch)) {
        $newTraits = class_uses(array_pop($traitsToSearch), $autoload);
        $traits = array_merge($newTraits, $traits);
        $traitsToSearch = array_merge($newTraits, $traitsToSearch);
    };
    foreach ($traits as $trait => $same) {
        $traits = array_merge(class_uses($trait, $autoload), $traits);
    }
    return $traits;
}