diff --git a/system/src/Grav/Common/Assets.php b/system/src/Grav/Common/Assets.php index 8d4190b86..a3634a5d7 100644 --- a/system/src/Grav/Common/Assets.php +++ b/system/src/Grav/Common/Assets.php @@ -1,8 +1,9 @@ getType(), 'inline')) { $this->base_url = rtrim($uri->rootUrl($config->get('system.absolute_urls')), '/') . '/'; - $this->remote = $this->isRemoteLink($asset); + $this->remote = static::isRemoteLink($asset); // Move this to render? if (!$this->remote) { diff --git a/system/src/Grav/Common/Assets/Css.php b/system/src/Grav/Common/Assets/Css.php index 4cc1bf7a9..405d8a347 100644 --- a/system/src/Grav/Common/Assets/Css.php +++ b/system/src/Grav/Common/Assets/Css.php @@ -1,8 +1,9 @@ 0) { + if (trim($buffer) !== '') { file_put_contents($this->assets_dir . $file, $buffer); } } @@ -213,16 +214,16 @@ class Pipeline extends PropertyObject } // Write file - if (\strlen(trim($buffer)) > 0) { + if (trim($buffer) !== '') { file_put_contents($this->assets_dir . $file, $buffer); } } if ($inline_group) { - $output = "renderAttributes(). ">\n" . $buffer . "\n\n"; + $output = 'renderAttributes(). ">\n" . $buffer . "\n\n"; } else { $this->asset = $relative_path; - $output = "\n"; + $output = '\n"; } return $output; @@ -249,7 +250,7 @@ class Pipeline extends PropertyObject $old_url = $matches[2]; - // Ensure link is not rooted to webserver, a data URL, or to a remote host + // Ensure link is not rooted to web server, a data URL, or to a remote host if (Utils::startsWith($old_url, '/') || Utils::startsWith($old_url, 'data:') || $this->isRemoteLink($old_url)) { return $matches[0]; } diff --git a/system/src/Grav/Common/Assets/Traits/AssetUtilsTrait.php b/system/src/Grav/Common/Assets/Traits/AssetUtilsTrait.php index 876a0839c..3a9b3e61c 100644 --- a/system/src/Grav/Common/Assets/Traits/AssetUtilsTrait.php +++ b/system/src/Grav/Common/Assets/Traits/AssetUtilsTrait.php @@ -1,8 +1,9 @@ rootUrl(true); - // sanity check for local URLs with absolute URL's enabled + // Sanity check for local URLs with absolute URL's enabled if (Utils::startsWith($link, $base)) { return false; } @@ -52,12 +53,12 @@ trait AssetUtilsTrait $link = $asset->getAsset(); $relative_path = $link; - if ($this->isRemoteLink($link)) { + if (static::isRemoteLink($link)) { $local = false; if (0 === strpos($link, '//')) { $link = 'http:' . $link; } - $relative_dir = dirname($relative_path); + $relative_dir = \dirname($relative_path); } else { // Fix to remove relative dir if grav is in one if (($this->base_url !== '/') && Utils::startsWith($relative_path, $this->base_url)) { @@ -65,7 +66,7 @@ trait AssetUtilsTrait $relative_path = ltrim(preg_replace($base_url, '/', $link, 1), '/'); } - $relative_dir = dirname($relative_path); + $relative_dir = \dirname($relative_path); $link = ROOT_DIR . $relative_path; } @@ -73,7 +74,7 @@ trait AssetUtilsTrait // No file found, skip it... if ($file === false) { - if (!$local) { // Assume we coudln't download this file for some reason assume it's not pipeline compatible + if (!$local) { // Assume we couldn't download this file for some reason assume it's not pipeline compatible $no_pipeline[$id] = $asset; } continue; @@ -125,8 +126,6 @@ trait AssetUtilsTrait * * Build an HTML attribute string from an array. * - * @param array $attributes - * * @return string */ protected function renderAttributes() @@ -157,6 +156,7 @@ trait AssetUtilsTrait /** * Render Querystring * + * @param string $asset * @return string */ protected function renderQueryString($asset = null) diff --git a/system/src/Grav/Common/Assets/Traits/LegacyAssetsTrait.php b/system/src/Grav/Common/Assets/Traits/LegacyAssetsTrait.php index 664d630d3..8b5954c11 100644 --- a/system/src/Grav/Common/Assets/Traits/LegacyAssetsTrait.php +++ b/system/src/Grav/Common/Assets/Traits/LegacyAssetsTrait.php @@ -1,8 +1,9 @@ collections = $collections; + return $this; } diff --git a/system/src/Grav/Common/Backup/Backups.php b/system/src/Grav/Common/Backup/Backups.php index 95a2e570c..074bc6c80 100644 --- a/system/src/Grav/Common/Backup/Backups.php +++ b/system/src/Grav/Common/Backup/Backups.php @@ -1,8 +1,9 @@ findResource('backup://', true, true); Folder::create(static::$backup_dir); } @@ -53,9 +54,9 @@ class Backups /** @var Inflector $inflector */ $inflector = Grav::instance()['inflector']; - foreach ($this->getBackupProfiles() as $id => $profile) { + foreach (static::getBackupProfiles() as $id => $profile) { $at = $profile['schedule_at']; - $name = $inflector->hyphenize($profile['name']); + $name = $inflector::hyphenize($profile['name']); $logs = 'logs/backup-' . $name . '.out'; /** @var Job $job */ $job = $scheduler->addFunction('Grav\Common\Backup\Backups::backup', [$id], $name ); @@ -86,7 +87,7 @@ class Backups public function getBackupNames() { - return array_column($this->getBackupProfiles(), 'name'); + return array_column(static::getBackupProfiles(), 'name'); } public static function getTotalBackupsSize() @@ -99,7 +100,7 @@ class Backups public static function getAvailableBackups($force = false) { - if ($force || is_null(static::$backups)) { + if ($force || null === static::$backups) { static::$backups = []; $backups_itr = new \GlobIterator(static::$backup_dir . '/*.zip', \FilesystemIterator::KEY_AS_FILENAME); $inflector = Grav::instance()['inflector']; @@ -165,7 +166,7 @@ class Backups } if (!file_exists($backup_root)) { - throw new \RuntimeException("Backup location: " . $backup_root . ' does not exist...'); + throw new \RuntimeException("Backup location: {$backup_root} does not exist..."); } $options = [ @@ -245,6 +246,6 @@ class Backups protected static function convertExclude($exclude) { $lines = preg_split("/[\s,]+/", $exclude); - return array_map('trim', $lines, array_fill(0,count($lines),'/')); + return array_map('trim', $lines, array_fill(0, \count($lines), '/')); } } diff --git a/system/src/Grav/Common/Browser.php b/system/src/Grav/Common/Browser.php index b56bc8e79..037d454e2 100644 --- a/system/src/Grav/Common/Browser.php +++ b/system/src/Grav/Common/Browser.php @@ -1,8 +1,9 @@ getLongVersion()); - return intval($version[0]); + return (int)$version[0]; } /** @@ -143,10 +144,6 @@ class Browser */ public function isTrackable(): bool { - if (isset($_SERVER['HTTP_DNT']) && $_SERVER['HTTP_DNT'] === '1') { - return false; - } - - return true; + return !(isset($_SERVER['HTTP_DNT']) && $_SERVER['HTTP_DNT'] === '1'); } } diff --git a/system/src/Grav/Common/Cache.php b/system/src/Grav/Common/Cache.php index bfbdda60c..d868cf5cf 100644 --- a/system/src/Grav/Common/Cache.php +++ b/system/src/Grav/Common/Cache.php @@ -1,8 +1,9 @@ config = $grav['config']; $this->now = time(); - if (is_null($this->enabled)) { + if (null === $this->enabled) { $this->enabled = (bool)$this->config->get('system.cache.enabled'); } @@ -147,7 +150,7 @@ class Cache extends Getters foreach (new \DirectoryIterator($cache_dir) as $file) { $dir = $file->getBasename(); - if ($file->isDot() || $file->isFile() || $dir === $current) { + if ($dir === $current || $file->isDot() || $file->isFile()) { continue; } @@ -165,7 +168,7 @@ class Cache extends Getters */ public function setEnabled($enabled) { - $this->enabled = (bool) $enabled; + $this->enabled = (bool)$enabled; } /** @@ -202,19 +205,15 @@ class Cache extends Getters // CLI compatibility requires a non-volatile cache driver if ($this->config->get('system.cache.cli_compatibility') && ( - $setting == 'auto' || $this->isVolatileDriver($setting))) { + $setting === 'auto' || $this->isVolatileDriver($setting))) { $setting = $driver_name; } - if (!$setting || $setting == 'auto') { + if (!$setting || $setting === 'auto') { if (extension_loaded('apcu')) { $driver_name = 'apcu'; - } elseif (extension_loaded('apc')) { - $driver_name = 'apc'; } elseif (extension_loaded('wincache')) { $driver_name = 'wincache'; - } elseif (extension_loaded('xcache')) { - $driver_name = 'xcache'; } } else { $driver_name = $setting; @@ -224,9 +223,6 @@ class Cache extends Getters switch ($driver_name) { case 'apc': - $driver = new DoctrineCache\ApcCache(); - break; - case 'apcu': $driver = new DoctrineCache\ApcuCache(); break; @@ -235,10 +231,6 @@ class Cache extends Getters $driver = new DoctrineCache\WinCacheCache(); break; - case 'xcache': - $driver = new DoctrineCache\XcacheCache(); - break; - case 'memcache': $memcache = new \Memcache(); $memcache->connect($this->config->get('system.cache.memcache.server', 'localhost'), @@ -295,9 +287,9 @@ class Cache extends Getters { if ($this->enabled) { return $this->driver->fetch($id); - } else { - return false; } + + return false; } /** @@ -328,6 +320,7 @@ class Cache extends Getters if ($this->enabled) { return $this->driver->delete($id); } + return false; } @@ -341,6 +334,7 @@ class Cache extends Getters if ($this->enabled) { return $this->driver->deleteAll(); } + return false; } @@ -355,6 +349,7 @@ class Cache extends Getters if ($this->enabled) { return $this->driver->contains(($id)); } + return false; } @@ -459,7 +454,7 @@ class Cache extends Getters $output[] = ''; - if (($remove == 'all' || $remove == 'standard') && file_exists($user_config)) { + if (($remove === 'all' || $remove === 'standard') && file_exists($user_config)) { touch($user_config); $output[] = 'Touched: ' . $user_config; @@ -540,17 +535,17 @@ class Cache extends Getters { if (in_array($setting, ['apc', 'apcu', 'xcache', 'wincache'])) { return true; - } else { - return false; } + + return false; } public static function purgeJob() { $cache = Grav::instance()['cache']; $deleted_folders = $cache->purgeOldCache(); - $msg = 'Purged ' . $deleted_folders . ' old cache folders...'; - return $msg; + + return 'Purged ' . $deleted_folders . ' old cache folders...'; } public function onSchedulerInitialized(Event $event) diff --git a/system/src/Grav/Common/Composer.php b/system/src/Grav/Common/Composer.php index 65c994564..c6abb2c6c 100644 --- a/system/src/Grav/Common/Composer.php +++ b/system/src/Grav/Common/Composer.php @@ -1,8 +1,9 @@ version = 2; + } /** * Returns checksum from the configuration files. diff --git a/system/src/Grav/Common/Config/CompiledConfig.php b/system/src/Grav/Common/Config/CompiledConfig.php index 955e0d8e6..1c92edd9a 100644 --- a/system/src/Grav/Common/Config/CompiledConfig.php +++ b/system/src/Grav/Common/Config/CompiledConfig.php @@ -1,8 +1,9 @@ version = 1; + } + /** * Set blueprints for the configuration. * diff --git a/system/src/Grav/Common/Config/CompiledLanguages.php b/system/src/Grav/Common/Config/CompiledLanguages.php index 610e347df..ef18145c8 100644 --- a/system/src/Grav/Common/Config/CompiledLanguages.php +++ b/system/src/Grav/Common/Config/CompiledLanguages.php @@ -1,8 +1,9 @@ version = 1; + } /** * Create configuration object. diff --git a/system/src/Grav/Common/Config/Config.php b/system/src/Grav/Common/Config/Config.php index 56e4ebf5b..1635bd382 100644 --- a/system/src/Grav/Common/Config/Config.php +++ b/system/src/Grav/Common/Config/Config.php @@ -1,8 +1,9 @@ getUri()->getHost(); diff --git a/system/src/Grav/Common/Data/Blueprint.php b/system/src/Grav/Common/Data/Blueprint.php index f7c669ab2..cde533d79 100644 --- a/system/src/Grav/Common/Data/Blueprint.php +++ b/system/src/Grav/Common/Data/Blueprint.php @@ -1,8 +1,9 @@ translate('GRAV.FORM.INVALID_INPUT', null, true) . ' "' . $language->translate($name) . '"'; + // Validate type with fallback type text. + $method = 'type' . str_replace('-', '_', $type); + // If this is a YAML field validate/filter as such - if ($type !== 'yaml' && isset($field['yaml']) && $field['yaml'] === true) { + if (isset($field['yaml']) && $field['yaml'] === true) { $method = 'typeYaml'; } - if (method_exists(__CLASS__, $method)) { - $success = self::$method($value, $validate, $field); - } else { - $success = true; - } + $messages = []; + $success = method_exists(__CLASS__, $method) ? self::$method($value, $validate, $field) : true; if (!$success) { $messages[$field['name']][] = $message; } @@ -89,7 +86,7 @@ class Validation */ public static function filter($value, array $field) { - $validate = isset($field['validate']) ? (array) $field['validate'] : []; + $validate = (array)($field['validate'] ?? null); // If value isn't required, we will return null if empty value is given. if (($value === null || $value === '') && empty($validate['required'])) { @@ -99,14 +96,12 @@ class Validation if (!isset($field['type'])) { $field['type'] = 'text'; } + $type = $field['validate']['type'] ?? $field['type']; - - // Validate type with fallback type text. - $type = (string) isset($field['validate']['type']) ? $field['validate']['type'] : $field['type']; $method = 'filter' . ucfirst(str_replace('-', '_', $type)); // If this is a YAML field validate/filter as such - if ($type !== 'yaml' && isset($field['yaml']) && $field['yaml'] === true) { + if (isset($field['yaml']) && $field['yaml'] === true) { $method = 'filterYaml'; } @@ -261,8 +256,8 @@ class Validation */ public static function typeCheckbox($value, array $params, array $field) { - $value = (string) $value; - $field_value = (string) ($field['value'] ?? '1'); + $value = (string)$value; + $field_value = (string)($field['value'] ?? '1'); return $value === $field_value; } @@ -303,12 +298,12 @@ class Validation */ public static function typeFile($value, array $params, array $field) { - return self::typeArray((array) $value, $params, $field); + return self::typeArray((array)$value, $params, $field); } protected static function filterFile($value, array $params, array $field) { - return (array) $value; + return (array)$value; } /** @@ -758,7 +753,7 @@ class Validation public static function validateInt($value, $params) { - return is_numeric($value) && (int) $value == $value; + return is_numeric($value) && (int)$value == $value; } protected static function filterInt($value, $params) diff --git a/system/src/Grav/Common/Data/ValidationException.php b/system/src/Grav/Common/Data/ValidationException.php index 5b96cec0d..8bdb0572d 100644 --- a/system/src/Grav/Common/Data/ValidationException.php +++ b/system/src/Grav/Common/Data/ValidationException.php @@ -1,8 +1,9 @@ enabled()) { + if (strpos($name, '_') === 0 || $this->enabled()) { $this->debugbar['time']->startMeasure($name, $description); $this->timers[] = $name; } @@ -286,7 +287,7 @@ class Debugger */ public function stopTimer($name) { - if (\in_array($name, $this->timers, true) && ($name[0] === '_' || $this->enabled())) { + if (\in_array($name, $this->timers, true) && (strpos($name, '_') === 0 || $this->enabled())) { $this->debugbar['time']->stopMeasure($name); } @@ -319,7 +320,7 @@ class Debugger */ public function addException(\Exception $e) { - if ($this->enabled() && $this->initialized) { + if ($this->initialized && $this->enabled()) { $this->debugbar['exceptions']->addException($e); } diff --git a/system/src/Grav/Common/Errors/BareHandler.php b/system/src/Grav/Common/Errors/BareHandler.php index 25c0e0ae9..52effc6d4 100644 --- a/system/src/Grav/Common/Errors/BareHandler.php +++ b/system/src/Grav/Common/Errors/BareHandler.php @@ -1,8 +1,9 @@ get('system.errors'); - $jsonRequest = $_SERVER && isset($_SERVER['HTTP_ACCEPT']) && $_SERVER['HTTP_ACCEPT'] == 'application/json'; + $jsonRequest = $_SERVER && isset($_SERVER['HTTP_ACCEPT']) && $_SERVER['HTTP_ACCEPT'] === 'application/json'; // Setup Whoops-based error handler $system = new SystemFacade; - $whoops = new \Whoops\Run($system); + $whoops = new Whoops\Run($system); $verbosity = 1; @@ -49,17 +50,8 @@ class Errors break; } - if (method_exists('Whoops\Util\Misc', 'isAjaxRequest')) { //Whoops 2.0 - if (Whoops\Util\Misc::isAjaxRequest() || $jsonRequest) { - $whoops->pushHandler(new Whoops\Handler\JsonResponseHandler); - } - } elseif (function_exists('Whoops\isAjaxRequest')) { //Whoops 2.0.0-alpha - if (Whoops\isAjaxRequest() || $jsonRequest) { - $whoops->pushHandler(new Whoops\Handler\JsonResponseHandler); - } - } else { //Whoops 1.x - $json_page = new Whoops\Handler\JsonResponseHandler; - $json_page->onlyForAjaxRequests(true); + if (Whoops\Util\Misc::isAjaxRequest() || $jsonRequest) { + $whoops->pushHandler(new Whoops\Handler\JsonResponseHandler); } if (isset($config['log']) && $config['log']) { diff --git a/system/src/Grav/Common/Errors/SimplePageHandler.php b/system/src/Grav/Common/Errors/SimplePageHandler.php index 829f596e7..f6a23e665 100644 --- a/system/src/Grav/Common/Errors/SimplePageHandler.php +++ b/system/src/Grav/Common/Errors/SimplePageHandler.php @@ -1,8 +1,9 @@ searchPaths[] = __DIR__ . "/Resources"; + $this->searchPaths[] = __DIR__ . '/Resources'; } /** @@ -31,8 +32,8 @@ class SimplePageHandler extends Handler $inspector = $this->getInspector(); $helper = new TemplateHelper(); - $templateFile = $this->getResource("layout.html.php"); - $cssFile = $this->getResource("error.css"); + $templateFile = $this->getResource('layout.html.php'); + $cssFile = $this->getResource('error.css'); $code = $inspector->getException()->getCode(); if ( ($code >= 400) && ($code < 600) ) @@ -46,9 +47,9 @@ class SimplePageHandler extends Handler } $vars = array( - "stylesheet" => file_get_contents($cssFile), - "code" => $code, - "message" => filter_var(rawurldecode($message), FILTER_SANITIZE_STRING), + 'stylesheet' => file_get_contents($cssFile), + 'code' => $code, + 'message' => filter_var(rawurldecode($message), FILTER_SANITIZE_STRING), ); $helper->setVariables($vars); @@ -74,7 +75,7 @@ class SimplePageHandler extends Handler // Search through available search paths, until we find the // resource we're after: foreach ($this->searchPaths as $path) { - $fullPath = $path . "/$resource"; + $fullPath = "{$path}/{$resource}"; if (is_file($fullPath)) { // Cache the result: diff --git a/system/src/Grav/Common/Errors/SystemFacade.php b/system/src/Grav/Common/Errors/SystemFacade.php index 5b73a2b77..02ef0cf8c 100644 --- a/system/src/Grav/Common/Errors/SystemFacade.php +++ b/system/src/Grav/Common/Errors/SystemFacade.php @@ -1,8 +1,9 @@ getFilename()[0] === '.') { + if (strpos($file->getFilename(), '.') === 0) { continue; } if (!$folders && $file->isDir()) { @@ -255,7 +257,7 @@ abstract class Folder if (isset($filters['value'])) { $filter = $filters['value']; if (is_callable($filter)) { - $filePath = call_user_func($filter, $file); + $filePath = $filter($file); } else { $filePath = preg_replace($filter, '', $filePath); } diff --git a/system/src/Grav/Common/Filesystem/RecursiveDirectoryFilterIterator.php b/system/src/Grav/Common/Filesystem/RecursiveDirectoryFilterIterator.php index e972eba50..e14e347f8 100644 --- a/system/src/Grav/Common/Filesystem/RecursiveDirectoryFilterIterator.php +++ b/system/src/Grav/Common/Filesystem/RecursiveDirectoryFilterIterator.php @@ -1,8 +1,9 @@ current(); - if ($current->isDir() && !in_array($current->getFilename(), $this::$ignore_folders, true)) { - return true; - } - return false; + return $current->isDir() && !in_array($current->getFilename(), $this::$ignore_folders, true); } } diff --git a/system/src/Grav/Common/Filesystem/ZipArchiver.php b/system/src/Grav/Common/Filesystem/ZipArchiver.php index c29f25cad..bc5aac97d 100644 --- a/system/src/Grav/Common/Filesystem/ZipArchiver.php +++ b/system/src/Grav/Common/Filesystem/ZipArchiver.php @@ -1,8 +1,9 @@ items as $name => $package) { - $items[$name] = $package->toArray(); - } - - return json_encode($items); + return json_encode($this->toArray()); } public function toArray() diff --git a/system/src/Grav/Common/GPM/Common/AbstractPackageCollection.php b/system/src/Grav/Common/GPM/Common/AbstractPackageCollection.php index 78d93bce7..bc4ecab9d 100644 --- a/system/src/Grav/Common/GPM/Common/AbstractPackageCollection.php +++ b/system/src/Grav/Common/GPM/Common/AbstractPackageCollection.php @@ -1,8 +1,9 @@ $item) { + foreach (self::$cache[get_called_class() . __METHOD__] as $name => $item) { $this->append([$name => $item]); } } diff --git a/system/src/Grav/Common/GPM/Common/Package.php b/system/src/Grav/Common/GPM/Common/Package.php index fe4618af7..dc799adf9 100644 --- a/system/src/Grav/Common/GPM/Common/Package.php +++ b/system/src/Grav/Common/GPM/Common/Package.php @@ -1,8 +1,9 @@ data = $package; if ($type) { @@ -22,28 +24,38 @@ class Package { } } - public function getData() { + public function getData() + { return $this->data; } - public function __get($key) { + public function __get($key) + { return $this->data->get($key); } - public function __isset($key) { - return isset($this->data->$key); + public function __set($key, $value) + { + throw new $this->data->set($key, $value); } - public function __toString() { + public function __isset($key) + { + return isset($this->data->{$key}); + } + + public function __toString() + { return $this->toJson(); } - public function toJson() { + public function toJson() + { return $this->data->toJson(); } - public function toArray() { + public function toArray() + { return $this->data->toArray(); } - } diff --git a/system/src/Grav/Common/GPM/GPM.php b/system/src/Grav/Common/GPM/GPM.php index 696ba657c..bb4ab67fc 100644 --- a/system/src/Grav/Common/GPM/GPM.php +++ b/system/src/Grav/Common/GPM/GPM.php @@ -1,8 +1,9 @@ available = $remote_version; $repository[$slug]->version = $local_version; - $repository[$slug]->name = $repository[$slug]->name; $repository[$slug]->type = $repository[$slug]->release_type; $items[$slug] = $repository[$slug]; } @@ -322,7 +322,7 @@ class GPM extends Iterator continue; } - $local_version = $plugin->version ? $plugin->version : 'Unknown'; + $local_version = $plugin->version ?: 'Unknown'; $remote_version = $repository[$slug]->version; if (version_compare($local_version, $remote_version) < 0) { @@ -564,31 +564,33 @@ class GPM extends Iterator file_exists($source . 'system/config/system.yaml') ) { return 'grav'; - } else { - // must have a blueprint - if (!file_exists($source . 'blueprints.yaml')) { - return false; - } + } - // either theme or plugin - $name = basename($source); - if (Utils::contains($name, 'theme')) { - return 'theme'; - } elseif (Utils::contains($name, 'plugin')) { - return 'plugin'; - } - foreach (glob($source . "*.php") as $filename) { - $contents = file_get_contents($filename); - if (preg_match($theme_regex, $contents)) { - return 'theme'; - } elseif (preg_match($plugin_regex, $contents)) { - return 'plugin'; - } - } + // must have a blueprint + if (!file_exists($source . 'blueprints.yaml')) { + return false; + } - // Assume it's a theme + // either theme or plugin + $name = basename($source); + if (Utils::contains($name, 'theme')) { return 'theme'; } + if (Utils::contains($name, 'plugin')) { + return 'plugin'; + } + foreach (glob($source . '*.php') as $filename) { + $contents = file_get_contents($filename); + if (preg_match($theme_regex, $contents)) { + return 'theme'; + } + if (preg_match($plugin_regex, $contents)) { + return 'plugin'; + } + } + + // Assume it's a theme + return 'theme'; } /** @@ -601,7 +603,7 @@ class GPM extends Iterator { $ignore_yaml_files = ['blueprints', 'languages']; - foreach (glob($source . "*.yaml") as $filename) { + foreach (glob($source . '*.yaml') as $filename) { $name = strtolower(basename($filename, '.yaml')); if (in_array($name, $ignore_yaml_files)) { continue; @@ -642,7 +644,7 @@ class GPM extends Iterator { $locator = Grav::instance()['locator']; - if ($type == 'theme') { + if ($type === 'theme') { $install_path = $locator->findResource('themes://', false) . DS . $name; } else { $install_path = $locator->findResource('plugins://', false) . DS . $name; @@ -692,7 +694,7 @@ class GPM extends Iterator } $not_found = new \stdClass(); - $not_found->name = $inflector->camelize($search); + $not_found->name = $inflector::camelize($search); $not_found->slug = $search; $not_found->package_type = $type; $not_found->install_path = str_replace('%name%', $search, $this->install_paths[$type]); @@ -726,7 +728,7 @@ class GPM extends Iterator $dependency = $dependency['name']; } - if ($dependency == $slug) { + if ($dependency === $slug) { $dependent_packages[] = $package_name; } } @@ -833,19 +835,19 @@ class GPM extends Iterator { $dependencies = $this->calculateMergedDependenciesOfPackages($packages); foreach ($dependencies as $dependency_slug => $dependencyVersionWithOperator) { - if (in_array($dependency_slug, $packages)) { + if (\in_array($dependency_slug, $packages, true)) { unset($dependencies[$dependency_slug]); continue; } // Check PHP version - if ($dependency_slug == 'php') { + if ($dependency_slug === 'php') { $current_php_version = phpversion(); if (version_compare($this->calculateVersionNumberFromDependencyVersion($dependencyVersionWithOperator), $current_php_version) === 1 ) { //Needs a Grav update first - throw new \Exception("One of the packages require PHP " . $dependencies['php'] . ". Please update PHP to resolve this"); + throw new \RuntimeException("One of the packages require PHP {$dependencies['php']}. Please update PHP to resolve this"); } else { unset($dependencies[$dependency_slug]); continue; @@ -853,12 +855,12 @@ class GPM extends Iterator } //First, check for Grav dependency. If a dependency requires Grav > the current version, abort and tell. - if ($dependency_slug == 'grav') { + if ($dependency_slug === 'grav') { if (version_compare($this->calculateVersionNumberFromDependencyVersion($dependencyVersionWithOperator), GRAV_VERSION) === 1 ) { //Needs a Grav update first - throw new \Exception("One of the packages require Grav " . $dependencies['grav'] . ". Please update Grav to the latest release."); + throw new \RuntimeException("One of the packages require Grav {$dependencies['grav']}. Please update Grav to the latest release."); } else { unset($dependencies[$dependency_slug]); continue; @@ -888,7 +890,7 @@ class GPM extends Iterator $currentlyInstalledVersion); if (!$compatible) { - throw new \Exception('Dependency ' . $dependency_slug . ' is required in an older version than the one installed. This package must be updated. Please get in touch with its developer.', + throw new \RuntimeException('Dependency ' . $dependency_slug . ' is required in an older version than the one installed. This package must be updated. Please get in touch with its developer.', 2); } } @@ -899,7 +901,7 @@ class GPM extends Iterator if ($this->firstVersionIsLower($latestRelease, $dependencyVersion)) { //throw an exception if a required version cannot be found in the GPM yet - throw new \Exception('Dependency ' . $package_yaml['name'] . ' is required in version ' . $dependencyVersion . ' which is higher than the latest release, ' . $latestRelease . '. Try running `bin/gpm -f index` to force a refresh of the GPM cache', + throw new \RuntimeException('Dependency ' . $package_yaml['name'] . ' is required in version ' . $dependencyVersion . ' which is higher than the latest release, ' . $latestRelease . '. Try running `bin/gpm -f index` to force a refresh of the GPM cache', 1); } @@ -950,7 +952,7 @@ class GPM extends Iterator private function firstVersionIsLower($firstVersion, $secondVersion) { - return version_compare($firstVersion, $secondVersion) == -1; + return version_compare($firstVersion, $secondVersion) === -1; } /** @@ -1005,7 +1007,7 @@ class GPM extends Iterator $current_package_version_number = $this->calculateVersionNumberFromDependencyVersion($current_package_version_information); if (!$current_package_version_number) { - throw new \Exception('Bad format for version of dependency ' . $current_package_name . ' for package ' . $packageName, + throw new \RuntimeException('Bad format for version of dependency ' . $current_package_name . ' for package ' . $packageName, 1); } @@ -1021,7 +1023,7 @@ class GPM extends Iterator if (!$currently_stored_version_is_in_next_significant_release_format && !$current_package_version_is_in_next_significant_release_format) { //Comparing versions equals or higher, a simple version_compare is enough if (version_compare($currently_stored_version_number, - $current_package_version_number) == -1 + $current_package_version_number) === -1 ) { //Current package version is higher $dependencies[$current_package_name] = $current_package_version_information; } @@ -1029,7 +1031,7 @@ class GPM extends Iterator $compatible = $this->checkNextSignificantReleasesAreCompatible($currently_stored_version_number, $current_package_version_number); if (!$compatible) { - throw new \Exception('Dependency ' . $current_package_name . ' is required in two incompatible versions', + throw new \RuntimeException('Dependency ' . $current_package_name . ' is required in two incompatible versions', 2); } } @@ -1076,17 +1078,19 @@ class GPM extends Iterator */ public function calculateVersionNumberFromDependencyVersion($version) { - if ($version == '*') { + if ($version === '*') { return null; - } elseif ($version == '') { - return null; - } elseif ($this->versionFormatIsNextSignificantRelease($version)) { - return trim(substr($version, 1)); - } elseif ($this->versionFormatIsEqualOrHigher($version)) { - return trim(substr($version, 2)); - } else { - return $version; } + if ($version === '') { + return null; + } + if ($this->versionFormatIsNextSignificantRelease($version)) { + return trim(substr($version, 1)); + } + if ($this->versionFormatIsEqualOrHigher($version)) { + return trim(substr($version, 2)); + } + return $version; } /** @@ -1100,7 +1104,7 @@ class GPM extends Iterator */ public function versionFormatIsNextSignificantRelease($version) { - return substr($version, 0, 1) == '~'; + return strpos($version, '~') === 0; } /** @@ -1114,7 +1118,7 @@ class GPM extends Iterator */ public function versionFormatIsEqualOrHigher($version) { - return substr($version, 0, 2) == '>='; + return strpos($version, '>=') === 0; } /** @@ -1135,12 +1139,12 @@ class GPM extends Iterator $version1array = explode('.', $version1); $version2array = explode('.', $version2); - if (count($version1array) > count($version2array)) { + if (\count($version1array) > \count($version2array)) { list($version1array, $version2array) = [$version2array, $version1array]; } $i = 0; - while ($i < count($version1array) - 1) { + while ($i < \count($version1array) - 1) { if ($version1array[$i] != $version2array[$i]) { return false; } diff --git a/system/src/Grav/Common/GPM/Installer.php b/system/src/Grav/Common/GPM/Installer.php index f16cdcca8..b29350808 100644 --- a/system/src/Grav/Common/GPM/Installer.php +++ b/system/src/Grav/Common/GPM/Installer.php @@ -1,8 +1,9 @@ getNameIndex(0)); $zip->close(); - $extracted_folder = $destination . '/' . $package_folder_name; - return $extracted_folder; + return $destination . '/' . $package_folder_name; } self::$error = self::ZIP_EXTRACT_ERROR; @@ -216,7 +216,7 @@ class Installer $install_file = $installer_file_folder . DS . 'install.php'; if (file_exists($install_file)) { - require_once($install_file); + require_once $install_file; } else { return null; } @@ -279,10 +279,10 @@ class Installer { if (empty($source_path)) { throw new \RuntimeException("Directory $source_path is missing"); - } else { - Folder::rcopy($source_path, $install_path); } + Folder::rcopy($source_path, $install_path); + return true; } @@ -296,7 +296,7 @@ class Installer { foreach (new \DirectoryIterator($source_path) as $file) { - if ($file->isLink() || $file->isDot() || in_array($file->getFilename(), $ignores)) { + if ($file->isLink() || $file->isDot() || \in_array($file->getFilename(), $ignores, true)) { continue; } @@ -385,11 +385,11 @@ class Installer self::$error = self::NOT_DIRECTORY; } - if (count($exclude) && in_array(self::$error, $exclude)) { + if (\count($exclude) && \in_array(self::$error, $exclude, true)) { return true; } - return !(self::$error); + return !self::$error; } /** @@ -469,23 +469,23 @@ class Installer if (self::$error_zip) { switch(self::$error_zip) { case \ZipArchive::ER_EXISTS: - $msg .= "File already exists."; + $msg .= 'File already exists.'; break; case \ZipArchive::ER_INCONS: - $msg .= "Zip archive inconsistent."; + $msg .= 'Zip archive inconsistent.'; break; case \ZipArchive::ER_MEMORY: - $msg .= "Malloc failure."; + $msg .= 'Memory allocation failure.'; break; case \ZipArchive::ER_NOENT: - $msg .= "No such file."; + $msg .= 'No such file.'; break; case \ZipArchive::ER_NOZIP: - $msg .= "Not a zip archive."; + $msg .= 'Not a zip archive.'; break; case \ZipArchive::ER_OPEN: @@ -493,11 +493,11 @@ class Installer break; case \ZipArchive::ER_READ: - $msg .= "Read error."; + $msg .= 'Read error.'; break; case \ZipArchive::ER_SEEK: - $msg .= "Seek error."; + $msg .= 'Seek error.'; break; } } diff --git a/system/src/Grav/Common/GPM/Licenses.php b/system/src/Grav/Common/GPM/Licenses.php index 517174c12..cd596a214 100644 --- a/system/src/Grav/Common/GPM/Licenses.php +++ b/system/src/Grav/Common/GPM/Licenses.php @@ -1,8 +1,9 @@ content(); + $data = (array)$licenses->content(); $slug = strtolower($slug); if ($license && !self::validate($license)) { return false; } - if (!is_string($license)) { + if (!\is_string($license)) { if (isset($data['licenses'][$slug])) { unset($data['licenses'][$slug]); } else { @@ -68,24 +69,20 @@ class Licenses * * @param $slug * - * @return string + * @return array|string */ public static function get($slug = null) { $licenses = self::getLicenseFile(); - $data = $licenses->content(); + $data = (array)$licenses->content(); $licenses->free(); $slug = strtolower($slug); if (!$slug) { - return isset($data['licenses']) ? $data['licenses'] : []; + return $data['licenses'] ?? []; } - if (!isset($data['licenses']) || !isset($data['licenses'][$slug])) { - return ''; - } - - return $data['licenses'][$slug]; + return $data['licenses'][$slug] ?? ''; } diff --git a/system/src/Grav/Common/GPM/Local/AbstractPackageCollection.php b/system/src/Grav/Common/GPM/Local/AbstractPackageCollection.php index b9762085c..68b3df651 100644 --- a/system/src/Grav/Common/GPM/Local/AbstractPackageCollection.php +++ b/system/src/Grav/Common/GPM/Local/AbstractPackageCollection.php @@ -1,8 +1,9 @@ min_php)) { + if (null === $this->min_php) { $this->min_php = phpversion(); } return $this->min_php; diff --git a/system/src/Grav/Common/GPM/Remote/Package.php b/system/src/Grav/Common/GPM/Remote/Package.php index 830f63dd5..749851d76 100644 --- a/system/src/Grav/Common/GPM/Remote/Package.php +++ b/system/src/Grav/Common/GPM/Remote/Package.php @@ -1,8 +1,9 @@ 1 ? $args : array_shift($args); $uri = $args[0]; - $options = $args[1]; - $callback = $args[2]; + $options = $args[1] ?? []; + $callback = $args[2] ?? null; $ch = curl_init($uri); @@ -381,7 +382,7 @@ class Response return curl_exec($ch); } - $max_redirects = isset($options['curl'][CURLOPT_MAXREDIRS]) ? $options['curl'][CURLOPT_MAXREDIRS] : 5; + $max_redirects = $options['curl'][CURLOPT_MAXREDIRS] ?? 5; $options['curl'][CURLOPT_FOLLOWLOCATION] = false; // open_basedir set but no redirects to follow, we can disable followlocation and proceed normally @@ -405,8 +406,8 @@ class Response if (curl_errno($rch)) { $code = 0; } else { - $code = curl_getinfo($rch, CURLINFO_HTTP_CODE); - if ($code == 301 || $code == 302 || $code == 303) { + $code = (int)curl_getinfo($rch, CURLINFO_HTTP_CODE); + if ($code === 301 || $code === 302 || $code === 303) { preg_match('/Location:(.*?)\n/', $header, $matches); $uri = trim(array_pop($matches)); } else { diff --git a/system/src/Grav/Common/GPM/Upgrader.php b/system/src/Grav/Common/GPM/Upgrader.php index 1c995bc4c..5d9406d5a 100644 --- a/system/src/Grav/Common/GPM/Upgrader.php +++ b/system/src/Grav/Common/GPM/Upgrader.php @@ -1,8 +1,9 @@ min_php)) { + if (null === $this->min_php) { $this->min_php = $this->remote->getMinPHPVersion(); } return $this->min_php; @@ -125,7 +126,7 @@ class Upgrader */ public function isUpgradable() { - return version_compare($this->getLocalVersion(), $this->getRemoteVersion(), "<"); + return version_compare($this->getLocalVersion(), $this->getRemoteVersion(), '<'); } /** diff --git a/system/src/Grav/Common/Getters.php b/system/src/Grav/Common/Getters.php index 6f58fba20..e69116e15 100644 --- a/system/src/Grav/Common/Getters.php +++ b/system/src/Grav/Common/Getters.php @@ -1,8 +1,9 @@ gettersVariable; return isset($this->{$var}[$offset]); - } else { - return isset($this->{$offset}); } + + return isset($this->{$offset}); } /** @@ -88,10 +89,10 @@ abstract class Getters implements \ArrayAccess, \Countable if ($this->gettersVariable) { $var = $this->gettersVariable; - return isset($this->{$var}[$offset]) ? $this->{$var}[$offset] : null; - } else { - return isset($this->{$offset}) ? $this->{$offset} : null; + return $this->{$var}[$offset] ?? null; } + + return $this->{$offset} ?? null; } /** @@ -128,10 +129,10 @@ abstract class Getters implements \ArrayAccess, \Countable { if ($this->gettersVariable) { $var = $this->gettersVariable; - count($this->{$var}); - } else { - count($this->toArray()); + return \count($this->{$var}); } + + return \count($this->toArray()); } /** @@ -145,16 +146,16 @@ abstract class Getters implements \ArrayAccess, \Countable $var = $this->gettersVariable; return $this->{$var}; - } else { - $properties = (array)$this; - $list = []; - foreach ($properties as $property => $value) { - if ($property[0] != "\0") { - $list[$property] = $value; - } - } - - return $list; } + + $properties = (array)$this; + $list = []; + foreach ($properties as $property => $value) { + if ($property[0] !== "\0") { + $list[$property] = $value; + } + } + + return $list; } } diff --git a/system/src/Grav/Common/Grav.php b/system/src/Grav/Common/Grav.php index 92b9649c7..cffb7c92c 100644 --- a/system/src/Grav/Common/Grav.php +++ b/system/src/Grav/Common/Grav.php @@ -1,8 +1,9 @@ media(); @@ -247,10 +248,10 @@ class Excerpts $medium = static::processMediaActions($medium, $url_parts); $element_excerpt = $excerpt['element']['attributes']; - $alt = isset($element_excerpt['alt']) ? $element_excerpt['alt'] : ''; - $title = isset($element_excerpt['title']) ? $element_excerpt['title'] : ''; - $class = isset($element_excerpt['class']) ? $element_excerpt['class'] : ''; - $id = isset($element_excerpt['id']) ? $element_excerpt['id'] : ''; + $alt = $element_excerpt['alt'] ?? ''; + $title = $element_excerpt['title'] ?? ''; + $class = $element_excerpt['class'] ?? ''; + $id = $element_excerpt['id'] ?? ''; $excerpt['element'] = $medium->parsedownElement($title, $alt, $class, $id, true); @@ -283,7 +284,7 @@ class Excerpts if (isset($url_parts['query'])) { $actions = array_reduce(explode('&', $url_parts['query']), function ($carry, $item) { $parts = explode('=', $item, 2); - $value = isset($parts[1]) ? $parts[1] : null; + $value = $parts[1] ?? null; $carry[] = ['method' => $parts[0], 'params' => $value]; return $carry; @@ -357,6 +358,10 @@ class Excerpts /** @var UniformResourceLocator $locator */ $locator = Grav::instance()['locator']; - return $locator->isStream($url) ? ($locator->findResource($url, false) ?: $locator->findResource($url, false, true)) : $url; + if ($locator->isStream($url)) { + return $locator->findResource($url, false) ?: $locator->findResource($url, false, true); + } + + return $url; } } diff --git a/system/src/Grav/Common/Helpers/Exif.php b/system/src/Grav/Common/Helpers/Exif.php index ee0c4cae7..15aff6677 100644 --- a/system/src/Grav/Common/Helpers/Exif.php +++ b/system/src/Grav/Common/Helpers/Exif.php @@ -1,15 +1,15 @@ getElementsByTagName("body")->item(0); + $body = $dom->getElementsByTagName('body')->item(0); // Iterate over words. $words = new DOMWordsIterator($body); @@ -81,9 +82,9 @@ class Truncator { // Return original HTML if not truncated. if ($truncated) { return self::innerHTML($body); - } else { - return $html; } + + return $html; } /** @@ -93,7 +94,7 @@ class Truncator { * @param string $ellipsis String to use as ellipsis (if any). * @return string Safe truncated HTML. */ - public static function truncateLetters($html, $limit = 0, $ellipsis = "") + public static function truncateLetters($html, $limit = 0, $ellipsis = '') { if ($limit <= 0) { return $html; @@ -129,9 +130,9 @@ class Truncator { // Return original HTML if not truncated. if ($truncated) { return self::innerHTML($body); - } else { - return $html; } + + return $html; } /** diff --git a/system/src/Grav/Common/Inflector.php b/system/src/Grav/Common/Inflector.php index 169e9a356..82fc6dd18 100644 --- a/system/src/Grav/Common/Inflector.php +++ b/system/src/Grav/Common/Inflector.php @@ -1,15 +1,14 @@ y > 0) { - $diff->m = $diff->m + 12 * $diff->y; + $diff->m += 12 * $diff->y; } return $diff->m; diff --git a/system/src/Grav/Common/Iterator.php b/system/src/Grav/Common/Iterator.php index 9bf31c353..d8e40456c 100644 --- a/system/src/Grav/Common/Iterator.php +++ b/system/src/Grav/Common/Iterator.php @@ -1,8 +1,9 @@ active ? $this->active : $this->default; + return $this->active ?: $this->default; } /** @@ -314,7 +315,8 @@ class Language * $this->grav['pages']->init(); * ``` */ - public function resetFallbackPageExtensions() { + public function resetFallbackPageExtensions() + { $this->page_extensions = null; } diff --git a/system/src/Grav/Common/Language/LanguageCodes.php b/system/src/Grav/Common/Language/LanguageCodes.php index a411ae43d..780df7c02 100644 --- a/system/src/Grav/Common/Language/LanguageCodes.php +++ b/system/src/Grav/Common/Language/LanguageCodes.php @@ -1,8 +1,9 @@ addPage($page); } + return $this; } @@ -117,6 +119,7 @@ class Collection extends Iterator $this->items = array_uintersect($array1, $array2, function($val1, $val2) { return strcmp($val1['slug'], $val2['slug']); }); + return $this; } @@ -130,6 +133,7 @@ class Collection extends Iterator public function setParams(array $params) { $this->params = array_merge($this->params, $params); + return $this; } @@ -166,7 +170,7 @@ class Collection extends Iterator */ public function offsetGet($offset) { - return !empty($this->items[$offset]) ? $this->pages->get($offset) : null; + return $this->pages->get($offset) ?: null; } /** @@ -200,7 +204,7 @@ class Collection extends Iterator if ($key instanceof Page) { $key = $key->path(); } elseif (null === $key) { - $key = key($this->items); + $key = (string)key($this->items); } if (!\is_string($key)) { throw new \InvalidArgumentException('Invalid argument $key.'); @@ -342,6 +346,7 @@ class Collection extends Iterator } $this->items = $date_range; + return $this; } diff --git a/system/src/Grav/Common/Page/Header.php b/system/src/Grav/Common/Page/Header.php index 7df862bb1..e3854aecf 100644 --- a/system/src/Grav/Common/Page/Header.php +++ b/system/src/Grav/Common/Page/Header.php @@ -1,8 +1,9 @@ $info) { // Ignore folders and Markdown files. - if (!$info->isFile() || $info->getExtension() === 'md' || $info->getFilename()[0] === '.') { + if (!$info->isFile() || $info->getExtension() === 'md' || strpos($info->getFilename(), '.') === 0) { continue; } // Find out what type we're dealing with list($basename, $ext, $type, $extra) = $this->getFileParts($info->getFilename()); - if (!in_array(strtolower($ext), $media_types)) { + if (!\in_array(strtolower($ext), $media_types, true)) { continue; } if ($type === 'alternative') { - $media["{$basename}.{$ext}"][$type][$extra] = [ 'file' => $path, 'size' => $info->getSize() ]; + $media["{$basename}.{$ext}"][$type][$extra] = ['file' => $path, 'size' => $info->getSize()]; } else { - $media["{$basename}.{$ext}"][$type] = [ 'file' => $path, 'size' => $info->getSize() ]; + $media["{$basename}.{$ext}"][$type] = ['file' => $path, 'size' => $info->getSize()]; } } @@ -147,7 +148,7 @@ class Media extends AbstractMedia if (file_exists($meta_path)) { $types['meta']['file'] = $meta_path; - } elseif ($file_path && $medium->get('mime') === 'image/jpeg' && empty($types['meta']) && $config->get('system.media.auto_metadata_exif') && $exif_reader) { + } elseif ($file_path && $exif_reader && $medium->get('mime') === 'image/jpeg' && empty($types['meta']) && $config->get('system.media.auto_metadata_exif')) { $meta = $exif_reader->read($file_path); diff --git a/system/src/Grav/Common/Page/Medium/AbstractMedia.php b/system/src/Grav/Common/Page/Medium/AbstractMedia.php index 9747d2e6c..ada87f2c3 100644 --- a/system/src/Grav/Common/Page/Medium/AbstractMedia.php +++ b/system/src/Grav/Common/Page/Medium/AbstractMedia.php @@ -1,8 +1,9 @@ attributes['controls'] = true; - } - else - { + } else { unset($this->attributes['controls']); } + return $this; } @@ -57,12 +56,12 @@ class AudioMedium extends Medium */ public function preload($preload) { - $validPreloadAttrs = array('auto','metadata','none'); + $validPreloadAttrs = ['auto', 'metadata', 'none']; - if (in_array($preload, $validPreloadAttrs)) - { + if (\in_array($preload, $validPreloadAttrs, true)) { $this->attributes['preload'] = $preload; } + return $this; } @@ -77,6 +76,7 @@ class AudioMedium extends Medium { $controlsList = str_replace('-', ' ', $controlsList); $this->attributes['controlsList'] = $controlsList; + return $this; } @@ -88,14 +88,12 @@ class AudioMedium extends Medium */ public function muted($status = false) { - if($status) - { + if($status) { $this->attributes['muted'] = true; - } - else - { + } else { unset($this->attributes['muted']); } + return $this; } @@ -107,14 +105,12 @@ class AudioMedium extends Medium */ public function loop($status = false) { - if($status) - { + if($status) { $this->attributes['loop'] = true; - } - else - { + } else { unset($this->attributes['loop']); } + return $this; } @@ -126,14 +122,12 @@ class AudioMedium extends Medium */ public function autoplay($status = false) { - if($status) - { + if($status) { $this->attributes['autoplay'] = true; - } - else - { + } else { unset($this->attributes['autoplay']); } + return $this; } @@ -148,6 +142,7 @@ class AudioMedium extends Medium parent::reset(); $this->attributes['controls'] = true; + return $this; } } diff --git a/system/src/Grav/Common/Page/Medium/GlobalMedia.php b/system/src/Grav/Common/Page/Medium/GlobalMedia.php index 74adc088d..b9de527c4 100644 --- a/system/src/Grav/Common/Page/Medium/GlobalMedia.php +++ b/system/src/Grav/Common/Page/Medium/GlobalMedia.php @@ -1,8 +1,9 @@ alternatives)) { $max = max(array_keys($this->alternatives)); $base = $this->alternatives[$max]; @@ -346,7 +348,7 @@ class ImageMedium extends Medium $attributes['sizes'] = $this->sizes(); } - return [ 'name' => 'img', 'attributes' => $attributes ]; + return ['name' => 'img', 'attributes' => $attributes]; } /** @@ -426,6 +428,7 @@ class ImageMedium extends Medium } $this->quality = $quality; + return $this; } @@ -445,6 +448,7 @@ class ImageMedium extends Medium } $this->format = $format; + return $this; } @@ -459,6 +463,7 @@ class ImageMedium extends Medium if ($sizes) { $this->sizes = $sizes; + return $this; } @@ -479,10 +484,12 @@ class ImageMedium extends Medium */ public function width($value = 'auto') { - if (!$value || $value === 'auto') + if (!$value || $value === 'auto') { $this->attributes['width'] = $this->get('width'); - else + } else { $this->attributes['width'] = $value; + } + return $this; } @@ -500,10 +507,12 @@ class ImageMedium extends Medium */ public function height($value = 'auto') { - if (!$value || $value === 'auto') + if (!$value || $value === 'auto') { $this->attributes['height'] = $this->get('height'); - else + } else { $this->attributes['height'] = $value; + } + return $this; } diff --git a/system/src/Grav/Common/Page/Medium/Link.php b/system/src/Grav/Common/Page/Medium/Link.php index 15aac7b3b..62e9265cf 100644 --- a/system/src/Grav/Common/Page/Medium/Link.php +++ b/system/src/Grav/Common/Page/Medium/Link.php @@ -1,8 +1,9 @@ medium_querystring[] = ltrim($querystring, '?&'); foreach ($this->alternatives as $alt) { $alt->querystring($querystring, $withQuestionmark); @@ -278,11 +279,11 @@ class Medium extends Data implements RenderableInterface, MediaObjectInterface } // join the strings - $querystring = implode("&", $this->medium_querystring); + $querystring = implode('&', $this->medium_querystring); // explode all strings - $query_parts = explode("&", $querystring); + $query_parts = explode('&', $querystring); // Join them again now ensure the elements are unique - $querystring = implode("&", array_unique($query_parts)); + $querystring = implode('&', array_unique($query_parts)); return $withQuestionmark ? ('?' . $querystring) : $querystring; } @@ -494,7 +495,7 @@ class Medium extends Data implements RenderableInterface, MediaObjectInterface */ public function thumbnail($type = 'auto') { - if ($type !== 'auto' && !in_array($type, $this->thumbnailTypes)) { + if ($type !== 'auto' && !\in_array($type, $this->thumbnailTypes, true)) { return $this; } @@ -560,7 +561,7 @@ class Medium extends Data implements RenderableInterface, MediaObjectInterface { $classes = func_get_args(); if (!empty($classes)) { - $this->attributes['class'] = implode(',', (array)$classes); + $this->attributes['class'] = implode(',', $classes); } return $this; @@ -605,7 +606,7 @@ class Medium extends Data implements RenderableInterface, MediaObjectInterface public function __call($method, $args) { $qs = $method; - if (count($args) > 1 || (count($args) == 1 && !empty($args[0]))) { + if (\count($args) > 1 || (\count($args) === 1 && !empty($args[0]))) { $qs .= '=' . implode(',', array_map(function ($a) { if (is_array($a)) { $a = '[' . implode(',', $a) . ']'; diff --git a/system/src/Grav/Common/Page/Medium/MediumFactory.php b/system/src/Grav/Common/Page/Medium/MediumFactory.php index 1c1c28a83..7f253e24d 100644 --- a/system/src/Grav/Common/Page/Medium/MediumFactory.php +++ b/system/src/Grav/Common/Page/Medium/MediumFactory.php @@ -1,8 +1,9 @@ url($reset); - return [ 'name' => 'img', 'attributes' => $attributes ]; + return ['name' => 'img', 'attributes' => $attributes]; } } diff --git a/system/src/Grav/Common/Page/Medium/StaticResizeTrait.php b/system/src/Grav/Common/Page/Medium/StaticResizeTrait.php index 4e7d61901..8d6d43fb4 100644 --- a/system/src/Grav/Common/Page/Medium/StaticResizeTrait.php +++ b/system/src/Grav/Common/Page/Medium/StaticResizeTrait.php @@ -1,8 +1,9 @@ bubble('thumbnail', [$type], false); + return $this->bubble('getThumbnail', [], false); } diff --git a/system/src/Grav/Common/Page/Medium/VideoMedium.php b/system/src/Grav/Common/Page/Medium/VideoMedium.php index a8713b377..deeb4a216 100644 --- a/system/src/Grav/Common/Page/Medium/VideoMedium.php +++ b/system/src/Grav/Common/Page/Medium/VideoMedium.php @@ -1,8 +1,9 @@ hide_home_route = $config->get('system.home.hide_in_urls', false); $this->home_route = $this->adjustRouteCase($config->get('system.home.alias')); - $this->filePath($file->getPathName()); + $this->filePath($file->getPathname()); $this->modified($file->getMTime()); $this->id($this->modified() . md5($this->filePath())); $this->routable(true); @@ -197,7 +198,7 @@ class Page implements PageInterface $aPage = new Page(); $aPage->init(new \SplFileInfo($path), $language . '.md'); - $route = isset($aPage->header()->routes['default']) ? $aPage->header()->routes['default'] : $aPage->rawRoute(); + $route = $aPage->header()->routes['default'] ?? $aPage->rawRoute(); if (!$route) { $route = $aPage->route(); } @@ -222,7 +223,7 @@ class Page implements PageInterface */ public function untranslatedLanguages($includeUnpublished = false) { - $filename = substr($this->name, 0, -(strlen($this->extension()))); + $filename = substr($this->name, 0, -strlen($this->extension())); $config = Grav::instance()['config']; $languages = $config->get('system.languages.supported', []); $untranslatedLanguages = []; @@ -364,10 +365,10 @@ class Page implements PageInterface if ($var) { if (isset($this->header->slug)) { - $this->slug(($this->header->slug)); + $this->slug($this->header->slug); } if (isset($this->header->routes)) { - $this->routes = (array)($this->header->routes); + $this->routes = (array)$this->header->routes; } if (isset($this->header->title)) { $this->title = trim($this->header->title); @@ -417,7 +418,7 @@ class Page implements PageInterface } } if (isset($this->header->max_count)) { - $this->max_count = intval($this->header->max_count); + $this->max_count = (int)$this->header->max_count; } if (isset($this->header->process)) { foreach ((array)$this->header->process as $process => $status) { @@ -434,7 +435,7 @@ class Page implements PageInterface $this->unpublishDate($this->header->unpublish_date); } if (isset($this->header->expires)) { - $this->expires = intval($this->header->expires); + $this->expires = (int)$this->header->expires; } if (isset($this->header->cache_control)) { $this->cache_control = $this->header->cache_control; @@ -611,7 +612,7 @@ class Page implements PageInterface return mb_strimwidth($content, 0, $size, '...', 'utf-8'); } - $summary = Utils::truncateHTML($content, $size); + $summary = Utils::truncateHtml($content, $size); return html_entity_decode($summary); } @@ -673,13 +674,13 @@ class Page implements PageInterface $process_markdown = $this->shouldProcess('markdown'); $process_twig = $this->shouldProcess('twig') || $this->modularTwig(); - $cache_enable = isset($this->header->cache_enable) ? $this->header->cache_enable : $config->get('system.cache.enabled', + $cache_enable = $this->header->cache_enable ?? $config->get('system.cache.enabled', true); - $twig_first = isset($this->header->twig_first) ? $this->header->twig_first : $config->get('system.pages.twig_first', + $twig_first = $this->header->twig_first ?? $config->get('system.pages.twig_first', true); // never cache twig means it's always run after content - $never_cache_twig = isset($this->header->never_cache_twig) ? $this->header->never_cache_twig : $config->get('system.pages.never_cache_twig', + $never_cache_twig = $this->header->never_cache_twig ?? $config->get('system.pages.never_cache_twig', false); // if no cached-content run everything @@ -876,9 +877,7 @@ class Page implements PageInterface */ public function setRawContent($content) { - $content = $content === null ? '': $content; - - $this->content = $content; + $this->content = $content ?? ''; } /** @@ -895,7 +894,9 @@ class Page implements PageInterface return $this->raw_content; } if ($name === 'route') { - return $this->parent()->rawRoute(); + $parent = $this->parent(); + + return $parent ? $parent->rawRoute() : ''; } if ($name === 'order') { $order = $this->order(); @@ -1036,10 +1037,10 @@ class Page implements PageInterface $this->_action = 'move'; if ($this->route() === $parent->route()) { - throw new Exception('Failed: Cannot set page parent to self'); + throw new \RuntimeException('Failed: Cannot set page parent to self'); } if (Utils::startsWith($parent->rawRoute(), $this->rawRoute())) { - throw new Exception('Failed: Cannot set page parent to a child of current page'); + throw new \RuntimeException('Failed: Cannot set page parent to a child of current page'); } $this->parent($parent); @@ -1122,7 +1123,7 @@ class Page implements PageInterface /** * Validate page header. * - * @throws Exception + * @throws \Exception */ public function validate() { @@ -1324,7 +1325,7 @@ class Page implements PageInterface $this->name = $var; } - return empty($this->name) ? 'default.md' : $this->name; + return $this->name ?: 'default.md'; } /** @@ -1380,6 +1381,7 @@ class Page implements PageInterface $page_extension = trim($this->header->append_url_extension ?? '' , '.'); if (!empty($page_extension)) { $this->template_format = $page_extension; + return $this->template_format; } @@ -1387,6 +1389,7 @@ class Page implements PageInterface $uri_extension = Grav::instance()['uri']->extension(); if (is_string($uri_extension)) { $this->template_format = $uri_extension; + return $this->template_format; } @@ -1399,8 +1402,9 @@ class Page implements PageInterface $priorities = Utils::getMimeTypes($supported_types); $media_type = $negotiator->getBest($http_accept, $priorities); - $mimetype = $media_type->getValue(); + $mimetype = $media_type ? $media_type->getValue() : ''; $this->template_format = Utils::getExtensionByMime($mimetype); + return $this->template_format; } @@ -1461,7 +1465,7 @@ class Page implements PageInterface $this->expires = $var; } - return !isset($this->expires) ? Grav::instance()['config']->get('system.pages.expires') : $this->expires; + return $this->expires ?? Grav::instance()['config']->get('system.pages.expires'); } /** @@ -1477,7 +1481,7 @@ class Page implements PageInterface $this->cache_control = $var; } - return !isset($this->cache_control) ? Grav::instance()['config']->get('system.pages.cache_control') : $this->cache_control; + return $this->cache_control ?? Grav::instance()['config']->get('system.pages.cache_control'); } /** @@ -1649,11 +1653,7 @@ class Page implements PageInterface */ public function debugger() { - if (isset($this->debugger) && $this->debugger === false) { - return false; - } - - return true; + return !(isset($this->debugger) && $this->debugger === false); } /** @@ -1706,7 +1706,7 @@ class Page implements PageInterface } else { // If it this is a standard meta data type if ($value) { - if (in_array($key, $header_tag_http_equivs)) { + if (\in_array($key, $header_tag_http_equivs, true)) { $this->metadata[$key] = [ 'http_equiv' => $key, 'content' => htmlspecialchars($value, ENT_QUOTES, 'UTF-8') @@ -1755,7 +1755,6 @@ class Page implements PageInterface $this->slug = $this->adjustRouteCase(preg_replace(PAGE_ORDER_PREFIX_REGEX, '', $this->folder)) ?: null; } - return $this->slug; } @@ -1769,7 +1768,7 @@ class Page implements PageInterface public function order($var = null) { if ($var !== null) { - $order = !empty($var) ? sprintf('%02d.', (int)$var) : ''; + $order = $var ? sprintf('%02d.', (int)$var) : ''; $this->folder($order . preg_replace(PAGE_ORDER_PREFIX_REGEX, '', $this->folder)); return $order; @@ -1777,7 +1776,7 @@ class Page implements PageInterface preg_match(PAGE_ORDER_PREFIX_REGEX, $this->folder, $order); - return isset($order[0]) ? $order[0] : false; + return $order[0] ?? false; } /** @@ -1838,7 +1837,7 @@ class Page implements PageInterface /** @var Config $config */ $config = $grav['config']; - // get base route (multisite base and language) + // get base route (multi-site base and language) $route = $include_base ? $pages->baseRoute() : ''; // add full route if configured to do so @@ -1911,8 +1910,7 @@ class Page implements PageInterface */ public function unsetRouteSlug() { - unset($this->route); - unset($this->slug); + unset($this->route, $this->slug); } /** @@ -1929,7 +1927,8 @@ class Page implements PageInterface } if (empty($this->raw_route)) { - $baseRoute = $this->parent ? (string)$this->parent()->rawRoute() : null; + $parent = $this->parent(); + $baseRoute = $parent ? (string)$parent->rawRoute() : null; $slug = $this->adjustRouteCase(preg_replace(PAGE_ORDER_PREFIX_REGEX, '', $this->folder)); @@ -2084,7 +2083,7 @@ class Page implements PageInterface // Folder of the page. $this->folder = basename(dirname($var)); // Path to the page. - $this->path = dirname(dirname($var)); + $this->path = dirname($var, 2); } return $this->path . '/' . $this->folder . '/' . ($this->name ?: ''); @@ -2097,9 +2096,7 @@ class Page implements PageInterface */ public function filePathClean() { - $path = str_replace(ROOT_DIR, '', $this->filePath()); - - return $path; + return str_replace(ROOT_DIR, '', $this->filePath()); } /** @@ -2107,9 +2104,7 @@ class Page implements PageInterface */ public function relativePagePath() { - $path = str_replace('/' . $this->name(), '', $this->filePathClean()); - - return $path; + return str_replace('/' . $this->name(), '', $this->filePathClean()); } /** @@ -2197,6 +2192,7 @@ class Page implements PageInterface if ($var !== null) { $this->order_dir = $var; } + if (empty($this->order_dir)) { $this->order_dir = 'asc'; } @@ -2324,7 +2320,7 @@ class Page implements PageInterface */ public function shouldProcess($process) { - return isset($this->process[$process]) ? (bool)$this->process[$process] : false; + return (bool)($this->process[$process] ?? false); } /** @@ -2394,7 +2390,8 @@ class Page implements PageInterface */ public function isFirst() { - $collection = $this->parent()->collection('content', false); + $parent = $this->parent(); + $collection = $parent ? $parent->collection('content', false) : null; if ($collection instanceof Collection) { return $collection->isFirst($this->path()); } @@ -2409,7 +2406,8 @@ class Page implements PageInterface */ public function isLast() { - $collection = $this->parent()->collection('content', false); + $parent = $this->parent(); + $collection = $parent ? $parent->collection('content', false) : null; if ($collection instanceof Collection) { return $collection->isLast($this->path()); } @@ -2446,7 +2444,8 @@ class Page implements PageInterface */ public function adjacentSibling($direction = 1) { - $collection = $this->parent()->collection('content', false); + $parent = $this->parent(); + $collection = $parent ? $parent->collection('content', false) : null; if ($collection instanceof Collection) { return $collection->adjacentSibling($this->path(), $direction); } @@ -2463,7 +2462,8 @@ class Page implements PageInterface */ public function currentPosition() { - $collection = $this->parent()->collection('content', false); + $parent = $this->parent(); + $collection = $parent ? $parent->collection('content', false) : null; if ($collection instanceof Collection) { return $collection->currentPosition($this->path()); } @@ -2481,14 +2481,7 @@ class Page implements PageInterface $uri_path = rtrim(urldecode(Grav::instance()['uri']->path()), '/') ?: '/'; $routes = Grav::instance()['pages']->routes(); - if (isset($routes[$uri_path])) { - if ($routes[$uri_path] === $this->path()) { - return true; - } - - } - - return false; + return isset($routes[$uri_path]) && $routes[$uri_path] === $this->path(); } /** @@ -2528,9 +2521,8 @@ class Page implements PageInterface public function home() { $home = Grav::instance()['config']->get('system.home.alias'); - $is_home = ($this->route() === $home || $this->rawRoute() === $home); - return $is_home; + return ($this->route() === $home || $this->rawRoute() === $home); } /** @@ -2540,11 +2532,7 @@ class Page implements PageInterface */ public function root() { - if (!$this->parent && !$this->name && !$this->visible) { - return true; - } - - return false; + return !$this->parent && !$this->name && !$this->visible; } /** @@ -2608,7 +2596,7 @@ class Page implements PageInterface /** @var Pages $pages */ $inherited = $pages->inherited($this->route, $field); - $inheritedParams = (array)$inherited->value('header.' . $field); + $inheritedParams = $inherited ? (array)$inherited->value('header.' . $field) : []; $currentParams = (array)$this->value('header.' . $field); if ($inheritedParams && is_array($inheritedParams)) { $currentParams = array_replace_recursive($inheritedParams, $currentParams); @@ -2673,7 +2661,7 @@ class Page implements PageInterface /** @var Config $config */ $config = Grav::instance()['config']; - $process_taxonomy = isset($params['url_taxonomy_filters']) ? $params['url_taxonomy_filters'] : $config->get('system.pages.url_taxonomy_filters'); + $process_taxonomy = $params['url_taxonomy_filters'] ?? $config->get('system.pages.url_taxonomy_filters'); if ($process_taxonomy) { foreach ((array)$config->get('site.taxonomies') as $taxonomy) { @@ -2688,8 +2676,7 @@ class Page implements PageInterface } foreach ($items as $item) { $item = rawurldecode($item); - if (empty($page->taxonomy[$taxonomy]) || !in_array(htmlspecialchars_decode($item, - ENT_QUOTES), $page->taxonomy[$taxonomy]) + if (empty($page->taxonomy[$taxonomy]) || !\in_array(htmlspecialchars_decode($item, ENT_QUOTES), $page->taxonomy[$taxonomy], true) ) { $collection->remove($page->path()); } @@ -2705,12 +2692,9 @@ class Page implements PageInterface // remove any inclusive sets from filer: $sets = ['published', 'visible', 'modular', 'routable']; foreach ($sets as $type) { - if (isset($params['filter'][$type]) && isset($params['filter']['non-'.$type])) { - if ($params['filter'][$type] && $params['filter']['non-'.$type]) { - unset ($params['filter'][$type]); - unset ($params['filter']['non-'.$type]); - } - + $var = "non-{$type}"; + if (isset($params['filter'][$type], $params['filter'][$var]) && $params['filter'][$type] && $params['filter'][$var]) { + unset ($params['filter'][$type], $params['filter'][$var]); } } @@ -2770,17 +2754,17 @@ class Page implements PageInterface } if (isset($params['dateRange'])) { - $start = isset($params['dateRange']['start']) ? $params['dateRange']['start'] : 0; - $end = isset($params['dateRange']['end']) ? $params['dateRange']['end'] : false; - $field = isset($params['dateRange']['field']) ? $params['dateRange']['field'] : false; + $start = $params['dateRange']['start'] ?? 0; + $end = $params['dateRange']['end'] ?? false; + $field = $params['dateRange']['field'] ?? false; $collection->dateRange($start, $end, $field); } if (isset($params['order'])) { - $by = isset($params['order']['by']) ? $params['order']['by'] : 'default'; - $dir = isset($params['order']['dir']) ? $params['order']['dir'] : 'asc'; - $custom = isset($params['order']['custom']) ? $params['order']['custom'] : null; - $sort_flags = isset($params['order']['sort_flags']) ? $params['order']['sort_flags'] : null; + $by = $params['order']['by'] ?? 'default'; + $dir = $params['order']['dir'] ?? 'asc'; + $custom = $params['order']['custom'] ?? null; + $sort_flags = $params['order']['sort_flags'] ?? null; if (is_array($sort_flags)) { $sort_flags = array_map('constant', $sort_flags); //transform strings to constant value @@ -2802,7 +2786,7 @@ class Page implements PageInterface if ($pagination) { $params = $collection->params(); - $limit = isset($params['limit']) ? $params['limit'] : 0; + $limit = $params['limit'] ?? 0; $start = !empty($params['pagination']) ? ($uri->currentPage() - 1) * $limit : 0; if ($limit && $collection->count() > $limit) { @@ -3045,28 +3029,32 @@ class Page implements PageInterface $this->_original->path($this->path()); - $siblings = $this->parent()->children(); - $siblings->order('slug', 'asc', $new_order); + $parent = $this->parent(); + $siblings = $parent ? $parent->children() : null; - $counter = 0; + if ($siblings) { + $siblings->order('slug', 'asc', $new_order); - // Reorder all moved pages. - foreach ($siblings as $slug => $page) { - $order = (int)trim($page->order(), '.'); - $counter++; + $counter = 0; - if ($order) { - if ($page->path() === $this->path() && $this->folderExists()) { - // Handle current page; we do want to change ordering number, but nothing else. - $this->order($counter); - $this->save(false); - } else { - // Handle all the other pages. - $page = $pages->get($page->path()); - if ($page && $page->folderExists() && !$page->_action) { - $page = $page->move($this->parent()); - $page->order($counter); - $page->save(false); + // Reorder all moved pages. + foreach ($siblings as $slug => $page) { + $order = (int)trim($page->order(), '.'); + $counter++; + + if ($order) { + if ($page->path() === $this->path() && $this->folderExists()) { + // Handle current page; we do want to change ordering number, but nothing else. + $this->order($counter); + $this->save(false); + } else { + // Handle all the other pages. + $page = $pages->get($page->path()); + if ($page && $page->folderExists() && !$page->_action) { + $page = $page->move($this->parent()); + $page->order($counter); + $page->save(false); + } } } } @@ -3078,7 +3066,7 @@ class Page implements PageInterface * * @internal * - * @throws Exception + * @throws \Exception */ protected function doRelocation() { @@ -3128,11 +3116,7 @@ class Page implements PageInterface { $case_insensitive = Grav::instance()['config']->get('system.force_lowercase_urls'); - if ($case_insensitive) { - return mb_strtolower($route); - } else { - return $route; - } + return $case_insensitive ? mb_strtolower($route) : $route; } /** diff --git a/system/src/Grav/Common/Page/Pages.php b/system/src/Grav/Common/Page/Pages.php index 151338e0b..c59ca5201 100644 --- a/system/src/Grav/Common/Page/Pages.php +++ b/system/src/Grav/Common/Page/Pages.php @@ -1,8 +1,9 @@ grav[$type] . $this->baseRoute($lang); } @@ -310,7 +317,7 @@ class Pages } $path = $page->path(); - $children = isset($this->children[$path]) ? $this->children[$path] : []; + $children = $this->children[$path] ?? []; if (!$children) { return $children; @@ -334,6 +341,7 @@ class Pages * @param $orderBy * @param string $orderDir * @param null $orderManual + * @param null $sort_flags * * @return array * @internal @@ -370,7 +378,7 @@ class Pages */ public function get($path) { - return isset($this->instances[(string)$path]) ? $this->instances[(string)$path] : null; + return $this->instances[(string)$path] ?? null; } /** @@ -382,7 +390,7 @@ class Pages */ public function children($path) { - $children = isset($this->children[(string)$path]) ? $this->children[(string)$path] : []; + $children = $this->children[(string)$path] ?? []; return new Collection($children, [], $this); } @@ -403,8 +411,10 @@ class Pages if ($page && $page->path() === $path) { return $page; } - if ($page && !$page->parent()->root()) { - return $this->ancestor($page->parent()->route(), $path); + + $parent = $page ? $page->parent() : null; + if ($parent && !$parent->root()) { + return $this->ancestor($parent->route(), $path); } } @@ -425,11 +435,12 @@ class Pages $page = $this->dispatch($route, true); - if ($page && $page->parent()->value('header.' . $field) !== null) { - return $page->parent(); + $parent = $page ? $page->parent() : null; + if ($parent && $parent->value('header.' . $field) !== null) { + return $parent; } - if ($page && !$page->parent()->root()) { - return $this->inherited($page->parent()->route(), $field); + if ($parent && !$parent->root()) { + return $this->inherited($parent->route(), $field); } } @@ -498,13 +509,13 @@ class Pages $source_url = $uri->uri(false); // Try Regex style redirects - $site_redirects = $config->get("site.redirects"); + $site_redirects = $config->get('site.redirects'); if (is_array($site_redirects)) { foreach ((array)$site_redirects as $pattern => $replace) { $pattern = '#^' . str_replace('/', '\/', ltrim($pattern, '^')) . '#'; try { $found = preg_replace($pattern, $replace, $source_url); - if ($found != $source_url) { + if ($found !== $source_url) { $this->grav->redirectLangSafe($found); } } catch (ErrorException $e) { @@ -514,7 +525,7 @@ class Pages } // Try Regex style routes - $site_routes = $config->get("site.routes"); + $site_routes = $config->get('site.routes'); if (is_array($site_routes)) { foreach ((array)$site_routes as $pattern => $replace) { $pattern = '#^' . str_replace('/', '\/', ltrim($pattern, '^')) . '#'; @@ -544,6 +555,7 @@ class Pages { /** @var UniformResourceLocator $locator */ $locator = $this->grav['locator']; + return $this->instances[rtrim($locator->findResource('page://'), DS)]; } @@ -822,19 +834,18 @@ class Pages $accessLevels = []; foreach ($this->all() as $page) { if (isset($page->header()->access)) { - if (is_array($page->header()->access)) { + if (\is_array($page->header()->access)) { foreach ($page->header()->access as $index => $accessLevel) { - if (is_array($accessLevel)) { + if (\is_array($accessLevel)) { foreach ($accessLevel as $innerIndex => $innerAccessLevel) { - array_push($accessLevels, $innerIndex); + $accessLevels[] = $innerIndex; } } else { - array_push($accessLevels, $index); + $accessLevels[] = $index; } } } else { - - array_push($accessLevels, $page->header()->access); + $accessLevels[] = $page->header()->access; } } } @@ -1013,13 +1024,10 @@ class Pages /** @var Language $language */ $language = $this->grav['language']; - // stuff to do at root page - if ($parent === null) { - - // Fire event for memory and time consuming plugins... - if ($config->get('system.pages.events.page')) { - $this->grav->fireEvent('onBuildPagesInitialized'); - } + // Stuff to do at root page + // Fire event for memory and time consuming plugins... + if ($parent === null && $config->get('system.pages.events.page')) { + $this->grav->fireEvent('onBuildPagesInitialized'); } $page->path($directory); @@ -1060,7 +1068,7 @@ class Pages $filename = $file->getFilename(); // Ignore all hidden files if set. - if ($this->ignore_hidden && $filename && $filename[0] === '.') { + if ($this->ignore_hidden && $filename && strpos($filename, '.') === 0) { continue; } @@ -1192,7 +1200,7 @@ class Pages $this->routes[$route] = $page_path; // add raw route - if ($raw_route != $route) { + if ($raw_route !== $route) { $this->routes[$raw_route] = $page_path; } @@ -1213,9 +1221,10 @@ class Pages } // Alias and set default route to home page. - if ($home && isset($this->routes['/' . $home])) { - $this->routes['/'] = $this->routes['/' . $home]; - $this->get($this->routes['/' . $home])->route('/'); + $homeRoute = '/' . $home; + if ($home && isset($this->routes[$homeRoute])) { + $this->routes['/'] = $this->routes[$homeRoute]; + $this->get($this->routes[$homeRoute])->route('/'); } } @@ -1244,7 +1253,7 @@ class Pages } foreach ($pages as $key => $info) { - $child = isset($this->instances[$key]) ? $this->instances[$key] : null; + $child = $this->instances[$key] ?? null; if (!$child) { throw new \RuntimeException("Page does not exist: {$key}"); } @@ -1341,7 +1350,7 @@ class Pages foreach ($list as $key => $dummy) { $info = $pages[$key]; - $order = array_search($info['slug'], $manual); + $order = \array_search($info['slug'], $manual, true); if ($order === false) { $order = $i++; } diff --git a/system/src/Grav/Common/Page/Types.php b/system/src/Grav/Common/Page/Types.php index 10b07beda..03e3f6eb0 100644 --- a/system/src/Grav/Common/Page/Types.php +++ b/system/src/Grav/Common/Page/Types.php @@ -1,8 +1,9 @@ content(), $blueprint); + $obj = new Data((array)$file->content(), $blueprint); // Override with user configuration. $obj->merge(Grav::instance()['config']->get('plugins.' . $name) ?: []); diff --git a/system/src/Grav/Common/Processors/AssetsProcessor.php b/system/src/Grav/Common/Processors/AssetsProcessor.php index 6a5e3459f..8b4640138 100644 --- a/system/src/Grav/Common/Processors/AssetsProcessor.php +++ b/system/src/Grav/Common/Processors/AssetsProcessor.php @@ -1,8 +1,9 @@ get('system.pages.redirect_trailing_slash', false) && Utils::endsWith($path, '/')) { - $redirect = (string) $uri->getCurrentRoute()->toString(); + $redirect = (string) $uri::getCurrentRoute()->toString(); $this->container->redirectLangSafe($redirect); } diff --git a/system/src/Grav/Common/Processors/LoggerProcessor.php b/system/src/Grav/Common/Processors/LoggerProcessor.php index 255bf9ae6..af3c16999 100644 --- a/system/src/Grav/Common/Processors/LoggerProcessor.php +++ b/system/src/Grav/Common/Processors/LoggerProcessor.php @@ -1,9 +1,9 @@ modified for Grav integration - * @copyright Copyright (C) 2015 - 2018 Trilby Media, LLC. All rights reserved. + * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved. * @license MIT License; see LICENSE file for details. */ @@ -44,20 +45,21 @@ namespace Grav\Common\Scheduler; * var_dump($cron->matchWithMargin(new \DateTime('2012-07-01 12:32:50'), -3, 5)); * // bool(true) */ -class Cron { - const TYPE_UNDEFINED = ''; - const TYPE_MINUTE = 'minute'; - const TYPE_HOUR = 'hour'; - const TYPE_DAY = 'day'; - const TYPE_WEEK = 'week'; - const TYPE_MONTH = 'month'; - const TYPE_YEAR = 'year'; +class Cron +{ + public const TYPE_UNDEFINED = ''; + public const TYPE_MINUTE = 'minute'; + public const TYPE_HOUR = 'hour'; + public const TYPE_DAY = 'day'; + public const TYPE_WEEK = 'week'; + public const TYPE_MONTH = 'month'; + public const TYPE_YEAR = 'year'; /** * * @var array */ - protected $texts = array( - 'fr' => array( + protected $texts = [ + 'fr' => [ 'empty' => '-tout-', 'name_minute' => 'minute', 'name_hour' => 'heure', @@ -71,10 +73,10 @@ class Cron { 'text_dow' => 'le %s', 'text_month' => 'de %s', 'text_dom' => 'le %s', - 'weekdays' => array('lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche'), - 'months' => array('janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'), - ), - 'en' => array( + 'weekdays' => ['lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche'], + 'months' => ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'], + ], + 'en' => [ 'empty' => '-all-', 'name_minute' => 'minute', 'name_hour' => 'hour', @@ -88,10 +90,11 @@ class Cron { 'text_dow' => 'on %s', 'text_month' => 'of %s', 'text_dom' => 'on the %s', - 'weekdays' => array('monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'), - 'months' => array('january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'), - ), - ); + 'weekdays' => ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'], + 'months' => ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'], + ], + ]; + /** * min hour dom month dow * @var string @@ -101,263 +104,327 @@ class Cron { * * @var array */ - protected $minutes = array(); + protected $minutes = []; /** * * @var array */ - protected $hours = array(); + protected $hours = []; /** * * @var array */ - protected $months = array(); + protected $months = []; /** * 0-7 : sunday, monday, ... saturday, sunday * @var array */ - protected $dow = array(); + protected $dow = []; /** * * @var array */ - protected $dom = array(); + protected $dom = []; + /** * * @param string $cron */ - public function __construct($cron = null) { - if (!empty($cron)) { + public function __construct($cron = null) + { + if (null !== $cron) { $this->setCron($cron); } } + /** * * @return string */ - public function getCron() { - return implode(' ', array( + public function getCron() + { + return implode(' ', [ $this->getCronMinutes(), $this->getCronHours(), $this->getCronDaysOfMonth(), $this->getCronMonths(), $this->getCronDaysOfWeek(), - )); + ]); } + /** * * @param string $lang 'fr' or 'en' * @return string */ - public function getText($lang) { + public function getText($lang) + { // check lang if (!isset($this->texts[$lang])) { return $this->getCron(); } + $texts = $this->texts[$lang]; // check type + $type = $this->getType(); - if ($type == self::TYPE_UNDEFINED) { + if ($type === self::TYPE_UNDEFINED) { return $this->getCron(); } + // init - $elements = array(); + $elements = []; $elements[] = sprintf($texts['text_period'], $texts['name_' . $type]); + // hour - if (in_array($type, array(self::TYPE_HOUR))) { + if ($type === self::TYPE_HOUR) { $elements[] = sprintf($texts['text_mins'], $this->getCronMinutes()); } + // week - if (in_array($type, array(self::TYPE_WEEK))) { + if ($type === self::TYPE_WEEK) { $dow = $this->getCronDaysOfWeek(); foreach ($texts['weekdays'] as $i => $wd) { $dow = str_replace((string) ($i + 1), $wd, $dow); } $elements[] = sprintf($texts['text_dow'], $dow); } + // month + year - if (in_array($type, array(self::TYPE_MONTH, self::TYPE_YEAR))) { + if (\in_array($type, [self::TYPE_MONTH, self::TYPE_YEAR], true)) { $elements[] = sprintf($texts['text_dom'], $this->getCronDaysOfMonth()); } + // year - if (in_array($type, array(self::TYPE_YEAR))) { + if ($type === self::TYPE_YEAR) { $months = $this->getCronMonths(); for ($i = count($texts['months']) - 1; $i >= 0; $i--) { $months = str_replace((string) ($i + 1), $texts['months'][$i], $months); } $elements[] = sprintf($texts['text_month'], $months); } + // day + week + month + year - if (in_array($type, array(self::TYPE_DAY, self::TYPE_WEEK, self::TYPE_MONTH, self::TYPE_YEAR))) { + if (\in_array($type, [self::TYPE_DAY, self::TYPE_WEEK, self::TYPE_MONTH, self::TYPE_YEAR], true)) { $elements[] = sprintf($texts['text_time'], $this->getCronHours(), $this->getCronMinutes()); } + return str_replace('*', $texts['empty'], implode(' ', $elements)); } + /** * * @return string */ - public function getType() { - $mask = preg_replace('/[^\* ]/si', '-', $this->getCron()); - $mask = preg_replace('/-+/si', '-', $mask); - $mask = preg_replace('/[^-\*]/si', '', $mask); - if ($mask == '*****') { + public function getType() + { + $mask = preg_replace('/[^\* ]/', '-', $this->getCron()); + $mask = preg_replace('/-+/', '-', $mask); + $mask = preg_replace('/[^-\*]/', '', $mask); + + if ($mask === '*****') { return self::TYPE_MINUTE; } - elseif ($mask == '-****') { + + if ($mask === '-****') { return self::TYPE_HOUR; } - elseif (substr($mask, -3) == '***') { + + if (substr($mask, -3) === '***') { return self::TYPE_DAY; } - elseif (substr($mask, -3) == '-**') { + + if (substr($mask, -3) === '-**') { return self::TYPE_MONTH; } - elseif (substr($mask, -3) == '**-') { + + if (substr($mask, -3) === '**-') { return self::TYPE_WEEK; } - elseif (substr($mask, -2) == '-*') { + + if (substr($mask, -2) === '-*') { return self::TYPE_YEAR; } + return self::TYPE_UNDEFINED; } + /** * * @param string $cron * @return Cron */ - public function setCron($cron) { + public function setCron($cron) + { // sanitize $cron = trim($cron); $cron = preg_replace('/\s+/', ' ', $cron); // explode $elements = explode(' ', $cron); - if (count($elements) != 5) { - throw new Exception('Bad number of elements'); + if (\count($elements) !== 5) { + throw new \RuntimeException('Bad number of elements'); } + $this->cron = $cron; $this->setMinutes($elements[0]); $this->setHours($elements[1]); $this->setDaysOfMonth($elements[2]); $this->setMonths($elements[3]); $this->setDaysOfWeek($elements[4]); + return $this; } + /** * * @return string */ - public function getCronMinutes() { + public function getCronMinutes() + { return $this->arrayToCron($this->minutes); } + /** * * @return string */ - public function getCronHours() { + public function getCronHours() + { return $this->arrayToCron($this->hours); } + /** * * @return string */ - public function getCronDaysOfMonth() { + public function getCronDaysOfMonth() + { return $this->arrayToCron($this->dom); } + /** * * @return string */ - public function getCronMonths() { + public function getCronMonths() + { return $this->arrayToCron($this->months); } + /** * * @return string */ - public function getCronDaysOfWeek() { + public function getCronDaysOfWeek() + { return $this->arrayToCron($this->dow); } + /** * * @return array */ - public function getMinutes() { + public function getMinutes() + { return $this->minutes; } + /** * * @return array */ - public function getHours() { + public function getHours() + { return $this->hours; } + /** * * @return array */ - public function getDaysOfMonth() { + public function getDaysOfMonth() + { return $this->dom; } + /** * * @return array */ - public function getMonths() { + public function getMonths() + { return $this->months; } + /** * * @return array */ - public function getDaysOfWeek() { + public function getDaysOfWeek() + { return $this->dow; } + /** * * @param string|array $minutes * @return Cron */ - public function setMinutes($minutes) { + public function setMinutes($minutes) + { $this->minutes = $this->cronToArray($minutes, 0, 59); + return $this; } + /** * * @param string|array $hours * @return Cron */ - public function setHours($hours) { + public function setHours($hours) + { $this->hours = $this->cronToArray($hours, 0, 23); + return $this; } + /** * * @param string|array $months * @return Cron */ - public function setMonths($months) { + public function setMonths($months) + { $this->months = $this->cronToArray($months, 1, 12); + return $this; } + /** * * @param string|array $dow * @return Cron */ - public function setDaysOfWeek($dow) { + public function setDaysOfWeek($dow) + { $this->dow = $this->cronToArray($dow, 0, 7); + return $this; } + /** * * @param string|array $dom * @return Cron */ - public function setDaysOfMonth($dom) { + public function setDaysOfMonth($dom) + { $this->dom = $this->cronToArray($dom, 1, 31); + return $this; } + /** * * @param mixed $date @@ -366,57 +433,65 @@ class Cron { * @param int $day * @param int $month * @param int $weekday - * @return DateTime + * @return \DateTime */ - protected function parseDate($date, &$min, &$hour, &$day, &$month, &$weekday) { - if (is_numeric($date) && intval($date) == $date) { + protected function parseDate($date, &$min, &$hour, &$day, &$month, &$weekday) + { + if (is_numeric($date) && (int)$date == $date) { $date = new \DateTime('@' . $date); } elseif (is_string($date)) { $date = new \DateTime('@' . strtotime($date)); } if ($date instanceof \DateTime) { - $min = intval($date->format('i')); - $hour = intval($date->format('H')); - $day = intval($date->format('d')); - $month = intval($date->format('m')); - $weekday = intval($date->format('w')); // 0-6 + $min = (int)$date->format('i'); + $hour = (int)$date->format('H'); + $day = (int)$date->format('d'); + $month = (int)$date->format('m'); + $weekday = (int)$date->format('w'); // 0-6 } else { - throw new Exception('Date format not supported'); + throw new \RuntimeException('Date format not supported'); } + return new \DateTime($date->format('Y-m-d H:i:sP')); } + /** * * @param int|string|\Datetime $date */ - public function matchExact($date) { + public function matchExact($date) + { $date = $this->parseDate($date, $min, $hour, $day, $month, $weekday); + return - (empty($this->minutes) || in_array($min, $this->minutes)) && - (empty($this->hours) || in_array($hour, $this->hours)) && - (empty($this->dom) || in_array($day, $this->dom)) && - (empty($this->months) || in_array($month, $this->months)) && - (empty($this->dow) || in_array($weekday, $this->dow) || ($weekday == 0 && in_array(7, $this->dow)) || ($weekday == 7 && in_array(0, $this->dow)) + (empty($this->minutes) || \in_array($min, $this->minutes, true)) && + (empty($this->hours) || \in_array($hour, $this->hours, true)) && + (empty($this->dom) || \in_array($day, $this->dom, true)) && + (empty($this->months) || \in_array($month, $this->months, true)) && + (empty($this->dow) || \in_array($weekday, $this->dow, true) || ($weekday == 0 && \in_array(7, $this->dow, true)) || ($weekday == 7 && \in_array(0, $this->dow, true)) ); } + /** * * @param int|string|\Datetime $date * @param int $minuteBefore * @param int $minuteAfter */ - public function matchWithMargin($date, $minuteBefore = 0, $minuteAfter = 0) { + public function matchWithMargin($date, $minuteBefore = 0, $minuteAfter = 0) + { if ($minuteBefore > 0) { - throw new Exception('MinuteBefore parameter cannot be positive !'); + throw new \RuntimeException('MinuteBefore parameter cannot be positive !'); } if ($minuteAfter < 0) { - throw new Exception('MinuteAfter parameter cannot be negative !'); + throw new \RuntimeException('MinuteAfter parameter cannot be negative !'); } + $date = $this->parseDate($date, $min, $hour, $day, $month, $weekday); $interval = new \DateInterval('PT1M'); // 1 min - if ($minuteBefore != 0) { + if ($minuteBefore !== 0) { $date->sub(new \DateInterval('PT' . abs($minuteBefore) . 'M')); } $n = $minuteAfter - $minuteBefore + 1; @@ -426,62 +501,68 @@ class Cron { } $date->add($interval); } + return false; } + /** * * @param array $array * @return string */ - protected function arrayToCron($array) { - $n = count($array); - if (!is_array($array) || $n == 0) { + protected function arrayToCron($array) + { + $n = \count($array); + if (!\is_array($array) || $n === 0) { return '*'; } - $cron = array($array[0]); + + $cron = [$array[0]]; $s = $c = $array[0]; for ($i = 1; $i < $n; $i++) { if ($array[$i] == $c + 1) { $c = $array[$i]; - $cron[count($cron) - 1] = $s . '-' . $c; + $cron[\count($cron) - 1] = $s . '-' . $c; } else { $s = $c = $array[$i]; $cron[] = $c; } } + return implode(',', $cron); } + /** * - * @param string $string + * @param array|string $string * @param int $min * @param int $max * @return array */ - protected function cronToArray($string, $min, $max) { - $array = array(); - if (is_array($string)) { + protected function cronToArray($string, $min, $max) + { + $array = []; + if (\is_array($string)) { foreach ($string as $val) { - if (is_numeric($val) && intval($val) == $val && $val >= $min && $val <= $max) { - $array[] = intval($val); + if (is_numeric($val) && (int)$val == $val && $val >= $min && $val <= $max) { + $array[] = (int)$val; } } - } - else if ($string !== '*') { - while ($string != '') { + } elseif ($string !== '*') { + while ($string !== '') { // test "*/n" expression if (preg_match('/^\*\/([0-9]+),?/', $string, $m)) { - for ($i = max(0, $min); $i <= min(59, $max); $i+=$m[1]) { - $array[] = intval($i); + for ($i = max(0, $min); $i <= min(59, $max); $i += $m[1]) { + $array[] = (int)$i; } $string = substr($string, strlen($m[0])); continue; } // test "a-b/n" expression if (preg_match('/^([0-9]+)-([0-9]+)\/([0-9]+),?/', $string, $m)) { - for ($i = max($m[1], $min); $i <= min($m[2], $max); $i+=$m[3]) { - $array[] = intval($i); + for ($i = max($m[1], $min); $i <= min($m[2], $max); $i += $m[3]) { + $array[] = (int)$i; } $string = substr($string, strlen($m[0])); continue; @@ -489,7 +570,7 @@ class Cron { // test "a-b" expression if (preg_match('/^([0-9]+)-([0-9]+),?/', $string, $m)) { for ($i = max($m[1], $min); $i <= min($m[2], $max); $i++) { - $array[] = intval($i); + $array[] = (int)$i; } $string = substr($string, strlen($m[0])); continue; @@ -497,16 +578,18 @@ class Cron { // test "c" expression if (preg_match('/^([0-9]+),?/', $string, $m)) { if ($m[1] >= $min && $m[1] <= $max) { - $array[] = intval($m[1]); + $array[] = (int)$m[1]; } $string = substr($string, strlen($m[0])); continue; } + // something goes wrong in the expression - return array(); + return []; } } sort($array); + return $array; } } diff --git a/system/src/Grav/Common/Scheduler/IntervalTrait.php b/system/src/Grav/Common/Scheduler/IntervalTrait.php index 9df03699c..b382c9d72 100644 --- a/system/src/Grav/Common/Scheduler/IntervalTrait.php +++ b/system/src/Grav/Common/Scheduler/IntervalTrait.php @@ -1,8 +1,9 @@ at = $expression; $this->executionTime = CronExpression::factory($expression); + return $this; } + /** * Set the execution time to every minute. * @@ -33,6 +36,7 @@ trait IntervalTrait { return $this->at('* * * * *'); } + /** * Set the execution time to every hour. * @@ -42,8 +46,10 @@ trait IntervalTrait public function hourly($minute = 0) { $c = $this->validateCronSequence($minute); + return $this->at("{$c['minute']} * * * *"); } + /** * Set the execution time to once a day. * @@ -53,14 +59,16 @@ trait IntervalTrait */ public function daily($hour = 0, $minute = 0) { - if (is_string($hour)) { + if (\is_string($hour)) { $parts = explode(':', $hour); $hour = $parts[0]; - $minute = isset($parts[1]) ? $parts[1] : '0'; + $minute = $parts[1] ?? '0'; } $c = $this->validateCronSequence($minute, $hour); + return $this->at("{$c['minute']} {$c['hour']} * * *"); } + /** * Set the execution time to once a week. * @@ -71,14 +79,16 @@ trait IntervalTrait */ public function weekly($weekday = 0, $hour = 0, $minute = 0) { - if (is_string($hour)) { + if (\is_string($hour)) { $parts = explode(':', $hour); $hour = $parts[0]; - $minute = isset($parts[1]) ? $parts[1] : '0'; + $minute = $parts[1] ?? '0'; } $c = $this->validateCronSequence($minute, $hour, null, null, $weekday); + return $this->at("{$c['minute']} {$c['hour']} * * {$c['weekday']}"); } + /** * Set the execution time to once a month. * @@ -90,14 +100,16 @@ trait IntervalTrait */ public function monthly($month = '*', $day = 1, $hour = 0, $minute = 0) { - if (is_string($hour)) { + if (\is_string($hour)) { $parts = explode(':', $hour); $hour = $parts[0]; - $minute = isset($parts[1]) ? $parts[1] : '0'; + $minute = $parts[1] ?? '0'; } $c = $this->validateCronSequence($minute, $hour, $day, $month); + return $this->at("{$c['minute']} {$c['hour']} {$c['day']} {$c['month']} *"); } + /** * Set the execution time to every Sunday. * @@ -109,6 +121,7 @@ trait IntervalTrait { return $this->weekly(0, $hour, $minute); } + /** * Set the execution time to every Monday. * @@ -120,6 +133,7 @@ trait IntervalTrait { return $this->weekly(1, $hour, $minute); } + /** * Set the execution time to every Tuesday. * @@ -131,6 +145,7 @@ trait IntervalTrait { return $this->weekly(2, $hour, $minute); } + /** * Set the execution time to every Wednesday. * @@ -142,6 +157,7 @@ trait IntervalTrait { return $this->weekly(3, $hour, $minute); } + /** * Set the execution time to every Thursday. * @@ -153,6 +169,7 @@ trait IntervalTrait { return $this->weekly(4, $hour, $minute); } + /** * Set the execution time to every Friday. * @@ -164,6 +181,7 @@ trait IntervalTrait { return $this->weekly(5, $hour, $minute); } + /** * Set the execution time to every Saturday. * @@ -175,6 +193,7 @@ trait IntervalTrait { return $this->weekly(6, $hour, $minute); } + /** * Set the execution time to every January. * @@ -187,6 +206,7 @@ trait IntervalTrait { return $this->monthly(1, $day, $hour, $minute); } + /** * Set the execution time to every February. * @@ -199,6 +219,7 @@ trait IntervalTrait { return $this->monthly(2, $day, $hour, $minute); } + /** * Set the execution time to every March. * @@ -211,6 +232,7 @@ trait IntervalTrait { return $this->monthly(3, $day, $hour, $minute); } + /** * Set the execution time to every April. * @@ -223,6 +245,7 @@ trait IntervalTrait { return $this->monthly(4, $day, $hour, $minute); } + /** * Set the execution time to every May. * @@ -235,6 +258,7 @@ trait IntervalTrait { return $this->monthly(5, $day, $hour, $minute); } + /** * Set the execution time to every June. * @@ -247,6 +271,7 @@ trait IntervalTrait { return $this->monthly(6, $day, $hour, $minute); } + /** * Set the execution time to every July. * @@ -259,6 +284,7 @@ trait IntervalTrait { return $this->monthly(7, $day, $hour, $minute); } + /** * Set the execution time to every August. * @@ -271,6 +297,7 @@ trait IntervalTrait { return $this->monthly(8, $day, $hour, $minute); } + /** * Set the execution time to every September. * @@ -283,6 +310,7 @@ trait IntervalTrait { return $this->monthly(9, $day, $hour, $minute); } + /** * Set the execution time to every October. * @@ -295,6 +323,7 @@ trait IntervalTrait { return $this->monthly(10, $day, $hour, $minute); } + /** * Set the execution time to every November. * @@ -307,6 +336,7 @@ trait IntervalTrait { return $this->monthly(11, $day, $hour, $minute); } + /** * Set the execution time to every December. * @@ -319,6 +349,7 @@ trait IntervalTrait { return $this->monthly(12, $day, $hour, $minute); } + /** * Validate sequence of cron expression. * @@ -339,6 +370,7 @@ trait IntervalTrait 'weekday' => $this->validateCronRange($weekday, 0, 6), ]; } + /** * Validate sequence of cron expression. * @@ -352,13 +384,15 @@ trait IntervalTrait if ($value === null || $value === '*') { return '*'; } + if (! is_numeric($value) || ! ($value >= $min && $value <= $max) ) { - throw new InvalidArgumentException( + throw new \InvalidArgumentException( "Invalid value: it should be '*' or between {$min} and {$max}." ); } + return $value; } } diff --git a/system/src/Grav/Common/Scheduler/Job.php b/system/src/Grav/Common/Scheduler/Job.php index 995e69609..7d80f7362 100644 --- a/system/src/Grav/Common/Scheduler/Job.php +++ b/system/src/Grav/Common/Scheduler/Job.php @@ -1,8 +1,9 @@ args = $args; // Set enabled state $status = Grav::instance()['config']->get('scheduler.status'); - $this->enabled = isset($status[$id]) && $status[$id] === 'disabled' ? false : true; + $this->enabled = !(isset($status[$id]) && $status[$id] === 'disabled'); } /** @@ -101,14 +102,15 @@ class Job /** * Get optional arguments * - * @return array|string|void + * @return string|null */ public function getArguments() { - if (is_string($this->args)) { + if (\is_string($this->args)) { return $this->args; } - return; + + return null; } public function getCronExpression() @@ -142,7 +144,7 @@ class Job * the job is due. Defaults to job creation time. * It also default the execution time if not previously defined. * - * @param DateTime $date + * @param \DateTime $date * @return bool */ public function isDue(\DateTime $date = null) @@ -151,7 +153,9 @@ class Job if (!$this->executionTime) { $this->at('* * * * *'); } - $date = $date !== null ? $date : $this->creationTime; + + $date = $date ?? $this->creationTime; + return $this->executionTime->isDue($date); } @@ -175,6 +179,7 @@ class Job public function inForeground() { $this->runInBackground = false; + return $this; } @@ -185,10 +190,7 @@ class Job */ public function runInBackground() { - if (is_callable($this->command) || $this->runInBackground === false) { - return false; - } - return true; + return !(is_callable($this->command) || $this->runInBackground === false); } /** @@ -217,6 +219,7 @@ class Job return false; }; } + return $this; } @@ -232,6 +235,7 @@ class Job if (isset($config['tempDir']) && is_dir($config['tempDir'])) { $this->tempDir = $config['tempDir']; } + return $this; } @@ -244,6 +248,7 @@ class Job public function when(callable $fn) { $this->truthTest = $fn(); + return $this; } @@ -258,10 +263,12 @@ class Job if ($this->truthTest !== true) { return false; } + // If overlapping, don't run if ($this->isOverlapping()) { return false; } + // Write lock file if necessary $this->createLockFile(); @@ -269,12 +276,13 @@ class Job if (is_callable($this->before)) { call_user_func($this->before); } + // If command is callable... if (is_callable($this->command)) { $this->output = $this->exec(); } else { /** @var Process process */ - $args = is_string($this->args) ? $this->args : implode(' ', $this->args); + $args = \is_string($this->args) ? $this->args : implode(' ', $this->args); $command = $this->command . ' ' . $args; $process = new Process($command); @@ -287,6 +295,7 @@ class Job $this->finalize(); } } + return true; } @@ -349,7 +358,7 @@ class Job private function createLockFile($content = null) { if ($this->lockFile) { - if ($content === null || !is_string($content)) { + if ($content === null || !\is_string($content)) { $content = $this->getId(); } file_put_contents($this->lockFile, $content); @@ -371,7 +380,7 @@ class Job /** * Execute a callable job. * - * @throws Exception + * @throws \RuntimeException * @return string */ private function exec() @@ -381,7 +390,7 @@ class Job try { $return_data = call_user_func_array($this->command, $this->args); $this->successful = true; - } catch (Exception $e) { + } catch (\RuntimeException $e) { $this->successful = false; } $this->output = ob_get_clean() . (is_string($return_data) ? $return_data : ''); @@ -400,6 +409,7 @@ class Job { $this->outputTo = is_array($filename) ? $filename : [$filename]; $this->outputMode = $append === false ? 'overwrite' : 'append'; + return $this; } @@ -424,11 +434,13 @@ class Job public function email($email) { if (!is_string($email) && !is_array($email)) { - throw new InvalidArgumentException('The email can be only string or array'); + throw new \InvalidArgumentException('The email can be only string or array'); } + $this->emailTo = is_array($email) ? $email : [$email]; // Force the job to run in foreground $this->inForeground(); + return $this; } @@ -450,6 +462,7 @@ class Job \Grav\Plugin\Email\Utils::sendEmail($subject, $content, $to); } + return true; } @@ -463,6 +476,7 @@ class Job public function before(callable $fn) { $this->before = $fn; + return $this; } @@ -485,6 +499,7 @@ class Job if ($runInBackground === false) { $this->inForeground(); } + return $this; } } diff --git a/system/src/Grav/Common/Scheduler/Scheduler.php b/system/src/Grav/Common/Scheduler/Scheduler.php index 043f2b991..332947289 100644 --- a/system/src/Grav/Common/Scheduler/Scheduler.php +++ b/system/src/Grav/Common/Scheduler/Scheduler.php @@ -1,8 +1,9 @@ get('scheduler.custom_jobs', []); foreach ($saved_jobs as $id => $j) { - $args = isset($j['args']) ? $j['args'] : []; + $args = $j['args'] ?? []; $id = Grav::instance()['inflector']->hyphenize($id); $job = $this->addCommand($j['command'], $args, $id); @@ -113,6 +112,7 @@ class Scheduler public function getAllJobs() { list($background, $foreground) = $this->loadSavedJobs()->getQueuedJobs(true); + return array_merge($background, $foreground); } @@ -128,6 +128,7 @@ class Scheduler { $job = new Job($fn, $args, $id); $this->queueJob($job->configure($this->config)); + return $job; } @@ -143,6 +144,7 @@ class Scheduler { $job = new Job($command, $args, $id); $this->queueJob($job->configure($this->config)); + return $job; } @@ -159,7 +161,7 @@ class Scheduler list($background, $foreground) = $this->getQueuedJobs(false); $alljobs = array_merge($background, $foreground); - if (is_null($runTime)) { + if (null === $runTime) { $runTime = new \DateTime('now'); } @@ -191,6 +193,7 @@ class Scheduler $this->executed_jobs = []; $this->failed_jobs = []; $this->output_schedule = []; + return $this; } @@ -220,6 +223,7 @@ class Scheduler public function clearJobs() { $this->jobs = []; + return $this; } @@ -250,19 +254,12 @@ class Scheduler if ($process->isSuccessful()) { $output = $process->getOutput(); - if (preg_match('$bin\/grav schedule$', $output)) { - return 1; - } else { - return 0; - } - } else { - $error = $process->getErrorOutput(); - if (Utils::startsWith($error, 'crontab: no crontab')) { - return 0; - } else { - return 2; - } + return preg_match('$bin\/grav schedule$', $output) ? 1 : 0; } + + $error = $process->getErrorOutput(); + + return Utils::startsWith($error, 'crontab: no crontab') ? 0 : 2; } /** @@ -272,8 +269,7 @@ class Scheduler */ public function getJobStates() { - $file = YamlFile::instance($this->status_path . '/status.yaml'); - return $file; + return YamlFile::instance($this->status_path . '/status.yaml'); } /** @@ -293,6 +289,7 @@ class Scheduler $this->pushFailedJob($job); } } + $saved_states = $this->getJobStates(); $saved_states->save(array_merge($saved_states->content(), $new_states)); } @@ -337,9 +334,10 @@ class Scheduler $args = $job->getArguments(); // If callable, log the string Closure if (is_callable($command)) { - $command = is_string($command) ? $command : 'Closure'; + $command = \is_string($command) ? $command : 'Closure'; } $this->addSchedulerVerboseOutput("Success: {$command} {$args}"); + return $job; } @@ -355,10 +353,11 @@ class Scheduler $command = $job->getCommand(); // If callable, log the string Closure if (is_callable($command)) { - $command = is_string($command) ? $command : 'Closure'; + $command = \is_string($command) ? $command : 'Closure'; } $output = trim($job->getOutput()); $this->addSchedulerVerboseOutput("Error: {$command} → {$output}"); + return $job; } } diff --git a/system/src/Grav/Common/Security.php b/system/src/Grav/Common/Security.php index 0a73a6777..fb6e75738 100644 --- a/system/src/Grav/Common/Security.php +++ b/system/src/Grav/Common/Security.php @@ -1,17 +1,20 @@ routes(); diff --git a/system/src/Grav/Common/Service/AssetsServiceProvider.php b/system/src/Grav/Common/Service/AssetsServiceProvider.php index d7cab3a6f..004da9cac 100644 --- a/system/src/Grav/Common/Service/AssetsServiceProvider.php +++ b/system/src/Grav/Common/Service/AssetsServiceProvider.php @@ -1,8 +1,9 @@ {$name}); + $object = unserialize($this->{$name}, ['allowed_classes' => true]); $this->{$name} = null; diff --git a/system/src/Grav/Common/Taxonomy.php b/system/src/Grav/Common/Taxonomy.php index dda284412..4d7bec073 100644 --- a/system/src/Grav/Common/Taxonomy.php +++ b/system/src/Grav/Common/Taxonomy.php @@ -1,8 +1,9 @@ taxonomy(); } - if (!$page->published() || empty($page_taxonomy)) { + if (empty($page_taxonomy) || !$page->published()) { return; } @@ -99,7 +100,7 @@ class Taxonomy } } - if (strtolower($operator) == 'or') { + if (strtolower($operator) === 'or') { foreach ($matches as $match) { $results = array_merge($results, $match); } @@ -136,14 +137,8 @@ class Taxonomy * * @return array keys of this taxonomy */ - public function getTaxonomyItemKeys($taxonomy) { - if (isset($this->taxonomy_map[$taxonomy])) { - - $results = array_keys($this->taxonomy_map[$taxonomy]); - - return $results; - } - - return []; + public function getTaxonomyItemKeys($taxonomy) + { + return isset($this->taxonomy_map[$taxonomy]) ? array_keys($this->taxonomy_map[$taxonomy]) : []; } } diff --git a/system/src/Grav/Common/Theme.php b/system/src/Grav/Common/Theme.php index 537df11d6..7b075e074 100644 --- a/system/src/Grav/Common/Theme.php +++ b/system/src/Grav/Common/Theme.php @@ -1,8 +1,9 @@ getFilename(); - $result = self::get($theme); + $result = $this->get($theme); if ($result) { $list[$theme] = $result; @@ -143,7 +144,7 @@ class Themes extends Iterator $blueprint->set('thumbnail', $this->grav['base_url'] . '/' . $path); } - $obj = new Data($file->content(), $blueprint); + $obj = new Data((array)$file->content(), $blueprint); // Override with user configuration. $obj->merge($this->config->get('themes.' . $name) ?: []); @@ -249,7 +250,7 @@ class Themes extends Iterator } } - if (in_array($scheme, $registered)) { + if (\in_array($scheme, $registered, true)) { stream_wrapper_unregister($scheme); } $type = !empty($config['type']) ? $config['type'] : 'ReadOnlyStream'; @@ -289,12 +290,12 @@ class Themes extends Iterator $locator = $this->grav['locator']; if ($config->get('system.languages.translations', true)) { - $language_file = $locator->findResource("theme://languages" . YAML_EXT); + $language_file = $locator->findResource('theme://languages' . YAML_EXT); if ($language_file) { $language = CompiledYamlFile::instance($language_file)->content(); $this->grav['languages']->mergeRecursive($language); } - $languages_folder = $locator->findResource("theme://languages/"); + $languages_folder = $locator->findResource('theme://languages'); if (file_exists($languages_folder)) { $languages = []; $iterator = new \DirectoryIterator($languages_folder); diff --git a/system/src/Grav/Common/Twig/Node/TwigNodeMarkdown.php b/system/src/Grav/Common/Twig/Node/TwigNodeMarkdown.php index 0aa12eae5..833d97921 100644 --- a/system/src/Grav/Common/Twig/Node/TwigNodeMarkdown.php +++ b/system/src/Grav/Common/Twig/Node/TwigNodeMarkdown.php @@ -1,8 +1,9 @@ $body], [], $lineno, $tag); diff --git a/system/src/Grav/Common/Twig/Node/TwigNodeRender.php b/system/src/Grav/Common/Twig/Node/TwigNodeRender.php index d94f95152..07425580a 100644 --- a/system/src/Grav/Common/Twig/Node/TwigNodeRender.php +++ b/system/src/Grav/Common/Twig/Node/TwigNodeRender.php @@ -1,8 +1,9 @@ twig)) { + if (null === $this->twig) { /** @var Config $config */ $config = $this->grav['config']; /** @var UniformResourceLocator $locator */ $locator = $this->grav['locator']; - /** @var Language $language */ $language = $this->grav['language']; @@ -256,7 +256,7 @@ class Twig */ public function processPage(Page $item, $content = null) { - $content = $content !== null ? $content : $item->content(); + $content = $content ?? $item->content(); // override the twig header vars for local resolution $this->grav->fireEvent('onTwigPageVariables', new Event(['page' => $item])); @@ -266,7 +266,7 @@ class Twig $twig_vars['media'] = $item->media(); $twig_vars['header'] = $item->header(); - $local_twig = clone($this->twig); + $local_twig = clone $this->twig; try { // Process Modular Twig @@ -370,7 +370,7 @@ class Twig $twig_vars['header'] = $page->header(); $twig_vars['media'] = $page->media(); $twig_vars['content'] = $content; - $ext = '.' . ($format ? $format : 'html') . TWIG_EXT; + $ext = '.' . ($format ?: 'html') . TWIG_EXT; // determine if params are set, if so disable twig cache $params = $this->grav['uri']->params(null, true); @@ -386,7 +386,7 @@ class Twig } catch (\Twig_Error_Loader $e) { $error_msg = $e->getMessage(); // Try html version of this template if initial template was NOT html - if ($ext != '.html' . TWIG_EXT) { + if ($ext !== '.html' . TWIG_EXT) { try { $page->templateFormat('html'); $output = $this->twig->render($page->template() . '.html' . TWIG_EXT, $vars + $twig_vars); @@ -431,11 +431,7 @@ class Twig */ public function template($template) { - if (isset($this->template)) { - return $this->template; - } else { - return $template; - } + return $this->template ?? $template; } /** diff --git a/system/src/Grav/Common/Twig/TwigEnvironment.php b/system/src/Grav/Common/Twig/TwigEnvironment.php index 66ca8bf71..54ef24f71 100644 --- a/system/src/Grav/Common/Twig/TwigEnvironment.php +++ b/system/src/Grav/Common/Twig/TwigEnvironment.php @@ -1,8 +1,9 @@ grav = Grav::instance(); - $this->debugger = isset($this->grav['debugger']) ? $this->grav['debugger'] : null; + $this->debugger = $this->grav['debugger'] ?? null; $this->config = $this->grav['config']; } @@ -211,16 +212,13 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn public function safeEmailFilter($str) { $email = ''; - for ( $i = 0, $len = strlen( $str ); $i < $len; $i++ ) { - $j = mt_rand( 0, 1); - if ( $j === 0 ) { - $email .= '&#' . ord( $str[$i] ) . ';'; - } elseif ( $j === 1 ) { - $email .= $str[$i]; - } + for ($i = 0, $len = strlen($str); $i < $len; $i++) { + $j = random_int(0, 1); + + $email .= $j === 0 ? '&#' . ord($str[$i]) . ';' : $str[$i]; } - return str_replace( '@', '@', $email ); + return str_replace('@', '@', $email); } /** @@ -233,7 +231,7 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn */ public function randomizeFilter($original, $offset = 0) { - if (!is_array($original)) { + if (!\is_array($original)) { return $original; } @@ -245,7 +243,7 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn $random = array_slice($original, $offset); shuffle($random); - $sizeOf = count($original); + $sizeOf = \count($original); for ($x = 0; $x < $sizeOf; $x++) { if ($x < $offset) { $sorted[] = $original[$x]; @@ -268,19 +266,15 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn */ public function modulusFilter($number, $divider, $items = null) { - if (is_string($number)) { + if (\is_string($number)) { $number = strlen($number); } $remainder = $number % $divider; - if (is_array($items)) { - if (isset($items[$remainder])) { - return $items[$remainder]; - } - - return $items[0]; - } + if (\is_array($items)) { + return $items[$remainder] ?? $items[0]; + } return $remainder; } @@ -306,7 +300,7 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn */ public function inflectorFilter($action, $data, $count = null) { - $action = $action . 'ize'; + $action .= 'ize'; $inflector = $this->grav['inflector']; @@ -315,18 +309,14 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn ['titleize', 'camelize', 'underscorize', 'hyphenize', 'humanize', 'ordinalize', 'monthize'], true )) { - return $inflector->$action($data); + return $inflector->{$action}($data); } if (\in_array($action, ['pluralize', 'singularize'], true)) { - if ($count) { - return $inflector->$action($data, $count); - } + return $count ? $inflector->{$action}($data, $count) : $inflector->{$action}($data); + } - return $inflector->$action($data); - } - - return $data; + return $data; } /** @@ -458,8 +448,7 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn */ public function cronFunc($at) { - $cron = CronExpression::factory($at); - return $cron; + return CronExpression::factory($at); } /** @@ -479,34 +468,34 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn if ($long_strings) { $periods = [ - "NICETIME.SECOND", - "NICETIME.MINUTE", - "NICETIME.HOUR", - "NICETIME.DAY", - "NICETIME.WEEK", - "NICETIME.MONTH", - "NICETIME.YEAR", - "NICETIME.DECADE" + 'NICETIME.SECOND', + 'NICETIME.MINUTE', + 'NICETIME.HOUR', + 'NICETIME.DAY', + 'NICETIME.WEEK', + 'NICETIME.MONTH', + 'NICETIME.YEAR', + 'NICETIME.DECADE' ]; } else { $periods = [ - "NICETIME.SEC", - "NICETIME.MIN", - "NICETIME.HR", - "NICETIME.DAY", - "NICETIME.WK", - "NICETIME.MO", - "NICETIME.YR", - "NICETIME.DEC" + 'NICETIME.SEC', + 'NICETIME.MIN', + 'NICETIME.HR', + 'NICETIME.DAY', + 'NICETIME.WK', + 'NICETIME.MO', + 'NICETIME.YR', + 'NICETIME.DEC' ]; } - $lengths = ["60", "60", "24", "7", "4.35", "12", "10"]; + $lengths = ['60', '60', '24', '7', '4.35', '12', '10']; $now = time(); // check if unix timestamp - if ((string)(int)$date == $date) { + if ((string)(int)$date === (string)$date) { $unix_date = $date; } else { $unix_date = strtotime($date); @@ -522,7 +511,7 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn $difference = $now - $unix_date; $tense = $this->grav['language']->translate('GRAV.NICETIME.AGO', null, true); - } else if ($now == $unix_date) { + } elseif ($now == $unix_date) { $difference = $now - $unix_date; $tense = $this->grav['language']->translate('GRAV.NICETIME.JUST_NOW', null, false); @@ -552,13 +541,13 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn $periods[$j] = $this->grav['language']->translate('GRAV.'.$periods[$j], null, true); if ($now == $unix_date) { - return "{$tense}"; + return $tense; } - $time = "$difference $periods[$j]"; - $time = $time . ($show_tense ? " {$tense}" : ""); + $time = "{$difference} {$periods[$j]}"; + $time .= $show_tense ? " {$tense}" : ''; - return $time; + return $time; } /** @@ -569,7 +558,7 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn */ public function xssFunc($data) { - if (is_array($data)) { + if (\is_array($data)) { $results = Security::detectXssFromArray($data); } else { return Security::detectXss($data); @@ -579,7 +568,7 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn return $key.': \''.$value . '\''; }, array_values($results), array_keys($results)); - return implode(', ', $results_parts); + return implode(', ', $results_parts); } /** @@ -793,6 +782,7 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn $env = new \Twig_Environment($loader); $template = $env->createTemplate($twig); + return $template->render($context); } @@ -883,7 +873,7 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn * * @return string */ - public static function padFilter($input, $pad_length, $pad_string = " ", $pad_type = STR_PAD_RIGHT) + public static function padFilter($input, $pad_length, $pad_string = ' ', $pad_type = STR_PAD_RIGHT) { return str_pad($input, (int)$pad_length, $pad_string, $pad_type); } @@ -904,9 +894,10 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn return array($key => $val); } - $current_array[$key] = $val; - return $current_array; - } + $current_array[$key] = $val; + + return $current_array; + } /** * Wrapper for array_intersect() method @@ -937,8 +928,8 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn return json_encode($value); } - return $value; - } + return $value; + } /** * Translate a string @@ -1050,7 +1041,8 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn * @param int $flags * @return array */ - public function regexFilter($array, $regex, $flags = 0) { + public function regexFilter($array, $regex, $flags = 0) + { return preg_grep($regex, $array, $flags); } @@ -1103,7 +1095,6 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn public function exifFunc($image, $raw = false) { if (isset($this->grav['exif'])) { - /** @var UniformResourceLocator $locator */ $locator = $this->grav['locator']; @@ -1122,10 +1113,10 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn return $exif_data->getRawData(); } - return $exif_data->getData(); - } + return $exif_data->getData(); } } + } return null; } @@ -1238,7 +1229,8 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn public function themeVarFunc($var, $default = null) { $header = $this->grav['page']->header(); - $header_classes = isset($header->$var) ? $header->$var : null; + $header_classes = $header->{$var} ?? null; + return $header_classes ?: $this->config->get('theme.' . $var, $default); } @@ -1253,7 +1245,7 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn { $header = $this->grav['page']->header(); - $body_classes = isset($header->body_classes) ? $header->body_classes : ''; + $body_classes = $header->body_classes ?? ''; foreach ((array)$classes as $class) { if (!empty($body_classes) && Utils::contains($body_classes, $class)) { @@ -1281,20 +1273,20 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn } // Make sure pages are an array - if (!is_array($pages)) { - $pages = array($pages); + if (!\is_array($pages)) { + $pages = [$pages]; } // Loop over pages and look for header vars foreach ($pages as $page) { - if (is_string($page)) { + if (\is_string($page)) { $page = $this->grav['pages']->find($page); } if ($page) { $header = $page->header(); - if (isset($header->$var)) { - return $header->$var; + if (isset($header->{$var})) { + return $header->{$var}; } } } diff --git a/system/src/Grav/Common/Twig/WriteCacheFileTrait.php b/system/src/Grav/Common/Twig/WriteCacheFileTrait.php index c413ca6fb..f521b4274 100644 --- a/system/src/Grav/Common/Twig/WriteCacheFileTrait.php +++ b/system/src/Grav/Common/Twig/WriteCacheFileTrait.php @@ -1,8 +1,9 @@ $group) { - $groups[$groupname] = isset($group['readableName']) ? $group['readableName'] : $groupname; + $groups[$groupname] = $group['readableName'] ?? $groupname; } return $groups; @@ -66,7 +67,7 @@ class Group extends Data { $groups = self::groups(); - $content = isset($groups[$groupname]) ? $groups[$groupname] : []; + $content = $groups[$groupname] ?? []; $content += ['groupname' => $groupname]; $blueprints = new Blueprints; diff --git a/system/src/Grav/Common/User/User.php b/system/src/Grav/Common/User/User.php index 6b8d717ad..b57e1a62e 100644 --- a/system/src/Grav/Common/User/User.php +++ b/system/src/Grav/Common/User/User.php @@ -1,8 +1,9 @@ 'd-m-Y H:i (e.g. '.$now->format('d-m-Y H:i').')', @@ -356,7 +359,7 @@ abstract class Utils * * @return string */ - public static function truncate($string, $limit = 150, $up_to_break = false, $break = " ", $pad = "…") + public static function truncate($string, $limit = 150, $up_to_break = false, $break = ' ', $pad = '…') { // return with no change if string is shorter than $limit if (mb_strlen($string) <= $limit) { @@ -642,10 +645,11 @@ abstract class Utils $extensions = []; foreach ($mimetypes as $mimetype) { $extension = static::getExtensionByMime($mimetype, false); - if ($extension && !in_array($extension, $extensions)) { + if ($extension && !\in_array($extension, $extensions, true)) { $extensions[] = $extension; } } + return $extensions; } @@ -731,7 +735,7 @@ abstract class Utils */ public static function normalizePath($path) { - $root = ($path[0] === '/') ? '/' : ''; + $root = strpos($path, '/') === 0 ? '/' : ''; $segments = explode('/', trim($path, '/')); $ret = []; @@ -758,7 +762,7 @@ abstract class Utils */ public static function isFunctionDisabled($function) { - return in_array($function, explode(',', ini_get('disable_functions')), true); + return \in_array($function, explode(',', ini_get('disable_functions')), true); } /** @@ -770,7 +774,7 @@ abstract class Utils { $timezones = \DateTimeZone::listIdentifiers(\DateTimeZone::ALL); $offsets = []; - $testDate = new \DateTime; + $testDate = new \DateTime(); foreach ($timezones as $zone) { $tz = new \DateTimeZone($zone); @@ -826,7 +830,7 @@ abstract class Utils public static function arrayFlatten($array) { $flatten = array(); - foreach ($array as $key => $inner){ + foreach ($array as $key => $inner) { if (is_array($inner)) { foreach ($inner as $inner_key => $value) { $flatten[$inner_key] = $value; @@ -835,6 +839,7 @@ abstract class Utils $flatten[$key] = $inner; } } + return $flatten; } @@ -848,17 +853,14 @@ abstract class Utils public static function arrayFlattenDotNotation($array, $prepend = '') { $results = array(); - foreach ($array as $key => $value) - { - if (is_array($value)) - { + foreach ($array as $key => $value) { + if (is_array($value)) { $results = array_merge($results, static::arrayFlattenDotNotation($value, $prepend.$key.'.')); - } - else - { + } else { $results[$prepend.$key] = $value; } } + return $results; } @@ -869,14 +871,17 @@ abstract class Utils * @param string $separator * @return array */ - public static function arrayUnflattenDotNotation($array, $separator = '.') { - $newArray = array(); - foreach($array as $key => $value) { + public static function arrayUnflattenDotNotation($array, $separator = '.') + { + $newArray = []; + foreach ($array as $key => $value) { $dots = explode($separator, $key); - if(count($dots) > 1) { - $last = &$newArray[ $dots[0] ]; - foreach($dots as $k => $dot) { - if($k == 0) continue; + if (\count($dots) > 1) { + $last = &$newArray[$dots[0]]; + foreach ($dots as $k => $dot) { + if ($k === 0) { + continue; + } $last = &$last[$dot]; } $last = $value; @@ -884,6 +889,7 @@ abstract class Utils $newArray[$key] = $value; } } + return $newArray; } @@ -902,7 +908,7 @@ abstract class Utils $languages_enabled = Grav::instance()['config']->get('system.languages.supported', []); - if ($string[0] === '/' && $string[3] === '/' && in_array(substr($string, 1, 2), $languages_enabled)) { + if ($string[0] === '/' && $string[3] === '/' && \in_array(substr($string, 1, 2), $languages_enabled, true)) { return true; } @@ -924,9 +930,9 @@ abstract class Utils // try to use DateTime and default format if ($dateformat) { - $datetime = DateTime::createFromFormat($dateformat, $date); + $datetime = \DateTime::createFromFormat($dateformat, $date); } else { - $datetime = new DateTime($date); + $datetime = new \DateTime($date); } // fallback to strtotime() if DateTime approach failed @@ -1050,12 +1056,8 @@ abstract class Utils //Nonce generated 12-24 hours ago $previousTick = true; - if ($nonce === self::getNonce($action, $previousTick)) { - return true; - } - //Invalid nonce - return false; + return $nonce === self::getNonce($action, $previousTick); } /** @@ -1139,7 +1141,6 @@ abstract class Utils $array[$key] = array_merge($array[$key], $value); } - return $array; } @@ -1190,7 +1191,7 @@ abstract class Utils * @param int $sort_flags * @return array */ - public static function sortArrayByKey($array, $array_key, $direction = SORT_DESC, $sort_flags = SORT_REGULAR ) + public static function sortArrayByKey($array, $array_key, $direction = SORT_DESC, $sort_flags = SORT_REGULAR) { $output = []; @@ -1289,13 +1290,14 @@ abstract class Utils * @return integer Returns only the number of units, not the type letter. Returns 0 if the $to unit type is out of scope. * */ - public static function convertSize($bytes, $to, $decimal_places = 1) { + public static function convertSize($bytes, $to, $decimal_places = 1) + { $formulas = array( 'K' => number_format($bytes / 1024, $decimal_places), 'M' => number_format($bytes / 1048576, $decimal_places), 'G' => number_format($bytes / 1073741824, $decimal_places) ); - return isset($formulas[$to]) ? $formulas[$to] : 0; + return $formulas[$to] ?? 0; } /** @@ -1305,7 +1307,8 @@ abstract class Utils * @param int $precision * @return string */ - public static function prettySize($bytes, $precision = 2) { + public static function prettySize($bytes, $precision = 2) + { $units = array('B', 'KB', 'MB', 'GB', 'TB'); $bytes = max($bytes, 0); diff --git a/system/src/Grav/Common/Yaml.php b/system/src/Grav/Common/Yaml.php index 2c43f73ab..ad6d81b07 100644 --- a/system/src/Grav/Common/Yaml.php +++ b/system/src/Grav/Common/Yaml.php @@ -1,8 +1,9 @@ 100 ? round($steps / 100) : $steps); + $freq = (int)($steps > 100 ? round($steps / 100) : $steps); $this->progress->setMaxSteps($steps); $this->progress->setRedrawFrequency($freq); $this->progress->setMessage('Adding files...'); diff --git a/system/src/Grav/Console/Cli/CacheCommand.php b/system/src/Grav/Console/Cli/CacheCommand.php index 459045d0d..b80482b11 100644 --- a/system/src/Grav/Console/Cli/CacheCommand.php +++ b/system/src/Grav/Console/Cli/CacheCommand.php @@ -1,9 +1,9 @@ output->writeln(' |- Dependencies found... [' . implode(',', $depencencies) . ']'); + $this->output->writeln(' |- Dependencies found... [' . implode(',', $dependencies) . ']'); $question = new ConfirmationQuestion(" | '- Dependencies will not be satisfied. Continue ? [y|N] ", false); $answer = $this->all_yes ? true : $helper->ask($this->input, $this->output, $question); diff --git a/system/src/Grav/Console/Gpm/IndexCommand.php b/system/src/Grav/Console/Gpm/IndexCommand.php index 876037e6e..fdefec7cf 100644 --- a/system/src/Grav/Console/Gpm/IndexCommand.php +++ b/system/src/Grav/Console/Gpm/IndexCommand.php @@ -1,9 +1,9 @@ slug]) ? $list[$package->slug] : $package; + $package = $list[$package->slug] ?? $package; $type = ucfirst(preg_replace('/s$/', '', $package->package_type)); $method = 'is' . $type . 'Installed'; $installed = $this->gpm->{$method}($package->slug); diff --git a/system/src/Grav/Console/Gpm/InfoCommand.php b/system/src/Grav/Console/Gpm/InfoCommand.php index e73889464..64a5bd967 100644 --- a/system/src/Grav/Console/Gpm/InfoCommand.php +++ b/system/src/Grav/Console/Gpm/InfoCommand.php @@ -1,9 +1,9 @@