Parkour\Access::update PHP Method

update() public static method

Updates data at the given path.
See also: splitPath()
public static update ( array $data, array | string $path, callable $cb ) : mixed
$data array Data.
$path array | string Path.
$cb callable Callback to update the value.
return mixed Updated data.
    public static function update(array $data, $path, callable $cb)
    {
        $keys = self::splitPath($path);
        $current =& $data;
        foreach ($keys as $key) {
            if (!isset($current[$key])) {
                return $data;
            }
            $current =& $current[$key];
        }
        $current = call_user_func($cb, $current);
        return $data;
    }

Usage Example

 /**
  *
  */
 public function testUpdate()
 {
     $data = ['a' => 1, 'b' => ['c' => 2, 'd' => ['e' => 3]]];
     $expected = ['a' => 2, 'b' => ['c' => 2, 'd' => ['e' => 4]]];
     $increment = function ($value) {
         return $value + 1;
     };
     $result = Access::update($data, 'a', $increment);
     $result = Access::update($result, 'z', $increment);
     $result = Access::update($result, 'b.d.e', $increment);
     $this->assertEquals($expected, $result);
 }