Completed
Push — master ( 7f0412...717772 )
by Michal
02:42 queued 10s
created

ApiLinkMacro::addQuotes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
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 Tomaj\NetteApi\Link;
4
5
use Latte\Compiler;
6
use Latte\MacroNode;
7
use Latte\Macros\MacroSet;
8
use Latte\PhpWriter;
9
use Nette\Application\UI\InvalidLinkException;
10
use Tracy\Debugger;
11
12
/**
13
 * Usage in latte:
14
 * {apiLink $method, $version, $package, $apiAction, ['title' => 'My title', 'data-foo' => 'bar']}
15
 */
16
class ApiLinkMacro extends MacroSet
17
{
18
    public static function install(Compiler $compiler)
19
    {
20
        $macroSet = new static($compiler);
21
        $macroSet->addMacro('apiLink', [self::class, 'start']);
22
    }
23
24
    public static function start(MacroNode $node, PhpWriter $writer)
25
    {
26
        $args = array_map('trim', explode(',', $node->args, 5));
27
28
        if (count($args) < 3) {
29
            $message = "Invalid link destination, too few arguments.";
30
            if (!Debugger::$productionMode) {
31
                throw new InvalidLinkException($message);
32
            }
33
            Debugger::log($message, Debugger::EXCEPTION);
34
            return '';
35
        }
36
37
        $arguments = [
38
            'method' => self::addQuotes($args[0]),
39
            'version' => $args[1],
40
            'package' => self::addQuotes($args[2]),
41
            'action' => isset($args[3]) ? self::addQuotes($args[3]) : 'null',
42
            'params' => $args[4] ?? '[]',
43
        ];
44
45
        return $writer->write('echo ($_presenter->context->getByType("' . ApiLink::class . '"))' .
46
            '->link((new Tomaj\NetteApi\EndpointIdentifier(' .
47
                $arguments['method']  . ', ' .
48
                $arguments['version']  . ', ' .
49
                $arguments['package'] . ', ' .
50
                $arguments['action'] . ')), ' . $arguments['params'] . ')');
51
    }
52
53
    private static function addQuotes($string)
54
    {
55
        return '"' . trim($string, "'\"") . '"';
56
    }
57
}
58