Passed
Branch master (6e4050)
by Scott
02:58
created

LoadFile::updatePaths()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 16
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 13
cts 13
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 13
nc 5
nop 1
crap 4
1
<?php
2
namespace Desmond\functions\special;
3
use Desmond\functions\DesmondSpecialFunction;
4
use Desmond\exceptions\ArgumentException;
5
use Desmond\ArgumentHelper;
6
use Desmond\functions\core\FileContents;
7
use Desmond\functions\core\Ast;
8
use Desmond\data_types\StringType;
9
10
class LoadFile extends DesmondSpecialFunction
11
{
12
    use ArgumentHelper;
13
14
    private $file;
15
    private $oldFilePath;
16
    private $oldDir;
17
18 7
    public function run(array $args)
19
    {
20 7
        if (!isset($args[0])) {
21 1
            throw new ArgumentException('"load-file" expects argument 1 to be one of (Symbol, String)');
22
        }
23 6
        $this->file = $this->eval->getReturn($args[0]);
24 6
        $this->updatePaths('new');
25 6
        $return = $this->eval->getReturn($this->getAst());
26 5
        $this->updatePaths('old');
27 5
        return $return;
28
    }
29
30 6
    private function getAst()
31
    {
32 6
        $ast = new Ast();
33 6
        return $ast->run([
34 6
            new StringType($this->getContents(), true)
35
        ]);
36
    }
37
38 6
    private function getContents()
39
    {
40 6
        $fileContents = new FileContents;
41 6
        $contents = $fileContents->run([$this->file]);
42 5
        return sprintf('(do %s)', $contents);
43
    }
44
45 6
    private function updatePaths($to)
46
    {
47 6
        if ($to == 'new') {
48 6
            $this->oldFilePath = $this->currentEnv->exists('_file')
49 1
                ? $this->currentEnv->get('_file')
50 6
                : new StringType('');
51 6
            $this->oldDir = $this->currentEnv->exists('_dir')
52 1
                ? $this->currentEnv->get('_dir')
53 6
                : new StringType('');
54 6
            $this->currentEnv->set('_file', new StringType($this->getFilePath()));
55 6
            $this->currentEnv->set('_dir', new StringType($this->getDir()));
56
        } else {
57 5
            $this->currentEnv->set('_file', $this->oldFilePath);
58 5
            $this->currentEnv->set('_dir', $this->oldDir);
59
        }
60 6
    }
61
62 6
    private function getDir()
63
    {
64 6
        return dirname(realpath($this->file->value()));
65
    }
66
67 6
    private function getFilePath()
68
    {
69 6
        return realpath($this->file->value());
70
    }
71
}
72