Completed
Push — master ( 7cb054...584ba8 )
by Tim
44:11 queued 26:38
created

Extractor   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 54
rs 10
wmc 10
lcom 1
cbo 1
1
<?php
2
/*
3
 * Copyright (c) Ouzo contributors, http://ouzoframework.org
4
 * This file is made available under the MIT License (view the LICENSE file for more information).
5
 */
6
namespace Ouzo\Utilities;
7
8
use ArrayAccess;
9
use BadMethodCallException;
10
11
/**
12
 * Sample usage:
13
 *
14
 * <code>
15
 *  $cities = Arrays::map($users, Functions::extract()->getAddress('home')->city);
16
 * </code>
17
 */
18
class Extractor implements ArrayAccess
19
{
20
    private $_operations = array();
21
22
    public function __get($field)
23
    {
24
        $this->_operations[] = function ($input) use ($field) {
25
            return Objects::getValue($input, $field);
26
        };
27
        return $this;
28
    }
29
30
    public function __call($name, $arguments)
31
    {
32
        $this->_operations[] = function ($input) use ($name, $arguments) {
33
            return call_user_func_array(array($input, $name), $arguments);
34
        };
35
        return $this;
36
    }
37
38
    public function __invoke($input)
39
    {
40
        foreach ($this->_operations as $operation) {
41
            $input = $operation($input);
42
            if ($input === null) {
43
                return null;
44
            }
45
        }
46
        return $input;
47
    }
48
49
    public function offsetGet($offset)
50
    {
51
        $this->_operations[] = function ($input) use ($offset) {
52
            return isset($input[$offset]) ? $input[$offset] : null;
53
        };
54
        return $this;
55
    }
56
57
    public function offsetExists($offset)
58
    {
59
        throw new BadMethodCallException();
60
    }
61
62
    public function offsetSet($offset, $value)
63
    {
64
        throw new BadMethodCallException();
65
    }
66
67
    public function offsetUnset($offset)
68
    {
69
        throw new BadMethodCallException();
70
    }
71
}
72