Completed
Push — master ( dcd940...44d656 )
by Dmitry
04:43
created

Application::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Basis\Test;
4
5
use Basis\Application as BaseApplication;
6
use Basis\Cache;
7
use Basis\Context;
8
use Basis\Converter;
9
use Basis\Runner;
10
use Basis\Test;
11
use Exception;
12
13
class Application extends BaseApplication
14
{
15
    private $test;
16
17
    public function __construct(Test $test)
18
    {
19
        parent::__construct(getcwd());
20
21
        $this->test = $test;
22
    }
23
24 45
    public function dispatch(string $job, array $params = [], string $service = null)
25
    {
26 45
        if (array_key_exists('context', $this->test->params)) {
27
            $this->get(Context::class)->apply($this->test->params);
28
        }
29 45
        if (array_key_exists($job, $this->test->mockInstances)) {
30 8
            $mocks = $this->test->mockInstances[$job];
31 8
            $valid = null;
32 8
            foreach ($mocks as $mock) {
33 8
                if ($mock->params == $params || (!$mock->params && !$valid)) {
34 8
                    $valid = $mock;
35
                }
36
            }
37 8
            if ($valid) {
38 8
                return $this->get(Cache::class)
39 8
                    ->wrap([$job, $params, $service], function () use ($valid, $params) {
40 8
                        $result = $valid->result;
41 8
                        if (is_callable($result)) {
42 5
                            $result = $result($params);
43
                        }
44 8
                        $valid->calls++;
45 8
                        return $this->get(Converter::class)->toObject($result);
46 8
                    });
47
            }
48
        }
49 45
        if ($this->test->disableRemote) {
50 43
            if (!$this->get(Runner::class)->hasJob($job)) {
51 4
                throw new Exception("Remote calls ($job) are disabled for tests");
52
            }
53
        }
54
55 45
        $converter = $this->get(Converter::class);
56
57 45
        $global = $this->test->params ?: [];
58 45
        $global = $converter->toObject($global);
59 45
        if (is_object($global)) {
60 2
            $global = get_object_vars($global);
61
        }
62
63 45
        return parent::dispatch($job, array_merge($params, $global), $service);
64
    }
65
}
66