4 * This file is part of Psy Shell.
6 * (c) 2012-2017 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 = array(Include_::TYPE_REQUIRE, Include_::TYPE_REQUIRE_ONCE);
34 public function enterNode(Node $node)
36 if (!$this->isRequireNode($node)) {
47 * $foo = Psy\CodeCleaner\RequirePass::resolve($bar)
49 return new StaticCall(
50 new FullyQualifiedName('Psy\CodeCleaner\RequirePass'),
52 array(new Arg($node->expr), new Arg(new LNumber($node->getLine()))),
53 $node->getAttributes()
58 * Runtime validation that $file can be resolved as an include path.
60 * If $file can be resolved, return $file. Otherwise throw a fatal error exception.
62 * @throws FatalErrorException when unable to resolve include path for $file
63 * @throws ErrorException if $file is empty and E_WARNING is included in error_reporting level
66 * @param int $lineNumber Line number of the original require expression
68 * @return string Exactly the same as $file
70 public static function resolve($file, $lineNumber = null)
72 $file = (string) $file;
75 // @todo Shell::handleError would be better here, because we could
76 // fake the file and line number, but we can't call it statically.
77 // So we're duplicating some of the logics here.
78 if (E_WARNING & error_reporting()) {
79 ErrorException::throwException(E_WARNING, 'Filename cannot be empty', null, $lineNumber);
81 // @todo trigger an error as fallback? this is pretty ugly…
82 // trigger_error('Filename cannot be empty', E_USER_WARNING);
86 if ($file === '' || !stream_resolve_include_path($file)) {
87 $msg = sprintf("Failed opening required '%s'", $file);
88 throw new FatalErrorException($msg, 0, E_ERROR, null, $lineNumber);
94 private function isRequireNode(Node $node)
96 return $node instanceof Include_ && in_array($node->type, self::$requireTypes);