add trashes

This commit is contained in:
Diskette Guy
2025-07-21 15:40:51 +07:00
parent c8f2944770
commit 07171f5b5a
848 changed files with 134166 additions and 0 deletions
@@ -0,0 +1,563 @@
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Autoloader;
use CodeIgniter\Exceptions\ConfigException;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\Exceptions\RuntimeException;
use Composer\Autoload\ClassLoader;
use Composer\InstalledVersions;
use Config\Autoload;
use Config\Kint as KintConfig;
use Config\Modules;
use Kint;
use Kint\Renderer\CliRenderer;
use Kint\Renderer\RichRenderer;
/**
* An autoloader that uses both PSR4 autoloading, and traditional classmaps.
*
* Given a foo-bar package of classes in the file system at the following paths:
* ```
* /path/to/packages/foo-bar/
* /src
* Baz.php # Foo\Bar\Baz
* Qux/
* Quux.php # Foo\Bar\Qux\Quux
* ```
* you can add the path to the configuration array that is passed in the constructor.
* The Config array consists of 2 primary keys, both of which are associative arrays:
* 'psr4', and 'classmap'.
* ```
* $Config = [
* 'psr4' => [
* 'Foo\Bar' => '/path/to/packages/foo-bar'
* ],
* 'classmap' => [
* 'MyClass' => '/path/to/class/file.php'
* ]
* ];
* ```
* Example:
* ```
* <?php
* // our configuration array
* $Config = [ ... ];
* $loader = new \CodeIgniter\Autoloader\Autoloader($Config);
*
* // register the autoloader
* $loader->register();
* ```
*
* @see \CodeIgniter\Autoloader\AutoloaderTest
*/
class Autoloader
{
/**
* Stores namespaces as key, and path as values.
*
* @var array<string, list<string>>
*/
protected $prefixes = [];
/**
* Stores class name as key, and path as values.
*
* @var array<class-string, string>
*/
protected $classmap = [];
/**
* Stores files as a list.
*
* @var list<string>
*/
protected $files = [];
/**
* Stores helper list.
* Always load the URL helper, it should be used in most apps.
*
* @var list<string>
*/
protected $helpers = ['url'];
/**
* Reads in the configuration array (described above) and stores
* the valid parts that we'll need.
*
* @return $this
*/
public function initialize(Autoload $config, Modules $modules)
{
$this->prefixes = [];
$this->classmap = [];
$this->files = [];
// We have to have one or the other, though we don't enforce the need
// to have both present in order to work.
if ($config->psr4 === [] && $config->classmap === []) {
throw new InvalidArgumentException('Config array must contain either the \'psr4\' key or the \'classmap\' key.');
}
if ($config->psr4 !== []) {
$this->addNamespace($config->psr4);
}
if ($config->classmap !== []) {
$this->classmap = $config->classmap;
}
if ($config->files !== []) {
$this->files = $config->files;
}
if ($config->helpers !== []) {
$this->helpers = [...$this->helpers, ...$config->helpers];
}
if (is_file(COMPOSER_PATH)) {
$this->loadComposerAutoloader($modules);
}
return $this;
}
private function loadComposerAutoloader(Modules $modules): void
{
// The path to the vendor directory.
// We do not want to enforce this, so set the constant if Composer was used.
if (! defined('VENDORPATH')) {
define('VENDORPATH', dirname(COMPOSER_PATH) . DIRECTORY_SEPARATOR);
}
/** @var ClassLoader $composer */
$composer = include COMPOSER_PATH;
// Should we load through Composer's namespaces, also?
if ($modules->discoverInComposer) {
// @phpstan-ignore-next-line
$this->loadComposerNamespaces($composer, $modules->composerPackages ?? []);
}
unset($composer);
}
/**
* Register the loader with the SPL autoloader stack.
*
* @return void
*/
public function register()
{
// Register classmap loader for the files in our class map.
spl_autoload_register($this->loadClassmap(...), true);
// Register the PSR-4 autoloader.
spl_autoload_register($this->loadClass(...), true);
// Load our non-class files
foreach ($this->files as $file) {
$this->includeFile($file);
}
}
/**
* Unregister autoloader.
*
* This method is for testing.
*/
public function unregister(): void
{
spl_autoload_unregister($this->loadClass(...));
spl_autoload_unregister($this->loadClassmap(...));
}
/**
* Registers namespaces with the autoloader.
*
* @param array<string, list<string>|string>|string $namespace
*
* @return $this
*/
public function addNamespace($namespace, ?string $path = null)
{
if (is_array($namespace)) {
foreach ($namespace as $prefix => $namespacedPath) {
$prefix = trim($prefix, '\\');
if (is_array($namespacedPath)) {
foreach ($namespacedPath as $dir) {
$this->prefixes[$prefix][] = rtrim($dir, '\\/') . DIRECTORY_SEPARATOR;
}
continue;
}
$this->prefixes[$prefix][] = rtrim($namespacedPath, '\\/') . DIRECTORY_SEPARATOR;
}
} else {
$this->prefixes[trim($namespace, '\\')][] = rtrim($path, '\\/') . DIRECTORY_SEPARATOR;
}
return $this;
}
/**
* Get namespaces with prefixes as keys and paths as values.
*
* If a prefix param is set, returns only paths to the given prefix.
*
* @return array<string, list<string>>|list<string>
* @phpstan-return ($prefix is null ? array<string, list<string>> : list<string>)
*/
public function getNamespace(?string $prefix = null)
{
if ($prefix === null) {
return $this->prefixes;
}
return $this->prefixes[trim($prefix, '\\')] ?? [];
}
/**
* Removes a single namespace from the psr4 settings.
*
* @return $this
*/
public function removeNamespace(string $namespace)
{
if (isset($this->prefixes[trim($namespace, '\\')])) {
unset($this->prefixes[trim($namespace, '\\')]);
}
return $this;
}
/**
* Load a class using available class mapping.
*
* @internal For `spl_autoload_register` use.
*/
public function loadClassmap(string $class): void
{
$file = $this->classmap[$class] ?? '';
if (is_string($file) && $file !== '') {
$this->includeFile($file);
}
}
/**
* Loads the class file for a given class name.
*
* @internal For `spl_autoload_register` use.
*
* @param string $class The fully qualified class name.
*/
public function loadClass(string $class): void
{
$this->loadInNamespace($class);
}
/**
* Loads the class file for a given class name.
*
* @param string $class The fully-qualified class name
*
* @return false|string The mapped file name on success, or boolean false on fail
*/
protected function loadInNamespace(string $class)
{
if (! str_contains($class, '\\')) {
return false;
}
foreach ($this->prefixes as $namespace => $directories) {
if (str_starts_with($class, $namespace)) {
$relativeClassPath = str_replace('\\', DIRECTORY_SEPARATOR, substr($class, strlen($namespace)));
foreach ($directories as $directory) {
$directory = rtrim($directory, '\\/');
$filePath = $directory . $relativeClassPath . '.php';
$filename = $this->includeFile($filePath);
if ($filename) {
return $filename;
}
}
}
}
// never found a mapped file
return false;
}
/**
* A central way to include a file. Split out primarily for testing purposes.
*
* @return false|string The filename on success, false if the file is not loaded
*/
protected function includeFile(string $file)
{
if (is_file($file)) {
include_once $file;
return $file;
}
return false;
}
/**
* Check file path.
*
* Checks special characters that are illegal in filenames on certain
* operating systems and special characters requiring special escaping
* to manipulate at the command line. Replaces spaces and consecutive
* dashes with a single dash. Trim period, dash and underscore from beginning
* and end of filename.
*
* @return string The sanitized filename
*
* @deprecated No longer used. See https://github.com/codeigniter4/CodeIgniter4/issues/7055
*/
public function sanitizeFilename(string $filename): string
{
// Only allow characters deemed safe for POSIX portable filenames.
// Plus the forward slash for directory separators since this might be a path.
// http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_278
// Modified to allow backslash and colons for on Windows machines.
$result = preg_match_all('/[^0-9\p{L}\s\/\-_.:\\\\]/u', $filename, $matches);
if ($result > 0) {
$chars = implode('', $matches[0]);
throw new InvalidArgumentException(
'The file path contains special characters "' . $chars
. '" that are not allowed: "' . $filename . '"',
);
}
if ($result === false) {
$message = preg_last_error_msg();
throw new RuntimeException($message . '. filename: "' . $filename . '"');
}
// Clean up our filename edges.
$cleanFilename = trim($filename, '.-_');
if ($filename !== $cleanFilename) {
throw new InvalidArgumentException('The characters ".-_" are not allowed in filename edges: "' . $filename . '"');
}
return $cleanFilename;
}
/**
* @param array{only?: list<string>, exclude?: list<string>} $composerPackages
*/
private function loadComposerNamespaces(ClassLoader $composer, array $composerPackages): void
{
$namespacePaths = $composer->getPrefixesPsr4();
// Get rid of duplicated namespaces.
$duplicatedNamespaces = ['CodeIgniter', APP_NAMESPACE, 'Config'];
foreach ($duplicatedNamespaces as $ns) {
if (isset($namespacePaths[$ns . '\\'])) {
unset($namespacePaths[$ns . '\\']);
}
}
if (! method_exists(InstalledVersions::class, 'getAllRawData')) { // @phpstan-ignore function.alreadyNarrowedType
throw new RuntimeException(
'Your Composer version is too old.'
. ' Please update Composer (run `composer self-update`) to v2.0.14 or later'
. ' and remove your vendor/ directory, and run `composer update`.',
);
}
// This method requires Composer 2.0.14 or later.
$allData = InstalledVersions::getAllRawData();
$packageList = [];
foreach ($allData as $list) {
$packageList = array_merge($packageList, $list['versions']);
}
// Check config for $composerPackages.
$only = $composerPackages['only'] ?? [];
$exclude = $composerPackages['exclude'] ?? [];
if ($only !== [] && $exclude !== []) {
throw new ConfigException('Cannot use "only" and "exclude" at the same time in "Config\Modules::$composerPackages".');
}
// Get install paths of packages to add namespace for auto-discovery.
$installPaths = [];
if ($only !== []) {
foreach ($packageList as $packageName => $data) {
if (in_array($packageName, $only, true) && isset($data['install_path'])) {
$installPaths[] = $data['install_path'];
}
}
} else {
foreach ($packageList as $packageName => $data) {
if (! in_array($packageName, $exclude, true) && isset($data['install_path'])) {
$installPaths[] = $data['install_path'];
}
}
}
$newPaths = [];
foreach ($namespacePaths as $namespace => $srcPaths) {
$add = false;
foreach ($srcPaths as $path) {
foreach ($installPaths as $installPath) {
if (str_starts_with($path, $installPath)) {
$add = true;
break 2;
}
}
}
if ($add) {
// Composer stores namespaces with trailing slash. We don't.
$newPaths[rtrim($namespace, '\\ ')] = $srcPaths;
}
}
$this->addNamespace($newPaths);
}
/**
* Locates autoload information from Composer, if available.
*
* @deprecated No longer used.
*
* @return void
*/
protected function discoverComposerNamespaces()
{
if (! is_file(COMPOSER_PATH)) {
return;
}
/**
* @var ClassLoader $composer
*/
$composer = include COMPOSER_PATH;
$paths = $composer->getPrefixesPsr4();
$classes = $composer->getClassMap();
unset($composer);
// Get rid of CodeIgniter so we don't have duplicates
if (isset($paths['CodeIgniter\\'])) {
unset($paths['CodeIgniter\\']);
}
$newPaths = [];
foreach ($paths as $key => $value) {
// Composer stores namespaces with trailing slash. We don't.
$newPaths[rtrim($key, '\\ ')] = $value;
}
$this->prefixes = array_merge($this->prefixes, $newPaths);
$this->classmap = array_merge($this->classmap, $classes);
}
/**
* Loads helpers
*/
public function loadHelpers(): void
{
helper($this->helpers);
}
/**
* Initializes Kint
*/
public function initializeKint(bool $debug = false): void
{
if ($debug) {
$this->autoloadKint();
$this->configureKint();
} elseif (class_exists(Kint::class)) {
// In case that Kint is already loaded via Composer.
Kint::$enabled_mode = false;
}
helper('kint');
}
private function autoloadKint(): void
{
// If we have KINT_DIR it means it's already loaded via composer
if (! defined('KINT_DIR')) {
spl_autoload_register(function ($class): void {
$class = explode('\\', $class);
if (array_shift($class) !== 'Kint') {
return;
}
$file = SYSTEMPATH . 'ThirdParty/Kint/' . implode('/', $class) . '.php';
if (is_file($file)) {
require_once $file;
}
});
require_once SYSTEMPATH . 'ThirdParty/Kint/init.php';
}
}
private function configureKint(): void
{
$config = new KintConfig();
Kint::$depth_limit = $config->maxDepth;
Kint::$display_called_from = $config->displayCalledFrom;
Kint::$expanded = $config->expanded;
if (isset($config->plugins) && is_array($config->plugins)) {
Kint::$plugins = $config->plugins;
}
$csp = service('csp');
if ($csp->enabled()) {
RichRenderer::$js_nonce = $csp->getScriptNonce();
RichRenderer::$css_nonce = $csp->getStyleNonce();
}
RichRenderer::$theme = $config->richTheme;
RichRenderer::$folder = $config->richFolder;
if (isset($config->richObjectPlugins) && is_array($config->richObjectPlugins)) {
RichRenderer::$value_plugins = $config->richObjectPlugins;
}
if (isset($config->richTabPlugins) && is_array($config->richTabPlugins)) {
RichRenderer::$tab_plugins = $config->richTabPlugins;
}
CliRenderer::$cli_colors = $config->cliColors;
CliRenderer::$force_utf8 = $config->cliForceUTF8;
CliRenderer::$detect_width = $config->cliDetectWidth;
CliRenderer::$min_terminal_width = $config->cliMinWidth;
}
}
@@ -0,0 +1,407 @@
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Autoloader;
/**
* Allows loading non-class files in a namespaced manner.
* Works with Helpers, Views, etc.
*
* @see \CodeIgniter\Autoloader\FileLocatorTest
*/
class FileLocator implements FileLocatorInterface
{
/**
* The Autoloader to use.
*
* @var Autoloader
*/
protected $autoloader;
/**
* List of classnames that did not exist.
*
* @var list<class-string>
*/
private array $invalidClassnames = [];
public function __construct(Autoloader $autoloader)
{
$this->autoloader = $autoloader;
}
/**
* Attempts to locate a file by examining the name for a namespace
* and looking through the PSR-4 namespaced files that we know about.
*
* @param string $file The relative file path or namespaced file to
* locate. If not namespaced, search in the app
* folder.
* @param non-empty-string|null $folder The folder within the namespace that we should
* look for the file. If $file does not contain
* this value, it will be appended to the namespace
* folder.
* @param string $ext The file extension the file should have.
*
* @return false|string The path to the file, or false if not found.
*/
public function locateFile(string $file, ?string $folder = null, string $ext = 'php')
{
$file = $this->ensureExt($file, $ext);
// Clears the folder name if it is at the beginning of the filename
if ($folder !== null && str_starts_with($file, $folder)) {
$file = substr($file, strlen($folder . '/'));
}
// Is not namespaced? Try the application folder.
if (! str_contains($file, '\\')) {
return $this->legacyLocate($file, $folder);
}
// Standardize slashes to handle nested directories.
$file = strtr($file, '/', '\\');
$file = ltrim($file, '\\');
$segments = explode('\\', $file);
// The first segment will be empty if a slash started the filename.
if ($segments[0] === '') {
unset($segments[0]);
}
$paths = [];
$filename = '';
// Namespaces always comes with arrays of paths
$namespaces = $this->autoloader->getNamespace();
foreach (array_keys($namespaces) as $namespace) {
if (substr($file, 0, strlen($namespace) + 1) === $namespace . '\\') {
$fileWithoutNamespace = substr($file, strlen($namespace));
// There may be sub-namespaces of the same vendor,
// so overwrite them with namespaces found later.
$paths = $namespaces[$namespace];
$filename = ltrim(str_replace('\\', '/', $fileWithoutNamespace), '/');
}
}
// if no namespaces matched then quit
if ($paths === []) {
return false;
}
// Check each path in the namespace
foreach ($paths as $path) {
// Ensure trailing slash
$path = rtrim($path, '/') . '/';
// If we have a folder name, then the calling function
// expects this file to be within that folder, like 'Views',
// or 'libraries'.
if ($folder !== null && ! str_contains($path . $filename, '/' . $folder . '/')) {
$path .= trim($folder, '/') . '/';
}
$path .= $filename;
if (is_file($path)) {
return $path;
}
}
return false;
}
/**
* Examines a file and returns the fully qualified class name.
*/
public function getClassname(string $file): string
{
if (is_dir($file)) {
return '';
}
$php = file_get_contents($file);
$tokens = token_get_all($php);
$dlm = false;
$namespace = '';
$className = '';
foreach ($tokens as $i => $token) {
if ($i < 2) {
continue;
}
if ((isset($tokens[$i - 2][1]) && ($tokens[$i - 2][1] === 'phpnamespace' || $tokens[$i - 2][1] === 'namespace')) || ($dlm && $tokens[$i - 1][0] === T_NS_SEPARATOR && $token[0] === T_STRING)) {
if (! $dlm) {
$namespace = '';
}
if (isset($token[1])) {
$namespace = $namespace !== '' ? $namespace . '\\' . $token[1] : $token[1];
$dlm = true;
}
} elseif ($dlm && ($token[0] !== T_NS_SEPARATOR) && ($token[0] !== T_STRING)) {
$dlm = false;
}
if (($tokens[$i - 2][0] === T_CLASS || (isset($tokens[$i - 2][1]) && $tokens[$i - 2][1] === 'phpclass'))
&& $tokens[$i - 1][0] === T_WHITESPACE
&& $token[0] === T_STRING) {
$className = $token[1];
break;
}
}
if ($className === '') {
return '';
}
return $namespace . '\\' . $className;
}
/**
* Searches through all of the defined namespaces looking for a file.
* Returns an array of all found locations for the defined file.
*
* Example:
*
* $locator->search('Config/Routes.php');
* // Assuming PSR4 namespaces include foo and bar, might return:
* [
* 'app/Modules/foo/Config/Routes.php',
* 'app/Modules/bar/Config/Routes.php',
* ]
*
* @return list<string>
*/
public function search(string $path, string $ext = 'php', bool $prioritizeApp = true): array
{
$path = $this->ensureExt($path, $ext);
$foundPaths = [];
$appPaths = [];
foreach ($this->getNamespaces() as $namespace) {
if (isset($namespace['path']) && is_file($namespace['path'] . $path)) {
$fullPath = $namespace['path'] . $path;
$resolvedPath = realpath($fullPath);
$fullPath = $resolvedPath !== false ? $resolvedPath : $fullPath;
if ($prioritizeApp) {
$foundPaths[] = $fullPath;
} elseif (str_starts_with($fullPath, APPPATH)) {
$appPaths[] = $fullPath;
} else {
$foundPaths[] = $fullPath;
}
}
}
if (! $prioritizeApp && $appPaths !== []) {
$foundPaths = [...$foundPaths, ...$appPaths];
}
// Remove any duplicates
return array_values(array_unique($foundPaths));
}
/**
* Ensures a extension is at the end of a filename
*/
protected function ensureExt(string $path, string $ext): string
{
if ($ext !== '') {
$ext = '.' . $ext;
if (! str_ends_with($path, $ext)) {
$path .= $ext;
}
}
return $path;
}
/**
* Return the namespace mappings we know about.
*
* @return array<int, array<string, string>>
*/
protected function getNamespaces()
{
$namespaces = [];
// Save system for last
$system = [];
foreach ($this->autoloader->getNamespace() as $prefix => $paths) {
foreach ($paths as $path) {
if ($prefix === 'CodeIgniter') {
$system[] = [
'prefix' => $prefix,
'path' => rtrim($path, '\\/') . DIRECTORY_SEPARATOR,
];
continue;
}
$namespaces[] = [
'prefix' => $prefix,
'path' => rtrim($path, '\\/') . DIRECTORY_SEPARATOR,
];
}
}
return array_merge($namespaces, $system);
}
public function findQualifiedNameFromPath(string $path)
{
$resolvedPath = realpath($path);
$path = $resolvedPath !== false ? $resolvedPath : $path;
if (! is_file($path)) {
return false;
}
foreach ($this->getNamespaces() as $namespace) {
$resolvedNamespacePath = realpath($namespace['path']);
$namespace['path'] = $resolvedNamespacePath !== false ? $resolvedNamespacePath : $namespace['path'];
if ($namespace['path'] === '') {
continue;
}
if (mb_strpos($path, $namespace['path']) === 0) {
$className = $namespace['prefix'] . '\\' .
ltrim(
str_replace(
'/',
'\\',
mb_substr($path, mb_strlen($namespace['path'])),
),
'\\',
);
// Remove the file extension (.php)
/** @var class-string */
$className = mb_substr($className, 0, -4);
if (in_array($className, $this->invalidClassnames, true)) {
continue;
}
// Check if this exists
if (class_exists($className)) {
return $className;
}
// If the class does not exist, it is an invalid classname.
$this->invalidClassnames[] = $className;
}
}
return false;
}
/**
* Scans the defined namespaces, returning a list of all files
* that are contained within the subpath specified by $path.
*
* @return list<string> List of file paths
*/
public function listFiles(string $path): array
{
if ($path === '') {
return [];
}
$files = [];
helper('filesystem');
foreach ($this->getNamespaces() as $namespace) {
$fullPath = $namespace['path'] . $path;
$resolvedPath = realpath($fullPath);
$fullPath = $resolvedPath !== false ? $resolvedPath : $fullPath;
if (! is_dir($fullPath)) {
continue;
}
$tempFiles = get_filenames($fullPath, true, false, false);
if ($tempFiles !== []) {
$files = array_merge($files, $tempFiles);
}
}
return $files;
}
/**
* Scans the provided namespace, returning a list of all files
* that are contained within the sub path specified by $path.
*
* @return list<string> List of file paths
*/
public function listNamespaceFiles(string $prefix, string $path): array
{
if ($path === '' || ($prefix === '')) {
return [];
}
$files = [];
helper('filesystem');
// autoloader->getNamespace($prefix) returns an array of paths for that namespace
foreach ($this->autoloader->getNamespace($prefix) as $namespacePath) {
$fullPath = rtrim($namespacePath, '/') . '/' . $path;
$resolvedPath = realpath($fullPath);
$fullPath = $resolvedPath !== false ? $resolvedPath : $fullPath;
if (! is_dir($fullPath)) {
continue;
}
$tempFiles = get_filenames($fullPath, true, false, false);
if ($tempFiles !== []) {
$files = array_merge($files, $tempFiles);
}
}
return $files;
}
/**
* Checks the app folder to see if the file can be found.
* Only for use with filenames that DO NOT include namespacing.
*
* @param non-empty-string|null $folder
*
* @return false|string The path to the file, or false if not found.
*/
protected function legacyLocate(string $file, ?string $folder = null)
{
$path = APPPATH . ($folder === null ? $file : $folder . '/' . $file);
$resolvedPath = realpath($path);
$path = $resolvedPath !== false ? $resolvedPath : $path;
if (is_file($path)) {
return $path;
}
return false;
}
}
@@ -0,0 +1,177 @@
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Autoloader;
use CodeIgniter\Cache\CacheInterface;
use CodeIgniter\Cache\FactoriesCache\FileVarExportHandler;
/**
* FileLocator with Cache
*
* @see \CodeIgniter\Autoloader\FileLocatorCachedTest
*/
final class FileLocatorCached implements FileLocatorInterface
{
/**
* @var CacheInterface|FileVarExportHandler
*/
private $cacheHandler;
/**
* Cache data
*
* [method => data]
* E.g.,
* [
* 'search' => [$path => $foundPaths],
* ]
*
* @var array<string, array<string, mixed>>
*/
private array $cache = [];
/**
* Is the cache updated?
*/
private bool $cacheUpdated = false;
private string $cacheKey = 'FileLocatorCache';
/**
* @param CacheInterface|FileVarExportHandler|null $cache
*/
public function __construct(private readonly FileLocator $locator, $cache = null)
{
$this->cacheHandler = $cache ?? new FileVarExportHandler();
$this->loadCache();
}
private function loadCache(): void
{
$data = $this->cacheHandler->get($this->cacheKey);
if (is_array($data)) {
$this->cache = $data;
}
}
public function __destruct()
{
$this->saveCache();
}
private function saveCache(): void
{
if ($this->cacheUpdated) {
$this->cacheHandler->save($this->cacheKey, $this->cache, 3600 * 24);
}
}
/**
* Delete cache data
*/
public function deleteCache(): void
{
$this->cacheUpdated = false;
$this->cacheHandler->delete($this->cacheKey);
}
public function findQualifiedNameFromPath(string $path): false|string
{
if (isset($this->cache['findQualifiedNameFromPath'][$path])) {
return $this->cache['findQualifiedNameFromPath'][$path];
}
$classname = $this->locator->findQualifiedNameFromPath($path);
$this->cache['findQualifiedNameFromPath'][$path] = $classname;
$this->cacheUpdated = true;
return $classname;
}
public function getClassname(string $file): string
{
if (isset($this->cache['getClassname'][$file])) {
return $this->cache['getClassname'][$file];
}
$classname = $this->locator->getClassname($file);
$this->cache['getClassname'][$file] = $classname;
$this->cacheUpdated = true;
return $classname;
}
/**
* @return list<string>
*/
public function search(string $path, string $ext = 'php', bool $prioritizeApp = true): array
{
if (isset($this->cache['search'][$path][$ext][$prioritizeApp])) {
return $this->cache['search'][$path][$ext][$prioritizeApp];
}
$foundPaths = $this->locator->search($path, $ext, $prioritizeApp);
$this->cache['search'][$path][$ext][$prioritizeApp] = $foundPaths;
$this->cacheUpdated = true;
return $foundPaths;
}
public function listFiles(string $path): array
{
if (isset($this->cache['listFiles'][$path])) {
return $this->cache['listFiles'][$path];
}
$files = $this->locator->listFiles($path);
$this->cache['listFiles'][$path] = $files;
$this->cacheUpdated = true;
return $files;
}
public function listNamespaceFiles(string $prefix, string $path): array
{
if (isset($this->cache['listNamespaceFiles'][$prefix][$path])) {
return $this->cache['listNamespaceFiles'][$prefix][$path];
}
$files = $this->locator->listNamespaceFiles($prefix, $path);
$this->cache['listNamespaceFiles'][$prefix][$path] = $files;
$this->cacheUpdated = true;
return $files;
}
public function locateFile(string $file, ?string $folder = null, string $ext = 'php'): false|string
{
if (isset($this->cache['locateFile'][$file][$folder][$ext])) {
return $this->cache['locateFile'][$file][$folder][$ext];
}
$files = $this->locator->locateFile($file, $folder, $ext);
$this->cache['locateFile'][$file][$folder][$ext] = $files;
$this->cacheUpdated = true;
return $files;
}
}
@@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Autoloader;
/**
* Allows loading non-class files in a namespaced manner.
* Works with Helpers, Views, etc.
*/
interface FileLocatorInterface
{
/**
* Attempts to locate a file by examining the name for a namespace
* and looking through the PSR-4 namespaced files that we know about.
*
* @param string $file The relative file path or namespaced file to
* locate. If not namespaced, search in the app
* folder.
* @param non-empty-string|null $folder The folder within the namespace that we should
* look for the file. If $file does not contain
* this value, it will be appended to the namespace
* folder.
* @param string $ext The file extension the file should have.
*
* @return false|string The path to the file, or false if not found.
*/
public function locateFile(string $file, ?string $folder = null, string $ext = 'php');
/**
* Examines a file and returns the fully qualified class name.
*/
public function getClassname(string $file): string;
/**
* Searches through all of the defined namespaces looking for a file.
* Returns an array of all found locations for the defined file.
*
* Example:
*
* $locator->search('Config/Routes.php');
* // Assuming PSR4 namespaces include foo and bar, might return:
* [
* 'app/Modules/foo/Config/Routes.php',
* 'app/Modules/bar/Config/Routes.php',
* ]
*
* @return list<string>
*/
public function search(string $path, string $ext = 'php', bool $prioritizeApp = true): array;
/**
* Find the qualified name of a file according to
* the namespace of the first matched namespace path.
*
* @return class-string|false The qualified name or false if the path is not found
*/
public function findQualifiedNameFromPath(string $path);
/**
* Scans the defined namespaces, returning a list of all files
* that are contained within the subpath specified by $path.
*
* @return list<string> List of file paths
*/
public function listFiles(string $path): array;
/**
* Scans the provided namespace, returning a list of all files
* that are contained within the sub path specified by $path.
*
* @return list<string> List of file paths
*/
public function listNamespaceFiles(string $prefix, string $path): array;
}