Passed
Push — 4.x ( 17e0c5...e9b635 )
by Doug
07:44
created

AddNewConstantsVisitor::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
/**
3
 * PHPCoord.
4
 *
5
 * @author Doug Wright
6
 */
7
declare(strict_types=1);
8
9
namespace PHPCoord\EPSG\Import;
10
11
use PhpParser\Comment\Doc;
12
use PhpParser\Node;
13
use PhpParser\Node\Stmt\Class_;
14
use PhpParser\Node\Stmt\ClassConst;
15
use PhpParser\Node\Stmt\ClassLike;
16
use PhpParser\NodeTraverser;
17
use PhpParser\NodeVisitorAbstract;
18
use SQLite3Result;
19
20
class AddNewConstantsVisitor extends NodeVisitorAbstract
21
{
22
    /**
23
     * @var SQLite3Result
24
     */
25
    private $constants;
26
27
    public function __construct(SQLite3Result $constants)
28
    {
29
        $this->constants = $constants;
30
    }
31
32
    public function enterNode(Node $node)
33
    {
34
        if ($node instanceof ClassLike) {
35
            $commentNodes = [];
36
37
            while ($row = $this->constants->fetchArray(SQLITE3_ASSOC)) {
38
                $name = str_replace(
39
                    [' ', '-', '\'', '(', ')', '[', ']', '.', '/', '=', ',', ':', '°', '+', '&', '<>'],
40
                    ['_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_DEG_', '_PLUS_', '_AND_', '_TO_'],
41
                    $row['constant_name']
42
                );
43
                $name = preg_replace('/_+/', '_', $name);
44
                $name = trim($name, '_');
45
46
                $comment = '';
47
                if ($row['constant_help'] || $row['deprecated']) {
48
                    $comment .= "/**\n";
49
                    $helpLines = explode("\n", trim(wordwrap($row['constant_help'], 112)));
50
                    foreach ($helpLines as $helpLine) {
51
                        $comment .= '* ' . $helpLine . "\n";
52
                    }
53
                    if ($row['deprecated']) {
54
                        $comment .= "* @deprecated\n";
55
                    }
56
                    $comment .= " */\n";
57
                }
58
59
                $constName = strtoupper('EPSG_' . $name);
60
                $constValue = is_string($row['constant_value']) ? new Node\Scalar\String_($row['constant_value']) : new Node\Scalar\LNumber($row['constant_value']);
61
                $constComment = new Doc($comment);
62
                $const = new Node\Const_($constName, $constValue);
63
64
                $constStmt = new ClassConst([$const], Class_::MODIFIER_PUBLIC);
65
                $constStmt->setDocComment($constComment);
66
                $commentNodes[] = $constStmt;
67
            }
68
69
            $node->stmts = array_merge($commentNodes, $node->stmts);
70
71
            return NodeTraverser::STOP_TRAVERSAL;
72
        }
73
74
        return null;
75
    }
76
}
77