4 * This file is part of Psy Shell.
6 * (c) 2012-2018 Justin Hileman
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Psy\CodeCleaner;
15 use PhpParser\Node\Arg;
16 use PhpParser\Node\Expr\Include_;
17 use PhpParser\Node\Expr\StaticCall;
18 use PhpParser\Node\Name\FullyQualified as FullyQualifiedName;
19 use PhpParser\Node\Scalar\LNumber;
20 use Psy\Exception\ErrorException;
21 use Psy\Exception\FatalErrorException;
25 * Add runtime validation for `require` and `require_once` calls.
27 class RequirePass extends CodeCleanerPass
29 private static $requireTypes = [Include_::TYPE_REQUIRE, Include_::TYPE_REQUIRE_ONCE];
34 public function enterNode(Node $origNode)
36 if (!$this->isRequireNode($origNode)) {
40 $node = clone $origNode;
49 * $foo = require \Psy\CodeCleaner\RequirePass::resolve($bar)
51 $node->expr = new StaticCall(
52 new FullyQualifiedName('Psy\CodeCleaner\RequirePass'),
54 [new Arg($origNode->expr), new Arg(new LNumber($origNode->getLine()))],
55 $origNode->getAttributes()
62 * Runtime validation that $file can be resolved as an include path.
64 * If $file can be resolved, return $file. Otherwise throw a fatal error exception.
66 * @throws FatalErrorException when unable to resolve include path for $file
67 * @throws ErrorException if $file is empty and E_WARNING is included in error_reporting level
70 * @param int $lineNumber Line number of the original require expression
72 * @return string Exactly the same as $file
74 public static function resolve($file, $lineNumber = null)
76 $file = (string) $file;
79 // @todo Shell::handleError would be better here, because we could
80 // fake the file and line number, but we can't call it statically.
81 // So we're duplicating some of the logics here.
82 if (E_WARNING & error_reporting()) {
83 ErrorException::throwException(E_WARNING, 'Filename cannot be empty', null, $lineNumber);
85 // @todo trigger an error as fallback? this is pretty ugly…
86 // trigger_error('Filename cannot be empty', E_USER_WARNING);
90 if ($file === '' || !stream_resolve_include_path($file)) {
91 $msg = sprintf("Failed opening required '%s'", $file);
92 throw new FatalErrorException($msg, 0, E_ERROR, null, $lineNumber);
98 private function isRequireNode(Node $node)
100 return $node instanceof Include_ && in_array($node->type, self::$requireTypes);