Code readability improvements

This commit is contained in:
Matias Griese
2017-11-06 10:18:22 +02:00
parent cd15055280
commit 980b2b67cd
25 changed files with 100 additions and 83 deletions

View File

@@ -32,7 +32,7 @@ class ZipBackup
/**
* Backup
*
* @param null $destination
* @param string|null $destination
* @param callable|null $messager
*
* @return null|string
@@ -107,18 +107,19 @@ class ZipBackup
* @param $exclusiveLength
* @param $messager
*/
private static function folderToZip($folder, \ZipArchive &$zipFile, $exclusiveLength, callable $messager = null)
private static function folderToZip($folder, \ZipArchive $zipFile, $exclusiveLength, callable $messager = null)
{
$handle = opendir($folder);
while (false !== $f = readdir($handle)) {
if ($f != '.' && $f != '..') {
if ($f !== '.' && $f !== '..') {
$filePath = "$folder/$f";
// Remove prefix from file path before add to zip.
$localPath = substr($filePath, $exclusiveLength);
if (in_array($f, static::$ignoreFolders)) {
continue;
} elseif (in_array($localPath, static::$ignorePaths)) {
}
if (in_array($localPath, static::$ignorePaths)) {
$zipFile->addEmptyDir($f);
continue;
}

View File

@@ -32,7 +32,7 @@ class CompiledBlueprints extends CompiledBase
*/
public function checksum()
{
if (!isset($this->checksum)) {
if (null === $this->checksum) {
$this->checksum = md5(json_encode($this->files) . json_encode($this->getTypes()) . $this->version);
}
@@ -92,6 +92,7 @@ class CompiledBlueprints extends CompiledBase
// Convert file list into parent list.
$list = [];
/** @var array $files */
foreach ($this->files as $files) {
foreach ($files as $name => $item) {
$list[$name][] = $this->path . $item['file'];

View File

@@ -60,7 +60,7 @@ class CompiledLanguages extends CompiledBase
{
$file = CompiledYamlFile::instance($filename);
if (preg_match('|languages\.yaml$|', $filename)) {
$this->object->mergeRecursive($file->content());
$this->object->mergeRecursive((array) $file->content());
} else {
$this->object->mergeRecursive([$name => $file->content()]);
}

View File

@@ -16,6 +16,7 @@ use Grav\Common\Utils;
class Config extends Data
{
/** @var string */
protected $checksum;
protected $modified = false;
protected $timestamp = 0;

View File

@@ -133,7 +133,7 @@ class Setup extends Data
*/
public function __construct($container)
{
$environment = isset(static::$environment) ? static::$environment : ($container['uri']->environment() ?: 'localhost');
$environment = null !== static::$environment ? static::$environment : ($container['uri']->environment() ?: 'localhost');
// Pre-load setup.php which contains our initial configuration.
// Configuration may contain dynamic parts, which is why we need to always load it.
@@ -151,11 +151,13 @@ class Setup extends Data
// Set up environment.
$this->def('environment', $environment ?: 'cli');
$this->def('streams.schemes.environment.prefixes', ['' => ($environment ? ["user://{$this->environment}"] : [])]);
$this->def('streams.schemes.environment.prefixes', ['' => $environment ? ["user://{$this->environment}"] : []]);
}
/**
* @return $this
* @throws \RuntimeException
* @throws \InvalidArgumentException
*/
public function init()
{
@@ -175,7 +177,7 @@ class Setup extends Data
// Update streams.
foreach (array_reverse($files) as $path) {
$file = CompiledYamlFile::instance($path);
$content = $file->content();
$content = (array)$file->content();
if (!empty($content['schemes'])) {
$this->items['streams']['schemes'] = $content['schemes'] + $this->items['streams']['schemes'];
}
@@ -196,6 +198,7 @@ class Setup extends Data
* Initialize resource locator by using the configuration.
*
* @param UniformResourceLocator $locator
* @throws \BadMethodCallException
*/
public function initializeLocator(UniformResourceLocator $locator)
{
@@ -212,7 +215,7 @@ class Setup extends Data
$force = isset($config['force']) ? $config['force'] : false;
if (isset($config['prefixes'])) {
foreach ($config['prefixes'] as $prefix => $paths) {
foreach ((array)$config['prefixes'] as $prefix => $paths) {
$locator->addPath($scheme, $prefix, $paths, $override, $force);
}
}
@@ -229,7 +232,7 @@ class Setup extends Data
$schemes = [];
foreach ((array) $this->get('streams.schemes') as $scheme => $config) {
$type = !empty($config['type']) ? $config['type'] : 'ReadOnlyStream';
if ($type[0] != '\\') {
if ($type[0] !== '\\') {
$type = '\\RocketTheme\\Toolbox\\StreamWrapper\\' . $type;
}
@@ -242,6 +245,8 @@ class Setup extends Data
/**
* @param UniformResourceLocator $locator
* @throws \InvalidArgumentException
* @throws \BadMethodCallException
* @throws \RuntimeException
*/
protected function check(UniformResourceLocator $locator)
{

View File

@@ -78,7 +78,7 @@ class BlueprintSchema extends BlueprintSchemaBase implements ExportInterface
} elseif (is_array($field) && is_array($val)) {
// Array has been defined in blueprints.
$messages += $this->validateArray($field, $val);
} elseif (isset($rules['validation']) && $rules['validation'] == 'strict') {
} elseif (isset($rules['validation']) && $rules['validation'] === 'strict') {
// Undefined/extra item.
throw new \RuntimeException(sprintf('%s is not defined in blueprints', $key));
}
@@ -106,7 +106,7 @@ class BlueprintSchema extends BlueprintSchemaBase implements ExportInterface
} elseif (is_array($field) && is_array($val)) {
// Array has been defined in blueprints.
$field = $this->filterArray($field, $val);
} elseif (isset($rules['validation']) && $rules['validation'] == 'strict') {
} elseif (isset($rules['validation']) && $rules['validation'] === 'strict') {
$field = null;
}
@@ -138,7 +138,7 @@ class BlueprintSchema extends BlueprintSchemaBase implements ExportInterface
if (isset($data[$name])) {
continue;
}
if ($field['type'] == 'file' && isset($data['data']['name'][$name])) { //handle case of file input fields required
if ($field['type'] === 'file' && isset($data['data']['name'][$name])) { //handle case of file input fields required
continue;
}
@@ -164,7 +164,7 @@ class BlueprintSchema extends BlueprintSchemaBase implements ExportInterface
$default = isset($field[$property]) ? $field[$property] : null;
$config = Grav::instance()['config']->get($value, $default);
if (!is_null($config)) {
if (null !== $config) {
$field[$property] = $config;
}
}

View File

@@ -65,11 +65,11 @@ class Blueprints
/** @var \DirectoryIterator $file */
foreach ($iterator as $file) {
if (!$file->isFile() || '.' . $file->getExtension() != YAML_EXT) {
if (!$file->isFile() || '.' . $file->getExtension() !== YAML_EXT) {
continue;
}
$name = $file->getBasename(YAML_EXT);
$this->types[$name] = ucfirst(strtr($name, '_', ' '));
$this->types[$name] = ucfirst(str_replace('_', ' ', $name));
}
}

View File

@@ -233,6 +233,7 @@ class Data implements DataInterface, \ArrayAccess, \Countable, ExportInterface
/**
* Save data if storage has been defined.
* @throws \RuntimeException
*/
public function save()
{

View File

@@ -57,6 +57,7 @@ class SimplePageHandler extends Handler
* @param $resource
*
* @return string
* @throws \RuntimeException
*/
protected function getResource($resource)
{
@@ -80,8 +81,7 @@ class SimplePageHandler extends Handler
// If we got this far, nothing was found.
throw new \RuntimeException(
"Could not find resource '$resource' in any resource paths."
. "(searched: " . join(", ", $this->searchPaths). ")"
"Could not find resource '{$resource}' in any resource paths (searched: " . implode(', ', $this->searchPaths). ')'
);
}
@@ -89,7 +89,7 @@ class SimplePageHandler extends Handler
{
if (!is_dir($path)) {
throw new \InvalidArgumentException(
"'$path' is not a valid directory"
"'{$path}' is not a valid directory"
);
}

View File

@@ -42,9 +42,9 @@ trait CompiledFile
// Load real file if cache isn't up to date (or is invalid).
if (
!isset($cache['@class'])
|| $cache['@class'] != $class
|| $cache['modified'] != $modified
|| $cache['filename'] != $this->filename
|| $cache['@class'] !== $class
|| $cache['modified'] !== $modified
|| $cache['filename'] !== $this->filename
) {
// Attempt to lock the file for writing.
try {

View File

@@ -108,8 +108,7 @@ abstract class Folder
$files[] = $file->getPathname() . '?'. $file->getMTime();
}
$hash = md5(serialize($files));
return $hash;
return md5(serialize($files));
}
/**
@@ -234,7 +233,7 @@ abstract class Folder
/** @var \RecursiveDirectoryIterator $file */
foreach ($iterator as $file) {
// Ignore hidden files.
if ($file->getFilename()[0] == '.') {
if ($file->getFilename()[0] === '.') {
continue;
}
if (!$folders && $file->isDir()) {
@@ -339,7 +338,7 @@ abstract class Folder
}
// Don't do anything if the source is the same as the new target
if ($source == $target) {
if ($source === $target) {
return;
}
@@ -377,6 +376,7 @@ abstract class Folder
* @param string $target
* @param bool $include_target
* @return bool
* @throws \RuntimeException
*/
public static function delete($target, $include_target = true)
{
@@ -435,6 +435,7 @@ abstract class Folder
* @param $dest
*
* @return bool
* @throws \RuntimeException
*/
public static function rcopy($src, $dest)
{
@@ -447,7 +448,7 @@ abstract class Folder
// If the destination directory does not exist create it
if (!is_dir($dest)) {
Folder::mkdir($dest);
static::mkdir($dest);
}
// Open the source directory to read in files
@@ -455,10 +456,10 @@ abstract class Folder
/** @var \DirectoryIterator $f */
foreach ($i as $f) {
if ($f->isFile()) {
copy($f->getRealPath(), "$dest/" . $f->getFilename());
copy($f->getRealPath(), "{$dest}/" . $f->getFilename());
} else {
if (!$f->isDot() && $f->isDir()) {
static::rcopy($f->getRealPath(), "$dest/$f");
static::rcopy($f->getRealPath(), "{$dest}/{$f}");
}
}
}
@@ -479,10 +480,10 @@ abstract class Folder
}
// Go through all items in filesystem and recursively remove everything.
$files = array_diff(scandir($folder), array('.', '..'));
$files = array_diff(scandir($folder, SCANDIR_SORT_NONE), array('.', '..'));
foreach ($files as $file) {
$path = "{$folder}/{$file}";
(is_dir($path)) ? self::doDelete($path) : @unlink($path);
is_dir($path) ? self::doDelete($path) : @unlink($path);
}
return $include_target ? @rmdir($folder) : true;

View File

@@ -37,7 +37,7 @@ class RecursiveFolderFilterIterator extends \RecursiveFilterIterator
/** @var $current \SplFileInfo */
$current = $this->current();
if ($current->isDir() && !in_array($current->getFilename(), $this::$folder_ignores)) {
if ($current->isDir() && !in_array($current->getFilename(), $this::$folder_ignores, true)) {
return true;
}
return false;

View File

@@ -34,6 +34,10 @@ class Package {
return isset($this->data->$key);
}
public function __set($key, $value) {
throw new \BadMethodCallException('Not Implemented');
}
public function __toString() {
return $this->toJson();
}

View File

@@ -22,6 +22,7 @@ class GravCore extends AbstractPackageCollection
/**
* @param bool $refresh
* @param null $callback
* @throws \InvalidArgumentException
*/
public function __construct($refresh = false, $callback = null)
{
@@ -38,7 +39,7 @@ class GravCore extends AbstractPackageCollection
$this->date = isset($this->data['date']) ? $this->data['date'] : '-';
if (isset($this->data['assets'])) {
foreach ($this->data['assets'] as $slug => $data) {
foreach ((array)$this->data['assets'] as $slug => $data) {
$this->items[$slug] = new Package($data);
}
}
@@ -68,10 +69,10 @@ class GravCore extends AbstractPackageCollection
}
$diffLog = [];
foreach ($this->data['changelog'] as $version => $changelog) {
foreach ((array)$this->data['changelog'] as $version => $changelog) {
preg_match("/[\w-\.]+/", $version, $cleanVersion);
if (!$cleanVersion || version_compare($diff, $cleanVersion[0], ">=")) {
if (!$cleanVersion || version_compare($diff, $cleanVersion[0], '>=')) {
continue;
}

View File

@@ -29,6 +29,7 @@ class Upgrader
*
* @param boolean $refresh Applies to Remote Packages only and forces a refetch of data
* @param callable $callback Either a function or callback in array notation
* @throws \InvalidArgumentException
*/
public function __construct($refresh = false, $callback = null)
{

View File

@@ -32,7 +32,7 @@ class Base32 {
*/
public static function encode( $bytes ) {
$i = 0; $index = 0; $digit = 0;
$base32 = "";
$base32 = '';
$bytes_len = strlen($bytes);
while( $i < $bytes_len ) {
$currByte = ord($bytes{$i});
@@ -51,7 +51,7 @@ class Base32 {
} else {
$digit = ($currByte >> (8 - ($index + 5))) & 0x1F;
$index = ($index + 5) % 8;
if( $index == 0 ) $i++;
if( $index === 0 ) $i++;
}
$base32 .= self::$base32Chars{$digit};
}
@@ -96,7 +96,7 @@ class Base32 {
$bytes[$offset] |= $digit << (8 - $index);
}
}
$bites = "";
$bites = '';
foreach( $bytes as $byte ) $bites .= chr($byte);
return $bites;
}

View File

@@ -55,13 +55,13 @@ class Excerpts
public static function getExcerptFromHtml($html, $tag)
{
$doc = new \DOMDocument();
$doc->loadHtml($html);
$doc->loadHTML($html);
$images = $doc->getElementsByTagName($tag);
$excerpt = null;
foreach ($images as $image) {
$attributes = [];
foreach ($image->attributes as $name => $value) {
foreach ((array)$image->attributes as $name => $value) {
$attributes[$name] = $value->value;
}
$excerpt = [
@@ -87,7 +87,7 @@ class Excerpts
$html = '<'.$element['name'];
if (isset($element['attributes'])) {
foreach ($element['attributes'] as $name => $value) {
foreach ((array)$element['attributes'] as $name => $value) {
if ($value === null) {
continue;
}
@@ -141,9 +141,9 @@ class Excerpts
foreach ($actions as $attrib => $value) {
$key = $attrib;
if (in_array($attrib, $valid_attributes)) {
if (in_array($attrib, $valid_attributes, true)) {
// support both class and classes.
if ($attrib == 'classes') {
if ($attrib === 'classes') {
$attrib = 'class';
}
$excerpt['element']['attributes'][$attrib] = str_replace(',', ' ', $value);
@@ -210,8 +210,8 @@ class Excerpts
} else {
// File is also local if scheme is http(s) and host matches.
$local_file = isset($url_parts['path'])
&& (empty($url_parts['scheme']) || in_array($url_parts['scheme'], ['http', 'https']))
&& (empty($url_parts['host']) || $url_parts['host'] == Grav::instance()['uri']->host());
&& (empty($url_parts['scheme']) || in_array($url_parts['scheme'], ['http', 'https'], true))
&& (empty($url_parts['host']) || $url_parts['host'] === Grav::instance()['uri']->host());
if ($local_file) {
$filename = basename($url_parts['path']);
@@ -251,7 +251,7 @@ class Excerpts
$class = isset($excerpt['element']['attributes']['class']) ? $excerpt['element']['attributes']['class'] : '';
$id = isset($excerpt['element']['attributes']['id']) ? $excerpt['element']['attributes']['id'] : '';
$excerpt['element'] = $medium->parseDownElement($title, $alt, $class, $id, true);
$excerpt['element'] = $medium->parsedownElement($title, $alt, $class, $id, true);
} else {
// Not a current page media file, see if it needs converting to relative.

View File

@@ -9,18 +9,23 @@
namespace Grav\Common\Helpers;
use Grav\Common\Grav;
use SebastianBergmann\GlobalState\RuntimeException;
class Exif
{
public $reader;
/**
* Exif constructor.
* @throws RuntimeException
*/
public function __construct()
{
if (Grav::instance()['config']->get('system.media.auto_metadata_exif')) {
if (function_exists('exif_read_data') && class_exists('\PHPExif\Reader\Reader')) {
$this->reader = \PHPExif\Reader\Reader::factory(\PHPExif\Reader\Reader::TYPE_NATIVE);
} else {
throw new \Exception('Please enable the Exif extension for PHP or disable Exif support in Grav system configuration');
throw new \RuntimeException('Please enable the Exif extension for PHP or disable Exif support in Grav system configuration');
}
}
}

View File

@@ -34,7 +34,7 @@ class Truncator {
* @param string $ellipsis String to use as ellipsis (if any).
* @return string Safe truncated HTML.
*/
public static function truncateWords($html, $limit = 0, $ellipsis = "")
public static function truncateWords($html, $limit = 0, $ellipsis = '')
{
if ($limit <= 0) {
return $html;
@@ -94,7 +94,7 @@ class Truncator {
$dom = self::htmlToDomDocument($html);
// Grab the body of our DOM.
$body = $dom->getElementsByTagName("body")->item(0);
$body = $dom->getElementsByTagName('body')->item(0);
// Iterate over letters.
$letters = new DOMLettersIterator($body);
@@ -181,7 +181,7 @@ class Truncator {
{
$avoid = array('a', 'strong', 'em', 'h1', 'h2', 'h3', 'h4', 'h5'); //html tags to avoid appending the ellipsis to
if (in_array($domNode->parentNode->nodeName, $avoid) && $domNode->parentNode->parentNode !== null) {
if ($domNode->parentNode->parentNode !== null && in_array($domNode->parentNode->nodeName, $avoid, true)) {
// Append as text node to parent instead
$textNode = new DOMText($ellipsis);
@@ -204,9 +204,9 @@ class Truncator {
* @return string
*/
private static function innerHTML($element) {
$innerHTML = "";
$innerHTML = '';
$children = $element->childNodes;
foreach ($children as $child)
foreach ((array)$children as $child)
{
$tmp_dom = new DOMDocument();
$tmp_dom->appendChild($tmp_dom->importNode($child, true));

View File

@@ -157,14 +157,13 @@ class LanguageCodes
{
if (isset(static::$codes[$code])) {
return static::get($code, 'nativeName');
} else {
if (preg_match('/[a-zA-Z]{2}-[a-zA-Z]{2}/', $code)) {
return static::get(substr($code, 0, 2), 'nativeName') . ' (' . substr($code, -2) . ')';
} else {
return $code;
}
}
if (preg_match('/[a-zA-Z]{2}-[a-zA-Z]{2}/', $code)) {
return static::get(substr($code, 0, 2), 'nativeName') . ' (' . substr($code, -2) . ')';
}
return $code;
}
public static function getOrientation($code)
@@ -179,7 +178,7 @@ class LanguageCodes
public static function isRtl($code)
{
if (static::getOrientation($code) == 'rtl') {
if (static::getOrientation($code) === 'rtl') {
return true;
}
return false;
@@ -192,7 +191,6 @@ class LanguageCodes
if (isset(static::$codes[$key])) {
$results[$key] = static::$codes[$key];
}
}
return $results;
}
@@ -201,8 +199,8 @@ class LanguageCodes
{
if (isset(static::$codes[$code][$type])) {
return static::$codes[$code][$type];
} else {
return false;
}
return false;
}
}

View File

@@ -34,7 +34,7 @@ class MediumFactory
$config = Grav::instance()['config'];
$media_params = $config->get("media.types.".strtolower($ext));
$media_params = $config->get("media.types." . strtolower($ext));
if (!$media_params) {
return null;
}
@@ -106,7 +106,7 @@ class MediumFactory
* @param ImageMedium $medium
* @param int $from
* @param int $to
* @return Medium
* @return Medium|array
*/
public static function scaledFromMedium($medium, $from, $to)
{

View File

@@ -123,8 +123,8 @@ class ThumbnailImageMedium extends ImageMedium
{
if (!$testLinked || $this->linked) {
return $this->parent ? call_user_func_array(array($this->parent, $method), $arguments) : $this;
} else {
return call_user_func_array(array($this, 'parent::' . $method), $arguments);
}
return call_user_func_array(array($this, 'parent::' . $method), $arguments);
}
}

View File

@@ -38,14 +38,12 @@ class VideoMedium extends Medium
*/
public function controls($display = true)
{
if($display)
{
if($display) {
$this->attributes['controls'] = true;
}
else
{
} else {
unset($this->attributes['controls']);
}
return $this;
}
@@ -58,6 +56,7 @@ class VideoMedium extends Medium
public function poster($urlImage)
{
$this->attributes['poster'] = $urlImage;
return $this;
}
@@ -69,14 +68,12 @@ class VideoMedium extends Medium
*/
public function loop($status = false)
{
if($status)
{
if($status) {
$this->attributes['loop'] = true;
}
else
{
} else {
unset($this->attributes['loop']);
}
return $this;
}
@@ -88,14 +85,12 @@ class VideoMedium extends Medium
*/
public function autoplay($status = false)
{
if($status)
{
if($status) {
$this->attributes['autoplay'] = true;
}
else
{
} else {
unset($this->attributes['autoplay']);
}
return $this;
}
@@ -109,6 +104,7 @@ class VideoMedium extends Medium
parent::reset();
$this->attributes['controls'] = true;
return $this;
}
}

View File

@@ -38,6 +38,7 @@ class TwigNodeScript extends \Twig_Node implements \Twig_NodeOutputInterface
* Compiles the node to PHP.
*
* @param \Twig_Compiler $compiler A Twig_Compiler instance
* @throws \LogicException
*/
public function compile(\Twig_Compiler $compiler)
{

View File

@@ -35,6 +35,7 @@ class TwigNodeStyle extends \Twig_Node implements \Twig_NodeOutputInterface
* Compiles the node to PHP.
*
* @param \Twig_Compiler $compiler A Twig_Compiler instance
* @throws \LogicException
*/
public function compile(\Twig_Compiler $compiler)
{