1<?php
2/*
3 * This file is part of PHPUnit.
4 *
5 * (c) Sebastian Bergmann <sebastian@phpunit.de>
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
9 */
10
11/**
12 * Utility methods to load PHP sourcefiles.
13 */
14class PHPUnit_Util_Fileloader
15{
16    /**
17     * Checks if a PHP sourcefile is readable.
18     * The sourcefile is loaded through the load() method.
19     *
20     * @param string $filename
21     *
22     * @return string
23     *
24     * @throws PHPUnit_Framework_Exception
25     */
26    public static function checkAndLoad($filename)
27    {
28        $includePathFilename = stream_resolve_include_path($filename);
29
30        if (!$includePathFilename || !is_readable($includePathFilename)) {
31            throw new PHPUnit_Framework_Exception(
32                sprintf('Cannot open file "%s".' . "\n", $filename)
33            );
34        }
35
36        self::load($includePathFilename);
37
38        return $includePathFilename;
39    }
40
41    /**
42     * Loads a PHP sourcefile.
43     *
44     * @param string $filename
45     *
46     * @return mixed
47     */
48    public static function load($filename)
49    {
50        $oldVariableNames = array_keys(get_defined_vars());
51
52        include_once $filename;
53
54        $newVariables     = get_defined_vars();
55        $newVariableNames = array_diff(
56            array_keys($newVariables),
57            $oldVariableNames
58        );
59
60        foreach ($newVariableNames as $variableName) {
61            if ($variableName != 'oldVariableNames') {
62                $GLOBALS[$variableName] = $newVariables[$variableName];
63            }
64        }
65
66        return $filename;
67    }
68}
69