🎨 Fix spacing and code formatting

This commit is contained in:
Flavio Copes
2016-01-28 11:34:33 +01:00
parent 2fb22d813f
commit 2d49054a95
15 changed files with 355 additions and 249 deletions

View File

@@ -110,6 +110,7 @@ class Browser
public function getVersion()
{
$version = explode('.', $this->getLongVersion());
return intval($version[0]);
}

View File

@@ -16,7 +16,7 @@ use Grav\Common\Filesystem\Folder;
* MemCacheD
* FileSystem
*
* @author RocketTheme
* @author RocketTheme
* @license MIT
*/
class Cache extends Getters
@@ -91,6 +91,7 @@ class Cache extends Getters
* Initialization that sets a base key and the driver based on configuration settings
*
* @param Grav $grav
*
* @return void
*/
public function init(Grav $grav)
@@ -106,10 +107,11 @@ class Cache extends Getters
$prefix = $this->config->get('system.cache.prefix');
$this->enabled = (bool) $this->config->get('system.cache.enabled');
$this->enabled = (bool)$this->config->get('system.cache.enabled');
// Cache key allows us to invalidate all cache on configuration changes.
$this->key = ($prefix ? $prefix : 'g') . '-' . substr(md5($uri->rootUrl(true) . $this->config->key() . GRAV_VERSION), 2, 8);
$this->key = ($prefix ? $prefix : 'g') . '-' . substr(md5($uri->rootUrl(true) . $this->config->key() . GRAV_VERSION),
2, 8);
$this->driver_setting = $this->config->get('system.cache.driver');
@@ -170,16 +172,16 @@ class Cache extends Getters
case 'memcache':
$memcache = new \Memcache();
$memcache->connect($this->config->get('system.cache.memcache.server','localhost'),
$this->config->get('system.cache.memcache.port', 11211));
$memcache->connect($this->config->get('system.cache.memcache.server', 'localhost'),
$this->config->get('system.cache.memcache.port', 11211));
$driver = new DoctrineCache\MemcacheCache();
$driver->setMemcache($memcache);
break;
case 'redis':
$redis = new \Redis();
$redis->connect($this->config->get('system.cache.redis.server','localhost'),
$this->config->get('system.cache.redis.port', 6379));
$redis->connect($this->config->get('system.cache.redis.server', 'localhost'),
$this->config->get('system.cache.redis.port', 6379));
$driver = new DoctrineCache\RedisCache();
$driver->setRedis($redis);
@@ -197,6 +199,7 @@ class Cache extends Getters
* Gets a cached entry if it exists based on an id. If it does not exist, it returns false
*
* @param string $id the id of the cached entry
*
* @return object returns the cached entry, can be any type, or false if doesn't exist
*/
public function fetch($id)
@@ -211,9 +214,9 @@ class Cache extends Getters
/**
* Stores a new cached entry.
*
* @param string $id the id of the cached entry
* @param string $id the id of the cached entry
* @param array|object $data the data for the cached entry to store
* @param int $lifetime the lifetime to store the entry in seconds
* @param int $lifetime the lifetime to store the entry in seconds
*/
public function save($id, $data, $lifetime = null)
{
@@ -236,7 +239,7 @@ class Cache extends Getters
/**
* Helper method to clear all Grav caches
*
* @param string $remove standard|all|assets-only|images-only|cache-only
* @param string $remove standard|all|assets-only|images-only|cache-only
*
* @return array
*/
@@ -246,7 +249,7 @@ class Cache extends Getters
$output = [];
$user_config = USER_DIR . 'config/system.yaml';
switch($remove) {
switch ($remove) {
case 'all':
$remove_paths = self::$all_remove;
break;
@@ -269,8 +272,9 @@ class Cache extends Getters
// Convert stream to a real path
$path = $locator->findResource($stream, true, true);
// Make sure path exists before proceeding, otherwise we would wipe ROOT_DIR
if (!$path)
if (!$path) {
throw new \RuntimeException("Stream '{$stream}' not found", 500);
}
$anything = false;
$files = glob($path . '/*');

View File

@@ -12,7 +12,7 @@ use Grav\Common\Config\Config;
*/
class Debugger
{
/** @var Grav $grav*/
/** @var Grav $grav */
protected $grav;
/** @var Config $config */
@@ -52,6 +52,7 @@ class Debugger
$this->debugbar->addCollector(new ConfigCollector((array)$this->config->get('system'), 'Config'));
$this->debugbar->addCollector(new ConfigCollector((array)$this->config->get('plugins'), 'Plugins'));
}
return $this;
}
@@ -59,6 +60,7 @@ class Debugger
* Set/get the enabled state of the debugger
*
* @param bool $state If null, the method returns the enabled value. If set, the method sets the enabled state
*
* @return null
*/
public function enabled($state = null)
@@ -70,6 +72,7 @@ class Debugger
$this->enabled = $this->config->get('system.debugger.enabled');
}
}
return $this->enabled;
}
@@ -102,6 +105,7 @@ class Debugger
$assets->addJs($js);
}
}
return $this;
}
@@ -109,12 +113,14 @@ class Debugger
* Adds a data collector
*
* @param $collector
*
* @return $this
* @throws \DebugBar\DebugBarException
*/
public function addCollector($collector)
{
$this->debugbar->addCollector($collector);
return $this;
}
@@ -122,6 +128,7 @@ class Debugger
* Returns a data collector
*
* @param $collector
*
* @return \DebugBar\DataCollector\DataCollectorInterface
* @throws \DebugBar\DebugBarException
*/
@@ -140,6 +147,7 @@ class Debugger
if ($this->enabled()) {
echo $this->renderer->render();
}
return $this;
}
@@ -151,13 +159,14 @@ class Debugger
public function sendDataInHeaders()
{
$this->debugbar->sendDataInHeaders();
return $this;
}
/**
* Start a timer with an associated name and description
*
* @param $name
* @param $name
* @param string|null $description
*
* @return $this
@@ -168,6 +177,7 @@ class Debugger
$this->debugbar['time']->startMeasure($name, $description);
$this->timers[] = $name;
}
return $this;
}
@@ -175,6 +185,7 @@ class Debugger
* Stop the named timer
*
* @param string $name
*
* @return $this
*/
public function stopTimer($name)
@@ -189,9 +200,9 @@ class Debugger
/**
* Dump variables into the Messages tab of the Debug Bar
*
* @param $message
* @param $message
* @param string $label
* @param bool $isString
* @param bool $isString
*
* @return $this
*/
@@ -200,6 +211,7 @@ class Debugger
if ($this->enabled()) {
$this->debugbar['messages']->addMessage($message, $label, $isString);
}
return $this;
}
}

