repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Service/FlexServiceProvider.php
system/src/Grav/Common/Service/FlexServiceProvider.php
<?php /** * @package Grav\Common\Service * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Common\Service; use Grav\Common\Config\Config; use Grav\Common\Flex\Types\Users\Storage\UserFileStorage; use Grav\Common\Flex\Types\Users\Storage\UserFolderStorage; use Grav\Common\Grav; use Grav\Events\FlexRegisterEvent; use Grav\Framework\Flex\Flex; use Grav\Framework\Flex\FlexFormFlash; use Pimple\Container; use Pimple\ServiceProviderInterface; use function is_array; /** * Class FlexServiceProvider * @package Grav\Common\Service */ class FlexServiceProvider implements ServiceProviderInterface { /** * @param Container $container * @return void */ public function register(Container $container) { $container['flex'] = function (Grav $container) { /** @var Config $config */ $config = $container['config']; $flex = new Flex([], ['object' => $config->get('system.flex', [])]); FlexFormFlash::setFlex($flex); $accountsEnabled = $config->get('system.accounts.type', 'regular') === 'flex'; $pagesEnabled = $config->get('system.pages.type', 'regular') === 'flex'; // Add built-in types from Grav. if ($pagesEnabled) { $flex->addDirectoryType( 'pages', 'blueprints://flex/pages.yaml', [ 'enabled' => $pagesEnabled ] ); } if ($accountsEnabled) { $flex->addDirectoryType( 'user-accounts', 'blueprints://flex/user-accounts.yaml', [ 'enabled' => $accountsEnabled, 'data' => [ 'storage' => $this->getFlexAccountsStorage($config), ] ] ); $flex->addDirectoryType( 'user-groups', 'blueprints://flex/user-groups.yaml', [ 'enabled' => $accountsEnabled ] ); } // Call event to register Flex Directories. $event = new FlexRegisterEvent($flex); $container->dispatchEvent($event); return $flex; }; } /** * @param Config $config * @return array */ private function getFlexAccountsStorage(Config $config): array { $value = $config->get('system.accounts.storage', 'file'); if (is_array($value)) { return $value; } if ($value === 'folder') { return [ 'class' => UserFolderStorage::class, 'options' => [ 'file' => 'user', 'pattern' => '{FOLDER}/{KEY:2}/{KEY}/{FILE}{EXT}', 'key' => 'storage_key', 'indexed' => true, 'case_sensitive' => false ], ]; } if ($value === 'file') { return [ 'class' => UserFileStorage::class, 'options' => [ 'pattern' => '{FOLDER}/{KEY}{EXT}', 'key' => 'username', 'indexed' => true, 'case_sensitive' => false ], ]; } return []; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Service/ConfigServiceProvider.php
system/src/Grav/Common/Service/ConfigServiceProvider.php
<?php /** * @package Grav\Common\Service * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Common\Service; use DirectoryIterator; use Grav\Common\Config\CompiledBlueprints; use Grav\Common\Config\CompiledConfig; use Grav\Common\Config\CompiledLanguages; use Grav\Common\Config\Config; use Grav\Common\Config\ConfigFileFinder; use Grav\Common\Config\Setup; use Grav\Common\Language\Language; use Grav\Framework\Mime\MimeTypes; use Pimple\Container; use Pimple\ServiceProviderInterface; use RocketTheme\Toolbox\File\YamlFile; use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator; /** * Class ConfigServiceProvider * @package Grav\Common\Service */ class ConfigServiceProvider implements ServiceProviderInterface { /** * @param Container $container * @return void */ public function register(Container $container) { $container['setup'] = function ($c) { $setup = new Setup($c); $setup->init(); return $setup; }; $container['blueprints'] = function ($c) { return static::blueprints($c); }; $container['config'] = function ($c) { $config = static::load($c); // After configuration has been loaded, we can disable YAML compatibility if strict mode has been enabled. if (!$config->get('system.strict_mode.yaml_compat', true)) { YamlFile::globalSettings(['compat' => false, 'native' => true]); } return $config; }; $container['mime'] = function ($c) { /** @var Config $config */ $config = $c['config']; $mimes = $config->get('mime.types', []); foreach ($config->get('media.types', []) as $ext => $media) { if (!empty($media['mime'])) { $mimes[$ext] = array_unique(array_merge([$media['mime']], $mimes[$ext] ?? [])); } } return MimeTypes::createFromMimes($mimes); }; $container['languages'] = function ($c) { return static::languages($c); }; $container['language'] = function ($c) { return new Language($c); }; } /** * @param Container $container * @return mixed */ public static function blueprints(Container $container) { /** Setup $setup */ $setup = $container['setup']; /** @var UniformResourceLocator $locator */ $locator = $container['locator']; $cache = $locator->findResource('cache://compiled/blueprints', true, true); $files = []; $paths = $locator->findResources('blueprints://config'); $files += (new ConfigFileFinder)->locateFiles($paths); $paths = $locator->findResources('plugins://'); $files += (new ConfigFileFinder)->setBase('plugins')->locateInFolders($paths, 'blueprints'); $paths = $locator->findResources('themes://'); $files += (new ConfigFileFinder)->setBase('themes')->locateInFolders($paths, 'blueprints'); $blueprints = new CompiledBlueprints($cache, $files, GRAV_ROOT); return $blueprints->name("master-{$setup->environment}")->load(); } /** * @param Container $container * @return Config */ public static function load(Container $container) { /** Setup $setup */ $setup = $container['setup']; /** @var UniformResourceLocator $locator */ $locator = $container['locator']; $cache = $locator->findResource('cache://compiled/config', true, true); $files = []; $paths = $locator->findResources('config://'); $files += (new ConfigFileFinder)->locateFiles($paths); $paths = $locator->findResources('plugins://'); $files += (new ConfigFileFinder)->setBase('plugins')->locateInFolders($paths); $paths = $locator->findResources('themes://'); $files += (new ConfigFileFinder)->setBase('themes')->locateInFolders($paths); $compiled = new CompiledConfig($cache, $files, GRAV_ROOT); $compiled->setBlueprints(function () use ($container) { return $container['blueprints']; }); $config = $compiled->name("master-{$setup->environment}")->load(); $config->environment = $setup->environment; return $config; } /** * @param Container $container * @return mixed */ public static function languages(Container $container) { /** @var Setup $setup */ $setup = $container['setup']; /** @var Config $config */ $config = $container['config']; /** @var UniformResourceLocator $locator */ $locator = $container['locator']; $cache = $locator->findResource('cache://compiled/languages', true, true); $files = []; // Process languages only if enabled in configuration. if ($config->get('system.languages.translations', true)) { $paths = $locator->findResources('languages://'); $files += (new ConfigFileFinder)->locateFiles($paths); $paths = $locator->findResources('plugins://'); $files += (new ConfigFileFinder)->setBase('plugins')->locateInFolders($paths, 'languages'); $paths = static::pluginFolderPaths($paths, 'languages'); $files += (new ConfigFileFinder)->locateFiles($paths); } $languages = new CompiledLanguages($cache, $files, GRAV_ROOT); return $languages->name("master-{$setup->environment}")->load(); } /** * Find specific paths in plugins * * @param array $plugins * @param string $folder_path * @return array */ protected static function pluginFolderPaths($plugins, $folder_path) { $paths = []; foreach ($plugins as $path) { $iterator = new DirectoryIterator($path); /** @var DirectoryIterator $directory */ foreach ($iterator as $directory) { if (!$directory->isDir() || $directory->isDot()) { continue; } // Path to the languages folder $lang_path = $directory->getPathName() . '/' . $folder_path; // If this folder exists, add it to the list of paths if (file_exists($lang_path)) { $paths []= $lang_path; } } } return $paths; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Service/TaskServiceProvider.php
system/src/Grav/Common/Service/TaskServiceProvider.php
<?php /** * @package Grav\Common\Service * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Common\Service; use Grav\Common\Grav; use Pimple\Container; use Pimple\ServiceProviderInterface; use Psr\Http\Message\ServerRequestInterface; /** * Class TaskServiceProvider * @package Grav\Common\Service */ class TaskServiceProvider implements ServiceProviderInterface { /** * @param Container $container * @return void */ public function register(Container $container) { $container['task'] = function (Grav $c) { /** @var ServerRequestInterface $request */ $request = $c['request']; $body = $request->getParsedBody(); $task = $body['task'] ?? $c['uri']->param('task'); if (null !== $task) { $task = htmlspecialchars(strip_tags($task), ENT_QUOTES, 'UTF-8'); } return $task ?: null; }; $container['action'] = function (Grav $c) { /** @var ServerRequestInterface $request */ $request = $c['request']; $body = $request->getParsedBody(); $action = $body['action'] ?? $c['uri']->param('action'); if (null !== $action) { $action = htmlspecialchars(strip_tags($action), ENT_QUOTES, 'UTF-8'); } return $action ?: null; }; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Service/SessionServiceProvider.php
system/src/Grav/Common/Service/SessionServiceProvider.php
<?php /** * @package Grav\Common\Service * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Common\Service; use Grav\Common\Config\Config; use Grav\Common\Debugger; use Grav\Common\Session; use Grav\Common\Uri; use Grav\Common\Utils; use Grav\Framework\Session\Messages; use Pimple\Container; use Pimple\ServiceProviderInterface; /** * Class SessionServiceProvider * @package Grav\Common\Service */ class SessionServiceProvider implements ServiceProviderInterface { /** * @param Container $container * @return void */ public function register(Container $container) { // Define session service. $container['session'] = static function ($c) { /** @var Config $config */ $config = $c['config']; /** @var Uri $uri */ $uri = $c['uri']; // Get session options. $enabled = (bool)$config->get('system.session.enabled', false); $cookie_secure = $config->get('system.session.secure', false) || ($config->get('system.session.secure_https', true) && $uri->scheme(true) === 'https'); $cookie_httponly = (bool)$config->get('system.session.httponly', true); $cookie_lifetime = (int)$config->get('system.session.timeout', 1800); $cookie_domain = $config->get('system.session.domain'); $cookie_path = $config->get('system.session.path'); $cookie_samesite = $config->get('system.session.samesite', 'Lax'); if (null === $cookie_domain) { $cookie_domain = $uri->host(); if ($cookie_domain === 'localhost') { $cookie_domain = ''; } } if (null === $cookie_path) { $cookie_path = '/' . trim(Uri::filterPath($uri->rootUrl(false)), '/'); } // Session cookie path requires trailing slash. $cookie_path = rtrim($cookie_path, '/') . '/'; // Activate admin if we're inside the admin path. $is_admin = false; if ($config->get('plugins.admin.enabled')) { $admin_base = '/' . trim($config->get('plugins.admin.route'), '/'); // Uri::route() is not processed yet, let's quickly get what we need. $current_route = str_replace(Uri::filterPath($uri->rootUrl(false)), '', parse_url($uri->url(true), PHP_URL_PATH)); // Test to see if path starts with a supported language + admin base $lang = Utils::pathPrefixedByLangCode($current_route); $lang_admin_base = '/' . $lang . $admin_base; // Check no language, simple language prefix (en) and region specific language prefix (en-US). if (Utils::startsWith($current_route, $admin_base) || Utils::startsWith($current_route, $lang_admin_base)) { $cookie_lifetime = $config->get('plugins.admin.session.timeout', 1800); $enabled = $is_admin = true; } } // Fix for HUGE session timeouts. if ($cookie_lifetime > 99999999999) { $cookie_lifetime = 9999999999; } $session_prefix = $c['inflector']->hyphenize($config->get('system.session.name', 'grav-site')); $session_uniqueness = $config->get('system.session.uniqueness', 'path') === 'path' ? substr(md5(GRAV_ROOT), 0, 7) : md5($config->get('security.salt')); $session_name = $session_prefix . '-' . $session_uniqueness; if ($is_admin && $config->get('system.session.split', true)) { $session_name .= '-admin'; } // Define session service. $options = [ 'name' => $session_name, 'cookie_lifetime' => $cookie_lifetime, 'cookie_path' => $cookie_path, 'cookie_domain' => $cookie_domain, 'cookie_secure' => $cookie_secure, 'cookie_httponly' => $cookie_httponly, 'cookie_samesite' => $cookie_samesite ] + (array) $config->get('system.session.options'); $session = new Session($options); $session->setAutoStart($enabled); return $session; }; // Define session message service. $container['messages'] = function ($c) { if (!isset($c['session']) || !$c['session']->isStarted()) { /** @var Debugger $debugger */ $debugger = $c['debugger']; $debugger->addMessage('Inactive session: session messages may disappear', 'warming'); return new Messages(); } /** @var Session $session */ $session = $c['session']; if (!$session->messages instanceof Messages) { $session->messages = new Messages(); } return $session->messages; }; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Service/InflectorServiceProvider.php
system/src/Grav/Common/Service/InflectorServiceProvider.php
<?php /** * @package Grav\Common\Service * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Common\Service; use Grav\Common\Inflector; use Pimple\Container; use Pimple\ServiceProviderInterface; /** * Class InflectorServiceProvider * @package Grav\Common\Service */ class InflectorServiceProvider implements ServiceProviderInterface { /** * @param Container $container * @return void */ public function register(Container $container) { $container['inflector'] = function () { return new Inflector(); }; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Service/LoggerServiceProvider.php
system/src/Grav/Common/Service/LoggerServiceProvider.php
<?php /** * @package Grav\Common\Service * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Common\Service; use Monolog\Handler\StreamHandler; use Monolog\Logger; use Pimple\Container; use Pimple\ServiceProviderInterface; use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator; /** * Class LoggerServiceProvider * @package Grav\Common\Service */ class LoggerServiceProvider implements ServiceProviderInterface { /** * @param Container $container * @return void */ public function register(Container $container) { $container['log'] = function ($c) { $log = new Logger('grav'); /** @var UniformResourceLocator $locator */ $locator = $c['locator']; $log_file = $locator->findResource('log://grav.log', true, true); $log->pushHandler(new StreamHandler($log_file, Logger::DEBUG)); return $log; }; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Service/ErrorServiceProvider.php
system/src/Grav/Common/Service/ErrorServiceProvider.php
<?php /** * @package Grav\Common\Service * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Common\Service; use Grav\Common\Errors\Errors; use Pimple\Container; use Pimple\ServiceProviderInterface; /** * Class ErrorServiceProvider * @package Grav\Common\Service */ class ErrorServiceProvider implements ServiceProviderInterface { /** * @param Container $container * @return void */ public function register(Container $container) { $container['errors'] = new Errors; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Service/FilesystemServiceProvider.php
system/src/Grav/Common/Service/FilesystemServiceProvider.php
<?php /** * @package Grav\Common\Service * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Common\Service; use Grav\Framework\Filesystem\Filesystem; use Pimple\Container; use Pimple\ServiceProviderInterface; /** * Class FilesystemServiceProvider * @package Grav\Common\Service */ class FilesystemServiceProvider implements ServiceProviderInterface { /** * @param Container $container * @return void */ public function register(Container $container) { $container['filesystem'] = function () { return Filesystem::getInstance(); }; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Service/RequestServiceProvider.php
system/src/Grav/Common/Service/RequestServiceProvider.php
<?php /** * @package Grav\Common\Service * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Common\Service; use Grav\Common\Uri; use JsonException; use Nyholm\Psr7\Factory\Psr17Factory; use Nyholm\Psr7Server\ServerRequestCreator; use Pimple\Container; use Pimple\ServiceProviderInterface; use function explode; use function fopen; use function function_exists; use function in_array; use function is_array; use function strtolower; use function trim; /** * Class RequestServiceProvider * @package Grav\Common\Service */ class RequestServiceProvider implements ServiceProviderInterface { /** * @param Container $container * @return void */ public function register(Container $container) { $container['request'] = function () { $psr17Factory = new Psr17Factory(); $creator = new ServerRequestCreator( $psr17Factory, // ServerRequestFactory $psr17Factory, // UriFactory $psr17Factory, // UploadedFileFactory $psr17Factory // StreamFactory ); $server = $_SERVER; if (false === isset($server['REQUEST_METHOD'])) { $server['REQUEST_METHOD'] = 'GET'; } $method = $server['REQUEST_METHOD']; $headers = function_exists('getallheaders') ? getallheaders() : $creator::getHeadersFromServer($_SERVER); $post = null; if (in_array($method, ['POST', 'PUT', 'PATCH', 'DELETE'])) { foreach ($headers as $headerName => $headerValue) { if ('content-type' !== strtolower($headerName)) { continue; } $contentType = strtolower(trim(explode(';', $headerValue, 2)[0])); switch ($contentType) { case 'application/x-www-form-urlencoded': case 'multipart/form-data': $post = $_POST; break 2; case 'application/json': case 'application/vnd.api+json': try { $json = file_get_contents('php://input'); $post = json_decode($json, true, 512, JSON_THROW_ON_ERROR); if (!is_array($post)) { $post = null; } } catch (JsonException $e) { $post = null; } break 2; } } } // Remove _url from ngnix routes. $get = $_GET; unset($get['_url']); if (isset($server['QUERY_STRING'])) { $query = $server['QUERY_STRING']; if (strpos($query, '_url=') !== false) { parse_str($query, $query); unset($query['_url']); $server['QUERY_STRING'] = http_build_query($query); } } return $creator->fromArrays($server, $headers, $_COOKIE, $get, $post, $_FILES, fopen('php://input', 'rb') ?: null); }; $container['route'] = $container->factory(function () { return clone Uri::getCurrentRoute(); }); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/ConsoleTrait.php
system/src/Grav/Console/ConsoleTrait.php
<?php /** * @package Grav\Console * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console; use Exception; use Grav\Common\Cache; use Grav\Common\Grav; use Grav\Common\Composer; use Grav\Common\Language\Language; use Grav\Common\Processors\InitializeProcessor; use Grav\Console\Cli\ClearCacheCommand; use RocketTheme\Toolbox\Event\Event; use RocketTheme\Toolbox\File\YamlFile; use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; /** * Trait ConsoleTrait * @package Grav\Console */ trait ConsoleTrait { /** @var string */ protected $argv; /** @var InputInterface */ protected $input; /** @var SymfonyStyle */ protected $output; /** @var array */ protected $local_config; /** @var bool */ private $plugins_initialized = false; /** @var bool */ private $themes_initialized = false; /** @var bool */ private $pages_initialized = false; /** * Set colors style definition for the formatter. * * @param InputInterface $input * @param OutputInterface $output * @return void */ public function setupConsole(InputInterface $input, OutputInterface $output) { $this->argv = $_SERVER['argv'][0]; $this->input = $input; $this->output = new SymfonyStyle($input, $output); $this->setupGrav(); } public function getInput(): InputInterface { return $this->input; } /** * @return SymfonyStyle */ public function getIO(): SymfonyStyle { return $this->output; } /** * Adds an option. * * @param string $name The option name * @param string|array|null $shortcut The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts * @param int|null $mode The option mode: One of the InputOption::VALUE_* constants * @param string $description A description text * @param string|string[]|int|bool|null $default The default value (must be null for InputOption::VALUE_NONE) * @return $this * @throws InvalidArgumentException If option mode is invalid or incompatible */ public function addOption($name, $shortcut = null, $mode = null, $description = '', $default = null) { if ($name !== 'env' && $name !== 'lang') { parent::addOption($name, $shortcut, $mode, $description, $default); } return $this; } /** * @return void */ final protected function setupGrav(): void { try { $language = $this->input->getOption('lang'); if ($language) { // Set used language. $this->setLanguage($language); } } catch (InvalidArgumentException $e) {} // Initialize cache with CLI compatibility $grav = Grav::instance(); $grav['config']->set('system.cache.cli_compatibility', true); } /** * Initialize Grav. * * - Load configuration * - Initialize logger * - Disable debugger * - Set timezone, locale * - Load plugins (call PluginsLoadedEvent) * - Set Pages and Users type to be used in the site * * Safe to be called multiple times. * * @return $this */ final protected function initializeGrav() { InitializeProcessor::initializeCli(Grav::instance()); return $this; } /** * Set language to be used in CLI. * * @param string|null $code * @return $this */ final protected function setLanguage(string $code = null) { $this->initializeGrav(); $grav = Grav::instance(); /** @var Language $language */ $language = $grav['language']; if ($language->enabled()) { if ($code && $language->validate($code)) { $language->setActive($code); } else { $language->setActive($language->getDefault()); } } return $this; } /** * Properly initialize plugins. * * - call $this->initializeGrav() * - call onPluginsInitialized event * * Safe to be called multiple times. * * @return $this */ final protected function initializePlugins() { if (!$this->plugins_initialized) { $this->plugins_initialized = true; $this->initializeGrav(); // Initialize plugins. $grav = Grav::instance(); $grav['plugins']->init(); $grav->fireEvent('onPluginsInitialized'); } return $this; } /** * Properly initialize themes. * * - call $this->initializePlugins() * - initialize theme (call onThemeInitialized event) * * Safe to be called multiple times. * * @return $this */ final protected function initializeThemes() { if (!$this->themes_initialized) { $this->themes_initialized = true; $this->initializePlugins(); // Initialize themes. $grav = Grav::instance(); $grav['themes']->init(); } return $this; } /** * Properly initialize pages. * * - call $this->initializeThemes() * - initialize assets (call onAssetsInitialized event) * - initialize twig (calls the twig events) * - initialize pages (calls onPagesInitialized event) * * Safe to be called multiple times. * * @return $this */ final protected function initializePages() { if (!$this->pages_initialized) { $this->pages_initialized = true; $this->initializeThemes(); $grav = Grav::instance(); // Initialize assets. $grav['assets']->init(); $grav->fireEvent('onAssetsInitialized'); // Initialize twig. $grav['twig']->init(); // Initialize pages. $pages = $grav['pages']; $pages->init(); $grav->fireEvent('onPagesInitialized', new Event(['pages' => $pages])); } return $this; } /** * @param string $path * @return void */ public function isGravInstance($path) { $io = $this->getIO(); if (!file_exists($path)) { $io->writeln(''); $io->writeln("<red>ERROR</red>: Destination doesn't exist:"); $io->writeln(" <white>$path</white>"); $io->writeln(''); exit; } if (!is_dir($path)) { $io->writeln(''); $io->writeln("<red>ERROR</red>: Destination chosen to install is not a directory:"); $io->writeln(" <white>$path</white>"); $io->writeln(''); exit; } if (!file_exists($path . DS . 'index.php') || !file_exists($path . DS . '.dependencies') || !file_exists($path . DS . 'system' . DS . 'config' . DS . 'system.yaml')) { $io->writeln(''); $io->writeln('<red>ERROR</red>: Destination chosen to install does not appear to be a Grav instance:'); $io->writeln(" <white>$path</white>"); $io->writeln(''); exit; } } /** * @param string $path * @param string $action * @return string|false */ public function composerUpdate($path, $action = 'install') { $composer = Composer::getComposerExecutor(); return system($composer . ' --working-dir=' . escapeshellarg($path) . ' --no-interaction --no-dev --prefer-dist -o '. $action); } /** * @param array $all * @return int * @throws Exception */ public function clearCache($all = []) { if ($all) { $all = ['--all' => true]; } $command = new ClearCacheCommand(); $input = new ArrayInput($all); return $command->run($input, $this->output); } /** * @return void */ public function invalidateCache() { Cache::invalidateCache(); } /** * Load the local config file * * @return string|false The local config file name. false if local config does not exist */ public function loadLocalConfig() { $home_folder = getenv('HOME') ?: getenv('HOMEDRIVE') . getenv('HOMEPATH'); $local_config_file = $home_folder . '/.grav/config'; if (file_exists($local_config_file)) { $file = YamlFile::instance($local_config_file); $this->local_config = $file->content(); $file->free(); return $local_config_file; } return false; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/ConsoleCommand.php
system/src/Grav/Console/ConsoleCommand.php
<?php /** * @package Grav\Console * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * Class ConsoleCommand * @package Grav\Console */ class ConsoleCommand extends Command { use ConsoleTrait; /** * @param InputInterface $input * @param OutputInterface $output * @return int */ protected function execute(InputInterface $input, OutputInterface $output) { $this->setupConsole($input, $output); return $this->serve(); } /** * Override with your implementation. * * @return int */ protected function serve() { // Return error. return 1; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/GpmCommand.php
system/src/Grav/Console/GpmCommand.php
<?php /** * @package Grav\Console * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console; use Grav\Common\Config\Config; use Grav\Common\Grav; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * Class ConsoleCommand * @package Grav\Console */ class GpmCommand extends Command { use ConsoleTrait; /** * @param InputInterface $input * @param OutputInterface $output * @return int */ protected function execute(InputInterface $input, OutputInterface $output) { $this->setupConsole($input, $output); $grav = Grav::instance(); $grav['config']->init(); $grav['uri']->init(); // @phpstan-ignore-next-line $grav['accounts']; return $this->serve(); } /** * Override with your implementation. * * @return int */ protected function serve() { // Return error. return 1; } /** * @return void */ protected function displayGPMRelease() { /** @var Config $config */ $config = Grav::instance()['config']; $io = $this->getIO(); $io->newLine(); $io->writeln('GPM Releases Configuration: <yellow>' . ucfirst($config->get('system.gpm.releases')) . '</yellow>'); $io->newLine(); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/GravCommand.php
system/src/Grav/Console/GravCommand.php
<?php /** * @package Grav\Console * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * Class ConsoleCommand * @package Grav\Console */ class GravCommand extends Command { use ConsoleTrait; /** * @param InputInterface $input * @param OutputInterface $output * @return int */ protected function execute(InputInterface $input, OutputInterface $output) { $this->setupConsole($input, $output); // Old versions of Grav called this command after grav upgrade. // We need make this command to work with older ConsoleTrait: if (method_exists($this, 'initializeGrav')) { $this->initializeGrav(); } return $this->serve(); } /** * Override with your implementation. * * @return int */ protected function serve() { // Return error. return 1; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Application/Application.php
system/src/Grav/Console/Application/Application.php
<?php /** * @package Grav\Console * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Application; use Grav\Common\Grav; use Symfony\Component\Console\ConsoleEvents; use Symfony\Component\Console\Event\ConsoleCommandEvent; use Symfony\Component\Console\Formatter\OutputFormatterStyle; use Symfony\Component\Console\Input\InputDefinition; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\EventDispatcher\EventDispatcher; /** * Class GpmApplication * @package Grav\Console\Application */ class Application extends \Symfony\Component\Console\Application { /** @var string|null */ protected $environment; /** @var string|null */ protected $language; /** @var bool */ protected $initialized = false; /** * PluginApplication constructor. * @param string $name * @param string $version */ public function __construct(string $name = 'UNKNOWN', string $version = 'UNKNOWN') { parent::__construct($name, $version); // Add listener to prepare environment. $dispatcher = new EventDispatcher(); $dispatcher->addListener(ConsoleEvents::COMMAND, [$this, 'prepareEnvironment']); $this->setDispatcher($dispatcher); } /** * @param InputInterface $input * @return string|null */ public function getCommandName(InputInterface $input): ?string { if ($input->hasParameterOption('--env', true)) { $this->environment = $input->getParameterOption('--env'); } if ($input->hasParameterOption('--lang', true)) { $this->language = $input->getParameterOption('--lang'); } $this->init(); return parent::getCommandName($input); } /** * @param ConsoleCommandEvent $event * @return void */ public function prepareEnvironment(ConsoleCommandEvent $event): void { } /** * @return void */ protected function init(): void { if ($this->initialized) { return; } $this->initialized = true; $grav = Grav::instance(); $grav->setup($this->environment); } /** * Add global --env and --lang options. * * @return InputDefinition */ protected function getDefaultInputDefinition(): InputDefinition { $inputDefinition = parent::getDefaultInputDefinition(); $inputDefinition->addOption( new InputOption( '--env', '', InputOption::VALUE_OPTIONAL, 'Use environment configuration (defaults to localhost)' ) ); $inputDefinition->addOption( new InputOption( '--lang', '', InputOption::VALUE_OPTIONAL, 'Language to be used (defaults to en)' ) ); return $inputDefinition; } /** * @param InputInterface $input * @param OutputInterface $output * @return void */ protected function configureIO(InputInterface $input, OutputInterface $output) { $formatter = $output->getFormatter(); $formatter->setStyle('normal', new OutputFormatterStyle('white')); $formatter->setStyle('yellow', new OutputFormatterStyle('yellow', null, ['bold'])); $formatter->setStyle('red', new OutputFormatterStyle('red', null, ['bold'])); $formatter->setStyle('cyan', new OutputFormatterStyle('cyan', null, ['bold'])); $formatter->setStyle('green', new OutputFormatterStyle('green', null, ['bold'])); $formatter->setStyle('magenta', new OutputFormatterStyle('magenta', null, ['bold'])); $formatter->setStyle('white', new OutputFormatterStyle('white', null, ['bold'])); parent::configureIO($input, $output); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Application/GravApplication.php
system/src/Grav/Console/Application/GravApplication.php
<?php /** * @package Grav\Console * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Application; use Grav\Console\Cli\BackupCommand; use Grav\Console\Cli\CleanCommand; use Grav\Console\Cli\ClearCacheCommand; use Grav\Console\Cli\ComposerCommand; use Grav\Console\Cli\InstallCommand; use Grav\Console\Cli\LogViewerCommand; use Grav\Console\Cli\NewProjectCommand; use Grav\Console\Cli\PageSystemValidatorCommand; use Grav\Console\Cli\SandboxCommand; use Grav\Console\Cli\SchedulerCommand; use Grav\Console\Cli\SecurityCommand; use Grav\Console\Cli\ServerCommand; use Grav\Console\Cli\YamlLinterCommand; /** * Class GravApplication * @package Grav\Console\Application */ class GravApplication extends Application { public function __construct(string $name = 'UNKNOWN', string $version = 'UNKNOWN') { parent::__construct($name, $version); $this->addCommands([ new InstallCommand(), new ComposerCommand(), new SandboxCommand(), new CleanCommand(), new ClearCacheCommand(), new BackupCommand(), new NewProjectCommand(), new SchedulerCommand(), new SecurityCommand(), new LogViewerCommand(), new YamlLinterCommand(), new ServerCommand(), new PageSystemValidatorCommand(), ]); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Application/GpmApplication.php
system/src/Grav/Console/Application/GpmApplication.php
<?php /** * @package Grav\Console * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Application; use Grav\Console\Gpm\DirectInstallCommand; use Grav\Console\Gpm\IndexCommand; use Grav\Console\Gpm\InfoCommand; use Grav\Console\Gpm\InstallCommand; use Grav\Console\Gpm\SelfupgradeCommand; use Grav\Console\Gpm\UninstallCommand; use Grav\Console\Gpm\UpdateCommand; use Grav\Console\Gpm\VersionCommand; /** * Class GpmApplication * @package Grav\Console\Application */ class GpmApplication extends Application { public function __construct(string $name = 'UNKNOWN', string $version = 'UNKNOWN') { parent::__construct($name, $version); $this->addCommands([ new IndexCommand(), new VersionCommand(), new InfoCommand(), new InstallCommand(), new UninstallCommand(), new UpdateCommand(), new SelfupgradeCommand(), new DirectInstallCommand(), ]); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Application/PluginApplication.php
system/src/Grav/Console/Application/PluginApplication.php
<?php /** * @package Grav\Console * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Application; use Grav\Common\Grav; use Grav\Common\Plugins; use Grav\Console\Application\CommandLoader\PluginCommandLoader; use Grav\Console\Plugin\PluginListCommand; use Symfony\Component\Console\Exception\NamespaceNotFoundException; use Symfony\Component\Console\Input\ArgvInput; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Throwable; /** * Class PluginApplication * @package Grav\Console\Application */ class PluginApplication extends Application { /** @var string|null */ protected $pluginName; /** * PluginApplication constructor. * @param string $name * @param string $version */ public function __construct(string $name = 'UNKNOWN', string $version = 'UNKNOWN') { parent::__construct($name, $version); $this->addCommands([ new PluginListCommand(), ]); } /** * @param string $pluginName * @return void */ public function setPluginName(string $pluginName): void { $this->pluginName = $pluginName; } /** * @return string */ public function getPluginName(): string { return $this->pluginName; } /** * @param InputInterface|null $input * @param OutputInterface|null $output * @return int * @throws Throwable */ public function run(InputInterface $input = null, OutputInterface $output = null): int { if (null === $input) { $argv = $_SERVER['argv'] ?? []; $bin = array_shift($argv); $this->pluginName = array_shift($argv); $argv = array_merge([$bin], $argv); $input = new ArgvInput($argv); } return parent::run($input, $output); } /** * @return void */ protected function init(): void { if ($this->initialized) { return; } parent::init(); if (null === $this->pluginName) { $this->setDefaultCommand('plugins:list'); return; } $grav = Grav::instance(); $grav->initializeCli(); /** @var Plugins $plugins */ $plugins = $grav['plugins']; $plugin = $this->pluginName ? $plugins::get($this->pluginName) : null; if (null === $plugin) { throw new NamespaceNotFoundException("Plugin \"{$this->pluginName}\" is not installed."); } if (!$plugin->enabled) { throw new NamespaceNotFoundException("Plugin \"{$this->pluginName}\" is not enabled."); } $this->setCommandLoader(new PluginCommandLoader($this->pluginName)); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Application/CommandLoader/PluginCommandLoader.php
system/src/Grav/Console/Application/CommandLoader/PluginCommandLoader.php
<?php /** * @package Grav\Console * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Application\CommandLoader; use Grav\Common\Filesystem\Folder; use Grav\Common\Grav; use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator; use RuntimeException; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\CommandLoader\CommandLoaderInterface; use Symfony\Component\Console\Exception\CommandNotFoundException; /** * Class GpmApplication * @package Grav\Console\Application */ class PluginCommandLoader implements CommandLoaderInterface { /** @var array */ private $commands; /** * PluginCommandLoader constructor. * * @param string $name */ public function __construct(string $name) { $this->commands = []; try { $path = "plugins://{$name}/cli"; $pattern = '([A-Z]\w+Command\.php)'; $commands = is_dir($path) ? Folder::all($path, ['compare' => 'Filename', 'pattern' => '/' . $pattern . '$/usm', 'levels' => 1]) : []; } catch (RuntimeException $e) { throw new RuntimeException("Failed to load console commands for plugin {$name}"); } $grav = Grav::instance(); /** @var UniformResourceLocator $locator */ $locator = $grav['locator']; foreach ($commands as $command_path) { $full_path = $locator->findResource("plugins://{$name}/cli/{$command_path}"); require_once $full_path; $command_class = 'Grav\Plugin\Console\\' . preg_replace('/.php$/', '', $command_path); if (class_exists($command_class)) { $command = new $command_class(); if ($command instanceof Command) { $this->commands[$command->getName()] = $command; // If the command has an alias, add that as a possible command name. $aliases = $this->commands[$command->getName()]->getAliases(); if (isset($aliases)) { foreach ($aliases as $alias) { $this->commands[$alias] = $command; } } } } } } /** * @param string $name * @return Command */ public function get($name): Command { $command = $this->commands[$name] ?? null; if (null === $command) { throw new CommandNotFoundException(sprintf('The command "%s" does not exist.', $name)); } return $command; } /** * @param string $name * @return bool */ public function has($name): bool { return isset($this->commands[$name]); } /** * @return string[] */ public function getNames(): array { return array_keys($this->commands); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Plugin/PluginListCommand.php
system/src/Grav/Console/Plugin/PluginListCommand.php
<?php /** * @package Grav\Console\Plugin * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Plugin; use Grav\Common\Filesystem\Folder; use Grav\Common\Plugins; use Grav\Console\ConsoleCommand; /** * Class InfoCommand * @package Grav\Console\Gpm */ class PluginListCommand extends ConsoleCommand { protected static $defaultName = 'plugins:list'; /** * @return void */ protected function configure(): void { $this->setHidden(true); } /** * @return int */ protected function serve(): int { $bin = $this->argv; $pattern = '([A-Z]\w+Command\.php)'; $io = $this->getIO(); $io->newLine(); $io->writeln('<red>Usage:</red>'); $io->writeln(" {$bin} [slug] [command] [arguments]"); $io->newLine(); $io->writeln('<red>Example:</red>'); $io->writeln(" {$bin} error log -l 1 --trace"); $io->newLine(); $io->writeln('<red>Plugins with CLI available:</red>'); $plugins = Plugins::all(); $index = 0; foreach ($plugins as $name => $plugin) { if (!$plugin->enabled) { continue; } $list = Folder::all("plugins://{$name}", ['compare' => 'Pathname', 'pattern' => '/\/cli\/' . $pattern . '$/usm', 'levels' => 1]); if (!$list) { continue; } $index++; $num = str_pad((string)$index, 2, '0', STR_PAD_LEFT); $io->writeln(' ' . $num . '. <red>' . str_pad($name, 15) . "</red> <white>{$bin} {$name} list</white>"); } return 0; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Gpm/VersionCommand.php
system/src/Grav/Console/Gpm/VersionCommand.php
<?php /** * @package Grav\Console\Gpm * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Gpm; use Grav\Common\GPM\GPM; use Grav\Common\GPM\Upgrader; use Grav\Common\Grav; use Grav\Console\GpmCommand; use RocketTheme\Toolbox\File\YamlFile; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use function count; /** * Class VersionCommand * @package Grav\Console\Gpm */ class VersionCommand extends GpmCommand { /** @var GPM */ protected $gpm; /** * @return void */ protected function configure(): void { $this ->setName('version') ->addOption( 'force', 'f', InputOption::VALUE_NONE, 'Force re-fetching the data from remote' ) ->addArgument( 'package', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'The package or packages that is desired to know the version of. By default and if not specified this would be grav' ) ->setDescription('Shows the version of an installed package. If available also shows pending updates.') ->setHelp('The <info>version</info> command displays the current version of a package installed and, if available, the available version of pending updates'); } /** * @return int */ protected function serve(): int { $input = $this->getInput(); $io = $this->getIO(); $this->gpm = new GPM($input->getOption('force')); $packages = $input->getArgument('package'); $installed = false; if (!count($packages)) { $packages = ['grav']; } foreach ($packages as $package) { $package = strtolower($package); $name = null; $version = null; $updatable = false; if ($package === 'grav') { $name = 'Grav'; $version = GRAV_VERSION; $upgrader = new Upgrader(); if ($upgrader->isUpgradable()) { $updatable = " [upgradable: v<green>{$upgrader->getRemoteVersion()}</green>]"; } } else { // get currently installed version $locator = Grav::instance()['locator']; $blueprints_path = $locator->findResource('plugins://' . $package . DS . 'blueprints.yaml'); if (!file_exists($blueprints_path)) { // theme? $blueprints_path = $locator->findResource('themes://' . $package . DS . 'blueprints.yaml'); if (!file_exists($blueprints_path)) { continue; } } $file = YamlFile::instance($blueprints_path); $package_yaml = $file->content(); $file->free(); $version = $package_yaml['version']; if (!$version) { continue; } $installed = $this->gpm->findPackage($package); if ($installed) { $name = $installed->name; if ($this->gpm->isUpdatable($package)) { $updatable = " [updatable: v<green>{$installed->available}</green>]"; } } } $updatable = $updatable ?: ''; if ($installed || $package === 'grav') { $io->writeln("You are running <white>{$name}</white> v<cyan>{$version}</cyan>{$updatable}"); } else { $io->writeln("Package <red>{$package}</red> not found"); } } return 0; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Gpm/InstallCommand.php
system/src/Grav/Console/Gpm/InstallCommand.php
<?php /** * @package Grav\Console\Gpm * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Gpm; use Exception; use Grav\Common\Filesystem\Folder; use Grav\Common\HTTP\Response; use Grav\Common\GPM\GPM; use Grav\Common\GPM\Installer; use Grav\Common\GPM\Licenses; use Grav\Common\GPM\Remote\Package; use Grav\Common\Grav; use Grav\Common\Utils; use Grav\Console\GpmCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Question\ConfirmationQuestion; use ZipArchive; use function array_key_exists; use function count; use function define; define('GIT_REGEX', '/http[s]?:\/\/(?:.*@)?(github|bitbucket)(?:.org|.com)\/.*\/(.*)/'); /** * Class InstallCommand * @package Grav\Console\Gpm */ class InstallCommand extends GpmCommand { /** @var array */ protected $data; /** @var GPM */ protected $gpm; /** @var string */ protected $destination; /** @var string */ protected $file; /** @var string */ protected $tmp; /** @var bool */ protected $use_symlinks; /** @var array */ protected $demo_processing = []; /** @var string */ protected $all_yes; /** * @return void */ protected function configure(): void { $this ->setName('install') ->addOption( 'force', 'f', InputOption::VALUE_NONE, 'Force re-fetching the data from remote' ) ->addOption( 'all-yes', 'y', InputOption::VALUE_NONE, 'Assumes yes (or best approach) instead of prompting' ) ->addOption( 'destination', 'd', InputOption::VALUE_OPTIONAL, 'The destination where the package should be installed at. By default this would be where the grav instance has been launched from', GRAV_ROOT ) ->addArgument( 'package', InputArgument::IS_ARRAY | InputArgument::REQUIRED, 'Package(s) to install. Use "bin/gpm index" to list packages. Use "bin/gpm direct-install" to install a specific version' ) ->setDescription('Performs the installation of plugins and themes') ->setHelp('The <info>install</info> command allows to install plugins and themes'); } /** * Allows to set the GPM object, used for testing the class * * @param GPM $gpm */ public function setGpm(GPM $gpm): void { $this->gpm = $gpm; } /** * @return int */ protected function serve(): int { $input = $this->getInput(); $io = $this->getIO(); if (!class_exists(ZipArchive::class)) { $io->title('GPM Install'); $io->error('php-zip extension needs to be enabled!'); return 1; } $this->gpm = new GPM($input->getOption('force')); $this->all_yes = $input->getOption('all-yes'); $this->displayGPMRelease(); $this->destination = realpath($input->getOption('destination')); $packages = array_map('strtolower', $input->getArgument('package')); $this->data = $this->gpm->findPackages($packages); $this->loadLocalConfig(); if (!Installer::isGravInstance($this->destination) || !Installer::isValidDestination($this->destination, [Installer::EXISTS, Installer::IS_LINK]) ) { $io->writeln('<red>ERROR</red>: ' . Installer::lastErrorMsg()); return 1; } $io->newLine(); if (!$this->data['total']) { $io->writeln('Nothing to install.'); $io->newLine(); return 0; } if (count($this->data['not_found'])) { $io->writeln('These packages were not found on Grav: <red>' . implode( '</red>, <red>', array_keys($this->data['not_found']) ) . '</red>'); } unset($this->data['not_found'], $this->data['total']); if (null !== $this->local_config) { // Symlinks available, ask if Grav should use them $this->use_symlinks = false; $question = new ConfirmationQuestion('Should Grav use the symlinks if available? [y|N] ', false); $answer = $this->all_yes ? false : $io->askQuestion($question); if ($answer) { $this->use_symlinks = true; } } $io->newLine(); try { $dependencies = $this->gpm->getDependencies($packages); } catch (Exception $e) { //Error out if there are incompatible packages requirements and tell which ones, and what to do //Error out if there is any error in parsing the dependencies and their versions, and tell which one is broken $io->writeln("<red>{$e->getMessage()}</red>"); return 1; } if ($dependencies) { try { $this->installDependencies($dependencies, 'install', 'The following dependencies need to be installed...'); $this->installDependencies($dependencies, 'update', 'The following dependencies need to be updated...'); $this->installDependencies($dependencies, 'ignore', "The following dependencies can be updated as there is a newer version, but it's not mandatory...", false); } catch (Exception $e) { $io->writeln('<red>Installation aborted</red>'); return 1; } $io->writeln('<green>Dependencies are OK</green>'); $io->newLine(); } //We're done installing dependencies. Install the actual packages foreach ($this->data as $data) { foreach ($data as $package_name => $package) { if (array_key_exists($package_name, $dependencies)) { $io->writeln("<green>Package {$package_name} already installed as dependency</green>"); } else { $is_valid_destination = Installer::isValidDestination($this->destination . DS . $package->install_path); if ($is_valid_destination || Installer::lastErrorCode() == Installer::NOT_FOUND) { $this->processPackage($package, false); } else { if (Installer::lastErrorCode() == Installer::EXISTS) { try { $this->askConfirmationIfMajorVersionUpdated($package); $this->gpm->checkNoOtherPackageNeedsThisDependencyInALowerVersion($package->slug, $package->available, array_keys($data)); } catch (Exception $e) { $io->writeln("<red>{$e->getMessage()}</red>"); return 1; } $question = new ConfirmationQuestion("The package <cyan>{$package_name}</cyan> is already installed, overwrite? [y|N] ", false); $answer = $this->all_yes ? true : $io->askQuestion($question); if ($answer) { $is_update = true; $this->processPackage($package, $is_update); } else { $io->writeln("<yellow>Package {$package_name} not overwritten</yellow>"); } } else { if (Installer::lastErrorCode() == Installer::IS_LINK) { $io->writeln("<red>Cannot overwrite existing symlink for </red><cyan>{$package_name}</cyan>"); $io->newLine(); } } } } } } if (count($this->demo_processing) > 0) { foreach ($this->demo_processing as $package) { $this->installDemoContent($package); } } // clear cache after successful upgrade $this->clearCache(); return 0; } /** * If the package is updated from an older major release, show warning and ask confirmation * * @param Package $package * @return void */ public function askConfirmationIfMajorVersionUpdated(Package $package): void { $io = $this->getIO(); $package_name = $package->name; $new_version = $package->available ?: $this->gpm->getLatestVersionOfPackage($package->slug); $old_version = $package->version; $major_version_changed = explode('.', $new_version)[0] !== explode('.', $old_version)[0]; if ($major_version_changed) { if ($this->all_yes) { $io->writeln("The package <cyan>{$package_name}</cyan> will be updated to a new major version <green>{$new_version}</green>, from <magenta>{$old_version}</magenta>"); return; } $question = new ConfirmationQuestion("The package <cyan>{$package_name}</cyan> will be updated to a new major version <green>{$new_version}</green>, from <magenta>{$old_version}</magenta>. Be sure to read what changed with the new major release. Continue? [y|N] ", false); if (!$io->askQuestion($question)) { $io->writeln("<yellow>Package {$package_name} not updated</yellow>"); exit; } } } /** * Given a $dependencies list, filters their type according to $type and * shows $message prior to listing them to the user. Then asks the user a confirmation prior * to installing them. * * @param array $dependencies The dependencies array * @param string $type The type of dependency to show: install, update, ignore * @param string $message A message to be shown prior to listing the dependencies * @param bool $required A flag that determines if the installation is required or optional * @return void * @throws Exception */ public function installDependencies(array $dependencies, string $type, string $message, bool $required = true): void { $io = $this->getIO(); $packages = array_filter($dependencies, static function ($action) use ($type) { return $action === $type; }); if (count($packages) > 0) { $io->writeln($message); foreach ($packages as $dependencyName => $dependencyVersion) { $io->writeln(" |- Package <cyan>{$dependencyName}</cyan>"); } $io->newLine(); if ($type === 'install') { $questionAction = 'Install'; } else { $questionAction = 'Update'; } if (count($packages) === 1) { $questionArticle = 'this'; } else { $questionArticle = 'these'; } if (count($packages) === 1) { $questionNoun = 'package'; } else { $questionNoun = 'packages'; } $question = new ConfirmationQuestion("{$questionAction} {$questionArticle} {$questionNoun}? [Y|n] ", true); $answer = $this->all_yes ? true : $io->askQuestion($question); if ($answer) { foreach ($packages as $dependencyName => $dependencyVersion) { $package = $this->gpm->findPackage($dependencyName); $this->processPackage($package, $type === 'update'); } $io->newLine(); } elseif ($required) { throw new Exception(); } } } /** * @param Package|null $package * @param bool $is_update True if the package is an update * @return void */ private function processPackage(?Package $package, bool $is_update = false): void { $io = $this->getIO(); if (!$package) { $io->writeln('<red>Package not found on the GPM!</red>'); $io->newLine(); return; } $symlink = false; if ($this->use_symlinks) { if (!isset($package->version) || $this->getSymlinkSource($package)) { $symlink = true; } } $symlink ? $this->processSymlink($package) : $this->processGpm($package, $is_update); $this->processDemo($package); } /** * Add package to the queue to process the demo content, if demo content exists * * @param Package $package * @return void */ private function processDemo(Package $package): void { $demo_dir = $this->destination . DS . $package->install_path . DS . '_demo'; if (file_exists($demo_dir)) { $this->demo_processing[] = $package; } } /** * Prompt to install the demo content of a package * * @param Package $package * @return void */ private function installDemoContent(Package $package): void { $io = $this->getIO(); $demo_dir = $this->destination . DS . $package->install_path . DS . '_demo'; if (file_exists($demo_dir)) { $dest_dir = $this->destination . DS . 'user'; $pages_dir = $dest_dir . DS . 'pages'; // Demo content exists, prompt to install it. $io->writeln("<white>Attention: </white><cyan>{$package->name}</cyan> contains demo content"); $question = new ConfirmationQuestion('Do you wish to install this demo content? [y|N] ', false); $answer = $io->askQuestion($question); if (!$answer) { $io->writeln(" '- <red>Skipped!</red> "); $io->newLine(); return; } // if pages folder exists in demo if (file_exists($demo_dir . DS . 'pages')) { $pages_backup = 'pages.' . date('m-d-Y-H-i-s'); $question = new ConfirmationQuestion('This will backup your current `user/pages` folder to `user/' . $pages_backup . '`, continue? [y|N]', false); $answer = $this->all_yes ? true : $io->askQuestion($question); if (!$answer) { $io->writeln(" '- <red>Skipped!</red> "); $io->newLine(); return; } // backup current pages folder if (file_exists($dest_dir)) { if (rename($pages_dir, $dest_dir . DS . $pages_backup)) { $io->writeln(' |- Backing up pages... <green>ok</green>'); } else { $io->writeln(' |- Backing up pages... <red>failed</red>'); } } } // Confirmation received, copy over the data $io->writeln(' |- Installing demo content... <green>ok</green> '); Folder::rcopy($demo_dir, $dest_dir); $io->writeln(" '- <green>Success!</green> "); $io->newLine(); } } /** * @param Package $package * @return array|false */ private function getGitRegexMatches(Package $package) { if (isset($package->repository)) { $repository = $package->repository; } else { return false; } preg_match(GIT_REGEX, $repository, $matches); return $matches; } /** * @param Package $package * @return string|false */ private function getSymlinkSource(Package $package) { $matches = $this->getGitRegexMatches($package); foreach ($this->local_config as $paths) { if (Utils::endsWith($matches[2], '.git')) { $repo_dir = preg_replace('/\.git$/', '', $matches[2]); } else { $repo_dir = $matches[2]; } $paths = (array) $paths; foreach ($paths as $repo) { $path = rtrim($repo, '/') . '/' . $repo_dir; if (file_exists($path)) { return $path; } } } return false; } /** * @param Package $package * @return void */ private function processSymlink(Package $package): void { $io = $this->getIO(); exec('cd ' . escapeshellarg($this->destination)); $to = $this->destination . DS . $package->install_path; $from = $this->getSymlinkSource($package); $io->writeln("Preparing to Symlink <cyan>{$package->name}</cyan>"); $io->write(' |- Checking source... '); if (file_exists($from)) { $io->writeln('<green>ok</green>'); $io->write(' |- Checking destination... '); $checks = $this->checkDestination($package); if (!$checks) { $io->writeln(" '- <red>Installation failed or aborted.</red>"); $io->newLine(); } elseif (file_exists($to)) { $io->writeln(" '- <red>Symlink cannot overwrite an existing package, please remove first</red>"); $io->newLine(); } else { symlink($from, $to); // extra white spaces to clear out the buffer properly $io->writeln(' |- Symlinking package... <green>ok</green> '); $io->writeln(" '- <green>Success!</green> "); $io->newLine(); } return; } $io->writeln('<red>not found!</red>'); $io->writeln(" '- <red>Installation failed or aborted.</red>"); } /** * @param Package $package * @param bool $is_update * @return bool */ private function processGpm(Package $package, bool $is_update = false) { $io = $this->getIO(); $version = $package->available ?? $package->version; $license = Licenses::get($package->slug); $io->writeln("Preparing to install <cyan>{$package->name}</cyan> [v{$version}]"); $io->write(' |- Downloading package... 0%'); $this->file = $this->downloadPackage($package, $license); if (!$this->file) { $io->writeln(" '- <red>Installation failed or aborted.</red>"); $io->newLine(); return false; } $io->write(' |- Checking destination... '); $checks = $this->checkDestination($package); if (!$checks) { $io->writeln(" '- <red>Installation failed or aborted.</red>"); $io->newLine(); } else { $io->write(' |- Installing package... '); $installation = $this->installPackage($package, $is_update); if (!$installation) { $io->writeln(" '- <red>Installation failed or aborted.</red>"); $io->newLine(); } else { $io->writeln(" '- <green>Success!</green> "); $io->newLine(); return true; } } return false; } /** * @param Package $package * @param string|null $license * @return string|null */ private function downloadPackage(Package $package, string $license = null) { $io = $this->getIO(); $tmp_dir = Grav::instance()['locator']->findResource('tmp://', true, true); $this->tmp = $tmp_dir . '/Grav-' . uniqid(); $filename = $package->slug . Utils::basename($package->zipball_url); $filename = preg_replace('/[\\\\\/:"*?&<>|]+/m', '-', $filename); $query = ''; if (!empty($package->premium)) { $query = json_encode(array_merge( $package->premium, [ 'slug' => $package->slug, 'filename' => $package->premium['filename'], 'license_key' => $license, 'sid' => md5(GRAV_ROOT) ] )); $query = '?d=' . base64_encode($query); } try { $output = Response::get($package->zipball_url . $query, [], [$this, 'progress']); } catch (Exception $e) { if (!empty($package->premium) && $e->getCode() === 401) { $message = '<yellow>Unauthorized Premium License Key</yellow>'; } else { $message = $e->getMessage(); } $error = str_replace("\n", "\n | '- ", $message); $io->write("\x0D"); // extra white spaces to clear out the buffer properly $io->writeln(' |- Downloading package... <red>error</red> '); $io->writeln(" | '- " . $error); return null; } Folder::create($this->tmp); $io->write("\x0D"); $io->write(' |- Downloading package... 100%'); $io->newLine(); file_put_contents($this->tmp . DS . $filename, $output); return $this->tmp . DS . $filename; } /** * @param Package $package * @return bool */ private function checkDestination(Package $package): bool { $io = $this->getIO(); Installer::isValidDestination($this->destination . DS . $package->install_path); if (Installer::lastErrorCode() === Installer::IS_LINK) { $io->write("\x0D"); $io->writeln(' |- Checking destination... <yellow>symbolic link</yellow>'); if ($this->all_yes) { $io->writeln(" | '- <yellow>Skipped automatically.</yellow>"); return false; } $question = new ConfirmationQuestion( " | '- Destination has been detected as symlink, delete symbolic link first? [y|N] ", false ); $answer = $io->askQuestion($question); if (!$answer) { $io->writeln(" | '- <red>You decided to not delete the symlink automatically.</red>"); return false; } unlink($this->destination . DS . $package->install_path); } $io->write("\x0D"); $io->writeln(' |- Checking destination... <green>ok</green>'); return true; } /** * Install a package * * @param Package $package * @param bool $is_update True if it's an update. False if it's an install * @return bool */ private function installPackage(Package $package, bool $is_update = false): bool { $io = $this->getIO(); $type = $package->package_type; Installer::install($this->file, $this->destination, ['install_path' => $package->install_path, 'theme' => $type === 'themes', 'is_update' => $is_update]); $error_code = Installer::lastErrorCode(); Folder::delete($this->tmp); if ($error_code) { $io->write("\x0D"); // extra white spaces to clear out the buffer properly $io->writeln(' |- Installing package... <red>error</red> '); $io->writeln(" | '- " . Installer::lastErrorMsg()); return false; } $message = Installer::getMessage(); if ($message) { $io->write("\x0D"); // extra white spaces to clear out the buffer properly $io->writeln(" |- {$message}"); } $io->write("\x0D"); // extra white spaces to clear out the buffer properly $io->writeln(' |- Installing package... <green>ok</green> '); return true; } /** * @param array $progress * @return void */ public function progress(array $progress): void { $io = $this->getIO(); $io->write("\x0D"); $io->write(' |- Downloading package... ' . str_pad( $progress['percent'], 5, ' ', STR_PAD_LEFT ) . '%'); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Gpm/IndexCommand.php
system/src/Grav/Console/Gpm/IndexCommand.php
<?php /** * @package Grav\Console\Gpm * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Gpm; use Grav\Common\GPM\Remote\AbstractPackageCollection; use Grav\Common\GPM\Remote\Package; use Grav\Common\GPM\GPM; use Grav\Common\GPM\Remote\Packages; use Grav\Common\GPM\Remote\Plugins; use Grav\Common\GPM\Remote\Themes; use Grav\Common\Utils; use Grav\Console\GpmCommand; use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Input\InputOption; use function count; /** * Class IndexCommand * @package Grav\Console\Gpm */ class IndexCommand extends GpmCommand { /** @var Packages */ protected $data; /** @var GPM */ protected $gpm; /** @var array */ protected $options; /** * @return void */ protected function configure(): void { $this ->setName('index') ->addOption( 'force', 'f', InputOption::VALUE_NONE, 'Force re-fetching the data from remote' ) ->addOption( 'filter', 'F', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Allows to limit the results based on one or multiple filters input. This can be either portion of a name/slug or a regex' ) ->addOption( 'themes-only', 'T', InputOption::VALUE_NONE, 'Filters the results to only Themes' ) ->addOption( 'plugins-only', 'P', InputOption::VALUE_NONE, 'Filters the results to only Plugins' ) ->addOption( 'updates-only', 'U', InputOption::VALUE_NONE, 'Filters the results to Updatable Themes and Plugins only' ) ->addOption( 'installed-only', 'I', InputOption::VALUE_NONE, 'Filters the results to only the Themes and Plugins you have installed' ) ->addOption( 'sort', 's', InputOption::VALUE_REQUIRED, 'Allows to sort (ASC) the results. SORT can be either "name", "slug", "author", "date"', 'date' ) ->addOption( 'desc', 'D', InputOption::VALUE_NONE, 'Reverses the order of the output.' ) ->addOption( 'enabled', 'e', InputOption::VALUE_NONE, 'Filters the results to only enabled Themes and Plugins.' ) ->addOption( 'disabled', 'd', InputOption::VALUE_NONE, 'Filters the results to only disabled Themes and Plugins.' ) ->setDescription('Lists the plugins and themes available for installation') ->setHelp('The <info>index</info> command lists the plugins and themes available for installation') ; } /** * @return int */ protected function serve(): int { $input = $this->getInput(); $this->options = $input->getOptions(); $this->gpm = new GPM($this->options['force']); $this->displayGPMRelease(); $this->data = $this->gpm->getRepository(); $data = $this->filter($this->data); $io = $this->getIO(); if (count($data) === 0) { $io->writeln('No data was found in the GPM repository stored locally.'); $io->writeln('Please try clearing cache and running the <green>bin/gpm index -f</green> command again'); $io->writeln('If this doesn\'t work try tweaking your GPM system settings.'); $io->newLine(); $io->writeln('For more help go to:'); $io->writeln(' -> <yellow>https://learn.getgrav.org/troubleshooting/common-problems#cannot-connect-to-the-gpm</yellow>'); return 1; } foreach ($data as $type => $packages) { $io->writeln('<green>' . strtoupper($type) . '</green> [ ' . count($packages) . ' ]'); $packages = $this->sort($packages); if (!empty($packages)) { $io->section('Packages table'); $table = new Table($io); $table->setHeaders(['Count', 'Name', 'Slug', 'Version', 'Installed', 'Enabled']); $index = 0; foreach ($packages as $slug => $package) { $row = [ 'Count' => $index++ + 1, 'Name' => '<cyan>' . Utils::truncate($package->name, 20, false, ' ', '...') . '</cyan> ', 'Slug' => $slug, 'Version'=> $this->version($package), 'Installed' => $this->installed($package), 'Enabled' => $this->enabled($package), ]; $table->addRow($row); } $table->render(); } $io->newLine(); } $io->writeln('You can either get more informations about a package by typing:'); $io->writeln(" <green>{$this->argv} info <cyan><package></cyan></green>"); $io->newLine(); $io->writeln('Or you can install a package by typing:'); $io->writeln(" <green>{$this->argv} install <cyan><package></cyan></green>"); $io->newLine(); return 0; } /** * @param Package $package * @return string */ private function version(Package $package): string { $list = $this->gpm->{'getUpdatable' . ucfirst($package->package_type)}(); $package = $list[$package->slug] ?? $package; $type = ucfirst(preg_replace('/s$/', '', $package->package_type)); $updatable = $this->gpm->{'is' . $type . 'Updatable'}($package->slug); $installed = $this->gpm->{'is' . $type . 'Installed'}($package->slug); $local = $this->gpm->{'getInstalled' . $type}($package->slug); if (!$installed || !$updatable) { $version = $installed ? $local->version : $package->version; return "v<green>{$version}</green>"; } return "v<red>{$package->version}</red> <cyan>-></cyan> v<green>{$package->available}</green>"; } /** * @param Package $package * @return string */ private function installed(Package $package): string { $type = ucfirst(preg_replace('/s$/', '', $package->package_type)); $method = 'is' . $type . 'Installed'; $installed = $this->gpm->{$method}($package->slug); return !$installed ? '<magenta>not installed</magenta>' : '<cyan>installed</cyan>'; } /** * @param Package $package * @return string */ private function enabled(Package $package): string { $type = ucfirst(preg_replace('/s$/', '', $package->package_type)); $method = 'is' . $type . 'Installed'; $installed = $this->gpm->{$method}($package->slug); $result = ''; if ($installed) { $method = 'is' . $type . 'Enabled'; $enabled = $this->gpm->{$method}($package->slug); if ($enabled === true) { $result = '<cyan>enabled</cyan>'; } elseif ($enabled === false) { $result = '<red>disabled</red>'; } } return $result; } /** * @param Packages $data * @return Packages */ public function filter(Packages $data): Packages { // filtering and sorting if ($this->options['plugins-only']) { unset($data['themes']); } if ($this->options['themes-only']) { unset($data['plugins']); } $filter = [ $this->options['desc'], $this->options['disabled'], $this->options['enabled'], $this->options['filter'], $this->options['installed-only'], $this->options['updates-only'], ]; if (count(array_filter($filter))) { foreach ($data as $type => $packages) { foreach ($packages as $slug => $package) { $filter = true; // Filtering by string if ($this->options['filter']) { $filter = preg_grep('/(' . implode('|', $this->options['filter']) . ')/i', [$slug, $package->name]); } // Filtering updatables only if ($filter && ($this->options['installed-only'] || $this->options['enabled'] || $this->options['disabled'])) { $method = ucfirst(preg_replace('/s$/', '', $package->package_type)); $function = 'is' . $method . 'Installed'; $filter = $this->gpm->{$function}($package->slug); } // Filtering updatables only if ($filter && $this->options['updates-only']) { $method = ucfirst(preg_replace('/s$/', '', $package->package_type)); $function = 'is' . $method . 'Updatable'; $filter = $this->gpm->{$function}($package->slug); } // Filtering enabled only if ($filter && $this->options['enabled']) { $method = ucfirst(preg_replace('/s$/', '', $package->package_type)); // Check if packaged is enabled. $function = 'is' . $method . 'Enabled'; $filter = $this->gpm->{$function}($package->slug); } // Filtering disabled only if ($filter && $this->options['disabled']) { $method = ucfirst(preg_replace('/s$/', '', $package->package_type)); // Check if package is disabled. $function = 'is' . $method . 'Enabled'; $enabled_filter = $this->gpm->{$function}($package->slug); // Apply filtering results. if (!( $enabled_filter === false)) { $filter = false; } } if (!$filter) { unset($data[$type][$slug]); } } } } return $data; } /** * @param AbstractPackageCollection|Plugins|Themes $packages * @return array */ public function sort(AbstractPackageCollection $packages): array { $key = $this->options['sort']; // Sorting only works once. return $packages->sort( function ($a, $b) use ($key) { switch ($key) { case 'author': return strcmp($a->{$key}['name'], $b->{$key}['name']); default: return strcmp($a->$key, $b->$key); } }, $this->options['desc'] ? true : false ); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Gpm/DirectInstallCommand.php
system/src/Grav/Console/Gpm/DirectInstallCommand.php
<?php /** * @package Grav\Console\Gpm * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Gpm; use Exception; use Grav\Common\Grav; use Grav\Common\Filesystem\Folder; use Grav\Common\HTTP\Response; use Grav\Common\GPM\GPM; use Grav\Common\GPM\Installer; use Grav\Console\GpmCommand; use RuntimeException; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Question\ConfirmationQuestion; use ZipArchive; use function is_array; use function is_callable; /** * Class DirectInstallCommand * @package Grav\Console\Gpm */ class DirectInstallCommand extends GpmCommand { /** @var string */ protected $all_yes; /** @var string */ protected $destination; /** * @return void */ protected function configure(): void { $this ->setName('direct-install') ->setAliases(['directinstall']) ->addArgument( 'package-file', InputArgument::REQUIRED, 'Installable package local <path> or remote <URL>. Can install specific version' ) ->addOption( 'all-yes', 'y', InputOption::VALUE_NONE, 'Assumes yes (or best approach) instead of prompting' ) ->addOption( 'destination', 'd', InputOption::VALUE_OPTIONAL, 'The destination where the package should be installed at. By default this would be where the grav instance has been launched from', GRAV_ROOT ) ->setDescription('Installs Grav, plugin, or theme directly from a file or a URL') ->setHelp('The <info>direct-install</info> command installs Grav, plugin, or theme directly from a file or a URL'); } /** * @return int */ protected function serve(): int { $input = $this->getInput(); $io = $this->getIO(); if (!class_exists(ZipArchive::class)) { $io->title('Direct Install'); $io->error('php-zip extension needs to be enabled!'); return 1; } // Making sure the destination is usable $this->destination = realpath($input->getOption('destination')); if (!Installer::isGravInstance($this->destination) || !Installer::isValidDestination($this->destination, [Installer::EXISTS, Installer::IS_LINK]) ) { $io->writeln('<red>ERROR</red>: ' . Installer::lastErrorMsg()); return 1; } $this->all_yes = $input->getOption('all-yes'); $package_file = $input->getArgument('package-file'); $question = new ConfirmationQuestion("Are you sure you want to direct-install <cyan>{$package_file}</cyan> [y|N] ", false); $answer = $this->all_yes ? true : $io->askQuestion($question); if (!$answer) { $io->writeln('exiting...'); $io->newLine(); return 1; } $tmp_dir = Grav::instance()['locator']->findResource('tmp://', true, true); $tmp_zip = $tmp_dir . uniqid('/Grav-', false); $io->newLine(); $io->writeln("Preparing to install <cyan>{$package_file}</cyan>"); $zip = null; if (Response::isRemote($package_file)) { $io->write(' |- Downloading package... 0%'); try { $zip = GPM::downloadPackage($package_file, $tmp_zip); } catch (RuntimeException $e) { $io->newLine(); $io->writeln(" `- <red>ERROR: {$e->getMessage()}</red>"); $io->newLine(); return 1; } if ($zip) { $io->write("\x0D"); $io->write(' |- Downloading package... 100%'); $io->newLine(); } } elseif (is_file($package_file)) { $io->write(' |- Copying package... 0%'); $zip = GPM::copyPackage($package_file, $tmp_zip); if ($zip) { $io->write("\x0D"); $io->write(' |- Copying package... 100%'); $io->newLine(); } } if ($zip && file_exists($zip)) { $tmp_source = $tmp_dir . uniqid('/Grav-', false); $io->write(' |- Extracting package... '); $extracted = Installer::unZip($zip, $tmp_source); if (!$extracted) { $io->write("\x0D"); $io->writeln(' |- Extracting package... <red>failed</red>'); Folder::delete($tmp_source); Folder::delete($tmp_zip); return 1; } $io->write("\x0D"); $io->writeln(' |- Extracting package... <green>ok</green>'); $type = GPM::getPackageType($extracted); if (!$type) { $io->writeln(" '- <red>ERROR: Not a valid Grav package</red>"); $io->newLine(); Folder::delete($tmp_source); Folder::delete($tmp_zip); return 1; } $blueprint = GPM::getBlueprints($extracted); if ($blueprint) { if (isset($blueprint['dependencies'])) { $dependencies = []; foreach ($blueprint['dependencies'] as $dependency) { if (is_array($dependency)) { if (isset($dependency['name'])) { $dependencies[] = $dependency['name']; } if (isset($dependency['github'])) { $dependencies[] = $dependency['github']; } } else { $dependencies[] = $dependency; } } $io->writeln(' |- Dependencies found... <cyan>[' . implode(',', $dependencies) . ']</cyan>'); $question = new ConfirmationQuestion(" | '- Dependencies will not be satisfied. Continue ? [y|N] ", false); $answer = $this->all_yes ? true : $io->askQuestion($question); if (!$answer) { $io->writeln('exiting...'); $io->newLine(); Folder::delete($tmp_source); Folder::delete($tmp_zip); return 1; } } } if ($type === 'grav') { $io->write(' |- Checking destination... '); Installer::isValidDestination(GRAV_ROOT . '/system'); if (Installer::IS_LINK === Installer::lastErrorCode()) { $io->write("\x0D"); $io->writeln(' |- Checking destination... <yellow>symbolic link</yellow>'); $io->writeln(" '- <red>ERROR: symlinks found...</red> <yellow>" . GRAV_ROOT . '</yellow>'); $io->newLine(); Folder::delete($tmp_source); Folder::delete($tmp_zip); return 1; } $io->write("\x0D"); $io->writeln(' |- Checking destination... <green>ok</green>'); $io->write(' |- Installing package... '); $this->upgradeGrav($zip, $extracted); } else { $name = GPM::getPackageName($extracted); if (!$name) { $io->writeln('<red>ERROR: Name could not be determined.</red> Please specify with --name|-n'); $io->newLine(); Folder::delete($tmp_source); Folder::delete($tmp_zip); return 1; } $install_path = GPM::getInstallPath($type, $name); $is_update = file_exists($install_path); $io->write(' |- Checking destination... '); Installer::isValidDestination(GRAV_ROOT . DS . $install_path); if (Installer::lastErrorCode() === Installer::IS_LINK) { $io->write("\x0D"); $io->writeln(' |- Checking destination... <yellow>symbolic link</yellow>'); $io->writeln(" '- <red>ERROR: symlink found...</red> <yellow>" . GRAV_ROOT . DS . $install_path . '</yellow>'); $io->newLine(); Folder::delete($tmp_source); Folder::delete($tmp_zip); return 1; } $io->write("\x0D"); $io->writeln(' |- Checking destination... <green>ok</green>'); $io->write(' |- Installing package... '); Installer::install( $zip, $this->destination, $options = [ 'install_path' => $install_path, 'theme' => (($type === 'theme')), 'is_update' => $is_update ], $extracted ); // clear cache after successful upgrade $this->clearCache(); } Folder::delete($tmp_source); $io->write("\x0D"); if (Installer::lastErrorCode()) { $io->writeln(" '- <red>" . Installer::lastErrorMsg() . '</red>'); $io->newLine(); } else { $io->writeln(' |- Installing package... <green>ok</green>'); $io->writeln(" '- <green>Success!</green> "); $io->newLine(); } } else { $io->writeln(" '- <red>ERROR: ZIP package could not be found</red>"); Folder::delete($tmp_zip); return 1; } Folder::delete($tmp_zip); return 0; } /** * @param string $zip * @param string $folder * @return void */ private function upgradeGrav(string $zip, string $folder): void { if (!is_dir($folder)) { Installer::setError('Invalid source folder'); } try { $script = $folder . '/system/install.php'; /** Install $installer */ if ((file_exists($script) && $install = include $script) && is_callable($install)) { $install($zip); } else { throw new RuntimeException('Uploaded archive file is not a valid Grav update package'); } } catch (Exception $e) { Installer::setError($e->getMessage()); } } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Gpm/UninstallCommand.php
system/src/Grav/Console/Gpm/UninstallCommand.php
<?php /** * @package Grav\Console\Gpm * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Gpm; use Grav\Common\GPM\GPM; use Grav\Common\GPM\Installer; use Grav\Common\GPM\Local; use Grav\Common\GPM\Remote; use Grav\Common\Grav; use Grav\Console\GpmCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Question\ConfirmationQuestion; use Throwable; use function count; use function in_array; use function is_array; /** * Class UninstallCommand * @package Grav\Console\Gpm */ class UninstallCommand extends GpmCommand { /** @var array */ protected $data; /** @var GPM */ protected $gpm; /** @var string */ protected $destination; /** @var string */ protected $file; /** @var string */ protected $tmp; /** @var array */ protected $dependencies = []; /** @var string */ protected $all_yes; /** * @return void */ protected function configure(): void { $this ->setName('uninstall') ->addOption( 'all-yes', 'y', InputOption::VALUE_NONE, 'Assumes yes (or best approach) instead of prompting' ) ->addArgument( 'package', InputArgument::IS_ARRAY | InputArgument::REQUIRED, 'The package(s) that are desired to be removed. Use the "index" command for a list of packages' ) ->setDescription('Performs the uninstallation of plugins and themes') ->setHelp('The <info>uninstall</info> command allows to uninstall plugins and themes'); } /** * @return int */ protected function serve(): int { $input = $this->getInput(); $io = $this->getIO(); $this->gpm = new GPM(); $this->all_yes = $input->getOption('all-yes'); $packages = array_map('strtolower', $input->getArgument('package')); $this->data = ['total' => 0, 'not_found' => []]; $total = 0; foreach ($packages as $package) { $plugin = $this->gpm->getInstalledPlugin($package); $theme = $this->gpm->getInstalledTheme($package); if ($plugin || $theme) { $this->data[strtolower($package)] = $plugin ?: $theme; $total++; } else { $this->data['not_found'][] = $package; } } $this->data['total'] = $total; $io->newLine(); if (!$this->data['total']) { $io->writeln('Nothing to uninstall.'); $io->newLine(); return 0; } if (count($this->data['not_found'])) { $io->writeln('These packages were not found installed: <red>' . implode( '</red>, <red>', $this->data['not_found'] ) . '</red>'); } unset($this->data['not_found'], $this->data['total']); // Plugins need to be initialized in order to make clearcache to work. try { $this->initializePlugins(); } catch (Throwable $e) { $io->writeln("<red>Some plugins failed to initialize: {$e->getMessage()}</red>"); } $error = 0; foreach ($this->data as $slug => $package) { $io->writeln("Preparing to uninstall <cyan>{$package->name}</cyan> [v{$package->version}]"); $io->write(' |- Checking destination... '); $checks = $this->checkDestination($slug, $package); if (!$checks) { $io->writeln(" '- <red>Installation failed or aborted.</red>"); $io->newLine(); $error = 1; } else { $uninstall = $this->uninstallPackage($slug, $package); if (!$uninstall) { $io->writeln(" '- <red>Uninstallation failed or aborted.</red>"); $error = 1; } else { $io->writeln(" '- <green>Success!</green> "); } } } // clear cache after successful upgrade $this->clearCache(); return $error; } /** * @param string $slug * @param Local\Package|Remote\Package $package * @param bool $is_dependency * @return bool */ private function uninstallPackage($slug, $package, $is_dependency = false): bool { $io = $this->getIO(); if (!$slug) { return false; } //check if there are packages that have this as a dependency. Abort and show list $dependent_packages = $this->gpm->getPackagesThatDependOnPackage($slug); if (count($dependent_packages) > ($is_dependency ? 1 : 0)) { $io->newLine(2); $io->writeln('<red>Uninstallation failed.</red>'); $io->newLine(); if (count($dependent_packages) > ($is_dependency ? 2 : 1)) { $io->writeln('The installed packages <cyan>' . implode('</cyan>, <cyan>', $dependent_packages) . '</cyan> depends on this package. Please remove those first.'); } else { $io->writeln('The installed package <cyan>' . implode('</cyan>, <cyan>', $dependent_packages) . '</cyan> depends on this package. Please remove it first.'); } $io->newLine(); return false; } if (isset($package->dependencies)) { $dependencies = $package->dependencies; if ($is_dependency) { foreach ($dependencies as $key => $dependency) { if (in_array($dependency['name'], $this->dependencies, true)) { unset($dependencies[$key]); } } } elseif (count($dependencies) > 0) { $io->writeln(' `- Dependencies found...'); $io->newLine(); } foreach ($dependencies as $dependency) { $this->dependencies[] = $dependency['name']; if (is_array($dependency)) { $dependency = $dependency['name']; } if ($dependency === 'grav' || $dependency === 'php') { continue; } $dependencyPackage = $this->gpm->findPackage($dependency); $dependency_exists = $this->packageExists($dependency, $dependencyPackage); if ($dependency_exists == Installer::EXISTS) { $io->writeln("A dependency on <cyan>{$dependencyPackage->name}</cyan> [v{$dependencyPackage->version}] was found"); $question = new ConfirmationQuestion(" |- Uninstall <cyan>{$dependencyPackage->name}</cyan>? [y|N] ", false); $answer = $this->all_yes ? true : $io->askQuestion($question); if ($answer) { $uninstall = $this->uninstallPackage($dependency, $dependencyPackage, true); if (!$uninstall) { $io->writeln(" '- <red>Uninstallation failed or aborted.</red>"); } else { $io->writeln(" '- <green>Success!</green> "); } $io->newLine(); } else { $io->writeln(" '- <yellow>You decided not to uninstall {$dependencyPackage->name}.</yellow>"); $io->newLine(); } } } } $locator = Grav::instance()['locator']; $path = $locator->findResource($package->package_type . '://' . $slug); Installer::uninstall($path); $errorCode = Installer::lastErrorCode(); if ($errorCode && $errorCode !== Installer::IS_LINK && $errorCode !== Installer::EXISTS) { $io->writeln(" |- Uninstalling {$package->name} package... <red>error</red> "); $io->writeln(" | '- <yellow>" . Installer::lastErrorMsg() . '</yellow>'); return false; } $message = Installer::getMessage(); if ($message) { $io->writeln(" |- {$message}"); } if (!$is_dependency && $this->dependencies) { $io->writeln("Finishing up uninstalling <cyan>{$package->name}</cyan>"); } $io->writeln(" |- Uninstalling {$package->name} package... <green>ok</green> "); return true; } /** * @param string $slug * @param Local\Package|Remote\Package $package * @return bool */ private function checkDestination(string $slug, $package): bool { $io = $this->getIO(); $exists = $this->packageExists($slug, $package); if ($exists === Installer::IS_LINK) { $io->write("\x0D"); $io->writeln(' |- Checking destination... <yellow>symbolic link</yellow>'); if ($this->all_yes) { $io->writeln(" | '- <yellow>Skipped automatically.</yellow>"); return false; } $question = new ConfirmationQuestion( " | '- Destination has been detected as symlink, delete symbolic link first? [y|N] ", false ); $answer = $io->askQuestion($question); if (!$answer) { $io->writeln(" | '- <red>You decided not to delete the symlink automatically.</red>"); return false; } } $io->write("\x0D"); $io->writeln(' |- Checking destination... <green>ok</green>'); return true; } /** * Check if package exists * * @param string $slug * @param Local\Package|Remote\Package $package * @return int */ private function packageExists(string $slug, $package): int { $path = Grav::instance()['locator']->findResource($package->package_type . '://' . $slug); Installer::isValidDestination($path); return Installer::lastErrorCode(); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Gpm/UpdateCommand.php
system/src/Grav/Console/Gpm/UpdateCommand.php
<?php /** * @package Grav\Console\Gpm * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Gpm; use Grav\Common\GPM\GPM; use Grav\Common\GPM\Installer; use Grav\Common\GPM\Upgrader; use Grav\Console\GpmCommand; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Question\ConfirmationQuestion; use ZipArchive; use function array_key_exists; use function count; /** * Class UpdateCommand * @package Grav\Console\Gpm */ class UpdateCommand extends GpmCommand { /** @var array */ protected $data; /** @var string */ protected $destination; /** @var string */ protected $file; /** @var array */ protected $types = ['plugins', 'themes']; /** @var GPM */ protected $gpm; /** @var string */ protected $all_yes; /** @var string */ protected $overwrite; /** @var Upgrader */ protected $upgrader; /** * @return void */ protected function configure(): void { $this ->setName('update') ->addOption( 'force', 'f', InputOption::VALUE_NONE, 'Force re-fetching the data from remote' ) ->addOption( 'destination', 'd', InputOption::VALUE_OPTIONAL, 'The grav instance location where the updates should be applied to. By default this would be where the grav cli has been launched from', GRAV_ROOT ) ->addOption( 'all-yes', 'y', InputOption::VALUE_NONE, 'Assumes yes (or best approach) instead of prompting' ) ->addOption( 'overwrite', 'o', InputOption::VALUE_NONE, 'Option to overwrite packages if they already exist' ) ->addOption( 'plugins', 'p', InputOption::VALUE_NONE, 'Update only plugins' ) ->addOption( 'themes', 't', InputOption::VALUE_NONE, 'Update only themes' ) ->addArgument( 'package', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'The package or packages that is desired to update. By default all available updates will be applied.' ) ->setDescription('Detects and performs an update of plugins and themes when available') ->setHelp('The <info>update</info> command updates plugins and themes when a new version is available'); } /** * @return int */ protected function serve(): int { $input = $this->getInput(); $io = $this->getIO(); if (!class_exists(ZipArchive::class)) { $io->title('GPM Update'); $io->error('php-zip extension needs to be enabled!'); return 1; } $this->upgrader = new Upgrader($input->getOption('force')); $local = $this->upgrader->getLocalVersion(); $remote = $this->upgrader->getRemoteVersion(); if ($local !== $remote) { $io->writeln('<yellow>WARNING</yellow>: A new version of Grav is available. You should update Grav before updating plugins and themes. If you continue without updating Grav, some plugins or themes may stop working.'); $io->newLine(); $question = new ConfirmationQuestion('Continue with the update process? [Y|n] ', true); $answer = $io->askQuestion($question); if (!$answer) { $io->writeln('<red>Update aborted. Exiting...</red>'); return 1; } } $this->gpm = new GPM($input->getOption('force')); $this->all_yes = $input->getOption('all-yes'); $this->overwrite = $input->getOption('overwrite'); $this->displayGPMRelease(); $this->destination = realpath($input->getOption('destination')); if (!Installer::isGravInstance($this->destination)) { $io->writeln('<red>ERROR</red>: ' . Installer::lastErrorMsg()); exit; } if ($input->getOption('plugins') === false && $input->getOption('themes') === false) { $list_type = ['plugins' => true, 'themes' => true]; } else { $list_type['plugins'] = $input->getOption('plugins'); $list_type['themes'] = $input->getOption('themes'); } if ($this->overwrite) { $this->data = $this->gpm->getInstallable($list_type); $description = ' can be overwritten'; } else { $this->data = $this->gpm->getUpdatable($list_type); $description = ' need updating'; } $only_packages = array_map('strtolower', $input->getArgument('package')); if (!$this->overwrite && !$this->data['total']) { $io->writeln('Nothing to update.'); return 0; } $io->write("Found <green>{$this->gpm->countInstalled()}</green> packages installed of which <magenta>{$this->data['total']}</magenta>{$description}"); $limit_to = $this->userInputPackages($only_packages); $io->newLine(); unset($this->data['total'], $limit_to['total']); // updates review $slugs = []; $index = 1; foreach ($this->data as $packages) { foreach ($packages as $slug => $package) { if (!array_key_exists($slug, $limit_to) && count($only_packages)) { continue; } if (!$package->available) { $package->available = $package->version; } $io->writeln( // index str_pad((string)$index++, 2, '0', STR_PAD_LEFT) . '. ' . // name '<cyan>' . str_pad($package->name, 15) . '</cyan> ' . // version "[v<magenta>{$package->version}</magenta> -> v<green>{$package->available}</green>]" ); $slugs[] = $slug; } } if (!$this->all_yes) { // prompt to continue $io->newLine(); $question = new ConfirmationQuestion('Continue with the update process? [Y|n] ', true); $answer = $io->askQuestion($question); if (!$answer) { $io->writeln('<red>Update aborted. Exiting...</red>'); return 1; } } // finally update $install_command = $this->getApplication()->find('install'); $args = new ArrayInput([ 'command' => 'install', 'package' => $slugs, '-f' => $input->getOption('force'), '-d' => $this->destination, '-y' => true ]); $command_exec = $install_command->run($args, $io); if ($command_exec != 0) { $io->writeln('<red>Error:</red> An error occurred while trying to install the packages'); return 1; } return 0; } /** * @param array $only_packages * @return array */ private function userInputPackages(array $only_packages): array { $io = $this->getIO(); $found = ['total' => 0]; $ignore = []; if (!count($only_packages)) { $io->newLine(); } else { foreach ($only_packages as $only_package) { $find = $this->gpm->findPackage($only_package); if (!$find || (!$this->overwrite && !$this->gpm->isUpdatable($find->slug))) { $name = $find->slug ?? $only_package; $ignore[$name] = $name; } else { $found[$find->slug] = $find; $found['total']++; } } if ($found['total']) { $list = $found; unset($list['total']); $list = array_keys($list); if ($found['total'] !== $this->data['total']) { $io->write(", only <magenta>{$found['total']}</magenta> will be updated"); } $io->newLine(); $io->writeln('Limiting updates for only <cyan>' . implode( '</cyan>, <cyan>', $list ) . '</cyan>'); } if (count($ignore)) { $io->newLine(); $io->writeln('Packages not found or not requiring updates: <red>' . implode( '</red>, <red>', $ignore ) . '</red>'); } } return $found; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Gpm/InfoCommand.php
system/src/Grav/Console/Gpm/InfoCommand.php
<?php /** * @package Grav\Console\Gpm * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Gpm; use Grav\Common\GPM\GPM; use Grav\Console\GpmCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Question\ConfirmationQuestion; use function strlen; /** * Class InfoCommand * @package Grav\Console\Gpm */ class InfoCommand extends GpmCommand { /** @var array */ protected $data; /** @var GPM */ protected $gpm; /** @var string */ protected $all_yes; /** * @return void */ protected function configure(): void { $this ->setName('info') ->addOption( 'force', 'f', InputOption::VALUE_NONE, 'Force fetching the new data remotely' ) ->addOption( 'all-yes', 'y', InputOption::VALUE_NONE, 'Assumes yes (or best approach) instead of prompting' ) ->addArgument( 'package', InputArgument::REQUIRED, 'The package of which more informations are desired. Use the "index" command for a list of packages' ) ->setDescription('Shows more informations about a package') ->setHelp('The <info>info</info> shows more information about a package'); } /** * @return int */ protected function serve(): int { $input = $this->getInput(); $io = $this->getIO(); $this->gpm = new GPM($input->getOption('force')); $this->all_yes = $input->getOption('all-yes'); $this->displayGPMRelease(); $foundPackage = $this->gpm->findPackage($input->getArgument('package')); if (!$foundPackage) { $io->writeln("The package <cyan>'{$input->getArgument('package')}'</cyan> was not found in the Grav repository."); $io->newLine(); $io->writeln('You can list all the available packages by typing:'); $io->writeln(" <green>{$this->argv} index</green>"); $io->newLine(); return 1; } $io->writeln("Found package <cyan>'{$input->getArgument('package')}'</cyan> under the '<green>" . ucfirst($foundPackage->package_type) . "</green>' section"); $io->newLine(); $io->writeln("<cyan>{$foundPackage->name}</cyan> [{$foundPackage->slug}]"); $io->writeln(str_repeat('-', strlen($foundPackage->name) + strlen($foundPackage->slug) + 3)); $io->writeln('<white>' . strip_tags($foundPackage->description_plain) . '</white>'); $io->newLine(); $packageURL = ''; if (isset($foundPackage->author['url'])) { $packageURL = '<' . $foundPackage->author['url'] . '>'; } $io->writeln('<green>' . str_pad( 'Author', 12 ) . ':</green> ' . $foundPackage->author['name'] . ' <' . $foundPackage->author['email'] . '> ' . $packageURL); foreach ([ 'version', 'keywords', 'date', 'homepage', 'demo', 'docs', 'guide', 'repository', 'bugs', 'zipball_url', 'license' ] as $info) { if (isset($foundPackage->{$info})) { $name = ucfirst($info); $data = $foundPackage->{$info}; if ($info === 'zipball_url') { $name = 'Download'; } if ($info === 'date') { $name = 'Last Update'; $data = date('D, j M Y, H:i:s, P ', strtotime($data)); } $name = str_pad($name, 12); $io->writeln("<green>{$name}:</green> {$data}"); } } $type = rtrim($foundPackage->package_type, 's'); $updatable = $this->gpm->{'is' . $type . 'Updatable'}($foundPackage->slug); $installed = $this->gpm->{'is' . $type . 'Installed'}($foundPackage->slug); // display current version if installed and different if ($installed && $updatable) { $local = $this->gpm->{'getInstalled'. $type}($foundPackage->slug); $io->newLine(); $io->writeln("Currently installed version: <magenta>{$local->version}</magenta>"); $io->newLine(); } // display changelog information $question = new ConfirmationQuestion( 'Would you like to read the changelog? [y|N] ', false ); $answer = $this->all_yes ? true : $io->askQuestion($question); if ($answer) { $changelog = $foundPackage->changelog; $io->newLine(); foreach ($changelog as $version => $log) { $title = $version . ' [' . $log['date'] . ']'; $content = preg_replace_callback('/\d\.\s\[\]\(#(.*)\)/', static function ($match) { return "\n" . ucfirst($match[1]) . ':'; }, $log['content']); $io->writeln("<cyan>{$title}</cyan>"); $io->writeln(str_repeat('-', strlen($title))); $io->writeln($content); $io->newLine(); $question = new ConfirmationQuestion('Press [ENTER] to continue or [q] to quit ', true); $answer = $this->all_yes ? false : $io->askQuestion($question); if (!$answer) { break; } $io->newLine(); } } $io->newLine(); if ($installed && $updatable) { $io->writeln('You can update this package by typing:'); $io->writeln(" <green>{$this->argv} update</green> <cyan>{$foundPackage->slug}</cyan>"); } else { $io->writeln('You can install this package by typing:'); $io->writeln(" <green>{$this->argv} install</green> <cyan>{$foundPackage->slug}</cyan>"); } $io->newLine(); return 0; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Gpm/SelfupgradeCommand.php
system/src/Grav/Console/Gpm/SelfupgradeCommand.php
<?php /** * @package Grav\Console\Gpm * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Gpm; use Exception; use Grav\Common\Filesystem\Folder; use Grav\Common\HTTP\Response; use Grav\Common\GPM\Installer; use Grav\Common\GPM\Upgrader; use Grav\Common\Grav; use Grav\Console\GpmCommand; use Grav\Installer\Install; use RuntimeException; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Question\ConfirmationQuestion; use ZipArchive; use function is_callable; use function strlen; /** * Class SelfupgradeCommand * @package Grav\Console\Gpm */ class SelfupgradeCommand extends GpmCommand { /** @var array */ protected $data; /** @var string */ protected $file; /** @var array */ protected $types = ['plugins', 'themes']; /** @var string|null */ private $tmp; /** @var Upgrader */ private $upgrader; /** @var string */ protected $all_yes; /** @var string */ protected $overwrite; /** @var int */ protected $timeout; /** * @return void */ protected function configure(): void { $this ->setName('self-upgrade') ->setAliases(['selfupgrade', 'selfupdate']) ->addOption( 'force', 'f', InputOption::VALUE_NONE, 'Force re-fetching the data from remote' ) ->addOption( 'all-yes', 'y', InputOption::VALUE_NONE, 'Assumes yes (or best approach) instead of prompting' ) ->addOption( 'overwrite', 'o', InputOption::VALUE_NONE, 'Option to overwrite packages if they already exist' ) ->addOption( 'timeout', 't', InputOption::VALUE_OPTIONAL, 'Option to set the timeout in seconds when downloading the update (0 for no timeout)', 30 ) ->setDescription('Detects and performs an update of Grav itself when available') ->setHelp('The <info>update</info> command updates Grav itself when a new version is available'); } /** * @return int */ protected function serve(): int { $input = $this->getInput(); $io = $this->getIO(); if (!class_exists(ZipArchive::class)) { $io->title('GPM Self Upgrade'); $io->error('php-zip extension needs to be enabled!'); return 1; } $this->upgrader = new Upgrader($input->getOption('force')); $this->all_yes = $input->getOption('all-yes'); $this->overwrite = $input->getOption('overwrite'); $this->timeout = (int) $input->getOption('timeout'); $this->displayGPMRelease(); $update = $this->upgrader->getAssets()['grav-update']; $local = $this->upgrader->getLocalVersion(); $remote = $this->upgrader->getRemoteVersion(); $release = strftime('%c', strtotime($this->upgrader->getReleaseDate())); if (!$this->upgrader->meetsRequirements()) { $io->writeln('<red>ATTENTION:</red>'); $io->writeln(' Grav has increased the minimum PHP requirement.'); $io->writeln(' You are currently running PHP <red>' . phpversion() . '</red>, but PHP <green>' . $this->upgrader->minPHPVersion() . '</green> is required.'); $io->writeln(' Additional information: <white>http://getgrav.org/blog/changing-php-requirements</white>'); $io->newLine(); $io->writeln('Selfupgrade aborted.'); $io->newLine(); return 1; } if (!$this->overwrite && !$this->upgrader->isUpgradable()) { $io->writeln("You are already running the latest version of <green>Grav v{$local}</green>"); $io->writeln("which was released on {$release}"); $config = Grav::instance()['config']; $schema = $config->get('versions.core.grav.schema'); if ($schema !== GRAV_SCHEMA && version_compare($schema, GRAV_SCHEMA, '<')) { $io->newLine(); $io->writeln('However post-install scripts have not been run.'); if (!$this->all_yes) { $question = new ConfirmationQuestion( 'Would you like to run the scripts? [Y|n] ', true ); $answer = $io->askQuestion($question); } else { $answer = true; } if ($answer) { // Finalize installation. Install::instance()->finalize(); $io->write(' |- Running post-install scripts... '); $io->writeln(" '- <green>Success!</green> "); $io->newLine(); } } return 0; } Installer::isValidDestination(GRAV_ROOT . '/system'); if (Installer::IS_LINK === Installer::lastErrorCode()) { $io->writeln('<red>ATTENTION:</red> Grav is symlinked, cannot upgrade, aborting...'); $io->newLine(); $io->writeln("You are currently running a symbolically linked Grav v{$local}. Latest available is v{$remote}."); return 1; } // not used but preloaded just in case! new ArrayInput([]); $io->writeln("Grav v<cyan>{$remote}</cyan> is now available [release date: {$release}]."); $io->writeln('You are currently using v<cyan>' . GRAV_VERSION . '</cyan>.'); if (!$this->all_yes) { $question = new ConfirmationQuestion( 'Would you like to read the changelog before proceeding? [y|N] ', false ); $answer = $io->askQuestion($question); if ($answer) { $changelog = $this->upgrader->getChangelog(GRAV_VERSION); $io->newLine(); foreach ($changelog as $version => $log) { $title = $version . ' [' . $log['date'] . ']'; $content = preg_replace_callback('/\d\.\s\[\]\(#(.*)\)/', static function ($match) { return "\n" . ucfirst($match[1]) . ':'; }, $log['content']); $io->writeln($title); $io->writeln(str_repeat('-', strlen($title))); $io->writeln($content); $io->newLine(); } $question = new ConfirmationQuestion('Press [ENTER] to continue.', true); $io->askQuestion($question); } $question = new ConfirmationQuestion('Would you like to upgrade now? [y|N] ', false); $answer = $io->askQuestion($question); if (!$answer) { $io->writeln('Aborting...'); return 1; } } $io->newLine(); $io->writeln("Preparing to upgrade to v<cyan>{$remote}</cyan>.."); $io->write(" |- Downloading upgrade [{$this->formatBytes($update['size'])}]... 0%"); $this->file = $this->download($update); $io->write(' |- Installing upgrade... '); $installation = $this->upgrade(); $error = 0; if (!$installation) { $io->writeln(" '- <red>Installation failed or aborted.</red>"); $io->newLine(); $error = 1; } else { $io->writeln(" '- <green>Success!</green> "); $io->newLine(); } if ($this->tmp && is_dir($this->tmp)) { Folder::delete($this->tmp); } return $error; } /** * @param array $package * @return string */ private function download(array $package): string { $io = $this->getIO(); $tmp_dir = Grav::instance()['locator']->findResource('tmp://', true, true); $this->tmp = $tmp_dir . '/grav-update-' . uniqid('', false); $options = [ 'timeout' => $this->timeout, ]; $output = Response::get($package['download'], $options, [$this, 'progress']); Folder::create($this->tmp); $io->write("\x0D"); $io->write(" |- Downloading upgrade [{$this->formatBytes($package['size'])}]... 100%"); $io->newLine(); file_put_contents($this->tmp . DS . $package['name'], $output); return $this->tmp . DS . $package['name']; } /** * @return bool */ private function upgrade(): bool { $io = $this->getIO(); $this->upgradeGrav($this->file); $errorCode = Installer::lastErrorCode(); if ($errorCode) { $io->write("\x0D"); // extra white spaces to clear out the buffer properly $io->writeln(' |- Installing upgrade... <red>error</red> '); $io->writeln(" | '- " . Installer::lastErrorMsg()); return false; } $io->write("\x0D"); // extra white spaces to clear out the buffer properly $io->writeln(' |- Installing upgrade... <green>ok</green> '); return true; } /** * @param array $progress * @return void */ public function progress(array $progress): void { $io = $this->getIO(); $io->write("\x0D"); $io->write(" |- Downloading upgrade [{$this->formatBytes($progress['filesize']) }]... " . str_pad( $progress['percent'], 5, ' ', STR_PAD_LEFT ) . '%'); } /** * @param int|float $size * @param int $precision * @return string */ public function formatBytes($size, int $precision = 2): string { $base = log($size) / log(1024); $suffixes = array('', 'k', 'M', 'G', 'T'); return round(1024 ** ($base - floor($base)), $precision) . $suffixes[(int)floor($base)]; } /** * @param string $zip * @return void */ private function upgradeGrav(string $zip): void { try { $folder = Installer::unZip($zip, $this->tmp . '/zip'); if ($folder === false) { throw new RuntimeException(Installer::lastErrorMsg()); } $script = $folder . '/system/install.php'; if ((file_exists($script) && $install = include $script) && is_callable($install)) { $install($zip); } else { throw new RuntimeException('Uploaded archive file is not a valid Grav update package'); } } catch (Exception $e) { Installer::setError($e->getMessage()); } } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Cli/InstallCommand.php
system/src/Grav/Console/Cli/InstallCommand.php
<?php /** * @package Grav\Console\Cli * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Cli; use Grav\Console\GravCommand; use Grav\Framework\File\Formatter\JsonFormatter; use Grav\Framework\File\JsonFile; use RocketTheme\Toolbox\File\YamlFile; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use function is_array; /** * Class InstallCommand * @package Grav\Console\Cli */ class InstallCommand extends GravCommand { /** @var array */ protected $config; /** @var string */ protected $destination; /** @var string */ protected $user_path; /** * @return void */ protected function configure(): void { $this ->setName('install') ->addOption( 'symlink', 's', InputOption::VALUE_NONE, 'Symlink the required bits' ) ->addOption( 'plugin', 'p', InputOption::VALUE_REQUIRED, 'Install plugin (symlink)' ) ->addOption( 'theme', 't', InputOption::VALUE_REQUIRED, 'Install theme (symlink)' ) ->addArgument( 'destination', InputArgument::OPTIONAL, 'Where to install the required bits (default to current project)' ) ->setDescription('Installs the dependencies needed by Grav. Optionally can create symbolic links') ->setHelp('The <info>install</info> command installs the dependencies needed by Grav. Optionally can create symbolic links'); } /** * @return int */ protected function serve(): int { $input = $this->getInput(); $io = $this->getIO(); $dependencies_file = '.dependencies'; $this->destination = $input->getArgument('destination') ?: GRAV_WEBROOT; // fix trailing slash $this->destination = rtrim($this->destination, DS) . DS; $this->user_path = $this->destination . GRAV_USER_PATH . DS; if ($local_config_file = $this->loadLocalConfig()) { $io->writeln('Read local config from <cyan>' . $local_config_file . '</cyan>'); } // Look for dependencies file in ROOT and USER dir if (file_exists($this->user_path . $dependencies_file)) { $file = YamlFile::instance($this->user_path . $dependencies_file); } elseif (file_exists($this->destination . $dependencies_file)) { $file = YamlFile::instance($this->destination . $dependencies_file); } else { $io->writeln('<red>ERROR</red> Missing .dependencies file in <cyan>user/</cyan> folder'); if ($input->getArgument('destination')) { $io->writeln('<yellow>HINT</yellow> <info>Are you trying to install a plugin or a theme? Make sure you use <cyan>bin/gpm install <something></cyan>, not <cyan>bin/grav install</cyan>. This command is only used to install Grav skeletons.'); } else { $io->writeln('<yellow>HINT</yellow> <info>Are you trying to install Grav? Grav is already installed. You need to run this command only if you download a skeleton from GitHub directly.'); } return 1; } $this->config = $file->content(); $file->free(); // If no config, fail. if (!$this->config) { $io->writeln('<red>ERROR</red> invalid YAML in ' . $dependencies_file); return 1; } $plugin = $input->getOption('plugin'); $theme = $input->getOption('theme'); $name = $plugin ?? $theme; $symlink = $name || $input->getOption('symlink'); if (!$symlink) { // Updates composer first $io->writeln("\nInstalling vendor dependencies"); $io->writeln($this->composerUpdate(GRAV_ROOT, 'install')); $error = $this->gitclone(); } else { $type = $name ? ($plugin ? 'plugin' : 'theme') : null; $error = $this->symlink($name, $type); } return $error; } /** * Clones from Git * * @return int */ private function gitclone(): int { $io = $this->getIO(); $io->newLine(); $io->writeln('<green>Cloning Bits</green>'); $io->writeln('============'); $io->newLine(); $error = 0; $this->destination = rtrim($this->destination, DS); foreach ($this->config['git'] as $repo => $data) { $path = $this->destination . DS . $data['path']; if (!file_exists($path)) { exec('cd ' . escapeshellarg($this->destination) . ' && git clone -b ' . $data['branch'] . ' --depth 1 ' . $data['url'] . ' ' . $data['path'], $output, $return); if (!$return) { $io->writeln('<green>SUCCESS</green> cloned <magenta>' . $data['url'] . '</magenta> -> <cyan>' . $path . '</cyan>'); } else { $io->writeln('<red>ERROR</red> cloning <magenta>' . $data['url']); $error = 1; } $io->newLine(); } else { $io->writeln('<yellow>' . $path . ' already exists, skipping...</yellow>'); $io->newLine(); } } return $error; } /** * Symlinks * * @param string|null $name * @param string|null $type * @return int */ private function symlink(string $name = null, string $type = null): int { $io = $this->getIO(); $io->newLine(); $io->writeln('<green>Symlinking Bits</green>'); $io->writeln('==============='); $io->newLine(); if (!$this->local_config) { $io->writeln('<red>No local configuration available, aborting...</red>'); $io->newLine(); return 1; } $error = 0; $this->destination = rtrim($this->destination, DS); if ($name) { $src = "grav-{$type}-{$name}"; $links = [ $name => [ 'scm' => 'github', // TODO: make configurable 'src' => $src, 'path' => "user/{$type}s/{$name}" ] ]; } else { $links = $this->config['links']; } foreach ($links as $name => $data) { $scm = $data['scm'] ?? null; $src = $data['src'] ?? null; $path = $data['path'] ?? null; if (!isset($scm, $src, $path)) { $io->writeln("<red>Dependency '$name' has broken configuration, skipping...</red>"); $io->newLine(); $error = 1; continue; } $locations = (array) $this->local_config["{$scm}_repos"]; $to = $this->destination . DS . $path; $from = null; foreach ($locations as $location) { $test = rtrim($location, '\\/') . DS . $src; if (file_exists($test)) { $from = $test; continue; } } if (is_link($to) && !realpath($to)) { $io->writeln('<yellow>Removed broken symlink '. $path .'</yellow>'); unlink($to); } if (null === $from) { $io->writeln('<red>source for ' . $src . ' does not exists, skipping...</red>'); $io->newLine(); $error = 1; } elseif (!file_exists($to)) { $error = $this->addSymlinks($from, $to, ['name' => $name, 'src' => $src, 'path' => $path]); $io->newLine(); } else { $io->writeln('<yellow>destination: ' . $path . ' already exists, skipping...</yellow>'); $io->newLine(); } } return $error; } private function addSymlinks(string $from, string $to, array $options): int { $io = $this->getIO(); $hebe = $this->readHebe($from); if (null === $hebe) { symlink($from, $to); $io->writeln('<green>SUCCESS</green> symlinked <magenta>' . $options['src'] . '</magenta> -> <cyan>' . $options['path'] . '</cyan>'); } else { $to = GRAV_ROOT; $name = $options['name']; $io->writeln("Processing <magenta>{$name}</magenta>"); foreach ($hebe as $section => $symlinks) { foreach ($symlinks as $symlink) { $src = trim($symlink['source'], '/'); $dst = trim($symlink['destination'], '/'); $s = "{$from}/{$src}"; $d = "{$to}/{$dst}"; if (is_link($d) && !realpath($d)) { unlink($d); $io->writeln(' <yellow>Removed broken symlink '. $dst .'</yellow>'); } if (!file_exists($d)) { symlink($s, $d); $io->writeln(' symlinked <magenta>' . $src . '</magenta> -> <cyan>' . $dst . '</cyan>'); } } } $io->writeln('<green>SUCCESS</green>'); } return 0; } private function readHebe(string $folder): ?array { $filename = "{$folder}/hebe.json"; if (!is_file($filename)) { return null; } $formatter = new JsonFormatter(); $file = new JsonFile($filename, $formatter); $hebe = $file->load(); $paths = $hebe['platforms']['grav']['nodes'] ?? null; return is_array($paths) ? $paths : null; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Cli/SchedulerCommand.php
system/src/Grav/Console/Cli/SchedulerCommand.php
<?php /** * @package Grav\Console\Cli * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Cli; use Cron\CronExpression; use Grav\Common\Grav; use Grav\Common\Utils; use Grav\Common\Scheduler\Scheduler; use Grav\Console\GravCommand; use RocketTheme\Toolbox\Event\Event; use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Input\InputOption; use function is_null; /** * Class SchedulerCommand * @package Grav\Console\Cli */ class SchedulerCommand extends GravCommand { /** * @return void */ protected function configure(): void { $this ->setName('scheduler') ->addOption( 'install', 'i', InputOption::VALUE_NONE, 'Show Install Command' ) ->addOption( 'jobs', 'j', InputOption::VALUE_NONE, 'Show Jobs Summary' ) ->addOption( 'details', 'd', InputOption::VALUE_NONE, 'Show Job Details' ) ->addOption( 'run', 'r', InputOption::VALUE_OPTIONAL, 'Force run all jobs or a specific job if you specify a specific Job ID', false ) ->addOption( 'force', 'f', InputOption::VALUE_NONE, 'Force all due jobs to run regardless of their schedule' ) ->setDescription('Run the Grav Scheduler. Best when integrated with system cron') ->setHelp("Running without any options will process the Scheduler jobs based on their cron schedule. Use --force to run all jobs immediately."); } /** * @return int */ protected function serve(): int { $this->initializePlugins(); $grav = Grav::instance(); $grav['backups']->init(); $this->initializePages(); $this->initializeThemes(); /** @var Scheduler $scheduler */ $scheduler = $grav['scheduler']; $grav->fireEvent('onSchedulerInitialized', new Event(['scheduler' => $scheduler])); $input = $this->getInput(); $io = $this->getIO(); $error = 0; $run = $input->getOption('run'); $showDetails = $input->getOption('details'); $showJobs = $input->getOption('jobs'); $forceRun = $input->getOption('force'); // Handle running jobs first if -r flag is present if ($run !== false) { if ($run === null || $run === '') { // Run all jobs when -r is provided without a specific job ID $io->title('Force Run All Jobs'); $jobs = $scheduler->getAllJobs(); $hasOutput = false; foreach ($jobs as $job) { if ($job->getEnabled()) { $io->section('Running: ' . $job->getId()); $job->inForeground()->run(); if ($job->isSuccessful()) { $io->success('Job ' . $job->getId() . ' ran successfully'); } else { $error = 1; $io->error('Job ' . $job->getId() . ' failed to run'); } $output = $job->getOutput(); if ($output) { $io->write($output); $hasOutput = true; } } } if (!$hasOutput) { $io->note('All enabled jobs completed'); } } else { // Run specific job $io->title('Force Run Job: ' . $run); $job = $scheduler->getJob($run); if ($job) { $job->inForeground()->run(); if ($job->isSuccessful()) { $io->success('Job ran successfully...'); } else { $error = 1; $io->error('Job failed to run successfully...'); } $output = $job->getOutput(); if ($output) { $io->write($output); } } else { $error = 1; $io->error('Could not find a job with id: ' . $run); } } // Add separator if we're going to show details after if ($showDetails) { $io->newLine(); } } if ($showJobs) { // Show jobs list $jobs = $scheduler->getAllJobs(); $job_states = (array)$scheduler->getJobStates()->content(); $rows = []; $table = new Table($io); $table->setStyle('box'); $headers = ['Job ID', 'Command', 'Run At', 'Status', 'Last Run', 'State']; $io->title('Scheduler Jobs Listing'); foreach ($jobs as $job) { $job_status = ucfirst($job_states[$job->getId()]['state'] ?? 'ready'); $last_run = $job_states[$job->getId()]['last-run'] ?? 0; $status = $job_status === 'Failure' ? "<red>{$job_status}</red>" : "<green>{$job_status}</green>"; $state = $job->getEnabled() ? '<cyan>Enabled</cyan>' : '<red>Disabled</red>'; $row = [ $job->getId(), "<white>{$job->getCommand()}</white>", "<magenta>{$job->getAt()}</magenta>", $status, '<yellow>' . ($last_run === 0 ? 'Never' : date('Y-m-d H:i', $last_run)) . '</yellow>', $state, ]; $rows[] = $row; } if (!empty($rows)) { $table->setHeaders($headers); $table->setRows($rows); $table->render(); } else { $io->text('no jobs found...'); } $io->newLine(); $io->note('For error details run "bin/grav scheduler -d"'); $io->newLine(); } if ($showDetails) { $jobs = $scheduler->getAllJobs(); $job_states = (array)$scheduler->getJobStates()->content(); $io->title('Job Details'); $table = new Table($io); $table->setStyle('box'); $table->setHeaders(['Job ID', 'Last Run', 'Next Run', 'Errors']); $rows = []; foreach ($jobs as $job) { $job_state = $job_states[$job->getId()]; $error = isset($job_state['error']) ? trim($job_state['error']) : false; /** @var CronExpression $expression */ $expression = $job->getCronExpression(); $next_run = $expression->getNextRunDate(); $row = []; $row[] = $job->getId(); if (!is_null($job_state['last-run'])) { $row[] = '<yellow>' . date('Y-m-d H:i', $job_state['last-run']) . '</yellow>'; } else { $row[] = '<yellow>Never</yellow>'; } $row[] = '<yellow>' . $next_run->format('Y-m-d H:i') . '</yellow>'; if ($error) { $row[] = "<error>{$error}</error>"; } else { $row[] = '<green>None</green>'; } $rows[] = $row; } $table->setRows($rows); $table->render(); } if ($input->getOption('install')) { $io->title('Install Scheduler'); $verb = 'install'; if ($scheduler->isCrontabSetup()) { $io->success('All Ready! You have already set up Grav\'s Scheduler in your crontab. You can validate this by running "crontab -l" to list your current crontab entries.'); $verb = 'reinstall'; } else { $user = $scheduler->whoami(); $error = 1; $io->error('Can\'t find a crontab for ' . $user . '. You need to set up Grav\'s Scheduler in your crontab'); } if (!Utils::isWindows()) { $io->note("To $verb, run the following command from your terminal:"); $io->newLine(); $io->text(trim($scheduler->getCronCommand())); } else { $io->note("To $verb, create a scheduled task in Windows."); $io->text('Learn more at https://learn.getgrav.org/advanced/scheduler'); } } elseif (!$showJobs && !$showDetails && $run === false) { // Run scheduler only if no other options were provided $scheduler->run(null, $forceRun); if ($input->getOption('verbose')) { $io->title('Running Scheduled Jobs'); $io->text($scheduler->getVerboseOutput()); } } return $error; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Cli/CleanCommand.php
system/src/Grav/Console/Cli/CleanCommand.php
<?php /** * @package Grav\Console\Cli * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Cli; use Grav\Common\Filesystem\Folder; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Formatter\OutputFormatterStyle; use Symfony\Component\Console\Style\SymfonyStyle; /** * Class CleanCommand * @package Grav\Console\Cli */ class CleanCommand extends Command { /** @var InputInterface */ protected $input; /** @var SymfonyStyle */ protected $io; /** @var array */ protected $paths_to_remove = [ 'codeception.yml', 'tests/', 'user/plugins/admin/vendor/bacon/bacon-qr-code/tests', 'user/plugins/admin/vendor/bacon/bacon-qr-code/.gitignore', 'user/plugins/admin/vendor/bacon/bacon-qr-code/.travis.yml', 'user/plugins/admin/vendor/bacon/bacon-qr-code/composer.json', 'user/plugins/admin/vendor/robthree/twofactorauth/demo', 'user/plugins/admin/vendor/robthree/twofactorauth/.vs', 'user/plugins/admin/vendor/robthree/twofactorauth/tests', 'user/plugins/admin/vendor/robthree/twofactorauth/.gitignore', 'user/plugins/admin/vendor/robthree/twofactorauth/.travis.yml', 'user/plugins/admin/vendor/robthree/twofactorauth/composer.json', 'user/plugins/admin/vendor/robthree/twofactorauth/composer.lock', 'user/plugins/admin/vendor/robthree/twofactorauth/logo.png', 'user/plugins/admin/vendor/robthree/twofactorauth/multifactorauthforeveryone.png', 'user/plugins/admin/vendor/robthree/twofactorauth/TwoFactorAuth.phpproj', 'user/plugins/admin/vendor/robthree/twofactorauth/TwoFactorAuth.sin', 'user/plugins/admin/vendor/zendframework/zendxml/tests', 'user/plugins/admin/vendor/zendframework/zendxml/.gitignore', 'user/plugins/admin/vendor/zendframework/zendxml/.travis.yml', 'user/plugins/admin/vendor/zendframework/zendxml/composer.json', 'user/plugins/email/vendor/swiftmailer/swiftmailer/.travis.yml', 'user/plugins/email/vendor/swiftmailer/swiftmailer/build.xml', 'user/plugins/email/vendor/swiftmailer/swiftmailer/composer.json', 'user/plugins/email/vendor/swiftmailer/swiftmailer/create_pear_package.php', 'user/plugins/email/vendor/swiftmailer/swiftmailer/package.xml.tpl', 'user/plugins/email/vendor/swiftmailer/swiftmailer/.gitattributes', 'user/plugins/email/vendor/swiftmailer/swiftmailer/.gitignore', 'user/plugins/email/vendor/swiftmailer/swiftmailer/README.git', 'user/plugins/email/vendor/swiftmailer/swiftmailer/tests', 'user/plugins/email/vendor/swiftmailer/swiftmailer/test-suite', 'user/plugins/email/vendor/swiftmailer/swiftmailer/notes', 'user/plugins/email/vendor/swiftmailer/swiftmailer/doc', 'user/themes/antimatter/.sass-cache', 'vendor/antoligy/dom-string-iterators/composer.json', 'vendor/composer/ca-bundle/composer.json', 'vendor/composer/ca-bundle/phpstan.neon.dist', 'vendor/composer/semver/CHANGELOG.md', 'vendor/composer/semver/composer.json', 'vendor/composer/semver/phpstan.neon.dist', 'vendor/doctrine/cache/.travis.yml', 'vendor/doctrine/cache/build.properties', 'vendor/doctrine/cache/build.xml', 'vendor/doctrine/cache/composer.json', 'vendor/doctrine/cache/phpunit.xml.dist', 'vendor/doctrine/cache/.coveralls.yml', 'vendor/doctrine/cache/.gitignore', 'vendor/doctrine/cache/.git', 'vendor/doctrine/cache/tests', 'vendor/doctrine/cache/UPGRADE.md', 'vendor/doctrine/collections/docs', 'vendor/doctrine/collections/.doctrine-project.json', 'vendor/doctrine/collections/CONTRIBUTING.md', 'vendor/doctrine/collections/psalm.xml.dist', 'vendor/doctrine/collections/composer.json', 'vendor/doctrine/collections/phpunit.xml.dist', 'vendor/doctrine/collections/tests', 'vendor/donatj/phpuseragentparser/.git', 'vendor/donatj/phpuseragentparser/.github', 'vendor/donatj/phpuseragentparser/.gitignore', 'vendor/donatj/phpuseragentparser/.editorconfig', 'vendor/donatj/phpuseragentparser/.travis.yml', 'vendor/donatj/phpuseragentparser/composer.json', 'vendor/donatj/phpuseragentparser/phpunit.xml.dist', 'vendor/donatj/phpuseragentparser/tests', 'vendor/donatj/phpuseragentparser/Tools', 'vendor/donatj/phpuseragentparser/CONTRIBUTING.md', 'vendor/donatj/phpuseragentparser/Makefile', 'vendor/donatj/phpuseragentparser/.mddoc.xml', 'vendor/dragonmantank/cron-expression/.editorconfig', 'vendor/dragonmantank/cron-expression/composer.json', 'vendor/dragonmantank/cron-expression/tests', 'vendor/dragonmantank/cron-expression/CHANGELOG.md', 'vendor/rhukster/dom-sanitizer/tests', 'vendor/rhukster/dom-sanitizer/.gitignore', 'vendor/rhukster/dom-sanitizer/composer.json', 'vendor/rhukster/dom-sanitizer/composer.lock', 'vendor/erusev/parsedown/composer.json', 'vendor/erusev/parsedown/phpunit.xml.dist', 'vendor/erusev/parsedown/.travis.yml', 'vendor/erusev/parsedown/.git', 'vendor/erusev/parsedown/test', 'vendor/erusev/parsedown-extra/composer.json', 'vendor/erusev/parsedown-extra/phpunit.xml.dist', 'vendor/erusev/parsedown-extra/.travis.yml', 'vendor/erusev/parsedown-extra/.git', 'vendor/erusev/parsedown-extra/test', 'vendor/filp/whoops/composer.json', 'vendor/filp/whoops/docs', 'vendor/filp/whoops/examples', 'vendor/filp/whoops/tests', 'vendor/filp/whoops/.git', 'vendor/filp/whoops/.github', 'vendor/filp/whoops/.gitignore', 'vendor/filp/whoops/.scrutinizer.yml', 'vendor/filp/whoops/.travis.yml', 'vendor/filp/whoops/phpunit.xml.dist', 'vendor/filp/whoops/CHANGELOG.md', 'vendor/gregwar/image/Gregwar/Image/composer.json', 'vendor/gregwar/image/Gregwar/Image/phpunit.xml', 'vendor/gregwar/image/Gregwar/Image/phpunit.xml.dist', 'vendor/gregwar/image/Gregwar/Image/Makefile', 'vendor/gregwar/image/Gregwar/Image/.editorconfig', 'vendor/gregwar/image/Gregwar/Image/.php_cs', 'vendor/gregwar/image/Gregwar/Image/.styleci.yml', 'vendor/gregwar/image/Gregwar/Image/.travis.yml', 'vendor/gregwar/image/Gregwar/Image/.gitignore', 'vendor/gregwar/image/Gregwar/Image/.git', 'vendor/gregwar/image/Gregwar/Image/doc', 'vendor/gregwar/image/Gregwar/Image/demo', 'vendor/gregwar/image/Gregwar/Image/tests', 'vendor/gregwar/cache/Gregwar/Cache/composer.json', 'vendor/gregwar/cache/Gregwar/Cache/phpunit.xml', 'vendor/gregwar/cache/Gregwar/Cache/.travis.yml', 'vendor/gregwar/cache/Gregwar/Cache/.gitignore', 'vendor/gregwar/cache/Gregwar/Cache/.git', 'vendor/gregwar/cache/Gregwar/Cache/demo', 'vendor/gregwar/cache/Gregwar/Cache/tests', 'vendor/guzzlehttp/psr7/composer.json', 'vendor/guzzlehttp/psr7/.editorconfig', 'vendor/guzzlehttp/psr7/CHANGELOG.md', 'vendor/itsgoingd/clockwork/.gitattributes', 'vendor/itsgoingd/clockwork/CHANGELOG.md', 'vendor/itsgoingd/clockwork/composer.json', 'vendor/league/climate/composer.json', 'vendor/league/climate/CHANGELOG.md', 'vendor/league/climate/CONTRIBUTING.md', 'vendor/league/climate/Dockerfile', 'vendor/league/climate/CODE_OF_CONDUCT.md', 'vendor/matthiasmullie/minify/.github', 'vendor/matthiasmullie/minify/bin', 'vendor/matthiasmullie/minify/composer.json', 'vendor/matthiasmullie/minify/docker-compose.yml', 'vendor/matthiasmullie/minify/Dockerfile', 'vendor/matthiasmullie/minify/CONTRIBUTING.md', 'vendor/matthiasmullie/path-converter/composer.json', 'vendor/maximebf/debugbar/.github', 'vendor/maximebf/debugbar/bower.json', 'vendor/maximebf/debugbar/composer.json', 'vendor/maximebf/debugbar/.bowerrc', 'vendor/maximebf/debugbar/src/DebugBar/Resources/vendor', 'vendor/maximebf/debugbar/demo', 'vendor/maximebf/debugbar/docs', 'vendor/maximebf/debugbar/tests', 'vendor/maximebf/debugbar/phpunit.xml.dist', 'vendor/miljar/php-exif/.coveralls.yml', 'vendor/miljar/php-exif/.gitignore', 'vendor/miljar/php-exif/.travis.yml', 'vendor/miljar/php-exif/composer.json', 'vendor/miljar/php-exif/composer.lock', 'vendor/miljar/php-exif/phpunit.xml.dist', 'vendor/miljar/php-exif/Resources', 'vendor/miljar/php-exif/tests', 'vendor/miljar/php-exif/CHANGELOG.rst', 'vendor/monolog/monolog/composer.json', 'vendor/monolog/monolog/doc', 'vendor/monolog/monolog/phpunit.xml.dist', 'vendor/monolog/monolog/.php_cs', 'vendor/monolog/monolog/tests', 'vendor/monolog/monolog/CHANGELOG.md', 'vendor/monolog/monolog/phpstan.neon.dist', 'vendor/nyholm/psr7/composer.json', 'vendor/nyholm/psr7/phpstan.neon.dist', 'vendor/nyholm/psr7/CHANGELOG.md', 'vendor/nyholm/psr7/psalm.xml', 'vendor/nyholm/psr7-server/.github', 'vendor/nyholm/psr7-server/composer.json', 'vendor/nyholm/psr7-server/CHANGELOG.md', 'vendor/phive/twig-extensions-deferred/.gitignore', 'vendor/phive/twig-extensions-deferred/.travis.yml', 'vendor/phive/twig-extensions-deferred/composer.json', 'vendor/phive/twig-extensions-deferred/phpunit.xml.dist', 'vendor/phive/twig-extensions-deferred/tests', 'vendor/php-http/message-factory/composer.json', 'vendor/php-http/message-factory/puli.json', 'vendor/php-http/message-factory/CHANGELOG.md', 'vendor/pimple/pimple/.gitignore', 'vendor/pimple/pimple/.travis.yml', 'vendor/pimple/pimple/composer.json', 'vendor/pimple/pimple/ext', 'vendor/pimple/pimple/phpunit.xml.dist', 'vendor/pimple/pimple/src/Pimple/Tests', 'vendor/pimple/pimple/.php_cs.dist', 'vendor/pimple/pimple/CHANGELOG', 'vendor/psr/cache/CHANGELOG.md', 'vendor/psr/cache/composer.json', 'vendor/psr/container/composer.json', 'vendor/psr/container/.gitignore', 'vendor/psr/http-factory/.gitignore', 'vendor/psr/http-factory/.pullapprove.yml', 'vendor/psr/http-factory/composer.json', 'vendor/psr/http-message/composer.json', 'vendor/psr/http-message/CHANGELOG.md', 'vendor/psr/http-server-handler/composer.json', 'vendor/psr/http-server-middleware/composer.json', 'vendor/psr/simple-cache/.editorconfig', 'vendor/psr/simple-cache/composer.json', 'vendor/psr/log/composer.json', 'vendor/psr/log/.gitignore', 'vendor/ralouphie/getallheaders/.gitignore', 'vendor/ralouphie/getallheaders/.travis.yml', 'vendor/ralouphie/getallheaders/composer.json', 'vendor/ralouphie/getallheaders/phpunit.xml', 'vendor/ralouphie/getallheaders/tests/', 'vendor/rockettheme/toolbox/.git', 'vendor/rockettheme/toolbox/.gitignore', 'vendor/rockettheme/toolbox/.scrutinizer.yml', 'vendor/rockettheme/toolbox/.travis.yml', 'vendor/rockettheme/toolbox/composer.json', 'vendor/rockettheme/toolbox/phpunit.xml', 'vendor/rockettheme/toolbox/CHANGELOG.md', 'vendor/rockettheme/toolbox/Blueprints/tests', 'vendor/rockettheme/toolbox/ResourceLocator/tests', 'vendor/rockettheme/toolbox/Session/tests', 'vendor/rockettheme/toolbox/tests', 'vendor/seld/cli-prompt/composer.json', 'vendor/seld/cli-prompt/.gitignore', 'vendor/seld/cli-prompt/.github', 'vendor/seld/cli-prompt/phpstan.neon.dist', 'vendor/symfony/console/composer.json', 'vendor/symfony/console/phpunit.xml.dist', 'vendor/symfony/console/.gitignore', 'vendor/symfony/console/.git', 'vendor/symfony/console/Tester', 'vendor/symfony/console/Tests', 'vendor/symfony/console/CHANGELOG.md', 'vendor/symfony/contracts/Cache/.gitignore', 'vendor/symfony/contracts/Cache/composer.json', 'vendor/symfony/contracts/EventDispatcher/.gitignore', 'vendor/symfony/contracts/EventDispatcher/composer.json', 'vendor/symfony/contracts/HttpClient/.gitignore', 'vendor/symfony/contracts/HttpClient/composer.json', 'vendor/symfony/contracts/HttpClient/Test', 'vendor/symfony/contracts/Service/.gitignore', 'vendor/symfony/contracts/Service/composer.json', 'vendor/symfony/contracts/Service/Test', 'vendor/symfony/contracts/Tests', 'vendor/symfony/contracts/Translation/.gitignore', 'vendor/symfony/contracts/Translation/composer.json', 'vendor/symfony/contracts/Translation/Test', 'vendor/symfony/contracts/.gitignore', 'vendor/symfony/contracts/composer.json', 'vendor/symfony/contracts/phpunit.xml.dist', 'vendor/symfony/event-dispatcher/.git', 'vendor/symfony/event-dispatcher/.gitignore', 'vendor/symfony/event-dispatcher/composer.json', 'vendor/symfony/event-dispatcher/phpunit.xml.dist', 'vendor/symfony/event-dispatcher/Tests', 'vendor/symfony/event-dispatcher/CHANGELOG.md', 'vendor/symfony/http-client/CHANGELOG.md', 'vendor/symfony/http-client/composer.json', 'vendor/symfony/polyfill-ctype/composer.json', 'vendor/symfony/polyfill-iconv/.git', 'vendor/symfony/polyfill-iconv/.gitignore', 'vendor/symfony/polyfill-iconv/composer.json', 'vendor/symfony/polyfill-mbstring/.git', 'vendor/symfony/polyfill-mbstring/.gitignore', 'vendor/symfony/polyfill-mbstring/composer.json', 'vendor/symfony/polyfill-php72/composer.json', 'vendor/symfony/polyfill-php73/composer.json', 'vendor/symfony/process/.gitignore', 'vendor/symfony/process/composer.json', 'vendor/symfony/process/phpunit.xml.dist', 'vendor/symfony/process/Tests', 'vendor/symfony/process/CHANGELOG.md', 'vendor/symfony/var-dumper/.git', 'vendor/symfony/var-dumper/.gitignore', 'vendor/symfony/var-dumper/composer.json', 'vendor/symfony/var-dumper/phpunit.xml.dist', 'vendor/symfony/var-dumper/Test', 'vendor/symfony/var-dumper/Tests', 'vendor/symfony/var-dumper/CHANGELOG.md', 'vendor/symfony/yaml/composer.json', 'vendor/symfony/yaml/phpunit.xml.dist', 'vendor/symfony/yaml/.gitignore', 'vendor/symfony/yaml/.git', 'vendor/symfony/yaml/Tests', 'vendor/symfony/yaml/CHANGELOG.md', 'vendor/twig/twig/.editorconfig', 'vendor/twig/twig/.php_cs.dist', 'vendor/twig/twig/.travis.yml', 'vendor/twig/twig/.gitignore', 'vendor/twig/twig/.git', 'vendor/twig/twig/.github', 'vendor/twig/twig/composer.json', 'vendor/twig/twig/phpunit.xml.dist', 'vendor/twig/twig/doc', 'vendor/twig/twig/ext', 'vendor/twig/twig/test', 'vendor/twig/twig/.gitattributes', 'vendor/twig/twig/CHANGELOG', 'vendor/twig/twig/drupal_test.sh', 'vendor/willdurand/negotiation/.gitignore', 'vendor/willdurand/negotiation/.travis.yml', 'vendor/willdurand/negotiation/appveyor.yml', 'vendor/willdurand/negotiation/composer.json', 'vendor/willdurand/negotiation/phpunit.xml.dist', 'vendor/willdurand/negotiation/tests', 'vendor/willdurand/negotiation/CONTRIBUTING.md', 'user/config/security.yaml', 'cache/compiled/', ]; /** * @return void */ protected function configure(): void { $this ->setName('clean') ->setDescription('Handles cleaning chores for Grav distribution') ->setHelp('The <info>clean</info> clean extraneous folders and data'); } /** * @param InputInterface $input * @param OutputInterface $output * @return int */ protected function execute(InputInterface $input, OutputInterface $output): int { $this->setupConsole($input, $output); return $this->cleanPaths() ? 0 : 1; } /** * @return bool */ private function cleanPaths(): bool { $success = true; $this->io->writeln(''); $this->io->writeln('<red>DELETING</red>'); $anything = false; foreach ($this->paths_to_remove as $path) { $path = GRAV_ROOT . DS . $path; try { if (is_dir($path) && Folder::delete($path)) { $anything = true; $this->io->writeln('<red>dir: </red>' . $path); } elseif (is_file($path) && @unlink($path)) { $anything = true; $this->io->writeln('<red>file: </red>' . $path); } } catch (\Exception $e) { $success = false; $this->io->error(sprintf('Failed to delete %s: %s', $path, $e->getMessage())); } } if (!$anything) { $this->io->writeln(''); $this->io->writeln('<green>Nothing to clean...</green>'); } return $success; } /** * Set colors style definition for the formatter. * * @param InputInterface $input * @param OutputInterface $output * @return void */ public function setupConsole(InputInterface $input, OutputInterface $output): void { $this->input = $input; $this->io = new SymfonyStyle($input, $output); $this->io->getFormatter()->setStyle('normal', new OutputFormatterStyle('white')); $this->io->getFormatter()->setStyle('yellow', new OutputFormatterStyle('yellow', null, ['bold'])); $this->io->getFormatter()->setStyle('red', new OutputFormatterStyle('red', null, ['bold'])); $this->io->getFormatter()->setStyle('cyan', new OutputFormatterStyle('cyan', null, ['bold'])); $this->io->getFormatter()->setStyle('green', new OutputFormatterStyle('green', null, ['bold'])); $this->io->getFormatter()->setStyle('magenta', new OutputFormatterStyle('magenta', null, ['bold'])); $this->io->getFormatter()->setStyle('white', new OutputFormatterStyle('white', null, ['bold'])); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Cli/YamlLinterCommand.php
system/src/Grav/Console/Cli/YamlLinterCommand.php
<?php /** * @package Grav\Console\Cli * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Cli; use Grav\Common\Helpers\YamlLinter; use Grav\Console\GravCommand; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Style\SymfonyStyle; /** * Class YamlLinterCommand * @package Grav\Console\Cli */ class YamlLinterCommand extends GravCommand { /** * @return void */ protected function configure(): void { $this ->setName('yamllinter') ->addOption( 'all', 'a', InputOption::VALUE_NONE, 'Go through the whole Grav installation' ) ->addOption( 'folder', 'f', InputOption::VALUE_OPTIONAL, 'Go through specific folder' ) ->setDescription('Checks various files for YAML errors') ->setHelp('Checks various files for YAML errors'); } /** * @return int */ protected function serve(): int { $input = $this->getInput(); $io = $this->getIO(); $io->title('Yaml Linter'); $error = 0; if ($input->getOption('all')) { $io->section('All'); $errors = YamlLinter::lint(''); if (empty($errors)) { $io->success('No YAML Linting issues found'); } else { $error = 1; $this->displayErrors($errors, $io); } } elseif ($folder = $input->getOption('folder')) { $io->section($folder); $errors = YamlLinter::lint($folder); if (empty($errors)) { $io->success('No YAML Linting issues found'); } else { $error = 1; $this->displayErrors($errors, $io); } } else { $io->section('User Configuration'); $errors = YamlLinter::lintConfig(); if (empty($errors)) { $io->success('No YAML Linting issues with configuration'); } else { $error = 1; $this->displayErrors($errors, $io); } $io->section('Pages Frontmatter'); $errors = YamlLinter::lintPages(); if (empty($errors)) { $io->success('No YAML Linting issues with pages'); } else { $error = 1; $this->displayErrors($errors, $io); } $io->section('Page Blueprints'); $errors = YamlLinter::lintBlueprints(); if (empty($errors)) { $io->success('No YAML Linting issues with blueprints'); } else { $error = 1; $this->displayErrors($errors, $io); } } return $error; } /** * @param array $errors * @param SymfonyStyle $io * @return void */ protected function displayErrors(array $errors, SymfonyStyle $io): void { $io->error('YAML Linting issues found...'); foreach ($errors as $path => $error) { $io->writeln("<yellow>{$path}</yellow> - {$error}"); } } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Cli/BackupCommand.php
system/src/Grav/Console/Cli/BackupCommand.php
<?php /** * @package Grav\Console\Cli * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Cli; use Grav\Common\Backup\Backups; use Grav\Common\Grav; use Grav\Console\GravCommand; use Symfony\Component\Console\Helper\ProgressBar; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Question\ChoiceQuestion; use ZipArchive; use function count; /** * Class BackupCommand * @package Grav\Console\Cli */ class BackupCommand extends GravCommand { /** @var string $source */ protected $source; /** @var ProgressBar $progress */ protected $progress; /** * @return void */ protected function configure(): void { $this ->setName('backup') ->addArgument( 'id', InputArgument::OPTIONAL, 'The ID of the backup profile to perform without prompting' ) ->setDescription('Creates a backup of the Grav instance') ->setHelp('The <info>backup</info> creates a zipped backup.'); $this->source = getcwd(); } /** * @return int */ protected function serve(): int { $this->initializeGrav(); $input = $this->getInput(); $io = $this->getIO(); $io->title('Grav Backup'); if (!class_exists(ZipArchive::class)) { $io->error('php-zip extension needs to be enabled!'); return 1; } ProgressBar::setFormatDefinition('zip', 'Archiving <cyan>%current%</cyan> files [<green>%bar%</green>] <white>%percent:3s%%</white> %elapsed:6s% <yellow>%message%</yellow>'); $this->progress = new ProgressBar($this->output, 100); $this->progress->setFormat('zip'); /** @var Backups $backups */ $backups = Grav::instance()['backups']; $backups_list = $backups::getBackupProfiles(); $backups_names = $backups->getBackupNames(); $id = null; $inline_id = $input->getArgument('id'); if (null !== $inline_id && is_numeric($inline_id)) { $id = $inline_id; } if (null === $id) { if (count($backups_list) > 1) { $question = new ChoiceQuestion( 'Choose a backup?', $backups_names, 0 ); $question->setErrorMessage('Option %s is invalid.'); $backup_name = $io->askQuestion($question); $id = array_search($backup_name, $backups_names, true); $io->newLine(); $io->note('Selected backup: ' . $backup_name); } else { $id = 0; } } $backup = $backups::backup($id, function($args) { $this->outputProgress($args); }); $io->newline(2); $io->success('Backup Successfully Created: ' . $backup); return 0; } /** * @param array $args * @return void */ public function outputProgress(array $args): void { switch ($args['type']) { case 'count': $steps = $args['steps']; $freq = (int)($steps > 100 ? round($steps / 100) : $steps); $this->progress->setMaxSteps($steps); $this->progress->setRedrawFrequency($freq); $this->progress->setMessage('Adding files...'); break; case 'message': $this->progress->setMessage($args['message']); $this->progress->display(); break; case 'progress': if (isset($args['complete']) && $args['complete']) { $this->progress->finish(); } else { $this->progress->advance(); } break; } } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Cli/ClearCacheCommand.php
system/src/Grav/Console/Cli/ClearCacheCommand.php
<?php /** * @package Grav\Console\Cli * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Cli; use Grav\Common\Cache; use Grav\Console\GravCommand; use Symfony\Component\Console\Input\InputOption; /** * Class ClearCacheCommand * @package Grav\Console\Cli */ class ClearCacheCommand extends GravCommand { /** * @return void */ protected function configure(): void { $this ->setName('cache') ->setAliases(['clearcache', 'cache-clear']) ->setDescription('Clears Grav cache') ->addOption('invalidate', null, InputOption::VALUE_NONE, 'Invalidate cache, but do not remove any files') ->addOption('purge', null, InputOption::VALUE_NONE, 'If set purge old caches') ->addOption('all', null, InputOption::VALUE_NONE, 'If set will remove all including compiled, twig, doctrine caches') ->addOption('assets-only', null, InputOption::VALUE_NONE, 'If set will remove only assets/*') ->addOption('images-only', null, InputOption::VALUE_NONE, 'If set will remove only images/*') ->addOption('cache-only', null, InputOption::VALUE_NONE, 'If set will remove only cache/*') ->addOption('tmp-only', null, InputOption::VALUE_NONE, 'If set will remove only tmp/*') ->setHelp('The <info>cache</info> command allows you to interact with Grav cache'); } /** * @return int */ protected function serve(): int { // Old versions of Grav called this command after grav upgrade. // We need make this command to work with older GravCommand instance: if (!method_exists($this, 'initializePlugins')) { Cache::clearCache('all'); return 0; } $this->initializePlugins(); $this->cleanPaths(); return 0; } /** * loops over the array of paths and deletes the files/folders * * @return void */ private function cleanPaths(): void { $input = $this->getInput(); $io = $this->getIO(); $io->newLine(); if ($input->getOption('purge')) { $io->writeln('<magenta>Purging old cache</magenta>'); $io->newLine(); $msg = Cache::purgeJob(); $io->writeln($msg); } else { $io->writeln('<magenta>Clearing cache</magenta>'); $io->newLine(); if ($input->getOption('all')) { $remove = 'all'; } elseif ($input->getOption('assets-only')) { $remove = 'assets-only'; } elseif ($input->getOption('images-only')) { $remove = 'images-only'; } elseif ($input->getOption('cache-only')) { $remove = 'cache-only'; } elseif ($input->getOption('tmp-only')) { $remove = 'tmp-only'; } elseif ($input->getOption('invalidate')) { $remove = 'invalidate'; } else { $remove = 'standard'; } foreach (Cache::clearCache($remove) as $result) { $io->writeln($result); } } } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Cli/ComposerCommand.php
system/src/Grav/Console/Cli/ComposerCommand.php
<?php /** * @package Grav\Console\Cli * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Cli; use Grav\Console\GravCommand; use Symfony\Component\Console\Input\InputOption; /** * Class ComposerCommand * @package Grav\Console\Cli */ class ComposerCommand extends GravCommand { /** * @return void */ protected function configure(): void { $this ->setName('composer') ->addOption( 'install', 'i', InputOption::VALUE_NONE, 'install the dependencies' ) ->addOption( 'update', 'u', InputOption::VALUE_NONE, 'update the dependencies' ) ->setDescription('Updates the composer vendor dependencies needed by Grav.') ->setHelp('The <info>composer</info> command updates the composer vendor dependencies needed by Grav'); } /** * @return int */ protected function serve(): int { $input = $this->getInput(); $io = $this->getIO(); $action = $input->getOption('install') ? 'install' : ($input->getOption('update') ? 'update' : 'install'); if ($input->getOption('install')) { $action = 'install'; } // Updates composer first $io->writeln("\nInstalling vendor dependencies"); $io->writeln($this->composerUpdate(GRAV_ROOT, $action)); return 0; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Cli/LogViewerCommand.php
system/src/Grav/Console/Cli/LogViewerCommand.php
<?php /** * @package Grav\Console\Cli * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Cli; use DateTime; use Grav\Common\Grav; use Grav\Common\Helpers\LogViewer; use Grav\Console\GravCommand; use Symfony\Component\Console\Input\InputOption; /** * Class LogViewerCommand * @package Grav\Console\Cli */ class LogViewerCommand extends GravCommand { /** * @return void */ protected function configure(): void { $this ->setName('logviewer') ->addOption( 'file', 'f', InputOption::VALUE_OPTIONAL, 'custom log file location (default = grav.log)' ) ->addOption( 'lines', 'l', InputOption::VALUE_OPTIONAL, 'number of lines (default = 10)' ) ->setDescription('Display the last few entries of Grav log') ->setHelp('Display the last few entries of Grav log'); } /** * @return int */ protected function serve(): int { $input = $this->getInput(); $io = $this->getIO(); $file = $input->getOption('file') ?? 'grav.log'; $lines = $input->getOption('lines') ?? 20; $verbose = $input->getOption('verbose') ?? false; $io->title('Log Viewer'); $io->writeln(sprintf('viewing last %s entries in <white>%s</white>', $lines, $file)); $io->newLine(); $viewer = new LogViewer(); $grav = Grav::instance(); $logfile = $grav['locator']->findResource('log://' . $file); if (!$logfile) { $io->error('cannot find the log file: logs/' . $file); return 1; } $rows = $viewer->objectTail($logfile, $lines, true); foreach ($rows as $log) { $date = $log['date']; $level_color = LogViewer::levelColor($log['level']); if ($date instanceof DateTime) { $output = "<yellow>{$log['date']->format('Y-m-d h:i:s')}</yellow> [<{$level_color}>{$log['level']}</{$level_color}>]"; if ($log['trace'] && $verbose) { $output .= " <white>{$log['message']}</white>\n"; foreach ((array) $log['trace'] as $index => $tracerow) { $output .= "<white>{$index}</white>{$tracerow}\n"; } } else { $output .= " {$log['message']}"; } $io->writeln($output); } } return 0; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Cli/ServerCommand.php
system/src/Grav/Console/Cli/ServerCommand.php
<?php /** * @package Grav\Console\Cli * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Cli; use Grav\Common\Utils; use Grav\Console\GravCommand; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Process\PhpExecutableFinder; use Symfony\Component\Process\Process; /** * Class ServerCommand * @package Grav\Console\Cli */ class ServerCommand extends GravCommand { const SYMFONY_SERVER = 'Symfony Server'; const PHP_SERVER = 'Built-in PHP Server'; /** @var string */ protected $ip; /** @var int */ protected $port; /** * @return void */ protected function configure(): void { $this ->setName('server') ->addOption('port', 'p', InputOption::VALUE_OPTIONAL, 'Preferred HTTP port rather than auto-find (default is 8000-9000') ->addOption('symfony', null, InputOption::VALUE_NONE, 'Force using Symfony server') ->addOption('php', null, InputOption::VALUE_NONE, 'Force using built-in PHP server') ->setDescription("Runs built-in web-server, Symfony first, then tries PHP's") ->setHelp("Runs built-in web-server, Symfony first, then tries PHP's"); } /** * @return int */ protected function serve(): int { $input = $this->getInput(); $io = $this->getIO(); $io->title('Grav Web Server'); // Ensure CLI colors are on ini_set('cli_server.color', 'on'); // Options $force_symfony = $input->getOption('symfony'); $force_php = $input->getOption('php'); // Find PHP $executableFinder = new PhpExecutableFinder(); $php = $executableFinder->find(false); $this->ip = '127.0.0.1'; $this->port = (int)($input->getOption('port') ?? 8000); // Get an open port while (!$this->portAvailable($this->ip, $this->port)) { $this->port++; } // Setup the commands $symfony_cmd = ['symfony', 'server:start', '--ansi', '--port=' . $this->port]; $php_cmd = [$php, '-S', $this->ip.':'.$this->port, 'system/router.php']; $commands = [ self::SYMFONY_SERVER => $symfony_cmd, self::PHP_SERVER => $php_cmd ]; if ($force_symfony) { unset($commands[self::PHP_SERVER]); } elseif ($force_php) { unset($commands[self::SYMFONY_SERVER]); } $error = 0; foreach ($commands as $name => $command) { $process = $this->runProcess($name, $command); if (!$process) { $io->note('Starting ' . $name . '...'); } // Should only get here if there's an error running if (!$process->isRunning() && (($name === self::SYMFONY_SERVER && $force_symfony) || ($name === self::PHP_SERVER))) { $error = 1; $io->error('Could not start ' . $name); } } return $error; } /** * @param string $name * @param array $cmd * @return Process */ protected function runProcess(string $name, array $cmd): Process { $io = $this->getIO(); $process = new Process($cmd); $process->setTimeout(0); $process->start(); if ($name === self::SYMFONY_SERVER && Utils::contains($process->getErrorOutput(), 'symfony: not found')) { $io->error('The symfony binary could not be found, please install the CLI tools: https://symfony.com/download'); $io->warning('Falling back to PHP web server...'); } if ($name === self::PHP_SERVER) { $io->success('Built-in PHP web server listening on http://' . $this->ip . ':' . $this->port . ' (PHP v' . PHP_VERSION . ')'); } $process->wait(function ($type, $buffer) { $this->getIO()->write($buffer); }); return $process; } /** * Simple function test the port * * @param string $ip * @param int $port * @return bool */ protected function portAvailable(string $ip, int $port): bool { $fp = @fsockopen($ip, $port, $errno, $errstr, 0.1); if (!$fp) { return true; } fclose($fp); return false; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Cli/SecurityCommand.php
system/src/Grav/Console/Cli/SecurityCommand.php
<?php /** * @package Grav\Console\Cli * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Cli; use Grav\Common\Grav; use Grav\Common\Security; use Grav\Console\GravCommand; use Symfony\Component\Console\Helper\ProgressBar; use function count; /** * Class SecurityCommand * @package Grav\Console\Cli */ class SecurityCommand extends GravCommand { /** @var ProgressBar $progress */ protected $progress; /** * @return void */ protected function configure(): void { $this ->setName('security') ->setDescription('Capable of running various Security checks') ->setHelp('The <info>security</info> runs various security checks on your Grav site'); } /** * @return int */ protected function serve(): int { $this->initializePages(); $io = $this->getIO(); /** @var Grav $grav */ $grav = Grav::instance(); $this->progress = new ProgressBar($this->output, count($grav['pages']->routes()) - 1); $this->progress->setFormat('Scanning <cyan>%current%</cyan> pages [<green>%bar%</green>] <white>%percent:3s%%</white> %elapsed:6s%'); $this->progress->setBarWidth(100); $io->title('Grav Security Check'); $io->newline(2); $output = Security::detectXssFromPages($grav['pages'], false, [$this, 'outputProgress']); $error = 0; if (!empty($output)) { $counter = 1; foreach ($output as $route => $results) { $results_parts = array_map(static function ($value, $key) { return $key.': \''.$value . '\''; }, array_values($results), array_keys($results)); $io->writeln($counter++ .' - <cyan>' . $route . '</cyan> → <red>' . implode(', ', $results_parts) . '</red>'); } $error = 1; $io->error('Security Scan complete: ' . count($output) . ' potential XSS issues found...'); } else { $io->success('Security Scan complete: No issues found...'); } $io->newline(1); return $error; } /** * @param array $args * @return void */ public function outputProgress(array $args): void { switch ($args['type']) { case 'count': $steps = $args['steps']; $freq = (int)($steps > 100 ? round($steps / 100) : $steps); $this->progress->setMaxSteps($steps); $this->progress->setRedrawFrequency($freq); break; case 'progress': if (isset($args['complete']) && $args['complete']) { $this->progress->finish(); } else { $this->progress->advance(); } break; } } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Cli/NewProjectCommand.php
system/src/Grav/Console/Cli/NewProjectCommand.php
<?php /** * @package Grav\Console\Cli * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Cli; use Grav\Console\GravCommand; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; /** * Class NewProjectCommand * @package Grav\Console\Cli */ class NewProjectCommand extends GravCommand { /** * @return void */ protected function configure(): void { $this ->setName('new-project') ->setAliases(['newproject']) ->addArgument( 'destination', InputArgument::REQUIRED, 'The destination directory of your new Grav project' ) ->addOption( 'symlink', 's', InputOption::VALUE_NONE, 'Symlink the required bits' ) ->setDescription('Creates a new Grav project with all the dependencies installed') ->setHelp("The <info>new-project</info> command is a combination of the `setup` and `install` commands.\nCreates a new Grav instance and performs the installation of all the required dependencies."); } /** * @return int */ protected function serve(): int { $io = $this->getIO(); $sandboxCommand = $this->getApplication()->find('sandbox'); $installCommand = $this->getApplication()->find('install'); $sandboxArguments = new ArrayInput([ 'command' => 'sandbox', 'destination' => $this->input->getArgument('destination'), '-s' => $this->input->getOption('symlink') ]); $installArguments = new ArrayInput([ 'command' => 'install', 'destination' => $this->input->getArgument('destination'), '-s' => $this->input->getOption('symlink') ]); $error = $sandboxCommand->run($sandboxArguments, $io); if ($error === 0) { $error = $installCommand->run($installArguments, $io); } return $error; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Cli/SandboxCommand.php
system/src/Grav/Console/Cli/SandboxCommand.php
<?php /** * @package Grav\Console\Cli * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Cli; use Grav\Common\Filesystem\Folder; use Grav\Common\Utils; use Grav\Console\GravCommand; use RuntimeException; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use function count; /** * Class SandboxCommand * @package Grav\Console\Cli */ class SandboxCommand extends GravCommand { /** @var array */ protected $directories = [ '/assets', '/backup', '/cache', '/images', '/logs', '/tmp', '/user/accounts', '/user/config', '/user/data', '/user/pages', '/user/plugins', '/user/themes', ]; /** @var array */ protected $files = [ '/.dependencies', '/.htaccess', '/user/config/site.yaml', '/user/config/system.yaml', ]; /** @var array */ protected $mappings = [ '/.gitignore' => '/.gitignore', '/.editorconfig' => '/.editorconfig', '/CHANGELOG.md' => '/CHANGELOG.md', '/LICENSE.txt' => '/LICENSE.txt', '/README.md' => '/README.md', '/CONTRIBUTING.md' => '/CONTRIBUTING.md', '/index.php' => '/index.php', '/composer.json' => '/composer.json', '/bin' => '/bin', '/system' => '/system', '/vendor' => '/vendor', '/webserver-configs' => '/webserver-configs', ]; /** @var string */ protected $source; /** @var string */ protected $destination; /** * @return void */ protected function configure(): void { $this ->setName('sandbox') ->setDescription('Setup of a base Grav system in your webroot, good for development, playing around or starting fresh') ->addArgument( 'destination', InputArgument::REQUIRED, 'The destination directory to symlink into' ) ->addOption( 'symlink', 's', InputOption::VALUE_NONE, 'Symlink the base grav system' ) ->setHelp("The <info>sandbox</info> command help create a development environment that can optionally use symbolic links to link the core of grav to the git cloned repository.\nGood for development, playing around or starting fresh"); $source = getcwd(); if ($source === false) { throw new RuntimeException('Internal Error'); } $this->source = $source; } /** * @return int */ protected function serve(): int { $input = $this->getInput(); $this->destination = $input->getArgument('destination'); // Create Some core stuff if it doesn't exist $error = $this->createDirectories(); if ($error) { return $error; } // Copy files or create symlinks $error = $input->getOption('symlink') ? $this->symlink() : $this->copy(); if ($error) { return $error; } $error = $this->pages(); if ($error) { return $error; } $error = $this->initFiles(); if ($error) { return $error; } $error = $this->perms(); if ($error) { return $error; } return 0; } /** * @return int */ private function createDirectories(): int { $io = $this->getIO(); $io->newLine(); $io->writeln('<comment>Creating Directories</comment>'); $dirs_created = false; if (!file_exists($this->destination)) { Folder::create($this->destination); } foreach ($this->directories as $dir) { if (!file_exists($this->destination . $dir)) { $dirs_created = true; $io->writeln(' <cyan>' . $dir . '</cyan>'); Folder::create($this->destination . $dir); } } if (!$dirs_created) { $io->writeln(' <red>Directories already exist</red>'); } return 0; } /** * @return int */ private function copy(): int { $io = $this->getIO(); $io->newLine(); $io->writeln('<comment>Copying Files</comment>'); foreach ($this->mappings as $source => $target) { if ((string)(int)$source === (string)$source) { $source = $target; } $from = $this->source . $source; $to = $this->destination . $target; $io->writeln(' <cyan>' . $source . '</cyan> <comment>-></comment> ' . $to); @Folder::rcopy($from, $to); } return 0; } /** * @return int */ private function symlink(): int { $io = $this->getIO(); $io->newLine(); $io->writeln('<comment>Resetting Symbolic Links</comment>'); // Symlink also tests if using git. if (is_dir($this->source . '/tests')) { $this->mappings['/tests'] = '/tests'; } foreach ($this->mappings as $source => $target) { if ((string)(int)$source === (string)$source) { $source = $target; } $from = $this->source . $source; $to = $this->destination . $target; $io->writeln(' <cyan>' . $source . '</cyan> <comment>-></comment> ' . $to); if (is_dir($to)) { @Folder::delete($to); } else { @unlink($to); } symlink($from, $to); } return 0; } /** * @return int */ private function pages(): int { $io = $this->getIO(); $io->newLine(); $io->writeln('<comment>Pages Initializing</comment>'); // get pages files and initialize if no pages exist $pages_dir = $this->destination . '/user/pages'; $pages_files = array_diff(scandir($pages_dir), ['..', '.']); if (count($pages_files) === 0) { $destination = $this->source . '/user/pages'; Folder::rcopy($destination, $pages_dir); $io->writeln(' <cyan>' . $destination . '</cyan> <comment>-></comment> Created'); } return 0; } /** * @return int */ private function initFiles(): int { if (!$this->check()) { return 1; } $io = $this->getIO(); $io->newLine(); $io->writeln('<comment>File Initializing</comment>'); $files_init = false; // Copy files if they do not exist foreach ($this->files as $source => $target) { if ((string)(int)$source === (string)$source) { $source = $target; } $from = $this->source . $source; $to = $this->destination . $target; if (!file_exists($to)) { $files_init = true; copy($from, $to); $io->writeln(' <cyan>' . $target . '</cyan> <comment>-></comment> Created'); } } if (!$files_init) { $io->writeln(' <red>Files already exist</red>'); } return 0; } /** * @return int */ private function perms(): int { $io = $this->getIO(); $io->newLine(); $io->writeln('<comment>Permissions Initializing</comment>'); $dir_perms = 0755; $binaries = glob($this->destination . DS . 'bin' . DS . '*'); foreach ($binaries as $bin) { chmod($bin, $dir_perms); $io->writeln(' <cyan>bin/' . Utils::basename($bin) . '</cyan> permissions reset to ' . decoct($dir_perms)); } $io->newLine(); return 0; } /** * @return bool */ private function check(): bool { $success = true; $io = $this->getIO(); if (!file_exists($this->destination)) { $io->writeln(' file: <red>' . $this->destination . '</red> does not exist!'); $success = false; } foreach ($this->directories as $dir) { if (!file_exists($this->destination . $dir)) { $io->writeln(' directory: <red>' . $dir . '</red> does not exist!'); $success = false; } } foreach ($this->mappings as $target => $link) { if (!file_exists($this->destination . $target)) { $io->writeln(' mappings: <red>' . $target . '</red> does not exist!'); $success = false; } } if (!$success) { $io->newLine(); $io->writeln('<comment>install should be run with --symlink|--s to symlink first</comment>'); } return $success; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/Cli/PageSystemValidatorCommand.php
system/src/Grav/Console/Cli/PageSystemValidatorCommand.php
<?php /** * @package Grav\Console\Cli * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\Cli; use Grav\Common\Config\Config; use Grav\Common\File\CompiledYamlFile; use Grav\Common\Grav; use Grav\Common\Page\Interfaces\PageInterface; use Grav\Common\Page\Pages; use Grav\Console\GravCommand; use RocketTheme\Toolbox\Event\Event; use Symfony\Component\Console\Input\InputOption; use function in_array; use function is_object; /** * Class PageSystemValidatorCommand * @package Grav\Console\Cli */ class PageSystemValidatorCommand extends GravCommand { /** @var array */ protected $tests = [ // Content 'header' => [[]], 'summary' => [[], [200], [200, true]], 'content' => [[]], 'getRawContent' => [[]], 'rawMarkdown' => [[]], 'value' => [['content'], ['route'], ['order'], ['ordering'], ['folder'], ['slug'], ['name'], /*['frontmatter'],*/ ['header.menu'], ['header.slug']], 'title' => [[]], 'menu' => [[]], 'visible' => [[]], 'published' => [[]], 'publishDate' => [[]], 'unpublishDate' => [[]], 'process' => [[]], 'slug' => [[]], 'order' => [[]], //'id' => [[]], 'modified' => [[]], 'lastModified' => [[]], 'folder' => [[]], 'date' => [[]], 'dateformat' => [[]], 'taxonomy' => [[]], 'shouldProcess' => [['twig'], ['markdown']], 'isPage' => [[]], 'isDir' => [[]], 'exists' => [[]], // Forms 'forms' => [[]], // Routing 'urlExtension' => [[]], 'routable' => [[]], 'link' => [[], [false], [true]], 'permalink' => [[]], 'canonical' => [[], [false], [true]], 'url' => [[], [true], [true, true], [true, true, false], [false, false, true, false]], 'route' => [[]], 'rawRoute' => [[]], 'routeAliases' => [[]], 'routeCanonical' => [[]], 'redirect' => [[]], 'relativePagePath' => [[]], 'path' => [[]], //'folder' => [[]], 'parent' => [[]], 'topParent' => [[]], 'currentPosition' => [[]], 'active' => [[]], 'activeChild' => [[]], 'home' => [[]], 'root' => [[]], // Translations 'translatedLanguages' => [[], [false], [true]], 'untranslatedLanguages' => [[], [false], [true]], 'language' => [[]], // Legacy 'raw' => [[]], 'frontmatter' => [[]], 'httpResponseCode' => [[]], 'httpHeaders' => [[]], 'blueprintName' => [[]], 'name' => [[]], 'childType' => [[]], 'template' => [[]], 'templateFormat' => [[]], 'extension' => [[]], 'expires' => [[]], 'cacheControl' => [[]], 'ssl' => [[]], 'metadata' => [[]], 'eTag' => [[]], 'filePath' => [[]], 'filePathClean' => [[]], 'orderDir' => [[]], 'orderBy' => [[]], 'orderManual' => [[]], 'maxCount' => [[]], 'modular' => [[]], 'modularTwig' => [[]], //'children' => [[]], 'isFirst' => [[]], 'isLast' => [[]], 'prevSibling' => [[]], 'nextSibling' => [[]], 'adjacentSibling' => [[]], 'ancestor' => [[]], //'inherited' => [[]], //'inheritedField' => [[]], 'find' => [['/']], //'collection' => [[]], //'evaluate' => [[]], 'folderExists' => [[]], //'getOriginal' => [[]], //'getAction' => [[]], ]; /** @var Grav */ protected $grav; /** * @return void */ protected function configure(): void { $this ->setName('page-system-validator') ->setDescription('Page validator can be used to compare site before/after update and when migrating to Flex Pages.') ->addOption('record', 'r', InputOption::VALUE_NONE, 'Record results') ->addOption('check', 'c', InputOption::VALUE_NONE, 'Compare site against previously recorded results') ->setHelp('The <info>page-system-validator</info> command can be used to test the pages before and after upgrade'); } /** * @return int */ protected function serve(): int { $input = $this->getInput(); $io = $this->getIO(); $this->setLanguage('en'); $this->initializePages(); $io->newLine(); $this->grav = $grav = Grav::instance(); $grav->fireEvent('onPageInitialized', new Event(['page' => $grav['page']])); /** @var Config $config */ $config = $grav['config']; if ($input->getOption('record')) { $io->writeln('Pages: ' . $config->get('system.pages.type', 'page')); $io->writeln('<magenta>Record tests</magenta>'); $io->newLine(); $results = $this->record(); $file = $this->getFile('pages-old'); $file->save($results); $io->writeln('Recorded tests to ' . $file->filename()); } elseif ($input->getOption('check')) { $io->writeln('Pages: ' . $config->get('system.pages.type', 'page')); $io->writeln('<magenta>Run tests</magenta>'); $io->newLine(); $new = $this->record(); $file = $this->getFile('pages-new'); $file->save($new); $io->writeln('Recorded tests to ' . $file->filename()); $file = $this->getFile('pages-old'); $old = $file->content(); $results = $this->check($old, $new); $file = $this->getFile('diff'); $file->save($results); $io->writeln('Recorded results to ' . $file->filename()); } else { $io->writeln('<green>page-system-validator [-r|--record] [-c|--check]</green>'); } $io->newLine(); return 0; } /** * @return array */ private function record(): array { $io = $this->getIO(); /** @var Pages $pages */ $pages = $this->grav['pages']; $all = $pages->all(); $results = []; $results[''] = $this->recordRow($pages->root()); foreach ($all as $path => $page) { if (null === $page) { $io->writeln('<red>Error on page ' . $path . '</red>'); continue; } $results[$page->rawRoute()] = $this->recordRow($page); } return json_decode(json_encode($results), true); } /** * @param PageInterface $page * @return array */ private function recordRow(PageInterface $page): array { $results = []; foreach ($this->tests as $method => $params) { $params = $params ?: [[]]; foreach ($params as $p) { $result = $page->$method(...$p); if (in_array($method, ['summary', 'content', 'getRawContent'], true)) { $result = preg_replace('/name="(form-nonce|__unique_form_id__)" value="[^"]+"/', 'name="\\1" value="DYNAMIC"', $result); $result = preg_replace('`src=("|\'|&quot;)/images/./././././[^"]+\\1`', 'src="\\1images/GENERATED\\1', $result); $result = preg_replace('/\?\d{10}/', '?1234567890', $result); } elseif ($method === 'httpHeaders' && isset($result['Expires'])) { $result['Expires'] = 'Thu, 19 Sep 2019 13:10:24 GMT (REPLACED AS DYNAMIC)'; } elseif ($result instanceof PageInterface) { $result = $result->rawRoute(); } elseif (is_object($result)) { $result = json_decode(json_encode($result), true); } $ps = []; foreach ($p as $val) { $ps[] = (string)var_export($val, true); } $pstr = implode(', ', $ps); $call = "->{$method}({$pstr})"; $results[$call] = $result; } } return $results; } /** * @param array $old * @param array $new * @return array */ private function check(array $old, array $new): array { $errors = []; foreach ($old as $path => $page) { if (!isset($new[$path])) { $errors[$path] = 'PAGE REMOVED'; continue; } foreach ($page as $method => $test) { if (($new[$path][$method] ?? null) !== $test) { $errors[$path][$method] = ['old' => $test, 'new' => $new[$path][$method]]; } } } return $errors; } /** * @param string $name * @return CompiledYamlFile */ private function getFile(string $name): CompiledYamlFile { return CompiledYamlFile::instance('cache://tests/' . $name . '.yaml'); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Console/TerminalObjects/Table.php
system/src/Grav/Console/TerminalObjects/Table.php
<?php /** * @package Grav\Console\TerminalObjects * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Console\TerminalObjects; /** * Class Table * @package Grav\Console\TerminalObjects * @deprecated 1.7 Use Symfony Console Table */ class Table extends \League\CLImate\TerminalObject\Basic\Table { /** * @return array */ public function result() { $this->column_widths = $this->getColumnWidths(); $this->table_width = $this->getWidth(); $this->border = $this->getBorder(); $this->buildHeaderRow(); foreach ($this->data as $key => $columns) { $this->rows[] = $this->buildRow($columns); } $this->rows[] = $this->border; return $this->rows; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Mime/MimeTypes.php
system/src/Grav/Framework/Mime/MimeTypes.php
<?php declare(strict_types=1); /** * @package Grav\Framework\Mime * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Mime; use function in_array; /** * Class to handle mime-types. */ class MimeTypes { /** @var array */ protected $extensions; /** @var array */ protected $mimes; /** * Create a new mime types instance with the given mappings. * * @param array $mimes An associative array containing ['ext' => ['mime/type', 'mime/type2']] */ public static function createFromMimes(array $mimes): self { $extensions = []; foreach ($mimes as $ext => $list) { foreach ($list as $mime) { $list = $extensions[$mime] ?? []; if (!in_array($ext, $list, true)) { $list[] = $ext; $extensions[$mime] = $list; } } } return new static($extensions, $mimes); } /** * @param string $extension * @return string|null */ public function getMimeType(string $extension): ?string { $extension = $this->cleanInput($extension); return $this->mimes[$extension][0] ?? null; } /** * @param string $mime * @return string|null */ public function getExtension(string $mime): ?string { $mime = $this->cleanInput($mime); return $this->extensions[$mime][0] ?? null; } /** * @param string $extension * @return array */ public function getMimeTypes(string $extension): array { $extension = $this->cleanInput($extension); return $this->mimes[$extension] ?? []; } /** * @param string $mime * @return array */ public function getExtensions(string $mime): array { $mime = $this->cleanInput($mime); return $this->extensions[$mime] ?? []; } /** * @param string $input * @return string */ protected function cleanInput(string $input): string { return strtolower(trim($input)); } /** * @param array $extensions * @param array $mimes */ protected function __construct(array $extensions, array $mimes) { $this->extensions = $extensions; $this->mimes = $mimes; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Interfaces/RenderInterface.php
system/src/Grav/Framework/Interfaces/RenderInterface.php
<?php declare(strict_types=1); /** * @package Grav\Framework\Interfaces * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Interfaces; use Grav\Framework\ContentBlock\ContentBlockInterface; use Grav\Framework\ContentBlock\HtmlBlock; /** * Defines common interface to render any object. * * @used-by \Grav\Framework\Flex\FlexObject * @since 1.6 */ interface RenderInterface { /** * Renders the object. * * @example $block = $object->render('custom', ['variable' => 'value']); * @example {% render object layout 'custom' with { variable: 'value' } %} * * @param string|null $layout Layout to be used. * @param array $context Extra context given to the renderer. * * @return ContentBlockInterface|HtmlBlock Returns `HtmlBlock` containing the rendered output. * @api */ public function render(string $layout = null, array $context = []); }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Controller/Traits/ControllerResponseTrait.php
system/src/Grav/Framework/Controller/Traits/ControllerResponseTrait.php
<?php /** * @package Grav\Framework\Controller * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ declare(strict_types=1); namespace Grav\Framework\Controller\Traits; use Grav\Common\Config\Config; use Grav\Common\Data\ValidationException; use Grav\Common\Debugger; use Grav\Common\Grav; use Grav\Common\Utils; use Grav\Framework\Psr7\Response; use Grav\Framework\RequestHandler\Exception\RequestException; use Grav\Framework\Route\Route; use JsonSerializable; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\StreamInterface; use Throwable; use function get_class; use function in_array; /** * Trait ControllerResponseTrait * @package Grav\Framework\Controller\Traits */ trait ControllerResponseTrait { /** * Display the current page. * * @return Response */ protected function createDisplayResponse(): ResponseInterface { return new Response(418); } /** * @param string $content * @param int|null $code * @param array|null $headers * @return Response */ protected function createHtmlResponse(string $content, int $code = null, array $headers = null): ResponseInterface { $code = $code ?? 200; if ($code < 100 || $code > 599) { $code = 500; } $headers = $headers ?? []; return new Response($code, $headers, $content); } /** * @param array $content * @param int|null $code * @param array|null $headers * @return Response */ protected function createJsonResponse(array $content, int $code = null, array $headers = null): ResponseInterface { $code = $code ?? $content['code'] ?? 200; if (null === $code || $code < 100 || $code > 599) { $code = 200; } $headers = ($headers ?? []) + [ 'Content-Type' => 'application/json', 'Cache-Control' => 'no-store, max-age=0' ]; return new Response($code, $headers, json_encode($content)); } /** * @param string $filename * @param string|resource|StreamInterface $resource * @param array|null $headers * @param array|null $options * @return ResponseInterface */ protected function createDownloadResponse(string $filename, $resource, array $headers = null, array $options = null): ResponseInterface { // Required for IE, otherwise Content-Disposition may be ignored if (ini_get('zlib.output_compression')) { @ini_set('zlib.output_compression', 'Off'); } $headers = $headers ?? []; $options = $options ?? ['force_download' => true]; $file_parts = Utils::pathinfo($filename); if (!isset($headers['Content-Type'])) { $mimetype = Utils::getMimeByExtension($file_parts['extension']); $headers['Content-Type'] = $mimetype; } // TODO: add multipart download support. //$headers['Accept-Ranges'] = 'bytes'; if (!empty($options['force_download'])) { $headers['Content-Disposition'] = 'attachment; filename="' . $file_parts['basename'] . '"'; } if (!isset($headers['Content-Length'])) { $realpath = realpath($filename); if ($realpath) { $headers['Content-Length'] = filesize($realpath); } } $headers += [ 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT', 'Last-Modified' => gmdate('D, d M Y H:i:s') . ' GMT', 'Cache-Control' => 'no-store, no-cache, must-revalidate', 'Pragma' => 'no-cache' ]; return new Response(200, $headers, $resource); } /** * @param string $url * @param int|null $code * @return Response */ protected function createRedirectResponse(string $url, int $code = null): ResponseInterface { if (null === $code || $code < 301 || $code > 307) { $code = (int)$this->getConfig()->get('system.pages.redirect_default_code', 302); } $ext = Utils::pathinfo($url, PATHINFO_EXTENSION); $accept = $this->getAccept(['application/json', 'text/html']); if ($ext === 'json' || $accept === 'application/json') { return $this->createJsonResponse(['code' => $code, 'status' => 'redirect', 'redirect' => $url]); } return new Response($code, ['Location' => $url]); } /** * @param Throwable $e * @return ResponseInterface */ protected function createErrorResponse(Throwable $e): ResponseInterface { $response = $this->getErrorJson($e); $message = $response['message']; $code = $response['code']; $reason = $e instanceof RequestException ? $e->getHttpReason() : null; $accept = $this->getAccept(['application/json', 'text/html']); $request = $this->getRequest(); $context = $request->getAttributes(); /** @var Route $route */ $route = $context['route'] ?? null; $ext = $route ? $route->getExtension() : null; if ($ext !== 'json' && $accept === 'text/html') { $method = $request->getMethod(); // On POST etc, redirect back to the previous page. if ($method !== 'GET' && $method !== 'HEAD') { $this->setMessage($message, 'error'); $referer = $request->getHeaderLine('Referer'); return $this->createRedirectResponse($referer, 303); } // TODO: improve error page return $this->createHtmlResponse($response['message'], $code); } return new Response($code, ['Content-Type' => 'application/json'], json_encode($response), '1.1', $reason); } /** * @param Throwable $e * @return ResponseInterface */ protected function createJsonErrorResponse(Throwable $e): ResponseInterface { $response = $this->getErrorJson($e); $reason = $e instanceof RequestException ? $e->getHttpReason() : null; return new Response($response['code'], ['Content-Type' => 'application/json'], json_encode($response), '1.1', $reason); } /** * @param Throwable $e * @return array */ protected function getErrorJson(Throwable $e): array { $code = $this->getErrorCode($e instanceof RequestException ? $e->getHttpCode() : $e->getCode()); if ($e instanceof ValidationException) { $message = $e->getMessage(); } else { $message = htmlspecialchars($e->getMessage(), ENT_QUOTES | ENT_HTML5, 'UTF-8'); } $extra = $e instanceof JsonSerializable ? $e->jsonSerialize() : []; $response = [ 'code' => $code, 'status' => 'error', 'message' => $message, 'redirect' => null, 'error' => [ 'code' => $code, 'message' => $message ] + $extra ]; /** @var Debugger $debugger */ $debugger = Grav::instance()['debugger']; if ($debugger->enabled()) { $response['error'] += [ 'type' => get_class($e), 'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => explode("\n", $e->getTraceAsString()) ]; } return $response; } /** * @param int $code * @return int */ protected function getErrorCode(int $code): int { static $errorCodes = [ 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 422, 423, 424, 425, 426, 428, 429, 431, 451, 500, 501, 502, 503, 504, 505, 506, 507, 508, 511 ]; if (!in_array($code, $errorCodes, true)) { $code = 500; } return $code; } /** * @param array $compare * @return mixed */ protected function getAccept(array $compare) { $accepted = []; foreach ($this->getRequest()->getHeader('Accept') as $accept) { foreach (explode(',', $accept) as $item) { if (!$item) { continue; } $split = explode(';q=', $item); $mime = array_shift($split); $priority = array_shift($split) ?? 1.0; $accepted[$mime] = $priority; } } arsort($accepted); // TODO: add support for image/* etc $list = array_intersect($compare, array_keys($accepted)); if (!$list && (isset($accepted['*/*']) || isset($accepted['*']))) { return reset($compare); } return reset($list); } /** * @return ServerRequestInterface */ abstract protected function getRequest(): ServerRequestInterface; /** * @param string $message * @param string $type * @return $this */ abstract protected function setMessage(string $message, string $type = 'info'); /** * @return Config */ abstract protected function getConfig(): Config; }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/ArrayObject.php
system/src/Grav/Framework/Object/ArrayObject.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object; use ArrayAccess; use Grav\Framework\Object\Access\NestedArrayAccessTrait; use Grav\Framework\Object\Access\NestedPropertyTrait; use Grav\Framework\Object\Access\OverloadedPropertyTrait; use Grav\Framework\Object\Base\ObjectTrait; use Grav\Framework\Object\Interfaces\NestedObjectInterface; use Grav\Framework\Object\Property\ArrayPropertyTrait; /** * Array Objects keep the data in private array property. * @implements ArrayAccess<string,mixed> */ class ArrayObject implements NestedObjectInterface, ArrayAccess { use ObjectTrait; use ArrayPropertyTrait; use NestedPropertyTrait; use OverloadedPropertyTrait; use NestedArrayAccessTrait; }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/ObjectIndex.php
system/src/Grav/Framework/Object/ObjectIndex.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object; use Doctrine\Common\Collections\Criteria; use Grav\Framework\Collection\AbstractIndexCollection; use Grav\Framework\Object\Interfaces\NestedObjectCollectionInterface; use Grav\Framework\Object\Interfaces\ObjectCollectionInterface; use function get_class; use function is_object; /** * Keeps index of objects instead of collection of objects. This class allows you to keep a list of objects and load * them on demand. The class can be used seemingly instead of ObjectCollection when the objects haven't been loaded yet. * * This is an abstract class and has some protected abstract methods to load objects which you need to implement in * order to use the class. * * @template TKey of array-key * @template T of \Grav\Framework\Object\Interfaces\ObjectInterface * @template C of ObjectCollectionInterface * @extends AbstractIndexCollection<TKey,T,C> * @implements NestedObjectCollectionInterface<TKey,T> */ abstract class ObjectIndex extends AbstractIndexCollection implements NestedObjectCollectionInterface { /** @var string */ protected static $type; /** @var string */ protected $_key; /** * @param bool $prefix * @return string */ public function getType($prefix = true) { $type = $prefix ? $this->getTypePrefix() : ''; if (static::$type) { return $type . static::$type; } $class = get_class($this); return $type . strtolower(substr($class, strrpos($class, '\\') + 1)); } /** * @return string */ public function getKey() { return $this->_key ?: $this->getType() . '@@' . spl_object_hash($this); } /** * @param string $key * @return $this */ public function setKey($key) { $this->_key = $key; return $this; } /** * @param string $property Object property name. * @return bool[] True if property has been defined (can be null). */ public function hasProperty($property) { return $this->__call('hasProperty', [$property]); } /** * @param string $property Object property to be fetched. * @param mixed $default Default value if property has not been set. * @return mixed[] Property values. */ public function getProperty($property, $default = null) { return $this->__call('getProperty', [$property, $default]); } /** * @param string $property Object property to be updated. * @param string $value New value. * @return ObjectCollectionInterface * @phpstan-return C */ public function setProperty($property, $value) { return $this->__call('setProperty', [$property, $value]); } /** * @param string $property Object property to be defined. * @param mixed $default Default value. * @return ObjectCollectionInterface * @phpstan-return C */ public function defProperty($property, $default) { return $this->__call('defProperty', [$property, $default]); } /** * @param string $property Object property to be unset. * @return ObjectCollectionInterface * @phpstan-return C */ public function unsetProperty($property) { return $this->__call('unsetProperty', [$property]); } /** * @param string $property Object property name. * @param string|null $separator Separator, defaults to '.' * @return bool[] True if property has been defined (can be null). */ public function hasNestedProperty($property, $separator = null) { return $this->__call('hasNestedProperty', [$property, $separator]); } /** * @param string $property Object property to be fetched. * @param mixed $default Default value if property has not been set. * @param string|null $separator Separator, defaults to '.' * @return mixed[] Property values. */ public function getNestedProperty($property, $default = null, $separator = null) { return $this->__call('getNestedProperty', [$property, $default, $separator]); } /** * @param string $property Object property to be updated. * @param mixed $value New value. * @param string|null $separator Separator, defaults to '.' * @return ObjectCollectionInterface * @phpstan-return C */ public function setNestedProperty($property, $value, $separator = null) { return $this->__call('setNestedProperty', [$property, $value, $separator]); } /** * @param string $property Object property to be defined. * @param mixed $default Default value. * @param string|null $separator Separator, defaults to '.' * @return ObjectCollectionInterface * @phpstan-return C */ public function defNestedProperty($property, $default, $separator = null) { return $this->__call('defNestedProperty', [$property, $default, $separator]); } /** * @param string $property Object property to be unset. * @param string|null $separator Separator, defaults to '.' * @return ObjectCollectionInterface * @phpstan-return C */ public function unsetNestedProperty($property, $separator = null) { return $this->__call('unsetNestedProperty', [$property, $separator]); } /** * Create a copy from this collection by cloning all objects in the collection. * * @return static * @return static<TKey,T,C> */ public function copy() { $list = []; foreach ($this->getIterator() as $key => $value) { /** @phpstan-ignore-next-line */ $list[$key] = is_object($value) ? clone $value : $value; } /** @phpstan-var static<TKey,T,C> */ return $this->createFrom($list); } /** * @return array */ public function getObjectKeys() { return $this->getKeys(); } /** * @param array $ordering * @return ObjectCollectionInterface * @phpstan-return C */ public function orderBy(array $ordering) { return $this->__call('orderBy', [$ordering]); } /** * @param string $method * @param array $arguments * @return array|mixed */ public function call($method, array $arguments = []) { return $this->__call('call', [$method, $arguments]); } /** * Group items in the collection by a field and return them as associated array. * * @param string $property * @return array */ public function group($property) { return $this->__call('group', [$property]); } /** * Group items in the collection by a field and return them as associated array of collections. * * @param string $property * @return ObjectCollectionInterface[] * @phpstan-return C[] */ public function collectionGroup($property) { return $this->__call('collectionGroup', [$property]); } /** * @param Criteria $criteria * @return ObjectCollectionInterface * @phpstan-return C */ public function matching(Criteria $criteria) { $collection = $this->loadCollection($this->getEntries()); /** @phpstan-var C $matching */ $matching = $collection->matching($criteria); return $matching; } /** * @param string $name * @param array $arguments * @return mixed */ #[\ReturnTypeWillChange] abstract public function __call($name, $arguments); /** * @return string */ protected function getTypePrefix() { return ''; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/ObjectCollection.php
system/src/Grav/Framework/Object/ObjectCollection.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object; use Doctrine\Common\Collections\Criteria; use Grav\Framework\Collection\ArrayCollection; use Grav\Framework\Object\Access\NestedPropertyCollectionTrait; use Grav\Framework\Object\Base\ObjectCollectionTrait; use Grav\Framework\Object\Collection\ObjectExpressionVisitor; use Grav\Framework\Object\Interfaces\NestedObjectCollectionInterface; use InvalidArgumentException; use function array_slice; /** * Class contains a collection of objects. * * @template TKey of array-key * @template T of \Grav\Framework\Object\Interfaces\ObjectInterface * @extends ArrayCollection<TKey,T> * @implements NestedObjectCollectionInterface<TKey,T> */ class ObjectCollection extends ArrayCollection implements NestedObjectCollectionInterface { /** @phpstan-use ObjectCollectionTrait<TKey,T> */ use ObjectCollectionTrait; use NestedPropertyCollectionTrait { NestedPropertyCollectionTrait::group insteadof ObjectCollectionTrait; } /** * @param array $elements * @param string|null $key * @throws InvalidArgumentException */ public function __construct(array $elements = [], $key = null) { parent::__construct($this->setElements($elements)); $this->setKey($key ?? ''); } /** * @param array $ordering * @return static * @phpstan-return static<TKey,T> */ public function orderBy(array $ordering) { $criteria = Criteria::create()->orderBy($ordering); return $this->matching($criteria); } /** * @param int $start * @param int|null $limit * @return static * @phpstan-return static<TKey,T> */ public function limit($start, $limit = null) { /** @phpstan-var static<TKey,T> */ return $this->createFrom($this->slice($start, $limit)); } /** * @param Criteria $criteria * @return static * @phpstan-return static<TKey,T> */ public function matching(Criteria $criteria) { $expr = $criteria->getWhereExpression(); $filtered = $this->getElements(); if ($expr) { $visitor = new ObjectExpressionVisitor(); $filter = $visitor->dispatch($expr); $filtered = array_filter($filtered, $filter); } if ($orderings = $criteria->getOrderings()) { $next = null; foreach (array_reverse($orderings) as $field => $ordering) { $next = ObjectExpressionVisitor::sortByField($field, $ordering === Criteria::DESC ? -1 : 1, $next); } /** @phpstan-ignore-next-line */ if ($next) { uasort($filtered, $next); } } $offset = $criteria->getFirstResult(); $length = $criteria->getMaxResults(); if ($offset || $length) { $filtered = array_slice($filtered, (int)$offset, $length); } /** @phpstan-var static<TKey,T> */ return $this->createFrom($filtered); } /** * @return array * @phpstan-return array<TKey,T> */ protected function getElements() { return $this->toArray(); } /** * @param array $elements * @return array * @phpstan-return array<TKey,T> */ protected function setElements(array $elements) { /** @phpstan-var array<TKey,T> $elements */ return $elements; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/LazyObject.php
system/src/Grav/Framework/Object/LazyObject.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object; use ArrayAccess; use Grav\Framework\Object\Access\NestedArrayAccessTrait; use Grav\Framework\Object\Access\NestedPropertyTrait; use Grav\Framework\Object\Access\OverloadedPropertyTrait; use Grav\Framework\Object\Base\ObjectTrait; use Grav\Framework\Object\Interfaces\NestedObjectInterface; use Grav\Framework\Object\Property\LazyPropertyTrait; /** * Lazy Objects keep their data in both protected object properties and falls back to a stored array if property does * not exist or is not initialized. * * @package Grav\Framework\Object * @implements ArrayAccess<string,mixed> */ class LazyObject implements NestedObjectInterface, ArrayAccess { use ObjectTrait; use LazyPropertyTrait; use NestedPropertyTrait; use OverloadedPropertyTrait; use NestedArrayAccessTrait; }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/PropertyObject.php
system/src/Grav/Framework/Object/PropertyObject.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object; use ArrayAccess; use Grav\Framework\Object\Access\NestedArrayAccessTrait; use Grav\Framework\Object\Access\NestedPropertyTrait; use Grav\Framework\Object\Access\OverloadedPropertyTrait; use Grav\Framework\Object\Base\ObjectTrait; use Grav\Framework\Object\Interfaces\NestedObjectInterface; use Grav\Framework\Object\Property\ObjectPropertyTrait; /** * Property Objects keep their data in protected object properties. * * @implements ArrayAccess<string,mixed> */ class PropertyObject implements NestedObjectInterface, ArrayAccess { use ObjectTrait; use ObjectPropertyTrait; use NestedPropertyTrait; use OverloadedPropertyTrait; use NestedArrayAccessTrait; }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/Interfaces/NestedObjectCollectionInterface.php
system/src/Grav/Framework/Object/Interfaces/NestedObjectCollectionInterface.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object\Interfaces; use RuntimeException; /** * Common Interface for both Objects and Collections * @package Grav\Framework\Object * * @template TKey of array-key * @template T * @extends ObjectCollectionInterface<TKey,T> */ interface NestedObjectCollectionInterface extends ObjectCollectionInterface { /** * @param string $property Object property name. * @param string|null $separator Separator, defaults to '.' * @return bool[] List of [key => bool] pairs. */ public function hasNestedProperty($property, $separator = null); /** * @param string $property Object property to be fetched. * @param mixed|null $default Default value if property has not been set. * @param string|null $separator Separator, defaults to '.' * @return mixed[] List of [key => value] pairs. */ public function getNestedProperty($property, $default = null, $separator = null); /** * @param string $property Object property to be updated. * @param mixed $value New value. * @param string|null $separator Separator, defaults to '.' * @return $this * @throws RuntimeException */ public function setNestedProperty($property, $value, $separator = null); /** * @param string $property Object property to be defined. * @param mixed $default Default value. * @param string|null $separator Separator, defaults to '.' * @return $this * @throws RuntimeException */ public function defNestedProperty($property, $default, $separator = null); /** * @param string $property Object property to be unset. * @param string|null $separator Separator, defaults to '.' * @return $this * @throws RuntimeException */ public function unsetNestedProperty($property, $separator = null); }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/Interfaces/ObjectInterface.php
system/src/Grav/Framework/Object/Interfaces/ObjectInterface.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object\Interfaces; use JsonSerializable; use Serializable; /** * Object Interface * @package Grav\Framework\Object */ interface ObjectInterface extends Serializable, JsonSerializable { /** * @return string */ public function getType(); /** * @return string */ public function getKey(); /** * @param string $property Object property name. * @return bool True if property has been defined (property can be null). */ public function hasProperty($property); /** * @param string $property Object property to be fetched. * @param mixed|null $default Default value if property has not been set. * @return mixed Property value. */ public function getProperty($property, $default = null); /** * @param string $property Object property to be updated. * @param mixed $value New value. * @return $this */ public function setProperty($property, $value); /** * @param string $property Object property to be defined. * @param mixed $default Default value. * @return $this */ public function defProperty($property, $default); /** * @param string $property Object property to be unset. * @return $this */ public function unsetProperty($property); }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/Interfaces/NestedObjectInterface.php
system/src/Grav/Framework/Object/Interfaces/NestedObjectInterface.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object\Interfaces; use RuntimeException; /** * Common Interface for both Objects and Collections * @package Grav\Framework\Object */ interface NestedObjectInterface extends ObjectInterface { /** * @param string $property Object property name. * @param string|null $separator Separator, defaults to '.' * @return bool|bool[] True if property has been defined (can be null). */ public function hasNestedProperty($property, $separator = null); /** * @param string $property Object property to be fetched. * @param mixed|null $default Default value if property has not been set. * @param string|null $separator Separator, defaults to '.' * @return mixed|mixed[] Property value. */ public function getNestedProperty($property, $default = null, $separator = null); /** * @param string $property Object property to be updated. * @param mixed $value New value. * @param string|null $separator Separator, defaults to '.' * @return $this * @throws RuntimeException */ public function setNestedProperty($property, $value, $separator = null); /** * @param string $property Object property to be defined. * @param mixed $default Default value. * @param string|null $separator Separator, defaults to '.' * @return $this * @throws RuntimeException */ public function defNestedProperty($property, $default, $separator = null); /** * @param string $property Object property to be unset. * @param string|null $separator Separator, defaults to '.' * @return $this * @throws RuntimeException */ public function unsetNestedProperty($property, $separator = null); }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/Interfaces/ObjectCollectionInterface.php
system/src/Grav/Framework/Object/Interfaces/ObjectCollectionInterface.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object\Interfaces; use Doctrine\Common\Collections\Selectable; use Grav\Framework\Collection\CollectionInterface; use Serializable; /** * ObjectCollection Interface * @package Grav\Framework\Collection * @template TKey of array-key * @template T * @extends CollectionInterface<TKey,T> * @extends Selectable<TKey,T> */ interface ObjectCollectionInterface extends CollectionInterface, Selectable, Serializable { /** * @return string */ public function getType(); /** * @return string */ public function getKey(); /** * @param string $key * @return $this */ public function setKey($key); /** * @param string $property Object property name. * @return bool[] List of [key => bool] pairs. */ public function hasProperty($property); /** * @param string $property Object property to be fetched. * @param mixed|null $default Default value if property has not been set. * @return mixed[] List of [key => value] pairs. */ public function getProperty($property, $default = null); /** * @param string $property Object property to be updated. * @param mixed $value New value. * @return $this */ public function setProperty($property, $value); /** * @param string $property Object property to be defined. * @param mixed $default Default value. * @return $this */ public function defProperty($property, $default); /** * @param string $property Object property to be unset. * @return $this */ public function unsetProperty($property); /** * Create a copy from this collection by cloning all objects in the collection. * * @return static * @phpstan-return static<TKey,T> */ public function copy(); /** * @return array */ public function getObjectKeys(); /** * @param string $name Method name. * @param array $arguments List of arguments passed to the function. * @return array Return values. */ public function call($name, array $arguments = []); /** * Group items in the collection by a field and return them as associated array. * * @param string $property * @return array */ public function group($property); /** * Group items in the collection by a field and return them as associated array of collections. * * @param string $property * @return static[] * @phpstan-return array<static<TKey,T>> */ public function collectionGroup($property); /** * @param array $ordering * @return ObjectCollectionInterface * @phpstan-return static<TKey,T> */ public function orderBy(array $ordering); /** * @param int $start * @param int|null $limit * @return ObjectCollectionInterface * @phpstan-return static<TKey,T> */ public function limit($start, $limit = null); }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/Base/ObjectCollectionTrait.php
system/src/Grav/Framework/Object/Base/ObjectCollectionTrait.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object\Base; use Grav\Framework\Compat\Serializable; use Grav\Framework\Object\Interfaces\ObjectInterface; use InvalidArgumentException; use function call_user_func_array; use function get_class; use function is_callable; use function is_object; /** * ObjectCollection Trait * @package Grav\Framework\Object * * @template TKey as array-key * @template T as ObjectInterface */ trait ObjectCollectionTrait { use Serializable; /** @var string */ protected static $type; /** @var string */ private $_key; /** * @return string */ protected function getTypePrefix() { return ''; } /** * @param bool $prefix * @return string */ public function getType($prefix = true) { $type = $prefix ? $this->getTypePrefix() : ''; if (static::$type) { return $type . static::$type; } $class = get_class($this); return $type . strtolower(substr($class, strrpos($class, '\\') + 1)); } /** * @return string */ public function getKey() { return $this->_key ?: $this->getType() . '@@' . spl_object_hash($this); } /** * @return bool */ public function hasKey() { return !empty($this->_key); } /** * @param string $property Object property name. * @return bool[] True if property has been defined (can be null). */ public function hasProperty($property) { return $this->doHasProperty($property); } /** * @param string $property Object property to be fetched. * @param mixed $default Default value if property has not been set. * @return mixed[] Property values. */ public function getProperty($property, $default = null) { return $this->doGetProperty($property, $default); } /** * @param string $property Object property to be updated. * @param mixed $value New value. * @return $this */ public function setProperty($property, $value) { $this->doSetProperty($property, $value); return $this; } /** * @param string $property Object property to be unset. * @return $this */ public function unsetProperty($property) { $this->doUnsetProperty($property); return $this; } /** * @param string $property Object property to be defined. * @param mixed $default Default value. * @return $this */ public function defProperty($property, $default) { if (!$this->hasProperty($property)) { $this->setProperty($property, $default); } return $this; } /** * @return array */ final public function __serialize(): array { return $this->doSerialize(); } /** * @param array $data * @return void */ final public function __unserialize(array $data): void { if (method_exists($this, 'initObjectProperties')) { $this->initObjectProperties(); } $this->doUnserialize($data); } /** * @return array */ protected function doSerialize() { return [ 'key' => $this->getKey(), 'type' => $this->getType(), 'elements' => $this->getElements() ]; } /** * @param array $data * @return void */ protected function doUnserialize(array $data) { if (!isset($data['key'], $data['type'], $data['elements']) || $data['type'] !== $this->getType()) { throw new InvalidArgumentException("Cannot unserialize '{$this->getType()}': Bad data"); } $this->setKey($data['key']); $this->setElements($data['elements']); } /** * Implements JsonSerializable interface. * * @return array */ #[\ReturnTypeWillChange] public function jsonSerialize() { return $this->doSerialize(); } /** * Returns a string representation of this object. * * @return string */ #[\ReturnTypeWillChange] public function __toString() { return $this->getKey(); } /** * @param string $key * @return $this */ public function setKey($key) { $this->_key = (string) $key; return $this; } /** * Create a copy from this collection by cloning all objects in the collection. * * @return static<TKey,T> */ public function copy() { $list = []; foreach ($this->getIterator() as $key => $value) { /** @phpstan-ignore-next-line */ $list[$key] = is_object($value) ? clone $value : $value; } /** @phpstan-var static<TKey,T> */ return $this->createFrom($list); } /** * @return string[] */ public function getObjectKeys() { return $this->call('getKey'); } /** * @param string $property Object property to be matched. * @return bool[] Key/Value pairs of the properties. */ public function doHasProperty($property) { $list = []; /** @var ObjectInterface $element */ foreach ($this->getIterator() as $id => $element) { $list[$id] = (bool)$element->hasProperty($property); } return $list; } /** * @param string $property Object property to be fetched. * @param mixed $default Default value if not set. * @param bool $doCreate Not being used. * @return mixed[] Key/Value pairs of the properties. */ public function &doGetProperty($property, $default = null, $doCreate = false) { $list = []; /** @var ObjectInterface $element */ foreach ($this->getIterator() as $id => $element) { $list[$id] = $element->getProperty($property, $default); } return $list; } /** * @param string $property Object property to be updated. * @param mixed $value New value. * @return $this */ public function doSetProperty($property, $value) { /** @var ObjectInterface $element */ foreach ($this->getIterator() as $element) { $element->setProperty($property, $value); } return $this; } /** * @param string $property Object property to be updated. * @return $this */ public function doUnsetProperty($property) { /** @var ObjectInterface $element */ foreach ($this->getIterator() as $element) { $element->unsetProperty($property); } return $this; } /** * @param string $property Object property to be updated. * @param mixed $default Default value. * @return $this */ public function doDefProperty($property, $default) { /** @var ObjectInterface $element */ foreach ($this->getIterator() as $element) { $element->defProperty($property, $default); } return $this; } /** * @param string $method Method name. * @param array $arguments List of arguments passed to the function. * @return mixed[] Return values. */ public function call($method, array $arguments = []) { $list = []; /** * @var string|int $id * @var ObjectInterface $element */ foreach ($this->getIterator() as $id => $element) { $callable = [$element, $method]; $list[$id] = is_callable($callable) ? call_user_func_array($callable, $arguments) : null; } return $list; } /** * Group items in the collection by a field and return them as associated array. * * @param string $property * @return array * @phpstan-return array<TKey,T> */ public function group($property) { $list = []; /** @var ObjectInterface $element */ foreach ($this->getIterator() as $element) { $list[(string) $element->getProperty($property)][] = $element; } return $list; } /** * Group items in the collection by a field and return them as associated array of collections. * * @param string $property * @return static[] * @phpstan-return array<static<TKey,T>> */ public function collectionGroup($property) { $collections = []; foreach ($this->group($property) as $id => $elements) { /** @phpstan-var static<TKey,T> $collection */ $collection = $this->createFrom($elements); $collections[$id] = $collection; } return $collections; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/Base/ObjectTrait.php
system/src/Grav/Framework/Object/Base/ObjectTrait.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object\Base; use Grav\Framework\Compat\Serializable; use InvalidArgumentException; use function get_class; /** * Object trait. * * @package Grav\Framework\Object */ trait ObjectTrait { use Serializable; /** @var string */ protected static $type; /** @var string */ private $_key; /** * @return string */ protected function getTypePrefix() { return ''; } /** * @param bool $prefix * @return string */ public function getType($prefix = true) { $type = $prefix ? $this->getTypePrefix() : ''; if (static::$type) { return $type . static::$type; } $class = get_class($this); return $type . strtolower(substr($class, strrpos($class, '\\') + 1)); } /** * @return string */ public function getKey() { return $this->_key ?: $this->getType() . '@@' . spl_object_hash($this); } /** * @return bool */ public function hasKey() { return !empty($this->_key); } /** * @param string $property Object property name. * @return bool True if property has been defined (can be null). */ public function hasProperty($property) { return $this->doHasProperty($property); } /** * @param string $property Object property to be fetched. * @param mixed $default Default value if property has not been set. * @return mixed Property value. */ public function getProperty($property, $default = null) { return $this->doGetProperty($property, $default); } /** * @param string $property Object property to be updated. * @param mixed $value New value. * @return $this */ public function setProperty($property, $value) { $this->doSetProperty($property, $value); return $this; } /** * @param string $property Object property to be unset. * @return $this */ public function unsetProperty($property) { $this->doUnsetProperty($property); return $this; } /** * @param string $property Object property to be defined. * @param mixed $default Default value. * @return $this */ public function defProperty($property, $default) { if (!$this->hasProperty($property)) { $this->setProperty($property, $default); } return $this; } /** * @return array */ final public function __serialize(): array { return $this->doSerialize(); } /** * @param array $data * @return void */ final public function __unserialize(array $data): void { if (method_exists($this, 'initObjectProperties')) { $this->initObjectProperties(); } $this->doUnserialize($data); } /** * @return array */ protected function doSerialize() { return ['key' => $this->getKey(), 'type' => $this->getType(), 'elements' => $this->getElements()]; } /** * @param array $serialized * @return void */ protected function doUnserialize(array $serialized) { if (!isset($serialized['key'], $serialized['type'], $serialized['elements']) || $serialized['type'] !== $this->getType()) { throw new InvalidArgumentException("Cannot unserialize '{$this->getType()}': Bad data"); } $this->setKey($serialized['key']); $this->setElements($serialized['elements']); } /** * Implements JsonSerializable interface. * * @return array */ #[\ReturnTypeWillChange] public function jsonSerialize() { return $this->doSerialize(); } /** * Returns a string representation of this object. * * @return string */ #[\ReturnTypeWillChange] public function __toString() { return $this->getKey(); } /** * @param string $key * @return $this */ protected function setKey($key) { $this->_key = (string) $key; return $this; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/Collection/ObjectExpressionVisitor.php
system/src/Grav/Framework/Object/Collection/ObjectExpressionVisitor.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object\Collection; use ArrayAccess; use Closure; use Doctrine\Common\Collections\Expr\ClosureExpressionVisitor; use Doctrine\Common\Collections\Expr\Comparison; use RuntimeException; use function in_array; use function is_array; use function is_callable; use function is_string; use function strlen; /** * Class ObjectExpressionVisitor * @package Grav\Framework\Object\Collection */ class ObjectExpressionVisitor extends ClosureExpressionVisitor { /** * Accesses the field of a given object. * * @param object $object * @param string $field * @return mixed */ public static function getObjectFieldValue($object, $field) { $op = $value = null; $pos = strpos($field, '('); if (false !== $pos) { [$op, $field] = explode('(', $field, 2); $field = rtrim($field, ')'); } if ($object instanceof ArrayAccess && isset($object[$field])) { $value = $object[$field]; } else { $accessors = array('', 'get', 'is'); foreach ($accessors as $accessor) { $accessor .= $field; if (!is_callable([$object, $accessor])) { continue; } $value = $object->{$accessor}(); break; } } if ($op) { $function = 'filter' . ucfirst(strtolower($op)); if (method_exists(static::class, $function)) { $value = static::$function($value); } } return $value; } /** * @param string $str * @return string */ public static function filterLower($str) { return mb_strtolower($str); } /** * @param string $str * @return string */ public static function filterUpper($str) { return mb_strtoupper($str); } /** * @param string $str * @return int */ public static function filterLength($str) { return mb_strlen($str); } /** * @param string $str * @return string */ public static function filterLtrim($str) { return ltrim($str); } /** * @param string $str * @return string */ public static function filterRtrim($str) { return rtrim($str); } /** * @param string $str * @return string */ public static function filterTrim($str) { return trim($str); } /** * Helper for sorting arrays of objects based on multiple fields + orientations. * * Comparison between two strings is natural and case insensitive. * * @param string $name * @param int $orientation * @param Closure|null $next * * @return Closure */ public static function sortByField($name, $orientation = 1, Closure $next = null) { if (!$next) { $next = function ($a, $b) { return 0; }; } return function ($a, $b) use ($name, $next, $orientation) { $aValue = static::getObjectFieldValue($a, $name); $bValue = static::getObjectFieldValue($b, $name); if ($aValue === $bValue) { return $next($a, $b); } // For strings we use natural case insensitive sorting. if (is_string($aValue) && is_string($bValue)) { return strnatcasecmp($aValue, $bValue) * $orientation; } return (($aValue > $bValue) ? 1 : -1) * $orientation; }; } /** * {@inheritDoc} */ public function walkComparison(Comparison $comparison) { $field = $comparison->getField(); $value = $comparison->getValue()->getValue(); // shortcut for walkValue() switch ($comparison->getOperator()) { case Comparison::EQ: return function ($object) use ($field, $value) { return static::getObjectFieldValue($object, $field) === $value; }; case Comparison::NEQ: return function ($object) use ($field, $value) { return static::getObjectFieldValue($object, $field) !== $value; }; case Comparison::LT: return function ($object) use ($field, $value) { return static::getObjectFieldValue($object, $field) < $value; }; case Comparison::LTE: return function ($object) use ($field, $value) { return static::getObjectFieldValue($object, $field) <= $value; }; case Comparison::GT: return function ($object) use ($field, $value) { return static::getObjectFieldValue($object, $field) > $value; }; case Comparison::GTE: return function ($object) use ($field, $value) { return static::getObjectFieldValue($object, $field) >= $value; }; case Comparison::IN: return function ($object) use ($field, $value) { return in_array(static::getObjectFieldValue($object, $field), $value, true); }; case Comparison::NIN: return function ($object) use ($field, $value) { return !in_array(static::getObjectFieldValue($object, $field), $value, true); }; case Comparison::CONTAINS: return function ($object) use ($field, $value) { return false !== strpos(static::getObjectFieldValue($object, $field), $value); }; case Comparison::MEMBER_OF: return function ($object) use ($field, $value) { $fieldValues = static::getObjectFieldValue($object, $field); if (!is_array($fieldValues)) { $fieldValues = iterator_to_array($fieldValues); } return in_array($value, $fieldValues, true); }; case Comparison::STARTS_WITH: return function ($object) use ($field, $value) { return 0 === strpos(static::getObjectFieldValue($object, $field), $value); }; case Comparison::ENDS_WITH: return function ($object) use ($field, $value) { return $value === substr(static::getObjectFieldValue($object, $field), -strlen($value)); }; default: throw new RuntimeException('Unknown comparison operator: ' . $comparison->getOperator()); } } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/Identifiers/Identifier.php
system/src/Grav/Framework/Object/Identifiers/Identifier.php
<?php declare(strict_types=1); namespace Grav\Framework\Object\Identifiers; use Grav\Framework\Contracts\Object\IdentifierInterface; /** * Interface IdentifierInterface * * @template T of object */ class Identifier implements IdentifierInterface { /** @var string */ private $id; /** @var string */ private $type; /** * IdentifierInterface constructor. * @param string $id * @param string $type */ public function __construct(string $id, string $type) { $this->id = $id; $this->type = $type; } /** * @return string * @phpstan-pure */ public function getId(): string { return $this->id; } /** * @return string * @phpstan-pure */ public function getType(): string { return $this->type; } /** * @return array */ public function jsonSerialize(): array { return [ 'type' => $this->type, 'id' => $this->id ]; } /** * @return array */ public function __debugInfo(): array { return $this->jsonSerialize(); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/Access/NestedArrayAccessTrait.php
system/src/Grav/Framework/Object/Access/NestedArrayAccessTrait.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object\Access; /** * Nested ArrayAccess Object Trait * @package Grav\Framework\Object */ trait NestedArrayAccessTrait { /** * Whether or not an offset exists. * * @param mixed $offset An offset to check for. * @return bool Returns TRUE on success or FALSE on failure. */ #[\ReturnTypeWillChange] public function offsetExists($offset) { return $this->hasNestedProperty($offset); } /** * Returns the value at specified offset. * * @param mixed $offset The offset to retrieve. * @return mixed Can return all value types. */ #[\ReturnTypeWillChange] public function offsetGet($offset) { return $this->getNestedProperty($offset); } /** * Assigns a value to the specified offset. * * @param mixed $offset The offset to assign the value to. * @param mixed $value The value to set. * @return void */ #[\ReturnTypeWillChange] public function offsetSet($offset, $value) { $this->setNestedProperty($offset, $value); } /** * Unsets an offset. * * @param mixed $offset The offset to unset. * @return void */ #[\ReturnTypeWillChange] public function offsetUnset($offset) { $this->unsetNestedProperty($offset); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/Access/NestedPropertyCollectionTrait.php
system/src/Grav/Framework/Object/Access/NestedPropertyCollectionTrait.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object\Access; use Grav\Framework\Object\Interfaces\NestedObjectInterface; /** * Nested Properties Collection Trait * @package Grav\Framework\Object\Properties */ trait NestedPropertyCollectionTrait { /** * @param string $property Object property to be matched. * @param string|null $separator Separator, defaults to '.' * @return array Key/Value pairs of the properties. */ public function hasNestedProperty($property, $separator = null) { $list = []; /** @var NestedObjectInterface $element */ foreach ($this->getIterator() as $id => $element) { $list[$id] = $element->hasNestedProperty($property, $separator); } return $list; } /** * @param string $property Object property to be fetched. * @param mixed $default Default value if not set. * @param string|null $separator Separator, defaults to '.' * @return array Key/Value pairs of the properties. */ public function getNestedProperty($property, $default = null, $separator = null) { $list = []; /** @var NestedObjectInterface $element */ foreach ($this->getIterator() as $id => $element) { $list[$id] = $element->getNestedProperty($property, $default, $separator); } return $list; } /** * @param string $property Object property to be updated. * @param mixed $value New value. * @param string|null $separator Separator, defaults to '.' * @return $this */ public function setNestedProperty($property, $value, $separator = null) { /** @var NestedObjectInterface $element */ foreach ($this->getIterator() as $element) { $element->setNestedProperty($property, $value, $separator); } return $this; } /** * @param string $property Object property to be updated. * @param string|null $separator Separator, defaults to '.' * @return $this */ public function unsetNestedProperty($property, $separator = null) { /** @var NestedObjectInterface $element */ foreach ($this->getIterator() as $element) { $element->unsetNestedProperty($property, $separator); } return $this; } /** * @param string $property Object property to be updated. * @param string $default Default value. * @param string|null $separator Separator, defaults to '.' * @return $this */ public function defNestedProperty($property, $default, $separator = null) { /** @var NestedObjectInterface $element */ foreach ($this->getIterator() as $element) { $element->defNestedProperty($property, $default, $separator); } return $this; } /** * Group items in the collection by a field. * * @param string $property Object property to be used to make groups. * @param string|null $separator Separator, defaults to '.' * @return array */ public function group($property, $separator = null) { $list = []; /** @var NestedObjectInterface $element */ foreach ($this->getIterator() as $element) { $list[(string) $element->getNestedProperty($property, null, $separator)][] = $element; } return $list; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/Access/NestedPropertyTrait.php
system/src/Grav/Framework/Object/Access/NestedPropertyTrait.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object\Access; use Grav\Framework\Object\Interfaces\ObjectInterface; use RuntimeException; use stdClass; use function is_array; use function is_object; /** * Nested Property Object Trait * @package Grav\Framework\Object\Traits */ trait NestedPropertyTrait { /** * @param string $property Object property name. * @param string|null $separator Separator, defaults to '.' * @return bool True if property has been defined (can be null). */ public function hasNestedProperty($property, $separator = null) { $test = new stdClass; return $this->getNestedProperty($property, $test, $separator) !== $test; } /** * @param string $property Object property to be fetched. * @param mixed|null $default Default value if property has not been set. * @param string|null $separator Separator, defaults to '.' * @return mixed Property value. */ public function getNestedProperty($property, $default = null, $separator = null) { $separator = $separator ?: '.'; $path = explode($separator, (string) $property); $offset = array_shift($path); if (!$this->hasProperty($offset)) { return $default; } $current = $this->getProperty($offset); while ($path) { // Get property of nested Object. if ($current instanceof ObjectInterface) { if (method_exists($current, 'getNestedProperty')) { return $current->getNestedProperty(implode($separator, $path), $default, $separator); } return $current->getProperty(implode($separator, $path), $default); } $offset = array_shift($path); if ((is_array($current) || is_a($current, 'ArrayAccess')) && isset($current[$offset])) { $current = $current[$offset]; } elseif (is_object($current) && isset($current->{$offset})) { $current = $current->{$offset}; } else { return $default; } }; return $current; } /** * @param string $property Object property to be updated. * @param mixed $value New value. * @param string|null $separator Separator, defaults to '.' * @return $this * @throws RuntimeException */ public function setNestedProperty($property, $value, $separator = null) { $separator = $separator ?: '.'; $path = explode($separator, $property); $offset = array_shift($path); if (!$path) { $this->setProperty($offset, $value); return $this; } $current = &$this->doGetProperty($offset, null, true); while ($path) { $offset = array_shift($path); // Handle arrays and scalars. if ($current === null) { $current = [$offset => []]; } elseif (is_array($current)) { if (!isset($current[$offset])) { $current[$offset] = []; } } else { throw new RuntimeException("Cannot set nested property {$property} on non-array value"); } $current = &$current[$offset]; }; $current = $value; return $this; } /** * @param string $property Object property to be updated. * @param string|null $separator Separator, defaults to '.' * @return $this * @throws RuntimeException */ public function unsetNestedProperty($property, $separator = null) { $separator = $separator ?: '.'; $path = explode($separator, $property); $offset = array_shift($path); if (!$path) { $this->unsetProperty($offset); return $this; } $last = array_pop($path); $current = &$this->doGetProperty($offset, null, true); while ($path) { $offset = array_shift($path); // Handle arrays and scalars. if ($current === null) { return $this; } if (is_array($current)) { if (!isset($current[$offset])) { return $this; } } else { throw new RuntimeException("Cannot unset nested property {$property} on non-array value"); } $current = &$current[$offset]; }; unset($current[$last]); return $this; } /** * @param string $property Object property to be updated. * @param mixed $default Default value. * @param string|null $separator Separator, defaults to '.' * @return $this * @throws RuntimeException */ public function defNestedProperty($property, $default, $separator = null) { if (!$this->hasNestedProperty($property, $separator)) { $this->setNestedProperty($property, $default, $separator); } return $this; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/Access/OverloadedPropertyTrait.php
system/src/Grav/Framework/Object/Access/OverloadedPropertyTrait.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object\Access; /** * Overloaded Property Object Trait * @package Grav\Framework\Object\Access */ trait OverloadedPropertyTrait { /** * Checks whether or not an offset exists. * * @param mixed $offset An offset to check for. * @return bool Returns TRUE on success or FALSE on failure. */ #[\ReturnTypeWillChange] public function __isset($offset) { return $this->hasProperty($offset); } /** * Returns the value at specified offset. * * @param mixed $offset The offset to retrieve. * @return mixed Can return all value types. */ #[\ReturnTypeWillChange] public function __get($offset) { return $this->getProperty($offset); } /** * Assigns a value to the specified offset. * * @param mixed $offset The offset to assign the value to. * @param mixed $value The value to set. * @return void */ #[\ReturnTypeWillChange] public function __set($offset, $value) { $this->setProperty($offset, $value); } /** * Magic method to unset the attribute * * @param mixed $offset The name value to unset * @return void */ #[\ReturnTypeWillChange] public function __unset($offset) { $this->unsetProperty($offset); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/Access/ArrayAccessTrait.php
system/src/Grav/Framework/Object/Access/ArrayAccessTrait.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object\Access; /** * ArrayAccess Object Trait * @package Grav\Framework\Object */ trait ArrayAccessTrait { /** * Whether or not an offset exists. * * @param mixed $offset An offset to check for. * @return bool Returns TRUE on success or FALSE on failure. */ #[\ReturnTypeWillChange] public function offsetExists($offset) { return $this->hasProperty($offset); } /** * Returns the value at specified offset. * * @param mixed $offset The offset to retrieve. * @return mixed Can return all value types. */ #[\ReturnTypeWillChange] public function offsetGet($offset) { return $this->getProperty($offset); } /** * Assigns a value to the specified offset. * * @param mixed $offset The offset to assign the value to. * @param mixed $value The value to set. * @return void */ #[\ReturnTypeWillChange] public function offsetSet($offset, $value) { $this->setProperty($offset, $value); } /** * Unsets an offset. * * @param mixed $offset The offset to unset. * @return void */ #[\ReturnTypeWillChange] public function offsetUnset($offset) { $this->unsetProperty($offset); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/Property/ObjectPropertyTrait.php
system/src/Grav/Framework/Object/Property/ObjectPropertyTrait.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object\Property; use InvalidArgumentException; use function array_key_exists; use function get_object_vars; use function is_callable; /** * Object Property Trait * * Stores all properties as class member variables or object properties. All properties need to be defined as protected * properties. Undefined properties will throw an error. * * Additionally you may define following methods: * - `$this->offsetLoad($offset, $value)` called first time object property gets accessed * - `$this->offsetPrepare($offset, $value)` called on every object property set * - `$this->offsetSerialize($offset, $value)` called when the raw or serialized object property value is needed * * @package Grav\Framework\Object\Property */ trait ObjectPropertyTrait { /** @var array */ private $_definedProperties; /** * @param array $elements * @param string|null $key * @throws InvalidArgumentException */ public function __construct(array $elements = [], $key = null) { $this->initObjectProperties(); $this->setElements($elements); $this->setKey($key ?? ''); } /** * @param string $property Object property name. * @return bool True if property has been loaded. */ protected function isPropertyLoaded($property) { return !empty($this->_definedProperties[$property]); } /** * @param string $offset * @param mixed $value * @return mixed */ protected function offsetLoad($offset, $value) { $methodName = "offsetLoad_{$offset}"; return method_exists($this, $methodName)? $this->{$methodName}($value) : $value; } /** * @param string $offset * @param mixed $value * @return mixed */ protected function offsetPrepare($offset, $value) { $methodName = "offsetPrepare_{$offset}"; return method_exists($this, $methodName) ? $this->{$methodName}($value) : $value; } /** * @param string $offset * @param mixed $value * @return mixed */ protected function offsetSerialize($offset, $value) { $methodName = "offsetSerialize_{$offset}"; return method_exists($this, $methodName) ? $this->{$methodName}($value) : $value; } /** * @param string $property Object property name. * @return bool True if property has been defined (can be null). */ protected function doHasProperty($property) { return array_key_exists($property, $this->_definedProperties); } /** * @param string $property Object property to be fetched. * @param mixed $default Default value if property has not been set. * @param callable|bool $doCreate Set true to create variable. * @return mixed Property value. */ protected function &doGetProperty($property, $default = null, $doCreate = false) { if (!array_key_exists($property, $this->_definedProperties)) { throw new InvalidArgumentException("Property '{$property}' does not exist in the object!"); } if (empty($this->_definedProperties[$property])) { if ($doCreate === true) { $this->_definedProperties[$property] = true; $this->{$property} = null; } elseif (is_callable($doCreate)) { $this->_definedProperties[$property] = true; $this->{$property} = $this->offsetLoad($property, $doCreate()); } else { return $default; } } return $this->{$property}; } /** * @param string $property Object property to be updated. * @param mixed $value New value. * @return void * @throws InvalidArgumentException */ protected function doSetProperty($property, $value) { if (!array_key_exists($property, $this->_definedProperties)) { throw new InvalidArgumentException("Property '{$property}' does not exist in the object!"); } $this->_definedProperties[$property] = true; $this->{$property} = $this->offsetPrepare($property, $value); } /** * @param string $property Object property to be unset. * @return void */ protected function doUnsetProperty($property) { if (!array_key_exists($property, $this->_definedProperties)) { return; } $this->_definedProperties[$property] = false; $this->{$property} = null; } /** * @return void */ protected function initObjectProperties() { $this->_definedProperties = []; foreach (get_object_vars($this) as $property => $value) { if ($property[0] !== '_') { $this->_definedProperties[$property] = ($value !== null); } } } /** * @param string $property * @param mixed|null $default * @return mixed|null */ protected function getElement($property, $default = null) { if (empty($this->_definedProperties[$property])) { return $default; } return $this->offsetSerialize($property, $this->{$property}); } /** * @return array */ protected function getElements() { $properties = array_intersect_key(get_object_vars($this), array_filter($this->_definedProperties)); $elements = []; foreach ($properties as $offset => $value) { $serialized = $this->offsetSerialize($offset, $value); if ($serialized !== null) { $elements[$offset] = $this->offsetSerialize($offset, $value); } } return $elements; } /** * @param array $elements * @return void */ protected function setElements(array $elements) { foreach ($elements as $property => $value) { $this->setProperty($property, $value); } } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/Property/MixedPropertyTrait.php
system/src/Grav/Framework/Object/Property/MixedPropertyTrait.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object\Property; /** * Mixed Property Trait * * Stores defined object properties as class member variables and the rest into an array. * * You may define following methods for member variables: * - `$this->offsetLoad($offset, $value)` called first time object property gets accessed * - `$this->offsetPrepare($offset, $value)` called on every object property set * - `$this->offsetSerialize($offset, $value)` called when the raw or serialized object property value is needed * * @package Grav\Framework\Object\Property */ trait MixedPropertyTrait { use ArrayPropertyTrait, ObjectPropertyTrait { ObjectPropertyTrait::__construct insteadof ArrayPropertyTrait; ArrayPropertyTrait::doHasProperty as hasArrayProperty; ArrayPropertyTrait::doGetProperty as getArrayProperty; ArrayPropertyTrait::doSetProperty as setArrayProperty; ArrayPropertyTrait::doUnsetProperty as unsetArrayProperty; ArrayPropertyTrait::getElement as getArrayElement; ArrayPropertyTrait::getElements as getArrayElements; ArrayPropertyTrait::setElements as setArrayElements; ObjectPropertyTrait::doHasProperty as hasObjectProperty; ObjectPropertyTrait::doGetProperty as getObjectProperty; ObjectPropertyTrait::doSetProperty as setObjectProperty; ObjectPropertyTrait::doUnsetProperty as unsetObjectProperty; ObjectPropertyTrait::getElement as getObjectElement; ObjectPropertyTrait::getElements as getObjectElements; ObjectPropertyTrait::setElements as setObjectElements; } /** * @param string $property Object property name. * @return bool True if property has been defined (can be null). */ protected function doHasProperty($property) { return $this->hasArrayProperty($property) || $this->hasObjectProperty($property); } /** * @param string $property Object property to be fetched. * @param mixed $default Default value if property has not been set. * @param bool $doCreate * @return mixed Property value. */ protected function &doGetProperty($property, $default = null, $doCreate = false) { if ($this->hasObjectProperty($property)) { return $this->getObjectProperty($property); } return $this->getArrayProperty($property, $default, $doCreate); } /** * @param string $property Object property to be updated. * @param mixed $value New value. * @return void */ protected function doSetProperty($property, $value) { $this->hasObjectProperty($property) ? $this->setObjectProperty($property, $value) : $this->setArrayProperty($property, $value); } /** * @param string $property Object property to be unset. * @return void */ protected function doUnsetProperty($property) { $this->hasObjectProperty($property) ? $this->unsetObjectProperty($property) : $this->unsetArrayProperty($property); } /** * @param string $property * @param mixed|null $default * @return mixed|null */ protected function getElement($property, $default = null) { if ($this->hasObjectProperty($property)) { return $this->getObjectElement($property, $default); } return $this->getArrayElement($property, $default); } /** * @return array */ protected function getElements() { return $this->getObjectElements() + $this->getArrayElements(); } /** * @param array $elements * @return void */ protected function setElements(array $elements) { $this->setObjectElements(array_intersect_key($elements, $this->_definedProperties)); $this->setArrayElements(array_diff_key($elements, $this->_definedProperties)); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/Property/ArrayPropertyTrait.php
system/src/Grav/Framework/Object/Property/ArrayPropertyTrait.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object\Property; use InvalidArgumentException; use function array_key_exists; /** * Array Property Trait * * Stores all object properties into an array. * * @package Grav\Framework\Object\Property */ trait ArrayPropertyTrait { /** @var array Properties of the object. */ private $_elements; /** * @param array $elements * @param string|null $key * @throws InvalidArgumentException */ public function __construct(array $elements = [], $key = null) { $this->setElements($elements); $this->setKey($key ?? ''); } /** * @param string $property Object property name. * @return bool True if property has been defined (can be null). */ protected function doHasProperty($property) { return array_key_exists($property, $this->_elements); } /** * @param string $property Object property to be fetched. * @param mixed $default Default value if property has not been set. * @param bool $doCreate Set true to create variable. * @return mixed Property value. */ protected function &doGetProperty($property, $default = null, $doCreate = false) { if (!array_key_exists($property, $this->_elements)) { if ($doCreate) { $this->_elements[$property] = null; } else { return $default; } } return $this->_elements[$property]; } /** * @param string $property Object property to be updated. * @param mixed $value New value. * @return void */ protected function doSetProperty($property, $value) { $this->_elements[$property] = $value; } /** * @param string $property Object property to be unset. * @return void */ protected function doUnsetProperty($property) { unset($this->_elements[$property]); } /** * @param string $property * @param mixed|null $default * @return mixed|null */ protected function getElement($property, $default = null) { return array_key_exists($property, $this->_elements) ? $this->_elements[$property] : $default; } /** * @return array */ protected function getElements() { return array_filter($this->_elements, static function ($val) { return $val !== null; }); } /** * @param array $elements * @return void */ protected function setElements(array $elements) { $this->_elements = $elements; } abstract protected function setKey($key); }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Object/Property/LazyPropertyTrait.php
system/src/Grav/Framework/Object/Property/LazyPropertyTrait.php
<?php /** * @package Grav\Framework\Object * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Object\Property; /** * Lazy Mixed Property Trait * * Stores defined object properties as class member variables and the rest into an array. Object properties are lazy * loaded from the array. * * You may define following methods for the member variables: * - `$this->offsetLoad($offset, $value)` called first time object property gets accessed * - `$this->offsetPrepare($offset, $value)` called on every object property set * - `$this->offsetSerialize($offset, $value)` called when the raw or serialized object property value is needed * * @package Grav\Framework\Object\Property */ trait LazyPropertyTrait { use ArrayPropertyTrait, ObjectPropertyTrait { ObjectPropertyTrait::__construct insteadof ArrayPropertyTrait; ArrayPropertyTrait::doHasProperty as hasArrayProperty; ArrayPropertyTrait::doGetProperty as getArrayProperty; ArrayPropertyTrait::doSetProperty as setArrayProperty; ArrayPropertyTrait::doUnsetProperty as unsetArrayProperty; ArrayPropertyTrait::getElement as getArrayElement; ArrayPropertyTrait::getElements as getArrayElements; ArrayPropertyTrait::setElements insteadof ObjectPropertyTrait; ObjectPropertyTrait::doHasProperty as hasObjectProperty; ObjectPropertyTrait::doGetProperty as getObjectProperty; ObjectPropertyTrait::doSetProperty as setObjectProperty; ObjectPropertyTrait::doUnsetProperty as unsetObjectProperty; ObjectPropertyTrait::getElement as getObjectElement; ObjectPropertyTrait::getElements as getObjectElements; } /** * @param string $property Object property name. * @return bool True if property has been defined (can be null). */ protected function doHasProperty($property) { return $this->hasArrayProperty($property) || $this->hasObjectProperty($property); } /** * @param string $property Object property to be fetched. * @param mixed $default Default value if property has not been set. * @param bool $doCreate * @return mixed Property value. */ protected function &doGetProperty($property, $default = null, $doCreate = false) { if ($this->hasObjectProperty($property)) { return $this->getObjectProperty($property, $default, function ($default = null) use ($property) { return $this->getArrayProperty($property, $default); }); } return $this->getArrayProperty($property, $default, $doCreate); } /** * @param string $property Object property to be updated. * @param mixed $value New value. * @return void */ protected function doSetProperty($property, $value) { if ($this->hasObjectProperty($property)) { $this->setObjectProperty($property, $value); } else { $this->setArrayProperty($property, $value); } } /** * @param string $property Object property to be unset. * @return void */ protected function doUnsetProperty($property) { $this->hasObjectProperty($property) ? $this->unsetObjectProperty($property) : $this->unsetArrayProperty($property); } /** * @param string $property * @param mixed|null $default * @return mixed|null */ protected function getElement($property, $default = null) { if ($this->isPropertyLoaded($property)) { return $this->getObjectElement($property, $default); } return $this->getArrayElement($property, $default); } /** * @return array */ protected function getElements() { return $this->getObjectElements() + $this->getArrayElements(); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Uri/UriFactory.php
system/src/Grav/Framework/Uri/UriFactory.php
<?php /** * @package Grav\Framework\Uri * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Uri; use InvalidArgumentException; use function is_string; /** * Class Uri * @package Grav\Framework\Uri */ class UriFactory { /** * @param array $env * @return Uri * @throws InvalidArgumentException */ public static function createFromEnvironment(array $env) { return new Uri(static::parseUrlFromEnvironment($env)); } /** * @param string $uri * @return Uri * @throws InvalidArgumentException */ public static function createFromString($uri) { return new Uri(static::parseUrl($uri)); } /** * Creates a URI from a array of `parse_url()` components. * * @param array $parts * @return Uri * @throws InvalidArgumentException */ public static function createFromParts(array $parts) { return new Uri($parts); } /** * @param array $env * @return array * @throws InvalidArgumentException */ public static function parseUrlFromEnvironment(array $env) { // Build scheme. if (isset($env['REQUEST_SCHEME'])) { $scheme = strtolower($env['REQUEST_SCHEME']); } else { $https = $env['HTTPS'] ?? ''; $scheme = (empty($https) || strtolower($https) === 'off') ? 'http' : 'https'; } // Build user and password. $user = $env['PHP_AUTH_USER'] ?? ''; $pass = $env['PHP_AUTH_PW'] ?? ''; // Build host. $host = 'localhost'; if (isset($env['HTTP_HOST'])) { $host = $env['HTTP_HOST']; } elseif (isset($env['SERVER_NAME'])) { $host = $env['SERVER_NAME']; } // Remove port from HTTP_HOST generated $hostname $host = explode(':', $host)[0]; // Build port. $port = isset($env['SERVER_PORT']) ? (int)$env['SERVER_PORT'] : null; // Build path. $request_uri = $env['REQUEST_URI'] ?? ''; $path = parse_url('http://example.com' . $request_uri, PHP_URL_PATH); // Build query string. $query = $env['QUERY_STRING'] ?? ''; if ($query === '') { $query = parse_url('http://example.com' . $request_uri, PHP_URL_QUERY); } // Support ngnix routes. if (strpos((string) $query, '_url=') === 0) { parse_str($query, $q); unset($q['_url']); $query = http_build_query($q); } return [ 'scheme' => $scheme, 'user' => $user, 'pass' => $pass, 'host' => $host, 'port' => $port, 'path' => $path, 'query' => $query ]; } /** * UTF-8 aware parse_url() implementation. * * @param string $url * @return array * @throws InvalidArgumentException */ public static function parseUrl($url) { if (!is_string($url)) { throw new InvalidArgumentException('URL must be a string'); } $encodedUrl = preg_replace_callback( '%[^:/@?&=#]+%u', static function ($matches) { return rawurlencode($matches[0]); }, $url ); $parts = is_string($encodedUrl) ? parse_url($encodedUrl) : false; if ($parts === false) { throw new InvalidArgumentException("Malformed URL: {$url}"); } return $parts; } /** * Parse query string and return it as an array. * * @param string $query * @return mixed */ public static function parseQuery($query) { parse_str($query, $params); return $params; } /** * Build query string from variables. * * @param array $params * @return string */ public static function buildQuery(array $params) { if (!$params) { return ''; } $separator = ini_get('arg_separator.output') ?: '&'; return http_build_query($params, '', $separator, PHP_QUERY_RFC3986); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Uri/Uri.php
system/src/Grav/Framework/Uri/Uri.php
<?php /** * @package Grav\Framework\Uri * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Uri; use Grav\Framework\Psr7\AbstractUri; use GuzzleHttp\Psr7\Uri as GuzzleUri; use InvalidArgumentException; use Psr\Http\Message\UriInterface; /** * Implements PSR-7 UriInterface. * * @package Grav\Framework\Uri */ class Uri extends AbstractUri { /** @var array Array of Uri query. */ private $queryParams; /** * You can use `UriFactory` functions to create new `Uri` objects. * * @param array $parts * @return void * @throws InvalidArgumentException */ public function __construct(array $parts = []) { $this->initParts($parts); } /** * @return string */ public function getUser() { return parent::getUser(); } /** * @return string */ public function getPassword() { return parent::getPassword(); } /** * @return array */ public function getParts() { return parent::getParts(); } /** * @return string */ public function getUrl() { return parent::getUrl(); } /** * @return string */ public function getBaseUrl() { return parent::getBaseUrl(); } /** * @param string $key * @return string|null */ public function getQueryParam($key) { $queryParams = $this->getQueryParams(); return $queryParams[$key] ?? null; } /** * @param string $key * @return UriInterface */ public function withoutQueryParam($key) { return GuzzleUri::withoutQueryValue($this, $key); } /** * @param string $key * @param string|null $value * @return UriInterface */ public function withQueryParam($key, $value) { return GuzzleUri::withQueryValue($this, $key, $value); } /** * @return array */ public function getQueryParams() { if ($this->queryParams === null) { $this->queryParams = UriFactory::parseQuery($this->getQuery()); } return $this->queryParams; } /** * @param array $params * @return UriInterface */ public function withQueryParams(array $params) { $query = UriFactory::buildQuery($params); return $this->withQuery($query); } /** * Whether the URI has the default port of the current scheme. * * `$uri->getPort()` may return the standard port. This method can be used for some non-http/https Uri. * * @return bool */ public function isDefaultPort() { return $this->getPort() === null || GuzzleUri::isDefaultPort($this); } /** * Whether the URI is absolute, i.e. it has a scheme. * * An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true * if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative * to another URI, the base URI. Relative references can be divided into several forms: * - network-path references, e.g. '//example.com/path' * - absolute-path references, e.g. '/path' * - relative-path references, e.g. 'subpath' * * @return bool * @link https://tools.ietf.org/html/rfc3986#section-4 */ public function isAbsolute() { return GuzzleUri::isAbsolute($this); } /** * Whether the URI is a network-path reference. * * A relative reference that begins with two slash characters is termed an network-path reference. * * @return bool * @link https://tools.ietf.org/html/rfc3986#section-4.2 */ public function isNetworkPathReference() { return GuzzleUri::isNetworkPathReference($this); } /** * Whether the URI is a absolute-path reference. * * A relative reference that begins with a single slash character is termed an absolute-path reference. * * @return bool * @link https://tools.ietf.org/html/rfc3986#section-4.2 */ public function isAbsolutePathReference() { return GuzzleUri::isAbsolutePathReference($this); } /** * Whether the URI is a relative-path reference. * * A relative reference that does not begin with a slash character is termed a relative-path reference. * * @return bool * @link https://tools.ietf.org/html/rfc3986#section-4.2 */ public function isRelativePathReference() { return GuzzleUri::isRelativePathReference($this); } /** * Whether the URI is a same-document reference. * * A same-document reference refers to a URI that is, aside from its fragment * component, identical to the base URI. When no base URI is given, only an empty * URI reference (apart from its fragment) is considered a same-document reference. * * @param UriInterface|null $base An optional base URI to compare against * @return bool * @link https://tools.ietf.org/html/rfc3986#section-4.4 */ public function isSameDocumentReference(UriInterface $base = null) { return GuzzleUri::isSameDocumentReference($this, $base); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Uri/UriPartsFilter.php
system/src/Grav/Framework/Uri/UriPartsFilter.php
<?php /** * @package Grav\Framework\Uri * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Uri; use InvalidArgumentException; use function is_int; use function is_string; /** * Class Uri * @package Grav\Framework\Uri */ class UriPartsFilter { const HOSTNAME_REGEX = '/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/u'; /** * @param string $scheme * @return string * @throws InvalidArgumentException If the scheme is invalid. */ public static function filterScheme($scheme) { if (!is_string($scheme)) { throw new InvalidArgumentException('Uri scheme must be a string'); } return strtolower($scheme); } /** * Filters the user info string. * * @param string $info The raw user or password. * @return string The percent-encoded user or password string. * @throws InvalidArgumentException */ public static function filterUserInfo($info) { if (!is_string($info)) { throw new InvalidArgumentException('Uri user info must be a string'); } return preg_replace_callback( '/(?:[^a-zA-Z0-9_\-\.~!\$&\'\(\)\*\+,;=]+|%(?![A-Fa-f0-9]{2}))/u', function ($match) { return rawurlencode($match[0]); }, $info ) ?? ''; } /** * @param string $host * @return string * @throws InvalidArgumentException If the host is invalid. */ public static function filterHost($host) { if (!is_string($host)) { throw new InvalidArgumentException('Uri host must be a string'); } if (filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { $host = '[' . $host . ']'; } elseif ($host && preg_match(static::HOSTNAME_REGEX, $host) !== 1) { throw new InvalidArgumentException('Uri host name validation failed'); } return strtolower($host); } /** * Filter Uri port. * * This method * * @param int|null $port * @return int|null * @throws InvalidArgumentException If the port is invalid. */ public static function filterPort($port = null) { if (null === $port || (is_int($port) && ($port >= 0 && $port <= 65535))) { return $port; } throw new InvalidArgumentException('Uri port must be null or an integer between 0 and 65535'); } /** * Filter Uri path. * * This method percent-encodes all reserved characters in the provided path string. This method * will NOT double-encode characters that are already percent-encoded. * * @param string $path The raw uri path. * @return string The RFC 3986 percent-encoded uri path. * @throws InvalidArgumentException If the path is invalid. * @link http://www.faqs.org/rfcs/rfc3986.html */ public static function filterPath($path) { if (!is_string($path)) { throw new InvalidArgumentException('Uri path must be a string'); } return preg_replace_callback( '/(?:[^a-zA-Z0-9_\-\.~:@&=\+\$,\/;%]+|%(?![A-Fa-f0-9]{2}))/u', function ($match) { return rawurlencode($match[0]); }, $path ) ?? ''; } /** * Filters the query string or fragment of a URI. * * @param string $query The raw uri query string. * @return string The percent-encoded query string. * @throws InvalidArgumentException If the query is invalid. */ public static function filterQueryOrFragment($query) { if (!is_string($query)) { throw new InvalidArgumentException('Uri query string and fragment must be a string'); } return preg_replace_callback( '/(?:[^a-zA-Z0-9_\-\.~!\$&\'\(\)\*\+,;=%:@\/\?]+|%(?![A-Fa-f0-9]{2}))/u', function ($match) { return rawurlencode($match[0]); }, $query ) ?? ''; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Compat/Serializable.php
system/src/Grav/Framework/Compat/Serializable.php
<?php /** * @package Grav\Framework\Compat * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Compat; /** * Serializable trait * * Adds backwards compatibility to PHP 7.3 Serializable interface. * * Note: Remember to add: `implements \Serializable` to the classes which use this trait. * * @package Grav\Framework\Traits */ trait Serializable { /** * @return string */ final public function serialize(): string { return serialize($this->__serialize()); } /** * @param string $serialized * @return void */ final public function unserialize($serialized): void { $this->__unserialize(unserialize($serialized, ['allowed_classes' => $this->getUnserializeAllowedClasses()])); } /** * @return array|bool */ protected function getUnserializeAllowedClasses() { return false; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Logger/Processors/UserProcessor.php
system/src/Grav/Framework/Logger/Processors/UserProcessor.php
<?php /** * @package Grav\Framework\Logger * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Logger\Processors; use Grav\Common\Grav; use Grav\Common\User\Interfaces\UserInterface; use Monolog\Processor\ProcessorInterface; /** * Adds username and email to log messages. */ class UserProcessor implements ProcessorInterface { /** * {@inheritDoc} */ public function __invoke(array $record): array { /** @var UserInterface|null $user */ $user = Grav::instance()['user'] ?? null; if ($user && $user->exists()) { $record['extra']['user'] = ['username' => $user->username, 'email' => $user->email]; } return $record; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/DI/Container.php
system/src/Grav/Framework/DI/Container.php
<?php /** * @package Grav\Framework\DI * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ declare(strict_types=1); namespace Grav\Framework\DI; use Psr\Container\ContainerInterface; class Container extends \Pimple\Container implements ContainerInterface { /** * @param string $id * @return mixed */ public function get($id) { return $this->offsetGet($id); } /** * @param string $id * @return bool */ public function has($id): bool { return $this->offsetExists($id); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Form/FormFlash.php
system/src/Grav/Framework/Form/FormFlash.php
<?php /** * @package Grav\Framework\Form * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Form; use Exception; use Grav\Common\Filesystem\Folder; use Grav\Common\Grav; use Grav\Common\User\Interfaces\UserInterface; use Grav\Common\Utils; use Grav\Framework\Form\Interfaces\FormFlashInterface; use Psr\Http\Message\UploadedFileInterface; use RocketTheme\Toolbox\File\YamlFile; use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator; use RuntimeException; use function func_get_args; use function is_array; /** * Class FormFlash * @package Grav\Framework\Form */ class FormFlash implements FormFlashInterface { /** @var bool */ protected $exists; /** @var string */ protected $id; /** @var string */ protected $sessionId; /** @var string */ protected $uniqueId; /** @var string */ protected $formName; /** @var string */ protected $url; /** @var array|null */ protected $user; /** @var int */ protected $createdTimestamp; /** @var int */ protected $updatedTimestamp; /** @var array|null */ protected $data; /** @var array */ protected $files; /** @var array */ protected $uploadedFiles; /** @var string[] */ protected $uploadObjects; /** @var string */ protected $folder; /** * @inheritDoc */ public function __construct($config) { // Backwards compatibility with Grav 1.6 plugins. if (!is_array($config)) { user_error(__CLASS__ . '::' . __FUNCTION__ . '($sessionId, $uniqueId, $formName) is deprecated since Grav 1.6.11, use $config parameter instead', E_USER_DEPRECATED); $args = func_get_args(); $config = [ 'session_id' => $args[0], 'unique_id' => $args[1] ?? null, 'form_name' => $args[2] ?? null, ]; $config = array_filter($config, static function ($val) { return $val !== null; }); } $this->id = $config['id'] ?? ''; $this->sessionId = $config['session_id'] ?? ''; $this->uniqueId = $config['unique_id'] ?? ''; $this->setUser($config['user'] ?? null); $folder = $config['folder'] ?? ($this->sessionId ? 'tmp://forms/' . $this->sessionId : ''); /** @var UniformResourceLocator $locator */ $locator = Grav::instance()['locator']; $this->folder = $folder && $locator->isStream($folder) ? $locator->findResource($folder, true, true) : $folder; $this->init($this->loadStoredForm(), $config); } /** * @param array|null $data * @param array $config */ protected function init(?array $data, array $config): void { if (null === $data) { $this->exists = false; $this->formName = $config['form_name'] ?? ''; $this->url = ''; $this->createdTimestamp = $this->updatedTimestamp = time(); $this->files = []; } else { $this->exists = true; $this->formName = $data['form'] ?? $config['form_name'] ?? ''; $this->url = $data['url'] ?? ''; $this->user = $data['user'] ?? null; $this->updatedTimestamp = $data['timestamps']['updated'] ?? time(); $this->createdTimestamp = $data['timestamps']['created'] ?? $this->updatedTimestamp; $this->data = $data['data'] ?? null; $this->files = $data['files'] ?? []; } } /** * Load raw flex flash data from the filesystem. * * @return array|null */ protected function loadStoredForm(): ?array { $file = $this->getTmpIndex(); $exists = $file && $file->exists(); $data = null; if ($exists) { try { $data = (array)$file->content(); } catch (Exception $e) { } } return $data; } /** * @inheritDoc */ public function getId(): string { return $this->id && $this->uniqueId ? $this->id . '/' . $this->uniqueId : ''; } /** * @inheritDoc */ public function getSessionId(): string { return $this->sessionId; } /** * @inheritDoc */ public function getUniqueId(): string { return $this->uniqueId; } /** * @return string * @deprecated 1.6.11 Use '->getUniqueId()' method instead. */ public function getUniqieId(): string { user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6.11, use ->getUniqueId() method instead', E_USER_DEPRECATED); return $this->getUniqueId(); } /** * @inheritDoc */ public function getFormName(): string { return $this->formName; } /** * @inheritDoc */ public function getUrl(): string { return $this->url; } /** * @inheritDoc */ public function getUsername(): string { return $this->user['username'] ?? ''; } /** * @inheritDoc */ public function getUserEmail(): string { return $this->user['email'] ?? ''; } /** * @inheritDoc */ public function getCreatedTimestamp(): int { return $this->createdTimestamp; } /** * @inheritDoc */ public function getUpdatedTimestamp(): int { return $this->updatedTimestamp; } /** * @inheritDoc */ public function getData(): ?array { return $this->data; } /** * @inheritDoc */ public function setData(?array $data): void { $this->data = $data; } /** * @inheritDoc */ public function exists(): bool { return $this->exists; } /** * @inheritDoc */ public function save(bool $force = false) { if (!($this->folder && $this->uniqueId)) { return $this; } if ($force || $this->data || $this->files) { // Only save if there is data or files to be saved. $file = $this->getTmpIndex(); if ($file) { $file->save($this->jsonSerialize()); $this->exists = true; } } elseif ($this->exists) { // Delete empty form flash if it exists (it carries no information). return $this->delete(); } return $this; } /** * @inheritDoc */ public function delete() { if ($this->folder && $this->uniqueId) { $this->removeTmpDir(); $this->files = []; $this->exists = false; } return $this; } /** * @inheritDoc */ public function getFilesByField(string $field): array { if (!isset($this->uploadObjects[$field])) { $objects = []; foreach ($this->files[$field] ?? [] as $name => $upload) { $objects[$name] = $upload ? new FormFlashFile($field, $upload, $this) : null; } $this->uploadedFiles[$field] = $objects; } return $this->uploadedFiles[$field]; } /** * @inheritDoc */ public function getFilesByFields($includeOriginal = false): array { $list = []; foreach ($this->files as $field => $values) { if (!$includeOriginal && strpos($field, '/')) { continue; } $list[$field] = $this->getFilesByField($field); } return $list; } /** * @inheritDoc */ public function addUploadedFile(UploadedFileInterface $upload, string $field = null, array $crop = null): string { $tmp_dir = $this->getTmpDir(); $tmp_name = Utils::generateRandomString(12); $name = $upload->getClientFilename(); if (!$name) { throw new RuntimeException('Uploaded file has no filename'); } // Prepare upload data for later save $data = [ 'name' => $name, 'type' => $upload->getClientMediaType(), 'size' => $upload->getSize(), 'tmp_name' => $tmp_name ]; Folder::create($tmp_dir); $upload->moveTo("{$tmp_dir}/{$tmp_name}"); $this->addFileInternal($field, $name, $data, $crop); return $name; } /** * @inheritDoc */ public function addFile(string $filename, string $field, array $crop = null): bool { if (!file_exists($filename)) { throw new RuntimeException("File not found: {$filename}"); } // Prepare upload data for later save $data = [ 'name' => Utils::basename($filename), 'type' => Utils::getMimeByLocalFile($filename), 'size' => filesize($filename), ]; $this->addFileInternal($field, $data['name'], $data, $crop); return true; } /** * @inheritDoc */ public function removeFile(string $name, string $field = null): bool { if (!$name) { return false; } $field = $field ?: 'undefined'; $upload = $this->files[$field][$name] ?? null; if (null !== $upload) { $this->removeTmpFile($upload['tmp_name'] ?? ''); } $upload = $this->files[$field . '/original'][$name] ?? null; if (null !== $upload) { $this->removeTmpFile($upload['tmp_name'] ?? ''); } // Mark file as deleted. $this->files[$field][$name] = null; $this->files[$field . '/original'][$name] = null; unset( $this->uploadedFiles[$field][$name], $this->uploadedFiles[$field . '/original'][$name] ); return true; } /** * @inheritDoc */ public function clearFiles() { foreach ($this->files as $files) { foreach ($files as $upload) { $this->removeTmpFile($upload['tmp_name'] ?? ''); } } $this->files = []; } /** * @inheritDoc */ public function jsonSerialize(): array { return [ 'form' => $this->formName, 'id' => $this->getId(), 'unique_id' => $this->uniqueId, 'url' => $this->url, 'user' => $this->user, 'timestamps' => [ 'created' => $this->createdTimestamp, 'updated' => time(), ], 'data' => $this->data, 'files' => $this->files ]; } /** * @param string $url * @return $this */ public function setUrl(string $url): self { $this->url = $url; return $this; } /** * @param UserInterface|null $user * @return $this */ public function setUser(UserInterface $user = null) { if ($user && $user->username) { $this->user = [ 'username' => $user->username, 'email' => $user->email ?? '' ]; } else { $this->user = null; } return $this; } /** * @param string|null $username * @return $this */ public function setUserName(string $username = null): self { $this->user['username'] = $username; return $this; } /** * @param string|null $email * @return $this */ public function setUserEmail(string $email = null): self { $this->user['email'] = $email; return $this; } /** * @return string */ public function getTmpDir(): string { return $this->folder && $this->uniqueId ? "{$this->folder}/{$this->uniqueId}" : ''; } /** * @return ?YamlFile */ protected function getTmpIndex(): ?YamlFile { $tmpDir = $this->getTmpDir(); // Do not use CompiledYamlFile as the file can change multiple times per second. return $tmpDir ? YamlFile::instance($tmpDir . '/index.yaml') : null; } /** * @param string $name */ protected function removeTmpFile(string $name): void { $tmpDir = $this->getTmpDir(); $filename = $tmpDir ? $tmpDir . '/' . $name : ''; if ($name && $filename && is_file($filename)) { unlink($filename); } } /** * @return void */ protected function removeTmpDir(): void { // Make sure that index file cache gets always cleared. $file = $this->getTmpIndex(); if ($file) { $file->free(); } $tmpDir = $this->getTmpDir(); if ($tmpDir && file_exists($tmpDir)) { Folder::delete($tmpDir); } } /** * @param string|null $field * @param string $name * @param array $data * @param array|null $crop * @return void */ protected function addFileInternal(?string $field, string $name, array $data, array $crop = null): void { if (!($this->folder && $this->uniqueId)) { throw new RuntimeException('Cannot upload files: form flash folder not defined'); } $field = $field ?: 'undefined'; if (!isset($this->files[$field])) { $this->files[$field] = []; } $oldUpload = $this->files[$field][$name] ?? null; if ($crop) { // Deal with crop upload if ($oldUpload) { $originalUpload = $this->files[$field . '/original'][$name] ?? null; if ($originalUpload) { // If there is original file already present, remove the modified file $this->files[$field . '/original'][$name]['crop'] = $crop; $this->removeTmpFile($oldUpload['tmp_name'] ?? ''); } else { // Otherwise make the previous file as original $oldUpload['crop'] = $crop; $this->files[$field . '/original'][$name] = $oldUpload; } } else { $this->files[$field . '/original'][$name] = [ 'name' => $name, 'type' => $data['type'], 'crop' => $crop ]; } } else { // Deal with replacing upload $originalUpload = $this->files[$field . '/original'][$name] ?? null; $this->files[$field . '/original'][$name] = null; $this->removeTmpFile($oldUpload['tmp_name'] ?? ''); $this->removeTmpFile($originalUpload['tmp_name'] ?? ''); } // Prepare data to be saved later $this->files[$field][$name] = $data; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Form/FormFlashFile.php
system/src/Grav/Framework/Form/FormFlashFile.php
<?php /** * @package Grav\Framework\Form * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Form; use Grav\Common\Security; use Grav\Common\Utils; use Grav\Framework\Psr7\Stream; use InvalidArgumentException; use JsonSerializable; use Psr\Http\Message\StreamInterface; use Psr\Http\Message\UploadedFileInterface; use RuntimeException; use function copy; use function fopen; use function is_string; use function sprintf; /** * Class FormFlashFile * @package Grav\Framework\Form */ class FormFlashFile implements UploadedFileInterface, JsonSerializable { /** @var string */ private $id; /** @var string */ private $field; /** @var bool */ private $moved = false; /** @var array */ private $upload; /** @var FormFlash */ private $flash; /** * FormFlashFile constructor. * @param string $field * @param array $upload * @param FormFlash $flash */ public function __construct(string $field, array $upload, FormFlash $flash) { $this->id = $flash->getId() ?: $flash->getUniqueId(); $this->field = $field; $this->upload = $upload; $this->flash = $flash; $tmpFile = $this->getTmpFile(); if (!$tmpFile && $this->isOk()) { $this->upload['error'] = \UPLOAD_ERR_NO_FILE; } if (!isset($this->upload['size'])) { $this->upload['size'] = $tmpFile && $this->isOk() ? filesize($tmpFile) : 0; } } /** * @return StreamInterface */ public function getStream() { $this->validateActive(); $tmpFile = $this->getTmpFile(); if (null === $tmpFile) { throw new RuntimeException('No temporary file'); } $resource = fopen($tmpFile, 'rb'); if (false === $resource) { throw new RuntimeException('No temporary file'); } return Stream::create($resource); } /** * @param string $targetPath * @return void */ public function moveTo($targetPath) { $this->validateActive(); if (!is_string($targetPath) || empty($targetPath)) { throw new InvalidArgumentException('Invalid path provided for move operation; must be a non-empty string'); } $tmpFile = $this->getTmpFile(); if (null === $tmpFile) { throw new RuntimeException('No temporary file'); } $this->moved = copy($tmpFile, $targetPath); if (false === $this->moved) { throw new RuntimeException(sprintf('Uploaded file could not be moved to %s', $targetPath)); } $filename = $this->getClientFilename(); if ($filename) { $this->flash->removeFile($filename, $this->field); } } public function getId(): string { return $this->id; } /** * @return string */ public function getField(): string { return $this->field; } /** * @return int */ public function getSize() { return $this->upload['size']; } /** * @return int */ public function getError() { return $this->upload['error'] ?? \UPLOAD_ERR_OK; } /** * @return string */ public function getClientFilename() { return $this->upload['name'] ?? 'unknown'; } /** * @return string */ public function getClientMediaType() { return $this->upload['type'] ?? 'application/octet-stream'; } /** * @return bool */ public function isMoved(): bool { return $this->moved; } /** * @return array */ public function getMetaData(): array { if (isset($this->upload['crop'])) { return ['crop' => $this->upload['crop']]; } return []; } /** * @return string */ public function getDestination() { return $this->upload['path'] ?? ''; } /** * @return array */ #[\ReturnTypeWillChange] public function jsonSerialize() { return $this->upload; } /** * @return void */ public function checkXss(): void { $tmpFile = $this->getTmpFile(); $mime = $this->getClientMediaType(); if (Utils::contains($mime, 'svg', false)) { $response = Security::detectXssFromSvgFile($tmpFile); if ($response) { throw new RuntimeException(sprintf('SVG file XSS check failed on %s', $response)); } } } /** * @return string|null */ public function getTmpFile(): ?string { $tmpName = $this->upload['tmp_name'] ?? null; if (!$tmpName) { return null; } $tmpFile = $this->flash->getTmpDir() . '/' . $tmpName; return file_exists($tmpFile) ? $tmpFile : null; } /** * @return array */ #[\ReturnTypeWillChange] public function __debugInfo() { return [ 'id:private' => $this->id, 'field:private' => $this->field, 'moved:private' => $this->moved, 'upload:private' => $this->upload, ]; } /** * @return void * @throws RuntimeException if is moved or not ok */ private function validateActive(): void { if (!$this->isOk()) { throw new RuntimeException('Cannot retrieve stream due to upload error'); } if ($this->moved) { throw new RuntimeException('Cannot retrieve stream after it has already been moved'); } if (!$this->getTmpFile()) { throw new RuntimeException('Cannot retrieve stream as the file is missing'); } } /** * @return bool return true if there is no upload error */ private function isOk(): bool { return \UPLOAD_ERR_OK === $this->getError(); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Form/Interfaces/FormFlashInterface.php
system/src/Grav/Framework/Form/Interfaces/FormFlashInterface.php
<?php /** * @package Grav\Framework\Form * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Form\Interfaces; use Psr\Http\Message\UploadedFileInterface; /** * Interface FormFlashInterface * @package Grav\Framework\Form\Interfaces */ interface FormFlashInterface extends \JsonSerializable { /** * @param array $config Available configuration keys: session_id, unique_id, form_name */ public function __construct($config); /** * Get unique form flash id if set. * * @return string */ public function getId(): string; /** * Get session Id associated to this form instance. * * @return string */ public function getSessionId(): string; /** * Get unique identifier associated to this form instance. * * @return string */ public function getUniqueId(): string; /** * Get form name associated to this form instance. * * @return string */ public function getFormName(): string; /** * Get URL associated to this form instance. * * @return string */ public function getUrl(): string; /** * Get username from the user who was associated to this form instance. * * @return string */ public function getUsername(): string; /** * Get email from the user who was associated to this form instance. * * @return string */ public function getUserEmail(): string; /** * Get creation timestamp for this form flash. * * @return int */ public function getCreatedTimestamp(): int; /** * Get last updated timestamp for this form flash. * * @return int */ public function getUpdatedTimestamp(): int; /** * Get raw form data. * * @return array|null */ public function getData(): ?array; /** * Set raw form data. * * @param array|null $data * @return void */ public function setData(?array $data): void; /** * Check if this form flash exists. * * @return bool */ public function exists(): bool; /** * Save this form flash. * * @return $this */ public function save(); /** * Delete this form flash. * * @return $this */ public function delete(); /** * Get all files associated to a form field. * * @param string $field * @return array */ public function getFilesByField(string $field): array; /** * Get all files grouped by the associated form fields. * * @param bool $includeOriginal * @return array */ public function getFilesByFields($includeOriginal = false): array; /** * Add uploaded file to the form flash. * * @param UploadedFileInterface $upload * @param string|null $field * @param array|null $crop * @return string Return name of the file */ public function addUploadedFile(UploadedFileInterface $upload, string $field = null, array $crop = null): string; /** * Add existing file to the form flash. * * @param string $filename * @param string $field * @param array|null $crop * @return bool */ public function addFile(string $filename, string $field, array $crop = null): bool; /** * Remove any file from form flash. * * @param string $name * @param string|null $field * @return bool */ public function removeFile(string $name, string $field = null): bool; /** * Clear form flash from all uploaded files. * * @return void */ public function clearFiles(); /** * @return array */ public function jsonSerialize(): array; }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Form/Interfaces/FormFactoryInterface.php
system/src/Grav/Framework/Form/Interfaces/FormFactoryInterface.php
<?php declare(strict_types=1); /** * @package Grav\Framework\Form * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Form\Interfaces; use Grav\Common\Page\Interfaces\PageInterface; use Grav\Common\Page\Page; /** * Interface FormFactoryInterface * @package Grav\Framework\Form\Interfaces */ interface FormFactoryInterface { /** * @param Page $page * @param string $name * @param array $form * @return FormInterface|null * @deprecated 1.6 Use FormFactory::createFormByPage() instead. */ public function createPageForm(Page $page, string $name, array $form): ?FormInterface; /** * Create form using the header of the page. * * @param PageInterface $page * @param string $name * @param array $form * @return FormInterface|null * public function createFormForPage(PageInterface $page, string $name, array $form): ?FormInterface; */ }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Form/Interfaces/FormInterface.php
system/src/Grav/Framework/Form/Interfaces/FormInterface.php
<?php /** * @package Grav\Framework\Form * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Form\Interfaces; use Grav\Common\Data\Blueprint; use Grav\Common\Data\Data; use Grav\Framework\Interfaces\RenderInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\UploadedFileInterface; /** * Interface FormInterface * @package Grav\Framework\Form */ interface FormInterface extends RenderInterface, \Serializable { /** * Get HTML id="..." attribute. * * @return string */ public function getId(): string; /** * Sets HTML id="" attribute. * * @param string $id */ public function setId(string $id): void; /** * Get unique id for the current form instance. By default regenerated on every page reload. * * This id is used to load the saved form state, if available. * * @return string */ public function getUniqueId(): string; /** * Sets unique form id. * * @param string $uniqueId */ public function setUniqueId(string $uniqueId): void; /** * @return string */ public function getName(): string; /** * Get form name. * * @return string */ public function getFormName(): string; /** * Get nonce name. * * @return string */ public function getNonceName(): string; /** * Get nonce action. * * @return string */ public function getNonceAction(): string; /** * Get the nonce value for a form * * @return string */ public function getNonce(): string; /** * Get task for the form if set in blueprints. * * @return string */ public function getTask(): string; /** * Get form action (URL). If action is empty, it points to the current page. * * @return string */ public function getAction(): string; /** * Get current data passed to the form. * * @return Data|object */ public function getData(); /** * Get files which were passed to the form. * * @return array|UploadedFileInterface[] */ public function getFiles(): array; /** * Get a value from the form. * * Note: Used in form fields. * * @param string $name * @return mixed */ public function getValue(string $name); /** * Get form flash object. * * @return FormFlashInterface */ public function getFlash(); /** * @param ServerRequestInterface $request * @return $this */ public function handleRequest(ServerRequestInterface $request): FormInterface; /** * @param array $data * @param UploadedFileInterface[]|null $files * @return $this */ public function submit(array $data, array $files = null): FormInterface; /** * @return bool */ public function isValid(): bool; /** * @return string */ public function getError(): ?string; /** * @return array */ public function getErrors(): array; /** * @return bool */ public function isSubmitted(): bool; /** * Reset form. * * @return void */ public function reset(): void; /** * Get form fields as an array. * * Note: Used in form fields. * * @return array */ public function getFields(): array; /** * Get blueprint used in the form. * * @return Blueprint */ public function getBlueprint(): Blueprint; }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Form/Traits/FormTrait.php
system/src/Grav/Framework/Form/Traits/FormTrait.php
<?php /** * @package Grav\Framework\Form * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Form\Traits; use ArrayAccess; use Exception; use FilesystemIterator; use Grav\Common\Data\Blueprint; use Grav\Common\Data\Data; use Grav\Common\Data\ValidationException; use Grav\Common\Debugger; use Grav\Common\Form\FormFlash; use Grav\Common\Grav; use Grav\Common\Twig\Twig; use Grav\Common\User\Interfaces\UserInterface; use Grav\Common\Utils; use Grav\Framework\Compat\Serializable; use Grav\Framework\ContentBlock\HtmlBlock; use Grav\Framework\Form\FormFlashFile; use Grav\Framework\Form\Interfaces\FormFlashInterface; use Grav\Framework\Form\Interfaces\FormInterface; use Grav\Framework\Session\SessionInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\UploadedFileInterface; use RuntimeException; use SplFileInfo; use Twig\Error\LoaderError; use Twig\Error\SyntaxError; use Twig\Template; use Twig\TemplateWrapper; use function in_array; use function is_array; use function is_object; /** * Trait FormTrait * @package Grav\Framework\Form */ trait FormTrait { use Serializable; /** @var string */ public $status = 'success'; /** @var string|null */ public $message; /** @var string[] */ public $messages = []; /** @var string */ private $name; /** @var string */ private $id; /** @var bool */ private $enabled = true; /** @var string */ private $uniqueid; /** @var string */ private $sessionid; /** @var bool */ private $submitted; /** @var ArrayAccess<string,mixed>|Data|null */ private $data; /** @var UploadedFileInterface[] */ private $files = []; /** @var FormFlashInterface|null */ private $flash; /** @var string */ private $flashFolder; /** @var Blueprint */ private $blueprint; /** * @return string */ public function getId(): string { return $this->id; } /** * @param string $id */ public function setId(string $id): void { $this->id = $id; } /** * @return void */ public function disable(): void { $this->enabled = false; } /** * @return void */ public function enable(): void { $this->enabled = true; } /** * @return bool */ public function isEnabled(): bool { return $this->enabled; } /** * @return string */ public function getUniqueId(): string { return $this->uniqueid; } /** * @param string $uniqueId * @return void */ public function setUniqueId(string $uniqueId): void { $this->uniqueid = $uniqueId; } /** * @return string */ public function getName(): string { return $this->name; } /** * @return string */ public function getFormName(): string { return $this->name; } /** * @return string */ public function getNonceName(): string { return 'form-nonce'; } /** * @return string */ public function getNonceAction(): string { return 'form'; } /** * @return string */ public function getNonce(): string { return Utils::getNonce($this->getNonceAction()); } /** * @return string */ public function getAction(): string { return ''; } /** * @return string */ public function getTask(): string { return $this->getBlueprint()->get('form/task') ?? ''; } /** * @param string|null $name * @return mixed */ public function getData(string $name = null) { return null !== $name ? $this->data[$name] : $this->data; } /** * @return array|UploadedFileInterface[] */ public function getFiles(): array { return $this->files; } /** * @param string $name * @return mixed|null */ public function getValue(string $name) { return $this->data[$name] ?? null; } /** * @param string $name * @return mixed|null */ public function getDefaultValue(string $name) { $path = explode('.', $name); $offset = array_shift($path); $current = $this->getDefaultValues(); if (!isset($current[$offset])) { return null; } $current = $current[$offset]; while ($path) { $offset = array_shift($path); if ((is_array($current) || $current instanceof ArrayAccess) && isset($current[$offset])) { $current = $current[$offset]; } elseif (is_object($current) && isset($current->{$offset})) { $current = $current->{$offset}; } else { return null; } }; return $current; } /** * @return array */ public function getDefaultValues(): array { return $this->getBlueprint()->getDefaults(); } /** * @param ServerRequestInterface $request * @return FormInterface|$this */ public function handleRequest(ServerRequestInterface $request): FormInterface { // Set current form to be active. $grav = Grav::instance(); $forms = $grav['forms'] ?? null; if ($forms) { $forms->setActiveForm($this); /** @var Twig $twig */ $twig = $grav['twig']; $twig->twig_vars['form'] = $this; } try { [$data, $files] = $this->parseRequest($request); $this->submit($data, $files); } catch (Exception $e) { /** @var Debugger $debugger */ $debugger = $grav['debugger']; $debugger->addException($e); $this->setError($e->getMessage()); } return $this; } /** * @param ServerRequestInterface $request * @return FormInterface|$this */ public function setRequest(ServerRequestInterface $request): FormInterface { [$data, $files] = $this->parseRequest($request); $this->data = new Data($data, $this->getBlueprint()); $this->files = $files; return $this; } /** * @return bool */ public function isValid(): bool { return $this->status === 'success'; } /** * @return string|null */ public function getError(): ?string { return !$this->isValid() ? $this->message : null; } /** * @return array */ public function getErrors(): array { return !$this->isValid() ? $this->messages : []; } /** * @return bool */ public function isSubmitted(): bool { return $this->submitted; } /** * @return bool */ public function validate(): bool { if (!$this->isValid()) { return false; } try { $this->validateData($this->data); $this->validateUploads($this->getFiles()); } catch (ValidationException $e) { $this->setErrors($e->getMessages()); } catch (Exception $e) { /** @var Debugger $debugger */ $debugger = Grav::instance()['debugger']; $debugger->addException($e); $this->setError($e->getMessage()); } $this->filterData($this->data); return $this->isValid(); } /** * @param array $data * @param UploadedFileInterface[]|null $files * @return FormInterface|$this */ public function submit(array $data, array $files = null): FormInterface { try { if ($this->isSubmitted()) { throw new RuntimeException('Form has already been submitted'); } $this->data = new Data($data, $this->getBlueprint()); $this->files = $files ?? []; if (!$this->validate()) { return $this; } $this->doSubmit($this->data->toArray(), $this->files); $this->submitted = true; } catch (Exception $e) { /** @var Debugger $debugger */ $debugger = Grav::instance()['debugger']; $debugger->addException($e); $this->setError($e->getMessage()); } return $this; } /** * @return void */ public function reset(): void { // Make sure that the flash object gets deleted. $this->getFlash()->delete(); $this->data = null; $this->files = []; $this->status = 'success'; $this->message = null; $this->messages = []; $this->submitted = false; $this->flash = null; } /** * @return array */ public function getFields(): array { return $this->getBlueprint()->fields(); } /** * @return array */ public function getButtons(): array { return $this->getBlueprint()->get('form/buttons') ?? []; } /** * @return array */ public function getTasks(): array { return $this->getBlueprint()->get('form/tasks') ?? []; } /** * @return Blueprint */ abstract public function getBlueprint(): Blueprint; /** * Get form flash object. * * @return FormFlashInterface */ public function getFlash() { if (null === $this->flash) { $grav = Grav::instance(); $config = [ 'session_id' => $this->getSessionId(), 'unique_id' => $this->getUniqueId(), 'form_name' => $this->getName(), 'folder' => $this->getFlashFolder(), 'id' => $this->getFlashId() ]; $this->flash = new FormFlash($config); $this->flash->setUrl($grav['uri']->url)->setUser($grav['user'] ?? null); } return $this->flash; } /** * Get all available form flash objects for this form. * * @return FormFlashInterface[] */ public function getAllFlashes(): array { $folder = $this->getFlashFolder(); if (!$folder || !is_dir($folder)) { return []; } $name = $this->getName(); $list = []; /** @var SplFileInfo $file */ foreach (new FilesystemIterator($folder) as $file) { $uniqueId = $file->getFilename(); $config = [ 'session_id' => $this->getSessionId(), 'unique_id' => $uniqueId, 'form_name' => $name, 'folder' => $this->getFlashFolder(), 'id' => $this->getFlashId() ]; $flash = new FormFlash($config); if ($flash->exists() && $flash->getFormName() === $name) { $list[] = $flash; } } return $list; } /** * {@inheritdoc} * @see FormInterface::render() */ public function render(string $layout = null, array $context = []) { if (null === $layout) { $layout = 'default'; } $grav = Grav::instance(); $block = HtmlBlock::create(); $block->disableCache(); $output = $this->getTemplate($layout)->render( ['grav' => $grav, 'config' => $grav['config'], 'block' => $block, 'form' => $this, 'layout' => $layout] + $context ); $block->setContent($output); return $block; } /** * @return array */ public function jsonSerialize(): array { return $this->doSerialize(); } /** * @return array */ final public function __serialize(): array { return $this->doSerialize(); } /** * @param array $data * @return void */ final public function __unserialize(array $data): void { $this->doUnserialize($data); } protected function getSessionId(): string { if (null === $this->sessionid) { /** @var Grav $grav */ $grav = Grav::instance(); /** @var SessionInterface|null $session */ $session = $grav['session'] ?? null; $this->sessionid = $session ? ($session->getId() ?? '') : ''; } return $this->sessionid; } /** * @param string $sessionId * @return void */ protected function setSessionId(string $sessionId): void { $this->sessionid = $sessionId; } /** * @return void */ protected function unsetFlash(): void { $this->flash = null; } /** * @return string|null */ protected function getFlashFolder(): ?string { $grav = Grav::instance(); /** @var UserInterface|null $user */ $user = $grav['user'] ?? null; if (null !== $user && $user->exists()) { $username = $user->username; $mediaFolder = $user->getMediaFolder(); } else { $username = null; $mediaFolder = null; } $session = $grav['session'] ?? null; $sessionId = $session ? $session->getId() : null; // Fill template token keys/value pairs. $dataMap = [ '[FORM_NAME]' => $this->getName(), '[SESSIONID]' => $sessionId ?? '!!', '[USERNAME]' => $username ?? '!!', '[USERNAME_OR_SESSIONID]' => $username ?? $sessionId ?? '!!', '[ACCOUNT]' => $mediaFolder ?? '!!' ]; $flashLookupFolder = $this->getFlashLookupFolder(); $path = str_replace(array_keys($dataMap), array_values($dataMap), $flashLookupFolder); // Make sure we only return valid paths. return strpos($path, '!!') === false ? rtrim($path, '/') : null; } /** * @return string|null */ protected function getFlashId(): ?string { // Fill template token keys/value pairs. $dataMap = [ '[FORM_NAME]' => $this->getName(), '[SESSIONID]' => 'session', '[USERNAME]' => '!!', '[USERNAME_OR_SESSIONID]' => '!!', '[ACCOUNT]' => 'account' ]; $flashLookupFolder = $this->getFlashLookupFolder(); $path = str_replace(array_keys($dataMap), array_values($dataMap), $flashLookupFolder); // Make sure we only return valid paths. return strpos($path, '!!') === false ? rtrim($path, '/') : null; } /** * @return string */ protected function getFlashLookupFolder(): string { if (null === $this->flashFolder) { $this->flashFolder = $this->getBlueprint()->get('form/flash_folder') ?? 'tmp://forms/[SESSIONID]'; } return $this->flashFolder; } /** * @param string $folder * @return void */ protected function setFlashLookupFolder(string $folder): void { $this->flashFolder = $folder; } /** * Set a single error. * * @param string $error * @return void */ protected function setError(string $error): void { $this->status = 'error'; $this->message = $error; } /** * Set all errors. * * @param array $errors * @return void */ protected function setErrors(array $errors): void { $this->status = 'error'; $this->messages = $errors; } /** * @param string $layout * @return Template|TemplateWrapper * @throws LoaderError * @throws SyntaxError */ protected function getTemplate($layout) { $grav = Grav::instance(); /** @var Twig $twig */ $twig = $grav['twig']; return $twig->twig()->resolveTemplate( [ "forms/{$layout}/form.html.twig", 'forms/default/form.html.twig' ] ); } /** * Parse PSR-7 ServerRequest into data and files. * * @param ServerRequestInterface $request * @return array */ protected function parseRequest(ServerRequestInterface $request): array { $method = $request->getMethod(); if (!in_array($method, ['PUT', 'POST', 'PATCH'])) { throw new RuntimeException(sprintf('FlexForm: Bad HTTP method %s', $method)); } $body = (array)$request->getParsedBody(); $data = isset($body['data']) ? $this->decodeData($body['data']) : null; $flash = $this->getFlash(); /* if (null !== $data) { $flash->setData($data); $flash->save(); } */ $blueprint = $this->getBlueprint(); $includeOriginal = (bool)($blueprint->form()['images']['original'] ?? null); $files = $flash->getFilesByFields($includeOriginal); $data = $blueprint->processForm($data ?? [], $body['toggleable_data'] ?? []); return [ $data, $files ]; } /** * Validate data and throw validation exceptions if validation fails. * * @param ArrayAccess|Data|null $data * @return void * @throws ValidationException * @phpstan-param ArrayAccess<string,mixed>|Data|null $data * @throws Exception */ protected function validateData($data = null): void { if ($data instanceof Data) { $data->validate(); } } /** * Filter validated data. * * @param ArrayAccess|Data|null $data * @return void * @phpstan-param ArrayAccess<string,mixed>|Data|null $data */ protected function filterData($data = null): void { if ($data instanceof Data) { $data->filter(); } } /** * Validate all uploaded files. * * @param array $files * @return void */ protected function validateUploads(array $files): void { foreach ($files as $file) { if (null === $file) { continue; } if ($file instanceof UploadedFileInterface) { $this->validateUpload($file); } else { $this->validateUploads($file); } } } /** * Validate uploaded file. * * @param UploadedFileInterface $file * @return void */ protected function validateUpload(UploadedFileInterface $file): void { // Handle bad filenames. $filename = $file->getClientFilename(); if ($filename && !Utils::checkFilename($filename)) { $grav = Grav::instance(); throw new RuntimeException( sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_UPLOAD', null, true), $filename, 'Bad filename') ); } if ($file instanceof FormFlashFile) { $file->checkXss(); } } /** * Decode POST data * * @param array $data * @return array */ protected function decodeData($data): array { if (!is_array($data)) { return []; } // Decode JSON encoded fields and merge them to data. if (isset($data['_json'])) { $data = array_replace_recursive($data, $this->jsonDecode($data['_json'])); unset($data['_json']); } return $data; } /** * Recursively JSON decode POST data. * * @param array $data * @return array */ protected function jsonDecode(array $data): array { foreach ($data as $key => &$value) { if (is_array($value)) { $value = $this->jsonDecode($value); } elseif (trim($value) === '') { unset($data[$key]); } else { $value = json_decode($value, true); if ($value === null && json_last_error() !== JSON_ERROR_NONE) { unset($data[$key]); $this->setError("Badly encoded JSON data (for {$key}) was sent to the form"); } } } return $data; } /** * @return array */ protected function doSerialize(): array { $data = $this->data instanceof Data ? $this->data->toArray() : null; return [ 'name' => $this->name, 'id' => $this->id, 'uniqueid' => $this->uniqueid, 'submitted' => $this->submitted, 'status' => $this->status, 'message' => $this->message, 'messages' => $this->messages, 'data' => $data, 'files' => $this->files, ]; } /** * @param array $data * @return void */ protected function doUnserialize(array $data): void { $this->name = $data['name']; $this->id = $data['id']; $this->uniqueid = $data['uniqueid']; $this->submitted = $data['submitted'] ?? false; $this->status = $data['status'] ?? 'success'; $this->message = $data['message'] ?? null; $this->messages = $data['messages'] ?? []; $this->data = isset($data['data']) ? new Data($data['data'], $this->getBlueprint()) : null; $this->files = $data['files'] ?? []; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Collection/FileCollectionInterface.php
system/src/Grav/Framework/Collection/FileCollectionInterface.php
<?php /** * @package Grav\Framework\Collection * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Collection; use Doctrine\Common\Collections\Selectable; /** * Collection of objects stored into a filesystem. * * @package Grav\Framework\Collection * @template TKey of array-key * @template T * @extends CollectionInterface<TKey,T> * @extends Selectable<TKey,T> */ interface FileCollectionInterface extends CollectionInterface, Selectable { public const INCLUDE_FILES = 1; public const INCLUDE_FOLDERS = 2; public const RECURSIVE = 4; /** * @return string */ public function getPath(); }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Collection/CollectionInterface.php
system/src/Grav/Framework/Collection/CollectionInterface.php
<?php /** * @package Grav\Framework\Collection * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Collection; use Doctrine\Common\Collections\Collection; use JsonSerializable; /** * Collection Interface. * * @package Grav\Framework\Collection * @template TKey of array-key * @template T * @extends Collection<TKey,T> */ interface CollectionInterface extends Collection, JsonSerializable { /** * Reverse the order of the items. * * @return CollectionInterface * @phpstan-return static<TKey,T> */ public function reverse(); /** * Shuffle items. * * @return CollectionInterface * @phpstan-return static<TKey,T> */ public function shuffle(); /** * Split collection into chunks. * * @param int $size Size of each chunk. * @return array * @phpstan-return array<array<TKey,T>> */ public function chunk($size); /** * Select items from collection. * * Collection is returned in the order of $keys given to the function. * * @param array<int|string> $keys * @return CollectionInterface * @phpstan-return static<TKey,T> */ public function select(array $keys); /** * Un-select items from collection. * * @param array<int|string> $keys * @return CollectionInterface * @phpstan-return static<TKey,T> */ public function unselect(array $keys); }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Collection/FileCollection.php
system/src/Grav/Framework/Collection/FileCollection.php
<?php /** * @package Grav\Framework\Collection * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Collection; use stdClass; /** * Collection of objects stored into a filesystem. * * @package Grav\Framework\Collection * @extends AbstractFileCollection<array-key,stdClass> */ class FileCollection extends AbstractFileCollection { /** * @param string $path * @param int $flags */ public function __construct($path, $flags = null) { parent::__construct($path); $this->flags = (int)($flags ?: self::INCLUDE_FILES | self::INCLUDE_FOLDERS | self::RECURSIVE); $this->setIterator(); $this->setFilter(); $this->setObjectBuilder(); $this->setNestingLimit(); } /** * @return int */ public function getFlags() { return $this->flags; } /** * @return int */ public function getNestingLimit() { return $this->nestingLimit; } /** * @param int $limit * @return $this */ public function setNestingLimit($limit = 99) { $this->nestingLimit = (int) $limit; return $this; } /** * @param callable|null $filterFunction * @return $this */ public function setFilter(callable $filterFunction = null) { $this->filterFunction = $filterFunction; return $this; } /** * @param callable $filterFunction * @return $this */ public function addFilter(callable $filterFunction) { parent::addFilter($filterFunction); return $this; } /** * @param callable|null $objectFunction * @return $this */ public function setObjectBuilder(callable $objectFunction = null) { $this->createObjectFunction = $objectFunction ?: [$this, 'createObject']; return $this; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Collection/AbstractFileCollection.php
system/src/Grav/Framework/Collection/AbstractFileCollection.php
<?php /** * @package Grav\Framework\Collection * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Collection; use Doctrine\Common\Collections\Criteria; use Doctrine\Common\Collections\Expr\ClosureExpressionVisitor; use FilesystemIterator; use Grav\Common\Grav; use RecursiveDirectoryIterator; use RocketTheme\Toolbox\ResourceLocator\RecursiveUniformResourceIterator; use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator; use RuntimeException; use SeekableIterator; use function array_slice; /** * Collection of objects stored into a filesystem. * * @package Grav\Framework\Collection * @template TKey of array-key * @template T of object * @extends AbstractLazyCollection<TKey,T> * @implements FileCollectionInterface<TKey,T> */ class AbstractFileCollection extends AbstractLazyCollection implements FileCollectionInterface { /** @var string */ protected $path; /** @var RecursiveDirectoryIterator|RecursiveUniformResourceIterator */ protected $iterator; /** @var callable */ protected $createObjectFunction; /** @var callable|null */ protected $filterFunction; /** @var int */ protected $flags; /** @var int */ protected $nestingLimit; /** * @param string $path */ protected function __construct($path) { $this->path = $path; $this->flags = self::INCLUDE_FILES | self::INCLUDE_FOLDERS; $this->nestingLimit = 0; $this->createObjectFunction = [$this, 'createObject']; $this->setIterator(); } /** * @return string */ public function getPath() { return $this->path; } /** * @param Criteria $criteria * @return ArrayCollection * @phpstan-return ArrayCollection<TKey,T> * @todo Implement lazy matching */ public function matching(Criteria $criteria) { $expr = $criteria->getWhereExpression(); $oldFilter = $this->filterFunction; if ($expr) { $visitor = new ClosureExpressionVisitor(); $filter = $visitor->dispatch($expr); $this->addFilter($filter); } $filtered = $this->doInitializeByIterator($this->iterator, $this->nestingLimit); $this->filterFunction = $oldFilter; if ($orderings = $criteria->getOrderings()) { $next = null; /** * @var string $field * @var string $ordering */ foreach (array_reverse($orderings) as $field => $ordering) { $next = ClosureExpressionVisitor::sortByField($field, $ordering === Criteria::DESC ? -1 : 1, $next); } /** @phpstan-ignore-next-line */ if (null === $next) { throw new RuntimeException('Criteria is missing orderings'); } uasort($filtered, $next); } else { ksort($filtered); } $offset = $criteria->getFirstResult(); $length = $criteria->getMaxResults(); if ($offset || $length) { $filtered = array_slice($filtered, (int)$offset, $length); } return new ArrayCollection($filtered); } /** * @return void */ protected function setIterator() { $iteratorFlags = RecursiveDirectoryIterator::SKIP_DOTS + FilesystemIterator::UNIX_PATHS + FilesystemIterator::CURRENT_AS_SELF + FilesystemIterator::FOLLOW_SYMLINKS; if (strpos($this->path, '://')) { /** @var UniformResourceLocator $locator */ $locator = Grav::instance()['locator']; $this->iterator = $locator->getRecursiveIterator($this->path, $iteratorFlags); } else { $this->iterator = new RecursiveDirectoryIterator($this->path, $iteratorFlags); } } /** * @param callable $filterFunction * @return $this */ protected function addFilter(callable $filterFunction) { if ($this->filterFunction) { $oldFilterFunction = $this->filterFunction; $this->filterFunction = function ($expr) use ($oldFilterFunction, $filterFunction) { return $oldFilterFunction($expr) && $filterFunction($expr); }; } else { $this->filterFunction = $filterFunction; } return $this; } /** * {@inheritDoc} */ protected function doInitialize() { $filtered = $this->doInitializeByIterator($this->iterator, $this->nestingLimit); ksort($filtered); $this->collection = new ArrayCollection($filtered); } /** * @param SeekableIterator $iterator * @param int $nestingLimit * @return array * @phpstan-param SeekableIterator<int,T> $iterator */ protected function doInitializeByIterator(SeekableIterator $iterator, $nestingLimit) { $children = []; $objects = []; $filter = $this->filterFunction; $objectFunction = $this->createObjectFunction; /** @var RecursiveDirectoryIterator $file */ foreach ($iterator as $file) { // Skip files if they shouldn't be included. if (!($this->flags & static::INCLUDE_FILES) && $file->isFile()) { continue; } // Apply main filter. if ($filter && !$filter($file)) { continue; } // Include children if the recursive flag is set. if (($this->flags & static::RECURSIVE) && $nestingLimit > 0 && $file->hasChildren()) { $children[] = $file->getChildren(); } // Skip folders if they shouldn't be included. if (!($this->flags & static::INCLUDE_FOLDERS) && $file->isDir()) { continue; } $object = $objectFunction($file); $objects[$object->key] = $object; } if ($children) { $objects += $this->doInitializeChildren($children, $nestingLimit - 1); } return $objects; } /** * @param array $children * @param int $nestingLimit * @return array */ protected function doInitializeChildren(array $children, $nestingLimit) { $objects = []; foreach ($children as $iterator) { $objects += $this->doInitializeByIterator($iterator, $nestingLimit); } return $objects; } /** * @param RecursiveDirectoryIterator $file * @return object */ protected function createObject($file) { return (object) [ 'key' => $file->getSubPathname(), 'type' => $file->isDir() ? 'folder' : 'file:' . $file->getExtension(), 'url' => method_exists($file, 'getUrl') ? $file->getUrl() : null, 'pathname' => $file->getPathname(), 'mtime' => $file->getMTime() ]; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Collection/AbstractIndexCollection.php
system/src/Grav/Framework/Collection/AbstractIndexCollection.php
<?php /** * @package Grav\Framework\Collection * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Collection; use ArrayIterator; use Closure; use Grav\Framework\Compat\Serializable; use Grav\Framework\Flex\Interfaces\FlexObjectInterface; use InvalidArgumentException; use Iterator; use function array_key_exists; use function array_slice; use function count; /** * Abstract Index Collection. * @template TKey of array-key * @template T * @template C of CollectionInterface * @implements CollectionInterface<TKey,T> */ abstract class AbstractIndexCollection implements CollectionInterface { use Serializable; /** * @var array * @phpstan-var array<TKey,T> */ private $entries; /** * Initializes a new IndexCollection. * * @param array $entries * @phpstan-param array<TKey,T> $entries */ public function __construct(array $entries = []) { $this->entries = $entries; } /** * {@inheritDoc} */ public function toArray() { return $this->loadElements($this->entries); } /** * {@inheritDoc} */ public function first() { $value = reset($this->entries); $key = (string)key($this->entries); return $this->loadElement($key, $value); } /** * {@inheritDoc} */ public function last() { $value = end($this->entries); $key = (string)key($this->entries); return $this->loadElement($key, $value); } /** * {@inheritDoc} */ #[\ReturnTypeWillChange] public function key() { /** @phpstan-var TKey */ return (string)key($this->entries); } /** * {@inheritDoc} */ #[\ReturnTypeWillChange] public function next() { $value = next($this->entries); $key = (string)key($this->entries); return $this->loadElement($key, $value); } /** * {@inheritDoc} */ #[\ReturnTypeWillChange] public function current() { $value = current($this->entries); $key = (string)key($this->entries); return $this->loadElement($key, $value); } /** * {@inheritDoc} */ public function remove($key) { if (!array_key_exists($key, $this->entries)) { return null; } $value = $this->entries[$key]; unset($this->entries[$key]); return $this->loadElement((string)$key, $value); } /** * {@inheritDoc} */ public function removeElement($element) { $key = $this->isAllowedElement($element) ? $this->getCurrentKey($element) : null; if (null !== $key || !isset($this->entries[$key])) { return false; } unset($this->entries[$key]); return true; } /** * Required by interface ArrayAccess. * * @param string|int|null $offset * @return bool * @phpstan-param TKey|null $offset */ #[\ReturnTypeWillChange] public function offsetExists($offset) { /** @phpstan-ignore-next-line phpstan bug? */ return $offset !== null ? $this->containsKey($offset) : false; } /** * Required by interface ArrayAccess. * * @param string|int|null $offset * @return mixed * @phpstan-param TKey|null $offset */ #[\ReturnTypeWillChange] public function offsetGet($offset) { /** @phpstan-ignore-next-line phpstan bug? */ return $offset !== null ? $this->get($offset) : null; } /** * Required by interface ArrayAccess. * * @param string|int|null $offset * @param mixed $value * @return void * @phpstan-param TKey|null $offset */ #[\ReturnTypeWillChange] public function offsetSet($offset, $value) { if (null === $offset) { $this->add($value); } else { /** @phpstan-ignore-next-line phpstan bug? */ $this->set($offset, $value); } } /** * Required by interface ArrayAccess. * * @param string|int|null $offset * @return void * @phpstan-param TKey|null $offset */ #[\ReturnTypeWillChange] public function offsetUnset($offset) { if ($offset !== null) { /** @phpstan-ignore-next-line phpstan bug? */ $this->remove($offset); } } /** * {@inheritDoc} */ public function containsKey($key) { return isset($this->entries[$key]) || array_key_exists($key, $this->entries); } /** * {@inheritDoc} */ public function contains($element) { $key = $this->isAllowedElement($element) ? $this->getCurrentKey($element) : null; return $key && isset($this->entries[$key]); } /** * {@inheritDoc} */ public function exists(Closure $p) { return $this->loadCollection($this->entries)->exists($p); } /** * {@inheritDoc} */ public function indexOf($element) { $key = $this->isAllowedElement($element) ? $this->getCurrentKey($element) : null; return $key && isset($this->entries[$key]) ? $key : false; } /** * {@inheritDoc} */ public function get($key) { if (!isset($this->entries[$key])) { return null; } return $this->loadElement((string)$key, $this->entries[$key]); } /** * {@inheritDoc} */ public function getKeys() { return array_keys($this->entries); } /** * {@inheritDoc} */ public function getValues() { return array_values($this->loadElements($this->entries)); } /** * {@inheritDoc} */ #[\ReturnTypeWillChange] public function count() { return count($this->entries); } /** * {@inheritDoc} */ public function set($key, $value) { if (!$this->isAllowedElement($value)) { throw new InvalidArgumentException('Invalid argument $value'); } $this->entries[$key] = $this->getElementMeta($value); } /** * {@inheritDoc} */ public function add($element) { if (!$this->isAllowedElement($element)) { throw new InvalidArgumentException('Invalid argument $element'); } $this->entries[$this->getCurrentKey($element)] = $this->getElementMeta($element); return true; } /** * {@inheritDoc} */ public function isEmpty() { return empty($this->entries); } /** * Required by interface IteratorAggregate. * * {@inheritDoc} * @phpstan-return Iterator<TKey,T> */ #[\ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->loadElements()); } /** * {@inheritDoc} */ public function map(Closure $func) { return $this->loadCollection($this->entries)->map($func); } /** * {@inheritDoc} */ public function filter(Closure $p) { return $this->loadCollection($this->entries)->filter($p); } /** * {@inheritDoc} */ public function forAll(Closure $p) { return $this->loadCollection($this->entries)->forAll($p); } /** * {@inheritDoc} */ public function partition(Closure $p) { return $this->loadCollection($this->entries)->partition($p); } /** * Returns a string representation of this object. * * @return string */ #[\ReturnTypeWillChange] public function __toString() { return __CLASS__ . '@' . spl_object_hash($this); } /** * {@inheritDoc} */ public function clear() { $this->entries = []; } /** * {@inheritDoc} */ public function slice($offset, $length = null) { return $this->loadElements(array_slice($this->entries, $offset, $length, true)); } /** * @param int $start * @param int|null $limit * @return static * @phpstan-return static<TKey,T,C> */ public function limit($start, $limit = null) { return $this->createFrom(array_slice($this->entries, $start, $limit, true)); } /** * Reverse the order of the items. * * @return static * @phpstan-return static<TKey,T,C> */ public function reverse() { return $this->createFrom(array_reverse($this->entries)); } /** * Shuffle items. * * @return static * @phpstan-return static<TKey,T,C> */ public function shuffle() { $keys = $this->getKeys(); shuffle($keys); return $this->createFrom(array_replace(array_flip($keys), $this->entries)); } /** * Select items from collection. * * Collection is returned in the order of $keys given to the function. * * @param array $keys * @return static * @phpstan-return static<TKey,T,C> */ public function select(array $keys) { $list = []; foreach ($keys as $key) { if (isset($this->entries[$key])) { $list[$key] = $this->entries[$key]; } } return $this->createFrom($list); } /** * Un-select items from collection. * * @param array $keys * @return static * @phpstan-return static<TKey,T,C> */ public function unselect(array $keys) { return $this->select(array_diff($this->getKeys(), $keys)); } /** * Split collection into chunks. * * @param int $size Size of each chunk. * @return array * @phpstan-return array<array<TKey,T>> */ public function chunk($size) { /** @phpstan-var array<array<TKey,T>> */ return $this->loadCollection($this->entries)->chunk($size); } /** * @return array */ public function __serialize(): array { return [ 'entries' => $this->entries ]; } /** * @param array $data * @return void */ public function __unserialize(array $data): void { $this->entries = $data['entries']; } /** * Implements JsonSerializable interface. * * @return array */ #[\ReturnTypeWillChange] public function jsonSerialize() { return $this->loadCollection()->jsonSerialize(); } /** * Creates a new instance from the specified elements. * * This method is provided for derived classes to specify how a new * instance should be created when constructor semantics have changed. * * @param array $entries Elements. * @return static * @phpstan-return static<TKey,T,C> */ protected function createFrom(array $entries) { return new static($entries); } /** * @return array */ protected function getEntries(): array { return $this->entries; } /** * @param array $entries * @return void * @phpstan-param array<TKey,T> $entries */ protected function setEntries(array $entries): void { $this->entries = $entries; } /** * @param FlexObjectInterface $element * @return string * @phpstan-param T $element * @phpstan-return TKey */ protected function getCurrentKey($element) { return $element->getKey(); } /** * @param string $key * @param mixed $value * @return mixed|null */ abstract protected function loadElement($key, $value); /** * @param array|null $entries * @return array * @phpstan-return array<TKey,T> */ abstract protected function loadElements(array $entries = null): array; /** * @param array|null $entries * @return CollectionInterface * @phpstan-return C */ abstract protected function loadCollection(array $entries = null): CollectionInterface; /** * @param mixed $value * @return bool */ abstract protected function isAllowedElement($value): bool; /** * @param mixed $element * @return mixed */ abstract protected function getElementMeta($element); }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Collection/ArrayCollection.php
system/src/Grav/Framework/Collection/ArrayCollection.php
<?php /** * @package Grav\Framework\Collection * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Collection; use Doctrine\Common\Collections\ArrayCollection as BaseArrayCollection; /** * General JSON serializable collection. * * @package Grav\Framework\Collection * @template TKey of array-key * @template T * @extends BaseArrayCollection<TKey,T> * @implements CollectionInterface<TKey,T> */ class ArrayCollection extends BaseArrayCollection implements CollectionInterface { /** * Reverse the order of the items. * * @return static * @phpstan-return static<TKey,T> */ public function reverse() { $keys = array_reverse($this->toArray()); /** @phpstan-var static<TKey,T> */ return $this->createFrom($keys); } /** * Shuffle items. * * @return static * @phpstan-return static<TKey,T> */ public function shuffle() { $keys = $this->getKeys(); shuffle($keys); $keys = array_replace(array_flip($keys), $this->toArray()); /** @phpstan-var static<TKey,T> */ return $this->createFrom($keys); } /** * Split collection into chunks. * * @param int $size Size of each chunk. * @return array * @phpstan-return array<array<TKey,T>> */ public function chunk($size) { /** @phpstan-var array<array<TKey,T>> */ return array_chunk($this->toArray(), $size, true); } /** * Select items from collection. * * Collection is returned in the order of $keys given to the function. * * @param array<int,string> $keys * @return static * @phpstan-param TKey[] $keys * @phpstan-return static<TKey,T> */ public function select(array $keys) { $list = []; foreach ($keys as $key) { if ($this->containsKey($key)) { $list[$key] = $this->get($key); } } /** @phpstan-var static<TKey,T> */ return $this->createFrom($list); } /** * Un-select items from collection. * * @param array<int|string> $keys * @return static * @phpstan-param TKey[] $keys * @phpstan-return static<TKey,T> */ public function unselect(array $keys) { $list = array_diff($this->getKeys(), $keys); /** @phpstan-var static<TKey,T> */ return $this->select($list); } /** * Implements JsonSerializable interface. * * @return array */ #[\ReturnTypeWillChange] public function jsonSerialize() { return $this->toArray(); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Collection/AbstractLazyCollection.php
system/src/Grav/Framework/Collection/AbstractLazyCollection.php
<?php /** * @package Grav\Framework\Collection * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Collection; use Doctrine\Common\Collections\AbstractLazyCollection as BaseAbstractLazyCollection; /** * General JSON serializable collection. * * @package Grav\Framework\Collection * @template TKey of array-key * @template T * @extends BaseAbstractLazyCollection<TKey,T> * @implements CollectionInterface<TKey,T> */ abstract class AbstractLazyCollection extends BaseAbstractLazyCollection implements CollectionInterface { /** * @par ArrayCollection * @phpstan-var ArrayCollection<TKey,T> */ protected $collection; /** * {@inheritDoc} * @phpstan-return ArrayCollection<TKey,T> */ public function reverse() { $this->initialize(); return $this->collection->reverse(); } /** * {@inheritDoc} * @phpstan-return ArrayCollection<TKey,T> */ public function shuffle() { $this->initialize(); return $this->collection->shuffle(); } /** * {@inheritDoc} */ public function chunk($size) { $this->initialize(); return $this->collection->chunk($size); } /** * {@inheritDoc} * @phpstan-param array<TKey,T> $keys * @phpstan-return ArrayCollection<TKey,T> */ public function select(array $keys) { $this->initialize(); return $this->collection->select($keys); } /** * {@inheritDoc} * @phpstan-param array<TKey,T> $keys * @phpstan-return ArrayCollection<TKey,T> */ public function unselect(array $keys) { $this->initialize(); return $this->collection->unselect($keys); } /** * @return array */ #[\ReturnTypeWillChange] public function jsonSerialize() { $this->initialize(); return $this->collection->jsonSerialize(); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Relationships/ToOneRelationship.php
system/src/Grav/Framework/Relationships/ToOneRelationship.php
<?php declare(strict_types=1); namespace Grav\Framework\Relationships; use ArrayIterator; use Grav\Framework\Compat\Serializable; use Grav\Framework\Contracts\Object\IdentifierInterface; use Grav\Framework\Contracts\Relationships\ToOneRelationshipInterface; use Grav\Framework\Relationships\Traits\RelationshipTrait; use function is_callable; /** * Class ToOneRelationship * * @template T of IdentifierInterface * @template P of IdentifierInterface * @template-implements ToOneRelationshipInterface<T,P> */ class ToOneRelationship implements ToOneRelationshipInterface { /** @template-use RelationshipTrait<T> */ use RelationshipTrait; use Serializable; /** @var IdentifierInterface|null */ protected $identifier = null; public function __construct(IdentifierInterface $parent, string $name, array $options, IdentifierInterface $identifier = null) { $this->parent = $parent; $this->name = $name; $this->parseOptions($options); $this->replaceIdentifier($identifier); $this->modified = false; } /** * @return string * @phpstan-pure */ public function getCardinality(): string { return 'to-one'; } /** * @return int * @phpstan-pure */ public function count(): int { return $this->identifier ? 1 : 0; } /** * @return object|null */ public function fetch(): ?object { $identifier = $this->identifier; if (is_callable([$identifier, 'getObject'])) { $identifier = $identifier->getObject(); } return $identifier; } /** * @param string|null $id * @param string|null $type * @return bool * @phpstan-pure */ public function has(string $id = null, string $type = null): bool { return $this->getIdentifier($id, $type) !== null; } /** * @param string|null $id * @param string|null $type * @return IdentifierInterface|null * @phpstan-pure */ public function getIdentifier(string $id = null, string $type = null): ?IdentifierInterface { if ($id && $this->getType() === 'media' && !str_contains($id, '/')) { $name = $this->name; $id = $this->parent->getType() . '/' . $this->parent->getId() . '/'. $name . '/' . $id; } $identifier = $this->identifier ?? null; if (null === $identifier || ($type && $type !== $identifier->getType()) || ($id && $id !== $identifier->getId())) { return null; } return $identifier; } /** * @param string|null $id * @param string|null $type * @return T|null */ public function getObject(string $id = null, string $type = null): ?object { $identifier = $this->getIdentifier($id, $type); if ($identifier && is_callable([$identifier, 'getObject'])) { $identifier = $identifier->getObject(); } return $identifier; } /** * @param IdentifierInterface $identifier * @return bool */ public function addIdentifier(IdentifierInterface $identifier): bool { $this->identifier = $this->checkIdentifier($identifier); $this->modified = true; return true; } /** * @param IdentifierInterface|null $identifier * @return bool */ public function replaceIdentifier(IdentifierInterface $identifier = null): bool { if ($identifier === null) { $this->identifier = null; $this->modified = true; return true; } return $this->addIdentifier($identifier); } /** * @param IdentifierInterface|null $identifier * @return bool */ public function removeIdentifier(IdentifierInterface $identifier = null): bool { if (null === $identifier || $this->has($identifier->getId(), $identifier->getType())) { $this->identifier = null; $this->modified = true; return true; } return false; } /** * @return iterable<IdentifierInterface> * @phpstan-pure */ public function getIterator(): iterable { return new ArrayIterator((array)$this->identifier); } /** * @return array|null */ public function jsonSerialize(): ?array { return $this->identifier ? $this->identifier->jsonSerialize() : null; } /** * @return array */ public function __serialize(): array { return [ 'parent' => $this->parent, 'name' => $this->name, 'type' => $this->type, 'options' => $this->options, 'modified' => $this->modified, 'identifier' => $this->identifier, ]; } /** * @param array $data * @return void */ public function __unserialize(array $data): void { $this->parent = $data['parent']; $this->name = $data['name']; $this->type = $data['type']; $this->options = $data['options']; $this->modified = $data['modified']; $this->identifier = $data['identifier']; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Relationships/Relationships.php
system/src/Grav/Framework/Relationships/Relationships.php
<?php declare(strict_types=1); namespace Grav\Framework\Relationships; use Grav\Framework\Contracts\Object\IdentifierInterface; use Grav\Framework\Contracts\Relationships\RelationshipInterface; use Grav\Framework\Contracts\Relationships\RelationshipsInterface; use Grav\Framework\Flex\FlexIdentifier; use RuntimeException; use function count; /** * Class Relationships * * @template T of \Grav\Framework\Contracts\Object\IdentifierInterface * @template P of \Grav\Framework\Contracts\Object\IdentifierInterface * @implements RelationshipsInterface<T,P> */ class Relationships implements RelationshipsInterface { /** @var P */ protected $parent; /** @var array */ protected $options; /** @var RelationshipInterface<T,P>[] */ protected $relationships; /** * Relationships constructor. * @param P $parent * @param array $options */ public function __construct(IdentifierInterface $parent, array $options) { $this->parent = $parent; $this->options = $options; $this->relationships = []; } /** * @return bool * @phpstan-pure */ public function isModified(): bool { return !empty($this->getModified()); } /** * @return RelationshipInterface<T,P>[] * @phpstan-pure */ public function getModified(): array { $list = []; foreach ($this->relationships as $name => $relationship) { if ($relationship->isModified()) { $list[$name] = $relationship; } } return $list; } /** * @return int * @phpstan-pure */ public function count(): int { return count($this->options); } /** * @param string $offset * @return bool * @phpstan-pure */ public function offsetExists($offset): bool { return isset($this->options[$offset]); } /** * @param string $offset * @return RelationshipInterface<T,P>|null */ public function offsetGet($offset): ?RelationshipInterface { if (!isset($this->relationships[$offset])) { $options = $this->options[$offset] ?? null; if (null === $options) { return null; } $this->relationships[$offset] = $this->createRelationship($offset, $options); } return $this->relationships[$offset]; } /** * @param string $offset * @param mixed $value * @return never-return */ public function offsetSet($offset, $value) { throw new RuntimeException('Setting relationship is not supported', 500); } /** * @param string $offset * @return never-return */ public function offsetUnset($offset) { throw new RuntimeException('Removing relationship is not allowed', 500); } /** * @return RelationshipInterface<T,P>|null */ public function current(): ?RelationshipInterface { $name = key($this->options); if ($name === null) { return null; } return $this->offsetGet($name); } /** * @return string * @phpstan-pure */ public function key(): string { return key($this->options); } /** * @return void * @phpstan-pure */ public function next(): void { next($this->options); } /** * @return void * @phpstan-pure */ public function rewind(): void { reset($this->options); } /** * @return bool * @phpstan-pure */ public function valid(): bool { return key($this->options) !== null; } /** * @return array */ public function jsonSerialize(): array { $list = []; foreach ($this as $name => $relationship) { $list[$name] = $relationship->jsonSerialize(); } return $list; } /** * @param string $name * @param array $options * @return ToOneRelationship|ToManyRelationship */ private function createRelationship(string $name, array $options): RelationshipInterface { $data = null; $parent = $this->parent; if ($parent instanceof FlexIdentifier) { $object = $parent->getObject(); if (!method_exists($object, 'initRelationship')) { throw new RuntimeException(sprintf('Bad relationship %s', $name), 500); } $data = $object->initRelationship($name); } $cardinality = $options['cardinality'] ?? ''; switch ($cardinality) { case 'to-one': $relationship = new ToOneRelationship($parent, $name, $options, $data); break; case 'to-many': $relationship = new ToManyRelationship($parent, $name, $options, $data ?? []); break; default: throw new RuntimeException(sprintf('Bad relationship cardinality %s', $cardinality), 500); } return $relationship; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Relationships/ToManyRelationship.php
system/src/Grav/Framework/Relationships/ToManyRelationship.php
<?php declare(strict_types=1); namespace Grav\Framework\Relationships; use ArrayIterator; use Grav\Framework\Compat\Serializable; use Grav\Framework\Contracts\Object\IdentifierInterface; use Grav\Framework\Contracts\Relationships\ToManyRelationshipInterface; use Grav\Framework\Relationships\Traits\RelationshipTrait; use function count; use function is_callable; /** * Class ToManyRelationship * * @template T of IdentifierInterface * @template P of IdentifierInterface * @template-implements ToManyRelationshipInterface<T,P> */ class ToManyRelationship implements ToManyRelationshipInterface { /** @template-use RelationshipTrait<T> */ use RelationshipTrait; use Serializable; /** @var IdentifierInterface[] */ protected $identifiers = []; /** * ToManyRelationship constructor. * @param string $name * @param IdentifierInterface $parent * @param iterable<IdentifierInterface> $identifiers */ public function __construct(IdentifierInterface $parent, string $name, array $options, iterable $identifiers = []) { $this->parent = $parent; $this->name = $name; $this->parseOptions($options); $this->addIdentifiers($identifiers); $this->modified = false; } /** * @return string * @phpstan-pure */ public function getCardinality(): string { return 'to-many'; } /** * @return int * @phpstan-pure */ public function count(): int { return count($this->identifiers); } /** * @return array */ public function fetch(): array { $list = []; foreach ($this->identifiers as $identifier) { if (is_callable([$identifier, 'getObject'])) { $identifier = $identifier->getObject(); } $list[] = $identifier; } return $list; } /** * @param string $id * @param string|null $type * @return bool * @phpstan-pure */ public function has(string $id, string $type = null): bool { return $this->getIdentifier($id, $type) !== null; } /** * @param positive-int $pos * @return IdentifierInterface|null */ public function getNthIdentifier(int $pos): ?IdentifierInterface { $items = array_keys($this->identifiers); $key = $items[$pos - 1] ?? null; if (null === $key) { return null; } return $this->identifiers[$key] ?? null; } /** * @param string $id * @param string|null $type * @return IdentifierInterface|null * @phpstan-pure */ public function getIdentifier(string $id, string $type = null): ?IdentifierInterface { if (null === $type) { $type = $this->getType(); } if ($type === 'media' && !str_contains($id, '/')) { $name = $this->name; $id = $this->parent->getType() . '/' . $this->parent->getId() . '/'. $name . '/' . $id; } $key = "{$type}/{$id}"; return $this->identifiers[$key] ?? null; } /** * @param string $id * @param string|null $type * @return T|null */ public function getObject(string $id, string $type = null): ?object { $identifier = $this->getIdentifier($id, $type); if ($identifier && is_callable([$identifier, 'getObject'])) { $identifier = $identifier->getObject(); } return $identifier; } /** * @param IdentifierInterface $identifier * @return bool */ public function addIdentifier(IdentifierInterface $identifier): bool { return $this->addIdentifiers([$identifier]); } /** * @param IdentifierInterface|null $identifier * @return bool */ public function removeIdentifier(IdentifierInterface $identifier = null): bool { return !$identifier || $this->removeIdentifiers([$identifier]); } /** * @param iterable<IdentifierInterface> $identifiers * @return bool */ public function addIdentifiers(iterable $identifiers): bool { foreach ($identifiers as $identifier) { $type = $identifier->getType(); $id = $identifier->getId(); $key = "{$type}/{$id}"; $this->identifiers[$key] = $this->checkIdentifier($identifier); $this->modified = true; } return true; } /** * @param iterable<IdentifierInterface> $identifiers * @return bool */ public function replaceIdentifiers(iterable $identifiers): bool { $this->identifiers = []; $this->modified = true; return $this->addIdentifiers($identifiers); } /** * @param iterable<IdentifierInterface> $identifiers * @return bool */ public function removeIdentifiers(iterable $identifiers): bool { foreach ($identifiers as $identifier) { $type = $identifier->getType(); $id = $identifier->getId(); $key = "{$type}/{$id}"; unset($this->identifiers[$key]); $this->modified = true; } return true; } /** * @return iterable<IdentifierInterface> * @phpstan-pure */ public function getIterator(): iterable { return new ArrayIterator($this->identifiers); } /** * @return array */ public function jsonSerialize(): array { $list = []; foreach ($this->getIterator() as $item) { $list[] = $item->jsonSerialize(); } return $list; } /** * @return array */ public function __serialize(): array { return [ 'parent' => $this->parent, 'name' => $this->name, 'type' => $this->type, 'options' => $this->options, 'modified' => $this->modified, 'identifiers' => $this->identifiers, ]; } /** * @param array $data * @return void */ public function __unserialize(array $data): void { $this->parent = $data['parent']; $this->name = $data['name']; $this->type = $data['type']; $this->options = $data['options']; $this->modified = $data['modified']; $this->identifiers = $data['identifiers']; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Relationships/Traits/RelationshipTrait.php
system/src/Grav/Framework/Relationships/Traits/RelationshipTrait.php
<?php declare(strict_types=1); namespace Grav\Framework\Relationships\Traits; use Grav\Framework\Contracts\Object\IdentifierInterface; use Grav\Framework\Flex\FlexIdentifier; use Grav\Framework\Media\MediaIdentifier; use Grav\Framework\Object\Identifiers\Identifier; use RuntimeException; use function get_class; /** * Trait RelationshipTrait * * @template T of object */ trait RelationshipTrait { /** @var IdentifierInterface */ protected $parent; /** @var string */ protected $name; /** @var string */ protected $type; /** @var array */ protected $options; /** @var bool */ protected $modified = false; /** * @return string * @phpstan-pure */ public function getName(): string { return $this->name; } /** * @return string * @phpstan-pure */ public function getType(): string { return $this->type; } /** * @return bool * @phpstan-pure */ public function isModified(): bool { return $this->modified; } /** * @return IdentifierInterface * @phpstan-pure */ public function getParent(): IdentifierInterface { return $this->parent; } /** * @param IdentifierInterface $identifier * @return bool * @phpstan-pure */ public function hasIdentifier(IdentifierInterface $identifier): bool { return $this->getIdentifier($identifier->getId(), $identifier->getType()) !== null; } /** * @return int * @phpstan-pure */ abstract public function count(): int; /** * @return void * @phpstan-pure */ public function check(): void { $min = $this->options['min'] ?? 0; $max = $this->options['max'] ?? 0; if ($min || $max) { $count = $this->count(); if ($min && $count < $min) { throw new RuntimeException(sprintf('%s relationship has too few objects in it', $this->name)); } if ($max && $count > $max) { throw new RuntimeException(sprintf('%s relationship has too many objects in it', $this->name)); } } } /** * @param IdentifierInterface $identifier * @return IdentifierInterface */ private function checkIdentifier(IdentifierInterface $identifier): IdentifierInterface { if ($this->type !== $identifier->getType()) { throw new RuntimeException(sprintf('Bad identifier type %s', $identifier->getType())); } if (get_class($identifier) !== Identifier::class) { return $identifier; } if ($this->type === 'media') { return new MediaIdentifier($identifier->getId()); } return new FlexIdentifier($identifier->getId(), $identifier->getType()); } private function parseOptions(array $options): void { $this->type = $options['type']; $this->options = $options; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/RequestHandler/RequestHandler.php
system/src/Grav/Framework/RequestHandler/RequestHandler.php
<?php /** * @package Grav\Framework\RequestHandler * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ declare(strict_types=1); namespace Grav\Framework\RequestHandler; use Grav\Framework\RequestHandler\Traits\RequestHandlerTrait; use Pimple\Container; use Psr\Container\ContainerInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use function assert; /** * Class RequestHandler * @package Grav\Framework\RequestHandler */ class RequestHandler implements RequestHandlerInterface { use RequestHandlerTrait; /** * Delegate constructor. * * @param array $middleware * @param callable $default * @param ContainerInterface|null $container */ public function __construct(array $middleware, callable $default, ContainerInterface $container = null) { $this->middleware = $middleware; $this->handler = $default; $this->container = $container; } /** * Add callable initializing Middleware that will be executed as soon as possible. * * @param string $name * @param callable $callable * @return $this */ public function addCallable(string $name, callable $callable): self { if (null !== $this->container) { assert($this->container instanceof Container); $this->container[$name] = $callable; } array_unshift($this->middleware, $name); return $this; } /** * Add Middleware that will be executed as soon as possible. * * @param string $name * @param MiddlewareInterface $middleware * @return $this */ public function addMiddleware(string $name, MiddlewareInterface $middleware): self { if (null !== $this->container) { assert($this->container instanceof Container); $this->container[$name] = $middleware; } array_unshift($this->middleware, $name); return $this; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/RequestHandler/Traits/RequestHandlerTrait.php
system/src/Grav/Framework/RequestHandler/Traits/RequestHandlerTrait.php
<?php /** * @package Grav\Framework\RequestHandler * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ declare(strict_types=1); namespace Grav\Framework\RequestHandler\Traits; use Grav\Framework\RequestHandler\Exception\InvalidArgumentException; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use function call_user_func; /** * Trait RequestHandlerTrait * @package Grav\Framework\RequestHandler\Traits */ trait RequestHandlerTrait { /** @var array<int,string|MiddlewareInterface> */ protected $middleware; /** @var callable */ protected $handler; /** @var ContainerInterface|null */ protected $container; /** * {@inheritdoc} * @throws InvalidArgumentException */ public function handle(ServerRequestInterface $request): ResponseInterface { $middleware = array_shift($this->middleware); // Use default callable if there is no middleware. if ($middleware === null) { return call_user_func($this->handler, $request); } if ($middleware instanceof MiddlewareInterface) { return $middleware->process($request, clone $this); } if (null === $this->container || !$this->container->has($middleware)) { throw new InvalidArgumentException( sprintf('The middleware is not a valid %s and is not passed in the Container', MiddlewareInterface::class), $middleware ); } array_unshift($this->middleware, $this->container->get($middleware)); return $this->handle($request); } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/RequestHandler/Middlewares/Exceptions.php
system/src/Grav/Framework/RequestHandler/Middlewares/Exceptions.php
<?php declare(strict_types=1); /** * @package Grav\Framework\RequestHandler * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\RequestHandler\Middlewares; use Grav\Common\Data\ValidationException; use Grav\Common\Debugger; use Grav\Common\Grav; use Grav\Framework\Psr7\Response; use JsonException; use JsonSerializable; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use Throwable; use function get_class; /** * Class Exceptions * @package Grav\Framework\RequestHandler\Middlewares */ class Exceptions implements MiddlewareInterface { /** * @param ServerRequestInterface $request * @param RequestHandlerInterface $handler * @return ResponseInterface * @throws JsonException */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { try { return $handler->handle($request); } catch (Throwable $exception) { $code = $exception->getCode(); if ($exception instanceof ValidationException) { $message = $exception->getMessage(); } else { $message = htmlspecialchars($exception->getMessage(), ENT_QUOTES | ENT_HTML5, 'UTF-8'); } $extra = $exception instanceof JsonSerializable ? $exception->jsonSerialize() : []; $response = [ 'code' => $code, 'status' => 'error', 'message' => $message, 'error' => [ 'code' => $code, 'message' => $message, ] + $extra ]; /** @var Debugger $debugger */ $debugger = Grav::instance()['debugger']; if ($debugger->enabled()) { $response['error'] += [ 'type' => get_class($exception), 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'trace' => explode("\n", $exception->getTraceAsString()), ]; } /** @var string $json */ $json = json_encode($response, JSON_THROW_ON_ERROR); return new Response($code ?: 500, ['Content-Type' => 'application/json'], $json); } } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/RequestHandler/Middlewares/MultipartRequestSupport.php
system/src/Grav/Framework/RequestHandler/Middlewares/MultipartRequestSupport.php
<?php declare(strict_types=1); /** * @package Grav\Framework\RequestHandler * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\RequestHandler\Middlewares; use Grav\Framework\Psr7\UploadedFile; use Nyholm\Psr7\Stream; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\UploadedFileInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use function array_slice; use function count; use function in_array; use function is_array; use function strlen; /** * Multipart request support for PUT and PATCH. */ class MultipartRequestSupport implements MiddlewareInterface { /** * @param ServerRequestInterface $request * @param RequestHandlerInterface $handler * @return ResponseInterface */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $contentType = $request->getHeaderLine('content-type'); $method = $request->getMethod(); if (!str_starts_with($contentType, 'multipart/form-data') || !in_array($method, ['PUT', 'PATH'], true)) { return $handler->handle($request); } $boundary = explode('; boundary=', $contentType, 2)[1] ?? ''; $parts = explode("--{$boundary}", $request->getBody()->getContents()); $parts = array_slice($parts, 1, count($parts) - 2); $params = []; $files = []; foreach ($parts as $part) { $this->processPart($params, $files, $part); } return $handler->handle($request->withParsedBody($params)->withUploadedFiles($files)); } /** * @param array $params * @param array $files * @param string $part * @return void */ protected function processPart(array &$params, array &$files, string $part): void { $part = ltrim($part, "\r\n"); [$rawHeaders, $body] = explode("\r\n\r\n", $part, 2); // Parse headers. $rawHeaders = explode("\r\n", $rawHeaders); $headers = array_reduce( $rawHeaders, static function (array $headers, $header) { [$name, $value] = explode(':', $header); $headers[strtolower($name)] = ltrim($value, ' '); return $headers; }, [] ); if (!isset($headers['content-disposition'])) { return; } // Parse content disposition header. $contentDisposition = $headers['content-disposition']; preg_match('/^(.+); *name="([^"]+)"(; *filename="([^"]+)")?/', $contentDisposition, $matches); $name = $matches[2]; $filename = $matches[4] ?? null; if ($filename !== null) { $stream = Stream::create($body); $this->addFile($files, $name, new UploadedFile($stream, strlen($body), UPLOAD_ERR_OK, $filename, $headers['content-type'] ?? null)); } elseif (strpos($contentDisposition, 'filename') !== false) { // Not uploaded file. $stream = Stream::create(''); $this->addFile($files, $name, new UploadedFile($stream, 0, UPLOAD_ERR_NO_FILE)); } else { // Regular field. $params[$name] = substr($body, 0, -2); } } /** * @param array $files * @param string $name * @param UploadedFileInterface $file * @return void */ protected function addFile(array &$files, string $name, UploadedFileInterface $file): void { if (strpos($name, '[]') === strlen($name) - 2) { $name = substr($name, 0, -2); if (isset($files[$name]) && is_array($files[$name])) { $files[$name][] = $file; } else { $files[$name] = [$file]; } } else { $files[$name] = $file; } } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/RequestHandler/Exception/NotFoundException.php
system/src/Grav/Framework/RequestHandler/Exception/NotFoundException.php
<?php /** * @package Grav\Framework\RequestHandler * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ declare(strict_types=1); namespace Grav\Framework\RequestHandler\Exception; use Psr\Http\Message\ServerRequestInterface; use Throwable; use function in_array; /** * Class NotFoundException * @package Grav\Framework\RequestHandler\Exception */ class NotFoundException extends RequestException { /** * NotFoundException constructor. * @param ServerRequestInterface $request * @param Throwable|null $previous */ public function __construct(ServerRequestInterface $request, Throwable $previous = null) { if (in_array(strtoupper($request->getMethod()), ['PUT', 'PATCH', 'DELETE'])) { parent::__construct($request, 'Method Not Allowed', 405, $previous); } else { parent::__construct($request, 'Not Found', 404, $previous); } } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/RequestHandler/Exception/RequestException.php
system/src/Grav/Framework/RequestHandler/Exception/RequestException.php
<?php /** * @package Grav\Framework\RequestHandler * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ declare(strict_types=1); namespace Grav\Framework\RequestHandler\Exception; use Psr\Http\Message\ServerRequestInterface; use Throwable; /** * Class RequestException * @package Grav\Framework\RequestHandler\Exception */ class RequestException extends \RuntimeException { /** @var array Map of standard HTTP status code/reason phrases */ private static $phrases = [ 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed', 418 => 'I\'m a teapot', 419 => 'Page Expired', 422 => 'Unprocessable Entity', 423 => 'Locked', 424 => 'Failed Dependency', 425 => 'Unordered Collection', 426 => 'Upgrade Required', 428 => 'Precondition Required', 429 => 'Too Many Requests', 431 => 'Request Header Fields Too Large', 451 => 'Unavailable For Legal Reasons', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported', 506 => 'Variant Also Negotiates', 507 => 'Insufficient Storage', 508 => 'Loop Detected', 511 => 'Network Authentication Required', ]; /** @var ServerRequestInterface */ private $request; /** * @param ServerRequestInterface $request * @param string $message * @param int $code * @param Throwable|null $previous */ public function __construct(ServerRequestInterface $request, string $message, int $code = 500, Throwable $previous = null) { $this->request = $request; parent::__construct($message, $code, $previous); } /** * @return ServerRequestInterface */ public function getRequest(): ServerRequestInterface { return $this->request; } public function getHttpCode(): int { $code = $this->getCode(); return isset(self::$phrases[$code]) ? $code : 500; } public function getHttpReason(): ?string { return self::$phrases[$this->getCode()] ?? self::$phrases[500]; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/RequestHandler/Exception/NotHandledException.php
system/src/Grav/Framework/RequestHandler/Exception/NotHandledException.php
<?php /** * @package Grav\Framework\RequestHandler * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ declare(strict_types=1); namespace Grav\Framework\RequestHandler\Exception; /** * Class NotHandledException * @package Grav\Framework\RequestHandler\Exception */ class NotHandledException extends NotFoundException { }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/RequestHandler/Exception/InvalidArgumentException.php
system/src/Grav/Framework/RequestHandler/Exception/InvalidArgumentException.php
<?php /** * @package Grav\Framework\RequestHandler * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ declare(strict_types=1); namespace Grav\Framework\RequestHandler\Exception; use Throwable; /** * Class InvalidArgumentException * @package Grav\Framework\RequestHandler\Exception */ class InvalidArgumentException extends \InvalidArgumentException { /** @var mixed|null */ private $invalidMiddleware; /** * InvalidArgumentException constructor. * * @param string $message * @param mixed|null $invalidMiddleware * @param int $code * @param Throwable|null $previous */ public function __construct($message = '', $invalidMiddleware = null, $code = 0, Throwable $previous = null) { parent::__construct($message, $code, $previous); $this->invalidMiddleware = $invalidMiddleware; } /** * Return the invalid middleware * * @return mixed|null */ public function getInvalidMiddleware() { return $this->invalidMiddleware; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/RequestHandler/Exception/PageExpiredException.php
system/src/Grav/Framework/RequestHandler/Exception/PageExpiredException.php
<?php /** * @package Grav\Framework\RequestHandler * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ declare(strict_types=1); namespace Grav\Framework\RequestHandler\Exception; use Psr\Http\Message\ServerRequestInterface; use Throwable; /** * Class PageExpiredException * @package Grav\Framework\RequestHandler\Exception */ class PageExpiredException extends RequestException { /** * PageExpiredException constructor. * @param ServerRequestInterface $request * @param Throwable|null $previous */ public function __construct(ServerRequestInterface $request, Throwable $previous = null) { parent::__construct($request, 'Page Expired', 400, $previous); // 419 } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Acl/Permissions.php
system/src/Grav/Framework/Acl/Permissions.php
<?php /** * @package Grav\Framework\Acl * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Acl; use ArrayAccess; use ArrayIterator; use Countable; use IteratorAggregate; use RecursiveIteratorIterator; use RuntimeException; use Traversable; use function count; /** * Class Permissions * @package Grav\Framework\Acl * @implements ArrayAccess<string,Action> * @implements IteratorAggregate<string,Action> */ class Permissions implements ArrayAccess, Countable, IteratorAggregate { /** @var array<string,Action> */ protected $instances = []; /** @var array<string,Action> */ protected $actions = []; /** @var array */ protected $nested = []; /** @var array */ protected $types = []; /** * @return array */ public function getInstances(): array { $iterator = new RecursiveActionIterator($this->actions); $recursive = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST); return iterator_to_array($recursive); } /** * @param string $name * @return bool */ public function hasAction(string $name): bool { return isset($this->instances[$name]); } /** * @param string $name * @return Action|null */ public function getAction(string $name): ?Action { return $this->instances[$name] ?? null; } /** * @param Action $action * @return void */ public function addAction(Action $action): void { $name = $action->name; $parent = $this->getParent($name); if ($parent) { $parent->addChild($action); } else { $this->actions[$name] = $action; } $this->instances[$name] = $action; // If Action has children, add those, too. foreach ($action->getChildren() as $child) { $this->instances[$child->name] = $child; } } /** * @return array */ public function getActions(): array { return $this->actions; } /** * @param Action[] $actions * @return void */ public function addActions(array $actions): void { foreach ($actions as $action) { $this->addAction($action); } } /** * @param string $name * @return bool */ public function hasType(string $name): bool { return isset($this->types[$name]); } /** * @param string $name * @return Action|null */ public function getType(string $name): ?Action { return $this->types[$name] ?? null; } /** * @param string $name * @param array $type * @return void */ public function addType(string $name, array $type): void { $this->types[$name] = $type; } /** * @return array */ public function getTypes(): array { return $this->types; } /** * @param array $types * @return void */ public function addTypes(array $types): void { $types = array_replace($this->types, $types); $this->types = $types; } /** * @param array|null $access * @return Access */ public function getAccess(array $access = null): Access { return new Access($access ?? []); } /** * @param int|string $offset * @return bool */ public function offsetExists($offset): bool { return isset($this->nested[$offset]); } /** * @param int|string $offset * @return Action|null */ public function offsetGet($offset): ?Action { return $this->nested[$offset] ?? null; } /** * @param int|string $offset * @param mixed $value * @return void */ public function offsetSet($offset, $value): void { throw new RuntimeException(__METHOD__ . '(): Not Supported'); } /** * @param int|string $offset * @return void */ public function offsetUnset($offset): void { throw new RuntimeException(__METHOD__ . '(): Not Supported'); } /** * @return int */ public function count(): int { return count($this->actions); } /** * @return ArrayIterator|Traversable */ #[\ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->actions); } /** * @return array */ #[\ReturnTypeWillChange] public function __debugInfo() { return [ 'actions' => $this->actions ]; } /** * @param string $name * @return Action|null */ protected function getParent(string $name): ?Action { if ($pos = strrpos($name, '.')) { $parentName = substr($name, 0, $pos); $parent = $this->getAction($parentName); if (!$parent) { $parent = new Action($parentName); $this->addAction($parent); } return $parent; } return null; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false
getgrav/grav
https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Acl/Action.php
system/src/Grav/Framework/Acl/Action.php
<?php /** * @package Grav\Framework\Acl * * @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ namespace Grav\Framework\Acl; use ArrayIterator; use Countable; use Grav\Common\Inflector; use IteratorAggregate; use RuntimeException; use Traversable; use function count; /** * Class Action * @package Grav\Framework\Acl * @implements IteratorAggregate<string,Action> */ class Action implements IteratorAggregate, Countable { /** @var string */ public $name; /** @var string */ public $type; /** @var bool */ public $visible; /** @var string|null */ public $label; /** @var array */ public $params; /** @var Action|null */ protected $parent; /** @var array<string,Action> */ protected $children = []; /** * @param string $name * @param array $action */ public function __construct(string $name, array $action = []) { $label = $action['label'] ?? null; if (!$label) { if ($pos = mb_strrpos($name, '.')) { $label = mb_substr($name, $pos + 1); } else { $label = $name; } $label = Inflector::humanize($label, 'all'); } $this->name = $name; $this->type = $action['type'] ?? 'action'; $this->visible = (bool)($action['visible'] ?? true); $this->label = $label; unset($action['type'], $action['label']); $this->params = $action; // Include compact rules. if (isset($action['letters'])) { foreach ($action['letters'] as $letter => $data) { $data['letter'] = $letter; $childName = $this->name . '.' . $data['action']; unset($data['action']); $child = new Action($childName, $data); $this->addChild($child); } } } /** * @return array */ public function getParams(): array { return $this->params; } /** * @param string $name * @return mixed|null */ public function getParam(string $name) { return $this->params[$name] ?? null; } /** * @return Action|null */ public function getParent(): ?Action { return $this->parent; } /** * @param Action|null $parent * @return void */ public function setParent(?Action $parent): void { $this->parent = $parent; } /** * @return string */ public function getScope(): string { $pos = mb_strpos($this->name, '.'); if ($pos) { return mb_substr($this->name, 0, $pos); } return $this->name; } /** * @return int */ public function getLevels(): int { return mb_substr_count($this->name, '.'); } /** * @return bool */ public function hasChildren(): bool { return !empty($this->children); } /** * @return Action[] */ public function getChildren(): array { return $this->children; } /** * @param string $name * @return Action|null */ public function getChild(string $name): ?Action { return $this->children[$name] ?? null; } /** * @param Action $child * @return void */ public function addChild(Action $child): void { if (mb_strpos($child->name, "{$this->name}.") !== 0) { throw new RuntimeException('Bad child'); } $child->setParent($this); $name = mb_substr($child->name, mb_strlen($this->name) + 1); $this->children[$name] = $child; } /** * @return Traversable */ public function getIterator(): Traversable { return new ArrayIterator($this->children); } /** * @return int */ public function count(): int { return count($this->children); } /** * @return array */ #[\ReturnTypeWillChange] public function __debugInfo() { return [ 'name' => $this->name, 'type' => $this->type, 'label' => $this->label, 'params' => $this->params, 'actions' => $this->children ]; } }
php
MIT
97af1bc35b4d1065be46d403134020398dbcc43d
2026-01-04T15:02:35.884566Z
false