Grav 1.6 code cleanup (#2366)

* Code cleanup
* Define admin menu for Flex Users
This commit is contained in:
Matias Griese
2019-02-08 12:56:15 +02:00
committed by GitHub
parent 48816d9f2e
commit 9bd66031ab
17 changed files with 124 additions and 111 deletions

View File

@@ -1,4 +1,4 @@
title: Accounts
title: User Accounts
description: User Accounts
type: flex-objects
@@ -17,3 +17,10 @@ config:
order:
by: username
dir: asc
menu:
list:
route: /users
title: Users
icon: fa-users
authorize: ['admin.users', 'admin.super']

View File

@@ -19,11 +19,11 @@ abstract class BaseAsset extends PropertyObject
{
use AssetUtilsTrait;
const CSS_ASSET = true;
const JS_ASSET = false;
protected const CSS_ASSET = true;
protected const JS_ASSET = false;
/** @const Regex to match CSS import content */
const CSS_IMPORT_REGEX = '{@import(.*?);}';
protected const CSS_IMPORT_REGEX = '{@import(.*?);}';
protected $asset;

View File

@@ -21,17 +21,17 @@ class Pipeline extends PropertyObject
{
use AssetUtilsTrait;
const CSS_ASSET = true;
const JS_ASSET = false;
protected const CSS_ASSET = true;
protected const JS_ASSET = false;
/** @const Regex to match CSS urls */
const CSS_URL_REGEX = '{url\(([\'\"]?)(.*?)\1\)}';
protected const CSS_URL_REGEX = '{url\(([\'\"]?)(.*?)\1\)}';
/** @const Regex to match CSS sourcemap comments */
const CSS_SOURCEMAP_REGEX = '{\/\*# (.*?) \*\/}';
protected const CSS_SOURCEMAP_REGEX = '{\/\*# (.*?) \*\/}';
/** @const Regex to match CSS import content */
const CSS_IMPORT_REGEX = '{@import(.*?);}';
protected const CSS_IMPORT_REGEX = '{@import(.*?);}';
protected $css_minify;
protected $css_minify_windows;

View File

@@ -22,9 +22,9 @@ use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
class Backups
{
const BACKUP_FILENAME_REGEXZ = "#(.*)--(\d*).zip#";
protected const BACKUP_FILENAME_REGEXZ = "#(.*)--(\d*).zip#";
const BACKUP_DATE_FORMAT = 'YmdHis';
protected const BACKUP_DATE_FORMAT = 'YmdHis';
protected static $backup_dir;

View File

@@ -47,7 +47,7 @@ class Composer
$composer = static::getComposerLocation();
if ($composer !== static::DEFAULT_PATH && is_executable($composer)) {
$file = fopen($composer, 'r');
$file = fopen($composer, 'rb');
$firstLine = fgets($file);
fclose($file);

View File

@@ -24,21 +24,18 @@ class Validation
*/
public static function validate($value, array $field)
{
$messages = [];
$validate = isset($field['validate']) ? (array) $field['validate'] : [];
// Validate type with fallback type text.
$type = (string) isset($validate['type']) ? $validate['type'] : $field['type'];
$method = 'type' . str_replace('-', '_', $type);
// If value isn't required, we will stop validation if empty value is given.
if ((empty($validate['required']) || (isset($validate['required']) && $validate['required'] !== true)) && ($value === null || $value === '' || (($field['type'] === 'checkbox' || $field['type'] === 'switch') && $value == false))) {
return $messages;
}
if (!isset($field['type'])) {
$field['type'] = 'text';
}
$type = $validate['type'] ?? $field['type'];
$validate = (array)($field['validate'] ?? null);
$required = $validate['required'] ?? false;
// If value isn't required, we will stop validation if empty value is given.
if ($required !== true && ($value === null || $value === '' || (($field['type'] === 'checkbox' || $field['type'] === 'switch') && $value == false))
) {
return [];
}
// Get language class.
$language = Grav::instance()['language'];
@@ -49,17 +46,17 @@ class Validation
: $language->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;
}
@@ -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';
}

View File

@@ -150,8 +150,8 @@ abstract class Folder
return '';
}
$baseParts = explode('/', isset($base[0]) && '/' === $base[0] ? substr($base, 1) : $base);
$pathParts = explode('/', isset($path[0]) && '/' === $path[0] ? substr($path, 1) : $path);
$baseParts = explode('/', ltrim($base, '/'));
$pathParts = explode('/', ltrim($path, '/'));
array_pop($baseParts);
$lastPart = array_pop($pathParts);

View File

@@ -249,7 +249,6 @@ class GPM extends Iterator
if (version_compare($local_version, $remote_version) < 0) {
$repository[$slug]->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]->toArray();
}
@@ -645,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;
@@ -729,7 +728,7 @@ class GPM extends Iterator
$dependency = $dependency['name'];
}
if ($dependency == $slug) {
if ($dependency === $slug) {
$dependent_packages[] = $package_name;
}
}
@@ -836,13 +835,13 @@ 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
@@ -856,7 +855,7 @@ 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
) {
@@ -953,7 +952,7 @@ class GPM extends Iterator
private function firstVersionIsLower($firstVersion, $secondVersion)
{
return version_compare($firstVersion, $secondVersion) == -1;
return version_compare($firstVersion, $secondVersion) === -1;
}
/**
@@ -1024,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;
}

View File

@@ -90,8 +90,8 @@ class Installer
return false;
}
if (self::lastErrorCode() == self::IS_LINK && $options['ignore_symlinks'] ||
self::lastErrorCode() == self::EXISTS && !$options['overwrite']
if ((self::lastErrorCode() === self::IS_LINK && $options['ignore_symlinks']) ||
(self::lastErrorCode() === self::EXISTS && !$options['overwrite'])
) {
return false;
}
@@ -391,7 +391,7 @@ 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;
}

View File

@@ -52,7 +52,7 @@ class Inflector
$lowercased_word = strtolower($word);
foreach (static::$uncountable as $_uncountable) {
if (substr($lowercased_word, (-1 * strlen($_uncountable))) == $_uncountable) {
if (substr($lowercased_word, -1 * strlen($_uncountable)) === $_uncountable) {
return $word;
}
}
@@ -91,7 +91,7 @@ class Inflector
$lowercased_word = strtolower($word);
foreach (static::$uncountable as $_uncountable) {
if (substr($lowercased_word, (-1 * strlen($_uncountable))) == $_uncountable) {
if (substr($lowercased_word, -1 * strlen($_uncountable)) === $_uncountable) {
return $word;
}
}
@@ -286,7 +286,7 @@ class Inflector
{
static::init();
if (in_array(($number % 100), range(11, 13))) {
if (\in_array($number % 100, range(11, 13), true)) {
return $number . static::$ordinals['default'];
}

View File

@@ -495,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;
}

View File

@@ -894,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();
@@ -1400,7 +1402,7 @@ 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;
@@ -1704,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')
@@ -1925,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));
@@ -2387,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());
}
@@ -2402,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());
}
@@ -2439,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);
}
@@ -2456,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());
}
@@ -2589,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);
@@ -2669,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());
}
@@ -2686,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]);
}
}
@@ -3026,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);
}
}
}
}

View File

@@ -411,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);
}
}
@@ -433,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);
}
}
@@ -512,7 +515,7 @@ class Pages
$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) {
@@ -1197,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;
}
@@ -1347,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++;
}

View File

@@ -168,7 +168,7 @@ class Cron
// check type
$type = $this->getType();
if ($type == self::TYPE_UNDEFINED) {
if ($type === self::TYPE_UNDEFINED) {
return $this->getCron();
}
@@ -177,12 +177,12 @@ class Cron
$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);
@@ -191,12 +191,12 @@ class Cron
}
// 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);
@@ -205,7 +205,7 @@ class Cron
}
// 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());
}
@@ -466,11 +466,11 @@ class Cron
$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))
);
}
@@ -491,7 +491,7 @@ class Cron
$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;

View File

@@ -9,10 +9,12 @@
namespace Grav\Common;
use Grav\Common\Page\Pages;
class Security
{
public static function detectXssFromPages($pages, $route = true, callable $status = null)
public static function detectXssFromPages(Pages $pages, $route = true, callable $status = null)
{
$routes = $pages->routes();

View File

@@ -645,7 +645,7 @@ 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;
}
}

View File

@@ -68,7 +68,7 @@ class Flex implements \Countable
}
/**
* @return array
* @return array|FlexDirectory[]
*/
public function getDirectories() : array
{