ContextualizedTransformation   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 57
rs 10
c 0
b 0
f 0
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 2
A __clone() 0 3 1
A getContext() 0 3 1
A __invoke() 0 16 2
1
<?php
2
3
/*
4
 * This file is part of the ICanBoogie package.
5
 *
6
 * (c) Olivier Laviale <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace ICanBoogie\Transformation;
13
14
/**
15
 * A transformation associated with a context.
16
 *
17
 * Nested transformation can use the context the present the data differently. e.g. removing a number of fields if
18
 * they are embedded in a set, or because a user is lacking some permissions.
19
 */
20
class ContextualizedTransformation implements HasContext, Transformation
21
{
22
    /**
23
     * @var Context
24
     */
25
    private $context;
26
27
    /**
28
     * @var Transformation|callable
29
     */
30
    private $transformation;
31
32
    /**
33
     * @param Context|null $context
34
     * @param Transformation|callable|null $transformation
35
     */
36
    public function __construct(Context $context = null, callable $transformation = null)
37
    {
38
        $this->context = $context ?: new Context;
39
        $this->transformation = $transformation;
40
    }
41
42
    public function __clone()
43
    {
44
        $this->context = clone $this->context;
45
    }
46
47
    /**
48
     * @param mixed $data
49
     * @param Transformation|callable|null $transformation
50
     *
51
     * @return mixed
52
     */
53
    public function __invoke($data, callable $transformation = null)
54
    {
55
        if ($transformation) {
56
            $clone = clone $this;
57
            $clone->transformation = $transformation;
58
59
            return $clone($data);
60
        }
61
62
        $this->context->push($data);
63
64
        $result = ($this->transformation)($data, $this);
65
66
        $this->context->pop();
67
68
        return $result;
69
    }
70
71
    /**
72
     * @return Context
73
     */
74
    public function getContext(): Context
75
    {
76
        return $this->context;
77
    }
78
}
79