Skip to content

Change result ArrayHelper::getValue(). #23

@terabytesoftw

Description

@terabytesoftw

What steps will reproduce the problem?

I have the following object of a query:

Yiisoft\ActiveRecord\Tests\Stubs\Order#1
(
    [Yiisoft\ActiveRecord\BaseActiveRecord:attributes] => [
        'id' => 1
        'customer_id' => 1
        'created_at' => 1325282384
        'total' => '110'
    ]
    [Yiisoft\ActiveRecord\BaseActiveRecord:oldAttributes] => [
        'id' => 1
        'customer_id' => 1
        'created_at' => 1325282384
        'total' => '110'
    ]
    [Yiisoft\ActiveRecord\BaseActiveRecord:related] => [
        'customer' => Yiisoft\ActiveRecord\Tests\Stubs\Customer#2
        (
            [status2] => null
            [sumTotal] => null
            [Yiisoft\ActiveRecord\BaseActiveRecord:attributes] => [
                'id' => 1
                'email' => 'user1@example.com'
                'name' => 'user1'
                'address' => 'address1'
                'status' => 1
                'profile_id' => 1
            ]
            [Yiisoft\ActiveRecord\BaseActiveRecord:oldAttributes] => [
                'id' => 1
                'email' => 'user1@example.com'
                'name' => 'user1'
                'address' => 'address1'
                'status' => 1
                'profile_id' => 1
            ]
            [Yiisoft\ActiveRecord\BaseActiveRecord:related] => []
            [Yiisoft\ActiveRecord\BaseActiveRecord:relationsDependencies] => []
        )
    ]
    [Yiisoft\ActiveRecord\BaseActiveRecord:relationsDependencies] => []
)

With the current method I cannot recover customer, since of course it is not a property and therefore does not iterate and return null.

if (strpos($key, '.') !== false) {
    foreach (explode('.', $key) as $part) {
        if (is_array($array)) {
            if (!array_key_exists($part, $array)) {
                return $default;
            }
            $array = $array[$part];
        } elseif (is_object($array)) {
            if (!property_exists($array, $part)) {
                return $default;
            }
            $array = $array->$part;
        }
    }

    return $array;
}

Previous method: It allowed the object to be iterated, recovering the propierty.

if (strpos($key, '.') !== false) {
    foreach (explode('.', $key) as $part) {
        if (!array_key_exists($part, $array)) {
            return $default;
        }
        $array = $array[$part];
    }
    return $array;
}

Off course \array_key_exist is deprecated for object, change for isset its work.

What is the expected result?

ArrayHelper::getValue($object, 'customer.id') return 1.

Additional info

Q A
Version 3.0
PHP version 7.4
Operating system Windows 10

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions