Completed
Push — master ( bb4db2...716b50 )
by Greg
01:30
created

FilterHooks::wrapFilteredResult()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
namespace Consolidation\Filter\Hooks;
4
5
use Consolidation\AnnotatedCommand\CommandData;
6
use Consolidation\Filter\LogicalOpFactory;
7
use Consolidation\Filter\FilterOutputData;
8
use Symfony\Component\Yaml\Yaml;
9
10
class FilterHooks
11
{
12
    /**
13
     * @hook alter @filter-output
14
     * @option $filter Filter output based on provided expression
15
     * @default $filter ''
16
     */
17
    public function filterOutput($result, CommandData $commandData)
18
    {
19
        $expr = $commandData->input()->getOption('filter');
20
        if (!empty($expr)) {
21
            $factory = LogicalOpFactory::get();
22
            $op = $factory->evaluate($expr);
23
            $filter = new FilterOutputData();
24
            $result = $this->wrapFilteredResult($filter->filter($result, $op), get_class($result));
25
        }
26
27
        return $result;
28
    }
29
30
    /**
31
     * If the source data was wrapped in a marker class such
32
     * as RowsOfFields, then re-apply the wrapper.
33
     */
34
    protected function wrapFilteredResult($data, $sourceClass)
35
    {
36
        if (!$sourceClass) {
37
            return $data;
38
        }
39
40
        return new $sourceClass($data);
41
    }
42
}
43