PhpStan fixes

This commit is contained in:
Matias Griese
2020-10-02 13:12:47 +03:00
parent 5fc7b34ce7
commit 4f7a4ac1e2
24 changed files with 272 additions and 213 deletions

View File

@@ -17,6 +17,8 @@ use Grav\Framework\Flex\Interfaces\FlexCollectionInterface;
use Grav\Framework\Flex\Interfaces\FlexInterface;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
use Grav\Framework\Object\ObjectCollection;
use RuntimeException;
use function is_array;
/**
* Class Flex
@@ -26,7 +28,6 @@ class Flex implements FlexInterface
{
/** @var array */
protected $config;
/** @var FlexDirectory[] */
protected $types;
@@ -61,9 +62,6 @@ class Flex implements FlexInterface
public function addDirectoryType(string $type, string $blueprint, array $config = [])
{
$config = array_replace_recursive(['enabled' => true], $this->config ?? [], $config);
if ($config === null) {
throw new \RuntimeException('Internal error');
}
$this->types[$type] = new FlexDirectory($type, $blueprint, $config);
@@ -137,13 +135,13 @@ class Flex implements FlexInterface
* @param array $options In addition to the options in getObjects(), following options can be passed:
* collection_class: Class to be used to create the collection. Defaults to ObjectCollection.
* @return FlexCollectionInterface
* @throws \RuntimeException
* @throws RuntimeException
*/
public function getMixedCollection(array $keys, array $options = []): FlexCollectionInterface
{
$collectionClass = $options['collection_class'] ?? ObjectCollection::class;
if (!class_exists($collectionClass)) {
throw new \RuntimeException(sprintf('Cannot create collection: Class %s does not exist', $collectionClass));
throw new RuntimeException(sprintf('Cannot create collection: Class %s does not exist', $collectionClass));
}
$objects = $this->getObjects($keys, $options);
@@ -238,7 +236,7 @@ class Flex implements FlexInterface
$results = [];
foreach ($keys as $key) {
$flexKey = $guessed[$key] ?? $key;
if (\is_array($flexKey)) {
if (is_array($flexKey)) {
$result = null;
foreach ($flexKey as $tryKey) {
if ($result = $list[$tryKey] ?? null) {

View File

@@ -28,6 +28,10 @@ use Twig\Error\LoaderError;
use Twig\Error\SyntaxError;
use Twig\Template;
use Twig\TemplateWrapper;
use function array_filter;
use function get_class;
use function in_array;
use function is_array;
/**
* Class FlexCollection
@@ -88,6 +92,7 @@ class FlexCollection extends ObjectCollection implements FlexCollectionInterface
*/
public function __construct(array $entries = [], FlexDirectory $directory = null)
{
// @phpstan-ignore-next-line
if (get_class($this) === __CLASS__) {
user_error('Using ' . __CLASS__ . ' directly is deprecated since Grav 1.7, use \Grav\Common\Flex\Types\Generic\GenericCollection or your own class instead', E_USER_DEPRECATED);
}
@@ -139,7 +144,7 @@ class FlexCollection extends ObjectCollection implements FlexCollectionInterface
$matching = array_filter($matching);
if ($matching) {
uksort($matching, function ($a, $b) {
uksort($matching, static function ($a, $b) {
return -($a <=> $b);
});
}
@@ -421,6 +426,7 @@ class FlexCollection extends ObjectCollection implements FlexCollectionInterface
}
/**
* @param string $key
* @return array
*/
public function getMetaData(string $key): array
@@ -456,7 +462,7 @@ class FlexCollection extends ObjectCollection implements FlexCollectionInterface
public function isAuthorized(string $action, string $scope = null, UserInterface $user = null)
{
$list = $this->call('isAuthorized', [$action, $scope, $user]);
$list = \array_filter($list);
$list = array_filter($list);
return $this->select(array_keys($list));
}
@@ -491,7 +497,7 @@ class FlexCollection extends ObjectCollection implements FlexCollectionInterface
* @var array|FlexObject $object
*/
foreach ($this->getElements() as $key => $object) {
$elements[$key] = \is_array($object) ? $object : $object->jsonSerialize();
$elements[$key] = is_array($object) ? $object : $object->jsonSerialize();
}
return $elements;

View File

@@ -9,6 +9,7 @@
namespace Grav\Framework\Flex;
use Exception;
use Grav\Common\Cache;
use Grav\Common\Config\Config;
use Grav\Common\Data\Blueprint;
@@ -32,6 +33,12 @@ use Psr\SimpleCache\InvalidArgumentException;
use RocketTheme\Toolbox\File\YamlFile;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use function call_user_func_array;
use function is_array;
use Grav\Common\Flex\Types\Generic\GenericObject;
use Grav\Common\Flex\Types\Generic\GenericCollection;
use Grav\Common\Flex\Types\Generic\GenericIndex;
use function is_callable;
/**
* Class FlexDirectory
@@ -59,7 +66,7 @@ class FlexDirectory implements FlexAuthorizeInterface
protected $config;
/** @var FlexStorageInterface */
protected $storage;
/** @var CacheInterface */
/** @var CacheInterface[] */
protected $cache;
/** @var FlexObjectInterface[] */
protected $objects;
@@ -146,7 +153,7 @@ class FlexDirectory implements FlexAuthorizeInterface
$config = $this->getBlueprintInternal()->get('config', []);
$config = is_array($config) ? array_replace_recursive($config, $this->defaults, $this->getDirectoryConfig($config['admin']['configure']['form'] ?? null)) : null;
if (!is_array($config)) {
throw new \RuntimeException('Bad configuration');
throw new RuntimeException('Bad configuration');
}
$this->config = new Config($config);
@@ -193,7 +200,8 @@ class FlexDirectory implements FlexAuthorizeInterface
/**
* @param string $name
* @param array $data
* @throws \Exception
* @return void
* @throws Exception
* @internal
*/
public function saveDirectoryConfig(string $name, array $data)
@@ -234,6 +242,10 @@ class FlexDirectory implements FlexAuthorizeInterface
return $file->content();
}
/**
* @param string|null $name
* @return string
*/
public function getDirectoryConfigUri(string $name = null): string
{
$name = $name ?: $this->getFlexType();
@@ -242,6 +254,10 @@ class FlexDirectory implements FlexAuthorizeInterface
return $blueprint->get('blueprints/configure/file') ?? "config://flex/{$name}.yaml";
}
/**
* @param string|null $name
* @return array
*/
protected function getDirectoryConfig(string $name = null): array
{
$grav = Grav::instance();
@@ -323,7 +339,7 @@ class FlexDirectory implements FlexAuthorizeInterface
$index = clone $index;
if (null !== $keys) {
/** @var FlexCollectionInterface $index */
/** @var FlexIndexInterface $index */
$index = $index->select($keys);
}
@@ -335,7 +351,7 @@ class FlexDirectory implements FlexAuthorizeInterface
*
* Note: It is not safe to use the object without checking if the user can access it.
*
* @param string $key
* @param string|null $key
* @param string|null $keyField Field to be used as the key.
* @return FlexObjectInterface|null
*/
@@ -378,7 +394,7 @@ class FlexDirectory implements FlexAuthorizeInterface
}
$cache = new DoctrineCache($gravCache->getCacheDriver(), 'flex-objects-' . $this->getFlexType() . $key, $lifetime);
}
} catch (\Exception $e) {
} catch (Exception $e) {
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$debugger->addException($e);
@@ -495,7 +511,7 @@ class FlexDirectory implements FlexAuthorizeInterface
public function getObjectClass(): string
{
if (!$this->objectClassName) {
$this->objectClassName = $this->getConfig('data.object', 'Grav\\Common\\Flex\\Types\\Generic\\GenericObject');
$this->objectClassName = $this->getConfig('data.object', GenericObject::class);
}
return $this->objectClassName;
@@ -507,7 +523,7 @@ class FlexDirectory implements FlexAuthorizeInterface
public function getCollectionClass(): string
{
if (!$this->collectionClassName) {
$this->collectionClassName = $this->getConfig('data.collection', 'Grav\\Common\\Flex\\Types\\Generic\\GenericCollection');
$this->collectionClassName = $this->getConfig('data.collection', GenericCollection::class);
}
return $this->collectionClassName;
@@ -520,7 +536,7 @@ class FlexDirectory implements FlexAuthorizeInterface
public function getIndexClass(): string
{
if (!$this->indexClassName) {
$this->indexClassName = $this->getConfig('data.index', 'Grav\\Common\\Flex\\Types\\Generic\\GenericIndex');
$this->indexClassName = $this->getConfig('data.index', GenericIndex::class);
}
return $this->indexClassName;
@@ -626,7 +642,7 @@ class FlexDirectory implements FlexAuthorizeInterface
if (isset($row['__ERROR'])) {
$message = sprintf('Flex: Object %s is broken in %s storage: %s', $storageKey, $this->type, $row['__ERROR']);
$debugger->addException(new \RuntimeException($message));
$debugger->addException(new RuntimeException($message));
$debugger->addMessage($message, 'error');
continue;
}
@@ -674,7 +690,6 @@ class FlexDirectory implements FlexAuthorizeInterface
/**
* @return void
* @throws InvalidArgumentException
*/
public function reloadIndex(): void
{
@@ -749,10 +764,10 @@ class FlexDirectory implements FlexAuthorizeInterface
* @param array $call
* @return void
*/
protected function dynamicDataField(array &$field, $property, array &$call)
protected function dynamicDataField(array &$field, $property, array $call)
{
$params = $call['params'];
if (\is_array($params)) {
if (is_array($params)) {
$function = array_shift($params);
} else {
$function = $params;
@@ -765,13 +780,13 @@ class FlexDirectory implements FlexAuthorizeInterface
}
$data = null;
if (\is_callable($function)) {
$data = \call_user_func_array($function, $params);
if (is_callable($function)) {
$data = call_user_func_array($function, $params);
}
// If function returns a value,
if (null !== $data) {
if (\is_array($data) && isset($field[$property]) && \is_array($field[$property])) {
if (is_array($data) && isset($field[$property]) && is_array($field[$property])) {
// Combine field and @data-field together.
$field[$property] += $data;
} else {
@@ -787,7 +802,7 @@ class FlexDirectory implements FlexAuthorizeInterface
* @param array $call
* @return void
*/
protected function dynamicFlexField(array &$field, $property, array &$call)
protected function dynamicFlexField(array &$field, $property, array $call)
{
$params = (array)$call['params'];
$object = $call['object'] ?? null;
@@ -795,7 +810,7 @@ class FlexDirectory implements FlexAuthorizeInterface
if ($object && method_exists($object, $method)) {
$value = $object->{$method}(...$params);
if (\is_array($value) && isset($field[$property]) && \is_array($field[$property])) {
if (is_array($value) && isset($field[$property]) && is_array($field[$property])) {
$field[$property] = array_merge_recursive($field[$property], $value);
} else {
$field[$property] = $value;
@@ -812,7 +827,7 @@ class FlexDirectory implements FlexAuthorizeInterface
$storage = $this->getConfig('data.storage');
if (!\is_array($storage)) {
if (!is_array($storage)) {
$storage = ['options' => ['folder' => $storage]];
}
@@ -955,9 +970,9 @@ class FlexDirectory implements FlexAuthorizeInterface
$key = $object->getStorageKey();
if ($key) {
$rows = $storage->replaceRows([$key => $object->prepareStorage()]);
$storage->replaceRows([$key => $object->prepareStorage()]);
} else {
$rows = $storage->createRows([$object->prepareStorage()]);
$storage->createRows([$object->prepareStorage()]);
}
} else {
$oldKey = $object->getStorageKey();

View File

@@ -9,17 +9,18 @@
namespace Grav\Framework\Flex;
use ArrayAccess;
use Grav\Common\Data\Blueprint;
use Grav\Common\Data\Data;
use Grav\Common\Grav;
use Grav\Common\Twig\Twig;
use Grav\Framework\Flex\Interfaces\FlexDirectoryFormInterface;
use Grav\Framework\Flex\Interfaces\FlexFormInterface;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
use Grav\Framework\Form\Interfaces\FormFlashInterface;
use Grav\Framework\Form\Traits\FormTrait;
use Grav\Framework\Route\Route;
use RocketTheme\Toolbox\ArrayTraits\NestedArrayAccessWithGetters;
use RuntimeException;
use Twig\Error\LoaderError;
use Twig\Error\SyntaxError;
use Twig\Template;
@@ -42,10 +43,8 @@ class FlexDirectoryForm implements FlexDirectoryFormInterface, \JsonSerializable
/** @var array|null */
private $form;
/** @var FlexDirectory */
private $directory;
/** @var string */
private $flexName;
@@ -63,11 +62,11 @@ class FlexDirectoryForm implements FlexDirectoryFormInterface, \JsonSerializable
if (isset($options['directory'])) {
$directory = $options['directory'];
if (!$directory instanceof FlexDirectory) {
throw new \RuntimeException(__METHOD__ . "(): 'directory' should be instance of FlexDirectory", 400);
throw new RuntimeException(__METHOD__ . "(): 'directory' should be instance of FlexDirectory", 400);
}
unset($options['directory']);
} else {
throw new \RuntimeException(__METHOD__ . "(): You need to pass option 'directory'", 400);
throw new RuntimeException(__METHOD__ . "(): You need to pass option 'directory'", 400);
}
$name = $options['name'] ?? '';
@@ -79,7 +78,7 @@ class FlexDirectoryForm implements FlexDirectoryFormInterface, \JsonSerializable
* FlexForm constructor.
* @param string $name
* @param FlexDirectory $directory
* @param array $options
* @param array|null $options
*/
public function __construct(string $name, FlexDirectory $directory, array $options = null)
{
@@ -118,7 +117,7 @@ class FlexDirectoryForm implements FlexDirectoryFormInterface, \JsonSerializable
$directory = $flash->getDirectory();
if (null === $directory) {
throw new \RuntimeException('Flash has no directory');
throw new RuntimeException('Flash has no directory');
}
$this->directory = $directory;
$this->data = $data ? new Data($data, $this->getBlueprint()) : null;
@@ -290,7 +289,7 @@ class FlexDirectoryForm implements FlexDirectoryFormInterface, \JsonSerializable
$blueprint->extend(['form' => $this->form], true);
$blueprint->init();
}
} catch (\RuntimeException $e) {
} catch (RuntimeException $e) {
if (!isset($this->form['fields'])) {
throw $e;
}
@@ -367,6 +366,7 @@ class FlexDirectoryForm implements FlexDirectoryFormInterface, \JsonSerializable
/**
* @param string $name
* @param mixed $value
* @return void
*/
public function __set($name, $value)
{
@@ -394,6 +394,7 @@ class FlexDirectoryForm implements FlexDirectoryFormInterface, \JsonSerializable
/**
* @param string $name
* @return void
*/
public function __unset($name)
{
@@ -438,6 +439,7 @@ class FlexDirectoryForm implements FlexDirectoryFormInterface, \JsonSerializable
/**
* @param array $data
* @param array $files
* @return void
* @throws \Exception
*/
protected function doSubmit(array $data, array $files)
@@ -459,6 +461,7 @@ class FlexDirectoryForm implements FlexDirectoryFormInterface, \JsonSerializable
/**
* @param array $data
* @return void
*/
protected function doUnserialize(array $data): void
{
@@ -470,7 +473,7 @@ class FlexDirectoryForm implements FlexDirectoryFormInterface, \JsonSerializable
/**
* Filter validated data.
*
* @param \ArrayAccess|Data|null $data
* @param ArrayAccess|Data|null $data
*/
protected function filterData($data = null): void
{

View File

@@ -20,6 +20,7 @@ use Grav\Framework\Form\Interfaces\FormFlashInterface;
use Grav\Framework\Form\Traits\FormTrait;
use Grav\Framework\Route\Route;
use RocketTheme\Toolbox\ArrayTraits\NestedArrayAccessWithGetters;
use RuntimeException;
use Twig\Error\LoaderError;
use Twig\Error\SyntaxError;
use Twig\Template;
@@ -45,10 +46,8 @@ class FlexForm implements FlexObjectFormInterface, \JsonSerializable
/** @var array|null */
private $form;
/** @var FlexObjectInterface */
private $object;
/** @var string */
private $flexName;
@@ -68,17 +67,17 @@ class FlexForm implements FlexObjectFormInterface, \JsonSerializable
if (isset($options['object'])) {
$object = $options['object'];
if (!$object instanceof FlexObjectInterface) {
throw new \RuntimeException(__METHOD__ . "(): 'object' should be instance of FlexObjectInterface", 400);
throw new RuntimeException(__METHOD__ . "(): 'object' should be instance of FlexObjectInterface", 400);
}
} elseif (isset($options['directory'])) {
$directory = $options['directory'];
if (!$directory instanceof FlexDirectory) {
throw new \RuntimeException(__METHOD__ . "(): 'directory' should be instance of FlexDirectory", 400);
throw new RuntimeException(__METHOD__ . "(): 'directory' should be instance of FlexDirectory", 400);
}
$key = $options['key'] ?? '';
$object = $directory->getObject($key) ?? $directory->createObject([], $key);
} else {
throw new \RuntimeException(__METHOD__ . "(): You need to pass option 'directory' or 'object'", 400);
throw new RuntimeException(__METHOD__ . "(): You need to pass option 'directory' or 'object'", 400);
}
$name = $options['name'] ?? '';
@@ -93,7 +92,7 @@ class FlexForm implements FlexObjectFormInterface, \JsonSerializable
* FlexForm constructor.
* @param string $name
* @param FlexObjectInterface $object
* @param array $options
* @param array|null $options
*/
public function __construct(string $name, FlexObjectInterface $object, array $options = null)
{
@@ -144,7 +143,7 @@ class FlexForm implements FlexObjectFormInterface, \JsonSerializable
$object = $flash->getObject();
if (null === $object) {
throw new \RuntimeException('Flash has no object');
throw new RuntimeException('Flash has no object');
}
$this->object = $object;
@@ -330,7 +329,7 @@ class FlexForm implements FlexObjectFormInterface, \JsonSerializable
$blueprint->extend(['form' => $this->form], true);
$blueprint->init();
}
} catch (\RuntimeException $e) {
} catch (RuntimeException $e) {
if (!isset($this->form['fields'])) {
throw $e;
}

View File

@@ -13,6 +13,10 @@ use Grav\Framework\Flex\Interfaces\FlexInterface;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
use Grav\Framework\Form\FormFlash;
/**
* Class FlexFormFlash
* @package Grav\Framework\Flex
*/
class FlexFormFlash extends FormFlash
{
/** @var FlexDirectory|null */
@@ -99,6 +103,7 @@ class FlexFormFlash extends FormFlash
{
parent::init($data, $config);
$data = $data ?? [];
/** @var FlexObjectInterface|null $object */
$object = $config['object'] ?? null;
$create = true;

View File

@@ -9,6 +9,7 @@
namespace Grav\Framework\Flex;
use Exception;
use Grav\Common\Debugger;
use Grav\Common\File\CompiledYamlFile;
use Grav\Common\Grav;
@@ -24,6 +25,10 @@ use Grav\Framework\Object\Interfaces\ObjectInterface;
use Grav\Framework\Object\ObjectIndex;
use Monolog\Logger;
use Psr\SimpleCache\InvalidArgumentException;
use RuntimeException;
use function count;
use function get_class;
use function in_array;
class FlexIndex extends ObjectIndex implements FlexCollectionInterface, FlexIndexInterface
{
@@ -31,10 +36,8 @@ class FlexIndex extends ObjectIndex implements FlexCollectionInterface, FlexInde
/** @var FlexDirectory|null */
private $_flexDirectory;
/** @var string */
private $_keyField;
/** @var array */
private $_indexKeys;
@@ -77,6 +80,7 @@ class FlexIndex extends ObjectIndex implements FlexCollectionInterface, FlexInde
* @param array $meta
* @param array $data
* @param FlexStorageInterface $storage
* @return void
*/
public static function updateObjectMeta(array &$meta, array $data, FlexStorageInterface $storage)
{
@@ -92,6 +96,7 @@ class FlexIndex extends ObjectIndex implements FlexCollectionInterface, FlexInde
*/
public function __construct(array $entries = [], FlexDirectory $directory = null)
{
// @phpstan-ignore-next-line
if (get_class($this) === __CLASS__) {
user_error('Using ' . __CLASS__ . ' directly is deprecated since Grav 1.7, use \Grav\Common\Flex\Types\Generic\GenericIndex or your own class instead', E_USER_DEPRECATED);
}
@@ -175,7 +180,7 @@ class FlexIndex extends ObjectIndex implements FlexCollectionInterface, FlexInde
public function getFlexDirectory(): FlexDirectory
{
if (null === $this->_flexDirectory) {
throw new \RuntimeException('Flex Directory not defined, object is not fully defined');
throw new RuntimeException('Flex Directory not defined, object is not fully defined');
}
return $this->_flexDirectory;
@@ -324,6 +329,7 @@ class FlexIndex extends ObjectIndex implements FlexCollectionInterface, FlexInde
}
/**
* @param string $key
* @return array
*/
public function getMetaData(string $key): array
@@ -380,9 +386,6 @@ class FlexIndex extends ObjectIndex implements FlexCollectionInterface, FlexInde
if (null !== $previous) {
$search = array_replace($previous, $search);
}
if (null === $search) {
throw new \RuntimeException('Error while ordering collection');
}
// Order by current field.
if (strtoupper($ordering) === 'DESC') {
@@ -712,7 +715,7 @@ class FlexIndex extends ObjectIndex implements FlexCollectionInterface, FlexInde
static::updateObjectMeta($entry, $row ?? [], $storage);
if (isset($row['__ERROR'])) {
$entry['__ERROR'] = true;
static::onException(new \RuntimeException(sprintf('Object failed to load: %s (%s)', $key,
static::onException(new RuntimeException(sprintf('Object failed to load: %s (%s)', $key,
$row['__ERROR'])));
}
if (isset($index[$key])) {
@@ -739,7 +742,7 @@ class FlexIndex extends ObjectIndex implements FlexCollectionInterface, FlexInde
static::onChanges($index, $added, $updated, $removed);
$indexFile->save(['version' => static::VERSION, 'timestamp' => time(), 'count' => \count($index), 'index' => $index]);
$indexFile->save(['version' => static::VERSION, 'timestamp' => time(), 'count' => count($index), 'index' => $index]);
$indexFile->unlock();
return $index;
@@ -748,6 +751,7 @@ class FlexIndex extends ObjectIndex implements FlexCollectionInterface, FlexInde
/**
* @param array $entry
* @param array $data
* @return void
* @deprecated 1.7 Use static ::updateObjectMeta() method instead.
*/
protected static function updateIndexData(array &$entry, array $data)
@@ -770,8 +774,8 @@ class FlexIndex extends ObjectIndex implements FlexCollectionInterface, FlexInde
if ($version !== static::VERSION) {
$data = [];
}
} catch (\Exception $e) {
$e = new \RuntimeException(sprintf('Index failed to load: %s', $e->getMessage()), $e->getCode(), $e);
} catch (Exception $e) {
$e = new RuntimeException(sprintf('Index failed to load: %s', $e->getMessage()), $e->getCode(), $e);
static::onException($e);
}
@@ -819,10 +823,10 @@ class FlexIndex extends ObjectIndex implements FlexCollectionInterface, FlexInde
}
/**
* @param \Exception $e
* @param Exception $e
* @return void
*/
protected static function onException(\Exception $e)
protected static function onException(Exception $e)
{
$grav = Grav::instance();
@@ -845,12 +849,12 @@ class FlexIndex extends ObjectIndex implements FlexCollectionInterface, FlexInde
*/
protected static function onChanges(array $entries, array $added, array $updated, array $removed)
{
$addedCount = \count($added);
$updatedCount = \count($updated);
$removedCount = \count($removed);
$addedCount = count($added);
$updatedCount = count($updated);
$removedCount = count($removed);
if ($addedCount + $updatedCount + $removedCount) {
$message = sprintf('Index updated, %d objects (%d added, %d updated, %d removed).', \count($entries), $addedCount, $updatedCount, $removedCount);
$message = sprintf('Index updated, %d objects (%d added, %d updated, %d removed).', count($entries), $addedCount, $updatedCount, $removedCount);
$grav = Grav::instance();

View File

@@ -9,6 +9,8 @@
namespace Grav\Framework\Flex;
use ArrayAccess;
use Exception;
use Grav\Common\Data\Blueprint;
use Grav\Common\Debugger;
use Grav\Common\Grav;
@@ -31,10 +33,17 @@ use Grav\Framework\Object\Interfaces\ObjectInterface;
use Grav\Framework\Object\Property\LazyPropertyTrait;
use Psr\SimpleCache\InvalidArgumentException;
use RocketTheme\Toolbox\Event\Event;
use RuntimeException;
use Twig\Error\LoaderError;
use Twig\Error\SyntaxError;
use Twig\Template;
use Twig\TemplateWrapper;
use function get_class;
use function in_array;
use function is_array;
use function is_object;
use function is_scalar;
use function is_string;
/**
* Class FlexObject
@@ -328,6 +337,8 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface
*/
protected function searchValue(string $name, $value, string $search, array $options = null): float
{
$options = $options ?? [];
// Ignore empty search strings.
$search = trim($search);
if ($search === '') {
@@ -335,7 +346,7 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface
}
// Search only non-empty string values.
if (!\is_string($value) || $value === '') {
if (!is_string($value) || $value === '') {
return 0;
}
@@ -437,7 +448,7 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface
// Disable caching if context isn't all scalars.
if ($key) {
foreach ($context as $value) {
if (!\is_scalar($value)) {
if (!is_scalar($value)) {
$key = '';
break;
}
@@ -587,7 +598,7 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface
}
if ($this->exists()) {
throw new \RuntimeException('Cannot create new object (Already exists)');
throw new RuntimeException('Cannot create new object (Already exists)');
}
return $this->save();
@@ -654,7 +665,7 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface
if (method_exists($this, 'clearMediaCache')) {
$this->clearMediaCache();
}
} catch (\Exception $e) {
} catch (Exception $e) {
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$debugger->addException($e);
@@ -686,7 +697,7 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface
if (method_exists($this, 'clearMediaCache')) {
$this->clearMediaCache();
}
} catch (\Exception $e) {
} catch (Exception $e) {
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$debugger->addException($e);
@@ -746,9 +757,9 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface
while ($path) {
$offset = array_shift($path);
if ((\is_array($current) || $current instanceof \ArrayAccess) && isset($current[$offset])) {
if ((is_array($current) || $current instanceof ArrayAccess) && isset($current[$offset])) {
$current = $current[$offset];
} elseif (\is_object($current) && isset($current->{$offset})) {
} elseif (is_object($current) && isset($current->{$offset})) {
$current = $current->{$offset};
} else {
return null;
@@ -855,6 +866,7 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface
/**
* @param array $serialized
* @param FlexDirectory|null $directory
* @return void
*/
protected function doUnserialize(array $serialized, FlexDirectory $directory = null): void
{
@@ -941,7 +953,7 @@ class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface
* This methods allows you to override form objects in child classes.
*
* @param string $name Form name
* @param array $options Form optiosn
* @param array|null $options Form optiosn
* @return FlexFormInterface
*/
protected function createFormObject(string $name, array $options = null)

View File

@@ -15,6 +15,7 @@ use Grav\Framework\Flex\Flex;
use Grav\Framework\Object\Interfaces\NestedObjectInterface;
use Grav\Framework\Object\Interfaces\ObjectCollectionInterface;
use Grav\Framework\Flex\FlexDirectory;
use InvalidArgumentException;
/**
* Defines a collection of Flex Objects.
@@ -32,7 +33,6 @@ interface FlexCollectionInterface extends FlexCommonInterface, ObjectCollectionI
* @param FlexObjectInterface[] $entries Associated array of Flex Objects to be included in the collection.
* @param FlexDirectory $directory Flex Directory where all the objects belong into.
* @param string|null $keyField Key field used to index the collection.
*
* @return static Returns a new Flex Collection.
*/
public static function createFromArray(array $entries, FlexDirectory $directory, string $keyField = null);
@@ -44,8 +44,7 @@ interface FlexCollectionInterface extends FlexCommonInterface, ObjectCollectionI
*
* @param FlexObjectInterface[] $entries Associated array of Flex Objects to be included in the collection.
* @param FlexDirectory|null $directory Flex Directory where all the objects belong into.
*
* @throws \InvalidArgumentException
* @throws InvalidArgumentException
*/
public function __construct(array $entries = [], FlexDirectory $directory = null);
@@ -55,7 +54,6 @@ interface FlexCollectionInterface extends FlexCommonInterface, ObjectCollectionI
* @param string $search Search string.
* @param string|string[]|null $properties Properties to search for, defaults to configured properties.
* @param array|null $options Search options, defaults to configured options.
*
* @return FlexCollectionInterface Returns a Flex Collection with only matching objects.
* @api
*/
@@ -109,7 +107,6 @@ interface FlexCollectionInterface extends FlexCommonInterface, ObjectCollectionI
* Return new collection with a different key.
*
* @param string|null $keyField Switch key field of the collection.
*
* @return FlexCollectionInterface Returns a new Flex Collection with new key field.
* @api
*/

View File

@@ -39,7 +39,6 @@ interface FlexFormInterface extends \Serializable, FormInterface
*
* @param string $field Field where the file is associated into.
* @param string $filename Filename for the file.
*
* @return Route|null Returns Route object or null if file uploads are not enabled.
*/
public function getFileDeleteAjaxRoute($field, $filename);

View File

@@ -30,7 +30,6 @@ interface FlexIndexInterface extends FlexCollectionInterface
* @used-by FlexDirectory::getIndex() Official method to get Index from a Flex Directory.
*
* @param FlexDirectory $directory Flex directory.
*
* @return static Returns a new Flex Index.
*/
public static function createFromStorage(FlexDirectory $directory);
@@ -41,7 +40,6 @@ interface FlexIndexInterface extends FlexCollectionInterface
* @used-by FlexDirectory::getIndex() Official method to get Index from a Flex Directory.
*
* @param FlexStorageInterface $storage Flex Storage associated to the directory.
*
* @return array Returns a list of existing objects [storage_key => [storage_key => xxx, storage_timestamp => 123456, ...]]
*/
public static function loadEntriesFromStorage(FlexStorageInterface $storage): array;
@@ -50,8 +48,7 @@ interface FlexIndexInterface extends FlexCollectionInterface
* Return new collection with a different key.
*
* @param string|null $keyField Switch key field of the collection.
*
* @return FlexIndexInterface Returns a new Flex Collection with new key field.
* @return static Returns a new Flex Collection with new key field.
* @api
*/
public function withKeyField(string $keyField = null);

View File

@@ -11,13 +11,14 @@ declare(strict_types=1);
namespace Grav\Framework\Flex\Interfaces;
use Countable;
use Grav\Framework\Flex\FlexDirectory;
/**
* Interface FlexInterface
* @package Grav\Framework\Flex\Interfaces
*/
interface FlexInterface extends \Countable
interface FlexInterface extends Countable
{
/**
* @param string $type

View File

@@ -15,7 +15,9 @@ use Grav\Common\Data\Blueprint;
use Grav\Framework\Flex\Flex;
use Grav\Framework\Object\Interfaces\NestedObjectInterface;
use Grav\Framework\Flex\FlexDirectory;
use InvalidArgumentException;
use Psr\Http\Message\UploadedFileInterface;
use RuntimeException;
/**
* Defines Flex Objects.
@@ -34,8 +36,7 @@ interface FlexObjectInterface extends FlexCommonInterface, NestedObjectInterface
* @param string $key Identifier key for the new object.
* @param FlexDirectory $directory Flex Directory the object belongs into.
* @param bool $validate True if the object should be validated against blueprint.
*
* @throws \InvalidArgumentException
* @throws InvalidArgumentException
*/
public function __construct(array $elements, $key, FlexDirectory $directory, bool $validate = false);
@@ -49,7 +50,6 @@ interface FlexObjectInterface extends FlexCommonInterface, NestedObjectInterface
* @param string $search Search string.
* @param string|string[]|null $properties Properties to search for, defaults to configured properties.
* @param array|null $options Search options, defaults to configured options.
*
* @return float Returns a weight between 0 and 1.
* @api
*/
@@ -117,9 +117,8 @@ interface FlexObjectInterface extends FlexCommonInterface, NestedObjectInterface
*
* @param array $data Data containing updated properties with their values. To unset a value, use `null`.
* @param array|UploadedFileInterface[] $files List of uploaded files to be saved within the object.
*
* @return FlexObjectInterface
* @throws \RuntimeException
* @return static
* @throws RuntimeException
* @api
*/
public function update(array $data, array $files = []);
@@ -131,9 +130,8 @@ interface FlexObjectInterface extends FlexCommonInterface, NestedObjectInterface
* @see FlexObjectInterface::update() If you want to update properties of the object.
*
* @param string|null $key Optional new key. If key isn't given, random key will be associated to the object.
*
* @return FlexObjectInterface
* @throws \RuntimeException if object already exists.
* @return static
* @throws RuntimeException if object already exists.
* @api
*/
public function create(string $key = null);
@@ -143,7 +141,7 @@ interface FlexObjectInterface extends FlexCommonInterface, NestedObjectInterface
*
* @see FlexObjectInterface::update() If you want to update properties of the object.
*
* @return FlexObjectInterface
* @return static
* @api
*/
public function save();
@@ -151,7 +149,7 @@ interface FlexObjectInterface extends FlexCommonInterface, NestedObjectInterface
/**
* Delete object from the storage.
*
* @return FlexObjectInterface
* @return static
* @api
*/
public function delete();
@@ -163,7 +161,6 @@ interface FlexObjectInterface extends FlexCommonInterface, NestedObjectInterface
* @used-by FlexForm::getBlueprint()
*
* @param string $name Name of the Blueprint form. Used to create customized forms for different use cases.
*
* @return Blueprint Returns a Blueprint.
*/
public function getBlueprint(string $name = '');
@@ -173,7 +170,6 @@ interface FlexObjectInterface extends FlexCommonInterface, NestedObjectInterface
*
* @param string $name Name of the form. Can be used to create customized forms for different use cases.
* @param array|null $options Options can be used to further customize the form.
*
* @return FlexFormInterface Returns a Form.
* @api
*/
@@ -186,7 +182,6 @@ interface FlexObjectInterface extends FlexCommonInterface, NestedObjectInterface
*
* @param string $name Property name.
* @param string|null $separator Optional nested property separator.
*
* @return mixed|null Returns default value of the field, null if there is no default value.
*/
public function getDefaultValue(string $name, string $separator = null);
@@ -208,7 +203,6 @@ interface FlexObjectInterface extends FlexCommonInterface, NestedObjectInterface
* @param string $name Property name.
* @param mixed $default Default value.
* @param string|null $separator Optional nested property separator.
*
* @return mixed Returns value of the field.
*/
public function getFormValue(string $name, $default = null, string $separator = null);

View File

@@ -13,7 +13,9 @@ namespace Grav\Framework\Flex\Pages;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Framework\Flex\FlexCollection;
use Grav\Framework\Flex\Interfaces\FlexCollectionInterface;
use function array_search;
use function assert;
use function is_int;
/**
* Class FlexPageCollection
@@ -138,7 +140,7 @@ class FlexPageCollection extends FlexCollection
public function adjacentSibling($path, $direction = 1)
{
$keys = $this->getKeys();
$pos = \array_search($path, $keys, true);
$pos = array_search($path, $keys, true);
if ($pos !== false) {
$pos += $direction;

View File

@@ -13,7 +13,6 @@ namespace Grav\Framework\Flex\Pages;
use Grav\Common\Grav;
use Grav\Framework\Flex\FlexIndex;
use Grav\Framework\Flex\Interfaces\FlexStorageInterface;
/**
* Class FlexPageObject

View File

@@ -10,6 +10,7 @@
namespace Grav\Framework\Flex\Pages;
use DateTime;
use Exception;
use Grav\Common\Debugger;
use Grav\Common\Grav;
use Grav\Common\Page\Interfaces\PageInterface;
@@ -25,6 +26,9 @@ use Grav\Framework\Flex\Pages\Traits\PageLegacyTrait;
use Grav\Framework\Flex\Pages\Traits\PageRoutableTrait;
use Grav\Framework\Flex\Pages\Traits\PageTranslateTrait;
use Grav\Framework\Flex\Traits\FlexMediaTrait;
use RuntimeException;
use stdClass;
use function is_array;
/**
* Class FlexPageObject
@@ -40,8 +44,8 @@ class FlexPageObject extends FlexObject implements PageInterface, FlexTranslateI
use PageTranslateTrait;
use FlexMediaTrait;
const PAGE_ORDER_REGEX = '/^(\d+)\.(.*)$/u';
const PAGE_ORDER_PREFIX_REGEX = '/^[0-9]+\./u';
public const PAGE_ORDER_REGEX = '/^(\d+)\.(.*)$/u';
public const PAGE_ORDER_PREFIX_REGEX = '/^[0-9]+\./u';
/** @var array|null */
protected $_reorder;
@@ -168,7 +172,7 @@ class FlexPageObject extends FlexObject implements PageInterface, FlexTranslateI
*/
public function getFormValue(string $name, $default = null, string $separator = null)
{
$test = new \stdClass();
$test = new stdClass();
$value = $this->pageContentValue($name, $test);
if ($value !== $test) {
@@ -183,7 +187,7 @@ class FlexPageObject extends FlexObject implements PageInterface, FlexTranslateI
case 'header.permissions.groups':
$encoded = json_encode($this->getPermissions());
if ($encoded === false) {
throw new \RuntimeException('json_encode(): failed to encode group permissions');
throw new RuntimeException('json_encode(): failed to encode group permissions');
}
return json_decode($encoded, true);
@@ -230,7 +234,7 @@ class FlexPageObject extends FlexObject implements PageInterface, FlexTranslateI
/**
* @param array|bool $reorder
* @return FlexObject|\Grav\Framework\Flex\Interfaces\FlexObjectInterface
* @return FlexObject|FlexObjectInterface
*/
public function save($reorder = true)
{
@@ -322,10 +326,10 @@ class FlexPageObject extends FlexObject implements PageInterface, FlexTranslateI
return parent::getProperty($property, $default);
}
/*
/**
* @param string $property
* @param mixed $default
* @return void
* @param mixed $value
* @return $this
*/
public function setProperty($property, $value)
{
@@ -401,8 +405,8 @@ class FlexPageObject extends FlexObject implements PageInterface, FlexTranslateI
if ($media_order) {
$elements['header']['media_order'] = $media_order;
}
} catch (\RuntimeException $e) {
throw new \RuntimeException('Badly formatted markdown');
} catch (RuntimeException $e) {
throw new RuntimeException('Badly formatted markdown');
}
unset($elements['frontmatter']);
@@ -444,7 +448,7 @@ class FlexPageObject extends FlexObject implements PageInterface, FlexTranslateI
$value = '@' . $value;
}
$date = $value ? new DateTime($value) : null;
} catch (\Exception $e) {
} catch (Exception $e) {
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$debugger->addException($e);

View File

@@ -13,6 +13,11 @@ namespace Grav\Framework\Flex\Pages\Traits;
use Grav\Common\User\Interfaces\UserInterface;
use Grav\Framework\Acl\Access;
use InvalidArgumentException;
use function in_array;
use function is_array;
use function is_bool;
use function is_string;
/**
* Trait PageAuthorsTrait
@@ -53,7 +58,7 @@ trait PageAuthorsTrait
public function getAuthors(): array
{
if (null === $this->_authors) {
$this->_authors = (array)$this->loadAuthors($this->getNestedProperty('header.permissions.authors', []));
$this->_authors = $this->loadAuthors($this->getNestedProperty('header.permissions.authors', []));
}
return $this->_authors;
@@ -90,7 +95,7 @@ trait PageAuthorsTrait
$list = [];
foreach ($authors as $username) {
if (!is_string($username)) {
throw new \InvalidArgumentException('Iterable should return username (string).', 500);
throw new InvalidArgumentException('Iterable should return username (string).', 500);
}
$list[] = $accounts->load($username);
}
@@ -98,6 +103,13 @@ trait PageAuthorsTrait
return $list;
}
/**
* @param string $action
* @param string|null $scope
* @param UserInterface|null $user
* @param bool $isAuthor
* @return bool|null
*/
public function isParentAuthorized(string $action, string $scope = null, UserInterface $user = null, bool $isAuthor = false): ?bool
{
$scope = $scope ?? $this->getAuthorizeScope();

View File

@@ -9,6 +9,7 @@
namespace Grav\Framework\Flex\Pages\Traits;
use Exception;
use Grav\Common\Config\Config;
use Grav\Common\Grav;
use Grav\Common\Markdown\Parsedown;
@@ -21,6 +22,10 @@ use Grav\Common\Twig\Twig;
use Grav\Common\Utils;
use Grav\Framework\File\Formatter\YamlFormatter;
use RocketTheme\Toolbox\Event\Event;
use stdClass;
use function in_array;
use function is_array;
use function is_string;
/**
* Implements PageContentInterface.
@@ -123,7 +128,7 @@ trait PageContentTrait
/**
* @inheritdoc
* @throws \Exception
* @throws Exception
*/
public function content($var = null): string
{
@@ -430,7 +435,7 @@ trait PageContentTrait
'dateformat',
$var,
static function ($value) {
return $value ?? null;
return $value;
}
);
}
@@ -512,18 +517,26 @@ trait PageContentTrait
if (null === $value) {
$value = [];
} elseif ($value instanceof \stdClass) {
} elseif ($value instanceof stdClass) {
$value = (array)$value;
}
return new Header($value);
}
/**
* @param Header|stdClass|array|null $value
* @return Header
*/
protected function offsetPrepare_header($value)
{
return $this->offsetLoad_header($value);
}
/**
* @param Header|null $value
* @return array
*/
protected function offsetSerialize_header(?Header $value)
{
return $value ? $value->toArray() : [];
@@ -531,7 +544,7 @@ trait PageContentTrait
/**
* @param string $name
* @param mixed $default
* @param mixed|null $default
* @return mixed
*/
protected function pageContentValue($name, $default = null)
@@ -653,7 +666,7 @@ trait PageContentTrait
*
* @param string $content
* @return string
* @throws \Exception
* @throws Exception
*/
protected function processContent($content): string
{
@@ -784,7 +797,7 @@ trait PageContentTrait
* @param string $content
* @param array $options
* @return string
* @throws \Exception
* @throws Exception
*/
protected function processMarkdown($content, array $options = []): string
{

View File

@@ -17,17 +17,22 @@ use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Page\Pages;
use Grav\Common\Utils;
use Grav\Common\Yaml;
use Grav\Framework\Cache\CacheInterface;
use Grav\Framework\File\Formatter\MarkdownFormatter;
use Grav\Framework\File\Formatter\YamlFormatter;
use Grav\Framework\Filesystem\Filesystem;
use Grav\Framework\Flex\FlexDirectory;
use Grav\Framework\Flex\Interfaces\FlexCollectionInterface;
use Grav\Framework\Flex\Interfaces\FlexIndexInterface;
use Grav\Framework\Flex\Pages\FlexPageIndex;
use Grav\Framework\Flex\Pages\FlexPageObject;
use InvalidArgumentException;
use RocketTheme\Toolbox\File\MarkdownFile;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use SplFileInfo;
use function in_array;
use function is_array;
use function is_string;
use function strlen;
/**
* Implements PageLegacyInterface
@@ -42,29 +47,27 @@ trait PageLegacyTrait
/**
* Initializes the page instance variables based on a file
*
* @param \SplFileInfo $file The file information for the .md file that the page represents
* @param string $extension
*
* @param SplFileInfo $file The file information for the .md file that the page represents
* @param string|null $extension
* @return $this
*/
public function init(\SplFileInfo $file, $extension = null)
public function init(SplFileInfo $file, $extension = null)
{
// TODO:
throw new \RuntimeException(__METHOD__ . '(): Not Implemented');
throw new RuntimeException(__METHOD__ . '(): Not Implemented');
}
/**
* Gets and Sets the raw data
*
* @param string $var Raw content string
*
* @param string|null $var Raw content string
* @return string Raw content string
*/
public function raw($var = null): string
{
if (null !== $var) {
// TODO:
throw new \RuntimeException(__METHOD__ . '(string): Not Implemented');
throw new RuntimeException(__METHOD__ . '(string): Not Implemented');
}
$storage = $this->getFlexDirectory()->getStorage();
@@ -82,14 +85,13 @@ trait PageLegacyTrait
* Gets and Sets the page frontmatter
*
* @param string|null $var
*
* @return string
*/
public function frontmatter($var = null): string
{
if (null !== $var) {
// TODO:
throw new \RuntimeException(__METHOD__ . '(string): Not Implemented');
throw new RuntimeException(__METHOD__ . '(string): Not Implemented');
}
$storage = $this->getFlexDirectory()->getStorage();
@@ -108,6 +110,7 @@ trait PageLegacyTrait
*
* @param string $key
* @param string|array $value
* @return void
*/
public function modifyHeader($key, $value): void
{
@@ -124,6 +127,9 @@ trait PageLegacyTrait
return $code ?: 200;
}
/**
* @return array
*/
public function httpHeaders(): array
{
$headers = [];
@@ -187,6 +193,7 @@ trait PageLegacyTrait
*
* @param string $name
* @param string $value
* @return void
*/
public function addContentMeta($name, $value): void
{
@@ -197,7 +204,6 @@ trait PageLegacyTrait
* Return the whole contentMeta array as it currently stands
*
* @param string|null $name
*
* @return string|array|null
*/
public function getContentMeta($name = null)
@@ -213,7 +219,6 @@ trait PageLegacyTrait
* Sets the whole content meta array in one shot
*
* @param array $content_meta
*
* @return array
*/
public function setContentMeta($content_meta): array
@@ -246,32 +251,29 @@ trait PageLegacyTrait
public function file(): ?MarkdownFile
{
// TODO:
throw new \RuntimeException(__METHOD__ . '(): Not Implemented');
throw new RuntimeException(__METHOD__ . '(): Not Implemented');
}
abstract public function save($reorder = true);
/**
* Prepare move page to new location. Moves also everything that's under the current page.
*
* You need to call $this->save() in order to perform the move.
*
* @param PageInterface $parent New parent page.
*
* @return $this
*/
public function move(PageInterface $parent)
{
if ($this->route() === $parent->route()) {
throw new \RuntimeException('Failed: Cannot set page parent to self');
throw new RuntimeException('Failed: Cannot set page parent to self');
}
$rawRoute = $this->rawRoute();
if ($rawRoute && Utils::startsWith($parent->rawRoute(), $rawRoute)) {
throw new \RuntimeException('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');
}
// TODO:
throw new \RuntimeException(__METHOD__ . '(): Not Implemented');
throw new RuntimeException(__METHOD__ . '(): Not Implemented');
}
/**
@@ -281,7 +283,6 @@ trait PageLegacyTrait
* You need to call $this->save() in order to perform the move.
*
* @param PageInterface|null $parent New parent page.
*
* @return $this
*/
public function copy(PageInterface $parent = null)
@@ -300,7 +301,7 @@ trait PageLegacyTrait
$parentStorageKey = $k;
}
} else {
throw new \RuntimeException('Cannot copy page, parent is of unknown type');
throw new RuntimeException('Cannot copy page, parent is of unknown type');
}
} else {
$parent = $parentStorageKey
@@ -341,8 +342,6 @@ trait PageLegacyTrait
return $this;
}
abstract public function blueprints();
/**
* Get the blueprint name for this page. Use the blueprint form field if set
*
@@ -358,6 +357,7 @@ trait PageLegacyTrait
/**
* Validate page header.
*
* @return void
* @throws Exception
*/
public function validate(): void
@@ -368,6 +368,8 @@ trait PageLegacyTrait
/**
* Filter page header from illegal contents.
*
* @return void
*/
public function filter(): void
{
@@ -422,7 +424,7 @@ trait PageLegacyTrait
{
$json = json_encode($this->toArray());
if (!is_string($json)) {
throw new \RuntimeException('Internal error');
throw new RuntimeException('Internal error');
}
return $json;
@@ -431,8 +433,7 @@ trait PageLegacyTrait
/**
* Gets and sets the name field. If no name field is set, it will return 'default.md'.
*
* @param string $var The name of this page.
*
* @param string|null $var The name of this page.
* @return string The name of this page.
*/
public function name($var = null): string
@@ -473,8 +474,7 @@ trait PageLegacyTrait
* Gets and sets the template field. This is used to find the correct Twig template file to render.
* If no field is set, it will return the name without the .md extension
*
* @param string $var the template name
*
* @param string|null $var the template name
* @return string the template name
*/
public function template($var = null): string
@@ -493,7 +493,6 @@ trait PageLegacyTrait
* (e.g. `html`, `json`, `xml`, etc).
*
* @param string|null $var
*
* @return string
*/
public function templateFormat($var = null): string
@@ -511,7 +510,6 @@ trait PageLegacyTrait
* Gets and sets the extension field.
*
* @param string|null $var
*
* @return string
*/
public function extension($var = null): string
@@ -532,8 +530,7 @@ trait PageLegacyTrait
/**
* Gets and sets the expires field. If not set will return the default
*
* @param int $var The new expires value.
*
* @param int|null $var The new expires value.
* @return int The expires value
*/
public function expires($var = null): int
@@ -565,6 +562,10 @@ trait PageLegacyTrait
);
}
/**
* @param bool|null $var
* @return bool|null
*/
public function ssl($var = null): ?bool
{
return $this->loadHeaderProperty(
@@ -590,8 +591,7 @@ trait PageLegacyTrait
* Function to merge page metadata tags and build an array of Metadata objects
* that can then be rendered in the page.
*
* @param array $var an Array of metadata values to set
*
* @param array|null $var an Array of metadata values to set
* @return array an Array of metadata values for the page
*/
public function metadata($var = null): array
@@ -632,7 +632,7 @@ trait PageLegacyTrait
}
} elseif ($value) {
// If it this is a standard meta data type
if (\in_array($key, $header_tag_http_equivs, true)) {
if (in_array($key, $header_tag_http_equivs, true)) {
$this->_metadata[$key] = [
'http_equiv' => $key,
'content' => htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8')
@@ -673,8 +673,7 @@ trait PageLegacyTrait
/**
* Gets and sets the option to show the etag header for the page.
*
* @param bool $var show etag header
*
* @param bool|null $var show etag header
* @return bool show etag header
*/
public function eTag($var = null): bool
@@ -691,15 +690,14 @@ trait PageLegacyTrait
/**
* Gets and sets the path to the .md file for this Page object.
*
* @param string $var the file path
*
* @param string|null $var the file path
* @return string|null the file path
*/
public function filePath($var = null): ?string
{
if (null !== $var) {
// TODO:
throw new \RuntimeException(__METHOD__ . '(string): Not Implemented');
throw new RuntimeException(__METHOD__ . '(string): Not Implemented');
}
$folder = $this->getStorageFolder();
@@ -734,8 +732,7 @@ trait PageLegacyTrait
/**
* Gets and sets the order by which any sub-pages should be sorted.
*
* @param string $var the order, either "asc" or "desc"
*
* @param string|null $var the order, either "asc" or "desc"
* @return string the order, either "asc" or "desc"
*/
public function orderDir($var = null): string
@@ -757,8 +754,7 @@ trait PageLegacyTrait
* date - is the order based on the date set in the pages
* folder - is the order based on the name of the folder with any numerics omitted
*
* @param string $var supported options include "default", "title", "date", and "folder"
*
* @param string|null $var supported options include "default", "title", "date", and "folder"
* @return string supported options include "default", "title", "date", and "folder"
*/
public function orderBy($var = null): string
@@ -775,8 +771,7 @@ trait PageLegacyTrait
/**
* Gets the manual order set in the header.
*
* @param string $var supported options include "default", "title", "date", and "folder"
*
* @param string|null $var supported options include "default", "title", "date", and "folder"
* @return array
*/
public function orderManual($var = null): array
@@ -794,8 +789,7 @@ trait PageLegacyTrait
* Gets and sets the maxCount field which describes how many sub-pages should be displayed if the
* sub_pages header property is set for this page object.
*
* @param int $var the maximum number of sub-pages
*
* @param int|null $var the maximum number of sub-pages
* @return int the maximum number of sub-pages
*/
public function maxCount($var = null): int
@@ -812,7 +806,7 @@ trait PageLegacyTrait
/**
* Gets and sets the modular var that helps identify this page is a modular child
*
* @param bool $var true if modular_twig
* @param bool|null $var true if modular_twig
* @return bool true if modular_twig
* @deprecated 1.7 Use ->isModule() or ->modularTwig() method instead.
*/
@@ -827,8 +821,7 @@ trait PageLegacyTrait
* Gets and sets the modular_twig var that helps identify this page as a modular child page that will need
* twig processing handled differently from a regular page.
*
* @param bool $var true if modular_twig
*
* @param bool|null $var true if modular_twig
* @return bool true if modular_twig
*/
public function modularTwig($var = null): bool
@@ -919,8 +912,7 @@ trait PageLegacyTrait
* Returns the adjacent sibling based on a direction.
*
* @param int $direction either -1 or +1
*
* @return PageInterface|false the sibling page
* @return PageInterface|false the sibling page
*/
public function adjacentSibling($direction = 1)
{
@@ -930,14 +922,20 @@ trait PageLegacyTrait
$children = $children->withKeyField();
}
return $children instanceof PageCollectionInterface ? $children->adjacentSibling($this->getKey(), $direction) : false;
if ($children instanceof PageCollectionInterface) {
$child = $children->adjacentSibling($this->getKey(), $direction);
if ($child instanceof PageInterface) {
return $child;
}
}
return false;
}
/**
* Helper method to return an ancestor page.
*
* @param string|null $lookup Name of the parent folder
*
* @return PageInterface|null page you were looking for if it exists
*/
public function ancestor($lookup = null)
@@ -953,7 +951,6 @@ trait PageLegacyTrait
* page object is returned.
*
* @param string $field Name of the parent folder
*
* @return PageInterface|null
*/
public function inherited($field)
@@ -970,12 +967,11 @@ trait PageLegacyTrait
* first occurrence of an ancestor field will be returned if at all.
*
* @param string $field Name of the parent folder
*
* @return array
*/
public function inheritedField($field): array
{
[$inherited, $currentParams] = $this->getInheritedParams($field);
[, $currentParams] = $this->getInheritedParams($field);
return $currentParams;
}
@@ -984,14 +980,13 @@ trait PageLegacyTrait
* Method that contains shared logic for inherited() and inheritedField()
*
* @param string $field Name of the parent folder
*
* @return array
*/
protected function getInheritedParams($field): array
{
/** @var Pages $pages */
$pages = Grav::instance()['pages'];
/** @var Pages $pages */
$inherited = $pages->inherited($this->getProperty('parent_route'), $field);
$inheritedParams = $inherited ? (array)$inherited->value('header.' . $field) : [];
$currentParams = (array)$this->getFormValue('header.' . $field);
@@ -1007,7 +1002,6 @@ trait PageLegacyTrait
*
* @param string $url the url of the page
* @param bool $all
*
* @return PageInterface|null page you were looking for if it exists
*/
public function find($url, $all = false)
@@ -1023,9 +1017,8 @@ trait PageLegacyTrait
*
* @param string|array $params
* @param bool $pagination
*
* @return PageCollectionInterface|Collection
* @throws \InvalidArgumentException
* @throws InvalidArgumentException
*/
public function collection($params = 'content', $pagination = true)
{
@@ -1033,7 +1026,7 @@ trait PageLegacyTrait
// Look into a page header field.
$params = (array)$this->getFormValue('header.' . $params);
} elseif (!is_array($params)) {
throw new \InvalidArgumentException('Argument should be either header variable name or array of parameters');
throw new InvalidArgumentException('Argument should be either header variable name or array of parameters');
}
if (!$pagination) {
@@ -1092,7 +1085,7 @@ trait PageLegacyTrait
public function getOriginal()
{
// TODO:
throw new \RuntimeException(__METHOD__ . '(): Not Implemented');
throw new RuntimeException(__METHOD__ . '(): Not Implemented');
}
/**

View File

@@ -17,6 +17,7 @@ use Grav\Common\Page\Pages;
use Grav\Common\Uri;
use Grav\Framework\Filesystem\Filesystem;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use function is_string;
/**
* Implements PageRoutableInterface
@@ -26,7 +27,7 @@ trait PageRoutableTrait
/** @var bool */
protected $root = false;
/** @var string */
/** @var string|null */
private $_route;
/** @var string|null */
private $_path;
@@ -56,7 +57,7 @@ trait PageRoutableTrait
* Gets and Sets whether or not this Page is routable, ie you can reach it via a URL.
* The page must be *routable* and *published*
*
* @param bool $var true if the page is routable
* @param bool|null $var true if the page is routable
* @return bool true if the page is routable
*/
public function routable($var = null): bool
@@ -253,7 +254,7 @@ trait PageRoutableTrait
/**
* Gets the route aliases for the page based on page headers.
*
* @param array $var list of route aliases
* @param array|null $var list of route aliases
* @return array The route aliases for the Page.
*/
public function routeAliases($var = null): array
@@ -292,7 +293,7 @@ trait PageRoutableTrait
/**
* Gets the redirect set in the header.
*
* @param string $var redirect url
* @param string|null $var redirect url
* @return string|null
*/
public function redirect($var = null): ?string
@@ -362,7 +363,7 @@ trait PageRoutableTrait
/**
* Get/set the folder.
*
* @param string $var Optional path, including numeric prefix.
* @param string|null $var Optional path, including numeric prefix.
* @return string|null
*/
public function folder($var = null): ?string
@@ -383,7 +384,7 @@ trait PageRoutableTrait
/**
* Get/set the folder.
*
* @param string $var Optional path, including numeric prefix.
* @param string|null $var Optional path, including numeric prefix.
* @return string|null
*/
public function parentStorageKey($var = null): ?string

View File

@@ -13,6 +13,7 @@ use Grav\Common\Grav;
use Grav\Common\Language\Language;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
use function is_bool;
/**
* Implements PageTranslateInterface
@@ -82,19 +83,18 @@ trait PageTranslateTrait
if ($includeDefault) {
$languages[] = '';
} elseif (isset($translated[''])) {
$translated[$language->getDefault()] = $translated[''];
$default = $language->getDefault();
if (is_bool($default)) {
$default = '';
}
$translated[$default] = $translated[''];
unset($translated['']);
}
$languages = array_fill_keys($languages, false);
$translated = array_fill_keys(array_keys($translated), true);
$all = array_replace($languages, $translated);
if (null === $all) {
throw new \RuntimeException('Unexpected result');
}
return $all;
return array_replace($languages, $translated);
}
/**
@@ -112,7 +112,11 @@ trait PageTranslateTrait
/** @var Language $language */
$language = $grav['language'];
$languages[$language->getDefault()] = $languages[''];
$default = $language->getDefault();
if (is_bool($default)) {
$default = '';
}
$languages[$default] = $languages[''];
unset($languages['']);
}
@@ -152,10 +156,6 @@ trait PageTranslateTrait
}
}
if ($language === '') {
}
return $language;
}
@@ -212,7 +212,7 @@ trait PageTranslateTrait
/**
* Get page language
*
* @param string $var
* @param string|null $var
* @return string|null
*/
public function language($var = null): ?string

View File

@@ -27,6 +27,7 @@ use function count;
use function is_scalar;
use function is_string;
use function mb_strpos;
use function mb_substr;
/**
* Class FolderStorage
@@ -322,7 +323,7 @@ class FolderStorage extends AbstractFilesystemStorage
{
$keys = [
'key' => $key,
'key:2' => \mb_substr($key, 0, 2),
'key:2' => mb_substr($key, 0, 2),
];
if ($variations) {
$keys['file'] = $this->dataFile;

View File

@@ -23,6 +23,9 @@ use Grav\Framework\Form\FormFlashFile;
use Psr\Http\Message\UploadedFileInterface;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use function is_array;
use function is_object;
use function is_string;
/**
* Implements Grav Page content and header manipulation methods.
@@ -53,7 +56,7 @@ trait FlexMediaTrait
}
/**
* @return MediaCollectionInterface|MediaUploadInterface
* @return MediaCollectionInterface
*/
public function getMedia()
{
@@ -76,7 +79,7 @@ trait FlexMediaTrait
// Load settings for the field.
$schema = $this->getBlueprint()->schema();
$settings = $schema ? $schema->getProperty($field) : null;
$settings = $field && is_object($schema) ? (array)$schema->getProperty($field) : null;
if (isset($settings['type']) && \in_array($settings['type'], ['avatar', 'file', 'pagemedia'])) {
// Set destination folder.

View File

@@ -11,10 +11,11 @@ declare(strict_types=1);
namespace Grav\Framework\Flex\Traits;
use Grav\Framework\Flex\Flex;
use Grav\Framework\Flex\FlexCollection;
use Grav\Framework\Flex\FlexDirectory;
use Grav\Framework\Flex\Interfaces\FlexCollectionInterface;
use RuntimeException;
use function in_array;
/**
* Trait GravTrait
@@ -35,7 +36,7 @@ trait FlexRelatedDirectoryTrait
/** @var FlexCollection $collection */
$collection = $collection->filter(static function ($object) use ($list) {
return \in_array($object->id, $list, true);
return in_array($object->id, $list, true);
});
return $collection;
@@ -44,13 +45,13 @@ trait FlexRelatedDirectoryTrait
/**
* @param string $type
* @return FlexDirectory
* @throws \RuntimeException
* @throws RuntimeException
*/
protected function getRelatedDirectory($type): FlexDirectory
{
$directory = $this->getFlexContainer()->getDirectory($type);
if (!$directory) {
throw new \RuntimeException(ucfirst($type). ' directory does not exist!');
throw new RuntimeException(ucfirst($type). ' directory does not exist!');
}
return $directory;