Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 148 | Details | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
/*
4
 * This file is part of Psy Shell.
5
 *
200 lars 6
 * (c) 2012-2023 Justin Hileman
148 lars 7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
 
12
namespace Psy\CodeCleaner;
13
 
14
use PhpParser\Node;
15
use PhpParser\Node\Stmt\Do_;
16
use PhpParser\Node\Stmt\Function_;
17
use PhpParser\Node\Stmt\If_;
18
use PhpParser\Node\Stmt\Switch_;
19
use PhpParser\Node\Stmt\While_;
20
use Psy\Exception\FatalErrorException;
21
 
22
/**
23
 * Validate that function calls will succeed.
24
 *
25
 * This pass throws a FatalErrorException rather than letting PHP run
26
 * headfirst into a real fatal error and die.
27
 */
28
class ValidFunctionNamePass extends NamespaceAwarePass
29
{
30
    private $conditionalScopes = 0;
31
 
32
    /**
33
     * Store newly defined function names on the way in, to allow recursion.
34
     *
35
     * @throws FatalErrorException if a function is redefined in a non-conditional scope
36
     *
37
     * @param Node $node
38
     *
39
     * @return int|Node|null Replacement node (or special return value)
40
     */
41
    public function enterNode(Node $node)
42
    {
43
        parent::enterNode($node);
44
 
45
        if (self::isConditional($node)) {
46
            $this->conditionalScopes++;
47
        } elseif ($node instanceof Function_) {
48
            $name = $this->getFullyQualifiedName($node->name);
49
 
50
            // @todo add an "else" here which adds a runtime check for instances where we can't tell
51
            // whether a function is being redefined by static analysis alone.
52
            if ($this->conditionalScopes === 0) {
53
                if (\function_exists($name) ||
54
                    isset($this->currentScope[\strtolower($name)])) {
55
                    $msg = \sprintf('Cannot redeclare %s()', $name);
56
                    throw new FatalErrorException($msg, 0, \E_ERROR, null, $node->getLine());
57
                }
58
            }
59
 
60
            $this->currentScope[\strtolower($name)] = true;
61
        }
62
    }
63
 
64
    /**
65
     * @param Node $node
66
     *
67
     * @return int|Node|Node[]|null Replacement node (or special return value)
68
     */
69
    public function leaveNode(Node $node)
70
    {
71
        if (self::isConditional($node)) {
72
            $this->conditionalScopes--;
73
        }
74
    }
75
 
76
    private static function isConditional(Node $node)
77
    {
78
        return $node instanceof If_ ||
79
            $node instanceof While_ ||
80
            $node instanceof Do_ ||
81
            $node instanceof Switch_;
82
    }
83
}