View File

@@ -5,7 +5,7 @@ namespace Grav\Common;
* Abstract class to implement magic __get(), __set(), __isset() and __unset().
* Also implements ArrayAccess.
*
* @author RocketTheme
* @author RocketTheme
* @license MIT
*/
abstract class Getters implements \ArrayAccess, \Countable
@@ -32,6 +32,7 @@ abstract class Getters implements \ArrayAccess, \Countable
* Magic getter method
*
* @param mixed $offset Medium name value
*
* @return mixed Medium value
*/
public function __get($offset)
@@ -42,7 +43,8 @@ abstract class Getters implements \ArrayAccess, \Countable
/**
* Magic method to determine if the attribute is set
*
* @param mixed $offset Medium name value
* @param mixed $offset Medium name value
*
* @return boolean True if the value is set
*/
public function __isset($offset)
@@ -62,12 +64,14 @@ abstract class Getters implements \ArrayAccess, \Countable
/**
* @param mixed $offset
*
* @return bool
*/
public function offsetExists($offset)
{
if ($this->gettersVariable) {
$var = $this->gettersVariable;
return isset($this->{$var}[$offset]);
} else {
return isset($this->{$offset});
@@ -76,12 +80,14 @@ abstract class Getters implements \ArrayAccess, \Countable
/**
* @param mixed $offset
*
* @return mixed
*/
public function offsetGet($offset)
{
if ($this->gettersVariable) {
$var = $this->gettersVariable;
return isset($this->{$var}[$offset]) ? $this->{$var}[$offset] : null;
} else {
return isset($this->{$offset}) ? $this->{$offset} : null;
@@ -137,13 +143,17 @@ abstract class Getters implements \ArrayAccess, \Countable
{
if ($this->gettersVariable) {
$var = $this->gettersVariable;
return $this->{$var};
} else {
$properties = (array) $this;
$properties = (array)$this;
$list = [];
foreach ($properties as $property => $value) {
if ($property[0] != "\0") $list[$property] = $value;
if ($property[0] != "\0") {
$list[$property] = $value;
}
}
return $list;
}
}

View File

@@ -21,6 +21,7 @@ trait GravTrait
if (!self::$grav) {
self::$grav = Grav::instance();
}
return self::$grav;
}

View File

@@ -6,17 +6,17 @@ namespace Grav\Common;
*/
/**
* Inflector for pluralize and singularize English nouns.
*
* This Inflector is a port of Ruby on Rails Inflector.
*
* It can be really helpful for developers that want to
* create frameworks based on naming conventions rather than
* configurations.
*
* @author RocketTheme
* @license MIT
*/
* Inflector for pluralize and singularize English nouns.
*
* This Inflector is a port of Ruby on Rails Inflector.
*
* It can be really helpful for developers that want to
* create frameworks based on naming conventions rather than
* configurations.
*
* @author RocketTheme
* @license MIT
*/
class Inflector
{
@@ -43,7 +43,7 @@ class Inflector
/**
* Pluralizes English nouns.
*
* @param string $word English noun to pluralize
* @param string $word English noun to pluralize
* @param int $count The count
*
* @return string Plural noun
@@ -59,14 +59,14 @@ class Inflector
$lowercased_word = strtolower($word);
foreach ($this->uncountable as $_uncountable) {
if (substr($lowercased_word, (-1*strlen($_uncountable))) == $_uncountable) {
if (substr($lowercased_word, (-1 * strlen($_uncountable))) == $_uncountable) {
return $word;
}
}
foreach ($this->irregular as $_plural => $_singular) {
if (preg_match('/('.$_plural.')$/i', $word, $arr)) {
return preg_replace('/('.$_plural.')$/i', substr($arr[0], 0, 1).substr($_singular, 1), $word);
if (preg_match('/(' . $_plural . ')$/i', $word, $arr)) {
return preg_replace('/(' . $_plural . ')$/i', substr($arr[0], 0, 1) . substr($_singular, 1), $word);
}
}
@@ -75,17 +75,19 @@ class Inflector
return preg_replace($rule, $replacement, $word);
}
}
return false;
}
/**
* Singularizes English nouns.
*
* @param string $word English noun to singularize
* @param int $count
* @return string Singular noun.
*/
* Singularizes English nouns.
*
* @param string $word English noun to singularize
* @param int $count
*
* @return string Singular noun.
*/
public function singularize($word, $count = 1)
{
$this->init();
@@ -96,14 +98,14 @@ class Inflector
$lowercased_word = strtolower($word);
foreach ($this->uncountable as $_uncountable) {
if (substr($lowercased_word, (-1*strlen($_uncountable))) == $_uncountable) {
if (substr($lowercased_word, (-1 * strlen($_uncountable))) == $_uncountable) {
return $word;
}
}
foreach ($this->irregular as $_plural => $_singular) {
if (preg_match('/('.$_singular.')$/i', $word, $arr)) {
return preg_replace('/('.$_singular.')$/i', substr($arr[0], 0, 1).substr($_plural, 1), $word);
if (preg_match('/(' . $_singular . ')$/i', $word, $arr)) {
return preg_replace('/(' . $_singular . ')$/i', substr($arr[0], 0, 1) . substr($_plural, 1), $word);
}
}
@@ -117,176 +119,194 @@ class Inflector
}
/**
* Converts an underscored or CamelCase word into a English
* sentence.
*
* The titleize public function converts text like "WelcomePage",
* "welcome_page" or "welcome page" to this "Welcome
* Page".
* If second parameter is set to 'first' it will only
* capitalize the first character of the title.
*
* @param string $word Word to format as tile
* @param string $uppercase If set to 'first' it will only uppercase the
* first character. Otherwise it will uppercase all
* the words in the title.
* @return string Text formatted as title
*/
* Converts an underscored or CamelCase word into a English
* sentence.
*
* The titleize public function converts text like "WelcomePage",
* "welcome_page" or "welcome page" to this "Welcome
* Page".
* If second parameter is set to 'first' it will only
* capitalize the first character of the title.
*
* @param string $word Word to format as tile
* @param string $uppercase If set to 'first' it will only uppercase the
* first character. Otherwise it will uppercase all
* the words in the title.
*
* @return string Text formatted as title
*/
public function titleize($word, $uppercase = '')
{
$uppercase = $uppercase == 'first' ? 'ucfirst' : 'ucwords';
return $uppercase($this->humanize($this->underscorize($word)));
}
/**
* Returns given word as CamelCased
*
* Converts a word like "send_email" to "SendEmail". It
* will remove non alphanumeric character from the word, so
* "who's online" will be converted to "WhoSOnline"
*
* @see variablize
* @param string $word Word to convert to camel case
* @return string UpperCamelCasedWord
*/
* Returns given word as CamelCased
*
* Converts a word like "send_email" to "SendEmail". It
* will remove non alphanumeric character from the word, so
* "who's online" will be converted to "WhoSOnline"
*
* @see variablize
*
* @param string $word Word to convert to camel case
*
* @return string UpperCamelCasedWord
*/
public function camelize($word)
{
return str_replace(' ', '', ucwords(preg_replace('/[^A-Z^a-z^0-9]+/', ' ', $word)));
}
/**
* Converts a word "into_it_s_underscored_version"
*
* Convert any "CamelCased" or "ordinary Word" into an
* "underscored_word".
*
* This can be really useful for creating friendly URLs.
*
* @param string $word Word to underscore
* @return string Underscored word
*/
* Converts a word "into_it_s_underscored_version"
*
* Convert any "CamelCased" or "ordinary Word" into an
* "underscored_word".
*
* This can be really useful for creating friendly URLs.
*
* @param string $word Word to underscore
*
* @return string Underscored word
*/
public function underscorize($word)
{
$regex1 = preg_replace('/([A-Z]+)([A-Z][a-z])/', '\1_\2', $word);
$regex2 = preg_replace('/([a-zd])([A-Z])/', '\1_\2', $regex1);
$regex3 = preg_replace('/[^A-Z^a-z^0-9]+/', '_', $regex2);
return strtolower($regex3);
return strtolower($regex3);
}
/**
* Converts a word "into-it-s-hyphenated-version"
*
* Convert any "CamelCased" or "ordinary Word" into an
* "hyphenated-word".
*
* This can be really useful for creating friendly URLs.
*
* @param string $word Word to hyphenate
* @return string hyphenized word
*/
* Converts a word "into-it-s-hyphenated-version"
*
* Convert any "CamelCased" or "ordinary Word" into an
* "hyphenated-word".
*
* This can be really useful for creating friendly URLs.
*
* @param string $word Word to hyphenate
*
* @return string hyphenized word
*/
public function hyphenize($word)
{
$regex1 = preg_replace('/([A-Z]+)([A-Z][a-z])/', '\1-\2', $word);
$regex2 = preg_replace('/([a-zd])([A-Z])/', '\1-\2', $regex1);
$regex3 = preg_replace('/[^A-Z^a-z^0-9]+/', '-', $regex2);
return strtolower($regex3);
return strtolower($regex3);
}
/**
* Returns a human-readable string from $word
*
* Returns a human-readable string from $word, by replacing
* underscores with a space, and by upper-casing the initial
* character by default.
*
* If you need to uppercase all the words you just have to
* pass 'all' as a second parameter.
*
* @param string $word String to "humanize"
* @param string $uppercase If set to 'all' it will uppercase all the words
* instead of just the first one.
* @return string Human-readable word
*/
* Returns a human-readable string from $word
*
* Returns a human-readable string from $word, by replacing
* underscores with a space, and by upper-casing the initial
* character by default.
*
* If you need to uppercase all the words you just have to
* pass 'all' as a second parameter.
*
* @param string $word String to "humanize"
* @param string $uppercase If set to 'all' it will uppercase all the words
* instead of just the first one.
*
* @return string Human-readable word
*/
public function humanize($word, $uppercase = '')
{
$uppercase = $uppercase == 'all' ? 'ucwords' : 'ucfirst';
return $uppercase(str_replace('_', ' ', preg_replace('/_id$/', '', $word)));
}
/**
* Same as camelize but first char is underscored
*
* Converts a word like "send_email" to "sendEmail". It
* will remove non alphanumeric character from the word, so
* "who's online" will be converted to "whoSOnline"
*
* @see camelize
* @param string $word Word to lowerCamelCase
* @return string Returns a lowerCamelCasedWord
*/
* Same as camelize but first char is underscored
*
* Converts a word like "send_email" to "sendEmail". It
* will remove non alphanumeric character from the word, so
* "who's online" will be converted to "whoSOnline"
*
* @see camelize
*
* @param string $word Word to lowerCamelCase
*
* @return string Returns a lowerCamelCasedWord
*/
public function variablize($word)
{
$word = $this->camelize($word);
return strtolower($word[0]).substr($word, 1);
return strtolower($word[0]) . substr($word, 1);
}
/**
* Converts a class name to its table name according to rails
* naming conventions.
*
* Converts "Person" to "people"
*
* @see classify
* @param string $class_name Class name for getting related table_name.
* @return string plural_table_name
*/
* Converts a class name to its table name according to rails
* naming conventions.
*
* Converts "Person" to "people"
*
* @see classify
*
* @param string $class_name Class name for getting related table_name.
*
* @return string plural_table_name
*/
public function tableize($class_name)
{
return $this->pluralize($this->underscorize($class_name));
}
/**
* Converts a table name to its class name according to rails
* naming conventions.
*
* Converts "people" to "Person"
*
* @see tableize
* @param string $table_name Table name for getting related ClassName.
* @return string SingularClassName
*/
* Converts a table name to its class name according to rails
* naming conventions.
*
* Converts "people" to "Person"
*
* @see tableize
*
* @param string $table_name Table name for getting related ClassName.
*
* @return string SingularClassName
*/
public function classify($table_name)
{
return $this->camelize($this->singularize($table_name));
}
/**
* Converts number to its ordinal English form.
*
* This method converts 13 to 13th, 2 to 2nd ...
*
* @param integer $number Number to get its ordinal value
* @return string Ordinal representation of given string.
*/
* Converts number to its ordinal English form.
*
* This method converts 13 to 13th, 2 to 2nd ...
*
* @param integer $number Number to get its ordinal value
*
* @return string Ordinal representation of given string.
*/
public function ordinalize($number)
{
$this->init();
if (in_array(($number % 100), range(11, 13))) {
return $number.$this->ordinals['default'];
return $number . $this->ordinals['default'];
} else {
switch (($number % 10)) {
case 1:
return $number.$this->ordinals['first'];
return $number . $this->ordinals['first'];
break;
case 2:
return $number.$this->ordinals['second'];
return $number . $this->ordinals['second'];
break;
case 3:
return $number.$this->ordinals['third'];
return $number . $this->ordinals['third'];
break;
default:
return $number.$this->ordinals['default'];
return $number . $this->ordinals['default'];
break;
}
}
@@ -296,6 +316,7 @@ class Inflector
* Converts a number of days to a number of months
*
* @param int $days
*
* @return int
*/
public function monthize($days)
@@ -309,7 +330,7 @@ class Inflector
// handle years
if ($diff->y > 0) {
$diff->m = $diff->m + 12*$diff->y;
$diff->m = $diff->m + 12 * $diff->y;
}
return $diff->m;

View File

@@ -26,6 +26,7 @@ class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable
*
* @param string $key
* @param mixed $args
*
* @return mixed
*/
public function __call($key, $args)
@@ -79,11 +80,13 @@ class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable
* Return nth item.
*
* @param int $key
*
* @return mixed|bool
*/
public function nth($key)
{
$items = array_keys($this->items);
return (isset($items[$key])) ? $this->offsetGet($items[$key]) : false;
}
@@ -95,6 +98,7 @@ class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable
public function first()
{
$items = array_keys($this->items);
return $this->offsetGet(array_shift($items));
}
@@ -106,6 +110,7 @@ class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable
public function last()
{
$items = array_keys($this->items);
return $this->offsetGet(array_pop($items));
}
@@ -117,11 +122,13 @@ class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable
public function reverse()
{
$this->items = array_reverse($this->items);
return $this;
}
/**
* @param mixed $needle Searched value.
*
* @return string|bool Key if found, otherwise false.
*/
public function indexOf($needle)
@@ -131,6 +138,7 @@ class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable
return $key;
}
}
return false;
}
@@ -159,6 +167,7 @@ class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable
*
* @param int $offset
* @param int $length
*
* @return $this
*/
public function slice($offset, $length = null)
@@ -171,12 +180,13 @@ class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable
/**
* Pick one or more random entries.
*
* @param int $num Specifies how many entries should be picked.
* @param int $num Specifies how many entries should be picked.
*
* @return $this
*/
public function random($num = 1)
{
$this->items = array_intersect_key($this->items, array_flip((array) array_rand($this->items, $num)));
$this->items = array_intersect_key($this->items, array_flip((array)array_rand($this->items, $num)));
return $this;
}
@@ -184,7 +194,8 @@ class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable
/**
* Append new elements to the list.
*
* @param array|Iterator $items Items to be appended. Existing keys will be overridden with the new values.
* @param array|Iterator $items Items to be appended. Existing keys will be overridden with the new values.
*
* @return $this
*/
public function append($items)
@@ -192,14 +203,17 @@ class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable
if ($items instanceof static) {
$items = $items->toArray();
}
$this->items = array_merge($this->items, (array) $items);
$this->items = array_merge($this->items, (array)$items);
return $this;
}
/**
* Filter elements from the list
* @param callable|null $callback A function the receives ($value, $key) and must return a boolean to indicate filter status
*
* @param callable|null $callback A function the receives ($value, $key) and must return a boolean to indicate
* filter status
*
* @return $this
*/
public function filter(callable $callback = null)
@@ -207,7 +221,7 @@ class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable
foreach ($this->items as $key => $value) {
if (
($callback && !call_user_func($callback, $value, $key)) ||
(!$callback && !(bool) $value)
(!$callback && !(bool)$value)
) {
unset($this->items[$key]);
}
@@ -230,7 +244,9 @@ class Iterator implements \ArrayAccess, \Iterator, \Countable, \Serializable
*/
public function sort(callable $callback = null, $desc = false)
{
if (!$callback || !is_callable($callback)) { return $this; }
if (!$callback || !is_callable($callback)) {
return $this;
}
$items = $this->items;
uasort($items, $callback);

View File

@@ -11,7 +11,7 @@ use RocketTheme\Toolbox\File\YamlFile;
/**
* The Plugin object just holds the id and path to a plugin.
*
* @author RocketTheme
* @author RocketTheme
* @license MIT
*/
class Plugin implements EventSubscriberInterface
@@ -54,9 +54,9 @@ class Plugin implements EventSubscriberInterface
/**
* Constructor.
*
* @param string $name
* @param Grav $grav
* @param Config $config
* @param string $name
* @param Grav $grav
* @param Config $config
*/
public function __construct($name, Grav $grav, Config $config)
{
@@ -70,6 +70,7 @@ class Plugin implements EventSubscriberInterface
if (isset($this->grav['admin'])) {
return true;
}
return false;
}
@@ -122,15 +123,16 @@ class Plugin implements EventSubscriberInterface
*
* format: [plugin:myplugin_name](function_data)
*
* @param string $content The string to perform operations upon
* @param callable $function The anonymous callback function
* @param string $internal_regex Optional internal regex to extra data from
* @param string $content The string to perform operations upon
* @param callable $function The anonymous callback function
* @param string $internal_regex Optional internal regex to extra data from
*
* @return string
*/
protected function parseLinks($content, $function, $internal_regex = '(.*)')
{
$regex = '/\[plugin:(?:'.$this->name.')\]\('.$internal_regex.'\)/i';
$regex = '/\[plugin:(?:' . $this->name . ')\]\(' . $internal_regex . '\)/i';
return preg_replace_callback($regex, $function, $content);
}
@@ -149,7 +151,7 @@ class Plugin implements EventSubscriberInterface
{
$class_name = $this->name;
$class_name_merged = $class_name . '.merged';
$defaults = $this->config->get('plugins.'. $class_name, []);
$defaults = $this->config->get('plugins.' . $class_name, []);
$page_header = $page->header();
$header = [];
if (!isset($page_header->$class_name_merged) && isset($page_header->$class_name)) {
@@ -180,6 +182,7 @@ class Plugin implements EventSubscriberInterface
} else {
$header = array_merge($header, $params);
}
// Return configurations as a new data config class
return new Data($header);
}
@@ -187,11 +190,12 @@ class Plugin implements EventSubscriberInterface
/**
* Persists to disk the plugin parameters currently stored in the Grav Config object
*
* @param string $plugin_name The name of the plugin whose config it should store.
* @param string $plugin_name The name of the plugin whose config it should store.
*
* @return true
*/
public static function saveConfig($plugin_name) {
public static function saveConfig($plugin_name)
{
if (!$plugin_name) {
return false;
}

View File

@@ -12,7 +12,7 @@ use RocketTheme\Toolbox\Event\EventSubscriberInterface;
* The Plugins object holds an array of all the plugin objects that
* Grav knows about
*
* @author RocketTheme
* @author RocketTheme
* @license MIT
*/
class Plugins extends Iterator
@@ -29,7 +29,7 @@ class Plugins extends Iterator
{
/** @var Config $config */
$config = self::getGrav()['config'];
$plugins = (array) $config->get('plugins');
$plugins = (array)$config->get('plugins');
$inflector = self::getGrav()['inflector'];
@@ -52,8 +52,8 @@ class Plugins extends Iterator
require_once $filePath;
$pluginClassFormat = [
'Grav\\Plugin\\'.ucfirst($plugin).'Plugin',
'Grav\\Plugin\\'.$inflector->camelize($plugin).'Plugin'
'Grav\\Plugin\\' . ucfirst($plugin) . 'Plugin',
'Grav\\Plugin\\' . $inflector->camelize($plugin) . 'Plugin'
];
$pluginClassName = false;
@@ -65,7 +65,8 @@ class Plugins extends Iterator
}
if (false === $pluginClassName) {
throw new \RuntimeException(sprintf("Plugin '%s' class not found! Try reinstalling this plugin.", $plugin));
throw new \RuntimeException(sprintf("Plugin '%s' class not found! Try reinstalling this plugin.",
$plugin));
}
$instance = new $pluginClassName($plugin, self::getGrav(), $config);
@@ -99,7 +100,7 @@ class Plugins extends Iterator
$list = [];
$locator = Grav::instance()['locator'];
$plugins = (array) $locator->findResources('plugins://', false);
$plugins = (array)$locator->findResources('plugins://', false);
foreach ($plugins as $path) {
$iterator = new \DirectoryIterator($path);
@@ -126,6 +127,7 @@ class Plugins extends Iterator
* Get a plugin by name
*
* @param string $name
*
* @return Data|null
*/
public static function get($name)

View File

@@ -19,6 +19,9 @@ class Session extends \RocketTheme\Toolbox\Session\Session
$this->grav = $grav;
}
/**
* Session init
*/
public function init()
{
/** @var Uri $uri */
@@ -42,10 +45,7 @@ class Session extends \RocketTheme\Toolbox\Session\Session
if ($config->get('system.session.enabled') || $is_admin) {
// Define session service.
parent::__construct(
$session_timeout,
$session_path
);
parent::__construct($session_timeout, $session_path);
$domain = $uri->host();
if ($domain == 'localhost') {

View File

@@ -22,7 +22,7 @@ use Grav\Common\Page\Page;
* [tag][grav][path/to/item2]
* [tag][dog][path/to/item3]
*
* @author RocketTheme
* @author RocketTheme
* @license MIT
*/
class Taxonomy
@@ -45,7 +45,7 @@ class Taxonomy
* Takes an individual page and processes the taxonomies configured in its header. It
* then adds those taxonomies to the map
*
* @param Page $page the page to process
* @param Page $page the page to process
* @param array $page_taxonomy
*/
public function addTaxonomy(Page $page, $page_taxonomy = null)
@@ -61,10 +61,10 @@ class Taxonomy
/** @var Config $config */
$config = $this->grav['config'];
if ($config->get('site.taxonomies')) {
foreach ((array) $config->get('site.taxonomies') as $taxonomy) {
foreach ((array)$config->get('site.taxonomies') as $taxonomy) {
if (isset($page_taxonomy[$taxonomy])) {
foreach ((array) $page_taxonomy[$taxonomy] as $item) {
$this->taxonomy_map[$taxonomy][(string) $item][$page->path()] = ['slug' => $page->slug()];
foreach ((array)$page_taxonomy[$taxonomy] as $item) {
$this->taxonomy_map[$taxonomy][(string)$item][$page->path()] = ['slug' => $page->slug()];
}
}
}
@@ -75,8 +75,9 @@ class Taxonomy
* Returns a new Page object with the sub-pages containing all the values set for a
* particular taxonomy.
*
* @param array $taxonomies taxonomies to search, eg ['tag'=>['animal','cat']]
* @param string $operator can be 'or' or 'and' (defaults to 'or')
* @param array $taxonomies taxonomies to search, eg ['tag'=>['animal','cat']]
* @param string $operator can be 'or' or 'and' (defaults to 'or')
*
* @return Collection Collection object set to contain matches found in the taxonomy map
*/
public function findTaxonomy($taxonomies, $operator = 'and')
@@ -85,7 +86,7 @@ class Taxonomy
$results = [];
foreach ((array)$taxonomies as $taxonomy => $items) {
foreach ((array) $items as $item) {
foreach ((array)$items as $item) {
if (isset($this->taxonomy_map[$taxonomy][$item])) {
$matches[] = $this->taxonomy_map[$taxonomy][$item];
}
@@ -110,6 +111,7 @@ class Taxonomy
* Gets and Sets the taxonomy map
*
* @param array $var the taxonomy map
*
* @return array the taxonomy map
*/
public function taxonomy($var = null)
@@ -117,6 +119,7 @@ class Taxonomy
if ($var) {
$this->taxonomy_map = $var;
}
return $this->taxonomy_map;
}
}

View File

@@ -15,7 +15,7 @@ class Theme extends Plugin
/**
* Constructor.
*
* @param Grav $grav
* @param Grav $grav
* @param Config $config
* @param string $name
*/
@@ -29,11 +29,12 @@ class Theme extends Plugin
/**
* Persists to disk the theme parameters currently stored in the Grav Config object
*
* @param string $theme_name The name of the theme whose config it should store.
* @param string $theme_name The name of the theme whose config it should store.
*
* @return true
*/
public static function saveConfig($theme_name) {
public static function saveConfig($theme_name)
{
if (!$theme_name) {
return false;
}

View File

@@ -12,7 +12,7 @@ use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
/**
* The Themes object holds an array of all the theme objects that Grav knows about.
*
* @author RocketTheme
* @author RocketTheme
* @license MIT
*/
class Themes extends Iterator
@@ -56,7 +56,7 @@ class Themes extends Iterator
try {
$instance = $themes->load();
} catch (\InvalidArgumentException $e) {
throw new \RuntimeException($this->current(). ' theme could not be found');
throw new \RuntimeException($this->current() . ' theme could not be found');
}
if ($instance instanceof EventSubscriberInterface) {
@@ -81,7 +81,7 @@ class Themes extends Iterator
$list = [];
$locator = Grav::instance()['locator'];
$themes = (array) $locator->findResources('themes://', false);
$themes = (array)$locator->findResources('themes://', false);
foreach ($themes as $path) {
$iterator = new \DirectoryIterator($path);
@@ -107,7 +107,8 @@ class Themes extends Iterator
/**
* Get theme configuration or throw exception if it cannot be found.
*
* @param string $name
* @param string $name
*
* @return Data
* @throws \RuntimeException
*/
@@ -156,7 +157,7 @@ class Themes extends Iterator
*/
public function current()
{
return (string) $this->config->get('system.pages.theme');
return (string)$this->config->get('system.pages.theme');
}
/**
@@ -183,8 +184,8 @@ class Themes extends Iterator
if (!is_object($class)) {
$themeClassFormat = [
'Grav\\Theme\\'.ucfirst($name),
'Grav\\Theme\\'.$inflector->camelize($name)
'Grav\\Theme\\' . ucfirst($name),
'Grav\\Theme\\' . $inflector->camelize($name)
];
foreach ($themeClassFormat as $themeClass) {
@@ -259,8 +260,8 @@ class Themes extends Iterator
/**
* Load theme configuration.
*
* @param string $name Theme name
* @param Config $config Configuration class
* @param string $name Theme name
* @param Config $config Configuration class
*/
protected function loadConfiguration($name, Config $config)
{
@@ -271,7 +272,7 @@ class Themes extends Iterator
/**
* Load theme languages.
*
* @param Config $config Configuration class
* @param Config $config Configuration class
*/
protected function loadLanguages(Config $config)
{
@@ -317,7 +318,7 @@ class Themes extends Iterator
// Load class
if (file_exists($file)) {
return include_once($file);
return include_once($file);
}
}

View File

@@ -6,7 +6,7 @@ use Grav\Common\Page\Page;
/**
* The URI object provides information about the current URL
*
* @author RocketTheme
* @author RocketTheme
* @license MIT
*/
class Uri
@@ -87,6 +87,7 @@ class Uri
private function buildPort()
{
$port = isset($_SERVER['SERVER_PORT']) ? (string)$_SERVER['SERVER_PORT'] : '80';
return $port;
}
@@ -98,6 +99,7 @@ class Uri
private function buildUri()
{
$uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
return $uri;
}
@@ -168,7 +170,9 @@ class Uri
*/
public function initializeWithUrl($url = '')
{
if (!$url) return $this;
if (!$url) {
return $this;
}
$this->paths = [];
$this->params = [];
@@ -206,6 +210,7 @@ class Uri
*
* @param string $url
* @param string $root_path
*
* @return $this
*/
public function initializeWithUrlAndRootPath($url, $root_path)
@@ -229,7 +234,7 @@ class Uri
// add the port to the base for non-standard ports
if ($config->get('system.reverse_proxy_setup') == false && $this->port != '80' && $this->port != '443') {
$this->base .= ":".$this->port;
$this->base .= ":" . $this->port;
}
// Set some defaults
@@ -284,8 +289,8 @@ class Uri
$valid_page_types = implode('|', $config->get('system.pages.types'));
// Strip the file extension for valid page types
if (preg_match("/\.(".$valid_page_types.")$/", $parts['basename'])) {
$uri = rtrim(str_replace(DIRECTORY_SEPARATOR, DS, $parts['dirname']), DS). '/' .$parts['filename'];
if (preg_match("/\.(" . $valid_page_types . ")$/", $parts['basename'])) {
$uri = rtrim(str_replace(DIRECTORY_SEPARATOR, DS, $parts['dirname']), DS) . '/' . $parts['filename'];
}
// set the new url
@@ -323,13 +328,15 @@ class Uri
}
$uri = '/' . ltrim(implode('/', $path), '/');
}
return $uri;
}
/**
* Return URI path.
*
* @param string $id
* @param string $id
*
* @return string
*/
public function paths($id = null)
@@ -344,8 +351,9 @@ class Uri
/**
* Return route to the current URI. By default route doesn't include base path.
*
* @param bool $absolute True to include full path.
* @param bool $domain True to include domain. Works only if first parameter is also true.
* @param bool $absolute True to include full path.
* @param bool $domain True to include domain. Works only if first parameter is also true.
*
* @return string
*/
public function route($absolute = false, $domain = false)
@@ -372,6 +380,7 @@ class Uri
if (!$this->query) {
return '';
}
return http_build_query($this->query);
}
}
@@ -380,8 +389,9 @@ class Uri
/**
* Return all or a single query parameter as a URI compatible string.
*
* @param string $id Optional parameter name.
* @param string $id Optional parameter name.
* @param boolean $array return the array format or not
*
* @return null|string
*/
public function params($id = null, $array = false)
@@ -396,13 +406,13 @@ class Uri
$output = [];
foreach ($this->params as $key => $value) {
$output[] = $key . $config->get('system.param_sep') . $value;
$params = '/'.implode('/', $output);
$params = '/' . implode('/', $output);
}
} elseif (isset($this->params[$id])) {
if ($array) {
return $this->params[$id];
}
$params = "/{$id}". $config->get('system.param_sep') . $this->params[$id];
$params = "/{$id}" . $config->get('system.param_sep') . $this->params[$id];
}
return $params;
@@ -411,7 +421,8 @@ class Uri
/**
* Get URI parameter.
*
* @param string $id
* @param string $id
*
* @return bool|string
*/
public function param($id)
@@ -426,7 +437,8 @@ class Uri
/**
* Return URL.
*
* @param bool $include_host Include hostname.
* @param bool $include_host Include hostname.
*
* @return string
*/
public function url($include_host = false)
@@ -435,6 +447,7 @@ class Uri
return $this->url;
} else {
$url = (str_replace($this->base, '', rtrim($this->url, '/')));
return $url ? $url : '/';
}
}
@@ -450,6 +463,7 @@ class Uri
if ($path === '') {
$path = '/';
}
return $path;
}
@@ -465,6 +479,7 @@ class Uri
if (!$this->extension) {
$this->extension = $default;
}
return $this->extension;
}
@@ -522,7 +537,8 @@ class Uri
/**
* Return root URL to the site.
*
* @param bool $include_host Include hostname.
* @param bool $include_host Include hostname.
*
* @return mixed
*/
public function rootUrl($include_host = false)
@@ -531,6 +547,7 @@ class Uri
return $this->root;
} else {
$root = str_replace($this->base, '', $this->root);
return $root;
}
}
@@ -554,6 +571,7 @@ class Uri
*
* @param string $default
* @param string $attributes
*
* @return string
*/
public function referrer($default = null, $attributes = null)
@@ -609,7 +627,8 @@ class Uri
/**
* Is this an external URL? if it starts with `http` then yes, else false
*
* @param string $url the URL in question
* @param string $url the URL in question
*
* @return boolean is eternal state
*/
public function isExternal($url)
@@ -625,6 +644,7 @@ class Uri
* The opposite of built-in PHP method parse_url()
*
* @param $parsed_url
*
* @return string
*/
public static function buildUrl($parsed_url)
@@ -638,16 +658,17 @@ class Uri
$path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
$query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
$fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
return "$scheme$user$pass$host$port$path$query$fragment";
}
/**
* Converts links from absolute '/' or relative (../..) to a Grav friendly format
*
* @param Page $page the current page to use as reference
* @param string $markdown_url the URL as it was written in the markdown
* @param string $type the type of URL, image | link
* @param null $relative if null, will use system default, if true will use relative links internally
* @param Page $page the current page to use as reference
* @param string $markdown_url the URL as it was written in the markdown
* @param string $type the type of URL, image | link
* @param null $relative if null, will use system default, if true will use relative links internally
*
* @return string the more friendly formatted url
*/
@@ -667,7 +688,7 @@ class Uri
if (is_null($relative)) {
$base = $grav['base_url'];
} else {
$base = $relative ? $grav['base_url_relative'] : $grav['base_url_absolute'];
$base = $relative ? $grav['base_url_relative'] : $grav['base_url_absolute'];
}
$base_url = rtrim($base . $grav['pages']->base(), '/') . $language_append;
@@ -732,6 +753,7 @@ class Uri
/** @var Page $target */
$target = $instances[$page_path];
$url_bits['path'] = $base_url . rtrim($target->route(), '/') . $filename;
return Uri::buildUrl($url_bits);
}
@@ -742,8 +764,8 @@ class Uri
/**
* Adds the nonce to a URL for a specific action
*
* @param string $url the url
* @param string $action the action
* @param string $url the url
* @param string $action the action
* @param string $nonceParamName the param name to use
*
* @return string the url with the nonce
@@ -751,6 +773,7 @@ class Uri
public static function addNonce($url, $action, $nonceParamName = 'nonce')
{
$urlWithNonce = $url . '/' . $nonceParamName . Grav::instance()['config']->get('system.param_sep', ':') . Utils::getNonce($action);
return $urlWithNonce;
}
}

View File

@@ -85,13 +85,15 @@ abstract class Utils
*
* @param $haystack
* @param $needle
*
* @return string
*/
public static function substrToString($haystack, $needle)
{
if (static::contains($haystack, $needle)) {
return substr($haystack, 0, strpos($haystack,$needle));
return substr($haystack, 0, strpos($haystack, $needle));
}
return $haystack;
}
@@ -128,6 +130,7 @@ abstract class Utils
if ($default_format) {
$date_formats = array_merge([$default_format => $default_format.' (e.g. '.$now->format($default_format).')'], $date_formats);
}
return $date_formats;
}
@@ -135,10 +138,11 @@ abstract class Utils
* Truncate text by number of characters but can cut off words.
*
* @param string $string
* @param int $limit Max number of characters.
* @param bool $up_to_break truncate up to breakpoint after char count
* @param string $break Break point.
* @param string $pad Appended padding to the end of the string.
* @param int $limit Max number of characters.
* @param bool $up_to_break truncate up to breakpoint after char count
* @param string $break Break point.
* @param string $pad Appended padding to the end of the string.
*
* @return string
*/
public static function truncate($string, $limit = 150, $up_to_break = false, $break = " ", $pad = "…")
@@ -163,8 +167,9 @@ abstract class Utils
/**
* Truncate text by number of characters in a "word-safe" manor.
*
* @param $string
* @param int $limit
* @param string $string
* @param int $limit
*
* @return string
*/
public static function safeTruncate($string, $limit = 150)
@@ -214,8 +219,8 @@ abstract class Utils
/**
* Provides the ability to download a file to the browser
*
* @param string $file the full path to the file to be downloaded
* @param bool $force_download as opposed to letting browser choose if to download or render
* @param string $file the full path to the file to be downloaded
* @param bool $force_download as opposed to letting browser choose if to download or render
*/
public static function download($file, $force_download = true)
{
@@ -231,7 +236,8 @@ abstract class Utils
if (!Utils::isFunctionDisabled('set_time_limit') && !ini_get('safe_mode') && function_exists('set_time_limit')) {
set_time_limit(0);
}
} catch (\Exception $e) {}
} catch (\Exception $e) {
}
ignore_user_abort(false);
@@ -328,7 +334,7 @@ abstract class Utils
}
/**
* Get the formatted timezones list
* Get the formatted timezones list
*
* @return array
*/
@@ -369,19 +375,17 @@ abstract class Utils
public static function arrayFilterRecursive(Array $source, $fn)
{
$result = [];
foreach ($source as $key => $value)
{
if (is_array($value))
{
foreach ($source as $key => $value) {
if (is_array($value)) {
$result[$key] = static::arrayFilterRecursive($value, $fn);
continue;
}
if ($fn($key, $value))
{
if ($fn($key, $value)) {
$result[$key] = $value; // KEEP
continue;
}
}
return $result;
}
@@ -397,7 +401,7 @@ abstract class Utils
if (strlen($string) <= 3) {
return false;
}
$languages_enabled = self::getGrav()['config']->get('system.languages.supported', []);
if ($string[0] == '/' && $string[3] == '/' && in_array(substr($string, 1, 2), $languages_enabled)) {
@@ -410,7 +414,8 @@ abstract class Utils
/**
* Get the timestamp of a date
*
* @param string $date a String expressed in the system.pages.dateformat.default format, with fallback to a strtotime argument
* @param string $date a String expressed in the system.pages.dateformat.default format, with fallback to a
* strtotime argument
*
* @return int the timestamp
*/
@@ -437,9 +442,9 @@ abstract class Utils
/**
* Get value of an array element using dot notation
*
* @param array $array the Array to check
* @param string $path the dot notation path to check
* @param mixed $default a value to be returned if $path is not found in $array
* @param array $array the Array to check
* @param string $path the dot notation path to check
* @param mixed $default a value to be returned if $path is not found in $array
*
* @return mixed the value found
*/
@@ -477,7 +482,7 @@ abstract class Utils
* with reverse proxy setups.
*
* @param string $action
* @param bool $plusOneTick if true, generates the token for the next tick (the next 12 hours)
* @param bool $plusOneTick if true, generates the token for the next tick (the next 12 hours)
*
* @return string the nonce string
*/
@@ -496,7 +501,7 @@ abstract class Utils
$i++;
}
return ( $i . '|' . $action . '|' . $username . '|' . $token . '|' . self::getGrav()['config']->get('security.salt'));
return ($i . '|' . $action . '|' . $username . '|' . $token . '|' . self::getGrav()['config']->get('security.salt'));
}
//Added in version 1.0.8 to ensure that existing nonces are not broken.
@@ -517,7 +522,8 @@ abstract class Utils
if ($plusOneTick) {
$i++;
}
return ( $i . '|' . $action . '|' . $username . '|' . $token . '|' . self::getGrav()['config']->get('security.salt'));
return ($i . '|' . $action . '|' . $username . '|' . $token . '|' . self::getGrav()['config']->get('security.salt'));
}
/**
@@ -531,15 +537,16 @@ abstract class Utils
private static function nonceTick()
{
$secondsInHalfADay = 60 * 60 * 12;
return (int)ceil(time() / ( $secondsInHalfADay ));
return (int)ceil(time() / ($secondsInHalfADay));
}
/**
* Creates a hashed nonce tied to the passed action. Tied to the current user and time. The nonce for a given
* action is the same for 12 hours.
*
* @param string $action the action the nonce is tied to (e.g. save-user-admin or move-page-homepage)
* @param bool $plusOneTick if true, generates the token for the next tick (the next 12 hours)
* @param string $action the action the nonce is tied to (e.g. save-user-admin or move-page-homepage)
* @param bool $plusOneTick if true, generates the token for the next tick (the next 12 hours)
*
* @return string the nonce
*/
@@ -572,7 +579,7 @@ abstract class Utils
/**
* Verify the passed nonce for the give action
*
* @param string $nonce the nonce to verify
* @param string $nonce the nonce to verify
* @param string $action the action to verify the nonce to
*
* @return boolean verified or not