File.php 11.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Reflection
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: File.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Reflection_Class
 */
require_once 'Zend/Reflection/Class.php';

/**
 * @see Zend_Reflection_Function
 */
require_once 'Zend/Reflection/Function.php';

/**
 * @category   Zend
 * @package    Zend_Reflection
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Reflection_File implements Reflector
{
    /**
     * @var string
     */
    protected $_filepath        = null;

    /**
     * @var string
     */
    protected $_docComment      = null;

    /**
     * @var int
     */
    protected $_startLine       = 1;

    /**
     * @var int
     */
    protected $_endLine         = null;

    /**
     * @var string[]
     */
    protected $_requiredFiles   = array();

    /**
     * @var Zend_Reflection_Class[]
     */
    protected $_classes         = array();

    /**
     * @var Zend_Reflection_Function[]
     */
    protected $_functions       = array();

    /**
     * @var string
     */
    protected $_contents        = null;

    /**
     * Constructor
     *
     * @param  string $file
     * @return void
     */
    public function __construct($file)
    {
        $fileName = $file;

        if (($fileRealpath = realpath($fileName)) === false) {
            $fileRealpath = self::findRealpathInIncludePath($file);
        }

        if (!$fileRealpath || !in_array($fileRealpath, get_included_files())) {
            require_once 'Zend/Reflection/Exception.php';
            throw new Zend_Reflection_Exception('File ' . $file . ' must be required before it can be reflected');
        }

        $this->_fileName = $fileRealpath;
        $this->_contents = file_get_contents($this->_fileName);
        $this->_reflect();
    }

    /**
     * Find realpath of file based on include_path
     *
     * @param  string $fileName
     * @return string
     */
    public static function findRealpathInIncludePath($fileName)
    {
        require_once 'Zend/Loader.php';
        $includePaths = Zend_Loader::explodeIncludePath();
        while (count($includePaths) > 0) {
            $filePath = array_shift($includePaths) . DIRECTORY_SEPARATOR . $fileName;

            if ( ($foundRealpath = realpath($filePath)) !== false) {
                break;
            }
        }

        return $foundRealpath;
    }

    /**
     * Export
     *
     * Required by the Reflector interface.
     *
     * @todo   What should this do?
     * @return null
     */
    public static function export()
    {
        return null;
    }

    /**
     * Return the file name of the reflected file
     *
     * @return string
     */
    public function getFileName()
    {
        return $this->_fileName;
    }

    /**
     * Get the start line - Always 1, staying consistent with the Reflection API
     *
     * @return int
     */
    public function getStartLine()
    {
        return $this->_startLine;
    }

    /**
     * Get the end line / number of lines
     *
     * @return int
     */
    public function getEndLine()
    {
        return $this->_endLine;
    }

    /**
     * Return the doc comment
     *
     * @return string
     */
    public function getDocComment()
    {
        return $this->_docComment;
    }

    /**
     * Return the docblock
     *
     * @param  string $reflectionClass Reflection class to use
     * @return Zend_Reflection_Docblock
     */
    public function getDocblock($reflectionClass = 'Zend_Reflection_Docblock')
    {
        $instance = new $reflectionClass($this);
        if (!$instance instanceof Zend_Reflection_Docblock) {
            require_once 'Zend/Reflection/Exception.php';
            throw new Zend_Reflection_Exception('Invalid reflection class specified; must extend Zend_Reflection_Docblock');
        }
        return $instance;
    }

    /**
     * Return the reflection classes of the classes found inside this file
     *
     * @param  string $reflectionClass Name of reflection class to use for instances
     * @return array Array of Zend_Reflection_Class instances
     */
    public function getClasses($reflectionClass = 'Zend_Reflection_Class')
    {
        $classes = array();
        foreach ($this->_classes as $class) {
            $instance = new $reflectionClass($class);
            if (!$instance instanceof Zend_Reflection_Class) {
                require_once 'Zend/Reflection/Exception.php';
                throw new Zend_Reflection_Exception('Invalid reflection class provided; must extend Zend_Reflection_Class');
            }
            $classes[] = $instance;
        }
        return $classes;
    }

    /**
     * Return the reflection functions of the functions found inside this file
     *
     * @param  string $reflectionClass Name of reflection class to use for instances
     * @return array Array of Zend_Reflection_Functions
     */
    public function getFunctions($reflectionClass = 'Zend_Reflection_Function')
    {
        $functions = array();
        foreach ($this->_functions as $function) {
            $instance = new $reflectionClass($function);
            if (!$instance instanceof Zend_Reflection_Function) {
                require_once 'Zend/Reflection/Exception.php';
                throw new Zend_Reflection_Exception('Invalid reflection class provided; must extend Zend_Reflection_Function');
            }
            $functions[] = $instance;
        }
        return $functions;
    }

    /**
     * Retrieve the reflection class of a given class found in this file
     *
     * @param  null|string $name
     * @param  string $reflectionClass Reflection class to use when creating reflection instance
     * @return Zend_Reflection_Class
     * @throws Zend_Reflection_Exception for invalid class name or invalid reflection class
     */
    public function getClass($name = null, $reflectionClass = 'Zend_Reflection_Class')
    {
        if ($name === null) {
            reset($this->_classes);
            $selected = current($this->_classes);
            $instance = new $reflectionClass($selected);
            if (!$instance instanceof Zend_Reflection_Class) {
                require_once 'Zend/Reflection/Exception.php';
                throw new Zend_Reflection_Exception('Invalid reflection class given; must extend Zend_Reflection_Class');
            }
            return $instance;
        }

        if (in_array($name, $this->_classes)) {
            $instance = new $reflectionClass($name);
            if (!$instance instanceof Zend_Reflection_Class) {
                require_once 'Zend/Reflection/Exception.php';
                throw new Zend_Reflection_Exception('Invalid reflection class given; must extend Zend_Reflection_Class');
            }
            return $instance;
        }

        require_once 'Zend/Reflection/Exception.php';
        throw new Zend_Reflection_Exception('Class by name ' . $name . ' not found.');
    }

    /**
     * Return the full contents of file
     *
     * @return string
     */
    public function getContents()
    {
        return $this->_contents;
    }

    /**
     * Serialize to string
     *
     * Required by the Reflector interface
     *
     * @todo   What should this serialization look like?
     * @return string
     */
    public function __toString()
    {
        return '';
    }

    /**
     * This method does the work of "reflecting" the file
     *
     * Uses PHP's tokenizer to perform file reflection.
     *
     * @return void
     */
    protected function _reflect()
    {
        $contents = $this->_contents;
        $tokens   = token_get_all($contents);

        $functionTrapped = false;
        $classTrapped    = false;
        $requireTrapped  = false;
        $openBraces      = 0;

        $this->_checkFileDocBlock($tokens);

        foreach ($tokens as $token) {
            /*
             * Tokens are characters representing symbols or arrays
             * representing strings. The keys/values in the arrays are
             *
             * - 0 => token id,
             * - 1 => string,
             * - 2 => line number
             *
             * Token ID's are explained here:
             * http://www.php.net/manual/en/tokens.php.
             */

            if (is_array($token)) {
                $type    = $token[0];
                $value   = $token[1];
                $lineNum = $token[2];
            } else {
                // It's a symbol
                // Maintain the count of open braces
                if ($token == '{') {
                    $openBraces++;
                } else if ($token == '}') {
                    $openBraces--;
                }

                continue;
            }

            switch ($type) {
                // Name of something
                case T_STRING:
                    if ($functionTrapped) {
                        $this->_functions[] = $value;
                        $functionTrapped = false;
                    } elseif ($classTrapped) {
                        $this->_classes[] = $value;
                        $classTrapped = false;
                    }
                    continue;

                // Required file names are T_CONSTANT_ENCAPSED_STRING
                case T_CONSTANT_ENCAPSED_STRING:
                    if ($requireTrapped) {
                        $this->_requiredFiles[] = $value ."\n";
                        $requireTrapped = false;
                    }
                    continue;

                // Functions
                case T_FUNCTION:
                    if ($openBraces == 0) {
                        $functionTrapped = true;
                    }
                    break;

                // Classes
                case T_CLASS:
                case T_INTERFACE:
                    $classTrapped = true;
                    break;

                // All types of requires
                case T_REQUIRE:
                case T_REQUIRE_ONCE:
                case T_INCLUDE:
                case T_INCLUDE_ONCE:
                    $requireTrapped = true;
                    break;

                // Default case: do nothing
                default:
                    break;
            }
        }

        $this->_endLine = count(explode("\n", $this->_contents));
    }

    /**
     * Validate / check a file level docblock
     *
     * @param  array $tokens Array of tokenizer tokens
     * @return void
     */
    protected function _checkFileDocBlock($tokens) {
        foreach ($tokens as $token) {
            $type    = $token[0];
            $value   = $token[1];
            $lineNum = $token[2];
            if(($type == T_OPEN_TAG) || ($type == T_WHITESPACE)) {
                continue;
            } elseif ($type == T_DOC_COMMENT) {
                $this->_docComment = $value;
                $this->_startLine  = $lineNum + substr_count($value, "\n") + 1;
                return;
            } else {
                // Only whitespace is allowed before file docblocks
                return;
            }
        }
    }
}