Cache.php 10.6 KB
Newer Older
Ketan's avatar
Ketan committed
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
<?php
/**
 * Function for caching between runs.
 *
 * @author    Greg Sherwood <gsherwood@squiz.net>
 * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
 * @license   https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
 */

namespace PHP_CodeSniffer\Util;

use PHP_CodeSniffer\Autoload;
use PHP_CodeSniffer\Config;
use PHP_CodeSniffer\Ruleset;

class Cache
{

    /**
     * The filesystem location of the cache file.
     *
     * @var void
     */
    private static $path = '';

    /**
     * The cached data.
     *
     * @var array<string, mixed>
     */
    private static $cache = [];


    /**
     * Loads existing cache data for the run, if any.
     *
     * @param \PHP_CodeSniffer\Ruleset $ruleset The ruleset used for the run.
     * @param \PHP_CodeSniffer\Config  $config  The config data for the run.
     *
     * @return void
     */
    public static function load(Ruleset $ruleset, Config $config)
    {
        // Look at every loaded sniff class so far and use their file contents
        // to generate a hash for the code used during the run.
        // At this point, the loaded class list contains the core PHPCS code
        // and all sniffs that have been loaded as part of the run.
        if (PHP_CODESNIFFER_VERBOSITY > 1) {
            echo PHP_EOL."\tGenerating loaded file list for code hash".PHP_EOL;
        }

        $codeHashFiles = [];

        $classes = array_keys(Autoload::getLoadedClasses());
        sort($classes);

        $installDir     = dirname(__DIR__);
        $installDirLen  = strlen($installDir);
        $standardDir    = $installDir.DIRECTORY_SEPARATOR.'Standards';
        $standardDirLen = strlen($standardDir);
        foreach ($classes as $file) {
            if (substr($file, 0, $standardDirLen) !== $standardDir) {
                if (substr($file, 0, $installDirLen) === $installDir) {
                    // We are only interested in sniffs here.
                    continue;
                }

                if (PHP_CODESNIFFER_VERBOSITY > 1) {
                    echo "\t\t=> external file: $file".PHP_EOL;
                }
            } else if (PHP_CODESNIFFER_VERBOSITY > 1) {
                echo "\t\t=> internal sniff: $file".PHP_EOL;
            }

            $codeHashFiles[] = $file;
        }

        // Add the content of the used rulesets to the hash so that sniff setting
        // changes in the ruleset invalidate the cache.
        $rulesets = $ruleset->paths;
        sort($rulesets);
        foreach ($rulesets as $file) {
            if (substr($file, 0, $standardDirLen) !== $standardDir) {
                if (PHP_CODESNIFFER_VERBOSITY > 1) {
                    echo "\t\t=> external ruleset: $file".PHP_EOL;
                }
            } else if (PHP_CODESNIFFER_VERBOSITY > 1) {
                echo "\t\t=> internal ruleset: $file".PHP_EOL;
            }

            $codeHashFiles[] = $file;
        }

        // Go through the core PHPCS code and add those files to the file
        // hash. This ensures that core PHPCS changes will also invalidate the cache.
        // Note that we ignore sniffs here, and any files that don't affect
        // the outcome of the run.
        $di     = new \RecursiveDirectoryIterator($installDir);
        $filter = new \RecursiveCallbackFilterIterator(
            $di,
            function ($file, $key, $iterator) {
                // Skip hidden files.
                $filename = $file->getFilename();
                if (substr($filename, 0, 1) === '.') {
                    return false;
                }

                $filePath = Common::realpath($file->getPathname());
                if ($filePath === false) {
                    return false;
                }

                if (is_dir($filePath) === true
                    && ($filename === 'Standards'
                    || $filename === 'Exceptions'
                    || $filename === 'Reports'
                    || $filename === 'Generators')
                ) {
                    return false;
                }

                return true;
            }
        );

        $iterator      = new \RecursiveIteratorIterator($filter);
        $codeHashFiles = [];
        foreach ($iterator as $file) {
            if (PHP_CODESNIFFER_VERBOSITY > 1) {
                echo "\t\t=> core file: $file".PHP_EOL;
            }

            $codeHashFiles[] = $file->getPathname();
        }

        $codeHash = '';
        sort($codeHashFiles);
        foreach ($codeHashFiles as $file) {
            $codeHash .= md5_file($file);
        }

        $codeHash = md5($codeHash);

        // Along with the code hash, use various settings that can affect
        // the results of a run to create a new hash. This hash will be used
        // in the cache file name.
        $rulesetHash = md5(var_export($ruleset->ignorePatterns, true).var_export($ruleset->includePatterns, true));
        $configData  = [
            'phpVersion'   => PHP_VERSION_ID,
            'tabWidth'     => $config->tabWidth,
            'encoding'     => $config->encoding,
            'recordErrors' => $config->recordErrors,
            'annotations'  => $config->annotations,
            'configData'   => Config::getAllConfigData(),
            'codeHash'     => $codeHash,
            'rulesetHash'  => $rulesetHash,
        ];

        $configString = var_export($configData, true);
        $cacheHash    = substr(sha1($configString), 0, 12);

        if (PHP_CODESNIFFER_VERBOSITY > 1) {
            echo "\tGenerating cache key data".PHP_EOL;
            foreach ($configData as $key => $value) {
                if (is_array($value) === true) {
                    echo "\t\t=> $key:".PHP_EOL;
                    foreach ($value as $subKey => $subValue) {
                        echo "\t\t\t=> $subKey: $subValue".PHP_EOL;
                    }

                    continue;
                }

                if ($value === true || $value === false) {
                    $value = (int) $value;
                }

                echo "\t\t=> $key: $value".PHP_EOL;
            }

            echo "\t\t=> cacheHash: $cacheHash".PHP_EOL;
        }//end if

        if ($config->cacheFile !== null) {
            $cacheFile = $config->cacheFile;
        } else {
            // Determine the common paths for all files being checked.
            // We can use this to locate an existing cache file, or to
            // determine where to create a new one.
            if (PHP_CODESNIFFER_VERBOSITY > 1) {
                echo "\tChecking possible cache file paths".PHP_EOL;
            }

            $paths = [];
            foreach ($config->files as $file) {
                $file = Common::realpath($file);
                while ($file !== DIRECTORY_SEPARATOR) {
                    if (isset($paths[$file]) === false) {
                        $paths[$file] = 1;
                    } else {
                        $paths[$file]++;
                    }

                    $lastFile = $file;
                    $file     = dirname($file);
                    if ($file === $lastFile) {
                        // Just in case something went wrong,
                        // we don't want to end up in an infinite loop.
                        break;
                    }
                }
            }

            ksort($paths);
            $paths = array_reverse($paths);

            $numFiles  = count($config->files);
            $tmpDir    = sys_get_temp_dir();
            $cacheFile = null;
            foreach ($paths as $file => $count) {
                if ($count !== $numFiles) {
                    unset($paths[$file]);
                    continue;
                }

                $fileHash = substr(sha1($file), 0, 12);
                $testFile = $tmpDir.DIRECTORY_SEPARATOR."phpcs.$fileHash.$cacheHash.cache";
                if ($cacheFile === null) {
                    // This will be our default location if we can't find
                    // an existing file.
                    $cacheFile = $testFile;
                }

                if (PHP_CODESNIFFER_VERBOSITY > 1) {
                    echo "\t\t=> $testFile".PHP_EOL;
                    echo "\t\t\t * based on shared location: $file *".PHP_EOL;
                }

                if (file_exists($testFile) === true) {
                    $cacheFile = $testFile;
                    break;
                }
            }//end foreach

            if ($cacheFile === null) {
                // Unlikely, but just in case $paths is empty for some reason.
                $cacheFile = $tmpDir.DIRECTORY_SEPARATOR."phpcs.$cacheHash.cache";
            }
        }//end if

        self::$path = $cacheFile;
        if (PHP_CODESNIFFER_VERBOSITY > 1) {
            echo "\t=> Using cache file: ".self::$path.PHP_EOL;
        }

        if (file_exists(self::$path) === true) {
            self::$cache = json_decode(file_get_contents(self::$path), true);

            // Verify the contents of the cache file.
            if (self::$cache['config'] !== $configData) {
                self::$cache = [];
                if (PHP_CODESNIFFER_VERBOSITY > 1) {
                    echo "\t* cache was invalid and has been cleared *".PHP_EOL;
                }
            }
        } else if (PHP_CODESNIFFER_VERBOSITY > 1) {
            echo "\t* cache file does not exist *".PHP_EOL;
        }

        self::$cache['config'] = $configData;

    }//end load()


    /**
     * Saves the current cache to the filesystem.
     *
     * @return void
     */
    public static function save()
    {
        file_put_contents(self::$path, json_encode(self::$cache));

    }//end save()


    /**
     * Retrieves a single entry from the cache.
     *
     * @param string $key The key of the data to get. If NULL,
     *                    everything in the cache is returned.
     *
     * @return mixed
     */
    public static function get($key=null)
    {
        if ($key === null) {
            return self::$cache;
        }

        if (isset(self::$cache[$key]) === true) {
            return self::$cache[$key];
        }

        return false;

    }//end get()


    /**
     * Retrieves a single entry from the cache.
     *
     * @param string $key   The key of the data to set. If NULL,
     *                      sets the entire cache.
     * @param mixed  $value The value to set.
     *
     * @return void
     */
    public static function set($key, $value)
    {
        if ($key === null) {
            self::$cache = $value;
        } else {
            self::$cache[$key] = $value;
        }

    }//end set()


    /**
     * Retrieves the number of cache entries.
     *
     * @return int
     */
    public static function getSize()
    {
        return (count(self::$cache) - 1);

    }//end getSize()


}//end class