Completed
Push — dev ( 122982...5e45c8 )
by Zach
02:18
created

Yarak::call()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 14
nc 2
nop 4
dl 0
loc 24
rs 8.9713
c 0
b 0
f 0
1
<?php
2
3
namespace Yarak;
4
5
use Phalcon\DiInterface;
6
use Phalcon\Di\FactoryDefault;
7
use Yarak\Exceptions\FileNotFound;
8
use Symfony\Component\Console\Input\ArrayInput;
9
use Symfony\Component\Console\Output\NullOutput;
10
use Symfony\Component\Console\Output\BufferedOutput;
11
12
class Yarak
13
{
14
    /**
15
     * Call a Yarak console command.
16
     *
17
     * @param string         $command
18
     * @param array          $arguments Argument array.
19
     * @param FactoryDefault $di        DI, may be necessary for php 5.6.
20
     * @param bool           $debug     If true, use and return buffered output.
21
     */
22
    public static function call(
23
        $command,
24
        array $arguments = [],
25
        DiInterface $di = null,
26
        $debug = false
27
    ) {
28
        $kernel = self::getKernel($di);
29
30
        $arguments = ['command' => $command] + $arguments;
31
32
        $input = new ArrayInput($arguments);
33
34
        if ($debug) {
35
            $output = new BufferedOutput();
36
37
            $kernel->handle($input, $output);
38
39
            return $output;
40
        }
41
42
        $output = new NullOutput();
43
44
        $kernel->handle($input, $output);
45
    }
46
47
    /**
48
     * Resolve Yarak kernel from di.
49
     *
50
     * @param FactoryDefault|null $di
51
     *
52
     * @return Kernel
53
     */
54
    protected static function getKernel($di)
55
    {
56
        if ($di === null) {
57
            $di = self::getDI();
58
        }
59
60
        return $di->get('yarak');
61
    }
62
63
    /**
64
     * Get a fresh DI instance.
65
     *
66
     * @throws FileNotFound
67
     *
68
     * @return FactoryDefault
69
     */
70
    protected static function getDI()
71
    {
72
        $di = new FactoryDefault();
73
74
        $servicesPath = __DIR__.'/../../../../app/config/services.php';
75
76
        if (!realpath($servicesPath)) {
77
            $servicesPath = __DIR__.'/../app/config/services.php';
78
        }
79
80
        try {
81
            include $servicesPath;
82
        } catch (\Exception $e) {
83
            throw FileNotFound::servicesFileNotFound(
84
                'Try passing the Yarak config array as the third argument '.
85
                'to Yarak::call.'
86
            );
87
        }
88
89
        return $di;
90
    }
91
}
92