Completed
Push — master ( d4060f...2b91c4 )
by Greg
01:22
created

OpCommands::parse()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
namespace Consolidation\Filter\Cli;
4
5
use Consolidation\Filter\LogicalOpFactory;
6
use Symfony\Component\Yaml\Yaml;
7
8
class OpCommands extends \Robo\Tasks
9
{
10
    /**
11
     * Test the expression parser
12
     *
13
     * @command parse
14
     * @return array
15
     */
16
    public function parse($expr, $options = ['format' => 'yaml', 'dump' => false])
17
    {
18
        $factory = LogicalOpFactory::get();
19
        $op = $factory->evaluate($expr);
20
21
        $result = (string)$op;
22
23
        if ($options['dump']) {
24
            $result = var_export($op, true) . "\n$result";
25
        }
26
27
        return $result;
28
    }
29
30
    /**
31
     * Convert a command from one format to another, potentially with filtering.
32
     *
33
     * @command edit
34
     * @aliases ed
35
     * @return array
36
     */
37
    public function edit($data, $options = ['format' => 'yaml', 'in' => 'auto'])
38
    {
39
        return $this->read($data, $options['in']);
40
    }
41
42
    /**
43
     * Read the data provided to this command.
44
     */
45
    protected function read($data, $in)
46
    {
47
        // If our input spec is '-' then read from stdin
48
        if ($data == '-') {
49
            $data = 'php://stdin';
50
        }
51
        // If our input spec is a file or a url then read it. Otherwise
52
        // we'll presume the data was provided directly on the command line.
53
        if (file_exists($data) || preg_match('#^[a-z]*://#', $data)) {
54
            $data = file_get_contents($data);
55
        }
56
57
        return $this->parseData($data, $in);
58
    }
59
60
    /**
61
     * Convert our provided input data to a php array.
62
     */
63
    protected function parseData($data, $in)
64
    {
65
        $in = $this->inferInputFormat($data, $in);
66
67
        switch ($in) {
68
            case 'json':
69
                return json_decode($data, true);
70
71
            case 'yaml':
72
            default:
73
                return (array) Yaml::parse($data);
74
        }
75
    }
76
77
    /**
78
     * If the data type is 'auto', then try to infer what data type
79
     * we should parse as based on the contents of the data.
80
     */
81
    protected function inferInputFormat($data, $in)
82
    {
83
        // If the user explicitly set the data type then use that
84
        if ($in != 'auto') {
85
            return $in;
86
        }
87
88
        // If data begins with '{' then presume it is json
89
        if ($data[0] == '{') {
90
            return 'json';
91
        }
92
93
        // We don't know what the data type should be.
94
        return $in;
95
    }
96
}
97