repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Acl/Access.php | system/src/Grav/Framework/Acl/Access.php | <?php
/**
* @package Grav\Framework\Acl
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Acl;
use ArrayIterator;
use Countable;
use Grav\Common\Utils;
use IteratorAggregate;
use JsonSerializable;
use Traversable;
use function count;
use function is_array;
use function is_bool;
use function is_string;
use function strlen;
/**
* Class Access
* @package Grav\Framework\Acl
* @implements IteratorAggregate<string,bool|array|null>
*/
class Access implements JsonSerializable, IteratorAggregate, Countable
{
/** @var string */
private $name;
/** @var array */
private $rules;
/** @var array */
private $ops;
/** @var array<string,bool|array|null> */
private $acl = [];
/** @var array */
private $inherited = [];
/**
* Access constructor.
* @param string|array|null $acl
* @param array|null $rules
* @param string $name
*/
public function __construct($acl = null, array $rules = null, string $name = '')
{
$this->name = $name;
$this->rules = $rules ?? [];
$this->ops = ['+' => true, '-' => false];
if (is_string($acl)) {
$this->acl = $this->resolvePermissions($acl);
} elseif (is_array($acl)) {
$this->acl = $this->normalizeAcl($acl);
}
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @param Access $parent
* @param string|null $name
* @return void
*/
public function inherit(Access $parent, string $name = null)
{
// Remove cached null actions from acl.
$acl = $this->getAllActions();
// Get only inherited actions.
$inherited = array_diff_key($parent->getAllActions(), $acl);
$this->inherited += $parent->inherited + array_fill_keys(array_keys($inherited), $name ?? $parent->getName());
$this->acl = array_replace($acl, $inherited);
}
/**
* Checks user authorization to the action.
*
* @param string $action
* @param string|null $scope
* @return bool|null
*/
public function authorize(string $action, string $scope = null): ?bool
{
if (null !== $scope) {
$action = $scope !== 'test' ? "{$scope}.{$action}" : $action;
}
return $this->get($action);
}
/**
* @return array
*/
public function toArray(): array
{
return Utils::arrayUnflattenDotNotation($this->acl);
}
/**
* @return array
*/
public function getAllActions(): array
{
return array_filter($this->acl, static function($val) { return $val !== null; });
}
/**
* @return array
*/
public function jsonSerialize(): array
{
return $this->toArray();
}
/**
* @param string $action
* @return bool|null
*/
public function get(string $action)
{
// Get access value.
if (isset($this->acl[$action])) {
return $this->acl[$action];
}
// If no value is defined, check the parent access (all true|false).
$pos = strrpos($action, '.');
$value = $pos ? $this->get(substr($action, 0, $pos)) : null;
// Cache result for faster lookup.
$this->acl[$action] = $value;
return $value;
}
/**
* @param string $action
* @return bool
*/
public function isInherited(string $action): bool
{
return isset($this->inherited[$action]);
}
/**
* @param string $action
* @return string|null
*/
public function getInherited(string $action): ?string
{
return $this->inherited[$action] ?? null;
}
/**
* @return Traversable
*/
public function getIterator(): Traversable
{
return new ArrayIterator($this->acl);
}
/**
* @return int
*/
public function count(): int
{
return count($this->acl);
}
/**
* @param array $acl
* @return array
*/
protected function normalizeAcl(array $acl): array
{
if (empty($acl)) {
return [];
}
// Normalize access control list.
$list = [];
foreach (Utils::arrayFlattenDotNotation($acl) as $key => $value) {
if (is_bool($value)) {
$list[$key] = $value;
} elseif ($value === 0 || $value === 1) {
$list[$key] = (bool)$value;
} elseif($value === null) {
continue;
} elseif ($this->rules && is_string($value)) {
$list[$key] = $this->resolvePermissions($value);
} elseif (Utils::isPositive($value)) {
$list[$key] = true;
} elseif (Utils::isNegative($value)) {
$list[$key] = false;
}
}
return $list;
}
/**
* @param string $access
* @return array
*/
protected function resolvePermissions(string $access): array
{
$len = strlen($access);
$op = true;
$list = [];
for($count = 0; $count < $len; $count++) {
$letter = $access[$count];
if (isset($this->rules[$letter])) {
$list[$this->rules[$letter]] = $op;
$op = true;
} elseif (isset($this->ops[$letter])) {
$op = $this->ops[$letter];
}
}
return $list;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Acl/RecursiveActionIterator.php | system/src/Grav/Framework/Acl/RecursiveActionIterator.php | <?php
/**
* @package Grav\Framework\Acl
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Acl;
use RecursiveIterator;
use RocketTheme\Toolbox\ArrayTraits\Constructor;
use RocketTheme\Toolbox\ArrayTraits\Countable;
use RocketTheme\Toolbox\ArrayTraits\Iterator;
/**
* Class Action
* @package Grav\Framework\Acl
* @implements RecursiveIterator<string,Action>
*/
class RecursiveActionIterator implements RecursiveIterator, \Countable
{
use Constructor, Iterator, Countable;
public $items;
/**
* @see \Iterator::key()
* @return string
*/
#[\ReturnTypeWillChange]
public function key()
{
/** @var Action $current */
$current = $this->current();
return $current->name;
}
/**
* @see \RecursiveIterator::hasChildren()
* @return bool
*/
public function hasChildren(): bool
{
/** @var Action $current */
$current = $this->current();
return $current->hasChildren();
}
/**
* @see \RecursiveIterator::getChildren()
* @return RecursiveActionIterator
*/
public function getChildren(): self
{
/** @var Action $current */
$current = $this->current();
return new static($current->getChildren());
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Acl/PermissionsReader.php | system/src/Grav/Framework/Acl/PermissionsReader.php | <?php
/**
* @package Grav\Framework\Acl
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Acl;
use Grav\Common\File\CompiledYamlFile;
use RuntimeException;
use stdClass;
use function is_array;
/**
* Class PermissionsReader
* @package Grav\Framework\Acl
*/
class PermissionsReader
{
/** @var array */
protected static $types;
/**
* @param string $filename
* @return Action[]
*/
public static function fromYaml(string $filename): array
{
$content = CompiledYamlFile::instance($filename)->content();
$actions = $content['actions'] ?? [];
$types = $content['types'] ?? [];
return static::fromArray($actions, $types);
}
/**
* @param array $actions
* @param array $types
* @return Action[]
*/
public static function fromArray(array $actions, array $types): array
{
static::initTypes($types);
$list = [];
foreach (static::read($actions) as $type => $data) {
$list[$type] = new Action($type, $data);
}
return $list;
}
/**
* @param array $actions
* @param string $prefix
* @return array
*/
public static function read(array $actions, string $prefix = ''): array
{
$list = [];
foreach ($actions as $name => $action) {
$prefixName = $prefix . $name;
$list[$prefixName] = null;
// Support nested sets of actions.
if (isset($action['actions']) && is_array($action['actions'])) {
$innerList = static::read($action['actions'], "{$prefixName}.");
$list += $innerList;
}
unset($action['actions']);
// Add defaults if they exist.
$action = static::addDefaults($action);
// Build flat list of actions.
$list[$prefixName] = $action;
}
return $list;
}
/**
* @param array $types
* @return void
*/
protected static function initTypes(array $types)
{
static::$types = [];
$dependencies = [];
foreach ($types as $type => $defaults) {
$current = array_fill_keys((array)($defaults['use'] ?? null), null);
$defType = $defaults['type'] ?? $type;
if ($type !== $defType) {
$current[$defaults['type']] = null;
}
$dependencies[$type] = (object)$current;
}
// Build dependency tree.
foreach ($dependencies as $type => $dep) {
foreach (get_object_vars($dep) as $k => &$val) {
if (null === $val) {
$val = $dependencies[$k] ?? new stdClass();
}
}
unset($val);
}
$encoded = json_encode($dependencies);
if ($encoded === false) {
throw new RuntimeException('json_encode(): failed to encode dependencies');
}
$dependencies = json_decode($encoded, true);
foreach (static::getDependencies($dependencies) as $type) {
$defaults = $types[$type] ?? null;
if ($defaults) {
static::$types[$type] = static::addDefaults($defaults);
}
}
}
/**
* @param array $dependencies
* @return array
*/
protected static function getDependencies(array $dependencies): array
{
$list = [[]];
foreach ($dependencies as $name => $deps) {
$current = $deps ? static::getDependencies($deps) : [];
$current[] = $name;
$list[] = $current;
}
return array_unique(array_merge(...$list));
}
/**
* @param array $action
* @return array
*/
protected static function addDefaults(array $action): array
{
$scopes = [];
// Add used properties.
$use = (array)($action['use'] ?? null);
foreach ($use as $type) {
if (isset(static::$types[$type])) {
$used = static::$types[$type];
unset($used['type']);
$scopes[] = $used;
}
}
unset($action['use']);
// Add type defaults.
$type = $action['type'] ?? 'default';
$defaults = static::$types[$type] ?? null;
if (is_array($defaults)) {
$scopes[] = $defaults;
}
if ($scopes) {
$scopes[] = $action;
$action = array_replace_recursive(...$scopes);
$newType = $defaults['type'] ?? null;
if ($newType && $newType !== $type) {
$action['type'] = $newType;
}
}
return $action;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/File/DataFile.php | system/src/Grav/Framework/File/DataFile.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\File
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\File;
use Grav\Framework\File\Interfaces\FileFormatterInterface;
use RuntimeException;
use function is_string;
/**
* Class DataFile
* @package Grav\Framework\File
*/
class DataFile extends AbstractFile
{
/** @var FileFormatterInterface */
protected $formatter;
/**
* File constructor.
* @param string $filepath
* @param FileFormatterInterface $formatter
*/
public function __construct($filepath, FileFormatterInterface $formatter)
{
parent::__construct($filepath);
$this->formatter = $formatter;
}
/**
* {@inheritdoc}
* @see FileInterface::load()
*/
public function load()
{
$raw = parent::load();
try {
if (!is_string($raw)) {
throw new RuntimeException('Bad Data');
}
return $this->formatter->decode($raw);
} catch (RuntimeException $e) {
throw new RuntimeException(sprintf("Failed to load file '%s': %s", $this->getFilePath(), $e->getMessage()), $e->getCode(), $e);
}
}
/**
* {@inheritdoc}
* @see FileInterface::save()
*/
public function save($data): void
{
if (is_string($data)) {
// Make sure that the string is valid data.
try {
$this->formatter->decode($data);
} catch (RuntimeException $e) {
throw new RuntimeException(sprintf("Failed to save file '%s': %s", $this->getFilePath(), $e->getMessage()), $e->getCode(), $e);
}
$encoded = $data;
} else {
$encoded = $this->formatter->encode($data);
}
parent::save($encoded);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/File/AbstractFile.php | system/src/Grav/Framework/File/AbstractFile.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\File
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\File;
use Exception;
use Grav\Framework\Compat\Serializable;
use Grav\Framework\File\Interfaces\FileInterface;
use Grav\Framework\Filesystem\Filesystem;
use RuntimeException;
/**
* Class AbstractFile
* @package Grav\Framework\File
*/
class AbstractFile implements FileInterface
{
use Serializable;
/** @var Filesystem */
private $filesystem;
/** @var string */
private $filepath;
/** @var string|null */
private $filename;
/** @var string|null */
private $path;
/** @var string|null */
private $basename;
/** @var string|null */
private $extension;
/** @var resource|null */
private $handle;
/** @var bool */
private $locked = false;
/**
* @param string $filepath
* @param Filesystem|null $filesystem
*/
public function __construct(string $filepath, Filesystem $filesystem = null)
{
$this->filesystem = $filesystem ?? Filesystem::getInstance();
$this->setFilepath($filepath);
}
/**
* Unlock file when the object gets destroyed.
*/
#[\ReturnTypeWillChange]
public function __destruct()
{
if ($this->isLocked()) {
$this->unlock();
}
}
/**
* @return void
*/
#[\ReturnTypeWillChange]
public function __clone()
{
$this->handle = null;
$this->locked = false;
}
/**
* @return array
*/
final public function __serialize(): array
{
return ['filesystem_normalize' => $this->filesystem->getNormalization()] + $this->doSerialize();
}
/**
* @param array $data
* @return void
*/
final public function __unserialize(array $data): void
{
$this->filesystem = Filesystem::getInstance($data['filesystem_normalize'] ?? null);
$this->doUnserialize($data);
}
/**
* {@inheritdoc}
* @see FileInterface::getFilePath()
*/
public function getFilePath(): string
{
return $this->filepath;
}
/**
* {@inheritdoc}
* @see FileInterface::getPath()
*/
public function getPath(): string
{
if (null === $this->path) {
$this->setPathInfo();
}
return $this->path ?? '';
}
/**
* {@inheritdoc}
* @see FileInterface::getFilename()
*/
public function getFilename(): string
{
if (null === $this->filename) {
$this->setPathInfo();
}
return $this->filename ?? '';
}
/**
* {@inheritdoc}
* @see FileInterface::getBasename()
*/
public function getBasename(): string
{
if (null === $this->basename) {
$this->setPathInfo();
}
return $this->basename ?? '';
}
/**
* {@inheritdoc}
* @see FileInterface::getExtension()
*/
public function getExtension(bool $withDot = false): string
{
if (null === $this->extension) {
$this->setPathInfo();
}
return ($withDot ? '.' : '') . $this->extension;
}
/**
* {@inheritdoc}
* @see FileInterface::exists()
*/
public function exists(): bool
{
return is_file($this->filepath);
}
/**
* {@inheritdoc}
* @see FileInterface::getCreationTime()
*/
public function getCreationTime(): int
{
return is_file($this->filepath) ? (int)filectime($this->filepath) : time();
}
/**
* {@inheritdoc}
* @see FileInterface::getModificationTime()
*/
public function getModificationTime(): int
{
return is_file($this->filepath) ? (int)filemtime($this->filepath) : time();
}
/**
* {@inheritdoc}
* @see FileInterface::lock()
*/
public function lock(bool $block = true): bool
{
if (!$this->handle) {
if (!$this->mkdir($this->getPath())) {
throw new RuntimeException('Creating directory failed for ' . $this->filepath);
}
$this->handle = @fopen($this->filepath, 'cb+') ?: null;
if (!$this->handle) {
$error = error_get_last();
$message = $error['message'] ?? 'Unknown error';
throw new RuntimeException("Opening file for writing failed on error {$message}");
}
}
$lock = $block ? LOCK_EX : LOCK_EX | LOCK_NB;
// Some filesystems do not support file locks, only fail if another process holds the lock.
$this->locked = flock($this->handle, $lock, $wouldBlock) || !$wouldBlock;
return $this->locked;
}
/**
* {@inheritdoc}
* @see FileInterface::unlock()
*/
public function unlock(): bool
{
if (!$this->handle) {
return false;
}
if ($this->locked) {
flock($this->handle, LOCK_UN | LOCK_NB);
$this->locked = false;
}
fclose($this->handle);
$this->handle = null;
return true;
}
/**
* {@inheritdoc}
* @see FileInterface::isLocked()
*/
public function isLocked(): bool
{
return $this->locked;
}
/**
* {@inheritdoc}
* @see FileInterface::isReadable()
*/
public function isReadable(): bool
{
return is_readable($this->filepath) && is_file($this->filepath);
}
/**
* {@inheritdoc}
* @see FileInterface::isWritable()
*/
public function isWritable(): bool
{
if (!file_exists($this->filepath)) {
return $this->isWritablePath($this->getPath());
}
return is_writable($this->filepath) && is_file($this->filepath);
}
/**
* {@inheritdoc}
* @see FileInterface::load()
*/
public function load()
{
return file_get_contents($this->filepath);
}
/**
* {@inheritdoc}
* @see FileInterface::save()
*/
public function save($data): void
{
$filepath = $this->filepath;
$dir = $this->getPath();
if (!$this->mkdir($dir)) {
throw new RuntimeException('Creating directory failed for ' . $filepath);
}
try {
if ($this->handle) {
$tmp = true;
// As we are using non-truncating locking, make sure that the file is empty before writing.
if (@ftruncate($this->handle, 0) === false || @fwrite($this->handle, $data) === false) {
// Writing file failed, throw an error.
$tmp = false;
}
} else {
// Support for symlinks.
$realpath = is_link($filepath) ? realpath($filepath) : $filepath;
if ($realpath === false) {
throw new RuntimeException('Failed to save file ' . $filepath);
}
// Create file with a temporary name and rename it to make the save action atomic.
$tmp = $this->tempname($realpath);
if (@file_put_contents($tmp, $data) === false) {
$tmp = false;
} elseif (@rename($tmp, $realpath) === false) {
@unlink($tmp);
$tmp = false;
}
}
} catch (Exception $e) {
$tmp = false;
}
if ($tmp === false) {
throw new RuntimeException('Failed to save file ' . $filepath);
}
// Touch the directory as well, thus marking it modified.
@touch($dir);
}
/**
* {@inheritdoc}
* @see FileInterface::rename()
*/
public function rename(string $path): bool
{
if ($this->exists() && !@rename($this->filepath, $path)) {
return false;
}
$this->setFilepath($path);
return true;
}
/**
* {@inheritdoc}
* @see FileInterface::delete()
*/
public function delete(): bool
{
return @unlink($this->filepath);
}
/**
* @param string $dir
* @return bool
* @throws RuntimeException
* @internal
*/
protected function mkdir(string $dir): bool
{
// Silence error for open_basedir; should fail in mkdir instead.
if (@is_dir($dir)) {
return true;
}
$success = @mkdir($dir, 0777, true);
if (!$success) {
// Take yet another look, make sure that the folder doesn't exist.
clearstatcache(true, $dir);
if (!@is_dir($dir)) {
return false;
}
}
return true;
}
/**
* @return array
*/
protected function doSerialize(): array
{
return [
'filepath' => $this->filepath
];
}
/**
* @param array $serialized
* @return void
*/
protected function doUnserialize(array $serialized): void
{
$this->setFilepath($serialized['filepath']);
}
/**
* @param string $filepath
*/
protected function setFilepath(string $filepath): void
{
$this->filepath = $filepath;
$this->filename = null;
$this->basename = null;
$this->path = null;
$this->extension = null;
}
protected function setPathInfo(): void
{
/** @var array $pathInfo */
$pathInfo = $this->filesystem->pathinfo($this->filepath);
$this->filename = $pathInfo['filename'] ?? null;
$this->basename = $pathInfo['basename'] ?? null;
$this->path = $pathInfo['dirname'] ?? null;
$this->extension = $pathInfo['extension'] ?? null;
}
/**
* @param string $dir
* @return bool
* @internal
*/
protected function isWritablePath(string $dir): bool
{
if ($dir === '') {
return false;
}
if (!file_exists($dir)) {
// Recursively look up in the directory tree.
return $this->isWritablePath($this->filesystem->parent($dir));
}
return is_dir($dir) && is_writable($dir);
}
/**
* @param string $filename
* @param int $length
* @return string
*/
protected function tempname(string $filename, int $length = 5)
{
do {
$test = $filename . substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length);
} while (file_exists($test));
return $test;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/File/YamlFile.php | system/src/Grav/Framework/File/YamlFile.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\File
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\File;
use Grav\Framework\File\Formatter\YamlFormatter;
/**
* Class YamlFile
* @package Grav\Framework\File
*/
class YamlFile extends DataFile
{
/**
* File constructor.
* @param string $filepath
* @param YamlFormatter $formatter
*/
public function __construct($filepath, YamlFormatter $formatter)
{
parent::__construct($filepath, $formatter);
}
/**
* @return array
*/
public function load(): array
{
/** @var array */
return parent::load();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/File/MarkdownFile.php | system/src/Grav/Framework/File/MarkdownFile.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\File
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\File;
use Grav\Framework\File\Formatter\MarkdownFormatter;
/**
* Class MarkdownFile
* @package Grav\Framework\File
*/
class MarkdownFile extends DataFile
{
/**
* File constructor.
* @param string $filepath
* @param MarkdownFormatter $formatter
*/
public function __construct($filepath, MarkdownFormatter $formatter)
{
parent::__construct($filepath, $formatter);
}
/**
* @return array
*/
public function load(): array
{
/** @var array */
return parent::load();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/File/JsonFile.php | system/src/Grav/Framework/File/JsonFile.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\File
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\File;
use Grav\Framework\File\Formatter\JsonFormatter;
/**
* Class JsonFile
* @package Grav\Framework\File
*/
class JsonFile extends DataFile
{
/**
* File constructor.
* @param string $filepath
* @param JsonFormatter $formatter
*/
public function __construct($filepath, JsonFormatter $formatter)
{
parent::__construct($filepath, $formatter);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/File/IniFile.php | system/src/Grav/Framework/File/IniFile.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\File
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\File;
use Grav\Framework\File\Formatter\IniFormatter;
/**
* Class IniFile
* @package RocketTheme\Toolbox\File
*/
class IniFile extends DataFile
{
/**
* File constructor.
* @param string $filepath
* @param IniFormatter $formatter
*/
public function __construct($filepath, IniFormatter $formatter)
{
parent::__construct($filepath, $formatter);
}
/**
* @return array
*/
public function load(): array
{
/** @var array */
return parent::load();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/File/CsvFile.php | system/src/Grav/Framework/File/CsvFile.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\File
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\File;
use Grav\Framework\File\Formatter\CsvFormatter;
/**
* Class IniFile
* @package RocketTheme\Toolbox\File
*/
class CsvFile extends DataFile
{
/**
* File constructor.
* @param string $filepath
* @param CsvFormatter $formatter
*/
public function __construct($filepath, CsvFormatter $formatter)
{
parent::__construct($filepath, $formatter);
}
/**
* @return array
*/
public function load(): array
{
/** @var array */
return parent::load();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/File/File.php | system/src/Grav/Framework/File/File.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\File
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\File;
use RuntimeException;
use function is_string;
/**
* Class File
* @package Grav\Framework\File
*/
class File extends AbstractFile
{
/**
* {@inheritdoc}
* @see FileInterface::save()
*/
public function save($data): void
{
if (!is_string($data)) {
throw new RuntimeException('Cannot save data, string required');
}
parent::save($data);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/File/Formatter/IniFormatter.php | system/src/Grav/Framework/File/Formatter/IniFormatter.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\File\Formatter
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\File\Formatter;
use Grav\Framework\File\Interfaces\FileFormatterInterface;
use RuntimeException;
/**
* Class IniFormatter
* @package Grav\Framework\File\Formatter
*/
class IniFormatter extends AbstractFormatter
{
/**
* IniFormatter constructor.
* @param array $config
*/
public function __construct(array $config = [])
{
$config += [
'file_extension' => '.ini'
];
parent::__construct($config);
}
/**
* {@inheritdoc}
* @see FileFormatterInterface::encode()
*/
public function encode($data): string
{
$string = '';
foreach ($data as $key => $value) {
$string .= $key . '="' . preg_replace(
['/"/', '/\\\/', "/\t/", "/\n/", "/\r/"],
['\"', '\\\\', '\t', '\n', '\r'],
$value
) . "\"\n";
}
return $string;
}
/**
* {@inheritdoc}
* @see FileFormatterInterface::decode()
*/
public function decode($data): array
{
$decoded = @parse_ini_string($data);
if ($decoded === false) {
throw new RuntimeException('Decoding INI failed');
}
return $decoded;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/File/Formatter/MarkdownFormatter.php | system/src/Grav/Framework/File/Formatter/MarkdownFormatter.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\File\Formatter
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\File\Formatter;
use Grav\Framework\File\Interfaces\FileFormatterInterface;
use RuntimeException;
/**
* Class MarkdownFormatter
* @package Grav\Framework\File\Formatter
*/
class MarkdownFormatter extends AbstractFormatter
{
/** @var FileFormatterInterface */
private $headerFormatter;
public function __construct(array $config = [], FileFormatterInterface $headerFormatter = null)
{
$config += [
'file_extension' => '.md',
'header' => 'header',
'body' => 'markdown',
'raw' => 'frontmatter',
'yaml' => ['inline' => 20]
];
parent::__construct($config);
$this->headerFormatter = $headerFormatter ?? new YamlFormatter($config['yaml']);
}
/**
* Returns header field used in both encode() and decode().
*
* @return string
*/
public function getHeaderField(): string
{
return $this->getConfig('header');
}
/**
* Returns body field used in both encode() and decode().
*
* @return string
*/
public function getBodyField(): string
{
return $this->getConfig('body');
}
/**
* Returns raw field used in both encode() and decode().
*
* @return string
*/
public function getRawField(): string
{
return $this->getConfig('raw');
}
/**
* Returns header formatter object used in both encode() and decode().
*
* @return FileFormatterInterface
*/
public function getHeaderFormatter(): FileFormatterInterface
{
return $this->headerFormatter;
}
/**
* {@inheritdoc}
* @see FileFormatterInterface::encode()
*/
public function encode($data): string
{
$headerVar = $this->getHeaderField();
$bodyVar = $this->getBodyField();
$header = isset($data[$headerVar]) ? (array) $data[$headerVar] : [];
$body = isset($data[$bodyVar]) ? (string) $data[$bodyVar] : '';
// Create Markdown file with YAML header.
$encoded = '';
if ($header) {
$encoded = "---\n" . trim($this->getHeaderFormatter()->encode($data['header'])) . "\n---\n\n";
}
$encoded .= $body;
// Normalize line endings to Unix style.
$encoded = preg_replace("/(\r\n|\r)/u", "\n", $encoded);
if (null === $encoded) {
throw new RuntimeException('Encoding markdown failed');
}
return $encoded;
}
/**
* {@inheritdoc}
* @see FileFormatterInterface::decode()
*/
public function decode($data): array
{
$headerVar = $this->getHeaderField();
$bodyVar = $this->getBodyField();
$rawVar = $this->getRawField();
// Define empty content
$content = [
$headerVar => [],
$bodyVar => ''
];
$headerRegex = "/^---\n(.+?)\n---\n{0,}(.*)$/uis";
// Normalize line endings to Unix style.
$data = preg_replace("/(\r\n|\r)/u", "\n", $data);
if (null === $data) {
throw new RuntimeException('Decoding markdown failed');
}
// Parse header.
preg_match($headerRegex, ltrim($data), $matches);
if (empty($matches)) {
$content[$bodyVar] = $data;
} else {
// Normalize frontmatter.
$frontmatter = preg_replace("/\n\t/", "\n ", $matches[1]);
if ($rawVar) {
$content[$rawVar] = $frontmatter;
}
$content[$headerVar] = $this->getHeaderFormatter()->decode($frontmatter);
$content[$bodyVar] = $matches[2];
}
return $content;
}
public function __serialize(): array
{
return parent::__serialize() + ['headerFormatter' => $this->headerFormatter];
}
public function __unserialize(array $data): void
{
parent::__unserialize($data);
$this->headerFormatter = $data['headerFormatter'] ?? new YamlFormatter(['inline' => 20]);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/File/Formatter/YamlFormatter.php | system/src/Grav/Framework/File/Formatter/YamlFormatter.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\File\Formatter
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\File\Formatter;
use Grav\Framework\File\Interfaces\FileFormatterInterface;
use RuntimeException;
use Symfony\Component\Yaml\Exception\DumpException;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml as YamlParser;
use RocketTheme\Toolbox\Compat\Yaml\Yaml as FallbackYamlParser;
use function function_exists;
/**
* Class YamlFormatter
* @package Grav\Framework\File\Formatter
*/
class YamlFormatter extends AbstractFormatter
{
/**
* YamlFormatter constructor.
* @param array $config
*/
public function __construct(array $config = [])
{
$config += [
'file_extension' => '.yaml',
'inline' => 5,
'indent' => 2,
'native' => true,
'compat' => true
];
parent::__construct($config);
}
/**
* @return int
*/
public function getInlineOption(): int
{
return $this->getConfig('inline');
}
/**
* @return int
*/
public function getIndentOption(): int
{
return $this->getConfig('indent');
}
/**
* @return bool
*/
public function useNativeDecoder(): bool
{
return $this->getConfig('native');
}
/**
* @return bool
*/
public function useCompatibleDecoder(): bool
{
return $this->getConfig('compat');
}
/**
* @param array $data
* @param int|null $inline
* @param int|null $indent
* @return string
* @see FileFormatterInterface::encode()
*/
public function encode($data, $inline = null, $indent = null): string
{
try {
return YamlParser::dump(
$data,
$inline ? (int) $inline : $this->getInlineOption(),
$indent ? (int) $indent : $this->getIndentOption(),
YamlParser::DUMP_EXCEPTION_ON_INVALID_TYPE
);
} catch (DumpException $e) {
throw new RuntimeException('Encoding YAML failed: ' . $e->getMessage(), 0, $e);
}
}
/**
* {@inheritdoc}
* @see FileFormatterInterface::decode()
*/
public function decode($data): array
{
// Try native PECL YAML PHP extension first if available.
if (function_exists('yaml_parse') && $this->useNativeDecoder()) {
// Safely decode YAML.
$saved = @ini_get('yaml.decode_php');
@ini_set('yaml.decode_php', '0');
$decoded = @yaml_parse($data);
if ($saved !== false) {
@ini_set('yaml.decode_php', $saved);
}
if ($decoded !== false) {
return (array) $decoded;
}
}
try {
return (array) YamlParser::parse($data);
} catch (ParseException $e) {
if ($this->useCompatibleDecoder()) {
return (array) FallbackYamlParser::parse($data);
}
throw new RuntimeException('Decoding YAML failed: ' . $e->getMessage(), 0, $e);
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/File/Formatter/SerializeFormatter.php | system/src/Grav/Framework/File/Formatter/SerializeFormatter.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\File\Formatter
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\File\Formatter;
use Grav\Framework\File\Interfaces\FileFormatterInterface;
use RuntimeException;
use stdClass;
use function is_array;
use function is_string;
/**
* Class SerializeFormatter
* @package Grav\Framework\File\Formatter
*/
class SerializeFormatter extends AbstractFormatter
{
/**
* IniFormatter constructor.
* @param array $config
*/
public function __construct(array $config = [])
{
$config += [
'file_extension' => '.ser',
'decode_options' => ['allowed_classes' => [stdClass::class]]
];
parent::__construct($config);
}
/**
* Returns options used in decode().
*
* By default only allow stdClass class.
*
* @return array
*/
public function getOptions()
{
return $this->getConfig('decode_options');
}
/**
* {@inheritdoc}
* @see FileFormatterInterface::encode()
*/
public function encode($data): string
{
return serialize($this->preserveLines($data, ["\n", "\r"], ['\\n', '\\r']));
}
/**
* {@inheritdoc}
* @see FileFormatterInterface::decode()
*/
public function decode($data)
{
$classes = $this->getOptions()['allowed_classes'] ?? false;
$decoded = @unserialize($data, ['allowed_classes' => $classes]);
if ($decoded === false && $data !== serialize(false)) {
throw new RuntimeException('Decoding serialized data failed');
}
return $this->preserveLines($decoded, ['\\n', '\\r'], ["\n", "\r"]);
}
/**
* Preserve new lines, recursive function.
*
* @param mixed $data
* @param array $search
* @param array $replace
* @return mixed
*/
protected function preserveLines($data, array $search, array $replace)
{
if (is_string($data)) {
$data = str_replace($search, $replace, $data);
} elseif (is_array($data)) {
foreach ($data as &$value) {
$value = $this->preserveLines($value, $search, $replace);
}
unset($value);
}
return $data;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/File/Formatter/JsonFormatter.php | system/src/Grav/Framework/File/Formatter/JsonFormatter.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\File\Formatter
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\File\Formatter;
use Grav\Framework\File\Interfaces\FileFormatterInterface;
use RuntimeException;
use function is_int;
use function is_string;
/**
* Class JsonFormatter
* @package Grav\Framework\File\Formatter
*/
class JsonFormatter extends AbstractFormatter
{
/** @var array */
protected $encodeOptions = [
'JSON_FORCE_OBJECT' => JSON_FORCE_OBJECT,
'JSON_HEX_QUOT' => JSON_HEX_QUOT,
'JSON_HEX_TAG' => JSON_HEX_TAG,
'JSON_HEX_AMP' => JSON_HEX_AMP,
'JSON_HEX_APOS' => JSON_HEX_APOS,
'JSON_INVALID_UTF8_IGNORE' => JSON_INVALID_UTF8_IGNORE,
'JSON_INVALID_UTF8_SUBSTITUTE' => JSON_INVALID_UTF8_SUBSTITUTE,
'JSON_NUMERIC_CHECK' => JSON_NUMERIC_CHECK,
'JSON_PARTIAL_OUTPUT_ON_ERROR' => JSON_PARTIAL_OUTPUT_ON_ERROR,
'JSON_PRESERVE_ZERO_FRACTION' => JSON_PRESERVE_ZERO_FRACTION,
'JSON_PRETTY_PRINT' => JSON_PRETTY_PRINT,
'JSON_UNESCAPED_LINE_TERMINATORS' => JSON_UNESCAPED_LINE_TERMINATORS,
'JSON_UNESCAPED_SLASHES' => JSON_UNESCAPED_SLASHES,
'JSON_UNESCAPED_UNICODE' => JSON_UNESCAPED_UNICODE,
//'JSON_THROW_ON_ERROR' => JSON_THROW_ON_ERROR // PHP 7.3
];
/** @var array */
protected $decodeOptions = [
'JSON_BIGINT_AS_STRING' => JSON_BIGINT_AS_STRING,
'JSON_INVALID_UTF8_IGNORE' => JSON_INVALID_UTF8_IGNORE,
'JSON_INVALID_UTF8_SUBSTITUTE' => JSON_INVALID_UTF8_SUBSTITUTE,
'JSON_OBJECT_AS_ARRAY' => JSON_OBJECT_AS_ARRAY,
//'JSON_THROW_ON_ERROR' => JSON_THROW_ON_ERROR // PHP 7.3
];
public function __construct(array $config = [])
{
$config += [
'file_extension' => '.json',
'encode_options' => 0,
'decode_assoc' => true,
'decode_depth' => 512,
'decode_options' => 0
];
parent::__construct($config);
}
/**
* Returns options used in encode() function.
*
* @return int
*/
public function getEncodeOptions(): int
{
$options = $this->getConfig('encode_options');
if (!is_int($options)) {
if (is_string($options)) {
$list = preg_split('/[\s,|]+/', $options);
$options = 0;
if ($list) {
foreach ($list as $option) {
if (isset($this->encodeOptions[$option])) {
$options += $this->encodeOptions[$option];
}
}
}
} else {
$options = 0;
}
}
return $options;
}
/**
* Returns options used in decode() function.
*
* @return int
*/
public function getDecodeOptions(): int
{
$options = $this->getConfig('decode_options');
if (!is_int($options)) {
if (is_string($options)) {
$list = preg_split('/[\s,|]+/', $options);
$options = 0;
if ($list) {
foreach ($list as $option) {
if (isset($this->decodeOptions[$option])) {
$options += $this->decodeOptions[$option];
}
}
}
} else {
$options = 0;
}
}
return $options;
}
/**
* Returns recursion depth used in decode() function.
*
* @return int
* @phpstan-return positive-int
*/
public function getDecodeDepth(): int
{
return $this->getConfig('decode_depth');
}
/**
* Returns true if JSON objects will be converted into associative arrays.
*
* @return bool
*/
public function getDecodeAssoc(): bool
{
return $this->getConfig('decode_assoc');
}
/**
* {@inheritdoc}
* @see FileFormatterInterface::encode()
*/
public function encode($data): string
{
$encoded = @json_encode($data, $this->getEncodeOptions());
if ($encoded === false && json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('Encoding JSON failed: ' . json_last_error_msg());
}
return $encoded ?: '';
}
/**
* {@inheritdoc}
* @see FileFormatterInterface::decode()
*/
public function decode($data)
{
$decoded = @json_decode($data, $this->getDecodeAssoc(), $this->getDecodeDepth(), $this->getDecodeOptions());
if (null === $decoded && json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('Decoding JSON failed: ' . json_last_error_msg());
}
return $decoded;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/File/Formatter/CsvFormatter.php | system/src/Grav/Framework/File/Formatter/CsvFormatter.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\File\Formatter
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\File\Formatter;
use Exception;
use Grav\Framework\File\Interfaces\FileFormatterInterface;
use JsonSerializable;
use RuntimeException;
use stdClass;
use function count;
use function is_array;
use function is_object;
use function is_scalar;
/**
* Class CsvFormatter
* @package Grav\Framework\File\Formatter
*/
class CsvFormatter extends AbstractFormatter
{
/**
* IniFormatter constructor.
* @param array $config
*/
public function __construct(array $config = [])
{
$config += [
'file_extension' => ['.csv', '.tsv'],
'delimiter' => ',',
'mime' => 'text/x-csv'
];
parent::__construct($config);
}
/**
* Returns delimiter used to both encode and decode CSV.
*
* @return string
*/
public function getDelimiter(): string
{
// Call fails on bad configuration.
return $this->getConfig('delimiter');
}
/**
* @param array $data
* @param string|null $delimiter
* @return string
* @see FileFormatterInterface::encode()
*/
public function encode($data, $delimiter = null): string
{
if (count($data) === 0) {
return '';
}
$delimiter = $delimiter ?? $this->getDelimiter();
$header = array_keys(reset($data));
// Encode the field names
$string = $this->encodeLine($header, $delimiter);
// Encode the data
foreach ($data as $row) {
$string .= $this->encodeLine($row, $delimiter);
}
return $string;
}
/**
* @param string $data
* @param string|null $delimiter
* @return array
* @see FileFormatterInterface::decode()
*/
public function decode($data, $delimiter = null): array
{
$delimiter = $delimiter ?? $this->getDelimiter();
$lines = preg_split('/\r\n|\r|\n/', $data);
if ($lines === false) {
throw new RuntimeException('Decoding CSV failed');
}
// Get the field names
$headerStr = array_shift($lines);
if (!$headerStr) {
throw new RuntimeException('CSV header missing');
}
$header = str_getcsv($headerStr, $delimiter);
// Allow for replacing a null string with null/empty value
$null_replace = $this->getConfig('null');
// Get the data
$list = [];
$line = null;
try {
foreach ($lines as $line) {
if (!empty($line)) {
$csv_line = str_getcsv($line, $delimiter);
if ($null_replace) {
array_walk($csv_line, static function (&$el) use ($null_replace) {
$el = str_replace($null_replace, "\0", $el);
});
}
$list[] = array_combine($header, $csv_line);
}
}
} catch (Exception $e) {
throw new RuntimeException('Badly formatted CSV line: ' . $line);
}
return $list;
}
/**
* @param array $line
* @param string $delimiter
* @return string
*/
protected function encodeLine(array $line, string $delimiter): string
{
foreach ($line as $key => &$value) {
// Oops, we need to convert the line to a string.
if (!is_scalar($value)) {
if (is_array($value) || $value instanceof JsonSerializable || $value instanceof stdClass) {
$value = json_encode($value);
} elseif (is_object($value)) {
if (method_exists($value, 'toJson')) {
$value = $value->toJson();
} elseif (method_exists($value, 'toArray')) {
$value = json_encode($value->toArray());
}
}
}
$value = $this->escape((string)$value);
}
unset($value);
return implode($delimiter, $line). "\n";
}
/**
* @param string $value
* @return string
*/
protected function escape(string $value)
{
if (preg_match('/[,"\r\n]/u', $value)) {
$value = '"' . preg_replace('/"/', '""', $value) . '"';
}
return $value;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/File/Formatter/FormatterInterface.php | system/src/Grav/Framework/File/Formatter/FormatterInterface.php | <?php
namespace Grav\Framework\File\Formatter;
use Grav\Framework\File\Interfaces\FileFormatterInterface;
/**
* @deprecated 1.6 Use Grav\Framework\File\Interfaces\FileFormatterInterface instead
*/
interface FormatterInterface extends FileFormatterInterface
{
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/File/Formatter/AbstractFormatter.php | system/src/Grav/Framework/File/Formatter/AbstractFormatter.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\File\Formatter
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\File\Formatter;
use Grav\Framework\Compat\Serializable;
use Grav\Framework\File\Interfaces\FileFormatterInterface;
use function is_string;
/**
* Abstract file formatter.
*
* @package Grav\Framework\File\Formatter
*/
abstract class AbstractFormatter implements FileFormatterInterface
{
use Serializable;
/** @var array */
private $config;
/**
* IniFormatter constructor.
* @param array $config
*/
public function __construct(array $config = [])
{
$this->config = $config;
}
/**
* @return string
*/
public function getMimeType(): string
{
$mime = $this->getConfig('mime');
return is_string($mime) ? $mime : 'application/octet-stream';
}
/**
* {@inheritdoc}
* @see FileFormatterInterface::getDefaultFileExtension()
*/
public function getDefaultFileExtension(): string
{
$extensions = $this->getSupportedFileExtensions();
// Call fails on bad configuration.
return reset($extensions) ?: '';
}
/**
* {@inheritdoc}
* @see FileFormatterInterface::getSupportedFileExtensions()
*/
public function getSupportedFileExtensions(): array
{
$extensions = $this->getConfig('file_extension');
// Call fails on bad configuration.
return is_string($extensions) ? [$extensions] : $extensions;
}
/**
* {@inheritdoc}
* @see FileFormatterInterface::encode()
*/
abstract public function encode($data): string;
/**
* {@inheritdoc}
* @see FileFormatterInterface::decode()
*/
abstract public function decode($data);
/**
* @return array
*/
public function __serialize(): array
{
return ['config' => $this->config];
}
/**
* @param array $data
* @return void
*/
public function __unserialize(array $data): void
{
$this->config = $data['config'];
}
/**
* Get either full configuration or a single option.
*
* @param string|null $name Configuration option (optional)
* @return mixed
*/
protected function getConfig(string $name = null)
{
if (null !== $name) {
return $this->config[$name] ?? null;
}
return $this->config;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/File/Interfaces/FileInterface.php | system/src/Grav/Framework/File/Interfaces/FileInterface.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\File
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\File\Interfaces;
use RuntimeException;
use Serializable;
/**
* Defines common interface for all file readers.
*
* File readers allow you to read and optionally write files of various file formats, such as:
*
* @used-by \Grav\Framework\File\CsvFile CVS
* @used-by \Grav\Framework\File\JsonFile JSON
* @used-by \Grav\Framework\File\MarkdownFile Markdown
* @used-by \Grav\Framework\File\SerializeFile Serialized PHP
* @used-by \Grav\Framework\File\YamlFile YAML
*
* @since 1.6
*/
interface FileInterface extends Serializable
{
/**
* Get both path and filename of the file.
*
* @return string Returns path and filename in the filesystem. Can also be URI.
* @api
*/
public function getFilePath(): string;
/**
* Get path of the file.
*
* @return string Returns path in the filesystem. Can also be URI.
* @api
*/
public function getPath(): string;
/**
* Get filename of the file.
*
* @return string Returns name of the file.
* @api
*/
public function getFilename(): string;
/**
* Get basename of the file (filename without the associated file extension).
*
* @return string Returns basename of the file.
* @api
*/
public function getBasename(): string;
/**
* Get file extension of the file.
*
* @param bool $withDot If true, return file extension with beginning dot (.json).
*
* @return string Returns file extension of the file (can be empty).
* @api
*/
public function getExtension(bool $withDot = false): string;
/**
* Check if the file exits in the filesystem.
*
* @return bool Returns `true` if the filename exists and is a regular file, `false` otherwise.
* @api
*/
public function exists(): bool;
/**
* Get file creation time.
*
* @return int Returns Unix timestamp. If file does not exist, method returns current time.
* @api
*/
public function getCreationTime(): int;
/**
* Get file modification time.
*
* @return int Returns Unix timestamp. If file does not exist, method returns current time.
* @api
*/
public function getModificationTime(): int;
/**
* Lock file for writing. You need to manually call unlock().
*
* @param bool $block For non-blocking lock, set the parameter to `false`.
*
* @return bool Returns `true` if the file was successfully locked, `false` otherwise.
* @throws RuntimeException
* @api
*/
public function lock(bool $block = true): bool;
/**
* Unlock file after writing.
*
* @return bool Returns `true` if the file was successfully unlocked, `false` otherwise.
* @api
*/
public function unlock(): bool;
/**
* Returns true if file has been locked by you for writing.
*
* @return bool Returns `true` if the file is locked, `false` otherwise.
* @api
*/
public function isLocked(): bool;
/**
* Check if file exists and can be read.
*
* @return bool Returns `true` if the file can be read, `false` otherwise.
* @api
*/
public function isReadable(): bool;
/**
* Check if file can be written.
*
* @return bool Returns `true` if the file can be written, `false` otherwise.
* @api
*/
public function isWritable(): bool;
/**
* (Re)Load a file and return file contents.
*
* @return string|array|object|false Returns file content or `false` if file couldn't be read.
* @api
*/
public function load();
/**
* Save file.
*
* See supported data format for each of the file format.
*
* @param mixed $data Data to be saved.
*
* @throws RuntimeException
* @api
*/
public function save($data): void;
/**
* Rename file in the filesystem if it exists.
*
* Target folder will be created if if did not exist.
*
* @param string $path New path and filename for the file. Can also be URI.
*
* @return bool Returns `true` if the file was successfully renamed, `false` otherwise.
* @api
*/
public function rename(string $path): bool;
/**
* Delete file from filesystem.
*
* @return bool Returns `true` if the file was successfully deleted, `false` otherwise.
* @api
*/
public function delete(): bool;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/File/Interfaces/FileFormatterInterface.php | system/src/Grav/Framework/File/Interfaces/FileFormatterInterface.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\File
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\File\Interfaces;
use Serializable;
/**
* Defines common interface for all file formatters.
*
* File formatters allow you to read and optionally write various file formats, such as:
*
* @used-by \Grav\Framework\File\Formatter\CsvFormatter CVS
* @used-by \Grav\Framework\File\Formatter\JsonFormatter JSON
* @used-by \Grav\Framework\File\Formatter\MarkdownFormatter Markdown
* @used-by \Grav\Framework\File\Formatter\SerializeFormatter Serialized PHP
* @used-by \Grav\Framework\File\Formatter\YamlFormatter YAML
*
* @since 1.6
*/
interface FileFormatterInterface extends Serializable
{
/**
* @return string
* @since 1.7
*/
public function getMimeType(): string;
/**
* Get default file extension from current formatter (with dot).
*
* Default file extension is the first defined extension.
*
* @return string Returns file extension (can be empty).
* @api
*/
public function getDefaultFileExtension(): string;
/**
* Get file extensions supported by current formatter (with dot).
*
* @return string[] Returns list of all supported file extensions.
* @api
*/
public function getSupportedFileExtensions(): array;
/**
* Encode data into a string.
*
* @param mixed $data Data to be encoded.
* @return string Returns encoded data as a string.
* @api
*/
public function encode($data): string;
/**
* Decode a string into data.
*
* @param string $data String to be decoded.
* @return mixed Returns decoded data.
* @api
*/
public function decode($data);
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/ContentBlock/ContentBlockInterface.php | system/src/Grav/Framework/ContentBlock/ContentBlockInterface.php | <?php
/**
* @package Grav\Framework\ContentBlock
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\ContentBlock;
use Serializable;
/**
* ContentBlock Interface
* @package Grav\Framework\ContentBlock
*/
interface ContentBlockInterface extends Serializable
{
/**
* @param string|null $id
* @return static
*/
public static function create($id = null);
/**
* @param array $serialized
* @return ContentBlockInterface
*/
public static function fromArray(array $serialized);
/**
* @param string|null $id
*/
public function __construct($id = null);
/**
* @return string
*/
public function getId();
/**
* @return string
*/
public function getToken();
/**
* @return array
*/
public function toArray();
/**
* @return string
*/
public function toString();
/**
* @return string
*/
public function __toString();
/**
* @param array $serialized
* @return void
*/
public function build(array $serialized);
/**
* @param string $checksum
* @return $this
*/
public function setChecksum($checksum);
/**
* @return string
*/
public function getChecksum();
/**
* @param string $content
* @return $this
*/
public function setContent($content);
/**
* @param ContentBlockInterface $block
* @return $this
*/
public function addBlock(ContentBlockInterface $block);
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/ContentBlock/ContentBlock.php | system/src/Grav/Framework/ContentBlock/ContentBlock.php | <?php
/**
* @package Grav\Framework\ContentBlock
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\ContentBlock;
use Exception;
use Grav\Framework\Compat\Serializable;
use InvalidArgumentException;
use RuntimeException;
use function get_class;
/**
* Class to create nested blocks of content.
*
* $innerBlock = ContentBlock::create();
* $innerBlock->setContent('my inner content');
* $outerBlock = ContentBlock::create();
* $outerBlock->setContent(sprintf('Inside my outer block I have %s.', $innerBlock->getToken()));
* $outerBlock->addBlock($innerBlock);
* echo $outerBlock;
*
* @package Grav\Framework\ContentBlock
*/
class ContentBlock implements ContentBlockInterface
{
use Serializable;
/** @var int */
protected $version = 1;
/** @var string */
protected $id;
/** @var string */
protected $tokenTemplate = '@@BLOCK-%s@@';
/** @var string */
protected $content = '';
/** @var array */
protected $blocks = [];
/** @var string */
protected $checksum;
/** @var bool */
protected $cached = true;
/**
* @param string|null $id
* @return static
*/
public static function create($id = null)
{
return new static($id);
}
/**
* @param array $serialized
* @return ContentBlockInterface
* @throws InvalidArgumentException
*/
public static function fromArray(array $serialized)
{
try {
$type = $serialized['_type'] ?? null;
$id = $serialized['id'] ?? null;
if (!$type || !$id || !is_a($type, ContentBlockInterface::class, true)) {
throw new InvalidArgumentException('Bad data');
}
/** @var ContentBlockInterface $instance */
$instance = new $type($id);
$instance->build($serialized);
} catch (Exception $e) {
throw new InvalidArgumentException(sprintf('Cannot unserialize Block: %s', $e->getMessage()), $e->getCode(), $e);
}
return $instance;
}
/**
* Block constructor.
*
* @param string|null $id
*/
public function __construct($id = null)
{
$this->id = $id ? (string) $id : $this->generateId();
}
/**
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* @return string
*/
public function getToken()
{
return sprintf($this->tokenTemplate, $this->getId());
}
/**
* @return array
*/
public function toArray()
{
$blocks = [];
/** @var ContentBlockInterface $block */
foreach ($this->blocks as $block) {
$blocks[$block->getId()] = $block->toArray();
}
$array = [
'_type' => get_class($this),
'_version' => $this->version,
'id' => $this->id,
'cached' => $this->cached
];
if ($this->checksum) {
$array['checksum'] = $this->checksum;
}
if ($this->content) {
$array['content'] = $this->content;
}
if ($blocks) {
$array['blocks'] = $blocks;
}
return $array;
}
/**
* @return string
*/
public function toString()
{
if (!$this->blocks) {
return (string) $this->content;
}
$tokens = [];
$replacements = [];
foreach ($this->blocks as $block) {
$tokens[] = $block->getToken();
$replacements[] = $block->toString();
}
return str_replace($tokens, $replacements, (string) $this->content);
}
/**
* @return string
*/
#[\ReturnTypeWillChange]
public function __toString()
{
try {
return $this->toString();
} catch (Exception $e) {
return sprintf('Error while rendering block: %s', $e->getMessage());
}
}
/**
* @param array $serialized
* @return void
* @throws RuntimeException
*/
public function build(array $serialized)
{
$this->checkVersion($serialized);
$this->id = $serialized['id'] ?? $this->generateId();
$this->checksum = $serialized['checksum'] ?? null;
$this->cached = $serialized['cached'] ?? null;
if (isset($serialized['content'])) {
$this->setContent($serialized['content']);
}
$blocks = isset($serialized['blocks']) ? (array) $serialized['blocks'] : [];
foreach ($blocks as $block) {
$this->addBlock(self::fromArray($block));
}
}
/**
* @return bool
*/
public function isCached()
{
if (!$this->cached) {
return false;
}
foreach ($this->blocks as $block) {
if (!$block->isCached()) {
return false;
}
}
return true;
}
/**
* @return $this
*/
public function disableCache()
{
$this->cached = false;
return $this;
}
/**
* @param string $checksum
* @return $this
*/
public function setChecksum($checksum)
{
$this->checksum = $checksum;
return $this;
}
/**
* @return string
*/
public function getChecksum()
{
return $this->checksum;
}
/**
* @param string $content
* @return $this
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* @param ContentBlockInterface $block
* @return $this
*/
public function addBlock(ContentBlockInterface $block)
{
$this->blocks[$block->getId()] = $block;
return $this;
}
/**
* @return array
*/
final public function __serialize(): array
{
return $this->toArray();
}
/**
* @param array $data
* @return void
*/
final public function __unserialize(array $data): void
{
$this->build($data);
}
/**
* @return string
*/
protected function generateId()
{
return uniqid('', true);
}
/**
* @param array $serialized
* @return void
* @throws RuntimeException
*/
protected function checkVersion(array $serialized)
{
$version = isset($serialized['_version']) ? (int) $serialized['_version'] : 1;
if ($version !== $this->version) {
throw new RuntimeException(sprintf('Unsupported version %s', $version));
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/ContentBlock/HtmlBlockInterface.php | system/src/Grav/Framework/ContentBlock/HtmlBlockInterface.php | <?php
/**
* @package Grav\Framework\ContentBlock
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\ContentBlock;
/**
* Interface HtmlBlockInterface
* @package Grav\Framework\ContentBlock
*/
interface HtmlBlockInterface extends ContentBlockInterface
{
/**
* @return array
*/
public function getAssets();
/**
* @return array
*/
public function getFrameworks();
/**
* @param string $location
* @return array
*/
public function getStyles($location = 'head');
/**
* @param string $location
* @return array
*/
public function getScripts($location = 'head');
/**
* @param string $location
* @return array
*/
public function getLinks($location = 'head');
/**
* @param string $location
* @return array
*/
public function getHtml($location = 'bottom');
/**
* @param string $framework
* @return $this
*/
public function addFramework($framework);
/**
* @param string|array $element
* @param int $priority
* @param string $location
* @return bool
*
* @example $block->addStyle('assets/js/my.js');
* @example $block->addStyle(['href' => 'assets/js/my.js', 'media' => 'screen']);
*/
public function addStyle($element, $priority = 0, $location = 'head');
/**
* @param string|array $element
* @param int $priority
* @param string $location
* @return bool
*/
public function addInlineStyle($element, $priority = 0, $location = 'head');
/**
* @param string|array $element
* @param int $priority
* @param string $location
* @return bool
*/
public function addScript($element, $priority = 0, $location = 'head');
/**
* @param string|array $element
* @param int $priority
* @param string $location
* @return bool
*/
public function addInlineScript($element, $priority = 0, $location = 'head');
/**
* Shortcut for writing addScript(['type' => 'module', 'src' => ...]).
*
* @param string|array $element
* @param int $priority
* @param string $location
* @return bool
*/
public function addModule($element, $priority = 0, $location = 'head');
/**
* Shortcut for writing addInlineScript(['type' => 'module', 'content' => ...]).
*
* @param string|array $element
* @param int $priority
* @param string $location
* @return bool
*/
public function addInlineModule($element, $priority = 0, $location = 'head');
/**
* @param array $element
* @param int $priority
* @param string $location
* @return bool
*/
public function addLink($element, $priority = 0, $location = 'head');
/**
* @param string $html
* @param int $priority
* @param string $location
* @return bool
*/
public function addHtml($html, $priority = 0, $location = 'bottom');
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/ContentBlock/HtmlBlock.php | system/src/Grav/Framework/ContentBlock/HtmlBlock.php | <?php
/**
* @package Grav\Framework\ContentBlock
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\ContentBlock;
use RuntimeException;
use function is_array;
use function is_string;
/**
* HtmlBlock
*
* @package Grav\Framework\ContentBlock
*/
class HtmlBlock extends ContentBlock implements HtmlBlockInterface
{
/** @var int */
protected $version = 1;
/** @var array */
protected $frameworks = [];
/** @var array */
protected $styles = [];
/** @var array */
protected $scripts = [];
/** @var array */
protected $links = [];
/** @var array */
protected $html = [];
/**
* @return array
*/
public function getAssets()
{
$assets = $this->getAssetsFast();
$this->sortAssets($assets['styles']);
$this->sortAssets($assets['scripts']);
$this->sortAssets($assets['links']);
$this->sortAssets($assets['html']);
return $assets;
}
/**
* @return array
*/
public function getFrameworks()
{
$assets = $this->getAssetsFast();
return array_keys($assets['frameworks']);
}
/**
* @param string $location
* @return array
*/
public function getStyles($location = 'head')
{
return $this->getAssetsInLocation('styles', $location);
}
/**
* @param string $location
* @return array
*/
public function getScripts($location = 'head')
{
return $this->getAssetsInLocation('scripts', $location);
}
/**
* @param string $location
* @return array
*/
public function getLinks($location = 'head')
{
return $this->getAssetsInLocation('links', $location);
}
/**
* @param string $location
* @return array
*/
public function getHtml($location = 'bottom')
{
return $this->getAssetsInLocation('html', $location);
}
/**
* @return array
*/
public function toArray()
{
$array = parent::toArray();
if ($this->frameworks) {
$array['frameworks'] = $this->frameworks;
}
if ($this->styles) {
$array['styles'] = $this->styles;
}
if ($this->scripts) {
$array['scripts'] = $this->scripts;
}
if ($this->links) {
$array['links'] = $this->links;
}
if ($this->html) {
$array['html'] = $this->html;
}
return $array;
}
/**
* @param array $serialized
* @return void
* @throws RuntimeException
*/
public function build(array $serialized)
{
parent::build($serialized);
$this->frameworks = isset($serialized['frameworks']) ? (array) $serialized['frameworks'] : [];
$this->styles = isset($serialized['styles']) ? (array) $serialized['styles'] : [];
$this->scripts = isset($serialized['scripts']) ? (array) $serialized['scripts'] : [];
$this->links = isset($serialized['links']) ? (array) $serialized['links'] : [];
$this->html = isset($serialized['html']) ? (array) $serialized['html'] : [];
}
/**
* @param string $framework
* @return $this
*/
public function addFramework($framework)
{
$this->frameworks[$framework] = 1;
return $this;
}
/**
* @param string|array $element
* @param int $priority
* @param string $location
* @return bool
*
* @example $block->addStyle('assets/js/my.js');
* @example $block->addStyle(['href' => 'assets/js/my.js', 'media' => 'screen']);
*/
public function addStyle($element, $priority = 0, $location = 'head')
{
if (!is_array($element)) {
$element = ['href' => (string) $element];
}
if (empty($element['href'])) {
return false;
}
if (!isset($this->styles[$location])) {
$this->styles[$location] = [];
}
$id = !empty($element['id']) ? ['id' => (string) $element['id']] : [];
$href = $element['href'];
$type = !empty($element['type']) ? (string) $element['type'] : 'text/css';
$media = !empty($element['media']) ? (string) $element['media'] : null;
unset(
$element['tag'],
$element['id'],
$element['rel'],
$element['content'],
$element['href'],
$element['type'],
$element['media']
);
$this->styles[$location][md5($href) . sha1($href)] = [
':type' => 'file',
':priority' => (int) $priority,
'href' => $href,
'type' => $type,
'media' => $media,
'element' => $element
] + $id;
return true;
}
/**
* @param string|array $element
* @param int $priority
* @param string $location
* @return bool
*/
public function addInlineStyle($element, $priority = 0, $location = 'head')
{
if (!is_array($element)) {
$element = ['content' => (string) $element];
}
if (empty($element['content'])) {
return false;
}
if (!isset($this->styles[$location])) {
$this->styles[$location] = [];
}
$content = (string) $element['content'];
$type = !empty($element['type']) ? (string) $element['type'] : 'text/css';
unset($element['content'], $element['type']);
$this->styles[$location][md5($content) . sha1($content)] = [
':type' => 'inline',
':priority' => (int) $priority,
'content' => $content,
'type' => $type,
'element' => $element
];
return true;
}
/**
* @param string|array $element
* @param int $priority
* @param string $location
* @return bool
*/
public function addScript($element, $priority = 0, $location = 'head')
{
if (!is_array($element)) {
$element = ['src' => (string) $element];
}
if (empty($element['src'])) {
return false;
}
if (!isset($this->scripts[$location])) {
$this->scripts[$location] = [];
}
$src = $element['src'];
$type = !empty($element['type']) ? (string) $element['type'] : 'text/javascript';
$loading = !empty($element['loading']) ? (string) $element['loading'] : null;
$defer = !empty($element['defer']);
$async = !empty($element['async']);
$handle = !empty($element['handle']) ? (string) $element['handle'] : '';
unset($element['src'], $element['type'], $element['loading'], $element['defer'], $element['async'], $element['handle']);
$this->scripts[$location][md5($src) . sha1($src)] = [
':type' => 'file',
':priority' => (int) $priority,
'src' => $src,
'type' => $type,
'loading' => $loading,
'defer' => $defer,
'async' => $async,
'handle' => $handle,
'element' => $element
];
return true;
}
/**
* @param string|array $element
* @param int $priority
* @param string $location
* @return bool
*/
public function addInlineScript($element, $priority = 0, $location = 'head')
{
if (!is_array($element)) {
$element = ['content' => (string) $element];
}
if (empty($element['content'])) {
return false;
}
if (!isset($this->scripts[$location])) {
$this->scripts[$location] = [];
}
$content = (string) $element['content'];
$type = !empty($element['type']) ? (string) $element['type'] : 'text/javascript';
$loading = !empty($element['loading']) ? (string) $element['loading'] : null;
unset($element['content'], $element['type'], $element['loading']);
$this->scripts[$location][md5($content) . sha1($content)] = [
':type' => 'inline',
':priority' => (int) $priority,
'content' => $content,
'type' => $type,
'loading' => $loading,
'element' => $element
];
return true;
}
/**
* @param string|array $element
* @param int $priority
* @param string $location
* @return bool
*/
public function addModule($element, $priority = 0, $location = 'head')
{
if (!is_array($element)) {
$element = ['src' => (string) $element];
}
$element['type'] = 'module';
return $this->addScript($element, $priority, $location);
}
/**
* @param string|array $element
* @param int $priority
* @param string $location
* @return bool
*/
public function addInlineModule($element, $priority = 0, $location = 'head')
{
if (!is_array($element)) {
$element = ['content' => (string) $element];
}
$element['type'] = 'module';
return $this->addInlineScript($element, $priority, $location);
}
/**
* @param array $element
* @param int $priority
* @param string $location
* @return bool
*/
public function addLink($element, $priority = 0, $location = 'head')
{
if (!is_array($element) || empty($element['rel']) || empty($element['href'])) {
return false;
}
if (!isset($this->links[$location])) {
$this->links[$location] = [];
}
$rel = (string) $element['rel'];
$href = (string) $element['href'];
unset($element['rel'], $element['href']);
$this->links[$location][md5($href) . sha1($href)] = [
':type' => 'file',
':priority' => (int) $priority,
'href' => $href,
'rel' => $rel,
'element' => $element,
];
return true;
}
/**
* @param string $html
* @param int $priority
* @param string $location
* @return bool
*/
public function addHtml($html, $priority = 0, $location = 'bottom')
{
if (empty($html) || !is_string($html)) {
return false;
}
if (!isset($this->html[$location])) {
$this->html[$location] = [];
}
$this->html[$location][md5($html) . sha1($html)] = [
':priority' => (int) $priority,
'html' => $html
];
return true;
}
/**
* @return array
*/
protected function getAssetsFast()
{
$assets = [
'frameworks' => $this->frameworks,
'styles' => $this->styles,
'scripts' => $this->scripts,
'links' => $this->links,
'html' => $this->html
];
foreach ($this->blocks as $block) {
if ($block instanceof self) {
$blockAssets = $block->getAssetsFast();
$assets['frameworks'] += $blockAssets['frameworks'];
foreach ($blockAssets['styles'] as $location => $styles) {
if (!isset($assets['styles'][$location])) {
$assets['styles'][$location] = $styles;
} elseif ($styles) {
$assets['styles'][$location] += $styles;
}
}
foreach ($blockAssets['scripts'] as $location => $scripts) {
if (!isset($assets['scripts'][$location])) {
$assets['scripts'][$location] = $scripts;
} elseif ($scripts) {
$assets['scripts'][$location] += $scripts;
}
}
foreach ($blockAssets['links'] as $location => $links) {
if (!isset($assets['links'][$location])) {
$assets['links'][$location] = $links;
} elseif ($links) {
$assets['links'][$location] += $links;
}
}
foreach ($blockAssets['html'] as $location => $htmls) {
if (!isset($assets['html'][$location])) {
$assets['html'][$location] = $htmls;
} elseif ($htmls) {
$assets['html'][$location] += $htmls;
}
}
}
}
return $assets;
}
/**
* @param string $type
* @param string $location
* @return array
*/
protected function getAssetsInLocation($type, $location)
{
$assets = $this->getAssetsFast();
if (empty($assets[$type][$location])) {
return [];
}
$styles = $assets[$type][$location];
$this->sortAssetsInLocation($styles);
return $styles;
}
/**
* @param array $items
* @return void
*/
protected function sortAssetsInLocation(array &$items)
{
$count = 0;
foreach ($items as &$item) {
$item[':order'] = ++$count;
}
unset($item);
uasort(
$items,
static function ($a, $b) {
return $a[':priority'] <=> $b[':priority'] ?: $a[':order'] <=> $b[':order'];
}
);
}
/**
* @param array $array
* @return void
*/
protected function sortAssets(array &$array)
{
foreach ($array as &$items) {
$this->sortAssetsInLocation($items);
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Contracts/Object/IdentifierInterface.php | system/src/Grav/Framework/Contracts/Object/IdentifierInterface.php | <?php declare(strict_types=1);
namespace Grav\Framework\Contracts\Object;
use JsonSerializable;
/**
* Interface IdentifierInterface
*/
interface IdentifierInterface extends JsonSerializable
{
/**
* Get identifier's ID.
*
* @return string
* @phpstan-pure
*/
public function getId(): string;
/**
* Get identifier's type.
*
* @return string
* @phpstan-pure
*/
public function getType(): string;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Contracts/Relationships/ToOneRelationshipInterface.php | system/src/Grav/Framework/Contracts/Relationships/ToOneRelationshipInterface.php | <?php declare(strict_types=1);
namespace Grav\Framework\Contracts\Relationships;
use Grav\Framework\Contracts\Object\IdentifierInterface;
/**
* Interface ToOneRelationshipInterface
*
* @template T of IdentifierInterface
* @template P of IdentifierInterface
* @template-extends RelationshipInterface<T,P>
*/
interface ToOneRelationshipInterface extends RelationshipInterface
{
/**
* @param string|null $id
* @param string|null $type
* @return T|null
* @phpstan-pure
*/
public function getIdentifier(string $id = null, string $type = null): ?IdentifierInterface;
/**
* @param string|null $id
* @param string|null $type
* @return T|null
* @phpstan-pure
*/
public function getObject(string $id = null, string $type = null): ?object;
/**
* @param T|null $identifier
* @return bool
*/
public function replaceIdentifier(IdentifierInterface $identifier = null): bool;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Contracts/Relationships/RelationshipInterface.php | system/src/Grav/Framework/Contracts/Relationships/RelationshipInterface.php | <?php declare(strict_types=1);
namespace Grav\Framework\Contracts\Relationships;
use Countable;
use Grav\Framework\Contracts\Object\IdentifierInterface;
use IteratorAggregate;
use JsonSerializable;
use Serializable;
/**
* Interface Relationship
*
* @template T of IdentifierInterface
* @template P of IdentifierInterface
* @extends IteratorAggregate<string, T>
*/
interface RelationshipInterface extends Countable, IteratorAggregate, JsonSerializable, Serializable
{
/**
* @return string
* @phpstan-pure
*/
public function getName(): string;
/**
* @return string
* @phpstan-pure
*/
public function getType(): string;
/**
* @return bool
* @phpstan-pure
*/
public function isModified(): bool;
/**
* @return string
* @phpstan-pure
*/
public function getCardinality(): string;
/**
* @return P
* @phpstan-pure
*/
public function getParent(): IdentifierInterface;
/**
* @param string $id
* @param string|null $type
* @return bool
* @phpstan-pure
*/
public function has(string $id, string $type = null): bool;
/**
* @param T $identifier
* @return bool
* @phpstan-pure
*/
public function hasIdentifier(IdentifierInterface $identifier): bool;
/**
* @param T $identifier
* @return bool
*/
public function addIdentifier(IdentifierInterface $identifier): bool;
/**
* @param T|null $identifier
* @return bool
*/
public function removeIdentifier(IdentifierInterface $identifier = null): bool;
/**
* @return iterable<T>
*/
public function getIterator(): iterable;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Contracts/Relationships/ToManyRelationshipInterface.php | system/src/Grav/Framework/Contracts/Relationships/ToManyRelationshipInterface.php | <?php declare(strict_types=1);
namespace Grav\Framework\Contracts\Relationships;
use Grav\Framework\Contracts\Object\IdentifierInterface;
/**
* Interface ToManyRelationshipInterface
*
* @template T of IdentifierInterface
* @template P of IdentifierInterface
* @template-extends RelationshipInterface<T,P>
*/
interface ToManyRelationshipInterface extends RelationshipInterface
{
/**
* @param positive-int $pos
* @return IdentifierInterface|null
*/
public function getNthIdentifier(int $pos): ?IdentifierInterface;
/**
* @param string $id
* @param string|null $type
* @return T|null
* @phpstan-pure
*/
public function getIdentifier(string $id, string $type = null): ?IdentifierInterface;
/**
* @param string $id
* @param string|null $type
* @return T|null
* @phpstan-pure
*/
public function getObject(string $id, string $type = null): ?object;
/**
* @param iterable<T> $identifiers
* @return bool
*/
public function addIdentifiers(iterable $identifiers): bool;
/**
* @param iterable<T> $identifiers
* @return bool
*/
public function replaceIdentifiers(iterable $identifiers): bool;
/**
* @param iterable<T> $identifiers
* @return bool
*/
public function removeIdentifiers(iterable $identifiers): bool;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Contracts/Relationships/RelationshipIdentifierInterface.php | system/src/Grav/Framework/Contracts/Relationships/RelationshipIdentifierInterface.php | <?php declare(strict_types=1);
namespace Grav\Framework\Contracts\Relationships;
use ArrayAccess;
use Grav\Framework\Contracts\Object\IdentifierInterface;
/**
* Interface RelationshipIdentifierInterface
*/
interface RelationshipIdentifierInterface extends IdentifierInterface
{
/**
* If identifier has meta.
*
* @return bool
* @phpstan-pure
*/
public function hasIdentifierMeta(): bool;
/**
* Get identifier meta.
*
* @return array<string,mixed>|ArrayAccess<string,mixed>
* @phpstan-pure
*/
public function getIdentifierMeta();
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Contracts/Relationships/RelationshipsInterface.php | system/src/Grav/Framework/Contracts/Relationships/RelationshipsInterface.php | <?php declare(strict_types=1);
namespace Grav\Framework\Contracts\Relationships;
use ArrayAccess;
use Countable;
use Iterator;
use JsonSerializable;
/**
* Interface RelationshipsInterface
*
* @template T of \Grav\Framework\Contracts\Object\IdentifierInterface
* @template P of \Grav\Framework\Contracts\Object\IdentifierInterface
* @extends ArrayAccess<string,RelationshipInterface<T,P>>
* @extends Iterator<string,RelationshipInterface<T,P>>
*/
interface RelationshipsInterface extends Countable, ArrayAccess, Iterator, JsonSerializable
{
/**
* @return bool
* @phpstan-pure
*/
public function isModified(): bool;
/**
* @return array
*/
public function getModified(): array;
/**
* @return int
* @phpstan-pure
*/
public function count(): int;
/**
* @param string $offset
* @return RelationshipInterface<T,P>|null
*/
public function offsetGet($offset): ?RelationshipInterface;
/**
* @return RelationshipInterface<T,P>|null
*/
public function current(): ?RelationshipInterface;
/**
* @return string
* @phpstan-pure
*/
public function key(): string;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Contracts/Media/MediaObjectInterface.php | system/src/Grav/Framework/Contracts/Media/MediaObjectInterface.php | <?php declare(strict_types=1);
namespace Grav\Framework\Contracts\Media;
use Grav\Framework\Contracts\Object\IdentifierInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Media Object Interface
*/
interface MediaObjectInterface extends IdentifierInterface
{
/**
* Returns true if the object exists.
*
* @return bool
* @phpstan-pure
*/
public function exists(): bool;
/**
* Get metadata associated to the media object.
*
* @return array
* @phpstan-pure
*/
public function getMeta(): array;
/**
* @param string $field
* @return mixed
* @phpstan-pure
*/
public function get(string $field);
/**
* Return URL pointing to the media object.
*
* @return string
* @phpstan-pure
*/
public function getUrl(): string;
/**
* Create media response.
*
* @param array $actions
* @return ResponseInterface
* @phpstan-pure
*/
public function createResponse(array $actions): ResponseInterface;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Cache/AbstractCache.php | system/src/Grav/Framework/Cache/AbstractCache.php | <?php
/**
* @package Grav\Framework\Cache
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Cache;
use DateInterval;
use Psr\SimpleCache\InvalidArgumentException;
/**
* Cache trait for PSR-16 compatible "Simple Cache" implementation
* @package Grav\Framework\Cache
*/
abstract class AbstractCache implements CacheInterface
{
use CacheTrait;
/**
* @param string $namespace
* @param null|int|DateInterval $defaultLifetime
* @throws InvalidArgumentException
*/
public function __construct($namespace = '', $defaultLifetime = null)
{
$this->init($namespace, $defaultLifetime);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Cache/CacheInterface.php | system/src/Grav/Framework/Cache/CacheInterface.php | <?php
/**
* @package Grav\Framework\Cache
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Cache;
use Psr\SimpleCache\CacheInterface as SimpleCacheInterface;
/**
* PSR-16 compatible "Simple Cache" interface.
* @package Grav\Framework\Object\Storage
*/
interface CacheInterface extends SimpleCacheInterface
{
/**
* @param string $key
* @param mixed $miss
* @return mixed
*/
public function doGet($key, $miss);
/**
* @param string $key
* @param mixed $value
* @param int|null $ttl
* @return mixed
*/
public function doSet($key, $value, $ttl);
/**
* @param string $key
* @return mixed
*/
public function doDelete($key);
/**
* @return bool
*/
public function doClear();
/**
* @param string[] $keys
* @param mixed $miss
* @return mixed
*/
public function doGetMultiple($keys, $miss);
/**
* @param array<string, mixed> $values
* @param int|null $ttl
* @return mixed
*/
public function doSetMultiple($values, $ttl);
/**
* @param string[] $keys
* @return mixed
*/
public function doDeleteMultiple($keys);
/**
* @param string $key
* @return mixed
*/
public function doHas($key);
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Cache/CacheTrait.php | system/src/Grav/Framework/Cache/CacheTrait.php | <?php
/**
* @package Grav\Framework\Cache
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Cache;
use DateInterval;
use DateTime;
use Grav\Framework\Cache\Exception\InvalidArgumentException;
use stdClass;
use Traversable;
use function array_key_exists;
use function get_class;
use function gettype;
use function is_array;
use function is_int;
use function is_object;
use function is_string;
use function strlen;
/**
* Cache trait for PSR-16 compatible "Simple Cache" implementation
* @package Grav\Framework\Cache
*/
trait CacheTrait
{
/** @var string */
private $namespace = '';
/** @var int|null */
private $defaultLifetime = null;
/** @var stdClass */
private $miss;
/** @var bool */
private $validation = true;
/**
* Always call from constructor.
*
* @param string $namespace
* @param null|int|DateInterval $defaultLifetime
* @return void
* @throws InvalidArgumentException
*/
protected function init($namespace = '', $defaultLifetime = null)
{
$this->namespace = (string) $namespace;
$this->defaultLifetime = $this->convertTtl($defaultLifetime);
$this->miss = new stdClass;
}
/**
* @param bool $validation
* @return void
*/
public function setValidation($validation)
{
$this->validation = (bool) $validation;
}
/**
* @return string
*/
protected function getNamespace()
{
return $this->namespace;
}
/**
* @return int|null
*/
protected function getDefaultLifetime()
{
return $this->defaultLifetime;
}
/**
* @param string $key
* @param mixed|null $default
* @return mixed|null
* @throws InvalidArgumentException
*/
public function get($key, $default = null)
{
$this->validateKey($key);
$value = $this->doGet($key, $this->miss);
return $value !== $this->miss ? $value : $default;
}
/**
* @param string $key
* @param mixed $value
* @param null|int|DateInterval $ttl
* @return bool
* @throws InvalidArgumentException
*/
public function set($key, $value, $ttl = null)
{
$this->validateKey($key);
$ttl = $this->convertTtl($ttl);
// If a negative or zero TTL is provided, the item MUST be deleted from the cache.
return null !== $ttl && $ttl <= 0 ? $this->doDelete($key) : $this->doSet($key, $value, $ttl);
}
/**
* @param string $key
* @return bool
* @throws InvalidArgumentException
*/
public function delete($key)
{
$this->validateKey($key);
return $this->doDelete($key);
}
/**
* @return bool
*/
public function clear()
{
return $this->doClear();
}
/**
* @param iterable $keys
* @param mixed|null $default
* @return iterable
* @throws InvalidArgumentException
*/
public function getMultiple($keys, $default = null)
{
if ($keys instanceof Traversable) {
$keys = iterator_to_array($keys, false);
} elseif (!is_array($keys)) {
$isObject = is_object($keys);
throw new InvalidArgumentException(
sprintf(
'Cache keys must be array or Traversable, "%s" given',
$isObject ? get_class($keys) : gettype($keys)
)
);
}
if (empty($keys)) {
return [];
}
$this->validateKeys($keys);
$keys = array_unique($keys);
$keys = array_combine($keys, $keys);
$list = $this->doGetMultiple($keys, $this->miss);
// Make sure that values are returned in the same order as the keys were given.
$values = [];
foreach ($keys as $key) {
if (!array_key_exists($key, $list) || $list[$key] === $this->miss) {
$values[$key] = $default;
} else {
$values[$key] = $list[$key];
}
}
return $values;
}
/**
* @param iterable $values
* @param null|int|DateInterval $ttl
* @return bool
* @throws InvalidArgumentException
*/
public function setMultiple($values, $ttl = null)
{
if ($values instanceof Traversable) {
$values = iterator_to_array($values, true);
} elseif (!is_array($values)) {
$isObject = is_object($values);
throw new InvalidArgumentException(
sprintf(
'Cache values must be array or Traversable, "%s" given',
$isObject ? get_class($values) : gettype($values)
)
);
}
$keys = array_keys($values);
if (empty($keys)) {
return true;
}
$this->validateKeys($keys);
$ttl = $this->convertTtl($ttl);
// If a negative or zero TTL is provided, the item MUST be deleted from the cache.
return null !== $ttl && $ttl <= 0 ? $this->doDeleteMultiple($keys) : $this->doSetMultiple($values, $ttl);
}
/**
* @param iterable $keys
* @return bool
* @throws InvalidArgumentException
*/
public function deleteMultiple($keys)
{
if ($keys instanceof Traversable) {
$keys = iterator_to_array($keys, false);
} elseif (!is_array($keys)) {
$isObject = is_object($keys);
throw new InvalidArgumentException(
sprintf(
'Cache keys must be array or Traversable, "%s" given',
$isObject ? get_class($keys) : gettype($keys)
)
);
}
if (empty($keys)) {
return true;
}
$this->validateKeys($keys);
return $this->doDeleteMultiple($keys);
}
/**
* @param string $key
* @return bool
* @throws InvalidArgumentException
*/
public function has($key)
{
$this->validateKey($key);
return $this->doHas($key);
}
/**
* @param array $keys
* @param mixed $miss
* @return array
*/
public function doGetMultiple($keys, $miss)
{
$results = [];
foreach ($keys as $key) {
$value = $this->doGet($key, $miss);
if ($value !== $miss) {
$results[$key] = $value;
}
}
return $results;
}
/**
* @param array $values
* @param int|null $ttl
* @return bool
*/
public function doSetMultiple($values, $ttl)
{
$success = true;
foreach ($values as $key => $value) {
$success = $this->doSet($key, $value, $ttl) && $success;
}
return $success;
}
/**
* @param array $keys
* @return bool
*/
public function doDeleteMultiple($keys)
{
$success = true;
foreach ($keys as $key) {
$success = $this->doDelete($key) && $success;
}
return $success;
}
/**
* @param string|mixed $key
* @return void
* @throws InvalidArgumentException
*/
protected function validateKey($key)
{
if (!is_string($key)) {
throw new InvalidArgumentException(
sprintf(
'Cache key must be string, "%s" given',
is_object($key) ? get_class($key) : gettype($key)
)
);
}
if (!isset($key[0])) {
throw new InvalidArgumentException('Cache key length must be greater than zero');
}
if (strlen($key) > 64) {
throw new InvalidArgumentException(
sprintf('Cache key length must be less than 65 characters, key had %d characters', strlen($key))
);
}
if (strpbrk($key, '{}()/\@:') !== false) {
throw new InvalidArgumentException(
sprintf('Cache key "%s" contains reserved characters {}()/\@:', $key)
);
}
}
/**
* @param array $keys
* @return void
* @throws InvalidArgumentException
*/
protected function validateKeys($keys)
{
if (!$this->validation) {
return;
}
foreach ($keys as $key) {
$this->validateKey($key);
}
}
/**
* @param null|int|DateInterval $ttl
* @return int|null
* @throws InvalidArgumentException
*/
protected function convertTtl($ttl)
{
if ($ttl === null) {
return $this->getDefaultLifetime();
}
if (is_int($ttl)) {
return $ttl;
}
if ($ttl instanceof DateInterval) {
$date = DateTime::createFromFormat('U', '0');
$ttl = $date ? (int)$date->add($ttl)->format('U') : 0;
}
throw new InvalidArgumentException(
sprintf(
'Expiration date must be an integer, a DateInterval or null, "%s" given',
is_object($ttl) ? get_class($ttl) : gettype($ttl)
)
);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Cache/Exception/InvalidArgumentException.php | system/src/Grav/Framework/Cache/Exception/InvalidArgumentException.php | <?php
/**
* @package Grav\Framework\Cache
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Cache\Exception;
use Psr\SimpleCache\InvalidArgumentException as SimpleCacheInvalidArgumentException;
/**
* InvalidArgumentException class for PSR-16 compatible "Simple Cache" implementation.
* @package Grav\Framework\Cache\Exception
*/
class InvalidArgumentException extends \InvalidArgumentException implements SimpleCacheInvalidArgumentException
{
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Cache/Exception/CacheException.php | system/src/Grav/Framework/Cache/Exception/CacheException.php | <?php
/**
* @package Grav\Framework\Cache
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Cache\Exception;
use Exception;
use Psr\SimpleCache\CacheException as SimpleCacheException;
/**
* CacheException class for PSR-16 compatible "Simple Cache" implementation.
* @package Grav\Framework\Cache\Exception
*/
class CacheException extends Exception implements SimpleCacheException
{
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Cache/Adapter/SessionCache.php | system/src/Grav/Framework/Cache/Adapter/SessionCache.php | <?php
/**
* @package Grav\Framework\Cache
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Cache\Adapter;
use Grav\Framework\Cache\AbstractCache;
/**
* Cache class for PSR-16 compatible "Simple Cache" implementation using session backend.
*
* @package Grav\Framework\Cache
*/
class SessionCache extends AbstractCache
{
public const VALUE = 0;
public const LIFETIME = 1;
/**
* @param string $key
* @param mixed $miss
* @return mixed
*/
public function doGet($key, $miss)
{
$stored = $this->doGetStored($key);
return $stored ? $stored[self::VALUE] : $miss;
}
/**
* @param string $key
* @param mixed $value
* @param int $ttl
* @return bool
*/
public function doSet($key, $value, $ttl)
{
$stored = [self::VALUE => $value];
if (null !== $ttl) {
$stored[self::LIFETIME] = time() + $ttl;
}
$_SESSION[$this->getNamespace()][$key] = $stored;
return true;
}
/**
* @param string $key
* @return bool
*/
public function doDelete($key)
{
unset($_SESSION[$this->getNamespace()][$key]);
return true;
}
/**
* @return bool
*/
public function doClear()
{
unset($_SESSION[$this->getNamespace()]);
return true;
}
/**
* @param string $key
* @return bool
*/
public function doHas($key)
{
return $this->doGetStored($key) !== null;
}
/**
* @return string
*/
public function getNamespace()
{
return 'cache-' . parent::getNamespace();
}
/**
* @param string $key
* @return mixed|null
*/
protected function doGetStored($key)
{
$stored = $_SESSION[$this->getNamespace()][$key] ?? null;
if (isset($stored[self::LIFETIME]) && $stored[self::LIFETIME] < time()) {
unset($_SESSION[$this->getNamespace()][$key]);
$stored = null;
}
return $stored ?: null;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Cache/Adapter/DoctrineCache.php | system/src/Grav/Framework/Cache/Adapter/DoctrineCache.php | <?php
/**
* @package Grav\Framework\Cache
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Cache\Adapter;
use DateInterval;
use Doctrine\Common\Cache\CacheProvider;
use Grav\Framework\Cache\AbstractCache;
use Grav\Framework\Cache\Exception\InvalidArgumentException;
/**
* Cache class for PSR-16 compatible "Simple Cache" implementation using Doctrine Cache backend.
* @package Grav\Framework\Cache
*/
class DoctrineCache extends AbstractCache
{
/** @var CacheProvider */
protected $driver;
/**
* Doctrine Cache constructor.
*
* @param CacheProvider $doctrineCache
* @param string $namespace
* @param null|int|DateInterval $defaultLifetime
* @throws InvalidArgumentException
*/
public function __construct(CacheProvider $doctrineCache, $namespace = '', $defaultLifetime = null)
{
// Do not use $namespace or $defaultLifetime directly, store them with constructor and fetch with methods.
try {
parent::__construct($namespace, $defaultLifetime);
} catch (\Psr\SimpleCache\InvalidArgumentException $e) {
throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
// Set namespace to Doctrine Cache provider if it was given.
$namespace = $this->getNamespace();
if ($namespace) {
$doctrineCache->setNamespace($namespace);
}
$this->driver = $doctrineCache;
}
/**
* @inheritdoc
*/
public function doGet($key, $miss)
{
$value = $this->driver->fetch($key);
// Doctrine cache does not differentiate between no result and cached 'false'. Make sure that we do.
return $value !== false || $this->driver->contains($key) ? $value : $miss;
}
/**
* @inheritdoc
*/
public function doSet($key, $value, $ttl)
{
return $this->driver->save($key, $value, (int) $ttl);
}
/**
* @inheritdoc
*/
public function doDelete($key)
{
return $this->driver->delete($key);
}
/**
* @inheritdoc
*/
public function doClear()
{
return $this->driver->deleteAll();
}
/**
* @inheritdoc
*/
public function doGetMultiple($keys, $miss)
{
return $this->driver->fetchMultiple($keys);
}
/**
* @inheritdoc
*/
public function doSetMultiple($values, $ttl)
{
return $this->driver->saveMultiple($values, (int) $ttl);
}
/**
* @inheritdoc
*/
public function doDeleteMultiple($keys)
{
return $this->driver->deleteMultiple($keys);
}
/**
* @inheritdoc
*/
public function doHas($key)
{
return $this->driver->contains($key);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Cache/Adapter/MemoryCache.php | system/src/Grav/Framework/Cache/Adapter/MemoryCache.php | <?php
/**
* @package Grav\Framework\Cache
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Cache\Adapter;
use Grav\Framework\Cache\AbstractCache;
use function array_key_exists;
/**
* Cache class for PSR-16 compatible "Simple Cache" implementation using in memory backend.
*
* Memory backend does not use namespace or default ttl as the cache is unique to each cache object and request.
*
* @package Grav\Framework\Cache
*/
class MemoryCache extends AbstractCache
{
/** @var array */
protected $cache = [];
/**
* @param string $key
* @param mixed $miss
* @return mixed
*/
public function doGet($key, $miss)
{
if (!array_key_exists($key, $this->cache)) {
return $miss;
}
return $this->cache[$key];
}
/**
* @param string $key
* @param mixed $value
* @param int $ttl
* @return bool
*/
public function doSet($key, $value, $ttl)
{
$this->cache[$key] = $value;
return true;
}
/**
* @param string $key
* @return bool
*/
public function doDelete($key)
{
unset($this->cache[$key]);
return true;
}
/**
* @return bool
*/
public function doClear()
{
$this->cache = [];
return true;
}
/**
* @param string $key
* @return bool
*/
public function doHas($key)
{
return array_key_exists($key, $this->cache);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Cache/Adapter/FileCache.php | system/src/Grav/Framework/Cache/Adapter/FileCache.php | <?php
/**
* @package Grav\Framework\Cache
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Cache\Adapter;
use ErrorException;
use FilesystemIterator;
use Grav\Framework\Cache\AbstractCache;
use Grav\Framework\Cache\Exception\CacheException;
use Grav\Framework\Cache\Exception\InvalidArgumentException;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RuntimeException;
use function strlen;
/**
* Cache class for PSR-16 compatible "Simple Cache" implementation using file backend.
*
* Defaults to 1 year TTL. Does not support unlimited TTL.
*
* @package Grav\Framework\Cache
*/
class FileCache extends AbstractCache
{
/** @var string */
private $directory;
/** @var string|null */
private $tmp;
/**
* FileCache constructor.
* @param string $namespace
* @param int|null $defaultLifetime
* @param string|null $folder
* @throws \Psr\SimpleCache\InvalidArgumentException|InvalidArgumentException
*/
public function __construct($namespace = '', $defaultLifetime = null, $folder = null)
{
try {
parent::__construct($namespace, $defaultLifetime ?: 31557600); // = 1 year
$this->initFileCache($namespace, $folder ?? '');
} catch (\Psr\SimpleCache\InvalidArgumentException $e) {
throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
}
/**
* @inheritdoc
*/
public function doGet($key, $miss)
{
$now = time();
$file = $this->getFile($key);
if (!file_exists($file) || !$h = @fopen($file, 'rb')) {
return $miss;
}
if ($now >= (int) $expiresAt = fgets($h)) {
fclose($h);
@unlink($file);
} else {
$i = rawurldecode(rtrim((string)fgets($h)));
$value = stream_get_contents($h) ?: '';
fclose($h);
if ($i === $key) {
return unserialize($value, ['allowed_classes' => true]);
}
}
return $miss;
}
/**
* @inheritdoc
* @throws CacheException
*/
public function doSet($key, $value, $ttl)
{
$expiresAt = time() + (int)$ttl;
$result = $this->write(
$this->getFile($key, true),
$expiresAt . "\n" . rawurlencode($key) . "\n" . serialize($value),
$expiresAt
);
if (!$result && !is_writable($this->directory)) {
throw new CacheException(sprintf('Cache directory is not writable (%s)', $this->directory));
}
return $result;
}
/**
* @inheritdoc
*/
public function doDelete($key)
{
$file = $this->getFile($key);
$result = false;
if (file_exists($file)) {
$result = @unlink($file);
$result &= !file_exists($file);
}
return $result;
}
/**
* @inheritdoc
*/
public function doClear()
{
$result = true;
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->directory, FilesystemIterator::SKIP_DOTS));
foreach ($iterator as $file) {
$result = ($file->isDir() || @unlink($file) || !file_exists($file)) && $result;
}
return $result;
}
/**
* @inheritdoc
*/
public function doHas($key)
{
$file = $this->getFile($key);
return file_exists($file) && (@filemtime($file) > time() || $this->doGet($key, null));
}
/**
* @param string $key
* @param bool $mkdir
* @return string
*/
protected function getFile($key, $mkdir = false)
{
$hash = str_replace('/', '-', base64_encode(hash('sha256', static::class . $key, true)));
$dir = $this->directory . $hash[0] . DIRECTORY_SEPARATOR . $hash[1] . DIRECTORY_SEPARATOR;
if ($mkdir) {
$this->mkdir($dir);
}
return $dir . substr($hash, 2, 20);
}
/**
* @param string $namespace
* @param string $directory
* @return void
* @throws InvalidArgumentException
*/
protected function initFileCache($namespace, $directory)
{
if ($directory === '') {
$directory = sys_get_temp_dir() . '/grav-cache';
} else {
$directory = realpath($directory) ?: $directory;
}
if (isset($namespace[0])) {
if (preg_match('#[^-+_.A-Za-z0-9]#', $namespace, $match)) {
throw new InvalidArgumentException(sprintf('Namespace contains "%s" but only characters in [-+_.A-Za-z0-9] are allowed.', $match[0]));
}
$directory .= DIRECTORY_SEPARATOR . $namespace;
}
$this->mkdir($directory);
$directory .= DIRECTORY_SEPARATOR;
// On Windows the whole path is limited to 258 chars
if ('\\' === DIRECTORY_SEPARATOR && strlen($directory) > 234) {
throw new InvalidArgumentException(sprintf('Cache folder is too long (%s)', $directory));
}
$this->directory = $directory;
}
/**
* @param string $file
* @param string $data
* @param int|null $expiresAt
* @return bool
*/
private function write($file, $data, $expiresAt = null)
{
set_error_handler(__CLASS__.'::throwError');
try {
if ($this->tmp === null) {
$this->tmp = $this->directory . uniqid('', true);
}
file_put_contents($this->tmp, $data);
if ($expiresAt !== null) {
touch($this->tmp, $expiresAt);
}
return rename($this->tmp, $file);
} finally {
restore_error_handler();
}
}
/**
* @param string $dir
* @return void
* @throws RuntimeException
*/
private function mkdir($dir)
{
// Silence error for open_basedir; should fail in mkdir instead.
if (@is_dir($dir)) {
return;
}
$success = @mkdir($dir, 0777, true);
if (!$success) {
// Take yet another look, make sure that the folder doesn't exist.
clearstatcache(true, $dir);
if (!@is_dir($dir)) {
throw new RuntimeException(sprintf('Unable to create directory: %s', $dir));
}
}
}
/**
* @param int $type
* @param string $message
* @param string $file
* @param int $line
* @return bool
* @internal
* @throws ErrorException
*/
public static function throwError($type, $message, $file, $line)
{
throw new ErrorException($message, 0, $type, $file, $line);
}
/**
* @return void
*/
#[\ReturnTypeWillChange]
public function __destruct()
{
if ($this->tmp !== null && file_exists($this->tmp)) {
unlink($this->tmp);
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Cache/Adapter/ChainCache.php | system/src/Grav/Framework/Cache/Adapter/ChainCache.php | <?php
/**
* @package Grav\Framework\Cache
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Cache\Adapter;
use DateInterval;
use Grav\Framework\Cache\AbstractCache;
use Grav\Framework\Cache\CacheInterface;
use Grav\Framework\Cache\Exception\InvalidArgumentException;
use function count;
use function get_class;
/**
* Cache class for PSR-16 compatible "Simple Cache" implementation using chained cache adapters.
*
* @package Grav\Framework\Cache
*/
class ChainCache extends AbstractCache
{
/** @var CacheInterface[] */
protected $caches;
/** @var int */
protected $count;
/**
* Chain Cache constructor.
* @param array $caches
* @param null|int|DateInterval $defaultLifetime
* @throws InvalidArgumentException
*/
public function __construct(array $caches, $defaultLifetime = null)
{
try {
parent::__construct('', $defaultLifetime);
} catch (\Psr\SimpleCache\InvalidArgumentException $e) {
throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
if (!$caches) {
throw new InvalidArgumentException('At least one cache must be specified');
}
foreach ($caches as $cache) {
if (!$cache instanceof CacheInterface) {
throw new InvalidArgumentException(
sprintf(
"The class '%s' does not implement the '%s' interface",
get_class($cache),
CacheInterface::class
)
);
}
}
$this->caches = array_values($caches);
$this->count = count($caches);
}
/**
* @inheritdoc
*/
public function doGet($key, $miss)
{
foreach ($this->caches as $i => $cache) {
$value = $cache->doGet($key, $miss);
if ($value !== $miss) {
while (--$i >= 0) {
// Update all the previous caches with missing value.
$this->caches[$i]->doSet($key, $value, $this->getDefaultLifetime());
}
return $value;
}
}
return $miss;
}
/**
* @inheritdoc
*/
public function doSet($key, $value, $ttl)
{
$success = true;
$i = $this->count;
while ($i--) {
$success = $this->caches[$i]->doSet($key, $value, $ttl) && $success;
}
return $success;
}
/**
* @inheritdoc
*/
public function doDelete($key)
{
$success = true;
$i = $this->count;
while ($i--) {
$success = $this->caches[$i]->doDelete($key) && $success;
}
return $success;
}
/**
* @inheritdoc
*/
public function doClear()
{
$success = true;
$i = $this->count;
while ($i--) {
$success = $this->caches[$i]->doClear() && $success;
}
return $success;
}
/**
* @inheritdoc
*/
public function doGetMultiple($keys, $miss)
{
$list = [];
/**
* @var int $i
* @var CacheInterface $cache
*/
foreach ($this->caches as $i => $cache) {
$list[$i] = $cache->doGetMultiple($keys, $miss);
$keys = array_diff_key($keys, $list[$i]);
if (!$keys) {
break;
}
}
// Update all the previous caches with missing values.
$values = [];
/**
* @var int $i
* @var CacheInterface $items
*/
foreach (array_reverse($list) as $i => $items) {
$values += $items;
if ($i && $values) {
$this->caches[$i-1]->doSetMultiple($values, $this->getDefaultLifetime());
}
}
return $values;
}
/**
* @inheritdoc
*/
public function doSetMultiple($values, $ttl)
{
$success = true;
$i = $this->count;
while ($i--) {
$success = $this->caches[$i]->doSetMultiple($values, $ttl) && $success;
}
return $success;
}
/**
* @inheritdoc
*/
public function doDeleteMultiple($keys)
{
$success = true;
$i = $this->count;
while ($i--) {
$success = $this->caches[$i]->doDeleteMultiple($keys) && $success;
}
return $success;
}
/**
* @inheritdoc
*/
public function doHas($key)
{
foreach ($this->caches as $cache) {
if ($cache->doHas($key)) {
return true;
}
}
return false;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Filesystem/Filesystem.php | system/src/Grav/Framework/Filesystem/Filesystem.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Filesystem
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Filesystem;
use Grav\Framework\Filesystem\Interfaces\FilesystemInterface;
use RuntimeException;
use function count;
use function dirname;
use function is_array;
use function pathinfo;
/**
* Class Filesystem
* @package Grav\Framework\Filesystem
*/
class Filesystem implements FilesystemInterface
{
/** @var bool|null */
private $normalize;
/** @var static|null */
protected static $default;
/** @var static|null */
protected static $unsafe;
/** @var static|null */
protected static $safe;
/**
* @param bool|null $normalize See $this->setNormalization()
* @return Filesystem
*/
public static function getInstance(bool $normalize = null): Filesystem
{
if ($normalize === true) {
$instance = &static::$safe;
} elseif ($normalize === false) {
$instance = &static::$unsafe;
} else {
$instance = &static::$default;
}
if (null === $instance) {
$instance = new static($normalize);
}
return $instance;
}
/**
* Always use Filesystem::getInstance() instead.
*
* @param bool|null $normalize
* @internal
*/
protected function __construct(bool $normalize = null)
{
$this->normalize = $normalize;
}
/**
* Set path normalization.
*
* Default option enables normalization for the streams only, but you can force the normalization to be either
* on or off for every path. Disabling path normalization speeds up the calls, but may cause issues if paths were
* not normalized.
*
* @param bool|null $normalize
* @return Filesystem
*/
public function setNormalization(bool $normalize = null): self
{
return static::getInstance($normalize);
}
/**
* @return bool|null
*/
public function getNormalization(): ?bool
{
return $this->normalize;
}
/**
* Force all paths to be normalized.
*
* @return self
*/
public function unsafe(): self
{
return static::getInstance(true);
}
/**
* Force all paths not to be normalized (speeds up the calls if given paths are known to be normalized).
*
* @return self
*/
public function safe(): self
{
return static::getInstance(false);
}
/**
* {@inheritdoc}
* @see FilesystemInterface::parent()
*/
public function parent(string $path, int $levels = 1): string
{
[$scheme, $path] = $this->getSchemeAndHierarchy($path);
if ($this->normalize !== false) {
$path = $this->normalizePathPart($path);
}
if ($path === '' || $path === '.') {
return '';
}
[$scheme, $parent] = $this->dirnameInternal($scheme, $path, $levels);
return $parent !== $path ? $this->toString($scheme, $parent) : '';
}
/**
* {@inheritdoc}
* @see FilesystemInterface::normalize()
*/
public function normalize(string $path): string
{
[$scheme, $path] = $this->getSchemeAndHierarchy($path);
$path = $this->normalizePathPart($path);
return $this->toString($scheme, $path);
}
/**
* {@inheritdoc}
* @see FilesystemInterface::basename()
*/
public function basename(string $path, ?string $suffix = null): string
{
// Escape path.
$path = str_replace(['%2F', '%5C'], '/', rawurlencode($path));
return rawurldecode($suffix ? basename($path, $suffix) : basename($path));
}
/**
* {@inheritdoc}
* @see FilesystemInterface::dirname()
*/
public function dirname(string $path, int $levels = 1): string
{
[$scheme, $path] = $this->getSchemeAndHierarchy($path);
if ($this->normalize || ($scheme && null === $this->normalize)) {
$path = $this->normalizePathPart($path);
}
[$scheme, $path] = $this->dirnameInternal($scheme, $path, $levels);
return $this->toString($scheme, $path);
}
/**
* Gets full path with trailing slash.
*
* @param string $path
* @param int $levels
* @return string
* @phpstan-param positive-int $levels
*/
public function pathname(string $path, int $levels = 1): string
{
$path = $this->dirname($path, $levels);
return $path !== '.' ? $path . '/' : '';
}
/**
* {@inheritdoc}
* @see FilesystemInterface::pathinfo()
*/
public function pathinfo(string $path, ?int $options = null)
{
[$scheme, $path] = $this->getSchemeAndHierarchy($path);
if ($this->normalize || ($scheme && null === $this->normalize)) {
$path = $this->normalizePathPart($path);
}
return $this->pathinfoInternal($scheme, $path, $options);
}
/**
* @param string|null $scheme
* @param string $path
* @param int $levels
* @return array
* @phpstan-param positive-int $levels
*/
protected function dirnameInternal(?string $scheme, string $path, int $levels = 1): array
{
$path = dirname($path, $levels);
if (null !== $scheme && $path === '.') {
return [$scheme, ''];
}
// In Windows dirname() may return backslashes, fix that.
if (DIRECTORY_SEPARATOR !== '/') {
$path = str_replace('\\', '/', $path);
}
return [$scheme, $path];
}
/**
* @param string|null $scheme
* @param string $path
* @param int|null $options
* @return array|string
*/
protected function pathinfoInternal(?string $scheme, string $path, ?int $options = null)
{
$path = str_replace(['%2F', '%5C'], ['/', '\\'], rawurlencode($path));
if (null === $options) {
$info = pathinfo($path);
} else {
$info = pathinfo($path, $options);
}
if (!is_array($info)) {
return rawurldecode($info);
}
$info = array_map('rawurldecode', $info);
if (null !== $scheme) {
$info['scheme'] = $scheme;
/** @phpstan-ignore-next-line because pathinfo('') doesn't have dirname */
$dirname = $info['dirname'] ?? '.';
if ('' !== $dirname && '.' !== $dirname) {
// In Windows dirname may be using backslashes, fix that.
if (DIRECTORY_SEPARATOR !== '/') {
$dirname = str_replace(DIRECTORY_SEPARATOR, '/', $dirname);
}
$info['dirname'] = $scheme . '://' . $dirname;
} else {
$info = ['dirname' => $scheme . '://'] + $info;
}
}
return $info;
}
/**
* Gets a 2-tuple of scheme (may be null) and hierarchical part of a filename (e.g. file:///tmp -> array(file, tmp)).
*
* @param string $filename
* @return array
*/
protected function getSchemeAndHierarchy(string $filename): array
{
$components = explode('://', $filename, 2);
return 2 === count($components) ? $components : [null, $components[0]];
}
/**
* @param string|null $scheme
* @param string $path
* @return string
*/
protected function toString(?string $scheme, string $path): string
{
if ($scheme) {
return $scheme . '://' . $path;
}
return $path;
}
/**
* @param string $path
* @return string
* @throws RuntimeException
*/
protected function normalizePathPart(string $path): string
{
// Quick check for empty path.
if ($path === '' || $path === '.') {
return '';
}
// Quick check for root.
if ($path === '/') {
return '/';
}
// If the last character is not '/' or any of '\', './', '//' and '..' are not found, path is clean and we're done.
if ($path[-1] !== '/' && !preg_match('`(\\\\|\./|//|\.\.)`', $path)) {
return $path;
}
// Convert backslashes
$path = strtr($path, ['\\' => '/']);
$parts = explode('/', $path);
// Keep absolute paths.
$root = '';
if ($parts[0] === '') {
$root = '/';
array_shift($parts);
}
$list = [];
foreach ($parts as $i => $part) {
// Remove empty parts: // and /./
if ($part === '' || $part === '.') {
continue;
}
// Resolve /../ by removing path part.
if ($part === '..') {
$test = array_pop($list);
if ($test === null) {
// Oops, user tried to access something outside of our root folder.
throw new RuntimeException("Bad path {$path}");
}
} else {
$list[] = $part;
}
}
// Build path back together.
return $root . implode('/', $list);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Filesystem/Interfaces/FilesystemInterface.php | system/src/Grav/Framework/Filesystem/Interfaces/FilesystemInterface.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Filesystem
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Filesystem\Interfaces;
use Grav\Framework\Filesystem\Filesystem;
use RuntimeException;
/**
* Defines several stream-save filesystem actions.
*
* @used-by Filesystem
* @since 1.6
*/
interface FilesystemInterface
{
/**
* Get parent path. Empty path is returned if there are no segments remaining.
*
* Can be used recursively to get towards the root directory.
*
* @param string $path A filename or path, does not need to exist as a file.
* @param int $levels The number of parent directories to go up (>= 1).
* @return string Returns parent path.
* @throws RuntimeException
* @phpstan-param positive-int $levels
* @api
*/
public function parent(string $path, int $levels = 1): string;
/**
* Normalize path by cleaning up `\`, `/./`, `//` and `/../`.
*
* @param string $path A filename or path, does not need to exist as a file.
* @return string Returns normalized path.
* @throws RuntimeException
* @api
*/
public function normalize(string $path): string;
/**
* Unicode-safe and stream-safe `\basename()` replacement.
*
* @param string $path A filename or path, does not need to exist as a file.
* @param string|null $suffix If the filename ends in suffix this will also be cut off.
* @return string
* @api
*/
public function basename(string $path, ?string $suffix = null): string;
/**
* Unicode-safe and stream-safe `\dirname()` replacement.
*
* @see http://php.net/manual/en/function.dirname.php
*
* @param string $path A filename or path, does not need to exist as a file.
* @param int $levels The number of parent directories to go up (>= 1).
* @return string Returns path to the directory.
* @throws RuntimeException
* @phpstan-param positive-int $levels
* @api
*/
public function dirname(string $path, int $levels = 1): string;
/**
* Unicode-safe and stream-safe `\pathinfo()` replacement.
*
* @see http://php.net/manual/en/function.pathinfo.php
*
* @param string $path A filename or path, does not need to exist as a file.
* @param int|null $options A PATHINFO_* constant.
* @return array|string
* @api
*/
public function pathinfo(string $path, ?int $options = null);
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Pagination/AbstractPagination.php | system/src/Grav/Framework/Pagination/AbstractPagination.php | <?php
/**
* @package Grav\Framework\Pagination
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Pagination;
use ArrayIterator;
use Grav\Framework\Pagination\Interfaces\PaginationInterface;
use Grav\Framework\Route\Route;
use function count;
/**
* Class AbstractPagination
* @package Grav\Framework\Pagination
*/
class AbstractPagination implements PaginationInterface
{
/** @var Route Base rouse used for the pagination. */
protected $route;
/** @var int|null Current page. */
protected $page;
/** @var int|null The record number to start displaying from. */
protected $start;
/** @var int Number of records to display per page. */
protected $limit;
/** @var int Total number of records. */
protected $total;
/** @var array Pagination options */
protected $options;
/** @var bool View all flag. */
protected $viewAll;
/** @var int Total number of pages. */
protected $pages;
/** @var int Value pagination object begins at. */
protected $pagesStart;
/** @var int Value pagination object ends at .*/
protected $pagesStop;
/** @var array */
protected $defaultOptions = [
'type' => 'page',
'limit' => 10,
'display' => 5,
'opening' => 0,
'ending' => 0,
'url' => null,
'param' => null,
'use_query_param' => false
];
/** @var array */
private $items;
/**
* @return bool
*/
public function isEnabled(): bool
{
return $this->count() > 1;
}
/**
* @return array
*/
public function getOptions(): array
{
return $this->options;
}
/**
* @return Route|null
*/
public function getRoute(): ?Route
{
return $this->route;
}
/**
* @return int
*/
public function getTotalPages(): int
{
return $this->pages;
}
/**
* @return int
*/
public function getPageNumber(): int
{
return $this->page ?? 1;
}
/**
* @param int $count
* @return int|null
*/
public function getPrevNumber(int $count = 1): ?int
{
$page = $this->page - $count;
return $page >= 1 ? $page : null;
}
/**
* @param int $count
* @return int|null
*/
public function getNextNumber(int $count = 1): ?int
{
$page = $this->page + $count;
return $page <= $this->pages ? $page : null;
}
/**
* @param int $page
* @param string|null $label
* @return PaginationPage|null
*/
public function getPage(int $page, string $label = null): ?PaginationPage
{
if ($page < 1 || $page > $this->pages) {
return null;
}
$start = ($page - 1) * $this->limit;
$type = $this->getOptions()['type'];
$param = $this->getOptions()['param'];
$useQuery = $this->getOptions()['use_query_param'];
if ($type === 'page') {
$param = $param ?? 'page';
$offset = $page;
} else {
$param = $param ?? 'start';
$offset = $start;
}
if ($useQuery) {
$route = $this->route->withQueryParam($param, $offset);
} else {
$route = $this->route->withGravParam($param, $offset);
}
return new PaginationPage(
[
'label' => $label ?? (string)$page,
'number' => $page,
'offset_start' => $start,
'offset_end' => min($start + $this->limit, $this->total) - 1,
'enabled' => $page !== $this->page || $this->viewAll,
'active' => $page === $this->page,
'route' => $route
]
);
}
/**
* @param string|null $label
* @param int $count
* @return PaginationPage|null
*/
public function getFirstPage(string $label = null, int $count = 0): ?PaginationPage
{
return $this->getPage(1 + $count, $label ?? $this->getOptions()['label_first'] ?? null);
}
/**
* @param string|null $label
* @param int $count
* @return PaginationPage|null
*/
public function getPrevPage(string $label = null, int $count = 1): ?PaginationPage
{
return $this->getPage($this->page - $count, $label ?? $this->getOptions()['label_prev'] ?? null);
}
/**
* @param string|null $label
* @param int $count
* @return PaginationPage|null
*/
public function getNextPage(string $label = null, int $count = 1): ?PaginationPage
{
return $this->getPage($this->page + $count, $label ?? $this->getOptions()['label_next'] ?? null);
}
/**
* @param string|null $label
* @param int $count
* @return PaginationPage|null
*/
public function getLastPage(string $label = null, int $count = 0): ?PaginationPage
{
return $this->getPage($this->pages - $count, $label ?? $this->getOptions()['label_last'] ?? null);
}
/**
* @return int
*/
public function getStart(): int
{
return $this->start ?? 0;
}
/**
* @return int
*/
public function getLimit(): int
{
return $this->limit;
}
/**
* @return int
*/
public function getTotal(): int
{
return $this->total;
}
/**
* @return int
*/
public function count(): int
{
$this->loadItems();
return count($this->items);
}
/**
* @return ArrayIterator
* @phpstan-return ArrayIterator<int,PaginationPage>
*/
#[\ReturnTypeWillChange]
public function getIterator()
{
$this->loadItems();
return new ArrayIterator($this->items);
}
/**
* @return array
*/
public function getPages(): array
{
$this->loadItems();
return $this->items;
}
/**
* @return void
*/
protected function loadItems()
{
$this->calculateRange();
// Make list like: 1 ... 4 5 6 ... 10
$range = range($this->pagesStart, $this->pagesStop);
//$range[] = 1;
//$range[] = $this->pages;
natsort($range);
$range = array_unique($range);
$this->items = [];
foreach ($range as $i) {
$this->items[$i] = $this->getPage($i);
}
}
/**
* @param Route $route
* @return $this
*/
protected function setRoute(Route $route)
{
$this->route = $route;
return $this;
}
/**
* @param array|null $options
* @return $this
*/
protected function setOptions(array $options = null)
{
$this->options = $options ? array_merge($this->defaultOptions, $options) : $this->defaultOptions;
return $this;
}
/**
* @param int|null $page
* @return $this
*/
protected function setPage(int $page = null)
{
$this->page = (int)max($page, 1);
$this->start = null;
return $this;
}
/**
* @param int|null $start
* @return $this
*/
protected function setStart(int $start = null)
{
$this->start = (int)max($start, 0);
$this->page = null;
return $this;
}
/**
* @param int|null $limit
* @return $this
*/
protected function setLimit(int $limit = null)
{
$this->limit = (int)max($limit ?? $this->getOptions()['limit'], 0);
// No limit, display all records in a single page.
$this->viewAll = !$limit;
return $this;
}
/**
* @param int $total
* @return $this
*/
protected function setTotal(int $total)
{
$this->total = (int)max($total, 0);
return $this;
}
/**
* @param Route $route
* @param int $total
* @param int|null $pos
* @param int|null $limit
* @param array|null $options
* @return void
*/
protected function initialize(Route $route, int $total, int $pos = null, int $limit = null, array $options = null)
{
$this->setRoute($route);
$this->setOptions($options);
$this->setTotal($total);
if ($this->getOptions()['type'] === 'start') {
$this->setStart($pos);
} else {
$this->setPage($pos);
}
$this->setLimit($limit);
$this->calculateLimits();
}
/**
* @return void
*/
protected function calculateLimits()
{
$limit = $this->limit;
$total = $this->total;
if (!$limit || $limit > $total) {
// All records fit into a single page.
$this->start = 0;
$this->page = 1;
$this->pages = 1;
return;
}
if (null === $this->start) {
// If we are using page, convert it to start.
$this->start = (int)(($this->page - 1) * $limit);
}
if ($this->start > $total - $limit) {
// If start is greater than total count (i.e. we are asked to display records that don't exist)
// then set start to display the last natural page of results.
$this->start = (int)max(0, (ceil($total / $limit) - 1) * $limit);
}
// Set the total pages and current page values.
$this->page = (int)ceil(($this->start + 1) / $limit);
$this->pages = (int)ceil($total / $limit);
}
/**
* @return void
*/
protected function calculateRange()
{
$options = $this->getOptions();
$displayed = $options['display'];
$opening = $options['opening'];
$ending = $options['ending'];
// Set the pagination iteration loop values.
$this->pagesStart = $this->page - (int)($displayed / 2);
if ($this->pagesStart < 1 + $opening) {
$this->pagesStart = 1 + $opening;
}
if ($this->pagesStart + $displayed - $opening > $this->pages) {
$this->pagesStop = $this->pages;
if ($this->pages < $displayed) {
$this->pagesStart = 1 + $opening;
} else {
$this->pagesStart = $this->pages - $displayed + 1 + $opening;
}
} else {
$this->pagesStop = (int)max(1, $this->pagesStart + $displayed - 1 - $ending);
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Pagination/Pagination.php | system/src/Grav/Framework/Pagination/Pagination.php | <?php
/**
* @package Grav\Framework\Pagination
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Pagination;
use Grav\Framework\Route\Route;
/**
* Class Pagination
* @package Grav\Framework\Pagination
*/
class Pagination extends AbstractPagination
{
/**
* Pagination constructor.
* @param Route $route
* @param int $total
* @param int|null $pos
* @param int|null $limit
* @param array|null $options
*/
public function __construct(Route $route, int $total, int $pos = null, int $limit = null, array $options = null)
{
$this->initialize($route, $total, $pos, $limit, $options);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Pagination/PaginationPage.php | system/src/Grav/Framework/Pagination/PaginationPage.php | <?php
/**
* @package Grav\Framework\Pagination
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Pagination;
/**
* Class PaginationPage
* @package Grav\Framework\Pagination
*/
class PaginationPage extends AbstractPaginationPage
{
/**
* PaginationPage constructor.
* @param array $options
*/
public function __construct(array $options = [])
{
$this->setOptions($options);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Pagination/AbstractPaginationPage.php | system/src/Grav/Framework/Pagination/AbstractPaginationPage.php | <?php
/**
* @package Grav\Framework\Pagination
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Pagination;
use Grav\Framework\Pagination\Interfaces\PaginationPageInterface;
/**
* Class AbstractPaginationPage
* @package Grav\Framework\Pagination
*/
abstract class AbstractPaginationPage implements PaginationPageInterface
{
/** @var array */
protected $options;
/**
* @return bool
*/
public function isActive(): bool
{
return $this->options['active'] ?? false;
}
/**
* @return bool
*/
public function isEnabled(): bool
{
return $this->options['enabled'] ?? false;
}
/**
* @return array
*/
public function getOptions(): array
{
return $this->options;
}
/**
* @return int|null
*/
public function getNumber(): ?int
{
return $this->options['number'] ?? null;
}
/**
* @return string
*/
public function getLabel(): string
{
return $this->options['label'] ?? (string)$this->getNumber();
}
/**
* @return string|null
*/
public function getUrl(): ?string
{
return $this->options['route'] ? (string)$this->options['route']->getUri() : null;
}
/**
* @param array $options
*/
protected function setOptions(array $options): void
{
$this->options = $options;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Pagination/Interfaces/PaginationInterface.php | system/src/Grav/Framework/Pagination/Interfaces/PaginationInterface.php | <?php
/**
* @package Grav\Framework\Pagination
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Pagination\Interfaces;
use Countable;
use Grav\Framework\Pagination\PaginationPage;
use IteratorAggregate;
/**
* Interface PaginationInterface
* @package Grav\Framework\Pagination\Interfaces
* @extends IteratorAggregate<int,PaginationPage>
*/
interface PaginationInterface extends Countable, IteratorAggregate
{
/**
* @return int
*/
public function getTotalPages(): int;
/**
* @return int
*/
public function getPageNumber(): int;
/**
* @param int $count
* @return int|null
*/
public function getPrevNumber(int $count = 1): ?int;
/**
* @param int $count
* @return int|null
*/
public function getNextNumber(int $count = 1): ?int;
/**
* @return int
*/
public function getStart(): int;
/**
* @return int
*/
public function getLimit(): int;
/**
* @return int
*/
public function getTotal(): int;
/**
* @return int
*/
public function count(): int;
/**
* @return array
*/
public function getOptions(): array;
/**
* @param int $page
* @param string|null $label
* @return PaginationPage|null
*/
public function getPage(int $page, string $label = null): ?PaginationPage;
/**
* @param string|null $label
* @param int $count
* @return PaginationPage|null
*/
public function getFirstPage(string $label = null, int $count = 0): ?PaginationPage;
/**
* @param string|null $label
* @param int $count
* @return PaginationPage|null
*/
public function getPrevPage(string $label = null, int $count = 1): ?PaginationPage;
/**
* @param string|null $label
* @param int $count
* @return PaginationPage|null
*/
public function getNextPage(string $label = null, int $count = 1): ?PaginationPage;
/**
* @param string|null $label
* @param int $count
* @return PaginationPage|null
*/
public function getLastPage(string $label = null, int $count = 0): ?PaginationPage;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Pagination/Interfaces/PaginationPageInterface.php | system/src/Grav/Framework/Pagination/Interfaces/PaginationPageInterface.php | <?php
/**
* @package Grav\Framework\Pagination
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Pagination\Interfaces;
/**
* Interface PaginationPageInterface
* @package Grav\Framework\Pagination\Interfaces
*/
interface PaginationPageInterface
{
/**
* @return bool
*/
public function isActive(): bool;
/**
* @return bool
*/
public function isEnabled(): bool;
/**
* @return array
*/
public function getOptions(): array;
/**
* @return int|null
*/
public function getNumber(): ?int;
/**
* @return string
*/
public function getLabel(): string;
/**
* @return string|null
*/
public function getUrl(): ?string;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Psr7/ServerRequest.php | system/src/Grav/Framework/Psr7/ServerRequest.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Psr7
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Psr7;
use Grav\Framework\Psr7\Traits\ServerRequestDecoratorTrait;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UriInterface;
use function is_array;
use function is_object;
/**
* Class ServerRequest
* @package Slim\Http
*/
class ServerRequest implements ServerRequestInterface
{
use ServerRequestDecoratorTrait;
/**
* @param string $method HTTP method
* @param string|UriInterface $uri URI
* @param array $headers Request headers
* @param string|null|resource|StreamInterface $body Request body
* @param string $version Protocol version
* @param array $serverParams Typically the $_SERVER superglobal
*/
public function __construct(string $method, $uri, array $headers = [], $body = null, string $version = '1.1', array $serverParams = [])
{
$this->message = new \Nyholm\Psr7\ServerRequest($method, $uri, $headers, $body, $version, $serverParams);
}
/**
* Get serverRequest content character set, if known.
*
* Note: This method is not part of the PSR-7 standard.
*
* @return string|null
*/
public function getContentCharset(): ?string
{
$mediaTypeParams = $this->getMediaTypeParams();
if (isset($mediaTypeParams['charset'])) {
return $mediaTypeParams['charset'];
}
return null;
}
/**
* Get serverRequest content type.
*
* Note: This method is not part of the PSR-7 standard.
*
* @return string|null The serverRequest content type, if known
*/
public function getContentType(): ?string
{
$result = $this->getRequest()->getHeader('Content-Type');
return $result ? $result[0] : null;
}
/**
* Get serverRequest content length, if known.
*
* Note: This method is not part of the PSR-7 standard.
*
* @return int|null
*/
public function getContentLength(): ?int
{
$result = $this->getRequest()->getHeader('Content-Length');
return $result ? (int) $result[0] : null;
}
/**
* Fetch cookie value from cookies sent by the client to the server.
*
* Note: This method is not part of the PSR-7 standard.
*
* @param string $key The attribute name.
* @param mixed $default Default value to return if the attribute does not exist.
*
* @return mixed
*/
public function getCookieParam($key, $default = null)
{
$cookies = $this->getRequest()->getCookieParams();
return $cookies[$key] ?? $default;
}
/**
* Get serverRequest media type, if known.
*
* Note: This method is not part of the PSR-7 standard.
*
* @return string|null The serverRequest media type, minus content-type params
*/
public function getMediaType(): ?string
{
$contentType = $this->getContentType();
if ($contentType) {
$contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType);
if ($contentTypeParts === false) {
return null;
}
return strtolower($contentTypeParts[0]);
}
return null;
}
/**
* Get serverRequest media type params, if known.
*
* Note: This method is not part of the PSR-7 standard.
*
* @return mixed[]
*/
public function getMediaTypeParams(): array
{
$contentType = $this->getContentType();
$contentTypeParams = [];
if ($contentType) {
$contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType);
if ($contentTypeParts !== false) {
$contentTypePartsLength = count($contentTypeParts);
for ($i = 1; $i < $contentTypePartsLength; $i++) {
$paramParts = explode('=', $contentTypeParts[$i]);
$contentTypeParams[strtolower($paramParts[0])] = $paramParts[1];
}
}
}
return $contentTypeParams;
}
/**
* Fetch serverRequest parameter value from body or query string (in that order).
*
* Note: This method is not part of the PSR-7 standard.
*
* @param string $key The parameter key.
* @param string|null $default The default value.
*
* @return mixed The parameter value.
*/
public function getParam($key, $default = null)
{
$postParams = $this->getParsedBody();
$getParams = $this->getQueryParams();
$result = $default;
if (is_array($postParams) && isset($postParams[$key])) {
$result = $postParams[$key];
} elseif (is_object($postParams) && property_exists($postParams, $key)) {
$result = $postParams->$key;
} elseif (isset($getParams[$key])) {
$result = $getParams[$key];
}
return $result;
}
/**
* Fetch associative array of body and query string parameters.
*
* Note: This method is not part of the PSR-7 standard.
*
* @return mixed[]
*/
public function getParams(): array
{
$params = $this->getQueryParams();
$postParams = $this->getParsedBody();
if ($postParams) {
$params = array_merge($params, (array)$postParams);
}
return $params;
}
/**
* Fetch parameter value from serverRequest body.
*
* Note: This method is not part of the PSR-7 standard.
*
* @param string $key
* @param mixed $default
*
* @return mixed
*/
public function getParsedBodyParam($key, $default = null)
{
$postParams = $this->getParsedBody();
$result = $default;
if (is_array($postParams) && isset($postParams[$key])) {
$result = $postParams[$key];
} elseif (is_object($postParams) && property_exists($postParams, $key)) {
$result = $postParams->{$key};
}
return $result;
}
/**
* Fetch parameter value from query string.
*
* Note: This method is not part of the PSR-7 standard.
*
* @param string $key
* @param mixed $default
*
* @return mixed
*/
public function getQueryParam($key, $default = null)
{
$getParams = $this->getQueryParams();
return $getParams[$key] ?? $default;
}
/**
* Retrieve a server parameter.
*
* Note: This method is not part of the PSR-7 standard.
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public function getServerParam($key, $default = null)
{
$serverParams = $this->getRequest()->getServerParams();
return $serverParams[$key] ?? $default;
}
/**
* Does this serverRequest use a given method?
*
* Note: This method is not part of the PSR-7 standard.
*
* @param string $method HTTP method
* @return bool
*/
public function isMethod($method): bool
{
return $this->getRequest()->getMethod() === $method;
}
/**
* Is this a DELETE serverRequest?
*
* Note: This method is not part of the PSR-7 standard.
*
* @return bool
*/
public function isDelete(): bool
{
return $this->isMethod('DELETE');
}
/**
* Is this a GET serverRequest?
*
* Note: This method is not part of the PSR-7 standard.
*
* @return bool
*/
public function isGet(): bool
{
return $this->isMethod('GET');
}
/**
* Is this a HEAD serverRequest?
*
* Note: This method is not part of the PSR-7 standard.
*
* @return bool
*/
public function isHead(): bool
{
return $this->isMethod('HEAD');
}
/**
* Is this a OPTIONS serverRequest?
*
* Note: This method is not part of the PSR-7 standard.
*
* @return bool
*/
public function isOptions(): bool
{
return $this->isMethod('OPTIONS');
}
/**
* Is this a PATCH serverRequest?
*
* Note: This method is not part of the PSR-7 standard.
*
* @return bool
*/
public function isPatch(): bool
{
return $this->isMethod('PATCH');
}
/**
* Is this a POST serverRequest?
*
* Note: This method is not part of the PSR-7 standard.
*
* @return bool
*/
public function isPost(): bool
{
return $this->isMethod('POST');
}
/**
* Is this a PUT serverRequest?
*
* Note: This method is not part of the PSR-7 standard.
*
* @return bool
*/
public function isPut(): bool
{
return $this->isMethod('PUT');
}
/**
* Is this an XHR serverRequest?
*
* Note: This method is not part of the PSR-7 standard.
*
* @return bool
*/
public function isXhr(): bool
{
return $this->getRequest()->getHeaderLine('X-Requested-With') === 'XMLHttpRequest';
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Psr7/AbstractUri.php | system/src/Grav/Framework/Psr7/AbstractUri.php | <?php
/**
* @package Grav\Framework\Psr7
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Psr7;
use Grav\Framework\Uri\UriPartsFilter;
use InvalidArgumentException;
use Psr\Http\Message\UriInterface;
/**
* Bare minimum PSR7 implementation.
*
* @package Grav\Framework\Uri\Psr7
* @deprecated 1.6 Using message PSR-7 decorators instead.
*/
abstract class AbstractUri implements UriInterface
{
/** @var array */
protected static $defaultPorts = [
'http' => 80,
'https' => 443
];
/** @var string Uri scheme. */
private $scheme = '';
/** @var string Uri user. */
private $user = '';
/** @var string Uri password. */
private $password = '';
/** @var string Uri host. */
private $host = '';
/** @var int|null Uri port. */
private $port;
/** @var string Uri path. */
private $path = '';
/** @var string Uri query string (without ?). */
private $query = '';
/** @var string Uri fragment (without #). */
private $fragment = '';
/**
* Please define constructor which calls $this->init().
*/
abstract public function __construct();
/**
* @inheritdoc
*/
public function getScheme()
{
return $this->scheme;
}
/**
* @inheritdoc
*/
public function getAuthority()
{
$authority = $this->host;
$userInfo = $this->getUserInfo();
if ($userInfo !== '') {
$authority = $userInfo . '@' . $authority;
}
if ($this->port !== null) {
$authority .= ':' . $this->port;
}
return $authority;
}
/**
* @inheritdoc
*/
public function getUserInfo()
{
$userInfo = $this->user;
if ($this->password !== '') {
$userInfo .= ':' . $this->password;
}
return $userInfo;
}
/**
* @inheritdoc
*/
public function getHost()
{
return $this->host;
}
/**
* @inheritdoc
*/
public function getPort()
{
return $this->port;
}
/**
* @inheritdoc
*/
public function getPath()
{
return $this->path;
}
/**
* @inheritdoc
*/
public function getQuery()
{
return $this->query;
}
/**
* @inheritdoc
*/
public function getFragment()
{
return $this->fragment;
}
/**
* @inheritdoc
*/
public function withScheme($scheme)
{
$scheme = UriPartsFilter::filterScheme($scheme);
if ($this->scheme === $scheme) {
return $this;
}
$new = clone $this;
$new->scheme = $scheme;
$new->unsetDefaultPort();
$new->validate();
return $new;
}
/**
* @inheritdoc
* @throws InvalidArgumentException
*/
public function withUserInfo($user, $password = null)
{
$user = UriPartsFilter::filterUserInfo($user);
$password = UriPartsFilter::filterUserInfo($password ?? '');
if ($this->user === $user && $this->password === $password) {
return $this;
}
$new = clone $this;
$new->user = $user;
$new->password = $user !== '' ? $password : '';
$new->validate();
return $new;
}
/**
* @inheritdoc
*/
public function withHost($host)
{
$host = UriPartsFilter::filterHost($host);
if ($this->host === $host) {
return $this;
}
$new = clone $this;
$new->host = $host;
$new->validate();
return $new;
}
/**
* @inheritdoc
*/
public function withPort($port)
{
$port = UriPartsFilter::filterPort($port);
if ($this->port === $port) {
return $this;
}
$new = clone $this;
$new->port = $port;
$new->unsetDefaultPort();
$new->validate();
return $new;
}
/**
* @inheritdoc
*/
public function withPath($path)
{
$path = UriPartsFilter::filterPath($path);
if ($this->path === $path) {
return $this;
}
$new = clone $this;
$new->path = $path;
$new->validate();
return $new;
}
/**
* @inheritdoc
*/
public function withQuery($query)
{
$query = UriPartsFilter::filterQueryOrFragment($query);
if ($this->query === $query) {
return $this;
}
$new = clone $this;
$new->query = $query;
return $new;
}
/**
* @inheritdoc
* @throws InvalidArgumentException
*/
public function withFragment($fragment)
{
$fragment = UriPartsFilter::filterQueryOrFragment($fragment);
if ($this->fragment === $fragment) {
return $this;
}
$new = clone $this;
$new->fragment = $fragment;
return $new;
}
/**
* @return string
*/
#[\ReturnTypeWillChange]
public function __toString()
{
return $this->getUrl();
}
/**
* @return array
*/
protected function getParts()
{
return [
'scheme' => $this->scheme,
'host' => $this->host,
'port' => $this->port,
'user' => $this->user,
'pass' => $this->password,
'path' => $this->path,
'query' => $this->query,
'fragment' => $this->fragment
];
}
/**
* Return the fully qualified base URL ( like http://getgrav.org ).
*
* Note that this method never includes a trailing /
*
* @return string
*/
protected function getBaseUrl()
{
$uri = '';
$scheme = $this->getScheme();
if ($scheme !== '') {
$uri .= $scheme . ':';
}
$authority = $this->getAuthority();
if ($authority !== '' || $scheme === 'file') {
$uri .= '//' . $authority;
}
return $uri;
}
/**
* @return string
*/
protected function getUrl()
{
$uri = $this->getBaseUrl() . $this->getPath();
$query = $this->getQuery();
if ($query !== '') {
$uri .= '?' . $query;
}
$fragment = $this->getFragment();
if ($fragment !== '') {
$uri .= '#' . $fragment;
}
return $uri;
}
/**
* @return string
*/
protected function getUser()
{
return $this->user;
}
/**
* @return string
*/
protected function getPassword()
{
return $this->password;
}
/**
* @param array $parts
* @return void
* @throws InvalidArgumentException
*/
protected function initParts(array $parts)
{
$this->scheme = isset($parts['scheme']) ? UriPartsFilter::filterScheme($parts['scheme']) : '';
$this->user = isset($parts['user']) ? UriPartsFilter::filterUserInfo($parts['user']) : '';
$this->password = isset($parts['pass']) ? UriPartsFilter::filterUserInfo($parts['pass']) : '';
$this->host = isset($parts['host']) ? UriPartsFilter::filterHost($parts['host']) : '';
$this->port = isset($parts['port']) ? UriPartsFilter::filterPort((int)$parts['port']) : null;
$this->path = isset($parts['path']) ? UriPartsFilter::filterPath($parts['path']) : '';
$this->query = isset($parts['query']) ? UriPartsFilter::filterQueryOrFragment($parts['query']) : '';
$this->fragment = isset($parts['fragment']) ? UriPartsFilter::filterQueryOrFragment($parts['fragment']) : '';
$this->unsetDefaultPort();
$this->validate();
}
/**
* @return void
* @throws InvalidArgumentException
*/
private function validate()
{
if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) {
throw new InvalidArgumentException('Uri with a scheme must have a host');
}
if ($this->getAuthority() === '') {
if (0 === strpos($this->path, '//')) {
throw new InvalidArgumentException('The path of a URI without an authority must not start with two slashes \'//\'');
}
if ($this->scheme === '' && false !== strpos(explode('/', $this->path, 2)[0], ':')) {
throw new InvalidArgumentException('A relative URI must not have a path beginning with a segment containing a colon');
}
} elseif (isset($this->path[0]) && $this->path[0] !== '/') {
throw new InvalidArgumentException('The path of a URI with an authority must start with a slash \'/\' or be empty');
}
}
/**
* @return bool
*/
protected function isDefaultPort()
{
$scheme = $this->scheme;
$port = $this->port;
return $this->port === null
|| (isset(static::$defaultPorts[$scheme]) && $port === static::$defaultPorts[$scheme]);
}
/**
* @return void
*/
private function unsetDefaultPort()
{
if ($this->isDefaultPort()) {
$this->port = null;
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Psr7/Uri.php | system/src/Grav/Framework/Psr7/Uri.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Psr7
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Psr7;
use Grav\Framework\Psr7\Traits\UriDecorationTrait;
use Grav\Framework\Uri\UriFactory;
use GuzzleHttp\Psr7\Uri as GuzzleUri;
use Psr\Http\Message\UriInterface;
/**
* Class Uri
* @package Grav\Framework\Psr7
*/
class Uri implements UriInterface
{
use UriDecorationTrait;
public function __construct(string $uri = '')
{
$this->uri = new \Nyholm\Psr7\Uri($uri);
}
/**
* @return array
*/
public function getQueryParams(): array
{
return UriFactory::parseQuery($this->getQuery());
}
/**
* @param array $params
* @return UriInterface
*/
public function withQueryParams(array $params): UriInterface
{
$query = UriFactory::buildQuery($params);
return $this->withQuery($query);
}
/**
* Whether the URI has the default port of the current scheme.
*
* `$uri->getPort()` may return the standard port. This method can be used for some non-http/https Uri.
*
* @return bool
*/
public function isDefaultPort(): bool
{
return $this->getPort() === null || GuzzleUri::isDefaultPort($this);
}
/**
* Whether the URI is absolute, i.e. it has a scheme.
*
* An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true
* if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative
* to another URI, the base URI. Relative references can be divided into several forms:
* - network-path references, e.g. '//example.com/path'
* - absolute-path references, e.g. '/path'
* - relative-path references, e.g. 'subpath'
*
* @return bool
* @link https://tools.ietf.org/html/rfc3986#section-4
*/
public function isAbsolute(): bool
{
return GuzzleUri::isAbsolute($this);
}
/**
* Whether the URI is a network-path reference.
*
* A relative reference that begins with two slash characters is termed an network-path reference.
*
* @return bool
* @link https://tools.ietf.org/html/rfc3986#section-4.2
*/
public function isNetworkPathReference(): bool
{
return GuzzleUri::isNetworkPathReference($this);
}
/**
* Whether the URI is a absolute-path reference.
*
* A relative reference that begins with a single slash character is termed an absolute-path reference.
*
* @return bool
* @link https://tools.ietf.org/html/rfc3986#section-4.2
*/
public function isAbsolutePathReference(): bool
{
return GuzzleUri::isAbsolutePathReference($this);
}
/**
* Whether the URI is a relative-path reference.
*
* A relative reference that does not begin with a slash character is termed a relative-path reference.
*
* @return bool
* @link https://tools.ietf.org/html/rfc3986#section-4.2
*/
public function isRelativePathReference(): bool
{
return GuzzleUri::isRelativePathReference($this);
}
/**
* Whether the URI is a same-document reference.
*
* A same-document reference refers to a URI that is, aside from its fragment
* component, identical to the base URI. When no base URI is given, only an empty
* URI reference (apart from its fragment) is considered a same-document reference.
*
* @param UriInterface|null $base An optional base URI to compare against
* @return bool
* @link https://tools.ietf.org/html/rfc3986#section-4.4
*/
public function isSameDocumentReference(UriInterface $base = null): bool
{
return GuzzleUri::isSameDocumentReference($this, $base);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Psr7/Stream.php | system/src/Grav/Framework/Psr7/Stream.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Psr7
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Psr7;
use Grav\Framework\Psr7\Traits\StreamDecoratorTrait;
use Psr\Http\Message\StreamInterface;
/**
* Class Stream
* @package Grav\Framework\Psr7
*/
class Stream implements StreamInterface
{
use StreamDecoratorTrait;
/**
* @param string|resource|StreamInterface $body
* @return static
*/
public static function create($body = '')
{
return new static($body);
}
/**
* Stream constructor.
*
* @param string|resource|StreamInterface $body
*/
public function __construct($body = '')
{
$this->stream = \Nyholm\Psr7\Stream::create($body);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Psr7/Request.php | system/src/Grav/Framework/Psr7/Request.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Psr7
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Psr7;
use Grav\Framework\Psr7\Traits\RequestDecoratorTrait;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UriInterface;
class Request implements RequestInterface
{
use RequestDecoratorTrait;
/**
* @param string $method HTTP method
* @param string|UriInterface $uri URI
* @param array $headers Request headers
* @param string|null|resource|StreamInterface $body Request body
* @param string $version Protocol version
*/
public function __construct(string $method, $uri, array $headers = [], $body = null, string $version = '1.1')
{
$this->message = new \Nyholm\Psr7\Request($method, $uri, $headers, $body, $version);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Psr7/Response.php | system/src/Grav/Framework/Psr7/Response.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Psr7
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Psr7;
use Grav\Framework\Psr7\Traits\ResponseDecoratorTrait;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
use RuntimeException;
use function in_array;
/**
* Class Response
* @package Slim\Http
*/
class Response implements ResponseInterface
{
use ResponseDecoratorTrait;
/** @var string EOL characters used for HTTP response. */
private const EOL = "\r\n";
/**
* @param int $status Status code
* @param array $headers Response headers
* @param string|null|resource|StreamInterface $body Response body
* @param string $version Protocol version
* @param string|null $reason Reason phrase (optional)
*/
public function __construct(int $status = 200, array $headers = [], $body = null, string $version = '1.1', string $reason = null)
{
$this->message = new \Nyholm\Psr7\Response($status, $headers, $body, $version, $reason);
}
/**
* Json.
*
* Note: This method is not part of the PSR-7 standard.
*
* This method prepares the response object to return an HTTP Json
* response to the client.
*
* @param mixed $data The data
* @param int|null $status The HTTP status code.
* @param int $options Json encoding options
* @param int $depth Json encoding max depth
* @return static
* @phpstan-param positive-int $depth
*/
public function withJson($data, int $status = null, int $options = 0, int $depth = 512): ResponseInterface
{
$json = (string) json_encode($data, $options, $depth);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException(json_last_error_msg(), json_last_error());
}
$response = $this->getResponse()
->withHeader('Content-Type', 'application/json;charset=utf-8')
->withBody(new Stream($json));
if ($status !== null) {
$response = $response->withStatus($status);
}
$new = clone $this;
$new->message = $response;
return $new;
}
/**
* Redirect.
*
* Note: This method is not part of the PSR-7 standard.
*
* This method prepares the response object to return an HTTP Redirect
* response to the client.
*
* @param string $url The redirect destination.
* @param int|null $status The redirect HTTP status code.
* @return static
*/
public function withRedirect(string $url, $status = null): ResponseInterface
{
$response = $this->getResponse()->withHeader('Location', $url);
if ($status === null) {
$status = 302;
}
$new = clone $this;
$new->message = $response->withStatus($status);
return $new;
}
/**
* Is this response empty?
*
* Note: This method is not part of the PSR-7 standard.
*
* @return bool
*/
public function isEmpty(): bool
{
return in_array($this->getResponse()->getStatusCode(), [204, 205, 304], true);
}
/**
* Is this response OK?
*
* Note: This method is not part of the PSR-7 standard.
*
* @return bool
*/
public function isOk(): bool
{
return $this->getResponse()->getStatusCode() === 200;
}
/**
* Is this response a redirect?
*
* Note: This method is not part of the PSR-7 standard.
*
* @return bool
*/
public function isRedirect(): bool
{
return in_array($this->getResponse()->getStatusCode(), [301, 302, 303, 307, 308], true);
}
/**
* Is this response forbidden?
*
* Note: This method is not part of the PSR-7 standard.
*
* @return bool
* @api
*/
public function isForbidden(): bool
{
return $this->getResponse()->getStatusCode() === 403;
}
/**
* Is this response not Found?
*
* Note: This method is not part of the PSR-7 standard.
*
* @return bool
*/
public function isNotFound(): bool
{
return $this->getResponse()->getStatusCode() === 404;
}
/**
* Is this response informational?
*
* Note: This method is not part of the PSR-7 standard.
*
* @return bool
*/
public function isInformational(): bool
{
$response = $this->getResponse();
return $response->getStatusCode() >= 100 && $response->getStatusCode() < 200;
}
/**
* Is this response successful?
*
* Note: This method is not part of the PSR-7 standard.
*
* @return bool
*/
public function isSuccessful(): bool
{
$response = $this->getResponse();
return $response->getStatusCode() >= 200 && $response->getStatusCode() < 300;
}
/**
* Is this response a redirection?
*
* Note: This method is not part of the PSR-7 standard.
*
* @return bool
*/
public function isRedirection(): bool
{
$response = $this->getResponse();
return $response->getStatusCode() >= 300 && $response->getStatusCode() < 400;
}
/**
* Is this response a client error?
*
* Note: This method is not part of the PSR-7 standard.
*
* @return bool
*/
public function isClientError(): bool
{
$response = $this->getResponse();
return $response->getStatusCode() >= 400 && $response->getStatusCode() < 500;
}
/**
* Is this response a server error?
*
* Note: This method is not part of the PSR-7 standard.
*
* @return bool
*/
public function isServerError(): bool
{
$response = $this->getResponse();
return $response->getStatusCode() >= 500 && $response->getStatusCode() < 600;
}
/**
* Convert response to string.
*
* Note: This method is not part of the PSR-7 standard.
*
* @return string
*/
public function __toString(): string
{
$response = $this->getResponse();
$output = sprintf(
'HTTP/%s %s %s%s',
$response->getProtocolVersion(),
$response->getStatusCode(),
$response->getReasonPhrase(),
self::EOL
);
foreach ($response->getHeaders() as $name => $values) {
$output .= sprintf('%s: %s', $name, $response->getHeaderLine($name)) . self::EOL;
}
$output .= self::EOL;
$output .= $response->getBody();
return $output;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Psr7/UploadedFile.php | system/src/Grav/Framework/Psr7/UploadedFile.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Psr7
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Psr7;
use Grav\Framework\Psr7\Traits\UploadedFileDecoratorTrait;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UploadedFileInterface;
/**
* Class UploadedFile
* @package Grav\Framework\Psr7
*/
class UploadedFile implements UploadedFileInterface
{
use UploadedFileDecoratorTrait;
/** @var array */
private $meta = [];
/**
* @param StreamInterface|string|resource $streamOrFile
* @param int $size
* @param int $errorStatus
* @param string|null $clientFilename
* @param string|null $clientMediaType
*/
public function __construct($streamOrFile, $size, $errorStatus, $clientFilename = null, $clientMediaType = null)
{
$this->uploadedFile = new \Nyholm\Psr7\UploadedFile($streamOrFile, $size, $errorStatus, $clientFilename, $clientMediaType);
}
/**
* @param array $meta
* @return $this
*/
public function setMeta(array $meta)
{
$this->meta = $meta;
return $this;
}
/**
* @param array $meta
* @return $this
*/
public function addMeta(array $meta)
{
$this->meta = array_merge($this->meta, $meta);
return $this;
}
/**
* @return array
*/
public function getMeta(): array
{
return $this->meta;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Psr7/Traits/ResponseDecoratorTrait.php | system/src/Grav/Framework/Psr7/Traits/ResponseDecoratorTrait.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Psr7
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Psr7\Traits;
use Psr\Http\Message\ResponseInterface;
/**
* @author Márk Sági-Kazár <mark.sagikazar@gmail.com>
*/
trait ResponseDecoratorTrait
{
use MessageDecoratorTrait {
getMessage as private;
}
/**
* Returns the decorated response.
*
* Since the underlying Response is immutable as well
* exposing it is not an issue, because it's state cannot be altered
*
* @return ResponseInterface
*/
public function getResponse(): ResponseInterface
{
/** @var ResponseInterface $message */
$message = $this->getMessage();
return $message;
}
/**
* Exchanges the underlying response with another.
*
* @param ResponseInterface $response
*
* @return self
*/
public function withResponse(ResponseInterface $response): self
{
$new = clone $this;
$new->message = $response;
return $new;
}
/**
* {@inheritdoc}
*/
public function getStatusCode(): int
{
return $this->getResponse()->getStatusCode();
}
/**
* {@inheritdoc}
*/
public function withStatus($code, $reasonPhrase = ''): self
{
$new = clone $this;
$new->message = $this->getResponse()->withStatus($code, $reasonPhrase);
return $new;
}
/**
* {@inheritdoc}
*/
public function getReasonPhrase(): string
{
return $this->getResponse()->getReasonPhrase();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Psr7/Traits/StreamDecoratorTrait.php | system/src/Grav/Framework/Psr7/Traits/StreamDecoratorTrait.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Psr7
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Psr7\Traits;
use Psr\Http\Message\StreamInterface;
/**
* Trait StreamDecoratorTrait
* @package Grav\Framework\Psr7\Traits
*/
trait StreamDecoratorTrait
{
/** @var StreamInterface */
protected $stream;
/**
* {@inheritdoc}
*/
public function __toString(): string
{
return $this->stream->__toString();
}
/**
* @return void
*/
#[\ReturnTypeWillChange]
public function __destruct()
{
$this->stream->close();
}
/**
* {@inheritdoc}
*/
public function close(): void
{
$this->stream->close();
}
/**
* {@inheritdoc}
*/
public function detach()
{
return $this->stream->detach();
}
/**
* {@inheritdoc}
*/
public function getSize(): ?int
{
return $this->stream->getSize();
}
/**
* {@inheritdoc}
*/
public function tell(): int
{
return $this->stream->tell();
}
/**
* {@inheritdoc}
*/
public function eof(): bool
{
return $this->stream->eof();
}
/**
* {@inheritdoc}
*/
public function isSeekable(): bool
{
return $this->stream->isSeekable();
}
/**
* {@inheritdoc}
*/
public function seek($offset, $whence = \SEEK_SET): void
{
$this->stream->seek($offset, $whence);
}
/**
* {@inheritdoc}
*/
public function rewind(): void
{
$this->stream->rewind();
}
/**
* {@inheritdoc}
*/
public function isWritable(): bool
{
return $this->stream->isWritable();
}
/**
* {@inheritdoc}
*/
public function write($string): int
{
return $this->stream->write($string);
}
/**
* {@inheritdoc}
*/
public function isReadable(): bool
{
return $this->stream->isReadable();
}
/**
* {@inheritdoc}
*/
public function read($length): string
{
return $this->stream->read($length);
}
/**
* {@inheritdoc}
*/
public function getContents(): string
{
return $this->stream->getContents();
}
/**
* {@inheritdoc}
*/
public function getMetadata($key = null)
{
return $this->stream->getMetadata($key);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Psr7/Traits/MessageDecoratorTrait.php | system/src/Grav/Framework/Psr7/Traits/MessageDecoratorTrait.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Psr7
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Psr7\Traits;
use Psr\Http\Message\MessageInterface;
use Psr\Http\Message\StreamInterface;
/**
* @author Márk Sági-Kazár <mark.sagikazar@gmail.com>
*/
trait MessageDecoratorTrait
{
/** @var MessageInterface */
private $message;
/**
* Returns the decorated message.
*
* Since the underlying Message is immutable as well
* exposing it is not an issue, because it's state cannot be altered
*
* @return MessageInterface
*/
public function getMessage(): MessageInterface
{
return $this->message;
}
/**
* {@inheritdoc}
*/
public function getProtocolVersion(): string
{
return $this->message->getProtocolVersion();
}
/**
* {@inheritdoc}
*/
public function withProtocolVersion($version): self
{
$new = clone $this;
$new->message = $this->message->withProtocolVersion($version);
return $new;
}
/**
* {@inheritdoc}
*/
public function getHeaders(): array
{
return $this->message->getHeaders();
}
/**
* {@inheritdoc}
*/
public function hasHeader($header): bool
{
return $this->message->hasHeader($header);
}
/**
* {@inheritdoc}
*/
public function getHeader($header): array
{
return $this->message->getHeader($header);
}
/**
* {@inheritdoc}
*/
public function getHeaderLine($header): string
{
return $this->message->getHeaderLine($header);
}
/**
* {@inheritdoc}
*/
public function getBody(): StreamInterface
{
return $this->message->getBody();
}
/**
* {@inheritdoc}
*/
public function withHeader($header, $value): self
{
$new = clone $this;
$new->message = $this->message->withHeader($header, $value);
return $new;
}
/**
* {@inheritdoc}
*/
public function withAddedHeader($header, $value): self
{
$new = clone $this;
$new->message = $this->message->withAddedHeader($header, $value);
return $new;
}
/**
* {@inheritdoc}
*/
public function withoutHeader($header): self
{
$new = clone $this;
$new->message = $this->message->withoutHeader($header);
return $new;
}
/**
* {@inheritdoc}
*/
public function withBody(StreamInterface $body): self
{
$new = clone $this;
$new->message = $this->message->withBody($body);
return $new;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Psr7/Traits/UploadedFileDecoratorTrait.php | system/src/Grav/Framework/Psr7/Traits/UploadedFileDecoratorTrait.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Psr7
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Psr7\Traits;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UploadedFileInterface;
/**
* Trait UploadedFileDecoratorTrait
* @package Grav\Framework\Psr7\Traits
*/
trait UploadedFileDecoratorTrait
{
/** @var UploadedFileInterface */
protected $uploadedFile;
/**
* @return StreamInterface
*/
public function getStream(): StreamInterface
{
return $this->uploadedFile->getStream();
}
/**
* @param string $targetPath
*/
public function moveTo($targetPath): void
{
$this->uploadedFile->moveTo($targetPath);
}
/**
* @return int|null
*/
public function getSize(): ?int
{
return $this->uploadedFile->getSize();
}
/**
* @return int
*/
public function getError(): int
{
return $this->uploadedFile->getError();
}
/**
* @return string|null
*/
public function getClientFilename(): ?string
{
return $this->uploadedFile->getClientFilename();
}
/**
* @return string|null
*/
public function getClientMediaType(): ?string
{
return $this->uploadedFile->getClientMediaType();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Psr7/Traits/RequestDecoratorTrait.php | system/src/Grav/Framework/Psr7/Traits/RequestDecoratorTrait.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Psr7
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Psr7\Traits;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\UriInterface;
/**
* @author Márk Sági-Kazár <mark.sagikazar@gmail.com>
*/
trait RequestDecoratorTrait
{
use MessageDecoratorTrait {
getMessage as private;
}
/**
* Returns the decorated request.
*
* Since the underlying Request is immutable as well
* exposing it is not an issue, because it's state cannot be altered
*
* @return RequestInterface
*/
public function getRequest(): RequestInterface
{
/** @var RequestInterface $message */
$message = $this->getMessage();
return $message;
}
/**
* Exchanges the underlying request with another.
*
* @param RequestInterface $request
* @return self
*/
public function withRequest(RequestInterface $request): self
{
$new = clone $this;
$new->message = $request;
return $new;
}
/**
* {@inheritdoc}
*/
public function getRequestTarget(): string
{
return $this->getRequest()->getRequestTarget();
}
/**
* {@inheritdoc}
*/
public function withRequestTarget($requestTarget): self
{
$new = clone $this;
$new->message = $this->getRequest()->withRequestTarget($requestTarget);
return $new;
}
/**
* {@inheritdoc}
*/
public function getMethod(): string
{
return $this->getRequest()->getMethod();
}
/**
* {@inheritdoc}
*/
public function withMethod($method): self
{
$new = clone $this;
$new->message = $this->getRequest()->withMethod($method);
return $new;
}
/**
* {@inheritdoc}
*/
public function getUri(): UriInterface
{
return $this->getRequest()->getUri();
}
/**
* {@inheritdoc}
*/
public function withUri(UriInterface $uri, $preserveHost = false): self
{
$new = clone $this;
$new->message = $this->getRequest()->withUri($uri, $preserveHost);
return $new;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Psr7/Traits/UriDecorationTrait.php | system/src/Grav/Framework/Psr7/Traits/UriDecorationTrait.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Psr7
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Psr7\Traits;
use Psr\Http\Message\UriInterface;
/**
* Trait UriDecorationTrait
* @package Grav\Framework\Psr7\Traits
*/
trait UriDecorationTrait
{
/** @var UriInterface */
protected $uri;
/**
* @return string
*/
public function __toString(): string
{
return $this->uri->__toString();
}
/**
* @return string
*/
public function getScheme(): string
{
return $this->uri->getScheme();
}
/**
* @return string
*/
public function getAuthority(): string
{
return $this->uri->getAuthority();
}
/**
* @return string
*/
public function getUserInfo(): string
{
return $this->uri->getUserInfo();
}
/**
* @return string
*/
public function getHost(): string
{
return $this->uri->getHost();
}
/**
* @return int|null
*/
public function getPort(): ?int
{
return $this->uri->getPort();
}
/**
* @return string
*/
public function getPath(): string
{
return $this->uri->getPath();
}
/**
* @return string
*/
public function getQuery(): string
{
return $this->uri->getQuery();
}
/**
* @return string
*/
public function getFragment(): string
{
return $this->uri->getFragment();
}
/**
* @param string $scheme
* @return UriInterface
*/
public function withScheme($scheme): UriInterface
{
$new = clone $this;
$new->uri = $this->uri->withScheme($scheme);
/** @var UriInterface $new */
return $new;
}
/**
* @param string $user
* @param string|null $password
* @return UriInterface
*/
public function withUserInfo($user, $password = null): UriInterface
{
$new = clone $this;
$new->uri = $this->uri->withUserInfo($user, $password);
/** @var UriInterface $new */
return $new;
}
/**
* @param string $host
* @return UriInterface
*/
public function withHost($host): UriInterface
{
$new = clone $this;
$new->uri = $this->uri->withHost($host);
/** @var UriInterface $new */
return $new;
}
/**
* @param int|null $port
* @return UriInterface
*/
public function withPort($port): UriInterface
{
$new = clone $this;
$new->uri = $this->uri->withPort($port);
/** @var UriInterface $new */
return $new;
}
/**
* @param string $path
* @return UriInterface
*/
public function withPath($path): UriInterface
{
$new = clone $this;
$new->uri = $this->uri->withPath($path);
/** @var UriInterface $new */
return $new;
}
/**
* @param string $query
* @return UriInterface
*/
public function withQuery($query): UriInterface
{
$new = clone $this;
$new->uri = $this->uri->withQuery($query);
/** @var UriInterface $new */
return $new;
}
/**
* @param string $fragment
* @return UriInterface
*/
public function withFragment($fragment): UriInterface
{
$new = clone $this;
$new->uri = $this->uri->withFragment($fragment);
/** @var UriInterface $new */
return $new;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Psr7/Traits/ServerRequestDecoratorTrait.php | system/src/Grav/Framework/Psr7/Traits/ServerRequestDecoratorTrait.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Psr7
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Psr7\Traits;
use Psr\Http\Message\ServerRequestInterface;
/**
* Trait ServerRequestDecoratorTrait
* @package Grav\Framework\Psr7\Traits
*/
trait ServerRequestDecoratorTrait
{
use RequestDecoratorTrait;
/**
* Returns the decorated request.
*
* Since the underlying Request is immutable as well
* exposing it is not an issue, because it's state cannot be altered
*
* @return ServerRequestInterface
*/
public function getRequest(): ServerRequestInterface
{
/** @var ServerRequestInterface $message */
$message = $this->getMessage();
return $message;
}
/**
* @inheritdoc
*/
public function getAttribute($name, $default = null)
{
return $this->getRequest()->getAttribute($name, $default);
}
/**
* @inheritdoc
*/
public function getAttributes()
{
return $this->getRequest()->getAttributes();
}
/**
* @inheritdoc
*/
public function getCookieParams()
{
return $this->getRequest()->getCookieParams();
}
/**
* @inheritdoc
*/
public function getParsedBody()
{
return $this->getRequest()->getParsedBody();
}
/**
* @inheritdoc
*/
public function getQueryParams()
{
return $this->getRequest()->getQueryParams();
}
/**
* @inheritdoc
*/
public function getServerParams()
{
return $this->getRequest()->getServerParams();
}
/**
* @inheritdoc
*/
public function getUploadedFiles()
{
return $this->getRequest()->getUploadedFiles();
}
/**
* @inheritdoc
*/
public function withAttribute($name, $value)
{
$new = clone $this;
$new->message = $this->getRequest()->withAttribute($name, $value);
return $new;
}
/**
* @param array $attributes
* @return ServerRequestInterface
*/
public function withAttributes(array $attributes)
{
$new = clone $this;
foreach ($attributes as $attribute => $value) {
$new->message = $new->withAttribute($attribute, $value);
}
return $new;
}
/**
* @inheritdoc
*/
public function withoutAttribute($name)
{
$new = clone $this;
$new->message = $this->getRequest()->withoutAttribute($name);
return $new;
}
/**
* @inheritdoc
*/
public function withCookieParams(array $cookies)
{
$new = clone $this;
$new->message = $this->getRequest()->withCookieParams($cookies);
return $new;
}
/**
* @inheritdoc
*/
public function withParsedBody($data)
{
$new = clone $this;
$new->message = $this->getRequest()->withParsedBody($data);
return $new;
}
/**
* @inheritdoc
*/
public function withQueryParams(array $query)
{
$new = clone $this;
$new->message = $this->getRequest()->withQueryParams($query);
return $new;
}
/**
* @inheritdoc
*/
public function withUploadedFiles(array $uploadedFiles)
{
$new = clone $this;
$new->message = $this->getRequest()->withUploadedFiles($uploadedFiles);
return $new;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/FlexIndex.php | system/src/Grav/Framework/Flex/FlexIndex.php | <?php
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex;
use Exception;
use Grav\Common\Debugger;
use Grav\Common\File\CompiledJsonFile;
use Grav\Common\File\CompiledYamlFile;
use Grav\Common\Grav;
use Grav\Common\Inflector;
use Grav\Common\Session;
use Grav\Framework\Cache\CacheInterface;
use Grav\Framework\Collection\CollectionInterface;
use Grav\Framework\Flex\Interfaces\FlexCollectionInterface;
use Grav\Framework\Flex\Interfaces\FlexIndexInterface;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
use Grav\Framework\Flex\Interfaces\FlexStorageInterface;
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
* @package Grav\Framework\Flex
* @template T of FlexObjectInterface
* @template C of FlexCollectionInterface
* @extends ObjectIndex<string,T,C>
* @implements FlexIndexInterface<T>
* @mixin C
*/
class FlexIndex extends ObjectIndex implements FlexIndexInterface
{
const VERSION = 1;
/** @var FlexDirectory|null */
private $_flexDirectory;
/** @var string */
private $_keyField = 'storage_key';
/** @var array */
private $_indexKeys;
/**
* @param FlexDirectory $directory
* @return static
* @phpstan-return static<T,C>
*/
public static function createFromStorage(FlexDirectory $directory)
{
return static::createFromArray(static::loadEntriesFromStorage($directory->getStorage()), $directory);
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::createFromArray()
*/
public static function createFromArray(array $entries, FlexDirectory $directory, string $keyField = null)
{
$instance = new static($entries, $directory);
$instance->setKeyField($keyField);
return $instance;
}
/**
* @param FlexStorageInterface $storage
* @return array
*/
public static function loadEntriesFromStorage(FlexStorageInterface $storage): array
{
return $storage->getExistingKeys();
}
/**
* You can define indexes for fast lookup.
*
* Primary key: $meta['key']
* Secondary keys: $meta['my_field']
*
* @param array $meta
* @param array $data
* @param FlexStorageInterface $storage
* @return void
*/
public static function updateObjectMeta(array &$meta, array $data, FlexStorageInterface $storage)
{
// For backwards compatibility, no need to call this method when you override this method.
static::updateIndexData($meta, $data);
}
/**
* Initializes a new FlexIndex.
*
* @param array $entries
* @param FlexDirectory|null $directory
*/
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);
}
parent::__construct($entries);
$this->_flexDirectory = $directory;
$this->setKeyField(null);
}
/**
* @return string
*/
public function getKey()
{
return $this->_key ?: $this->getFlexType() . '@@' . spl_object_hash($this);
}
/**
* {@inheritdoc}
* @see FlexCommonInterface::hasFlexFeature()
*/
public function hasFlexFeature(string $name): bool
{
return in_array($name, $this->getFlexFeatures(), true);
}
/**
* {@inheritdoc}
* @see FlexCommonInterface::hasFlexFeature()
*/
public function getFlexFeatures(): array
{
/** @var array $implements */
$implements = class_implements($this->getFlexDirectory()->getCollectionClass());
$list = [];
foreach ($implements as $interface) {
if ($pos = strrpos($interface, '\\')) {
$interface = substr($interface, $pos+1);
}
$list[] = Inflector::hyphenize(str_replace('Interface', '', $interface));
}
return $list;
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::search()
*/
public function search(string $search, $properties = null, array $options = null)
{
$directory = $this->getFlexDirectory();
$properties = $directory->getSearchProperties($properties);
$options = $directory->getSearchOptions($options);
return $this->__call('search', [$search, $properties, $options]);
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::sort()
*/
public function sort(array $orderings)
{
return $this->orderBy($orderings);
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::filterBy()
*/
public function filterBy(array $filters)
{
return $this->__call('filterBy', [$filters]);
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::getFlexType()
*/
public function getFlexType(): string
{
return $this->getFlexDirectory()->getFlexType();
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::getFlexDirectory()
*/
public function getFlexDirectory(): FlexDirectory
{
if (null === $this->_flexDirectory) {
throw new RuntimeException('Flex Directory not defined, object is not fully defined');
}
return $this->_flexDirectory;
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::getTimestamp()
*/
public function getTimestamp(): int
{
$timestamps = $this->getTimestamps();
return $timestamps ? max($timestamps) : time();
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::getCacheKey()
*/
public function getCacheKey(): string
{
return $this->getTypePrefix() . $this->getFlexType() . '.' . sha1(json_encode($this->getKeys()) . $this->_keyField);
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::getCacheChecksum()
*/
public function getCacheChecksum(): string
{
$list = [];
foreach ($this->getEntries() as $key => $value) {
$list[$key] = $value['checksum'] ?? $value['storage_timestamp'];
}
return sha1((string)json_encode($list));
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::getTimestamps()
*/
public function getTimestamps(): array
{
return $this->getIndexMap('storage_timestamp');
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::getStorageKeys()
*/
public function getStorageKeys(): array
{
return $this->getIndexMap('storage_key');
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::getFlexKeys()
*/
public function getFlexKeys(): array
{
// Get storage keys for the objects.
$keys = [];
$type = $this->getFlexDirectory()->getFlexType() . '.obj:';
foreach ($this->getEntries() as $key => $value) {
$keys[$key] = $value['flex_key'] ?? $type . $value['storage_key'];
}
return $keys;
}
/**
* {@inheritdoc}
* @see FlexIndexInterface::withKeyField()
*/
public function withKeyField(string $keyField = null)
{
$keyField = $keyField ?: 'key';
if ($keyField === $this->getKeyField()) {
return $this;
}
$type = $keyField === 'flex_key' ? $this->getFlexDirectory()->getFlexType() . '.obj:' : '';
$entries = [];
foreach ($this->getEntries() as $key => $value) {
if (!isset($value['key'])) {
$value['key'] = $key;
}
if (isset($value[$keyField])) {
$entries[$value[$keyField]] = $value;
} elseif ($keyField === 'flex_key') {
$entries[$type . $value['storage_key']] = $value;
}
}
return $this->createFrom($entries, $keyField);
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::getIndex()
*/
public function getIndex()
{
return $this;
}
/**
* @return FlexCollectionInterface
* @phpstan-return C
*/
public function getCollection()
{
return $this->loadCollection();
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::render()
*/
public function render(string $layout = null, array $context = [])
{
return $this->__call('render', [$layout, $context]);
}
/**
* {@inheritdoc}
* @see FlexIndexInterface::getFlexKeys()
*/
public function getIndexMap(string $indexKey = null)
{
if (null === $indexKey) {
return $this->getEntries();
}
// Get storage keys for the objects.
$index = [];
foreach ($this->getEntries() as $key => $value) {
$index[$key] = $value[$indexKey] ?? null;
}
return $index;
}
/**
* @param string $key
* @return array
*/
public function getMetaData($key): array
{
return $this->getEntries()[$key] ?? [];
}
/**
* @return string
*/
public function getKeyField(): string
{
return $this->_keyField;
}
/**
* @param string|null $namespace
* @return CacheInterface
*/
public function getCache(string $namespace = null)
{
return $this->getFlexDirectory()->getCache($namespace);
}
/**
* @param array $orderings
* @return static
* @phpstan-return static<T,C>
*/
public function orderBy(array $orderings)
{
if (!$orderings || !$this->count()) {
return $this;
}
// Handle primary key alias.
$keyField = $this->getFlexDirectory()->getStorage()->getKeyField();
if ($keyField !== 'key' && $keyField !== 'storage_key' && isset($orderings[$keyField])) {
$orderings['key'] = $orderings[$keyField];
unset($orderings[$keyField]);
}
// Check if ordering needs to load the objects.
if (array_diff_key($orderings, $this->getIndexKeys())) {
return $this->__call('orderBy', [$orderings]);
}
// Ordering can be done by using index only.
$previous = null;
foreach (array_reverse($orderings) as $field => $ordering) {
$field = (string)$field;
if ($this->getKeyField() === $field) {
$keys = $this->getKeys();
$search = array_combine($keys, $keys) ?: [];
} elseif ($field === 'flex_key') {
$search = $this->getFlexKeys();
} else {
$search = $this->getIndexMap($field);
}
// Update current search to match the previous ordering.
if (null !== $previous) {
$search = array_replace($previous, $search);
}
// Order by current field.
if (strtoupper($ordering) === 'DESC') {
arsort($search, SORT_NATURAL | SORT_FLAG_CASE);
} else {
asort($search, SORT_NATURAL | SORT_FLAG_CASE);
}
$previous = $search;
}
return $this->createFrom(array_replace($previous ?? [], $this->getEntries()));
}
/**
* {@inheritDoc}
*/
public function call($method, array $arguments = [])
{
return $this->__call('call', [$method, $arguments]);
}
/**
* @param string $name
* @param array $arguments
* @return mixed
*/
#[\ReturnTypeWillChange]
public function __call($name, $arguments)
{
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
/** @phpstan-var class-string $className */
$className = $this->getFlexDirectory()->getCollectionClass();
$cachedMethods = $className::getCachedMethods();
$flexType = $this->getFlexType();
if (!empty($cachedMethods[$name])) {
$type = $cachedMethods[$name];
if ($type === 'session') {
/** @var Session $session */
$session = Grav::instance()['session'];
$cacheKey = $session->getId() . ($session->user->username ?? '');
} else {
$cacheKey = '';
}
$key = "{$flexType}.idx." . sha1($name . '.' . $cacheKey . json_encode($arguments) . $this->getCacheKey());
$checksum = $this->getCacheChecksum();
$cache = $this->getCache('object');
try {
$cached = $cache->get($key);
$test = $cached[0] ?? null;
$result = $test === $checksum ? ($cached[1] ?? null) : null;
// Make sure the keys aren't changed if the returned type is the same index type.
if ($result instanceof self && $flexType === $result->getFlexType()) {
$result = $result->withKeyField($this->getKeyField());
}
} catch (InvalidArgumentException $e) {
$debugger->addException($e);
}
if (!isset($result)) {
$collection = $this->loadCollection();
$result = $collection->{$name}(...$arguments);
$debugger->addMessage("Cache miss: '{$flexType}::{$name}()'", 'debug');
try {
// If flex collection is returned, convert it back to flex index.
if ($result instanceof FlexCollection) {
$cached = $result->getFlexDirectory()->getIndex($result->getKeys(), $this->getKeyField());
} else {
$cached = $result;
}
$cache->set($key, [$checksum, $cached]);
} catch (InvalidArgumentException $e) {
$debugger->addException($e);
// TODO: log error.
}
}
} else {
$collection = $this->loadCollection();
if (\is_callable([$collection, $name])) {
$result = $collection->{$name}(...$arguments);
if (!isset($cachedMethods[$name])) {
$debugger->addMessage("Call '{$flexType}:{$name}()' isn't cached", 'debug');
}
} else {
$result = null;
}
}
return $result;
}
/**
* @return array
*/
public function __serialize(): array
{
return ['type' => $this->getFlexType(), 'entries' => $this->getEntries()];
}
/**
* @param array $data
* @return void
*/
public function __unserialize(array $data): void
{
$this->_flexDirectory = Grav::instance()['flex']->getDirectory($data['type']);
$this->setEntries($data['entries']);
}
/**
* @return array
*/
#[\ReturnTypeWillChange]
public function __debugInfo()
{
return [
'type:private' => $this->getFlexType(),
'key:private' => $this->getKey(),
'entries_key:private' => $this->getKeyField(),
'entries:private' => $this->getEntries()
];
}
/**
* @param array $entries
* @param string|null $keyField
* @return static
* @phpstan-return static<T,C>
*/
protected function createFrom(array $entries, string $keyField = null)
{
/** @phpstan-var static<T,C> $index */
$index = new static($entries, $this->getFlexDirectory());
$index->setKeyField($keyField ?? $this->_keyField);
return $index;
}
/**
* @param string|null $keyField
* @return void
*/
protected function setKeyField(string $keyField = null)
{
$this->_keyField = $keyField ?? 'storage_key';
}
/**
* @return array
*/
protected function getIndexKeys()
{
if (null === $this->_indexKeys) {
$entries = $this->getEntries();
$first = reset($entries);
if ($first) {
$keys = array_keys($first);
$keys = array_combine($keys, $keys) ?: [];
} else {
$keys = [];
}
$this->setIndexKeys($keys);
}
return $this->_indexKeys;
}
/**
* @param array $indexKeys
* @return void
*/
protected function setIndexKeys(array $indexKeys)
{
// Add defaults.
$indexKeys += [
'key' => 'key',
'storage_key' => 'storage_key',
'storage_timestamp' => 'storage_timestamp',
'flex_key' => 'flex_key'
];
$this->_indexKeys = $indexKeys;
}
/**
* @return string
*/
protected function getTypePrefix()
{
return 'i.';
}
/**
* @param string $key
* @param mixed $value
* @return ObjectInterface|null
* @phpstan-return T|null
*/
protected function loadElement($key, $value): ?ObjectInterface
{
/** @phpstan-var T[] $objects */
$objects = $this->getFlexDirectory()->loadObjects([$key => $value]);
return $objects ? reset($objects): null;
}
/**
* @param array|null $entries
* @return ObjectInterface[]
* @phpstan-return T[]
*/
protected function loadElements(array $entries = null): array
{
/** @phpstan-var T[] $objects */
$objects = $this->getFlexDirectory()->loadObjects($entries ?? $this->getEntries());
return $objects;
}
/**
* @param array|null $entries
* @return CollectionInterface
* @phpstan-return C
*/
protected function loadCollection(array $entries = null): CollectionInterface
{
/** @var C $collection */
$collection = $this->getFlexDirectory()->loadCollection($entries ?? $this->getEntries(), $this->_keyField);
return $collection;
}
/**
* @param mixed $value
* @return bool
*/
protected function isAllowedElement($value): bool
{
return $value instanceof FlexObject;
}
/**
* @param FlexObjectInterface $object
* @return mixed
*/
protected function getElementMeta($object)
{
return $object->getMetaData();
}
/**
* @param FlexObjectInterface $element
* @return string
*/
protected function getCurrentKey($element)
{
$keyField = $this->getKeyField();
if ($keyField === 'storage_key') {
return $element->getStorageKey();
}
if ($keyField === 'flex_key') {
return $element->getFlexKey();
}
if ($keyField === 'key') {
return $element->getKey();
}
return $element->getKey();
}
/**
* @param FlexStorageInterface $storage
* @param array $index Saved index
* @param array $entries Updated index
* @param array $options
* @return array Compiled list of entries
*/
protected static function updateIndexFile(FlexStorageInterface $storage, array $index, array $entries, array $options = []): array
{
$indexFile = static::getIndexFile($storage);
if (null === $indexFile) {
return $entries;
}
// Calculate removed objects.
$removed = array_diff_key($index, $entries);
// First get rid of all removed objects.
if ($removed) {
$index = array_diff_key($index, $removed);
}
if ($entries && empty($options['force_update'])) {
// Calculate difference between saved index and current data.
foreach ($index as $key => $entry) {
$storage_key = $entry['storage_key'] ?? null;
if (isset($entries[$storage_key]) && $entries[$storage_key]['storage_timestamp'] === $entry['storage_timestamp']) {
// Entry is up to date, no update needed.
unset($entries[$storage_key]);
}
}
if (empty($entries) && empty($removed)) {
// No objects were added, updated or removed.
return $index;
}
} elseif (!$removed) {
// There are no objects and nothing was removed.
return [];
}
// Index should be updated, lock the index file for saving.
$indexFile->lock();
// Read all the data rows into an array using chunks of 100.
$keys = array_fill_keys(array_keys($entries), null);
$chunks = array_chunk($keys, 100, true);
$updated = $added = [];
foreach ($chunks as $keys) {
$rows = $storage->readRows($keys);
$keyField = $storage->getKeyField();
// Go through all the updated objects and refresh their index data.
foreach ($rows as $key => $row) {
if (null !== $row || !empty($options['include_missing'])) {
$entry = $entries[$key] + ['key' => $key];
if ($keyField !== 'storage_key' && isset($row[$keyField])) {
$entry['key'] = $row[$keyField];
}
static::updateObjectMeta($entry, $row ?? [], $storage);
if (isset($row['__ERROR'])) {
$entry['__ERROR'] = true;
static::onException(new RuntimeException(sprintf('Object failed to load: %s (%s)', $key,
$row['__ERROR'])));
}
if (isset($index[$key])) {
// Update object in the index.
$updated[$key] = $entry;
} else {
// Add object into the index.
$added[$key] = $entry;
}
// Either way, update the entry.
$index[$key] = $entry;
} elseif (isset($index[$key])) {
// Remove object from the index.
$removed[$key] = $index[$key];
unset($index[$key]);
}
}
unset($rows);
}
// Sort the index before saving it.
ksort($index, SORT_NATURAL | SORT_FLAG_CASE);
static::onChanges($index, $added, $updated, $removed);
$indexFile->save(['version' => static::VERSION, 'timestamp' => time(), 'count' => count($index), 'index' => $index]);
$indexFile->unlock();
return $index;
}
/**
* @param array $entry
* @param array $data
* @return void
* @deprecated 1.7 Use static ::updateObjectMeta() method instead.
*/
protected static function updateIndexData(array &$entry, array $data)
{
}
/**
* @param FlexStorageInterface $storage
* @return array
*/
protected static function loadIndex(FlexStorageInterface $storage)
{
$indexFile = static::getIndexFile($storage);
if ($indexFile) {
$data = [];
try {
$data = (array)$indexFile->content();
$version = $data['version'] ?? null;
if ($version !== static::VERSION) {
$data = [];
}
} catch (Exception $e) {
$e = new RuntimeException(sprintf('Index failed to load: %s', $e->getMessage()), $e->getCode(), $e);
static::onException($e);
}
if ($data) {
return $data;
}
}
return ['version' => static::VERSION, 'timestamp' => 0, 'count' => 0, 'index' => []];
}
/**
* @param FlexStorageInterface $storage
* @return array
*/
protected static function loadEntriesFromIndex(FlexStorageInterface $storage)
{
$data = static::loadIndex($storage);
return $data['index'] ?? [];
}
/**
* @param FlexStorageInterface $storage
* @return CompiledYamlFile|CompiledJsonFile|null
*/
protected static function getIndexFile(FlexStorageInterface $storage)
{
if (!method_exists($storage, 'isIndexed') || !$storage->isIndexed()) {
return null;
}
$path = $storage->getStoragePath();
if (!$path) {
return null;
}
// Load saved index file.
$grav = Grav::instance();
$locator = $grav['locator'];
$filename = $locator->findResource("{$path}/index.yaml", true, true);
return CompiledYamlFile::instance($filename);
}
/**
* @param Exception $e
* @return void
*/
protected static function onException(Exception $e)
{
$grav = Grav::instance();
/** @var Logger $logger */
$logger = $grav['log'];
$logger->addAlert($e->getMessage());
/** @var Debugger $debugger */
$debugger = $grav['debugger'];
$debugger->addException($e);
$debugger->addMessage($e, 'error');
}
/**
* @param array $entries
* @param array $added
* @param array $updated
* @param array $removed
* @return void
*/
protected static function onChanges(array $entries, array $added, array $updated, array $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);
$grav = Grav::instance();
/** @var Debugger $debugger */
$debugger = $grav['debugger'];
$debugger->addMessage($message, 'debug');
}
}
// DEPRECATED METHODS
/**
* @param bool $prefix
* @return string
* @deprecated 1.6 Use `->getFlexType()` instead.
*/
public function getType($prefix = false)
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->getFlexType() method instead', E_USER_DEPRECATED);
$type = $prefix ? $this->getTypePrefix() : '';
return $type . $this->getFlexType();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/FlexIdentifier.php | system/src/Grav/Framework/Flex/FlexIdentifier.php | <?php declare(strict_types=1);
namespace Grav\Framework\Flex;
use Grav\Common\Grav;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
use Grav\Framework\Object\Identifiers\Identifier;
use RuntimeException;
/**
* Interface IdentifierInterface
*
* @template T of FlexObjectInterface
* @extends Identifier<T>
*/
class FlexIdentifier extends Identifier
{
/** @var string */
private $keyField;
/** @var FlexObjectInterface|null */
private $object = null;
/**
* @param FlexObjectInterface $object
* @return FlexIdentifier<T>
*/
public static function createFromObject(FlexObjectInterface $object): FlexIdentifier
{
$instance = new static($object->getKey(), $object->getFlexType(), 'key');
$instance->setObject($object);
return $instance;
}
/**
* IdentifierInterface constructor.
* @param string $id
* @param string $type
* @param string $keyField
*/
public function __construct(string $id, string $type, string $keyField = 'key')
{
parent::__construct($id, $type);
$this->keyField = $keyField;
}
/**
* @return T
*/
public function getObject(): ?FlexObjectInterface
{
if (!isset($this->object)) {
/** @var Flex $flex */
$flex = Grav::instance()['flex'];
$this->object = $flex->getObject($this->getId(), $this->getType(), $this->keyField);
}
return $this->object;
}
/**
* @param T $object
*/
public function setObject(FlexObjectInterface $object): void
{
$type = $this->getType();
if ($type !== $object->getFlexType()) {
throw new RuntimeException(sprintf('Object has to be type %s, %s given', $type, $object->getFlexType()));
}
$this->object = $object;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/FlexCollection.php | system/src/Grav/Framework/Flex/FlexCollection.php | <?php
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\Criteria;
use Grav\Common\Debugger;
use Grav\Common\Grav;
use Grav\Common\Inflector;
use Grav\Common\Twig\Twig;
use Grav\Common\User\Interfaces\UserInterface;
use Grav\Common\Utils;
use Grav\Framework\Cache\CacheInterface;
use Grav\Framework\ContentBlock\HtmlBlock;
use Grav\Framework\Flex\Interfaces\FlexIndexInterface;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
use Grav\Framework\Object\ObjectCollection;
use Grav\Framework\Flex\Interfaces\FlexCollectionInterface;
use Psr\SimpleCache\InvalidArgumentException;
use RocketTheme\Toolbox\Event\Event;
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;
use function is_scalar;
/**
* Class FlexCollection
* @package Grav\Framework\Flex
* @template T of FlexObjectInterface
* @extends ObjectCollection<string,T>
* @implements FlexCollectionInterface<T>
*/
class FlexCollection extends ObjectCollection implements FlexCollectionInterface
{
/** @var FlexDirectory */
private $_flexDirectory;
/** @var string */
private $_keyField = 'storage_key';
/**
* Get list of cached methods.
*
* @return array Returns a list of methods with their caching information.
*/
public static function getCachedMethods(): array
{
return [
'getTypePrefix' => true,
'getType' => true,
'getFlexDirectory' => true,
'hasFlexFeature' => true,
'getFlexFeatures' => true,
'getCacheKey' => true,
'getCacheChecksum' => false,
'getTimestamp' => true,
'hasProperty' => true,
'getProperty' => true,
'hasNestedProperty' => true,
'getNestedProperty' => true,
'orderBy' => true,
'render' => false,
'isAuthorized' => 'session',
'search' => true,
'sort' => true,
'getDistinctValues' => true
];
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::createFromArray()
*/
public static function createFromArray(array $entries, FlexDirectory $directory, string $keyField = null)
{
$instance = new static($entries, $directory);
$instance->setKeyField($keyField);
return $instance;
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::__construct()
*/
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);
}
parent::__construct($entries);
if ($directory) {
$this->setFlexDirectory($directory)->setKey($directory->getFlexType());
}
}
/**
* {@inheritdoc}
* @see FlexCommonInterface::hasFlexFeature()
*/
public function hasFlexFeature(string $name): bool
{
return in_array($name, $this->getFlexFeatures(), true);
}
/**
* {@inheritdoc}
* @see FlexCommonInterface::hasFlexFeature()
*/
public function getFlexFeatures(): array
{
/** @var array $implements */
$implements = class_implements($this);
$list = [];
foreach ($implements as $interface) {
if ($pos = strrpos($interface, '\\')) {
$interface = substr($interface, $pos+1);
}
$list[] = Inflector::hyphenize(str_replace('Interface', '', $interface));
}
return $list;
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::search()
*/
public function search(string $search, $properties = null, array $options = null)
{
$directory = $this->getFlexDirectory();
$properties = $directory->getSearchProperties($properties);
$options = $directory->getSearchOptions($options);
$matching = $this->call('search', [$search, $properties, $options]);
$matching = array_filter($matching);
if ($matching) {
arsort($matching, SORT_NUMERIC);
}
/** @var string[] $array */
$array = array_keys($matching);
/** @phpstan-var static<T> */
return $this->select($array);
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::sort()
*/
public function sort(array $order)
{
$criteria = Criteria::create()->orderBy($order);
/** @phpstan-var FlexCollectionInterface<T> $matching */
$matching = $this->matching($criteria);
return $matching;
}
/**
* @param array $filters
* @return static
* @phpstan-return static<T>
*/
public function filterBy(array $filters)
{
$expr = Criteria::expr();
$criteria = Criteria::create();
foreach ($filters as $key => $value) {
$criteria->andWhere($expr->eq($key, $value));
}
/** @phpstan-var static<T> */
return $this->matching($criteria);
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::getFlexType()
*/
public function getFlexType(): string
{
return $this->_flexDirectory->getFlexType();
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::getFlexDirectory()
*/
public function getFlexDirectory(): FlexDirectory
{
return $this->_flexDirectory;
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::getTimestamp()
*/
public function getTimestamp(): int
{
$timestamps = $this->getTimestamps();
return $timestamps ? max($timestamps) : time();
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::getFlexDirectory()
*/
public function getCacheKey(): string
{
return $this->getTypePrefix() . $this->getFlexType() . '.' . sha1((string)json_encode($this->call('getKey')));
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::getFlexDirectory()
*/
public function getCacheChecksum(): string
{
$list = [];
/**
* @var string $key
* @var FlexObjectInterface $object
*/
foreach ($this as $key => $object) {
$list[$key] = $object->getCacheChecksum();
}
return sha1((string)json_encode($list));
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::getFlexDirectory()
*/
public function getTimestamps(): array
{
/** @var int[] $timestamps */
$timestamps = $this->call('getTimestamp');
return $timestamps;
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::getFlexDirectory()
*/
public function getStorageKeys(): array
{
/** @var string[] $keys */
$keys = $this->call('getStorageKey');
return $keys;
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::getFlexDirectory()
*/
public function getFlexKeys(): array
{
/** @var string[] $keys */
$keys = $this->call('getFlexKey');
return $keys;
}
/**
* Get all the values in property.
*
* Supports either single scalar values or array of scalar values.
*
* @param string $property Object property to be used to make groups.
* @param string|null $separator Separator, defaults to '.'
* @return array
*/
public function getDistinctValues(string $property, string $separator = null): array
{
$list = [];
/** @var FlexObjectInterface $element */
foreach ($this->getIterator() as $element) {
$value = (array)$element->getNestedProperty($property, null, $separator);
foreach ($value as $v) {
if (is_scalar($v)) {
$t = gettype($v) . (string)$v;
$list[$t] = $v;
}
}
}
return array_values($list);
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::withKeyField()
*/
public function withKeyField(string $keyField = null)
{
$keyField = $keyField ?: 'key';
if ($keyField === $this->getKeyField()) {
return $this;
}
$entries = [];
foreach ($this as $key => $object) {
// TODO: remove hardcoded logic
if ($keyField === 'storage_key') {
$entries[$object->getStorageKey()] = $object;
} elseif ($keyField === 'flex_key') {
$entries[$object->getFlexKey()] = $object;
} elseif ($keyField === 'key') {
$entries[$object->getKey()] = $object;
}
}
return $this->createFrom($entries, $keyField);
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::getIndex()
*/
public function getIndex()
{
/** @phpstan-var FlexIndexInterface<T> */
return $this->getFlexDirectory()->getIndex($this->getKeys(), $this->getKeyField());
}
/**
* @inheritdoc}
* @see FlexCollectionInterface::getCollection()
* @return $this
*/
public function getCollection()
{
return $this;
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::render()
*/
public function render(string $layout = null, array $context = [])
{
if (!$layout) {
$config = $this->getTemplateConfig();
$layout = $config['collection']['defaults']['layout'] ?? 'default';
}
$type = $this->getFlexType();
$grav = Grav::instance();
/** @var Debugger $debugger */
$debugger = $grav['debugger'];
$debugger->startTimer('flex-collection-' . ($debugKey = uniqid($type, false)), 'Render Collection ' . $type . ' (' . $layout . ')');
$key = null;
foreach ($context as $value) {
if (!is_scalar($value)) {
$key = false;
break;
}
}
if ($key !== false) {
$key = md5($this->getCacheKey() . '.' . $layout . json_encode($context));
$cache = $this->getCache('render');
} else {
$cache = null;
}
try {
$data = $cache && $key ? $cache->get($key) : null;
$block = $data ? HtmlBlock::fromArray($data) : null;
} catch (InvalidArgumentException $e) {
$debugger->addException($e);
$block = null;
} catch (\InvalidArgumentException $e) {
$debugger->addException($e);
$block = null;
}
$checksum = $this->getCacheChecksum();
if ($block && $checksum !== $block->getChecksum()) {
$block = null;
}
if (!$block) {
$block = HtmlBlock::create($key ?: null);
$block->setChecksum($checksum);
if (!$key) {
$block->disableCache();
}
$event = new Event([
'type' => 'flex',
'directory' => $this->getFlexDirectory(),
'collection' => $this,
'layout' => &$layout,
'context' => &$context
]);
$this->triggerEvent('onRender', $event);
$output = $this->getTemplate($layout)->render(
[
'grav' => $grav,
'config' => $grav['config'],
'block' => $block,
'directory' => $this->getFlexDirectory(),
'collection' => $this,
'layout' => $layout
] + $context
);
if ($debugger->enabled() &&
!($grav['uri']->getContentType() === 'application/json' || $grav['uri']->extension() === 'json')) {
$output = "\n<!–– START {$type} collection ––>\n{$output}\n<!–– END {$type} collection ––>\n";
}
$block->setContent($output);
try {
$cache && $key && $block->isCached() && $cache->set($key, $block->toArray());
} catch (InvalidArgumentException $e) {
$debugger->addException($e);
}
}
$debugger->stopTimer('flex-collection-' . $debugKey);
return $block;
}
/**
* @param FlexDirectory $type
* @return $this
*/
public function setFlexDirectory(FlexDirectory $type)
{
$this->_flexDirectory = $type;
return $this;
}
/**
* @param string $key
* @return array
*/
public function getMetaData($key): array
{
$object = $this->get($key);
return $object instanceof FlexObjectInterface ? $object->getMetaData() : [];
}
/**
* @param string|null $namespace
* @return CacheInterface
*/
public function getCache(string $namespace = null)
{
return $this->_flexDirectory->getCache($namespace);
}
/**
* @return string
*/
public function getKeyField(): string
{
return $this->_keyField;
}
/**
* @param string $action
* @param string|null $scope
* @param UserInterface|null $user
* @return static
* @phpstan-return static<T>
*/
public function isAuthorized(string $action, string $scope = null, UserInterface $user = null)
{
$list = $this->call('isAuthorized', [$action, $scope, $user]);
$list = array_filter($list);
/** @var string[] $keys */
$keys = array_keys($list);
/** @phpstan-var static<T> */
return $this->select($keys);
}
/**
* @param string $value
* @param string $field
* @return FlexObjectInterface|null
* @phpstan-return T|null
*/
public function find($value, $field = 'id')
{
if ($value) {
foreach ($this as $element) {
if (mb_strtolower($element->getProperty($field)) === mb_strtolower($value)) {
return $element;
}
}
}
return null;
}
/**
* @return array
*/
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
$elements = [];
/**
* @var string $key
* @var array|FlexObject $object
*/
foreach ($this->getElements() as $key => $object) {
$elements[$key] = is_array($object) ? $object : $object->jsonSerialize();
}
return $elements;
}
/**
* @return array
*/
#[\ReturnTypeWillChange]
public function __debugInfo()
{
return [
'type:private' => $this->getFlexType(),
'key:private' => $this->getKey(),
'objects_key:private' => $this->getKeyField(),
'objects:private' => $this->getElements()
];
}
/**
* Creates a new instance from the specified elements.
*
* This method is provided for derived classes to specify how a new
* instance should be created when constructor semantics have changed.
*
* @param array $elements Elements.
* @param string|null $keyField
* @return static
* @phpstan-return static<T>
* @throws \InvalidArgumentException
*/
protected function createFrom(array $elements, $keyField = null)
{
$collection = new static($elements, $this->_flexDirectory);
$collection->setKeyField($keyField ?: $this->_keyField);
return $collection;
}
/**
* @return string
*/
protected function getTypePrefix(): string
{
return 'c.';
}
/**
* @return array
*/
protected function getTemplateConfig(): array
{
$config = $this->getFlexDirectory()->getConfig('site.templates', []);
$defaults = array_replace($config['defaults'] ?? [], $config['collection']['defaults'] ?? []);
$config['collection']['defaults'] = $defaults;
return $config;
}
/**
* @param string $layout
* @return array
*/
protected function getTemplatePaths(string $layout): array
{
$config = $this->getTemplateConfig();
$type = $this->getFlexType();
$defaults = $config['collection']['defaults'] ?? [];
$ext = $defaults['ext'] ?? '.html.twig';
$types = array_unique(array_merge([$type], (array)($defaults['type'] ?? null)));
$paths = $config['collection']['paths'] ?? [
'flex/{TYPE}/collection/{LAYOUT}{EXT}',
'flex-objects/layouts/{TYPE}/collection/{LAYOUT}{EXT}'
];
$table = ['TYPE' => '%1$s', 'LAYOUT' => '%2$s', 'EXT' => '%3$s'];
$lookups = [];
foreach ($paths as $path) {
$path = Utils::simpleTemplate($path, $table);
foreach ($types as $type) {
$lookups[] = sprintf($path, $type, $layout, $ext);
}
}
return array_unique($lookups);
}
/**
* @param string $layout
* @return Template|TemplateWrapper
* @throws LoaderError
* @throws SyntaxError
*/
protected function getTemplate($layout)
{
$grav = Grav::instance();
/** @var Twig $twig */
$twig = $grav['twig'];
try {
return $twig->twig()->resolveTemplate($this->getTemplatePaths($layout));
} catch (LoaderError $e) {
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$debugger->addException($e);
return $twig->twig()->resolveTemplate(['flex/404.html.twig']);
}
}
/**
* @param string $type
* @return FlexDirectory
*/
protected function getRelatedDirectory($type): ?FlexDirectory
{
/** @var Flex $flex */
$flex = Grav::instance()['flex'];
return $flex->getDirectory($type);
}
/**
* @param string|null $keyField
* @return void
*/
protected function setKeyField($keyField = null): void
{
$this->_keyField = $keyField ?? 'storage_key';
}
// DEPRECATED METHODS
/**
* @param bool $prefix
* @return string
* @deprecated 1.6 Use `->getFlexType()` instead.
*/
public function getType($prefix = false)
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->getFlexType() method instead', E_USER_DEPRECATED);
$type = $prefix ? $this->getTypePrefix() : '';
return $type . $this->getFlexType();
}
/**
* @param string $name
* @param object|null $event
* @return $this
* @deprecated 1.7, moved to \Grav\Common\Flex\Traits\FlexObjectTrait
*/
public function triggerEvent(string $name, $event = null)
{
user_error(__METHOD__ . '() is deprecated since Grav 1.7, moved to \Grav\Common\Flex\Traits\FlexObjectTrait', E_USER_DEPRECATED);
if (null === $event) {
$event = new Event([
'type' => 'flex',
'directory' => $this->getFlexDirectory(),
'collection' => $this
]);
}
if (strpos($name, 'onFlexCollection') !== 0 && strpos($name, 'on') === 0) {
$name = 'onFlexCollection' . substr($name, 2);
}
$grav = Grav::instance();
if ($event instanceof Event) {
$grav->fireEvent($name, $event);
} else {
$grav->dispatchEvent($event);
}
return $this;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/FlexDirectoryForm.php | system/src/Grav/Framework/Flex/FlexDirectoryForm.php | <?php
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex;
use ArrayAccess;
use Exception;
use Grav\Common\Data\Blueprint;
use Grav\Common\Data\Data;
use Grav\Common\Grav;
use Grav\Common\Twig\Twig;
use Grav\Common\Utils;
use Grav\Framework\Flex\Interfaces\FlexDirectoryFormInterface;
use Grav\Framework\Flex\Interfaces\FlexFormInterface;
use Grav\Framework\Form\Interfaces\FormFlashInterface;
use Grav\Framework\Form\Traits\FormTrait;
use Grav\Framework\Route\Route;
use JsonSerializable;
use RocketTheme\Toolbox\ArrayTraits\NestedArrayAccessWithGetters;
use RuntimeException;
use Twig\Error\LoaderError;
use Twig\Error\SyntaxError;
use Twig\Template;
use Twig\TemplateWrapper;
/**
* Class FlexForm
* @package Grav\Framework\Flex
*/
class FlexDirectoryForm implements FlexDirectoryFormInterface, JsonSerializable
{
use NestedArrayAccessWithGetters {
NestedArrayAccessWithGetters::get as private traitGet;
NestedArrayAccessWithGetters::set as private traitSet;
}
use FormTrait {
FormTrait::doSerialize as doTraitSerialize;
FormTrait::doUnserialize as doTraitUnserialize;
}
/** @var array|null */
private $form;
/** @var FlexDirectory */
private $directory;
/** @var string */
private $flexName;
/**
* @param array $options Options to initialize the form instance:
* (string) name: Form name, allows you to use custom form.
* (string) unique_id: Unique id for this form instance.
* (array) form: Custom form fields.
* (FlexDirectory) directory: Flex Directory, mandatory.
*
* @return FlexFormInterface
*/
public static function instance(array $options = []): FlexFormInterface
{
if (isset($options['directory'])) {
$directory = $options['directory'];
if (!$directory instanceof FlexDirectory) {
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);
}
$name = $options['name'] ?? '';
return $directory->getDirectoryForm($name, $options);
}
/**
* FlexForm constructor.
* @param string $name
* @param FlexDirectory $directory
* @param array|null $options
*/
public function __construct(string $name, FlexDirectory $directory, array $options = null)
{
$this->name = $name;
$this->setDirectory($directory);
$this->setName($directory->getFlexType(), $name);
$this->setId($this->getName());
$uniqueId = $options['unique_id'] ?? null;
if (!$uniqueId) {
$uniqueId = md5($directory->getFlexType() . '-directory-' . $this->name);
}
$this->setUniqueId($uniqueId);
$this->setFlashLookupFolder($directory->getDirectoryBlueprint()->get('form/flash_folder') ?? 'tmp://forms/[SESSIONID]');
$this->form = $options['form'] ?? null;
if (Utils::isPositive($this->form['disabled'] ?? false)) {
$this->disable();
}
$this->initialize();
}
/**
* @return $this
*/
public function initialize()
{
$this->messages = [];
$this->submitted = false;
$this->data = new Data($this->directory->loadDirectoryConfig($this->name), $this->getBlueprint());
$this->files = [];
$this->unsetFlash();
/** @var FlexFormFlash $flash */
$flash = $this->getFlash();
if ($flash->exists()) {
$data = $flash->getData();
$includeOriginal = (bool)($this->getBlueprint()->form()['images']['original'] ?? null);
$directory = $flash->getDirectory();
if (null === $directory) {
throw new RuntimeException('Flash has no directory');
}
$this->directory = $directory;
$this->data = $data ? new Data($data, $this->getBlueprint()) : null;
$this->files = $flash->getFilesByFields($includeOriginal);
}
return $this;
}
/**
* @param string $uniqueId
* @return void
*/
public function setUniqueId(string $uniqueId): void
{
if ($uniqueId !== '') {
$this->uniqueid = $uniqueId;
}
}
/**
* @param string $name
* @param mixed $default
* @param string|null $separator
* @return mixed
*/
public function get($name, $default = null, $separator = null)
{
switch (strtolower($name)) {
case 'id':
case 'uniqueid':
case 'name':
case 'noncename':
case 'nonceaction':
case 'action':
case 'data':
case 'files':
case 'errors';
case 'fields':
case 'blueprint':
case 'page':
$method = 'get' . $name;
return $this->{$method}();
}
return $this->traitGet($name, $default, $separator);
}
/**
* @param string $name
* @param mixed $value
* @param string|null $separator
* @return $this
*/
public function set($name, $value, $separator = null)
{
switch (strtolower($name)) {
case 'id':
case 'uniqueid':
$method = 'set' . $name;
return $this->{$method}();
}
return $this->traitSet($name, $value, $separator);
}
/**
* @return string
*/
public function getName(): string
{
return $this->flexName;
}
protected function setName(string $type, string $name): void
{
// Make sure that both type and name do not have dash (convert dashes to underscores).
$type = str_replace('-', '_', $type);
$name = str_replace('-', '_', $name);
$this->flexName = $name ? "flex_conf-{$type}-{$name}" : "flex_conf-{$type}";
}
/**
* @return Data|object
*/
public function getData()
{
if (null === $this->data) {
$this->data = new Data([], $this->getBlueprint());
}
return $this->data;
}
/**
* Get a value from the form.
*
* Note: Used in form fields.
*
* @param string $name
* @return mixed
*/
public function getValue(string $name)
{
// Attempt to get value from the form data.
$value = $this->data ? $this->data[$name] : null;
// Return the form data or fall back to the object property.
return $value ?? null;
}
/**
* @param string $name
* @return array|mixed|null
*/
public function getDefaultValue(string $name)
{
return $this->getBlueprint()->getDefaultValue($name);
}
/**
* @return array
*/
public function getDefaultValues(): array
{
return $this->getBlueprint()->getDefaults();
}
/**
* @return string
*/
public function getFlexType(): string
{
return $this->directory->getFlexType();
}
/**
* Get form flash object.
*
* @return FormFlashInterface|FlexFormFlash
*/
public function getFlash()
{
if (null === $this->flash) {
$grav = Grav::instance();
$config = [
'session_id' => $this->getSessionId(),
'unique_id' => $this->getUniqueId(),
'form_name' => $this->getName(),
'folder' => $this->getFlashFolder(),
'id' => $this->getFlashId(),
'directory' => $this->getDirectory()
];
$this->flash = new FlexFormFlash($config);
$this->flash
->setUrl($grav['uri']->url)
->setUser($grav['user'] ?? null);
}
return $this->flash;
}
/**
* @return FlexDirectory
*/
public function getDirectory(): FlexDirectory
{
return $this->directory;
}
/**
* @return Blueprint
*/
public function getBlueprint(): Blueprint
{
if (null === $this->blueprint) {
try {
$blueprint = $this->getDirectory()->getDirectoryBlueprint();
if ($this->form) {
// We have field overrides available.
$blueprint->extend(['form' => $this->form], true);
$blueprint->init();
}
} catch (RuntimeException $e) {
if (!isset($this->form['fields'])) {
throw $e;
}
// Blueprint is not defined, but we have custom form fields available.
$blueprint = new Blueprint(null, ['form' => $this->form]);
$blueprint->load();
$blueprint->setScope('directory');
$blueprint->init();
}
$this->blueprint = $blueprint;
}
return $this->blueprint;
}
/**
* @return Route|null
*/
public function getFileUploadAjaxRoute(): ?Route
{
return null;
}
/**
* @param string|null $field
* @param string|null $filename
* @return Route|null
*/
public function getFileDeleteAjaxRoute($field = null, $filename = null): ?Route
{
return null;
}
/**
* @param array $params
* @param string|null $extension
* @return string
*/
public function getMediaTaskRoute(array $params = [], string $extension = null): string
{
return '';
}
/**
* @param string $name
* @return mixed|null
*/
#[\ReturnTypeWillChange]
public function __get($name)
{
$method = "get{$name}";
if (method_exists($this, $method)) {
return $this->{$method}();
}
$form = $this->getBlueprint()->form();
return $form[$name] ?? null;
}
/**
* @param string $name
* @param mixed $value
* @return void
*/
#[\ReturnTypeWillChange]
public function __set($name, $value)
{
$method = "set{$name}";
if (method_exists($this, $method)) {
$this->{$method}($value);
}
}
/**
* @param string $name
* @return bool
*/
#[\ReturnTypeWillChange]
public function __isset($name)
{
$method = "get{$name}";
if (method_exists($this, $method)) {
return true;
}
$form = $this->getBlueprint()->form();
return isset($form[$name]);
}
/**
* @param string $name
* @return void
*/
#[\ReturnTypeWillChange]
public function __unset($name)
{
}
/**
* @return array|bool
*/
protected function getUnserializeAllowedClasses()
{
return [FlexObject::class];
}
/**
* Note: this method clones the object.
*
* @param FlexDirectory $directory
* @return $this
*/
protected function setDirectory(FlexDirectory $directory): self
{
$this->directory = $directory;
return $this;
}
/**
* @param string $layout
* @return Template|TemplateWrapper
* @throws LoaderError
* @throws SyntaxError
*/
protected function getTemplate($layout)
{
$grav = Grav::instance();
/** @var Twig $twig */
$twig = $grav['twig'];
return $twig->twig()->resolveTemplate(
[
"flex-objects/layouts/{$this->getFlexType()}/form/{$layout}.html.twig",
"flex-objects/layouts/_default/form/{$layout}.html.twig",
"forms/{$layout}/form.html.twig",
'forms/default/form.html.twig'
]
);
}
/**
* @param array $data
* @param array $files
* @return void
* @throws Exception
*/
protected function doSubmit(array $data, array $files)
{
$this->directory->saveDirectoryConfig($this->name, $data);
$this->reset();
}
/**
* @return array
*/
protected function doSerialize(): array
{
return $this->doTraitSerialize() + [
'form' => $this->form,
'directory' => $this->directory,
'flexName' => $this->flexName
];
}
/**
* @param array $data
* @return void
*/
protected function doUnserialize(array $data): void
{
$this->doTraitUnserialize($data);
$this->form = $data['form'];
$this->directory = $data['directory'];
$this->flexName = $data['flexName'];
}
/**
* Filter validated data.
*
* @param ArrayAccess|Data|null $data
* @phpstan-param ArrayAccess<string,mixed>|Data|null $data
*/
protected function filterData($data = null): void
{
if ($data instanceof Data) {
$data->filter(false, true);
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/FlexDirectory.php | system/src/Grav/Framework/Flex/FlexDirectory.php | <?php
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex;
use Exception;
use Grav\Common\Cache;
use Grav\Common\Config\Config;
use Grav\Common\Data\Blueprint;
use Grav\Common\Debugger;
use Grav\Common\Grav;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\User\Interfaces\UserInterface;
use Grav\Common\Utils;
use Grav\Framework\Cache\Adapter\DoctrineCache;
use Grav\Framework\Cache\Adapter\MemoryCache;
use Grav\Framework\Cache\CacheInterface;
use Grav\Framework\Filesystem\Filesystem;
use Grav\Framework\Flex\Interfaces\FlexCollectionInterface;
use Grav\Framework\Flex\Interfaces\FlexDirectoryInterface;
use Grav\Framework\Flex\Interfaces\FlexFormInterface;
use Grav\Framework\Flex\Interfaces\FlexIndexInterface;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
use Grav\Framework\Flex\Interfaces\FlexStorageInterface;
use Grav\Framework\Flex\Storage\SimpleStorage;
use Grav\Framework\Flex\Traits\FlexAuthorizeTrait;
use Psr\SimpleCache\InvalidArgumentException;
use RocketTheme\Toolbox\File\YamlFile;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use function call_user_func_array;
use function count;
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
* @package Grav\Framework\Flex
*/
class FlexDirectory implements FlexDirectoryInterface
{
use FlexAuthorizeTrait;
/** @var string */
protected $type;
/** @var string */
protected $blueprint_file;
/** @var Blueprint[] */
protected $blueprints;
/**
* @var FlexIndexInterface[]
* @phpstan-var FlexIndexInterface<FlexObjectInterface>[]
*/
protected $indexes = [];
/**
* @var FlexCollectionInterface|null
* @phpstan-var FlexCollectionInterface<FlexObjectInterface>|null
*/
protected $collection;
/** @var bool */
protected $enabled;
/** @var array */
protected $defaults;
/** @var Config */
protected $config;
/** @var FlexStorageInterface */
protected $storage;
/** @var CacheInterface[] */
protected $cache;
/** @var FlexObjectInterface[] */
protected $objects;
/** @var string */
protected $objectClassName;
/** @var string */
protected $collectionClassName;
/** @var string */
protected $indexClassName;
/** @var string|null */
private $_authorize;
/**
* FlexDirectory constructor.
* @param string $type
* @param string $blueprint_file
* @param array $defaults
*/
public function __construct(string $type, string $blueprint_file, array $defaults = [])
{
$this->type = $type;
$this->blueprints = [];
$this->blueprint_file = $blueprint_file;
$this->defaults = $defaults;
$this->enabled = !empty($defaults['enabled']);
$this->objects = [];
}
/**
* @return bool
*/
public function isListed(): bool
{
$grav = Grav::instance();
/** @var Flex $flex */
$flex = $grav['flex'];
$directory = $flex->getDirectory($this->type);
return null !== $directory;
}
/**
* @return bool
*/
public function isEnabled(): bool
{
return $this->enabled;
}
/**
* @return string
*/
public function getFlexType(): string
{
return $this->type;
}
/**
* @return string
*/
public function getTitle(): string
{
return $this->getBlueprintInternal()->get('title', ucfirst($this->getFlexType()));
}
/**
* @return string
*/
public function getDescription(): string
{
return $this->getBlueprintInternal()->get('description', '');
}
/**
* @param string|null $name
* @param mixed $default
* @return mixed
*/
public function getConfig(string $name = null, $default = null)
{
if (null === $this->config) {
$config = $this->getBlueprintInternal()->get('config', []);
$config = is_array($config) ? array_replace_recursive($config, $this->defaults, $this->getDirectoryConfig($config['admin']['views']['configure']['form'] ?? $config['admin']['configure']['form'] ?? null)) : null;
if (!is_array($config)) {
throw new RuntimeException('Bad configuration');
}
$this->config = new Config($config);
}
return null === $name ? $this->config : $this->config->get($name, $default);
}
/**
* @param string|string[]|null $properties
* @return array
*/
public function getSearchProperties($properties = null): array
{
if (null !== $properties) {
return (array)$properties;
}
$properties = $this->getConfig('data.search.fields');
if (!$properties) {
$fields = $this->getConfig('admin.views.list.fields') ?? $this->getConfig('admin.list.fields', []);
foreach ($fields as $property => $value) {
if (!empty($value['link'])) {
$properties[] = $property;
}
}
}
return $properties;
}
/**
* @param array|null $options
* @return array
*/
public function getSearchOptions(array $options = null): array
{
if (empty($options['merge'])) {
return $options ?? (array)$this->getConfig('data.search.options');
}
unset($options['merge']);
return $options + (array)$this->getConfig('data.search.options');
}
/**
* @param string|null $name
* @param array $options
* @return FlexFormInterface
* @internal
*/
public function getDirectoryForm(string $name = null, array $options = [])
{
$name = $name ?: $this->getConfig('admin.views.configure.form', '') ?: $this->getConfig('admin.configure.form', '');
return new FlexDirectoryForm($name ?? '', $this, $options);
}
/**
* @return Blueprint
* @internal
*/
public function getDirectoryBlueprint()
{
$name = 'configure';
$type = $this->getBlueprint();
$overrides = $type->get("blueprints/{$name}");
$path = "blueprints://flex/shared/{$name}.yaml";
$blueprint = new Blueprint($path);
$blueprint->load();
if (isset($overrides['fields'])) {
$blueprint->embed('form/fields/tabs/fields', $overrides['fields']);
}
$blueprint->init();
return $blueprint;
}
/**
* @param string $name
* @param array $data
* @return void
* @throws Exception
* @internal
*/
public function saveDirectoryConfig(string $name, array $data)
{
$grav = Grav::instance();
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
$filename = $this->getDirectoryConfigUri($name);
if (file_exists($filename)) {
$filename = $locator->findResource($filename, true);
} else {
$filesystem = Filesystem::getInstance();
$dirname = $filesystem->dirname($filename);
$basename = $filesystem->basename($filename);
$dirname = $locator->findResource($dirname, true) ?: $locator->findResource($dirname, true, true);
$filename = "{$dirname}/{$basename}";
}
$file = YamlFile::instance($filename);
if (!empty($data)) {
$file->save($data);
} else {
$file->delete();
}
}
/**
* @param string $name
* @return array
* @internal
*/
public function loadDirectoryConfig(string $name): array
{
$grav = Grav::instance();
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
$uri = $this->getDirectoryConfigUri($name);
// If configuration is found in main configuration, use it.
if (str_starts_with($uri, 'config://')) {
$path = str_replace('/', '.', substr($uri, 9, -5));
return (array)$grav['config']->get($path);
}
// Load the configuration file.
$filename = $locator->findResource($uri, true);
if ($filename === false) {
return [];
}
$file = YamlFile::instance($filename);
return $file->content();
}
/**
* @param string|null $name
* @return string
*/
public function getDirectoryConfigUri(string $name = null): string
{
$name = $name ?: $this->getFlexType();
$blueprint = $this->getBlueprint();
return $blueprint->get('blueprints/views/configure/file') ?? $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();
/** @var Config $config */
$config = $grav['config'];
$name = $name ?: $this->getFlexType();
return $config->get("flex.{$name}", []);
}
/**
* Returns a new uninitialized instance of blueprint.
*
* Always use $object->getBlueprint() or $object->getForm()->getBlueprint() instead.
*
* @param string $type
* @param string $context
* @return Blueprint
*/
public function getBlueprint(string $type = '', string $context = '')
{
return clone $this->getBlueprintInternal($type, $context);
}
/**
* @param string $view
* @return string
*/
public function getBlueprintFile(string $view = ''): string
{
$file = $this->blueprint_file;
if ($view !== '') {
$file = preg_replace('/\.yaml/', "/{$view}.yaml", $file);
}
return (string)$file;
}
/**
* Get collection. In the site this will be filtered by the default filters (published etc).
*
* Use $directory->getIndex() if you want unfiltered collection.
*
* @param array|null $keys Array of keys.
* @param string|null $keyField Field to be used as the key.
* @return FlexCollectionInterface
* @phpstan-return FlexCollectionInterface<FlexObjectInterface>
*/
public function getCollection(array $keys = null, string $keyField = null): FlexCollectionInterface
{
// Get all selected entries.
$index = $this->getIndex($keys, $keyField);
if (!Utils::isAdminPlugin()) {
// If not in admin, filter the list by using default filters.
$filters = (array)$this->getConfig('site.filter', []);
foreach ($filters as $filter) {
$index = $index->{$filter}();
}
}
return $index;
}
/**
* Get the full collection of all stored objects.
*
* Use $directory->getCollection() if you want a filtered collection.
*
* @param array|null $keys Array of keys.
* @param string|null $keyField Field to be used as the key.
* @return FlexIndexInterface
* @phpstan-return FlexIndexInterface<FlexObjectInterface>
*/
public function getIndex(array $keys = null, string $keyField = null): FlexIndexInterface
{
$keyField = $keyField ?? '';
$index = $this->indexes[$keyField] ?? $this->loadIndex($keyField);
$index = clone $index;
if (null !== $keys) {
/** @var FlexIndexInterface<FlexObjectInterface> $index */
$index = $index->select($keys);
}
return $index->getIndex();
}
/**
* Returns an object if it exists. If no arguments are passed (or both of them are null), method creates a new empty object.
*
* Note: It is not safe to use the object without checking if the user can access it.
*
* @param string|null $key
* @param string|null $keyField Field to be used as the key.
* @return FlexObjectInterface|null
*/
public function getObject($key = null, string $keyField = null): ?FlexObjectInterface
{
if (null === $key) {
return $this->createObject([], '');
}
$keyField = $keyField ?? '';
$index = $this->indexes[$keyField] ?? $this->loadIndex($keyField);
return $index->get($key);
}
/**
* @param string|null $namespace
* @return CacheInterface
*/
public function getCache(string $namespace = null)
{
$namespace = $namespace ?: 'index';
$cache = $this->cache[$namespace] ?? null;
if (null === $cache) {
try {
$grav = Grav::instance();
/** @var Cache $gravCache */
$gravCache = $grav['cache'];
$config = $this->getConfig('object.cache.' . $namespace);
if (empty($config['enabled'])) {
$cache = new MemoryCache('flex-objects-' . $this->getFlexType());
} else {
$lifetime = $config['lifetime'] ?? 60;
$key = $gravCache->getKey();
if (Utils::isAdminPlugin()) {
$key = substr($key, 0, -1);
}
$cache = new DoctrineCache($gravCache->getCacheDriver(), 'flex-objects-' . $this->getFlexType() . $key, $lifetime);
}
} catch (Exception $e) {
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$debugger->addException($e);
$cache = new MemoryCache('flex-objects-' . $this->getFlexType());
}
// Disable cache key validation.
$cache->setValidation(false);
$this->cache[$namespace] = $cache;
}
return $cache;
}
/**
* @return $this
*/
public function clearCache()
{
$grav = Grav::instance();
/** @var Debugger $debugger */
$debugger = $grav['debugger'];
$debugger->addMessage(sprintf('Flex: Clearing all %s cache', $this->type), 'debug');
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
$locator->clearCache();
$this->getCache('index')->clear();
$this->getCache('object')->clear();
$this->getCache('render')->clear();
$this->indexes = [];
$this->objects = [];
return $this;
}
/**
* @param string|null $key
* @return string|null
*/
public function getStorageFolder(string $key = null): ?string
{
return $this->getStorage()->getStoragePath($key);
}
/**
* @param string|null $key
* @return string|null
*/
public function getMediaFolder(string $key = null): ?string
{
return $this->getStorage()->getMediaPath($key);
}
/**
* @return FlexStorageInterface
*/
public function getStorage(): FlexStorageInterface
{
if (null === $this->storage) {
$this->storage = $this->createStorage();
}
return $this->storage;
}
/**
* @param array $data
* @param string $key
* @param bool $validate
* @return FlexObjectInterface
*/
public function createObject(array $data, string $key = '', bool $validate = false): FlexObjectInterface
{
/** @phpstan-var class-string $className */
$className = $this->objectClassName ?: $this->getObjectClass();
if (!is_a($className, FlexObjectInterface::class, true)) {
throw new \RuntimeException('Bad object class: ' . $className);
}
return new $className($data, $key, $this, $validate);
}
/**
* @param array $entries
* @param string|null $keyField
* @return FlexCollectionInterface
* @phpstan-return FlexCollectionInterface<FlexObjectInterface>
*/
public function createCollection(array $entries, string $keyField = null): FlexCollectionInterface
{
/** phpstan-var class-string $className */
$className = $this->collectionClassName ?: $this->getCollectionClass();
if (!is_a($className, FlexCollectionInterface::class, true)) {
throw new \RuntimeException('Bad collection class: ' . $className);
}
return $className::createFromArray($entries, $this, $keyField);
}
/**
* @param array $entries
* @param string|null $keyField
* @return FlexIndexInterface
* @phpstan-return FlexIndexInterface<FlexObjectInterface>
*/
public function createIndex(array $entries, string $keyField = null): FlexIndexInterface
{
/** @phpstan-var class-string $className */
$className = $this->indexClassName ?: $this->getIndexClass();
if (!is_a($className, FlexIndexInterface::class, true)) {
throw new \RuntimeException('Bad index class: ' . $className);
}
return $className::createFromArray($entries, $this, $keyField);
}
/**
* @return string
*/
public function getObjectClass(): string
{
if (!$this->objectClassName) {
$this->objectClassName = $this->getConfig('data.object', GenericObject::class);
}
return $this->objectClassName;
}
/**
* @return string
*/
public function getCollectionClass(): string
{
if (!$this->collectionClassName) {
$this->collectionClassName = $this->getConfig('data.collection', GenericCollection::class);
}
return $this->collectionClassName;
}
/**
* @return string
*/
public function getIndexClass(): string
{
if (!$this->indexClassName) {
$this->indexClassName = $this->getConfig('data.index', GenericIndex::class);
}
return $this->indexClassName;
}
/**
* @param array $entries
* @param string|null $keyField
* @return FlexCollectionInterface
* @phpstan-return FlexCollectionInterface<FlexObjectInterface>
*/
public function loadCollection(array $entries, string $keyField = null): FlexCollectionInterface
{
return $this->createCollection($this->loadObjects($entries), $keyField);
}
/**
* @param array $entries
* @return FlexObjectInterface[]
* @internal
*/
public function loadObjects(array $entries): array
{
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$keys = [];
$rows = [];
$fetch = [];
// Build lookup arrays with storage keys for the objects.
foreach ($entries as $key => $value) {
$k = $value['storage_key'] ?? '';
if ($k === '') {
continue;
}
$v = $this->objects[$k] ?? null;
$keys[$k] = $key;
$rows[$k] = $v;
if (!$v) {
$fetch[] = $k;
}
}
// Attempt to fetch missing rows from the cache.
if ($fetch) {
$rows = (array)array_replace($rows, $this->loadCachedObjects($fetch));
}
// Read missing rows from the storage.
$updated = [];
$storage = $this->getStorage();
$rows = $storage->readRows($rows, $updated);
// Create objects from the rows.
$isListed = $this->isListed();
$list = [];
foreach ($rows as $storageKey => $row) {
$usedKey = $keys[$storageKey];
if ($row instanceof FlexObjectInterface) {
$object = $row;
} else {
if ($row === null) {
$debugger->addMessage(sprintf('Flex: Object %s was not found from %s storage', $storageKey, $this->type), 'debug');
continue;
}
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->addMessage($message, 'error');
continue;
}
if (!isset($row['__META'])) {
$row['__META'] = [
'storage_key' => $storageKey,
'storage_timestamp' => $entries[$usedKey]['storage_timestamp'] ?? 0,
];
}
$key = $row['__META']['key'] ?? $entries[$usedKey]['key'] ?? $usedKey;
$object = $this->createObject($row, $key, false);
$this->objects[$storageKey] = $object;
if ($isListed) {
// If unserialize works for the object, serialize the object to speed up the loading.
$updated[$storageKey] = $object;
}
}
$list[$usedKey] = $object;
}
// Store updated rows to the cache.
if ($updated) {
$cache = $this->getCache('object');
if (!$cache instanceof MemoryCache) {
///** @var Debugger $debugger */
//$debugger = Grav::instance()['debugger'];
//$debugger->addMessage(sprintf('Flex: Caching %d %s', \count($entries), $this->type), 'debug');
}
try {
$cache->setMultiple($updated);
} catch (InvalidArgumentException $e) {
$debugger->addException($e);
// TODO: log about the issue.
}
}
if ($fetch) {
$debugger->stopTimer('flex-objects');
}
return $list;
}
protected function loadCachedObjects(array $fetch): array
{
if (!$fetch) {
return [];
}
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$cache = $this->getCache('object');
// Attempt to fetch missing rows from the cache.
$fetched = [];
try {
$loading = count($fetch);
$debugger->startTimer('flex-objects', sprintf('Flex: Loading %d %s', $loading, $this->type));
$fetched = (array)$cache->getMultiple($fetch);
if ($fetched) {
$index = $this->loadIndex('storage_key');
// Make sure cached objects are up to date: compare against index checksum/timestamp.
/**
* @var string $key
* @var mixed $value
*/
foreach ($fetched as $key => $value) {
if ($value instanceof FlexObjectInterface) {
$objectMeta = $value->getMetaData();
} else {
$objectMeta = $value['__META'] ?? [];
}
$indexMeta = $index->getMetaData($key);
$indexChecksum = $indexMeta['checksum'] ?? $indexMeta['storage_timestamp'] ?? null;
$objectChecksum = $objectMeta['checksum'] ?? $objectMeta['storage_timestamp'] ?? null;
if ($indexChecksum !== $objectChecksum) {
unset($fetched[$key]);
}
}
}
} catch (InvalidArgumentException $e) {
$debugger->addException($e);
}
return $fetched;
}
/**
* @return void
*/
public function reloadIndex(): void
{
$this->getCache('index')->clear();
$this->getIndex()::loadEntriesFromStorage($this->getStorage());
$this->indexes = [];
$this->objects = [];
}
/**
* @param string $scope
* @param string $action
* @return string
*/
public function getAuthorizeRule(string $scope, string $action): string
{
if (!$this->_authorize) {
$config = $this->getConfig('admin.permissions');
if ($config) {
$this->_authorize = array_key_first($config) . '.%2$s';
} else {
$this->_authorize = '%1$s.flex-object.%2$s';
}
}
return sprintf($this->_authorize, $scope, $action);
}
/**
* @param string $type_view
* @param string $context
* @return Blueprint
*/
protected function getBlueprintInternal(string $type_view = '', string $context = '')
{
if (!isset($this->blueprints[$type_view])) {
if (!file_exists($this->blueprint_file)) {
throw new RuntimeException(sprintf('Flex: Blueprint file for %s is missing', $this->type));
}
$parts = explode('.', rtrim($type_view, '.'), 2);
$type = array_shift($parts);
$view = array_shift($parts) ?: '';
$blueprint = new Blueprint($this->getBlueprintFile($view));
$blueprint->addDynamicHandler('data', function (array &$field, $property, array &$call) {
$this->dynamicDataField($field, $property, $call);
});
$blueprint->addDynamicHandler('flex', function (array &$field, $property, array &$call) {
$this->dynamicFlexField($field, $property, $call);
});
$blueprint->addDynamicHandler('authorize', function (array &$field, $property, array &$call) {
$this->dynamicAuthorizeField($field, $property, $call);
});
if ($context) {
$blueprint->setContext($context);
}
$blueprint->load($type ?: null);
if ($blueprint->get('type') === 'flex-objects' && isset(Grav::instance()['admin'])) {
$blueprintBase = (new Blueprint('plugin://flex-objects/blueprints/flex-objects.yaml'))->load();
$blueprint->extend($blueprintBase, true);
}
$this->blueprints[$type_view] = $blueprint;
}
return $this->blueprints[$type_view];
}
/**
* @param array $field
* @param string $property
* @param array $call
* @return void
*/
protected function dynamicDataField(array &$field, $property, array $call)
{
$params = $call['params'];
if (is_array($params)) {
$function = array_shift($params);
} else {
$function = $params;
$params = [];
}
$object = $call['object'];
if ($function === '\Grav\Common\Page\Pages::pageTypes') {
$params = [$object instanceof PageInterface && $object->isModule() ? 'modular' : 'standard'];
}
$data = null;
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])) {
// Combine field and @data-field together.
$field[$property] += $data;
} else {
// Or create/replace field with @data-field.
$field[$property] = $data;
}
}
}
/**
* @param array $field
* @param string $property
* @param array $call
* @return void
*/
protected function dynamicFlexField(array &$field, $property, array $call): void
{
$params = (array)$call['params'];
$object = $call['object'] ?? null;
$method = array_shift($params);
$not = false;
if (str_starts_with($method, '!')) {
$method = substr($method, 1);
$not = true;
} elseif (str_starts_with($method, 'not ')) {
$method = substr($method, 4);
$not = true;
}
$method = trim($method);
if ($object && method_exists($object, $method)) {
$value = $object->{$method}(...$params);
if (is_array($value) && isset($field[$property]) && is_array($field[$property])) {
$value = $this->mergeArrays($field[$property], $value);
}
$value = $not ? !$value : $value;
if ($property === 'ignore' && $value) {
Blueprint::addPropertyRecursive($field, 'validate', ['ignore' => true]);
} else {
$field[$property] = $value;
}
}
}
/**
* @param array $field
* @param string $property
* @param array $call
* @return void
*/
protected function dynamicAuthorizeField(array &$field, $property, array $call): void
{
$params = (array)$call['params'];
$object = $call['object'] ?? null;
$permission = array_shift($params);
$not = false;
if (str_starts_with($permission, '!')) {
$permission = substr($permission, 1);
$not = true;
} elseif (str_starts_with($permission, 'not ')) {
$permission = substr($permission, 4);
$not = true;
}
$permission = trim($permission);
if ($object) {
$value = $object->isAuthorized($permission) ?? false;
$field[$property] = $not ? !$value : $value;
}
}
/**
* @param array $array1
* @param array $array2
* @return array
*/
protected function mergeArrays(array $array1, array $array2): array
{
foreach ($array2 as $key => $value) {
if (is_array($value) && isset($array1[$key]) && is_array($array1[$key])) {
$array1[$key] = $this->mergeArrays($array1[$key], $value);
} else {
$array1[$key] = $value;
}
}
return $array1;
}
/**
* @return FlexStorageInterface
*/
protected function createStorage(): FlexStorageInterface
{
$this->collection = $this->createCollection([]);
$storage = $this->getConfig('data.storage');
if (!is_array($storage)) {
$storage = ['options' => ['folder' => $storage]];
}
$className = $storage['class'] ?? SimpleStorage::class;
$options = $storage['options'] ?? [];
if (!is_a($className, FlexStorageInterface::class, true)) {
throw new \RuntimeException('Bad storage class: ' . $className);
}
return new $className($options);
}
/**
* @param string $keyField
* @return FlexIndexInterface
* @phpstan-return FlexIndexInterface<FlexObjectInterface>
*/
protected function loadIndex(string $keyField): FlexIndexInterface
{
static $i = 0;
$index = $this->indexes[$keyField] ?? null;
if (null !== $index) {
return $index;
}
$index = $this->indexes['storage_key'] ?? null;
if (null === $index) {
$i++;
$j = $i;
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$debugger->startTimer('flex-keys-' . $this->type . $j, "Flex: Loading {$this->type} index");
$storage = $this->getStorage();
$cache = $this->getCache('index');
try {
$keys = $cache->get('__keys');
} catch (InvalidArgumentException $e) {
$debugger->addException($e);
$keys = null;
}
if (!is_array($keys)) {
/** @phpstan-var class-string $className */
$className = $this->getIndexClass();
$keys = $className::loadEntriesFromStorage($storage);
if (!$cache instanceof MemoryCache) {
$debugger->addMessage(
sprintf('Flex: Caching %s index of %d objects', $this->type, count($keys)),
'debug'
);
}
try {
$cache->set('__keys', $keys);
} catch (InvalidArgumentException $e) {
$debugger->addException($e);
// TODO: log about the issue.
}
}
$ordering = $this->getConfig('data.ordering', []);
// We need to do this in two steps as orderBy() calls loadIndex() again and we do not want infinite loop.
$this->indexes['storage_key'] = $index = $this->createIndex($keys, 'storage_key');
if ($ordering) {
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | true |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/FlexObject.php | system/src/Grav/Framework/Flex/FlexObject.php | <?php
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex;
use ArrayAccess;
use Exception;
use Grav\Common\Data\Blueprint;
use Grav\Common\Data\Data;
use Grav\Common\Debugger;
use Grav\Common\Grav;
use Grav\Common\Inflector;
use Grav\Common\Twig\Twig;
use Grav\Common\User\Interfaces\UserInterface;
use Grav\Common\Utils;
use Grav\Framework\Cache\CacheInterface;
use Grav\Framework\ContentBlock\HtmlBlock;
use Grav\Framework\Flex\Interfaces\FlexAuthorizeInterface;
use Grav\Framework\Flex\Interfaces\FlexFormInterface;
use Grav\Framework\Flex\Traits\FlexAuthorizeTrait;
use Grav\Framework\Flex\Traits\FlexRelatedDirectoryTrait;
use Grav\Framework\Object\Access\NestedArrayAccessTrait;
use Grav\Framework\Object\Access\NestedPropertyTrait;
use Grav\Framework\Object\Access\OverloadedPropertyTrait;
use Grav\Framework\Object\Base\ObjectTrait;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
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;
use function json_encode;
/**
* Class FlexObject
* @package Grav\Framework\Flex
*/
class FlexObject implements FlexObjectInterface, FlexAuthorizeInterface
{
use ObjectTrait;
use LazyPropertyTrait {
LazyPropertyTrait::__construct as private objectConstruct;
}
use NestedPropertyTrait;
use OverloadedPropertyTrait;
use NestedArrayAccessTrait;
use FlexAuthorizeTrait;
use FlexRelatedDirectoryTrait;
/** @var FlexDirectory */
private $_flexDirectory;
/** @var FlexFormInterface[] */
private $_forms = [];
/** @var Blueprint[] */
private $_blueprint = [];
/** @var array|null */
private $_meta;
/** @var array|null */
protected $_original;
/** @var string|null */
protected $storage_key;
/** @var int|null */
protected $storage_timestamp;
/**
* @return array
*/
public static function getCachedMethods(): array
{
return [
'getTypePrefix' => true,
'getType' => true,
'getFlexType' => true,
'getFlexDirectory' => true,
'hasFlexFeature' => true,
'getFlexFeatures' => true,
'getCacheKey' => true,
'getCacheChecksum' => false,
'getTimestamp' => true,
'value' => true,
'exists' => true,
'hasProperty' => true,
'getProperty' => true,
// FlexAclTrait
'isAuthorized' => 'session',
];
}
/**
* @param array $elements
* @param array $storage
* @param FlexDirectory $directory
* @param bool $validate
* @return static
*/
public static function createFromStorage(array $elements, array $storage, FlexDirectory $directory, bool $validate = false)
{
$instance = new static($elements, $storage['key'], $directory, $validate);
$instance->setMetaData($storage);
return $instance;
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::__construct()
*/
public function __construct(array $elements, $key, FlexDirectory $directory, bool $validate = false)
{
if (get_class($this) === __CLASS__) {
user_error('Using ' . __CLASS__ . ' directly is deprecated since Grav 1.7, use \Grav\Common\Flex\Types\Generic\GenericObject or your own class instead', E_USER_DEPRECATED);
}
$this->_flexDirectory = $directory;
if (isset($elements['__META'])) {
$this->setMetaData($elements['__META']);
unset($elements['__META']);
}
if ($validate) {
$blueprint = $this->getFlexDirectory()->getBlueprint();
$blueprint->validate($elements, ['xss_check' => false]);
$elements = $blueprint->filter($elements, true, true);
}
$this->filterElements($elements);
$this->objectConstruct($elements, $key);
}
/**
* {@inheritdoc}
* @see FlexCommonInterface::hasFlexFeature()
*/
public function hasFlexFeature(string $name): bool
{
return in_array($name, $this->getFlexFeatures(), true);
}
/**
* {@inheritdoc}
* @see FlexCommonInterface::hasFlexFeature()
*/
public function getFlexFeatures(): array
{
/** @var array $implements */
$implements = class_implements($this);
$list = [];
foreach ($implements as $interface) {
if ($pos = strrpos($interface, '\\')) {
$interface = substr($interface, $pos+1);
}
$list[] = Inflector::hyphenize(str_replace('Interface', '', $interface));
}
return $list;
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::getFlexType()
*/
public function getFlexType(): string
{
return $this->_flexDirectory->getFlexType();
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::getFlexDirectory()
*/
public function getFlexDirectory(): FlexDirectory
{
return $this->_flexDirectory;
}
/**
* Refresh object from the storage.
*
* @param bool $keepMissing
* @return bool True if the object was refreshed
*/
public function refresh(bool $keepMissing = false): bool
{
$key = $this->getStorageKey();
if ('' === $key) {
return false;
}
$storage = $this->getFlexDirectory()->getStorage();
$meta = $storage->getMetaData([$key])[$key] ?? null;
$newChecksum = $meta['checksum'] ?? $meta['storage_timestamp'] ?? null;
$curChecksum = $this->_meta['checksum'] ?? $this->_meta['storage_timestamp'] ?? null;
// Check if object is up to date with the storage.
if (null === $newChecksum || $newChecksum === $curChecksum) {
return false;
}
// Get current elements (if requested).
$current = $keepMissing ? $this->getElements() : [];
// Get elements from the filesystem.
$elements = $storage->readRows([$key => null])[$key] ?? null;
if (null !== $elements) {
$meta = $elements['__META'] ?? $meta;
unset($elements['__META']);
$this->filterElements($elements);
$newKey = $meta['key'] ?? $this->getKey();
if ($meta) {
$this->setMetaData($meta);
}
$this->objectConstruct($elements, $newKey);
if ($current) {
// Inject back elements which are missing in the filesystem.
$data = $this->getBlueprint()->flattenData($current);
foreach ($data as $property => $value) {
if (strpos($property, '.') === false) {
$this->defProperty($property, $value);
} else {
$this->defNestedProperty($property, $value);
}
}
}
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$debugger->addMessage("Refreshed {$this->getFlexType()} object {$this->getKey()}", 'debug');
}
return true;
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::getTimestamp()
*/
public function getTimestamp(): int
{
return $this->_meta['storage_timestamp'] ?? 0;
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::getCacheKey()
*/
public function getCacheKey(): string
{
return $this->hasKey() ? $this->getTypePrefix() . $this->getFlexType() . '.' . $this->getKey() : '';
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::getCacheChecksum()
*/
public function getCacheChecksum(): string
{
return (string)($this->_meta['checksum'] ?? $this->getTimestamp());
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::search()
*/
public function search(string $search, $properties = null, array $options = null): float
{
$directory = $this->getFlexDirectory();
$properties = $directory->getSearchProperties($properties);
$options = $directory->getSearchOptions($options);
$weight = 0;
foreach ($properties as $property) {
if (strpos($property, '.')) {
$weight += $this->searchNestedProperty($property, $search, $options);
} else {
$weight += $this->searchProperty($property, $search, $options);
}
}
return $weight > 0 ? min($weight, 1) : 0;
}
/**
* {@inheritdoc}
* @see ObjectInterface::getFlexKey()
*/
public function getKey()
{
return (string)$this->_key;
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::getFlexKey()
*/
public function getFlexKey(): string
{
$key = $this->_meta['flex_key'] ?? null;
if (!$key && $key = $this->getStorageKey()) {
$key = $this->_flexDirectory->getFlexType() . '.obj:' . $key;
}
return (string)$key;
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::getStorageKey()
*/
public function getStorageKey(): string
{
return (string)($this->storage_key ?? $this->_meta['storage_key'] ?? null);
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::getMetaData()
*/
public function getMetaData(): array
{
return $this->_meta ?? [];
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::exists()
*/
public function exists(): bool
{
$key = $this->getStorageKey();
return $key && $this->getFlexDirectory()->getStorage()->hasKey($key);
}
/**
* @param string $property
* @param string $search
* @param array|null $options
* @return float
*/
public function searchProperty(string $property, string $search, array $options = null): float
{
$options = $options ?? (array)$this->getFlexDirectory()->getConfig('data.search.options');
$value = $this->getProperty($property);
return $this->searchValue($property, $value, $search, $options);
}
/**
* @param string $property
* @param string $search
* @param array|null $options
* @return float
*/
public function searchNestedProperty(string $property, string $search, array $options = null): float
{
$options = $options ?? (array)$this->getFlexDirectory()->getConfig('data.search.options');
if ($property === 'key') {
$value = $this->getKey();
} else {
$value = $this->getNestedProperty($property);
}
return $this->searchValue($property, $value, $search, $options);
}
/**
* @param string $name
* @param mixed $value
* @param string $search
* @param array|null $options
* @return float
*/
protected function searchValue(string $name, $value, string $search, array $options = null): float
{
$options = $options ?? [];
// Ignore empty search strings.
$search = trim($search);
if ($search === '') {
return 0;
}
// Search only non-empty string values.
if (!is_string($value) || $value === '') {
return 0;
}
$caseSensitive = $options['case_sensitive'] ?? false;
$tested = false;
if (($tested |= !empty($options['same_as']))) {
if ($caseSensitive) {
if ($value === $search) {
return (float)$options['same_as'];
}
} elseif (mb_strtolower($value) === mb_strtolower($search)) {
return (float)$options['same_as'];
}
}
if (($tested |= !empty($options['starts_with'])) && Utils::startsWith($value, $search, $caseSensitive)) {
return (float)$options['starts_with'];
}
if (($tested |= !empty($options['ends_with'])) && Utils::endsWith($value, $search, $caseSensitive)) {
return (float)$options['ends_with'];
}
if ((!$tested || !empty($options['contains'])) && Utils::contains($value, $search, $caseSensitive)) {
return (float)($options['contains'] ?? 1);
}
return 0;
}
/**
* Get original data before update
*
* @return array
*/
public function getOriginalData(): array
{
return $this->_original ?? [];
}
/**
* Get diff array from the object.
*
* @return array
*/
public function getDiff(): array
{
$blueprint = $this->getBlueprint();
$flattenOriginal = $blueprint->flattenData($this->getOriginalData());
$flattenElements = $blueprint->flattenData($this->getElements());
$removedElements = array_diff_key($flattenOriginal, $flattenElements);
$diff = [];
// Include all added or changed keys.
foreach ($flattenElements as $key => $value) {
$orig = $flattenOriginal[$key] ?? null;
if ($orig !== $value) {
$diff[$key] = ['old' => $orig, 'new' => $value];
}
}
// Include all removed keys.
foreach ($removedElements as $key => $value) {
$diff[$key] = ['old' => $value, 'new' => null];
}
return $diff;
}
/**
* Get any changes from the object.
*
* @return array
*/
public function getChanges(): array
{
$diff = $this->getDiff();
$data = new Data();
foreach ($diff as $key => $change) {
$data->set($key, $change['new']);
}
return $data->toArray();
}
/**
* @return string
*/
protected function getTypePrefix(): string
{
return 'o.';
}
/**
* Alias of getBlueprint()
*
* @return Blueprint
* @deprecated 1.6 Admin compatibility
*/
public function blueprints()
{
return $this->getBlueprint();
}
/**
* @param string|null $namespace
* @return CacheInterface
*/
public function getCache(string $namespace = null)
{
return $this->_flexDirectory->getCache($namespace);
}
/**
* @param string|null $key
* @return $this
*/
public function setStorageKey($key = null)
{
$this->storage_key = $key ?? '';
return $this;
}
/**
* @param int $timestamp
* @return $this
*/
public function setTimestamp($timestamp = null)
{
$this->storage_timestamp = $timestamp ?? time();
return $this;
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::render()
*/
public function render(string $layout = null, array $context = [])
{
if (!$layout) {
$config = $this->getTemplateConfig();
$layout = $config['object']['defaults']['layout'] ?? 'default';
}
$type = $this->getFlexType();
$grav = Grav::instance();
/** @var Debugger $debugger */
$debugger = $grav['debugger'];
$debugger->startTimer('flex-object-' . ($debugKey = uniqid($type, false)), 'Render Object ' . $type . ' (' . $layout . ')');
$key = $this->getCacheKey();
// Disable caching if context isn't all scalars.
if ($key) {
foreach ($context as $value) {
if (!is_scalar($value)) {
$key = '';
break;
}
}
}
if ($key) {
// Create a new key which includes layout and context.
$key = md5($key . '.' . $layout . json_encode($context));
$cache = $this->getCache('render');
} else {
$cache = null;
}
try {
$data = $cache ? $cache->get($key) : null;
$block = $data ? HtmlBlock::fromArray($data) : null;
} catch (InvalidArgumentException $e) {
$debugger->addException($e);
$block = null;
} catch (\InvalidArgumentException $e) {
$debugger->addException($e);
$block = null;
}
$checksum = $this->getCacheChecksum();
if ($block && $checksum !== $block->getChecksum()) {
$block = null;
}
if (!$block) {
$block = HtmlBlock::create($key ?: null);
$block->setChecksum($checksum);
if (!$cache) {
$block->disableCache();
}
$event = new Event([
'type' => 'flex',
'directory' => $this->getFlexDirectory(),
'object' => $this,
'layout' => &$layout,
'context' => &$context
]);
$this->triggerEvent('onRender', $event);
$output = $this->getTemplate($layout)->render(
[
'grav' => $grav,
'config' => $grav['config'],
'block' => $block,
'directory' => $this->getFlexDirectory(),
'object' => $this,
'layout' => $layout
] + $context
);
if ($debugger->enabled() &&
!($grav['uri']->getContentType() === 'application/json' || $grav['uri']->extension() === 'json')) {
$name = $this->getKey() . ' (' . $type . ')';
$output = "\n<!–– START {$name} object ––>\n{$output}\n<!–– END {$name} object ––>\n";
}
$block->setContent($output);
try {
$cache && $block->isCached() && $cache->set($key, $block->toArray());
} catch (InvalidArgumentException $e) {
$debugger->addException($e);
}
}
$debugger->stopTimer('flex-object-' . $debugKey);
return $block;
}
/**
* @return array
*/
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
return $this->getElements();
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::prepareStorage()
*/
public function prepareStorage(): array
{
return ['__META' => $this->getMetaData()] + $this->getElements();
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::update()
*/
public function update(array $data, array $files = [])
{
if ($data) {
// Get currently stored data.
$elements = $this->getElements();
// Store original version of the object.
if ($this->_original === null) {
$this->_original = $elements;
}
$blueprint = $this->getBlueprint();
// Process updated data through the object filters.
$this->filterElements($data);
// Merge existing object to the test data to be validated.
$test = $blueprint->mergeData($elements, $data);
// Validate and filter elements and throw an error if any issues were found.
$blueprint->validate($test + ['storage_key' => $this->getStorageKey(), 'timestamp' => $this->getTimestamp()], ['xss_check' => false]);
$data = $blueprint->filter($data, true, true);
// Finally update the object.
$flattenData = $blueprint->flattenData($data);
foreach ($flattenData as $key => $value) {
if ($value === null) {
$this->unsetNestedProperty($key);
} else {
$this->setNestedProperty($key, $value);
}
}
}
if ($files && method_exists($this, 'setUpdatedMedia')) {
$this->setUpdatedMedia($files);
}
return $this;
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::create()
*/
public function create(string $key = null)
{
if ($key) {
$this->setStorageKey($key);
}
if ($this->exists()) {
throw new RuntimeException('Cannot create new object (Already exists)');
}
return $this->save();
}
/**
* @param string|null $key
* @return FlexObject|FlexObjectInterface
*/
public function createCopy(string $key = null)
{
$this->markAsCopy();
return $this->create($key);
}
/**
* @param UserInterface|null $user
*/
public function check(UserInterface $user = null): void
{
// If user has been provided, check if the user has permissions to save this object.
if ($user && !$this->isAuthorized('save', null, $user)) {
throw new \RuntimeException('Forbidden', 403);
}
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::save()
*/
public function save()
{
$this->triggerEvent('onBeforeSave');
$storage = $this->getFlexDirectory()->getStorage();
$storageKey = $this->getStorageKey() ?: '@@' . spl_object_hash($this);
$result = $storage->replaceRows([$storageKey => $this->prepareStorage()]);
if (method_exists($this, 'clearMediaCache')) {
$this->clearMediaCache();
}
$value = reset($result);
$meta = $value['__META'] ?? null;
if ($meta) {
/** @phpstan-var class-string $indexClass */
$indexClass = $this->getFlexDirectory()->getIndexClass();
$indexClass::updateObjectMeta($meta, $value, $storage);
$this->_meta = $meta;
}
if ($value) {
$storageKey = $meta['storage_key'] ?? (string)key($result);
if ($storageKey !== '') {
$this->setStorageKey($storageKey);
}
$newKey = $meta['key'] ?? ($this->hasKey() ? $this->getKey() : null);
$this->setKey($newKey ?? $storageKey);
}
// FIXME: For some reason locator caching isn't cleared for the file, investigate!
$locator = Grav::instance()['locator'];
$locator->clearCache();
if (method_exists($this, 'saveUpdatedMedia')) {
$this->saveUpdatedMedia();
}
try {
$this->getFlexDirectory()->reloadIndex();
if (method_exists($this, 'clearMediaCache')) {
$this->clearMediaCache();
}
} catch (Exception $e) {
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$debugger->addException($e);
// Caching failed, but we can ignore that for now.
}
$this->triggerEvent('onAfterSave');
return $this;
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::delete()
*/
public function delete()
{
if (!$this->exists()) {
return $this;
}
$this->triggerEvent('onBeforeDelete');
$this->getFlexDirectory()->getStorage()->deleteRows([$this->getStorageKey() => $this->prepareStorage()]);
try {
$this->getFlexDirectory()->reloadIndex();
if (method_exists($this, 'clearMediaCache')) {
$this->clearMediaCache();
}
} catch (Exception $e) {
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$debugger->addException($e);
// Caching failed, but we can ignore that for now.
}
$this->triggerEvent('onAfterDelete');
return $this;
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::getBlueprint()
*/
public function getBlueprint(string $name = '')
{
if (!isset($this->_blueprint[$name])) {
$blueprint = $this->doGetBlueprint($name);
$blueprint->setScope('object');
$blueprint->setObject($this);
$this->_blueprint[$name] = $blueprint->init();
}
return $this->_blueprint[$name];
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::getForm()
*/
public function getForm(string $name = '', array $options = null)
{
$hash = $name . '-' . md5(json_encode($options, JSON_THROW_ON_ERROR));
if (!isset($this->_forms[$hash])) {
$this->_forms[$hash] = $this->createFormObject($name, $options);
}
return $this->_forms[$hash];
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::getDefaultValue()
*/
public function getDefaultValue(string $name, string $separator = null)
{
$separator = $separator ?: '.';
$path = explode($separator, $name);
$offset = array_shift($path);
$current = $this->getDefaultValues();
if (!isset($current[$offset])) {
return null;
}
$current = $current[$offset];
while ($path) {
$offset = array_shift($path);
if ((is_array($current) || $current instanceof ArrayAccess) && isset($current[$offset])) {
$current = $current[$offset];
} elseif (is_object($current) && isset($current->{$offset})) {
$current = $current->{$offset};
} else {
return null;
}
};
return $current;
}
/**
* @return array
*/
public function getDefaultValues(): array
{
return $this->getBlueprint()->getDefaults();
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::getFormValue()
*/
public function getFormValue(string $name, $default = null, string $separator = null)
{
if ($name === 'storage_key') {
return $this->getStorageKey();
}
if ($name === 'storage_timestamp') {
return $this->getTimestamp();
}
return $this->getNestedProperty($name, $default, $separator);
}
/**
* @param FlexDirectory $directory
*/
public function setFlexDirectory(FlexDirectory $directory): void
{
$this->_flexDirectory = $directory;
}
/**
* Returns a string representation of this object.
*
* @return string
*/
#[\ReturnTypeWillChange]
public function __toString()
{
return $this->getFlexKey();
}
/**
* @return array
*/
#[\ReturnTypeWillChange]
public function __debugInfo()
{
return [
'type:private' => $this->getFlexType(),
'storage_key:protected' => $this->getStorageKey(),
'storage_timestamp:protected' => $this->getTimestamp(),
'key:private' => $this->getKey(),
'elements:private' => $this->getElements(),
'storage:private' => $this->getMetaData()
];
}
/**
* Clone object.
*/
#[\ReturnTypeWillChange]
public function __clone()
{
// Allows future compatibility as parent::__clone() works.
}
protected function markAsCopy(): void
{
$meta = $this->getMetaData();
$meta['copy'] = true;
$this->_meta = $meta;
}
/**
* @param string $name
* @return Blueprint
*/
protected function doGetBlueprint(string $name = ''): Blueprint
{
return $this->_flexDirectory->getBlueprint($name ? '.' . $name : $name);
}
/**
* @param array $meta
*/
protected function setMetaData(array $meta): void
{
$this->_meta = $meta;
}
/**
* @return array
*/
protected function doSerialize(): array
{
return [
'type' => $this->getFlexType(),
'key' => $this->getKey(),
'elements' => $this->getElements(),
'storage' => $this->getMetaData()
];
}
/**
* @param array $serialized
* @param FlexDirectory|null $directory
* @return void
*/
protected function doUnserialize(array $serialized, FlexDirectory $directory = null): void
{
$type = $serialized['type'] ?? 'unknown';
if (!isset($serialized['key'], $serialized['type'], $serialized['elements'])) {
throw new \InvalidArgumentException("Cannot unserialize '{$type}': Bad data");
}
if (null === $directory) {
$directory = $this->getFlexContainer()->getDirectory($type);
if (!$directory) {
throw new \InvalidArgumentException("Cannot unserialize Flex type '{$type}': Directory not found");
}
}
$this->setFlexDirectory($directory);
$this->setMetaData($serialized['storage']);
$this->setKey($serialized['key']);
$this->setElements($serialized['elements']);
}
/**
* @return array
*/
protected function getTemplateConfig()
{
$config = $this->getFlexDirectory()->getConfig('site.templates', []);
$defaults = array_replace($config['defaults'] ?? [], $config['object']['defaults'] ?? []);
$config['object']['defaults'] = $defaults;
return $config;
}
/**
* @param string $layout
* @return array
*/
protected function getTemplatePaths(string $layout): array
{
$config = $this->getTemplateConfig();
$type = $this->getFlexType();
$defaults = $config['object']['defaults'] ?? [];
$ext = $defaults['ext'] ?? '.html.twig';
$types = array_unique(array_merge([$type], (array)($defaults['type'] ?? null)));
$paths = $config['object']['paths'] ?? [
'flex/{TYPE}/object/{LAYOUT}{EXT}',
'flex-objects/layouts/{TYPE}/object/{LAYOUT}{EXT}'
];
$table = ['TYPE' => '%1$s', 'LAYOUT' => '%2$s', 'EXT' => '%3$s'];
$lookups = [];
foreach ($paths as $path) {
$path = Utils::simpleTemplate($path, $table);
foreach ($types as $type) {
$lookups[] = sprintf($path, $type, $layout, $ext);
}
}
return array_unique($lookups);
}
/**
* Filter data coming to constructor or $this->update() request.
*
* NOTE: The incoming data can be an arbitrary array so do not assume anything from its content.
*
* @param array $elements
*/
protected function filterElements(array &$elements): void
{
if (isset($elements['storage_key'])) {
$elements['storage_key'] = trim($elements['storage_key']);
}
if (isset($elements['storage_timestamp'])) {
$elements['storage_timestamp'] = (int)$elements['storage_timestamp'];
}
unset($elements['_post_entries_save']);
}
/**
* This methods allows you to override form objects in child classes.
*
* @param string $name Form name
* @param array|null $options Form optiosn
* @return FlexFormInterface
*/
protected function createFormObject(string $name, array $options = null)
{
return new FlexForm($name, $this, $options);
}
/**
* @param string $action
* @return string
*/
protected function getAuthorizeAction(string $action): string
{
// Handle special action save, which can mean either update or create.
if ($action === 'save') {
$action = $this->exists() ? 'update' : 'create';
}
return $action;
}
/**
* Method to reset blueprints if the type changes.
*
* @return void
* @since 1.7.18
*/
protected function resetBlueprints(): void
{
$this->_blueprint = [];
}
// DEPRECATED METHODS
/**
* @param bool $prefix
* @return string
* @deprecated 1.6 Use `->getFlexType()` instead.
*/
public function getType($prefix = false)
{
user_error(__METHOD__ . '() is deprecated since Grav 1.6, use ->getFlexType() method instead', E_USER_DEPRECATED);
$type = $prefix ? $this->getTypePrefix() : '';
return $type . $this->getFlexType();
}
/**
* @param string $name
* @param mixed|null $default
* @param string|null $separator
* @return mixed
*
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | true |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/FlexForm.php | system/src/Grav/Framework/Flex/FlexForm.php | <?php
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex;
use ArrayAccess;
use Exception;
use Grav\Common\Data\Blueprint;
use Grav\Common\Data\Data;
use Grav\Common\Grav;
use Grav\Common\Twig\Twig;
use Grav\Common\Utils;
use Grav\Framework\Flex\Interfaces\FlexFormInterface;
use Grav\Framework\Flex\Interfaces\FlexObjectFormInterface;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
use Grav\Framework\Form\Interfaces\FormFlashInterface;
use Grav\Framework\Form\Traits\FormTrait;
use Grav\Framework\Route\Route;
use JsonSerializable;
use RocketTheme\Toolbox\ArrayTraits\NestedArrayAccessWithGetters;
use RuntimeException;
use Twig\Error\LoaderError;
use Twig\Error\SyntaxError;
use Twig\Template;
use Twig\TemplateWrapper;
/**
* Class FlexForm
* @package Grav\Framework\Flex
*/
class FlexForm implements FlexObjectFormInterface, JsonSerializable
{
use NestedArrayAccessWithGetters {
NestedArrayAccessWithGetters::get as private traitGet;
NestedArrayAccessWithGetters::set as private traitSet;
}
use FormTrait {
FormTrait::doSerialize as doTraitSerialize;
FormTrait::doUnserialize as doTraitUnserialize;
}
/** @var array */
private $items = [];
/** @var array|null */
private $form;
/** @var FlexObjectInterface */
private $object;
/** @var string */
private $flexName;
/** @var callable|null */
private $submitMethod;
/**
* @param array $options Options to initialize the form instance:
* (string) name: Form name, allows you to use custom form.
* (string) unique_id: Unique id for this form instance.
* (array) form: Custom form fields.
* (FlexObjectInterface) object: Object instance.
* (string) key: Object key, used only if object instance isn't given.
* (FlexDirectory) directory: Flex Directory, mandatory if object isn't given.
*
* @return FlexFormInterface
*/
public static function instance(array $options = [])
{
if (isset($options['object'])) {
$object = $options['object'];
if (!$object instanceof FlexObjectInterface) {
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);
}
$key = $options['key'] ?? '';
$object = $directory->getObject($key) ?? $directory->createObject([], $key);
} else {
throw new RuntimeException(__METHOD__ . "(): You need to pass option 'directory' or 'object'", 400);
}
$name = $options['name'] ?? '';
// There is no reason to pass object and directory.
unset($options['object'], $options['directory']);
return $object->getForm($name, $options);
}
/**
* FlexForm constructor.
* @param string $name
* @param FlexObjectInterface $object
* @param array|null $options
*/
public function __construct(string $name, FlexObjectInterface $object, array $options = null)
{
$this->name = $name;
$this->setObject($object);
if (isset($options['form']['name'])) {
// Use custom form name.
$this->flexName = $options['form']['name'];
} else {
// Use standard form name.
$this->setName($object->getFlexType(), $name);
}
$this->setId($this->getName());
$uniqueId = $options['unique_id'] ?? null;
if (!$uniqueId) {
if ($object->exists()) {
$uniqueId = $object->getStorageKey();
} elseif ($object->hasKey()) {
$uniqueId = "{$object->getKey()}:new";
} else {
$uniqueId = "{$object->getFlexType()}:new";
}
$uniqueId = md5($uniqueId);
}
$this->setUniqueId($uniqueId);
$directory = $object->getFlexDirectory();
$this->setFlashLookupFolder($options['flash_folder'] ?? $directory->getBlueprint()->get('form/flash_folder') ?? 'tmp://forms/[SESSIONID]');
$this->form = $options['form'] ?? null;
if (Utils::isPositive($this->items['disabled'] ?? $this->form['disabled'] ?? false)) {
$this->disable();
}
if (!empty($options['reset'])) {
$this->getFlash()->delete();
}
$this->initialize();
}
/**
* @return $this
*/
public function initialize()
{
$this->messages = [];
$this->submitted = false;
$this->data = null;
$this->files = [];
$this->unsetFlash();
/** @var FlexFormFlash $flash */
$flash = $this->getFlash();
if ($flash->exists()) {
$data = $flash->getData();
if (null !== $data) {
$data = new Data($data, $this->getBlueprint());
$data->setKeepEmptyValues(true);
$data->setMissingValuesAsNull(true);
}
$object = $flash->getObject();
if (null === $object) {
throw new RuntimeException('Flash has no object');
}
$this->object = $object;
$this->data = $data;
$includeOriginal = (bool)($this->getBlueprint()->form()['images']['original'] ?? null);
$this->files = $flash->getFilesByFields($includeOriginal);
}
return $this;
}
/**
* @param string $uniqueId
* @return void
*/
public function setUniqueId(string $uniqueId): void
{
if ($uniqueId !== '') {
$this->uniqueid = $uniqueId;
}
}
/**
* @param string $name
* @param mixed $default
* @param string|null $separator
* @return mixed
*/
public function get($name, $default = null, $separator = null)
{
switch (strtolower($name)) {
case 'id':
case 'uniqueid':
case 'name':
case 'noncename':
case 'nonceaction':
case 'action':
case 'data':
case 'files':
case 'errors';
case 'fields':
case 'blueprint':
case 'page':
$method = 'get' . $name;
return $this->{$method}();
}
return $this->traitGet($name, $default, $separator);
}
/**
* @param string $name
* @param mixed $value
* @param string|null $separator
* @return FlexForm
*/
public function set($name, $value, $separator = null)
{
switch (strtolower($name)) {
case 'id':
case 'uniqueid':
$method = 'set' . $name;
return $this->{$method}();
}
return $this->traitSet($name, $value, $separator);
}
/**
* @return string
*/
public function getName(): string
{
return $this->flexName;
}
/**
* @param callable|null $submitMethod
*/
public function setSubmitMethod(?callable $submitMethod): void
{
$this->submitMethod = $submitMethod;
}
/**
* @param string $type
* @param string $name
*/
protected function setName(string $type, string $name): void
{
// Make sure that both type and name do not have dash (convert dashes to underscores).
$type = str_replace('-', '_', $type);
$name = str_replace('-', '_', $name);
$this->flexName = $name ? "flex-{$type}-{$name}" : "flex-{$type}";
}
/**
* @return Data|FlexObjectInterface|object
*/
public function getData()
{
return $this->data ?? $this->getObject();
}
/**
* Get a value from the form.
*
* Note: Used in form fields.
*
* @param string $name
* @return mixed
*/
public function getValue(string $name)
{
// Attempt to get value from the form data.
$value = $this->data ? $this->data[$name] : null;
// Return the form data or fall back to the object property.
return $value ?? $this->getObject()->getFormValue($name);
}
/**
* @param string $name
* @return array|mixed|null
*/
public function getDefaultValue(string $name)
{
return $this->object->getDefaultValue($name);
}
/**
* @return array
*/
public function getDefaultValues(): array
{
return $this->object->getDefaultValues();
}
/**
* @return string
*/
public function getFlexType(): string
{
return $this->object->getFlexType();
}
/**
* Get form flash object.
*
* @return FormFlashInterface|FlexFormFlash
*/
public function getFlash()
{
if (null === $this->flash) {
$grav = Grav::instance();
$config = [
'session_id' => $this->getSessionId(),
'unique_id' => $this->getUniqueId(),
'form_name' => $this->getName(),
'folder' => $this->getFlashFolder(),
'id' => $this->getFlashId(),
'object' => $this->getObject()
];
$this->flash = new FlexFormFlash($config);
$this->flash
->setUrl($grav['uri']->url)
->setUser($grav['user'] ?? null);
}
return $this->flash;
}
/**
* @return FlexObjectInterface
*/
public function getObject(): FlexObjectInterface
{
return $this->object;
}
/**
* @return FlexObjectInterface
*/
public function updateObject(): FlexObjectInterface
{
$data = $this->data instanceof Data ? $this->data->toArray() : [];
$files = $this->files;
return $this->getObject()->update($data, $files);
}
/**
* @return Blueprint
*/
public function getBlueprint(): Blueprint
{
if (null === $this->blueprint) {
try {
$blueprint = $this->getObject()->getBlueprint($this->name);
if ($this->form) {
// We have field overrides available.
$blueprint->extend(['form' => $this->form], true);
$blueprint->init();
}
} catch (RuntimeException $e) {
if (!isset($this->form['fields'])) {
throw $e;
}
// Blueprint is not defined, but we have custom form fields available.
$blueprint = new Blueprint(null, ['form' => $this->form]);
$blueprint->load();
$blueprint->setScope('object');
$blueprint->init();
}
$this->blueprint = $blueprint;
}
return $this->blueprint;
}
/**
* @return Route|null
*/
public function getFileUploadAjaxRoute(): ?Route
{
$object = $this->getObject();
if (!method_exists($object, 'route')) {
/** @var Route $route */
$route = Grav::instance()['route'];
return $route->withExtension('json')->withGravParam('task', 'media.upload');
}
return $object->route('/edit.json/task:media.upload');
}
/**
* @param string|null $field
* @param string|null $filename
* @return Route|null
*/
public function getFileDeleteAjaxRoute($field = null, $filename = null): ?Route
{
$object = $this->getObject();
if (!method_exists($object, 'route')) {
/** @var Route $route */
$route = Grav::instance()['route'];
return $route->withExtension('json')->withGravParam('task', 'media.delete');
}
return $object->route('/edit.json/task:media.delete');
}
/**
* @param array $params
* @param string|null $extension
* @return string
*/
public function getMediaTaskRoute(array $params = [], string $extension = null): string
{
$grav = Grav::instance();
/** @var Flex $flex */
$flex = $grav['flex_objects'];
if (method_exists($flex, 'adminRoute')) {
return $flex->adminRoute($this->getObject(), $params, $extension ?? 'json');
}
return '';
}
/**
* @param string $name
* @return mixed|null
*/
#[\ReturnTypeWillChange]
public function __get($name)
{
$method = "get{$name}";
if (method_exists($this, $method)) {
return $this->{$method}();
}
$form = $this->getBlueprint()->form();
return $form[$name] ?? null;
}
/**
* @param string $name
* @param mixed $value
* @return void
*/
#[\ReturnTypeWillChange]
public function __set($name, $value)
{
$method = "set{$name}";
if (method_exists($this, $method)) {
$this->{$method}($value);
}
}
/**
* @param string $name
* @return bool
*/
#[\ReturnTypeWillChange]
public function __isset($name)
{
$method = "get{$name}";
if (method_exists($this, $method)) {
return true;
}
$form = $this->getBlueprint()->form();
return isset($form[$name]);
}
/**
* @param string $name
* @return void
*/
#[\ReturnTypeWillChange]
public function __unset($name)
{
}
/**
* @return array|bool
*/
protected function getUnserializeAllowedClasses()
{
return [FlexObject::class];
}
/**
* Note: this method clones the object.
*
* @param FlexObjectInterface $object
* @return $this
*/
protected function setObject(FlexObjectInterface $object): self
{
$this->object = clone $object;
return $this;
}
/**
* @param string $layout
* @return Template|TemplateWrapper
* @throws LoaderError
* @throws SyntaxError
*/
protected function getTemplate($layout)
{
$grav = Grav::instance();
/** @var Twig $twig */
$twig = $grav['twig'];
return $twig->twig()->resolveTemplate(
[
"flex-objects/layouts/{$this->getFlexType()}/form/{$layout}.html.twig",
"flex-objects/layouts/_default/form/{$layout}.html.twig",
"forms/{$layout}/form.html.twig",
'forms/default/form.html.twig'
]
);
}
/**
* @param array $data
* @param array $files
* @return void
* @throws Exception
*/
protected function doSubmit(array $data, array $files)
{
/** @var FlexObject $object */
$object = clone $this->getObject();
$method = $this->submitMethod;
if ($method) {
$method($data, $files, $object);
} else {
$object->update($data, $files);
$object->save();
}
$this->setObject($object);
$this->reset();
}
/**
* @return array
*/
protected function doSerialize(): array
{
return $this->doTraitSerialize() + [
'items' => $this->items,
'form' => $this->form,
'object' => $this->object,
'flexName' => $this->flexName,
'submitMethod' => $this->submitMethod,
];
}
/**
* @param array $data
* @return void
*/
protected function doUnserialize(array $data): void
{
$this->doTraitUnserialize($data);
$this->items = $data['items'] ?? null;
$this->form = $data['form'] ?? null;
$this->object = $data['object'] ?? null;
$this->flexName = $data['flexName'] ?? null;
$this->submitMethod = $data['submitMethod'] ?? null;
}
/**
* Filter validated data.
*
* @param ArrayAccess|Data|null $data
* @return void
* @phpstan-param ArrayAccess<string,mixed>|Data|null $data
*/
protected function filterData($data = null): void
{
if ($data instanceof Data) {
$data->filter(true, true);
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/FlexFormFlash.php | system/src/Grav/Framework/Flex/FlexFormFlash.php | <?php
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex;
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 */
protected $directory;
/** @var FlexObjectInterface|null */
protected $object;
/** @var FlexInterface */
static protected $flex;
public static function setFlex(FlexInterface $flex): void
{
static::$flex = $flex;
}
/**
* @param FlexObjectInterface $object
* @return void
*/
public function setObject(FlexObjectInterface $object): void
{
$this->object = $object;
$this->directory = $object->getFlexDirectory();
}
/**
* @return FlexObjectInterface|null
*/
public function getObject(): ?FlexObjectInterface
{
return $this->object;
}
/**
* @param FlexDirectory $directory
*/
public function setDirectory(FlexDirectory $directory): void
{
$this->directory = $directory;
}
/**
* @return FlexDirectory|null
*/
public function getDirectory(): ?FlexDirectory
{
return $this->directory;
}
/**
* @return array
*/
public function jsonSerialize(): array
{
$serialized = parent::jsonSerialize();
$object = $this->getObject();
if ($object instanceof FlexObjectInterface) {
$serialized['object'] = [
'type' => $object->getFlexType(),
'key' => $object->getKey() ?: null,
'storage_key' => $object->getStorageKey(),
'timestamp' => $object->getTimestamp(),
'serialized' => $object->prepareStorage()
];
} else {
$directory = $this->getDirectory();
if ($directory instanceof FlexDirectory) {
$serialized['directory'] = [
'type' => $directory->getFlexType()
];
}
}
return $serialized;
}
/**
* @param array|null $data
* @param array $config
* @return void
*/
protected function init(?array $data, array $config): void
{
parent::init($data, $config);
$data = $data ?? [];
/** @var FlexObjectInterface|null $object */
$object = $config['object'] ?? null;
$create = true;
if ($object) {
$directory = $object->getFlexDirectory();
$create = !$object->exists();
} elseif (null === ($directory = $config['directory'] ?? null)) {
$flex = $config['flex'] ?? static::$flex;
$type = $data['object']['type'] ?? $data['directory']['type'] ?? null;
$directory = $flex && $type ? $flex->getDirectory($type) : null;
}
if ($directory && $create && isset($data['object']['serialized'])) {
// TODO: update instead of create new.
$object = $directory->createObject($data['object']['serialized'], $data['object']['key'] ?? '');
}
if ($object) {
$this->setObject($object);
} elseif ($directory) {
$this->setDirectory($directory);
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Flex.php | system/src/Grav/Framework/Flex/Flex.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex;
use Grav\Common\Debugger;
use Grav\Common\Grav;
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 count;
use function is_array;
/**
* Class Flex
* @package Grav\Framework\Flex
*/
class Flex implements FlexInterface
{
/** @var array */
protected $config;
/** @var FlexDirectory[] */
protected $types;
/**
* Flex constructor.
* @param array $types List of [type => blueprint file, ...]
* @param array $config
*/
public function __construct(array $types, array $config)
{
$this->config = $config;
$this->types = [];
foreach ($types as $type => $blueprint) {
if (!file_exists($blueprint)) {
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$debugger->addMessage(sprintf('Flex: blueprint for flex type %s is missing', $type), 'error');
continue;
}
$this->addDirectoryType($type, $blueprint);
}
}
/**
* @param string $type
* @param string $blueprint
* @param array $config
* @return $this
*/
public function addDirectoryType(string $type, string $blueprint, array $config = [])
{
$config = array_replace_recursive(['enabled' => true], $this->config, $config);
$this->types[$type] = new FlexDirectory($type, $blueprint, $config);
return $this;
}
/**
* @param FlexDirectory $directory
* @return $this
*/
public function addDirectory(FlexDirectory $directory)
{
$this->types[$directory->getFlexType()] = $directory;
return $this;
}
/**
* @param string $type
* @return bool
*/
public function hasDirectory(string $type): bool
{
return isset($this->types[$type]);
}
/**
* @param array|string[]|null $types
* @param bool $keepMissing
* @return array<FlexDirectory|null>
*/
public function getDirectories(array $types = null, bool $keepMissing = false): array
{
if ($types === null) {
return $this->types;
}
// Return the directories in the given order.
$directories = [];
foreach ($types as $type) {
$directories[$type] = $this->types[$type] ?? null;
}
return $keepMissing ? $directories : array_filter($directories);
}
/**
* @param string $type
* @return FlexDirectory|null
*/
public function getDirectory(string $type): ?FlexDirectory
{
return $this->types[$type] ?? null;
}
/**
* @param string $type
* @param array|null $keys
* @param string|null $keyField
* @return FlexCollectionInterface|null
* @phpstan-return FlexCollectionInterface<FlexObjectInterface>|null
*/
public function getCollection(string $type, array $keys = null, string $keyField = null): ?FlexCollectionInterface
{
$directory = $type ? $this->getDirectory($type) : null;
return $directory ? $directory->getCollection($keys, $keyField) : null;
}
/**
* @param array $keys
* @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
* @phpstan-return FlexCollectionInterface<FlexObjectInterface>
*/
public function getMixedCollection(array $keys, array $options = []): FlexCollectionInterface
{
$collectionClass = $options['collection_class'] ?? ObjectCollection::class;
if (!is_a($collectionClass, FlexCollectionInterface::class, true)) {
throw new RuntimeException(sprintf('Cannot create collection: Class %s does not exist', $collectionClass));
}
$objects = $this->getObjects($keys, $options);
return new $collectionClass($objects);
}
/**
* @param array $keys
* @param array $options Following optional options can be passed:
* types: List of allowed types.
* type: Allowed type if types isn't defined, otherwise acts as default_type.
* default_type: Set default type for objects given without type (only used if key_field isn't set).
* keep_missing: Set to true if you want to return missing objects as null.
* key_field: Key field which is used to match the objects.
* @return array
*/
public function getObjects(array $keys, array $options = []): array
{
$type = $options['type'] ?? null;
$defaultType = $options['default_type'] ?? $type ?? null;
$keyField = $options['key_field'] ?? 'flex_key';
// Prepare empty result lists for all requested Flex types.
$types = $options['types'] ?? (array)$type ?: null;
if ($types) {
$types = array_fill_keys($types, []);
}
$strict = isset($types);
$guessed = [];
if ($keyField === 'flex_key') {
// We need to split Flex key lookups into individual directories.
$undefined = [];
$keyFieldFind = 'storage_key';
foreach ($keys as $flexKey) {
if (!$flexKey) {
continue;
}
$flexKey = (string)$flexKey;
// Normalize key and type using fallback to default type if it was set.
[$key, $type, $guess] = $this->resolveKeyAndType($flexKey, $defaultType);
if ($type === '' && $types) {
// Add keys which are not associated to any Flex type. They will be included to every Flex type.
foreach ($types as $type => &$array) {
$array[] = $key;
$guessed[$key][] = "{$type}.obj:{$key}";
}
unset($array);
} elseif (!$strict || isset($types[$type])) {
// Collect keys by their Flex type. If allowed types are defined, only include values from those types.
$types[$type][] = $key;
if ($guess) {
$guessed[$key][] = "{$type}.obj:{$key}";
}
}
}
} else {
// We are using a specific key field, make every key undefined.
$undefined = $keys;
$keyFieldFind = $keyField;
}
if (!$types) {
return [];
}
$list = [[]];
foreach ($types as $type => $typeKeys) {
// Also remember to look up keys from undefined Flex types.
$lookupKeys = $undefined ? array_merge($typeKeys, $undefined) : $typeKeys;
$collection = $this->getCollection($type, $lookupKeys, $keyFieldFind);
if ($collection && $keyFieldFind !== $keyField) {
$collection = $collection->withKeyField($keyField);
}
$list[] = $collection ? $collection->toArray() : [];
}
// Merge objects from individual types back together.
$list = array_merge(...$list);
// Use the original key ordering.
if (!$guessed) {
$list = array_replace(array_fill_keys($keys, null), $list);
} else {
// We have mixed keys, we need to map flex keys back to storage keys.
$results = [];
foreach ($keys as $key) {
$flexKey = $guessed[$key] ?? $key;
if (is_array($flexKey)) {
$result = null;
foreach ($flexKey as $tryKey) {
if ($result = $list[$tryKey] ?? null) {
// Use the first matching object (conflicting objects will be ignored for now).
break;
}
}
} else {
$result = $list[$flexKey] ?? null;
}
$results[$key] = $result;
}
$list = $results;
}
// Remove missing objects if not asked to keep them.
if (empty($options['keep_missing'])) {
$list = array_filter($list);
}
return $list;
}
/**
* @param string $key
* @param string|null $type
* @param string|null $keyField
* @return FlexObjectInterface|null
*/
public function getObject(string $key, string $type = null, string $keyField = null): ?FlexObjectInterface
{
if (null === $type && null === $keyField) {
// Special handling for quick Flex key lookups.
$keyField = 'storage_key';
[$key, $type] = $this->resolveKeyAndType($key, $type);
} else {
$type = $this->resolveType($type);
}
if ($type === '' || $key === '') {
return null;
}
$directory = $this->getDirectory($type);
return $directory ? $directory->getObject($key, $keyField) : null;
}
/**
* @return int
*/
public function count(): int
{
return count($this->types);
}
/**
* @param string $flexKey
* @param string|null $type
* @return array
*/
protected function resolveKeyAndType(string $flexKey, string $type = null): array
{
$guess = false;
if (strpos($flexKey, ':') !== false) {
[$type, $key] = explode(':', $flexKey, 2);
$type = $this->resolveType($type);
} else {
$key = $flexKey;
$type = (string)$type;
$guess = true;
}
return [$key, $type, $guess];
}
/**
* @param string|null $type
* @return string
*/
protected function resolveType(string $type = null): string
{
if (null !== $type && strpos($type, '.') !== false) {
return preg_replace('|\.obj$|', '', $type) ?? $type;
}
return $type ?? '';
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Interfaces/FlexCollectionInterface.php | system/src/Grav/Framework/Flex/Interfaces/FlexCollectionInterface.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Interfaces;
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.
*
* @used-by \Grav\Framework\Flex\FlexCollection
* @since 1.6
* @template T
* @extends ObjectCollectionInterface<string,T>
*/
interface FlexCollectionInterface extends FlexCommonInterface, ObjectCollectionInterface, NestedObjectInterface
{
/**
* Creates a Flex Collection from an array.
*
* @used-by FlexDirectory::createCollection() Official method to create a Flex Collection.
*
* @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);
/**
* Creates a new Flex Collection.
*
* @used-by FlexDirectory::createCollection() Official method to create Flex Collection.
*
* @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
*/
public function __construct(array $entries = [], FlexDirectory $directory = null);
/**
* Search a string from the collection.
*
* @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.
* @phpstan-return static<T>
* @api
*/
public function search(string $search, $properties = null, array $options = null);
/**
* Sort the collection.
*
* @param array $orderings Pair of [property => 'ASC'|'DESC', ...].
*
* @return FlexCollectionInterface Returns a sorted version from the collection.
* @phpstan-return static<T>
*/
public function sort(array $orderings);
/**
* Filter collection by filter array with keys and values.
*
* @param array $filters
* @return FlexCollectionInterface
* @phpstan-return static<T>
*/
public function filterBy(array $filters);
/**
* Get timestamps from all the objects in the collection.
*
* This method can be used for example in caching.
*
* @return int[] Returns [key => timestamp, ...] pairs.
*/
public function getTimestamps(): array;
/**
* Get storage keys from all the objects in the collection.
*
* @see FlexDirectory::getObject() If you want to get Flex Object from the Flex Directory.
*
* @return string[] Returns [key => storage_key, ...] pairs.
*/
public function getStorageKeys(): array;
/**
* Get Flex keys from all the objects in the collection.
*
* @see Flex::getObjects() If you want to get list of Flex Objects from any Flex Directory.
*
* @return string[] Returns[key => flex_key, ...] pairs.
*/
public function getFlexKeys(): array;
/**
* 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.
* @phpstan-return static<T>
* @api
*/
public function withKeyField(string $keyField = null);
/**
* Get Flex Index from the Flex Collection.
*
* @return FlexIndexInterface Returns a Flex Index from the current collection.
* @phpstan-return FlexIndexInterface<T>
*/
public function getIndex();
/**
* Load all the objects into memory,
*
* @return FlexCollectionInterface
* @phpstan-return static<T>
*/
public function getCollection();
/**
* Get metadata associated to the object
*
* @param string $key Key.
* @return array
*/
public function getMetaData($key): array;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Interfaces/FlexObjectInterface.php | system/src/Grav/Framework/Flex/Interfaces/FlexObjectInterface.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Interfaces;
use ArrayAccess;
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.
*
* @extends ArrayAccess<string,mixed>
* @used-by \Grav\Framework\Flex\FlexObject
* @since 1.6
*/
interface FlexObjectInterface extends FlexCommonInterface, NestedObjectInterface, ArrayAccess
{
/**
* Construct a new Flex Object instance.
*
* @used-by FlexDirectory::createObject() Method to create Flex Object.
*
* @param array $elements Array of object properties.
* @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
*/
public function __construct(array $elements, $key, FlexDirectory $directory, bool $validate = false);
/**
* Search a string from the object, returns weight between 0 and 1.
*
* Note: If you override this function, make sure you return value in range 0...1!
*
* @used-by FlexCollectionInterface::search() If you want to search a string from a Flex Collection.
*
* @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
*/
public function search(string $search, $properties = null, array $options = null): float;
/**
* Returns true if object has a key.
*
* @return bool
*/
public function hasKey();
/**
* Get a unique key for the object.
*
* Flex Keys can be used without knowing the Directory the Object belongs into.
*
* @see Flex::getObject() If you want to get Flex Object from any Flex Directory.
* @see Flex::getObjects() If you want to get list of Flex Objects from any Flex Directory.
*
* NOTE: Please do not override the method!
*
* @return string Returns Flex Key of the object.
* @api
*/
public function getFlexKey(): string;
/**
* Get an unique storage key (within the directory) which is used for figuring out the filename or database id.
*
* @see FlexDirectory::getObject() If you want to get Flex Object from the Flex Directory.
* @see FlexDirectory::getCollection() If you want to get Flex Collection with selected keys from the Flex Directory.
*
* @return string Returns storage key of the Object.
* @api
*/
public function getStorageKey(): string;
/**
* Get index data associated to the object.
*
* @return array Returns metadata of the object.
*/
public function getMetaData(): array;
/**
* Returns true if the object exists in the storage.
*
* @return bool Returns `true` if the object exists, `false` otherwise.
* @api
*/
public function exists(): bool;
/**
* Prepare object for saving into the storage.
*
* @return array Returns an array of object properties containing only scalars and arrays.
*/
public function prepareStorage(): array;
/**
* Updates object in the memory.
*
* @see FlexObjectInterface::save() You need to save the object after calling this method.
*
* @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 static
* @throws RuntimeException
* @api
*/
public function update(array $data, array $files = []);
/**
* Create new object into the storage.
*
* @see FlexDirectory::createObject() If you want to create a new object instance.
* @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 static
* @throws RuntimeException if object already exists.
* @api
*/
public function create(string $key = null);
/**
* Save object into the storage.
*
* @see FlexObjectInterface::update() If you want to update properties of the object.
*
* @return static
* @api
*/
public function save();
/**
* Delete object from the storage.
*
* @return static
* @api
*/
public function delete();
/**
* Returns the blueprint of the object.
*
* @see FlexObjectInterface::getForm()
* @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 = '');
/**
* Returns a form instance for the object.
*
* @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
*/
public function getForm(string $name = '', array $options = null);
/**
* Returns default value suitable to be used in a form for the given property.
*
* @see FlexObjectInterface::getForm()
*
* @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);
/**
* Returns default values suitable to be used in a form for the given property.
*
* @see FlexObjectInterface::getForm()
*
* @return array Returns default values.
*/
public function getDefaultValues(): array;
/**
* Returns raw value suitable to be used in a form for the given property.
*
* @see FlexObjectInterface::getForm()
*
* @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);
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Interfaces/FlexDirectoryFormInterface.php | system/src/Grav/Framework/Flex/Interfaces/FlexDirectoryFormInterface.php | <?php
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Interfaces;
/**
* Defines Forms for Flex Objects.
*
* @used-by \Grav\Framework\Flex\FlexForm
* @since 1.7
*/
interface FlexDirectoryFormInterface extends FlexFormInterface
{
/**
* Get object associated to the form.
*
* @return FlexObjectInterface Returns Flex Object associated to the form.
* @api
*/
public function getDirectory();
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Interfaces/FlexInterface.php | system/src/Grav/Framework/Flex/Interfaces/FlexInterface.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Interfaces;
use Countable;
use Grav\Framework\Flex\FlexDirectory;
use RuntimeException;
/**
* Interface FlexInterface
* @package Grav\Framework\Flex\Interfaces
*/
interface FlexInterface extends Countable
{
/**
* @param string $type
* @param string $blueprint
* @param array $config
* @return $this
*/
public function addDirectoryType(string $type, string $blueprint, array $config = []);
/**
* @param FlexDirectory $directory
* @return $this
*/
public function addDirectory(FlexDirectory $directory);
/**
* @param string $type
* @return bool
*/
public function hasDirectory(string $type): bool;
/**
* @param array|string[]|null $types
* @param bool $keepMissing
* @return array<FlexDirectory|null>
*/
public function getDirectories(array $types = null, bool $keepMissing = false): array;
/**
* @param string $type
* @return FlexDirectory|null
*/
public function getDirectory(string $type): ?FlexDirectory;
/**
* @param string $type
* @param array|null $keys
* @param string|null $keyField
* @return FlexCollectionInterface|null
* @phpstan-return FlexCollectionInterface<FlexObjectInterface>|null
*/
public function getCollection(string $type, array $keys = null, string $keyField = null): ?FlexCollectionInterface;
/**
* @param array $keys
* @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
* @phpstan-return FlexCollectionInterface<FlexObjectInterface>
*/
public function getMixedCollection(array $keys, array $options = []): FlexCollectionInterface;
/**
* @param array $keys
* @param array $options Following optional options can be passed:
* types: List of allowed types.
* type: Allowed type if types isn't defined, otherwise acts as default_type.
* default_type: Set default type for objects given without type (only used if key_field isn't set).
* keep_missing: Set to true if you want to return missing objects as null.
* key_field: Key field which is used to match the objects.
* @return array
*/
public function getObjects(array $keys, array $options = []): array;
/**
* @param string $key
* @param string|null $type
* @param string|null $keyField
* @return FlexObjectInterface|null
*/
public function getObject(string $key, string $type = null, string $keyField = null): ?FlexObjectInterface;
/**
* @return int
*/
public function count(): int;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Interfaces/FlexTranslateInterface.php | system/src/Grav/Framework/Flex/Interfaces/FlexTranslateInterface.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Interfaces;
/**
* Implements PageTranslateInterface
*/
interface FlexTranslateInterface
{
/**
* Returns true if object has a translation in given language (or any of its fallback languages).
*
* @param string|null $languageCode
* @param bool|null $fallback
* @return bool
*/
public function hasTranslation(string $languageCode = null, bool $fallback = null): bool;
/**
* Get translation.
*
* @param string|null $languageCode
* @param bool|null $fallback
* @return static|null
*/
public function getTranslation(string $languageCode = null, bool $fallback = null);
/**
* Returns all translated languages.
*
* @param bool $includeDefault If set to true, return separate entries for '' and 'en' (default) language.
* @return array
*/
public function getLanguages(bool $includeDefault = false): array;
/**
* Get used language.
*
* @return string
*/
public function getLanguage(): string;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Interfaces/FlexDirectoryInterface.php | system/src/Grav/Framework/Flex/Interfaces/FlexDirectoryInterface.php | <?php
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Interfaces;
use Exception;
use Grav\Common\Data\Blueprint;
use Grav\Framework\Cache\CacheInterface;
/**
* Interface FlexDirectoryInterface
* @package Grav\Framework\Flex\Interfaces
*/
interface FlexDirectoryInterface extends FlexAuthorizeInterface
{
/**
* @return bool
*/
public function isListed(): bool;
/**
* @return bool
*/
public function isEnabled(): bool;
/**
* @return string
*/
public function getFlexType(): string;
/**
* @return string
*/
public function getTitle(): string;
/**
* @return string
*/
public function getDescription(): string;
/**
* @param string|null $name
* @param mixed $default
* @return mixed
*/
public function getConfig(string $name = null, $default = null);
/**
* @param string|null $name
* @param array $options
* @return FlexFormInterface
* @internal
*/
public function getDirectoryForm(string $name = null, array $options = []);
/**
* @return Blueprint
* @internal
*/
public function getDirectoryBlueprint();
/**
* @param string $name
* @param array $data
* @return void
* @throws Exception
* @internal
*/
public function saveDirectoryConfig(string $name, array $data);
/**
* @param string|null $name
* @return string
*/
public function getDirectoryConfigUri(string $name = null): string;
/**
* Returns a new uninitialized instance of blueprint.
*
* Always use $object->getBlueprint() or $object->getForm()->getBlueprint() instead.
*
* @param string $type
* @param string $context
* @return Blueprint
*/
public function getBlueprint(string $type = '', string $context = '');
/**
* @param string $view
* @return string
*/
public function getBlueprintFile(string $view = ''): string;
/**
* Get collection. In the site this will be filtered by the default filters (published etc).
*
* Use $directory->getIndex() if you want unfiltered collection.
*
* @param array|null $keys Array of keys.
* @param string|null $keyField Field to be used as the key.
* @return FlexCollectionInterface
* @phpstan-return FlexCollectionInterface<FlexObjectInterface>
*/
public function getCollection(array $keys = null, string $keyField = null): FlexCollectionInterface;
/**
* Get the full collection of all stored objects.
*
* Use $directory->getCollection() if you want a filtered collection.
*
* @param array|null $keys Array of keys.
* @param string|null $keyField Field to be used as the key.
* @return FlexIndexInterface
* @phpstan-return FlexIndexInterface<FlexObjectInterface>
*/
public function getIndex(array $keys = null, string $keyField = null): FlexIndexInterface;
/**
* Returns an object if it exists. If no arguments are passed (or both of them are null), method creates a new empty object.
*
* Note: It is not safe to use the object without checking if the user can access it.
*
* @param string|null $key
* @param string|null $keyField Field to be used as the key.
* @return FlexObjectInterface|null
*/
public function getObject($key = null, string $keyField = null): ?FlexObjectInterface;
/**
* @param string|null $namespace
* @return CacheInterface
*/
public function getCache(string $namespace = null);
/**
* @return $this
*/
public function clearCache();
/**
* @param string|null $key
* @return string|null
*/
public function getStorageFolder(string $key = null): ?string;
/**
* @param string|null $key
* @return string|null
*/
public function getMediaFolder(string $key = null): ?string;
/**
* @return FlexStorageInterface
*/
public function getStorage(): FlexStorageInterface;
/**
* @param array $data
* @param string $key
* @param bool $validate
* @return FlexObjectInterface
*/
public function createObject(array $data, string $key = '', bool $validate = false): FlexObjectInterface;
/**
* @param array $entries
* @param string|null $keyField
* @return FlexCollectionInterface
* @phpstan-return FlexCollectionInterface<FlexObjectInterface>
*/
public function createCollection(array $entries, string $keyField = null): FlexCollectionInterface;
/**
* @param array $entries
* @param string|null $keyField
* @return FlexIndexInterface
* @phpstan-return FlexIndexInterface<FlexObjectInterface>
*/
public function createIndex(array $entries, string $keyField = null): FlexIndexInterface;
/**
* @return string
*/
public function getObjectClass(): string;
/**
* @return string
*/
public function getCollectionClass(): string;
/**
* @return string
*/
public function getIndexClass(): string;
/**
* @param array $entries
* @param string|null $keyField
* @return FlexCollectionInterface
* @phpstan-return FlexCollectionInterface<FlexObjectInterface>
*/
public function loadCollection(array $entries, string $keyField = null): FlexCollectionInterface;
/**
* @param array $entries
* @return FlexObjectInterface[]
* @internal
*/
public function loadObjects(array $entries): array;
/**
* @return void
*/
public function reloadIndex(): void;
/**
* @param string $scope
* @param string $action
* @return string
*/
public function getAuthorizeRule(string $scope, string $action): string;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Interfaces/FlexAuthorizeInterface.php | system/src/Grav/Framework/Flex/Interfaces/FlexAuthorizeInterface.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Interfaces;
use Grav\Common\User\Interfaces\UserInterface;
/**
* Defines authorization checks for Flex Objects.
*/
interface FlexAuthorizeInterface
{
/**
* Check if user is authorized for the action.
*
* Note: There are two deny values: denied (false), not set (null). This allows chaining multiple rules together
* when the previous rules were not matched.
*
* @param string $action
* @param string|null $scope
* @param UserInterface|null $user
* @return bool|null
*/
public function isAuthorized(string $action, string $scope = null, UserInterface $user = null): ?bool;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Interfaces/FlexStorageInterface.php | system/src/Grav/Framework/Flex/Interfaces/FlexStorageInterface.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Interfaces;
/**
* Defines Flex Storage layer.
*
* @since 1.6
*/
interface FlexStorageInterface
{
/**
* StorageInterface constructor.
* @param array $options
*/
public function __construct(array $options);
/**
* @return string
*/
public function getKeyField(): string;
/**
* @param string[] $keys
* @param bool $reload
* @return array
*/
public function getMetaData(array $keys, bool $reload = false): array;
/**
* Returns associated array of all existing storage keys with a timestamp.
*
* @return array Returns all existing keys as `[key => [storage_key => key, storage_timestamp => timestamp], ...]`.
*/
public function getExistingKeys(): array;
/**
* Check if the key exists in the storage.
*
* @param string $key Storage key of an object.
* @return bool Returns `true` if the key exists in the storage, `false` otherwise.
*/
public function hasKey(string $key): bool;
/**
* Check if the key exists in the storage.
*
* @param string[] $keys Storage key of an object.
* @return bool[] Returns keys with `true` if the key exists in the storage, `false` otherwise.
*/
public function hasKeys(array $keys): array;
/**
* Create new rows into the storage.
*
* New keys will be assigned when the objects are created.
*
* @param array $rows List of rows as `[row, ...]`.
* @return array Returns created rows as `[key => row, ...] pairs.
*/
public function createRows(array $rows): array;
/**
* Read rows from the storage.
*
* If you pass object or array as value, that value will be used to save I/O.
*
* @param array $rows Array of `[key => row, ...]` pairs.
* @param array|null $fetched Optional reference to store only fetched items.
* @return array Returns rows. Note that non-existing rows will have `null` as their value.
*/
public function readRows(array $rows, array &$fetched = null): array;
/**
* Update existing rows in the storage.
*
* @param array $rows Array of `[key => row, ...]` pairs.
* @return array Returns updated rows. Note that non-existing rows will not be saved and have `null` as their value.
*/
public function updateRows(array $rows): array;
/**
* Delete rows from the storage.
*
* @param array $rows Array of `[key => row, ...]` pairs.
* @return array Returns deleted rows. Note that non-existing rows have `null` as their value.
*/
public function deleteRows(array $rows): array;
/**
* Replace rows regardless if they exist or not.
*
* All rows should have a specified key for replace to work properly.
*
* @param array $rows Array of `[key => row, ...]` pairs.
* @return array Returns both created and updated rows.
*/
public function replaceRows(array $rows): array;
/**
* @param string $src
* @param string $dst
* @return bool
*/
public function copyRow(string $src, string $dst): bool;
/**
* @param string $src
* @param string $dst
* @return bool
*/
public function renameRow(string $src, string $dst): bool;
/**
* Get filesystem path for the collection or object storage.
*
* @param string|null $key Optional storage key.
* @return string|null Path in the filesystem. Can be URI or null if storage is not filesystem based.
*/
public function getStoragePath(string $key = null): ?string;
/**
* Get filesystem path for the collection or object media.
*
* @param string|null $key Optional storage key.
* @return string|null Path in the filesystem. Can be URI or null if media isn't supported.
*/
public function getMediaPath(string $key = null): ?string;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Interfaces/FlexCommonInterface.php | system/src/Grav/Framework/Flex/Interfaces/FlexCommonInterface.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Interfaces;
use Grav\Framework\Flex\FlexDirectory;
use Grav\Framework\Interfaces\RenderInterface;
/**
* Defines common interface shared with both Flex Objects and Collections.
*
* @used-by \Grav\Framework\Flex\FlexObject
* @since 1.6
*/
interface FlexCommonInterface extends RenderInterface
{
/**
* Get Flex Type of the object / collection.
*
* @return string Returns Flex Type of the collection.
* @api
*/
public function getFlexType(): string;
/**
* Get Flex Directory for the object / collection.
*
* @return FlexDirectory Returns associated Flex Directory.
* @api
*/
public function getFlexDirectory(): FlexDirectory;
/**
* Test whether the feature is implemented in the object / collection.
*
* @param string $name
* @return bool
*/
public function hasFlexFeature(string $name): bool;
/**
* Get full list of features the object / collection implements.
*
* @return array
*/
public function getFlexFeatures(): array;
/**
* Get last updated timestamp for the object / collection.
*
* @return int Returns Unix timestamp.
* @api
*/
public function getTimestamp(): int;
/**
* Get a cache key which is used for caching the object / collection.
*
* @return string Returns cache key.
*/
public function getCacheKey(): string;
/**
* Get cache checksum for the object / collection.
*
* If checksum changes, cache gets invalided.
*
* @return string Returns cache checksum.
*/
public function getCacheChecksum(): string;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Interfaces/FlexIndexInterface.php | system/src/Grav/Framework/Flex/Interfaces/FlexIndexInterface.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Interfaces;
use Grav\Framework\Flex\FlexDirectory;
/**
* Defines Indexes for Flex Objects.
*
* Flex indexes are similar to database indexes, they contain indexed fields which can be used to quickly look up or
* find the objects without loading them.
*
* @used-by \Grav\Framework\Flex\FlexIndex
* @since 1.6
* @template T
* @extends FlexCollectionInterface<T>
*/
interface FlexIndexInterface extends FlexCollectionInterface
{
/**
* Helper method to create Flex Index.
*
* @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);
/**
* Method to load index from the object storage, usually filesystem.
*
* @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;
/**
* Return new collection with a different key.
*
* @param string|null $keyField Switch key field of the collection.
* @return static Returns a new Flex Collection with new key field.
* @phpstan-return static<T>
* @api
*/
public function withKeyField(string $keyField = null);
/**
* @param string|null $indexKey
* @return array
*/
public function getIndexMap(string $indexKey = null);
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Interfaces/FlexObjectFormInterface.php | system/src/Grav/Framework/Flex/Interfaces/FlexObjectFormInterface.php | <?php
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Interfaces;
/**
* Defines Forms for Flex Objects.
*
* @used-by \Grav\Framework\Flex\FlexForm
* @since 1.7
*/
interface FlexObjectFormInterface extends FlexFormInterface
{
/**
* Get object associated to the form.
*
* @return FlexObjectInterface Returns Flex Object associated to the form.
* @api
*/
public function getObject();
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Interfaces/FlexFormInterface.php | system/src/Grav/Framework/Flex/Interfaces/FlexFormInterface.php | <?php
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Interfaces;
use Grav\Framework\Form\Interfaces\FormInterface;
use Grav\Framework\Route\Route;
use Serializable;
/**
* Defines Forms for Flex Objects.
*
* @used-by \Grav\Framework\Flex\FlexForm
* @since 1.6
*/
interface FlexFormInterface extends Serializable, FormInterface
{
/**
* Get media task route.
*
* @return string Returns admin route for media tasks.
*/
public function getMediaTaskRoute(): string;
/**
* Get route for uploading files by AJAX.
*
* @return Route|null Returns Route object or null if file uploads are not enabled.
*/
public function getFileUploadAjaxRoute();
/**
* Get route for deleting files by AJAX.
*
* @param string|null $field Field where the file is associated into.
* @param string|null $filename Filename for the file.
* @return Route|null Returns Route object or null if file uploads are not enabled.
*/
public function getFileDeleteAjaxRoute($field, $filename);
// /**
// * @return FlexObjectInterface
// */
// public function getObject();
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Traits/FlexRelatedDirectoryTrait.php | system/src/Grav/Framework/Flex/Traits/FlexRelatedDirectoryTrait.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Traits;
use Grav\Framework\Flex\FlexDirectory;
use Grav\Framework\Flex\Interfaces\FlexCollectionInterface;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
use RuntimeException;
use function in_array;
/**
* Trait GravTrait
* @package Grav\Common\Flex\Traits
*/
trait FlexRelatedDirectoryTrait
{
/**
* @param string $type
* @param string $property
* @return FlexCollectionInterface<FlexObjectInterface>
*/
protected function getCollectionByProperty($type, $property)
{
$directory = $this->getRelatedDirectory($type);
$collection = $directory->getCollection();
$list = $this->getNestedProperty($property) ?: [];
/** @var FlexCollectionInterface<FlexObjectInterface> $collection */
$collection = $collection->filter(static function ($object) use ($list) {
return in_array($object->getKey(), $list, true);
});
return $collection;
}
/**
* @param string $type
* @return FlexDirectory
* @throws RuntimeException
*/
protected function getRelatedDirectory($type): FlexDirectory
{
$directory = $this->getFlexContainer()->getDirectory($type);
if (!$directory) {
throw new RuntimeException(ucfirst($type). ' directory does not exist!');
}
return $directory;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Traits/FlexAuthorizeTrait.php | system/src/Grav/Framework/Flex/Traits/FlexAuthorizeTrait.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Traits;
use Grav\Common\User\Interfaces\UserInterface;
use Grav\Framework\Flex\FlexDirectory;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
/**
* Implements basic ACL
*/
trait FlexAuthorizeTrait
{
/**
* Check if user is authorized for the action.
*
* Note: There are two deny values: denied (false), not set (null). This allows chaining multiple rules together
* when the previous rules were not matched.
*
* To override the default behavior, please use isAuthorizedOverride().
*
* @param string $action
* @param string|null $scope
* @param UserInterface|null $user
* @return bool|null
* @final
*/
public function isAuthorized(string $action, string $scope = null, UserInterface $user = null): ?bool
{
$action = $this->getAuthorizeAction($action);
$scope = $scope ?? $this->getAuthorizeScope();
$isMe = null === $user;
if ($isMe) {
$user = $this->getActiveUser();
}
if (null === $user) {
return false;
}
// Finally authorize against given action.
return $this->isAuthorizedOverride($user, $action, $scope, $isMe);
}
/**
* Please override this method
*
* @param UserInterface $user
* @param string $action
* @param string $scope
* @param bool $isMe
* @return bool|null
*/
protected function isAuthorizedOverride(UserInterface $user, string $action, string $scope, bool $isMe): ?bool
{
return $this->isAuthorizedAction($user, $action, $scope, $isMe);
}
/**
* Check if user is authorized for the action.
*
* @param UserInterface $user
* @param string $action
* @param string $scope
* @param bool $isMe
* @return bool|null
*/
protected function isAuthorizedAction(UserInterface $user, string $action, string $scope, bool $isMe): ?bool
{
// Check if the action has been denied in the flex type configuration.
$directory = $this instanceof FlexDirectory ? $this : $this->getFlexDirectory();
$config = $directory->getConfig();
$allowed = $config->get("{$scope}.actions.{$action}") ?? $config->get("actions.{$action}") ?? true;
if (false === $allowed) {
return false;
}
// TODO: Not needed anymore with flex users, remove in 2.0.
$auth = $user instanceof FlexObjectInterface ? null : $user->authorize('admin.super');
if (true === $auth) {
return true;
}
// Finally authorize the action.
return $user->authorize($this->getAuthorizeRule($scope, $action), !$isMe ? 'test' : null);
}
/**
* @param UserInterface $user
* @return bool|null
* @deprecated 1.7 Not needed for Flex Users.
*/
protected function isAuthorizedSuperAdmin(UserInterface $user): ?bool
{
// Action authorization includes super user authorization if using Flex Users.
if ($user instanceof FlexObjectInterface) {
return null;
}
return $user->authorize('admin.super');
}
/**
* @param string $scope
* @param string $action
* @return string
*/
protected function getAuthorizeRule(string $scope, string $action): string
{
if ($this instanceof FlexDirectory) {
return $this->getAuthorizeRule($scope, $action);
}
return $this->getFlexDirectory()->getAuthorizeRule($scope, $action);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Traits/FlexRelationshipsTrait.php | system/src/Grav/Framework/Flex/Traits/FlexRelationshipsTrait.php | <?php declare(strict_types=1);
namespace Grav\Framework\Flex\Traits;
use Grav\Framework\Contracts\Relationships\RelationshipInterface;
use Grav\Framework\Contracts\Relationships\RelationshipsInterface;
use Grav\Framework\Flex\FlexIdentifier;
use Grav\Framework\Relationships\Relationships;
/**
* Trait FlexRelationshipsTrait
*/
trait FlexRelationshipsTrait
{
/** @var RelationshipsInterface|null */
private $_relationships = null;
/**
* @return Relationships
*/
public function getRelationships(): Relationships
{
if (!isset($this->_relationships)) {
$blueprint = $this->getBlueprint();
$options = $blueprint->get('config/relationships', []);
$parent = FlexIdentifier::createFromObject($this);
$this->_relationships = new Relationships($parent, $options);
}
return $this->_relationships;
}
/**
* @param string $name
* @return RelationshipInterface|null
*/
public function getRelationship(string $name): ?RelationshipInterface
{
return $this->getRelationships()[$name];
}
protected function resetRelationships(): void
{
$this->_relationships = null;
}
/**
* @param iterable $collection
* @return array
*/
protected function buildFlexIdentifierList(iterable $collection): array
{
$list = [];
foreach ($collection as $object) {
$list[] = FlexIdentifier::createFromObject($object);
}
return $list;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Traits/FlexMediaTrait.php | system/src/Grav/Framework/Flex/Traits/FlexMediaTrait.php | <?php
namespace Grav\Framework\Flex\Traits;
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
use Grav\Common\Config\Config;
use Grav\Common\Grav;
use Grav\Common\Media\Interfaces\MediaCollectionInterface;
use Grav\Common\Media\Interfaces\MediaUploadInterface;
use Grav\Common\Media\Traits\MediaTrait;
use Grav\Common\Page\Media;
use Grav\Common\Page\Medium\Medium;
use Grav\Common\Page\Medium\MediumFactory;
use Grav\Common\Utils;
use Grav\Framework\Cache\CacheInterface;
use Grav\Framework\Filesystem\Filesystem;
use Grav\Framework\Flex\FlexDirectory;
use Grav\Framework\Form\FormFlashFile;
use Grav\Framework\Media\Interfaces\MediaObjectInterface;
use Grav\Framework\Media\MediaObject;
use Grav\Framework\Media\UploadedMediaObject;
use Psr\Http\Message\UploadedFileInterface;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use function array_key_exists;
use function in_array;
use function is_array;
use function is_callable;
use function is_int;
use function is_string;
use function strpos;
/**
* Implements Grav Page content and header manipulation methods.
*/
trait FlexMediaTrait
{
use MediaTrait {
MediaTrait::getMedia as protected getExistingMedia;
}
/** @var array */
protected $_uploads = [];
/**
* @return string|null
*/
public function getStorageFolder()
{
return $this->exists() ? $this->getFlexDirectory()->getStorageFolder($this->getStorageKey()) : null;
}
/**
* @return string|null
*/
public function getMediaFolder()
{
return $this->exists() ? $this->getFlexDirectory()->getMediaFolder($this->getStorageKey()) : null;
}
/**
* @return MediaCollectionInterface
*/
public function getMedia()
{
$media = $this->media;
if (null === $media) {
$media = $this->getExistingMedia();
// Include uploaded media to the object media.
$this->addUpdatedMedia($media);
}
return $media;
}
/**
* @param string $field
* @return MediaCollectionInterface|null
*/
public function getMediaField(string $field): ?MediaCollectionInterface
{
// Field specific media.
$settings = $this->getFieldSettings($field);
if (!empty($settings['media_field'])) {
$var = 'destination';
} elseif (!empty($settings['media_picker_field'])) {
$var = 'folder';
}
if (empty($var)) {
// Not a media field.
$media = null;
} elseif ($settings['self']) {
// Uses main media.
$media = $this->getMedia();
} else {
// Uses custom media.
$media = new Media($settings[$var]);
$this->addUpdatedMedia($media);
}
return $media;
}
/**
* @param string $field
* @return array|null
*/
public function getFieldSettings(string $field): ?array
{
if ($field === '') {
return null;
}
// Load settings for the field.
$schema = $this->getBlueprint()->schema();
$settings = (array)$schema->getProperty($field);
if (!is_array($settings)) {
return null;
}
$type = $settings['type'] ?? '';
// Media field.
if (!empty($settings['media_field']) || array_key_exists('destination', $settings) || in_array($type, ['avatar', 'file', 'pagemedia'], true)) {
$settings['media_field'] = true;
$var = 'destination';
}
// Media picker field.
if (!empty($settings['media_picker_field']) || in_array($type, ['filepicker', 'pagemediaselect'], true)) {
$settings['media_picker_field'] = true;
$var = 'folder';
}
// Set media folder for media fields.
if (isset($var)) {
$folder = $settings[$var] ?? '';
if (in_array(rtrim($folder, '/'), ['', '@self', 'self@', '@self@'], true)) {
$settings[$var] = $this->getMediaFolder();
$settings['self'] = true;
} else {
$settings[$var] = Utils::getPathFromToken($folder, $this);
$settings['self'] = false;
}
}
return $settings;
}
/**
* @param string $field
* @return array
* @internal
*/
protected function getMediaFieldSettings(string $field): array
{
$settings = $this->getFieldSettings($field) ?? [];
return $settings + ['accept' => '*', 'limit' => 1000, 'self' => true];
}
/**
* @return array
*/
protected function getMediaFields(): array
{
// Load settings for the field.
$schema = $this->getBlueprint()->schema();
$list = [];
foreach ($schema->getState()['items'] as $field => $settings) {
if (isset($settings['type']) && (in_array($settings['type'], ['avatar', 'file', 'pagemedia']) || !empty($settings['destination']))) {
$list[] = $field;
}
}
return $list;
}
/**
* @param array|mixed $value
* @param array $settings
* @return array|mixed
*/
protected function parseFileProperty($value, array $settings = [])
{
if (!is_array($value)) {
return $value;
}
$media = $this->getMedia();
$originalMedia = is_callable([$this, 'getOriginalMedia']) ? $this->getOriginalMedia() : null;
$list = [];
foreach ($value as $filename => $info) {
if (!is_array($info)) {
$list[$filename] = $info;
continue;
}
if (is_int($filename)) {
$filename = $info['path'] ?? $info['name'];
}
/** @var Medium|null $imageFile */
$imageFile = $media[$filename];
/** @var Medium|null $originalFile */
$originalFile = $originalMedia ? $originalMedia[$filename] : null;
$url = $imageFile ? $imageFile->url() : null;
$originalUrl = $originalFile ? $originalFile->url() : null;
$list[$filename] = [
'name' => $info['name'] ?? null,
'type' => $info['type'] ?? null,
'size' => $info['size'] ?? null,
'path' => $filename,
'thumb_url' => $url,
'image_url' => $originalUrl ?? $url
];
if ($originalFile) {
$list[$filename]['cropData'] = (object)($originalFile->metadata()['upload']['crop'] ?? []);
}
}
return $list;
}
/**
* @param UploadedFileInterface $uploadedFile
* @param string|null $filename
* @param string|null $field
* @return void
* @internal
*/
public function checkUploadedMediaFile(UploadedFileInterface $uploadedFile, string $filename = null, string $field = null)
{
$media = $this->getMedia();
if (!$media instanceof MediaUploadInterface) {
throw new RuntimeException("Media for {$this->getFlexDirectory()->getFlexType()} doesn't support file uploads.");
}
$media->checkUploadedFile($uploadedFile, $filename, $this->getMediaFieldSettings($field ?? ''));
}
/**
* @param UploadedFileInterface $uploadedFile
* @param string|null $filename
* @param string|null $field
* @return void
* @internal
*/
public function uploadMediaFile(UploadedFileInterface $uploadedFile, string $filename = null, string $field = null): void
{
$settings = $this->getMediaFieldSettings($field ?? '');
$media = $field ? $this->getMediaField($field) : $this->getMedia();
if (!$media instanceof MediaUploadInterface) {
throw new RuntimeException("Media for {$this->getFlexDirectory()->getFlexType()} doesn't support file uploads.");
}
$filename = $media->checkUploadedFile($uploadedFile, $filename, $settings);
$media->copyUploadedFile($uploadedFile, $filename, $settings);
$this->clearMediaCache();
}
/**
* @param string $filename
* @return void
* @internal
*/
public function deleteMediaFile(string $filename): void
{
$media = $this->getMedia();
if (!$media instanceof MediaUploadInterface) {
throw new RuntimeException("Media for {$this->getFlexDirectory()->getFlexType()} doesn't support file uploads.");
}
$media->deleteFile($filename);
$this->clearMediaCache();
}
/**
* @return array
*/
#[\ReturnTypeWillChange]
public function __debugInfo()
{
return parent::__debugInfo() + [
'uploads:private' => $this->getUpdatedMedia()
];
}
/**
* @param string|null $field
* @param string $filename
* @param MediaObjectInterface|null $image
* @return MediaObject|UploadedMediaObject
*/
protected function buildMediaObject(?string $field, string $filename, MediaObjectInterface $image = null)
{
if (!$image) {
$media = $field ? $this->getMediaField($field) : null;
if ($media) {
$image = $media[$filename];
}
}
return new MediaObject($field, $filename, $image, $this);
}
/**
* @param string|null $field
* @return array
*/
protected function buildMediaList(?string $field): array
{
$names = $field ? (array)$this->getNestedProperty($field) : [];
$media = $field ? $this->getMediaField($field) : null;
if (null === $media) {
$media = $this->getMedia();
}
$list = [];
foreach ($names as $key => $val) {
$name = is_string($val) ? $val : $key;
$medium = $media[$name];
if ($medium) {
if ($medium->uploaded_file) {
$upload = $medium->uploaded_file;
$id = $upload instanceof FormFlashFile ? $upload->getId() : "{$field}-{$name}";
$list[] = new UploadedMediaObject($id, $field, $name, $upload);
} else {
$list[] = $this->buildMediaObject($field, $name, $medium);
}
}
}
return $list;
}
/**
* @param array $files
* @return void
*/
protected function setUpdatedMedia(array $files): void
{
$media = $this->getMedia();
if (!$media instanceof MediaUploadInterface) {
return;
}
$filesystem = Filesystem::getInstance(false);
$list = [];
foreach ($files as $field => $group) {
$field = (string)$field;
// Ignore files without a field and resized images.
if ($field === '' || strpos($field, '/')) {
continue;
}
// Load settings for the field.
$settings = $this->getMediaFieldSettings($field);
foreach ($group as $filename => $file) {
if ($file) {
// File upload.
$filename = $file->getClientFilename();
/** @var FormFlashFile $file */
$data = $file->jsonSerialize();
unset($data['tmp_name'], $data['path']);
} else {
// File delete.
$data = null;
}
if ($file) {
// Check file upload against media limits (except for max size).
$filename = $media->checkUploadedFile($file, $filename, ['filesize' => 0] + $settings);
}
$self = $settings['self'];
if ($this->_loadMedia && $self) {
$filepath = $filename;
} else {
$filepath = "{$settings['destination']}/{$filename}";
}
// Calculate path without the retina scaling factor.
$realpath = $filesystem->pathname($filepath) . str_replace(['@3x', '@2x'], '', Utils::basename($filepath));
$list[$filename] = [$file, $settings];
$path = str_replace('.', "\n", $field);
if (null !== $data) {
$data['name'] = $filename;
$data['path'] = $filepath;
$this->setNestedProperty("{$path}\n{$realpath}", $data, "\n");
} else {
$this->unsetNestedProperty("{$path}\n{$realpath}", "\n");
}
}
}
$this->clearMediaCache();
$this->_uploads = $list;
}
/**
* @param MediaCollectionInterface $media
*/
protected function addUpdatedMedia(MediaCollectionInterface $media): void
{
$updated = false;
foreach ($this->getUpdatedMedia() as $filename => $upload) {
if (is_array($upload)) {
/** @var array{UploadedFileInterface,array} $upload */
$settings = $upload[1];
if (isset($settings['destination']) && $settings['destination'] === $media->getPath()) {
$upload = $upload[0];
} else {
$upload = false;
}
}
if (false !== $upload) {
$medium = $upload ? MediumFactory::fromUploadedFile($upload) : null;
$updated = true;
if ($medium) {
$medium->uploaded = true;
$medium->uploaded_file = $upload;
$media->add($filename, $medium);
} elseif (is_callable([$media, 'hide'])) {
$media->hide($filename);
}
}
}
if ($updated) {
$media->setTimestamps();
}
}
/**
* @return array<string,UploadedFileInterface|array|null>
*/
protected function getUpdatedMedia(): array
{
return $this->_uploads;
}
/**
* @return void
*/
protected function saveUpdatedMedia(): void
{
$media = $this->getMedia();
if (!$media instanceof MediaUploadInterface) {
return;
}
// Upload/delete altered files.
/**
* @var string $filename
* @var UploadedFileInterface|array|null $file
*/
foreach ($this->getUpdatedMedia() as $filename => $file) {
if (is_array($file)) {
[$file, $settings] = $file;
} else {
$settings = null;
}
if ($file instanceof UploadedFileInterface) {
$media->copyUploadedFile($file, $filename, $settings);
} else {
$media->deleteFile($filename, $settings);
}
}
$this->setUpdatedMedia([]);
$this->clearMediaCache();
}
/**
* @return void
*/
protected function freeMedia(): void
{
$this->unsetObjectProperty('media');
}
/**
* @param string $uri
* @return Medium|null
*/
protected function createMedium($uri)
{
$grav = Grav::instance();
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
$file = $uri && $locator->isStream($uri) ? $locator->findResource($uri) : $uri;
return is_string($file) && file_exists($file) ? MediumFactory::fromFile($file) : null;
}
/**
* @return CacheInterface
*/
protected function getMediaCache()
{
return $this->getCache('object');
}
/**
* @return MediaCollectionInterface
*/
protected function offsetLoad_media()
{
return $this->getMedia();
}
/**
* @return null
*/
protected function offsetSerialize_media()
{
return null;
}
/**
* @return FlexDirectory
*/
abstract public function getFlexDirectory(): FlexDirectory;
/**
* @return string
*/
abstract public function getStorageKey(): string;
/**
* @param string $filename
* @return void
* @deprecated 1.7 Use Media class that implements MediaUploadInterface instead.
*/
public function checkMediaFilename(string $filename)
{
user_error(__METHOD__ . '() is deprecated since Grav 1.7, use Media class that implements MediaUploadInterface instead', E_USER_DEPRECATED);
// Check the file extension.
$extension = strtolower(Utils::pathinfo($filename, PATHINFO_EXTENSION));
$grav = Grav::instance();
/** @var Config $config */
$config = $grav['config'];
// If not a supported type, return
if (!$extension || !$config->get("media.types.{$extension}")) {
$language = $grav['language'];
throw new RuntimeException($language->translate('PLUGIN_ADMIN.UNSUPPORTED_FILE_TYPE') . ': ' . $extension, 400);
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Pages/FlexPageCollection.php | system/src/Grav/Framework/Flex/Pages/FlexPageCollection.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Pages;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Framework\Flex\FlexCollection;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
use function array_search;
use function assert;
use function is_int;
/**
* Class FlexPageCollection
* @package Grav\Plugin\FlexObjects\Types\FlexPages
* @template T of FlexObjectInterface
* @extends FlexCollection<T>
*/
class FlexPageCollection extends FlexCollection
{
/**
* @return array
*/
public static function getCachedMethods(): array
{
return [
// Collection filtering
'withPublished' => true,
'withVisible' => true,
'withRoutable' => true,
'isFirst' => true,
'isLast' => true,
// Find objects
'prevSibling' => false,
'nextSibling' => false,
'adjacentSibling' => false,
'currentPosition' => true,
'getNextOrder' => false,
] + parent::getCachedMethods();
}
/**
* @param bool $bool
* @return static
* @phpstan-return static<T>
*/
public function withPublished(bool $bool = true)
{
/** @var string[] $list */
$list = array_keys(array_filter($this->call('isPublished', [$bool])));
/** @phpstan-var static<T> */
return $this->select($list);
}
/**
* @param bool $bool
* @return static
* @phpstan-return static<T>
*/
public function withVisible(bool $bool = true)
{
/** @var string[] $list */
$list = array_keys(array_filter($this->call('isVisible', [$bool])));
/** @phpstan-var static<T> */
return $this->select($list);
}
/**
* @param bool $bool
* @return static
* @phpstan-return static<T>
*/
public function withRoutable(bool $bool = true)
{
/** @var string[] $list */
$list = array_keys(array_filter($this->call('isRoutable', [$bool])));
/** @phpstan-var static<T> */
return $this->select($list);
}
/**
* Check to see if this item is the first in the collection.
*
* @param string $path
* @return bool True if item is first.
*/
public function isFirst($path): bool
{
$keys = $this->getKeys();
$first = reset($keys);
return $path === $first;
}
/**
* Check to see if this item is the last in the collection.
*
* @param string $path
* @return bool True if item is last.
*/
public function isLast($path): bool
{
$keys = $this->getKeys();
$last = end($keys);
return $path === $last;
}
/**
* Gets the previous sibling based on current position.
*
* @param string $path
* @return PageInterface|false The previous item.
* @phpstan-return T|false
*/
public function prevSibling($path)
{
return $this->adjacentSibling($path, -1);
}
/**
* Gets the next sibling based on current position.
*
* @param string $path
* @return PageInterface|false The next item.
* @phpstan-return T|false
*/
public function nextSibling($path)
{
return $this->adjacentSibling($path, 1);
}
/**
* Returns the adjacent sibling based on a direction.
*
* @param string $path
* @param int $direction either -1 or +1
* @return PageInterface|false The sibling item.
* @phpstan-return T|false
*/
public function adjacentSibling($path, $direction = 1)
{
$keys = $this->getKeys();
$direction = (int)$direction;
$pos = array_search($path, $keys, true);
if (is_int($pos)) {
$pos += $direction;
if (isset($keys[$pos])) {
return $this[$keys[$pos]];
}
}
return false;
}
/**
* Returns the item in the current position.
*
* @param string $path the path the item
* @return int|null The index of the current page, null if not found.
*/
public function currentPosition($path): ?int
{
$pos = array_search($path, $this->getKeys(), true);
return is_int($pos) ? $pos : null;
}
/**
* @return string
*/
public function getNextOrder()
{
$directory = $this->getFlexDirectory();
$collection = $directory->getIndex();
$keys = $collection->getStorageKeys();
// Assign next free order.
$last = null;
$order = 0;
foreach ($keys as $folder => $key) {
preg_match(FlexPageIndex::ORDER_PREFIX_REGEX, $folder, $test);
$test = $test[0] ?? null;
if ($test && $test > $order) {
$order = $test;
$last = $key;
}
}
/** @var FlexPageObject|null $last */
$last = $collection[$last];
return sprintf('%d.', $last ? $last->getFormValue('order') + 1 : 1);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Pages/FlexPageIndex.php | system/src/Grav/Framework/Flex/Pages/FlexPageIndex.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Pages;
use Grav\Common\Grav;
use Grav\Framework\Flex\FlexIndex;
/**
* Class FlexPageObject
* @package Grav\Plugin\FlexObjects\Types\FlexPages
*
* @method FlexPageIndex withRoutable(bool $bool = true)
* @method FlexPageIndex withPublished(bool $bool = true)
* @method FlexPageIndex withVisible(bool $bool = true)
*
* @template T of FlexPageObject
* @template C of FlexPageCollection
* @extends FlexIndex<T,C>
*/
class FlexPageIndex extends FlexIndex
{
public const ORDER_PREFIX_REGEX = '/^\d+\./u';
/**
* @param string $route
* @return string
* @internal
*/
public static function normalizeRoute(string $route)
{
static $case_insensitive;
if (null === $case_insensitive) {
$case_insensitive = Grav::instance()['config']->get('system.force_lowercase_urls', false);
}
return $case_insensitive ? mb_strtolower($route) : $route;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Pages/FlexPageObject.php | system/src/Grav/Framework/Flex/Pages/FlexPageObject.php | <?php
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Pages;
use DateTime;
use Exception;
use Grav\Common\Debugger;
use Grav\Common\Grav;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Page\Traits\PageFormTrait;
use Grav\Common\User\Interfaces\UserCollectionInterface;
use Grav\Framework\Flex\FlexObject;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
use Grav\Framework\Flex\Interfaces\FlexTranslateInterface;
use Grav\Framework\Flex\Pages\Traits\PageAuthorsTrait;
use Grav\Framework\Flex\Pages\Traits\PageContentTrait;
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 array_key_exists;
use function is_array;
/**
* Class FlexPageObject
* @package Grav\Plugin\FlexObjects\Types\FlexPages
*/
class FlexPageObject extends FlexObject implements PageInterface, FlexTranslateInterface
{
use PageAuthorsTrait;
use PageContentTrait;
use PageFormTrait;
use PageLegacyTrait;
use PageRoutableTrait;
use PageTranslateTrait;
use FlexMediaTrait;
public const PAGE_ORDER_REGEX = '/^(\d+)\.(.*)$/u';
public const PAGE_ORDER_PREFIX_REGEX = '/^[0-9]+\./u';
/** @var array|null */
protected $_reorder;
/** @var FlexPageObject|null */
protected $_originalObject;
/**
* Clone page.
*/
#[\ReturnTypeWillChange]
public function __clone()
{
parent::__clone();
if (isset($this->header)) {
$this->header = clone($this->header);
}
}
/**
* @return array
*/
public static function getCachedMethods(): array
{
return [
// Page Content Interface
'header' => false,
'summary' => true,
'content' => true,
'value' => false,
'media' => false,
'title' => true,
'menu' => true,
'visible' => true,
'published' => true,
'publishDate' => true,
'unpublishDate' => true,
'process' => true,
'slug' => true,
'order' => true,
'id' => true,
'modified' => true,
'lastModified' => true,
'folder' => true,
'date' => true,
'dateformat' => true,
'taxonomy' => true,
'shouldProcess' => true,
'isPage' => true,
'isDir' => true,
'folderExists' => true,
// Page
'isPublished' => true,
'isOrdered' => true,
'isVisible' => true,
'isRoutable' => true,
'getCreated_Timestamp' => true,
'getPublish_Timestamp' => true,
'getUnpublish_Timestamp' => true,
'getUpdated_Timestamp' => true,
] + parent::getCachedMethods();
}
/**
* @param bool $test
* @return bool
*/
public function isPublished(bool $test = true): bool
{
$time = time();
$start = $this->getPublish_Timestamp();
$stop = $this->getUnpublish_Timestamp();
return $this->published() && $start <= $time && (!$stop || $time <= $stop) === $test;
}
/**
* @param bool $test
* @return bool
*/
public function isOrdered(bool $test = true): bool
{
return ($this->order() !== false) === $test;
}
/**
* @param bool $test
* @return bool
*/
public function isVisible(bool $test = true): bool
{
return $this->visible() === $test;
}
/**
* @param bool $test
* @return bool
*/
public function isRoutable(bool $test = true): bool
{
return $this->routable() === $test;
}
/**
* @return int
*/
public function getCreated_Timestamp(): int
{
return $this->getFieldTimestamp('created_date') ?? 0;
}
/**
* @return int
*/
public function getPublish_Timestamp(): int
{
return $this->getFieldTimestamp('publish_date') ?? $this->getCreated_Timestamp();
}
/**
* @return int|null
*/
public function getUnpublish_Timestamp(): ?int
{
return $this->getFieldTimestamp('unpublish_date');
}
/**
* @return int
*/
public function getUpdated_Timestamp(): int
{
return $this->getFieldTimestamp('updated_date') ?? $this->getPublish_Timestamp();
}
/**
* @inheritdoc
*/
public function getFormValue(string $name, $default = null, string $separator = null)
{
$test = new stdClass();
$value = $this->pageContentValue($name, $test);
if ($value !== $test) {
return $value;
}
switch ($name) {
case 'name':
return $this->getProperty('template');
case 'route':
return $this->hasKey() ? '/' . $this->getKey() : null;
case 'header.permissions.groups':
$encoded = json_encode($this->getPermissions());
if ($encoded === false) {
throw new RuntimeException('json_encode(): failed to encode group permissions');
}
return json_decode($encoded, true);
}
return parent::getFormValue($name, $default, $separator);
}
/**
* Get master storage key.
*
* @return string
* @see FlexObjectInterface::getStorageKey()
*/
public function getMasterKey(): string
{
$key = (string)($this->storage_key ?? $this->getMetaData()['storage_key'] ?? null);
if (($pos = strpos($key, '|')) !== false) {
$key = substr($key, 0, $pos);
}
return $key;
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::getCacheKey()
*/
public function getCacheKey(): string
{
return $this->hasKey() ? $this->getTypePrefix() . $this->getFlexType() . '.' . $this->getKey() . '.' . $this->getLanguage() : '';
}
/**
* @param string|null $key
* @return FlexObjectInterface
*/
public function createCopy(string $key = null)
{
$this->copy();
return parent::createCopy($key);
}
/**
* @param array|bool $reorder
* @return FlexObject|FlexObjectInterface
*/
public function save($reorder = true)
{
return parent::save();
}
/**
* Gets the Page Unmodified (original) version of the page.
*
* Assumes that object has been cloned before modifying it.
*
* @return FlexPageObject|null The original version of the page.
*/
public function getOriginal()
{
return $this->_originalObject;
}
/**
* Store the Page Unmodified (original) version of the page.
*
* Can be called multiple times, only the first call matters.
*
* @return void
*/
public function storeOriginal(): void
{
if (null === $this->_originalObject) {
$this->_originalObject = clone $this;
}
}
/**
* Get display order for the associated media.
*
* @return array
*/
public function getMediaOrder(): array
{
$order = $this->getNestedProperty('header.media_order');
if (is_array($order)) {
return $order;
}
if (!$order) {
return [];
}
return array_map('trim', explode(',', $order));
}
// Overrides for header properties.
/**
* Common logic to load header properties.
*
* @param string $property
* @param mixed $var
* @param callable $filter
* @return mixed|null
*/
protected function loadHeaderProperty(string $property, $var, callable $filter)
{
// We have to use parent methods in order to avoid loops.
$value = null === $var ? parent::getProperty($property) : null;
if (null === $value) {
$value = $filter($var ?? $this->getProperty('header')->get($property));
parent::setProperty($property, $value);
if ($this->doHasProperty($property)) {
$value = parent::getProperty($property);
}
}
return $value;
}
/**
* Common logic to load header properties.
*
* @param string $property
* @param mixed $var
* @param callable $filter
* @return mixed|null
*/
protected function loadProperty(string $property, $var, callable $filter)
{
// We have to use parent methods in order to avoid loops.
$value = null === $var ? parent::getProperty($property) : null;
if (null === $value) {
$value = $filter($var);
parent::setProperty($property, $value);
if ($this->doHasProperty($property)) {
$value = parent::getProperty($property);
}
}
return $value;
}
/**
* @param string $property
* @param mixed $default
* @return mixed
*/
public function getProperty($property, $default = null)
{
$method = static::$headerProperties[$property] ?? static::$calculatedProperties[$property] ?? null;
if ($method && method_exists($this, $method)) {
return $this->{$method}();
}
return parent::getProperty($property, $default);
}
/**
* @param string $property
* @param mixed $value
* @return $this
*/
public function setProperty($property, $value)
{
$method = static::$headerProperties[$property] ?? static::$calculatedProperties[$property] ?? null;
if ($method && method_exists($this, $method)) {
$this->{$method}($value);
return $this;
}
parent::setProperty($property, $value);
return $this;
}
/**
* @param string $property
* @param mixed $value
* @param string|null $separator
* @return $this
*/
public function setNestedProperty($property, $value, $separator = null)
{
$separator = $separator ?: '.';
if (strpos($property, 'header' . $separator) === 0) {
$this->getProperty('header')->set(str_replace('header' . $separator, '', $property), $value, $separator);
return $this;
}
parent::setNestedProperty($property, $value, $separator);
return $this;
}
/**
* @param string $property
* @param string|null $separator
* @return $this
*/
public function unsetNestedProperty($property, $separator = null)
{
$separator = $separator ?: '.';
if (strpos($property, 'header' . $separator) === 0) {
$this->getProperty('header')->undef(str_replace('header' . $separator, '', $property), $separator);
return $this;
}
parent::unsetNestedProperty($property, $separator);
return $this;
}
/**
* @param array $elements
* @param bool $extended
* @return void
*/
protected function filterElements(array &$elements, bool $extended = false): void
{
// Markdown storage conversion to page structure.
if (array_key_exists('content', $elements)) {
$elements['markdown'] = $elements['content'];
unset($elements['content']);
}
if (!$extended) {
$folder = !empty($elements['folder']) ? trim($elements['folder']) : '';
if ($folder) {
$order = !empty($elements['order']) ? (int)$elements['order'] : null;
// TODO: broken
$elements['storage_key'] = $order ? sprintf('%02d.%s', $order, $folder) : $folder;
}
}
parent::filterElements($elements);
}
/**
* @param string $field
* @return int|null
*/
protected function getFieldTimestamp(string $field): ?int
{
$date = $this->getFieldDateTime($field);
return $date ? $date->getTimestamp() : null;
}
/**
* @param string $field
* @return DateTime|null
*/
protected function getFieldDateTime(string $field): ?DateTime
{
try {
$value = $this->getProperty($field);
if (is_numeric($value)) {
$value = '@' . $value;
}
$date = $value ? new DateTime($value) : null;
} catch (Exception $e) {
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$debugger->addException($e);
$date = null;
}
return $date;
}
/**
* @return UserCollectionInterface|null
* @internal
*/
protected function loadAccounts()
{
return Grav::instance()['accounts'] ?? null;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Pages/Traits/PageRoutableTrait.php | system/src/Grav/Framework/Flex/Pages/Traits/PageRoutableTrait.php | <?php
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Pages\Traits;
use Grav\Common\Config\Config;
use Grav\Common\Grav;
use Grav\Common\Page\Interfaces\PageCollectionInterface;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Page\Pages;
use Grav\Common\Uri;
use Grav\Common\Utils;
use Grav\Framework\Filesystem\Filesystem;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use function is_string;
/**
* Implements PageRoutableInterface
*/
trait PageRoutableTrait
{
/** @var bool */
protected $root = false;
/** @var string|null */
private $_route;
/** @var string|null */
private $_path;
/** @var PageInterface|null */
private $_parentCache;
/**
* Returns the page extension, got from the page `url_extension` config and falls back to the
* system config `system.pages.append_url_extension`.
*
* @return string The extension of this page. For example `.html`
*/
public function urlExtension(): string
{
return $this->loadHeaderProperty(
'url_extension',
null,
function ($value) {
if ($this->home()) {
return '';
}
return $value ?? Grav::instance()['config']->get('system.pages.append_url_extension', '');
}
);
}
/**
* 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|null $var true if the page is routable
* @return bool true if the page is routable
*/
public function routable($var = null): bool
{
$value = $this->loadHeaderProperty(
'routable',
$var,
static function ($value) {
return $value ?? true;
}
);
return $value && $this->published() && !$this->isModule() && !$this->root() && $this->getLanguages(true);
}
/**
* Gets the URL for a page - alias of url().
*
* @param bool $include_host
* @return string the permalink
*/
public function link($include_host = false): string
{
return $this->url($include_host);
}
/**
* Gets the URL with host information, aka Permalink.
* @return string The permalink.
*/
public function permalink(): string
{
return $this->url(true, false, true, true);
}
/**
* Returns the canonical URL for a page
*
* @param bool $include_lang
* @return string
*/
public function canonical($include_lang = true): string
{
return $this->url(true, true, $include_lang);
}
/**
* Gets the url for the Page.
*
* @param bool $include_host Defaults false, but true would include http://yourhost.com
* @param bool $canonical true to return the canonical URL
* @param bool $include_base
* @param bool $raw_route
* @return string The url.
*/
public function url($include_host = false, $canonical = false, $include_base = true, $raw_route = false): string
{
// Override any URL when external_url is set
$external = $this->getNestedProperty('header.external_url');
if ($external) {
return $external;
}
$grav = Grav::instance();
/** @var Pages $pages */
$pages = $grav['pages'];
/** @var Config $config */
$config = $grav['config'];
// get base route (multi-site base and language)
$route = $include_base ? $pages->baseRoute() : '';
// add full route if configured to do so
if (!$include_host && $config->get('system.absolute_urls', false)) {
$include_host = true;
}
if ($canonical) {
$route .= $this->routeCanonical();
} elseif ($raw_route) {
$route .= $this->rawRoute();
} else {
$route .= $this->route();
}
/** @var Uri $uri */
$uri = $grav['uri'];
$url = $uri->rootUrl($include_host) . '/' . trim($route, '/') . $this->urlExtension();
return Uri::filterPath($url);
}
/**
* Gets the route for the page based on the route headers if available, else from
* the parents route and the current Page's slug.
*
* @param string $var Set new default route.
* @return string|null The route for the Page.
*/
public function route($var = null): ?string
{
if (null !== $var) {
// TODO: not the best approach, but works...
$this->setNestedProperty('header.routes.default', $var);
}
// Return default route if given.
$default = $this->getNestedProperty('header.routes.default');
if (is_string($default)) {
return $default;
}
return $this->routeInternal();
}
/**
* @return string|null
*/
protected function routeInternal(): ?string
{
$route = $this->_route;
if (null !== $route) {
return $route;
}
if ($this->root()) {
return null;
}
// Root and orphan nodes have no route.
$parent = $this->parent();
if (!$parent) {
return null;
}
if ($parent->home()) {
/** @var Config $config */
$config = Grav::instance()['config'];
$hide = (bool)$config->get('system.home.hide_in_urls', false);
$route = '/' . ($hide ? '' : $parent->slug());
} else {
$route = $parent->route();
}
if ($route !== '' && $route !== '/') {
$route .= '/';
}
if (!$this->home()) {
$route .= $this->slug();
}
$this->_route = $route;
return $route;
}
/**
* Helper method to clear the route out so it regenerates next time you use it
*/
public function unsetRouteSlug(): void
{
// TODO:
throw new RuntimeException(__METHOD__ . '(): Not Implemented');
}
/**
* Gets and Sets the page raw route
*
* @param string|null $var
* @return string|null
*/
public function rawRoute($var = null): ?string
{
if (null !== $var) {
// TODO:
throw new RuntimeException(__METHOD__ . '(string): Not Implemented');
}
if ($this->root()) {
return null;
}
return '/' . $this->getKey();
}
/**
* Gets the route aliases for the page based on page headers.
*
* @param array|null $var list of route aliases
* @return array The route aliases for the Page.
*/
public function routeAliases($var = null): array
{
if (null !== $var) {
$this->setNestedProperty('header.routes.aliases', (array)$var);
}
$aliases = (array)$this->getNestedProperty('header.routes.aliases');
$default = $this->getNestedProperty('header.routes.default');
if ($default) {
$aliases[] = $default;
}
return $aliases;
}
/**
* Gets the canonical route for this page if its set. If provided it will use
* that value, else if it's `true` it will use the default route.
*
* @param string|null $var
* @return string|null
*/
public function routeCanonical($var = null): ?string
{
if (null !== $var) {
$this->setNestedProperty('header.routes.canonical', (array)$var);
}
$canonical = $this->getNestedProperty('header.routes.canonical');
return is_string($canonical) ? $canonical : $this->route();
}
/**
* Gets the redirect set in the header.
*
* @param string|null $var redirect url
* @return string|null
*/
public function redirect($var = null): ?string
{
return $this->loadHeaderProperty(
'redirect',
$var,
static function ($value) {
return trim($value) ?: null;
}
);
}
/**
* Returns the clean path to the page file
*
* Needed in admin for Page Media.
*/
public function relativePagePath(): ?string
{
$folder = $this->getMediaFolder();
if (!$folder) {
return null;
}
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$path = $locator->isStream($folder) ? $locator->findResource($folder, false) : $folder;
return is_string($path) ? $path : null;
}
/**
* Gets and sets the path to the folder where the .md for this Page object resides.
* This is equivalent to the filePath but without the filename.
*
* @param string|null $var the path
* @return string|null the path
*/
public function path($var = null): ?string
{
if (null !== $var) {
// TODO:
throw new RuntimeException(__METHOD__ . '(string): Not Implemented');
}
$path = $this->_path;
if ($path) {
return $path;
}
if ($this->root()) {
$folder = $this->getFlexDirectory()->getStorageFolder();
} else {
$folder = $this->getStorageFolder();
}
if ($folder) {
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$folder = $locator->isStream($folder) ? $locator->getResource($folder) : GRAV_ROOT . "/{$folder}";
}
return $this->_path = is_string($folder) ? $folder : null;
}
/**
* Get/set the folder.
*
* @param string|null $var Optional path, including numeric prefix.
* @return string|null
*/
public function folder($var = null): ?string
{
return $this->loadProperty(
'folder',
$var,
function ($value) {
if (null === $value) {
$value = $this->getMasterKey() ?: $this->getKey();
}
return Utils::basename($value) ?: null;
}
);
}
/**
* Get/set the folder.
*
* @param string|null $var Optional path, including numeric prefix.
* @return string|null
*/
public function parentStorageKey($var = null): ?string
{
return $this->loadProperty(
'parent_key',
$var,
function ($value) {
if (null === $value) {
$filesystem = Filesystem::getInstance(false);
$value = $this->getMasterKey() ?: $this->getKey();
$value = ltrim($filesystem->dirname("/{$value}"), '/') ?: '';
}
return $value;
}
);
}
/**
* Gets and Sets the parent object for this page
*
* @param PageInterface|null $var the parent page object
* @return PageInterface|null the parent page object if it exists.
*/
public function parent(PageInterface $var = null)
{
if (null !== $var) {
// TODO:
throw new RuntimeException(__METHOD__ . '(PageInterface): Not Implemented');
}
if ($this->_parentCache || $this->root()) {
return $this->_parentCache;
}
// Use filesystem as \dirname() does not work in Windows because of '/foo' becomes '\'.
$filesystem = Filesystem::getInstance(false);
$directory = $this->getFlexDirectory();
$parentKey = ltrim($filesystem->dirname("/{$this->getKey()}"), '/');
if ('' !== $parentKey) {
$parent = $directory->getObject($parentKey);
$language = $this->getLanguage();
if ($language && $parent && method_exists($parent, 'getTranslation')) {
$parent = $parent->getTranslation($language) ?? $parent;
}
$this->_parentCache = $parent;
} else {
$index = $directory->getIndex();
$this->_parentCache = \is_callable([$index, 'getRoot']) ? $index->getRoot() : null;
}
return $this->_parentCache;
}
/**
* Gets the top parent object for this page. Can return page itself.
*
* @return PageInterface The top parent page object.
*/
public function topParent()
{
$topParent = $this;
while ($topParent) {
$parent = $topParent->parent();
if (!$parent || !$parent->parent()) {
break;
}
$topParent = $parent;
}
return $topParent;
}
/**
* Returns the item in the current position.
*
* @return int|null the index of the current page.
*/
public function currentPosition(): ?int
{
$parent = $this->parent();
$collection = $parent ? $parent->collection('content', false) : null;
if ($collection instanceof PageCollectionInterface && $path = $this->path()) {
return $collection->currentPosition($path);
}
return 1;
}
/**
* Returns whether or not this page is the currently active page requested via the URL.
*
* @return bool True if it is active
*/
public function active(): bool
{
$grav = Grav::instance();
$uri_path = rtrim(urldecode($grav['uri']->path()), '/') ?: '/';
$routes = $grav['pages']->routes();
return isset($routes[$uri_path]) && $routes[$uri_path] === $this->path();
}
/**
* Returns whether or not this URI's URL contains the URL of the active page.
* Or in other words, is this page's URL in the current URL
*
* @return bool True if active child exists
*/
public function activeChild(): bool
{
$grav = Grav::instance();
/** @var Uri $uri */
$uri = $grav['uri'];
/** @var Pages $pages */
$pages = $grav['pages'];
$uri_path = rtrim(urldecode($uri->path()), '/');
$routes = $pages->routes();
if (isset($routes[$uri_path])) {
$page = $pages->find($uri->route());
/** @var PageInterface|null $child_page */
$child_page = $page ? $page->parent() : null;
while ($child_page && !$child_page->root()) {
if ($this->path() === $child_page->path()) {
return true;
}
$child_page = $child_page->parent();
}
}
return false;
}
/**
* Returns whether or not this page is the currently configured home page.
*
* @return bool True if it is the homepage
*/
public function home(): bool
{
$home = Grav::instance()['config']->get('system.home.alias');
return '/' . $this->getKey() === $home;
}
/**
* Returns whether or not this page is the root node of the pages tree.
*
* @param bool|null $var
* @return bool True if it is the root
*/
public function root($var = null): bool
{
if (null !== $var) {
$this->root = (bool)$var;
}
return $this->root === true || $this->getKey() === '/';
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Pages/Traits/PageAuthorsTrait.php | system/src/Grav/Framework/Flex/Pages/Traits/PageAuthorsTrait.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
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
* @package Grav\Framework\Flex\Pages\Traits
*/
trait PageAuthorsTrait
{
/** @var array<int,UserInterface> */
private $_authors;
/** @var array|null */
private $_permissionsCache;
/**
* Returns true if object has the named author.
*
* @param string $username
* @return bool
*/
public function hasAuthor(string $username): bool
{
$authors = (array)$this->getNestedProperty('header.permissions.authors');
if (empty($authors)) {
return false;
}
foreach ($authors as $author) {
if ($username === $author) {
return true;
}
}
return false;
}
/**
* Get list of all author objects.
*
* @return array<int,UserInterface>
*/
public function getAuthors(): array
{
if (null === $this->_authors) {
$this->_authors = $this->loadAuthors($this->getNestedProperty('header.permissions.authors', []));
}
return $this->_authors;
}
/**
* @param bool $inherit
* @return array
*/
public function getPermissions(bool $inherit = false)
{
if (null === $this->_permissionsCache) {
$permissions = [];
if ($inherit && $this->getNestedProperty('header.permissions.inherit', true)) {
$parent = $this->parent();
if ($parent && method_exists($parent, 'getPermissions')) {
$permissions = $parent->getPermissions($inherit);
}
}
$this->_permissionsCache = $this->loadPermissions($permissions);
}
return $this->_permissionsCache;
}
/**
* @param iterable $authors
* @return array<int,UserInterface>
*/
protected function loadAuthors(iterable $authors): array
{
$accounts = $this->loadAccounts();
if (null === $accounts || empty($authors)) {
return [];
}
$list = [];
foreach ($authors as $username) {
if (!is_string($username)) {
throw new InvalidArgumentException('Iterable should return username (string).', 500);
}
$list[] = $accounts->load($username);
}
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();
$isMe = null === $user;
if ($isMe) {
$user = $this->getActiveUser();
}
if (null === $user) {
return false;
}
return $this->isAuthorizedByGroup($user, $action, $scope, $isMe, $isAuthor);
}
/**
* @param UserInterface $user
* @param string $action
* @param string $scope
* @param bool $isMe
* @return bool|null
*/
protected function isAuthorizedOverride(UserInterface $user, string $action, string $scope, bool $isMe): ?bool
{
if ($action === 'delete' && $this->root()) {
// Do not allow deleting root.
return false;
}
$isAuthor = !$isMe || $user->authorized ? $this->hasAuthor($user->username) : false;
return $this->isAuthorizedByGroup($user, $action, $scope, $isMe, $isAuthor) ?? parent::isAuthorizedOverride($user, $action, $scope, $isMe);
}
/**
* Group authorization works as follows:
*
* 1. if any of the groups deny access, return false
* 2. else if any of the groups allow access, return true
* 3. else return null
*
* @param UserInterface $user
* @param string $action
* @param string $scope
* @param bool $isMe
* @param bool $isAuthor
* @return bool|null
*/
protected function isAuthorizedByGroup(UserInterface $user, string $action, string $scope, bool $isMe, bool $isAuthor): ?bool
{
$authorized = null;
// In admin we want to check against group permissions.
$pageGroups = $this->getPermissions();
$userGroups = (array)$user->groups;
/** @var Access $access */
foreach ($pageGroups as $group => $access) {
if ($group === 'defaults') {
// Special defaults permissions group does not apply to guest.
if ($isMe && !$user->authorized) {
continue;
}
} elseif ($group === 'authors') {
if (!$isAuthor) {
continue;
}
} elseif (!in_array($group, $userGroups, true)) {
continue;
}
$auth = $access->authorize($action);
if (is_bool($auth)) {
if ($auth === false) {
return false;
}
$authorized = true;
}
}
if (null === $authorized && $this->getNestedProperty('header.permissions.inherit', true)) {
// Authorize against parent page.
$parent = $this->parent();
if ($parent && method_exists($parent, 'isParentAuthorized')) {
$authorized = $parent->isParentAuthorized($action, $scope, !$isMe ? $user : null, $isAuthor);
}
}
return $authorized;
}
/**
* @param array $parent
* @return array
*/
protected function loadPermissions(array $parent = []): array
{
static $rules = [
'c' => 'create',
'r' => 'read',
'u' => 'update',
'd' => 'delete',
'p' => 'publish',
'l' => 'list'
];
$permissions = $this->getNestedProperty('header.permissions.groups');
$name = $this->root() ? '<root>' : '/' . $this->getKey();
$list = [];
if (is_array($permissions)) {
foreach ($permissions as $group => $access) {
$list[$group] = new Access($access, $rules, $name);
}
}
foreach ($parent as $group => $access) {
if (isset($list[$group])) {
$object = $list[$group];
} else {
$object = new Access([], $rules, $name);
$list[$group] = $object;
}
$object->inherit($access);
}
return $list;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Pages/Traits/PageLegacyTrait.php | system/src/Grav/Framework/Flex/Pages/Traits/PageLegacyTrait.php | <?php
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Pages\Traits;
use Exception;
use Grav\Common\Grav;
use Grav\Common\Page\Collection;
use Grav\Common\Page\Interfaces\PageCollectionInterface;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Page\Pages;
use Grav\Common\Utils;
use Grav\Common\Yaml;
use Grav\Framework\File\Formatter\MarkdownFormatter;
use Grav\Framework\File\Formatter\YamlFormatter;
use Grav\Framework\Filesystem\Filesystem;
use Grav\Framework\Flex\Interfaces\FlexCollectionInterface;
use Grav\Framework\Flex\Interfaces\FlexIndexInterface;
use Grav\Framework\Flex\Pages\FlexPageCollection;
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
*/
trait PageLegacyTrait
{
/** @var array|null */
private $_content_meta;
/** @var array|null */
private $_metadata;
/**
* 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|null $extension
* @return $this
*/
public function init(SplFileInfo $file, $extension = null)
{
// TODO:
throw new RuntimeException(__METHOD__ . '(): Not Implemented');
}
/**
* Gets and Sets the raw data
*
* @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');
}
$storage = $this->getFlexDirectory()->getStorage();
if (method_exists($storage, 'readRaw')) {
return $storage->readRaw($this->getStorageKey());
}
$array = $this->prepareStorage();
$formatter = new MarkdownFormatter();
return $formatter->encode($array);
}
/**
* Gets and Sets the page frontmatter
*
* @param string|null $var
* @return string
*/
public function frontmatter($var = null): string
{
if (null !== $var) {
$formatter = new YamlFormatter();
$this->setProperty('frontmatter', $var);
$this->setProperty('header', $formatter->decode($var));
return $var;
}
$storage = $this->getFlexDirectory()->getStorage();
if (method_exists($storage, 'readFrontmatter')) {
return $storage->readFrontmatter($this->getStorageKey());
}
$array = $this->prepareStorage();
$formatter = new YamlFormatter();
return $formatter->encode($array['header'] ?? []);
}
/**
* Modify a header value directly
*
* @param string $key
* @param string|array $value
* @return void
*/
public function modifyHeader($key, $value): void
{
$this->setNestedProperty("header.{$key}", $value);
}
/**
* @return int
*/
public function httpResponseCode(): int
{
$code = (int)$this->getNestedProperty('header.http_response_code');
return $code ?: 200;
}
/**
* @return array
*/
public function httpHeaders(): array
{
$headers = [];
$format = $this->templateFormat();
$cache_control = $this->cacheControl();
$expires = $this->expires();
// Set Content-Type header.
$headers['Content-Type'] = Utils::getMimeByExtension($format, 'text/html');
// Calculate Expires Headers if set to > 0.
if ($expires > 0) {
$expires_date = gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT';
if (!$cache_control) {
$headers['Cache-Control'] = 'max-age=' . $expires;
}
$headers['Expires'] = $expires_date;
}
// Set Cache-Control header.
if ($cache_control) {
$headers['Cache-Control'] = strtolower($cache_control);
}
// Set Last-Modified header.
if ($this->lastModified()) {
$last_modified_date = gmdate('D, d M Y H:i:s', $this->modified()) . ' GMT';
$headers['Last-Modified'] = $last_modified_date;
}
// Calculate ETag based on the serialized page and modified time.
if ($this->eTag()) {
$headers['ETag'] = '1';
}
// Set Vary: Accept-Encoding header.
$grav = Grav::instance();
if ($grav['config']->get('system.pages.vary_accept_encoding', false)) {
$headers['Vary'] = 'Accept-Encoding';
}
return $headers;
}
/**
* Get the contentMeta array and initialize content first if it's not already
*
* @return array
*/
public function contentMeta(): array
{
// Content meta is generated during the content is being rendered, so make sure we have done it.
$this->content();
return $this->_content_meta ?? [];
}
/**
* Add an entry to the page's contentMeta array
*
* @param string $name
* @param string $value
* @return void
*/
public function addContentMeta($name, $value): void
{
$this->_content_meta[$name] = $value;
}
/**
* Return the whole contentMeta array as it currently stands
*
* @param string|null $name
* @return string|array|null
*/
public function getContentMeta($name = null)
{
if ($name) {
return $this->_content_meta[$name] ?? null;
}
return $this->_content_meta ?? [];
}
/**
* Sets the whole content meta array in one shot
*
* @param array $content_meta
* @return array
*/
public function setContentMeta($content_meta): array
{
return $this->_content_meta = $content_meta;
}
/**
* Fires the onPageContentProcessed event, and caches the page content using a unique ID for the page
*/
public function cachePageContent(): void
{
$value = [
'checksum' => $this->getCacheChecksum(),
'content' => $this->_content,
'content_meta' => $this->_content_meta
];
$cache = $this->getCache('render');
$key = md5($this->getCacheKey() . '-content');
$cache->set($key, $value);
}
/**
* Get file object to the page.
*
* @return MarkdownFile|null
*/
public function file(): ?MarkdownFile
{
// TODO:
throw new RuntimeException(__METHOD__ . '(): Not Implemented');
}
/**
* 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');
}
$rawRoute = $this->rawRoute();
if ($rawRoute && Utils::startsWith($parent->rawRoute(), $rawRoute)) {
throw new RuntimeException('Failed: Cannot set page parent to a child of current page');
}
$this->storeOriginal();
// TODO:
throw new RuntimeException(__METHOD__ . '(): Not Implemented');
}
/**
* Prepare a copy from the page. Copies also everything that's under the current page.
*
* Returns a new Page object for the copy.
* 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)
{
$this->storeOriginal();
$filesystem = Filesystem::getInstance(false);
$parentStorageKey = ltrim($filesystem->dirname("/{$this->getMasterKey()}"), '/');
/** @var FlexPageIndex<FlexPageObject,FlexPageCollection<FlexPageObject>> $index */
$index = $this->getFlexDirectory()->getIndex();
if ($parent) {
if ($parent instanceof FlexPageObject) {
$k = $parent->getMasterKey();
if ($k !== $parentStorageKey) {
$parentStorageKey = $k;
}
} else {
throw new RuntimeException('Cannot copy page, parent is of unknown type');
}
} else {
$parent = $parentStorageKey
? $this->getFlexDirectory()->getObject($parentStorageKey, 'storage_key')
: (method_exists($index, 'getRoot') ? $index->getRoot() : null);
}
// Find non-existing key.
$parentKey = $parent ? $parent->getKey() : '';
if ($this instanceof FlexPageObject) {
$key = trim($parentKey . '/' . $this->folder(), '/');
$key = preg_replace(static::PAGE_ORDER_PREFIX_REGEX, '', $key);
\assert(is_string($key));
} else {
$key = trim($parentKey . '/' . Utils::basename($this->getKey()), '/');
}
if ($index->containsKey($key)) {
$key = preg_replace('/\d+$/', '', $key);
$i = 1;
do {
$i++;
$test = "{$key}{$i}";
} while ($index->containsKey($test));
$key = $test;
}
$folder = Utils::basename($key);
// Get the folder name.
$order = $this->getProperty('order');
if ($order) {
$order++;
}
$parts = [];
if ($parentStorageKey !== '') {
$parts[] = $parentStorageKey;
}
$parts[] = $order ? sprintf('%02d.%s', $order, $folder) : $folder;
// Finally update the object.
$this->setKey($key);
$this->setStorageKey(implode('/', $parts));
$this->markAsCopy();
return $this;
}
/**
* Get the blueprint name for this page. Use the blueprint form field if set
*
* @return string
*/
public function blueprintName(): string
{
if (!isset($_POST['blueprint'])) {
return $this->template();
}
$post_value = $_POST['blueprint'];
$sanitized_value = htmlspecialchars(strip_tags($post_value), ENT_QUOTES, 'UTF-8');
return $sanitized_value ?: $this->template();
}
/**
* Validate page header.
*
* @return void
* @throws Exception
*/
public function validate(): void
{
$blueprint = $this->getBlueprint();
$blueprint->validate($this->toArray());
}
/**
* Filter page header from illegal contents.
*
* @return void
*/
public function filter(): void
{
$blueprints = $this->getBlueprint();
$values = $blueprints->filter($this->toArray());
if ($values && isset($values['header'])) {
$this->header($values['header']);
}
}
/**
* Get unknown header variables.
*
* @return array
*/
public function extra(): array
{
$data = $this->prepareStorage();
return $this->getBlueprint()->extra((array)($data['header'] ?? []), 'header.');
}
/**
* Convert page to an array.
*
* @return array
*/
public function toArray(): array
{
return [
'header' => (array)$this->header(),
'content' => (string)$this->getFormValue('content')
];
}
/**
* Convert page to YAML encoded string.
*
* @return string
*/
public function toYaml(): string
{
return Yaml::dump($this->toArray(), 20);
}
/**
* Convert page to JSON encoded string.
*
* @return string
*/
public function toJson(): string
{
$json = json_encode($this->toArray());
if (!is_string($json)) {
throw new RuntimeException('Internal error');
}
return $json;
}
/**
* Gets and sets the name field. If no name field is set, it will return 'default.md'.
*
* @param string|null $var The name of this page.
* @return string The name of this page.
*/
public function name($var = null): string
{
return $this->loadProperty(
'name',
$var,
function ($value) {
$value = $value ?? $this->getMetaData()['template'] ?? 'default';
if (!preg_match('/\.md$/', $value)) {
$language = $this->language();
if ($language) {
// TODO: better language support
$value .= ".{$language}";
}
$value .= '.md';
}
$value = preg_replace('|^modular/|', '', $value);
$this->unsetProperty('template');
return $value;
}
);
}
/**
* Returns child page type.
*
* @return string
*/
public function childType(): string
{
return (string)$this->getNestedProperty('header.child_type');
}
/**
* 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|null $var the template name
* @return string the template name
*/
public function template($var = null): string
{
return $this->loadHeaderProperty(
'template',
$var,
function ($value) {
return trim($value ?? (($this->isModule() ? 'modular/' : '') . str_replace($this->extension(), '', $this->name())));
}
);
}
/**
* Allows a page to override the output render format, usually the extension provided in the URL.
* (e.g. `html`, `json`, `xml`, etc).
*
* @param string|null $var
* @return string
*/
public function templateFormat($var = null): string
{
return $this->loadHeaderProperty(
'template_format',
$var,
function ($value) {
return ltrim($value ?? $this->getNestedProperty('header.append_url_extension') ?: Utils::getPageFormat(), '.');
}
);
}
/**
* Gets and sets the extension field.
*
* @param string|null $var
* @return string
*/
public function extension($var = null): string
{
if (null !== $var) {
$this->setProperty('format', $var);
}
$language = $this->language();
if ($language) {
$language = '.' . $language;
}
$format = '.' . ($this->getProperty('format') ?? Utils::pathinfo($this->name(), PATHINFO_EXTENSION));
return $language . $format;
}
/**
* Gets and sets the expires field. If not set will return the default
*
* @param int|null $var The new expires value.
* @return int The expires value
*/
public function expires($var = null): int
{
return $this->loadHeaderProperty(
'expires',
$var,
static function ($value) {
return (int)($value ?? Grav::instance()['config']->get('system.pages.expires'));
}
);
}
/**
* Gets and sets the cache-control property. If not set it will return the default value (null)
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control for more details on valid options
*
* @param string|null $var
* @return string|null
*/
public function cacheControl($var = null): ?string
{
return $this->loadHeaderProperty(
'cache_control',
$var,
static function ($value) {
return ((string)($value ?? Grav::instance()['config']->get('system.pages.cache_control'))) ?: null;
}
);
}
/**
* @param bool|null $var
* @return bool|null
*/
public function ssl($var = null): ?bool
{
return $this->loadHeaderProperty(
'ssl',
$var,
static function ($value) {
return $value ? (bool)$value : null;
}
);
}
/**
* Returns the state of the debugger override setting for this page
*
* @return bool
*/
public function debugger(): bool
{
return (bool)$this->getNestedProperty('header.debugger', true);
}
/**
* Function to merge page metadata tags and build an array of Metadata objects
* that can then be rendered in the page.
*
* @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
{
if ($var !== null) {
$this->_metadata = (array)$var;
}
// if not metadata yet, process it.
if (null === $this->_metadata) {
$this->_metadata = [];
$config = Grav::instance()['config'];
// Set the Generator tag
$defaultMetadata = ['generator' => 'GravCMS'];
$siteMetadata = $config->get('site.metadata', []);
$headerMetadata = $this->getNestedProperty('header.metadata', []);
// Get initial metadata for the page
$metadata = array_merge($defaultMetadata, $siteMetadata, $headerMetadata);
$header_tag_http_equivs = ['content-type', 'default-style', 'refresh', 'x-ua-compatible', 'content-security-policy'];
$escape = !$config->get('system.strict_mode.twig_compat', false) || $config->get('system.twig.autoescape', true);
// Build an array of meta objects..
foreach ($metadata as $key => $value) {
// Lowercase the key
$key = strtolower($key);
// If this is a property type metadata: "og", "twitter", "facebook" etc
// Backward compatibility for nested arrays in metas
if (is_array($value)) {
foreach ($value as $property => $prop_value) {
$prop_key = $key . ':' . $property;
$this->_metadata[$prop_key] = [
'name' => $prop_key,
'property' => $prop_key,
'content' => $escape ? htmlspecialchars($prop_value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $prop_value
];
}
} elseif ($value) {
// If it this is a standard meta data type
if (in_array($key, $header_tag_http_equivs, true)) {
$this->_metadata[$key] = [
'http_equiv' => $key,
'content' => $escape ? htmlspecialchars($value, ENT_COMPAT, 'UTF-8') : $value
];
} elseif ($key === 'charset') {
$this->_metadata[$key] = ['charset' => $escape ? htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $value];
} else {
// if it's a social metadata with separator, render as property
$separator = strpos($key, ':');
$hasSeparator = $separator && $separator < strlen($key) - 1;
$entry = [
'content' => $escape ? htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $value
];
if ($hasSeparator && !Utils::startsWith($key, 'twitter')) {
$entry['property'] = $key;
} else {
$entry['name'] = $key;
}
$this->_metadata[$key] = $entry;
}
}
}
}
return $this->_metadata;
}
/**
* Reset the metadata and pull from header again
*/
public function resetMetadata(): void
{
$this->_metadata = null;
}
/**
* Gets and sets the option to show the etag header for the page.
*
* @param bool|null $var show etag header
* @return bool show etag header
*/
public function eTag($var = null): bool
{
return $this->loadHeaderProperty(
'etag',
$var,
static function ($value) {
return (bool)($value ?? Grav::instance()['config']->get('system.pages.etag'));
}
);
}
/**
* Gets and sets the path to the .md file for this Page object.
*
* @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');
}
$folder = $this->getStorageFolder();
if (!$folder) {
return null;
}
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$folder = $locator->isStream($folder) ? $locator->getResource($folder) : GRAV_ROOT . "/{$folder}";
return $folder . '/' . ($this->isPage() ? $this->name() : 'default.md');
}
/**
* Gets the relative path to the .md file
*
* @return string|null The relative file path
*/
public function filePathClean(): ?string
{
$folder = $this->getStorageFolder();
if (!$folder) {
return null;
}
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$folder = $locator->isStream($folder) ? $locator->getResource($folder, false) : $folder;
return $folder . '/' . ($this->isPage() ? $this->name() : 'default.md');
}
/**
* Gets and sets the order by which any sub-pages should be sorted.
*
* @param string|null $var the order, either "asc" or "desc"
* @return string the order, either "asc" or "desc"
*/
public function orderDir($var = null): string
{
return $this->loadHeaderProperty(
'order_dir',
$var,
static function ($value) {
return strtolower(trim($value) ?: Grav::instance()['config']->get('system.pages.order.dir')) === 'desc' ? 'desc' : 'asc';
}
);
}
/**
* Gets and sets the order by which the sub-pages should be sorted.
*
* default - is the order based on the file system, ie 01.Home before 02.Advark
* title - is the order based on the title set in the pages
* 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|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
{
return $this->loadHeaderProperty(
'order_by',
$var,
static function ($value) {
return trim($value) ?: Grav::instance()['config']->get('system.pages.order.by');
}
);
}
/**
* Gets the manual order set in the header.
*
* @param string|null $var supported options include "default", "title", "date", and "folder"
* @return array
*/
public function orderManual($var = null): array
{
return $this->loadHeaderProperty(
'order_manual',
$var,
static function ($value) {
return (array)$value;
}
);
}
/**
* 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|null $var the maximum number of sub-pages
* @return int the maximum number of sub-pages
*/
public function maxCount($var = null): int
{
return $this->loadHeaderProperty(
'max_count',
$var,
static function ($value) {
return (int)($value ?? Grav::instance()['config']->get('system.pages.list.count'));
}
);
}
/**
* Gets and sets the modular var that helps identify this page is a modular child
*
* @param bool|null $var true if modular_twig
* @return bool true if modular_twig
* @deprecated 1.7 Use ->isModule() or ->modularTwig() method instead.
*/
public function modular($var = null): bool
{
user_error(__METHOD__ . '() is deprecated since Grav 1.7, use ->isModule() or ->modularTwig() method instead', E_USER_DEPRECATED);
return $this->modularTwig($var);
}
/**
* 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|null $var true if modular_twig
* @return bool true if modular_twig
*/
public function modularTwig($var = null): bool
{
if ($var !== null) {
$this->setProperty('modular_twig', (bool)$var);
if ($var) {
$this->visible(false);
}
}
return (bool)($this->getProperty('modular_twig') ?? strpos($this->slug(), '_') === 0);
}
/**
* Returns children of this page.
*
* @return PageCollectionInterface|FlexIndexInterface
*/
public function children()
{
$meta = $this->getMetaData();
$keys = array_keys($meta['children'] ?? []);
$prefix = $this->getMasterKey();
if ($prefix) {
foreach ($keys as &$key) {
$key = $prefix . '/' . $key;
}
unset($key);
}
return $this->getFlexDirectory()->getIndex($keys, 'storage_key');
}
/**
* Check to see if this item is the first in an array of sub-pages.
*
* @return bool True if item is first.
*/
public function isFirst(): bool
{
$parent = $this->parent();
$children = $parent ? $parent->children() : null;
if ($children instanceof FlexCollectionInterface) {
$children = $children->withKeyField();
}
return $children instanceof PageCollectionInterface ? $children->isFirst($this->getKey()) : true;
}
/**
* Check to see if this item is the last in an array of sub-pages.
*
* @return bool True if item is last
*/
public function isLast(): bool
{
$parent = $this->parent();
$children = $parent ? $parent->children() : null;
if ($children instanceof FlexCollectionInterface) {
$children = $children->withKeyField();
}
return $children instanceof PageCollectionInterface ? $children->isLast($this->getKey()) : true;
}
/**
* Gets the previous sibling based on current position.
*
* @return PageInterface|false the previous Page item
*/
public function prevSibling()
{
return $this->adjacentSibling(-1);
}
/**
* Gets the next sibling based on current position.
*
* @return PageInterface|false the next Page item
*/
public function nextSibling()
{
return $this->adjacentSibling(1);
}
/**
* Returns the adjacent sibling based on a direction.
*
* @param int $direction either -1 or +1
* @return PageInterface|false the sibling page
*/
public function adjacentSibling($direction = 1)
{
$parent = $this->parent();
$children = $parent ? $parent->children() : null;
if ($children instanceof FlexCollectionInterface) {
$children = $children->withKeyField();
}
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)
{
/** @var Pages $pages */
$pages = Grav::instance()['pages'];
return $pages->ancestor($this->getProperty('parent_route'), $lookup);
}
/**
* Helper method to return an ancestor page to inherit from. The current
* page object is returned.
*
* @param string $field Name of the parent folder
* @return PageInterface|null
*/
public function inherited($field)
{
[$inherited, $currentParams] = $this->getInheritedParams($field);
$this->modifyHeader($field, $currentParams);
return $inherited;
}
/**
* Helper method to return an ancestor field only to inherit from. The
* 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
{
[, $currentParams] = $this->getInheritedParams($field);
return $currentParams;
}
/**
* 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'];
$inherited = $pages->inherited($this->getProperty('parent_route'), $field);
$inheritedParams = $inherited ? (array)$inherited->value('header.' . $field) : [];
$currentParams = (array)$this->getFormValue('header.' . $field);
if ($inheritedParams && is_array($inheritedParams)) {
$currentParams = array_replace_recursive($inheritedParams, $currentParams);
}
return [$inherited, $currentParams];
}
/**
* Helper method to return a page.
*
* @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)
{
/** @var Pages $pages */
$pages = Grav::instance()['pages'];
return $pages->find($url, $all);
}
/**
* Get a collection of pages in the current context.
*
* @param string|array $params
* @param bool $pagination
* @return PageCollectionInterface|Collection
* @throws InvalidArgumentException
*/
public function collection($params = 'content', $pagination = true)
{
if (is_string($params)) {
// 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');
}
if (!$pagination) {
$params['pagination'] = false;
}
$context = [
'pagination' => $pagination,
'self' => $this
];
/** @var Pages $pages */
$pages = Grav::instance()['pages'];
return $pages->getCollection($params, $context);
}
/**
* @param string|array $value
* @param bool $only_published
* @return PageCollectionInterface|Collection
*/
public function evaluate($value, $only_published = true)
{
$params = [
'items' => $value,
'published' => $only_published
];
$context = [
'event' => false,
'pagination' => false,
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | true |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Pages/Traits/PageTranslateTrait.php | system/src/Grav/Framework/Flex/Pages/Traits/PageTranslateTrait.php | <?php
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Pages\Traits;
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
*/
trait PageTranslateTrait
{
/** @var array|null */
private $_languages;
/** @var PageInterface[] */
private $_translations = [];
/**
* @return bool
*/
public function translated(): bool
{
return (bool)$this->translatedLanguages(true);
}
/**
* @param string|null $languageCode
* @param bool|null $fallback
* @return bool
*/
public function hasTranslation(string $languageCode = null, bool $fallback = null): bool
{
$code = $this->findTranslation($languageCode, $fallback);
return null !== $code;
}
/**
* @param string|null $languageCode
* @param bool|null $fallback
* @return FlexObjectInterface|PageInterface|null
*/
public function getTranslation(string $languageCode = null, bool $fallback = null)
{
if ($this->root()) {
return $this;
}
$code = $this->findTranslation($languageCode, $fallback);
if (null === $code) {
$object = null;
} elseif ('' === $code) {
$object = $this->getLanguage() ? $this->getFlexDirectory()->getObject($this->getMasterKey(), 'storage_key') : $this;
} else {
$meta = $this->getMetaData();
$meta['template'] = $this->getLanguageTemplates()[$code] ?? $meta['template'];
$key = $this->getStorageKey() . '|' . $meta['template'] . '.' . $code;
$meta['storage_key'] = $key;
$meta['lang'] = $code;
$object = $this->getFlexDirectory()->loadObjects([$key => $meta])[$key] ?? null;
}
return $object;
}
/**
* @param bool $includeDefault If set to true, return separate entries for '' and 'en' (default) language.
* @return array
*/
public function getAllLanguages(bool $includeDefault = false): array
{
$grav = Grav::instance();
/** @var Language $language */
$language = $grav['language'];
$languages = $language->getLanguages();
if (!$languages) {
return [];
}
$translated = $this->getLanguageTemplates();
if ($includeDefault) {
$languages[] = '';
} elseif (isset($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);
return array_replace($languages, $translated);
}
/**
* Returns all translated languages.
*
* @param bool $includeDefault If set to true, return separate entries for '' and 'en' (default) language.
* @return array
*/
public function getLanguages(bool $includeDefault = false): array
{
$languages = $this->getLanguageTemplates();
if (!$includeDefault && isset($languages[''])) {
$grav = Grav::instance();
/** @var Language $language */
$language = $grav['language'];
$default = $language->getDefault();
if (is_bool($default)) {
$default = '';
}
$languages[$default] = $languages[''];
unset($languages['']);
}
return array_keys($languages);
}
/**
* @return string
*/
public function getLanguage(): string
{
return $this->language() ?? '';
}
/**
* @param string|null $languageCode
* @param bool|null $fallback
* @return string|null
*/
public function findTranslation(string $languageCode = null, bool $fallback = null): ?string
{
$translated = $this->getLanguageTemplates();
// If there's no translations (including default), we have an empty folder.
if (!$translated) {
return '';
}
// FIXME: only published is not implemented...
$languages = $this->getFallbackLanguages($languageCode, $fallback);
$language = null;
foreach ($languages as $code) {
if (isset($translated[$code])) {
$language = $code;
break;
}
}
return $language;
}
/**
* Return an array with the routes of other translated languages
*
* @param bool $onlyPublished only return published translations
* @return array the page translated languages
*/
public function translatedLanguages($onlyPublished = false): array
{
// FIXME: only published is not implemented...
$translated = $this->getLanguageTemplates();
if (!$translated) {
return $translated;
}
$grav = Grav::instance();
/** @var Language $language */
$language = $grav['language'];
$languages = $language->getLanguages();
$languages[] = '';
$translated = array_intersect_key($translated, array_flip($languages));
$list = array_fill_keys($languages, null);
foreach ($translated as $languageCode => $languageFile) {
$path = ($languageCode ? '/' : '') . $languageCode;
$list[$languageCode] = "{$path}/{$this->getKey()}";
}
return array_filter($list);
}
/**
* Return an array listing untranslated languages available
*
* @param bool $includeUnpublished also list unpublished translations
* @return array the page untranslated languages
*/
public function untranslatedLanguages($includeUnpublished = false): array
{
$grav = Grav::instance();
/** @var Language $language */
$language = $grav['language'];
$languages = $language->getLanguages();
$translated = array_keys($this->translatedLanguages(!$includeUnpublished));
return array_values(array_diff($languages, $translated));
}
/**
* Get page language
*
* @param string|null $var
* @return string|null
*/
public function language($var = null): ?string
{
return $this->loadHeaderProperty(
'lang',
$var,
function ($value) {
$value = $value ?? $this->getMetaData()['lang'] ?? '';
return trim($value) ?: null;
}
);
}
/**
* @return array
*/
protected function getLanguageTemplates(): array
{
if (null === $this->_languages) {
$template = $this->getProperty('template');
$meta = $this->getMetaData();
$translations = $meta['markdown'] ?? [];
$list = [];
foreach ($translations as $code => $search) {
if (isset($search[$template])) {
// Use main template if possible.
$list[$code] = $template;
} elseif (!empty($search)) {
// Fall back to first matching template.
$list[$code] = key($search);
}
}
$this->_languages = $list;
}
return $this->_languages;
}
/**
* @param string|null $languageCode
* @param bool|null $fallback
* @return array
*/
protected function getFallbackLanguages(string $languageCode = null, bool $fallback = null): array
{
$fallback = $fallback ?? true;
if (!$fallback && null !== $languageCode) {
return [$languageCode];
}
$grav = Grav::instance();
/** @var Language $language */
$language = $grav['language'];
$languageCode = $languageCode ?? ($language->getLanguage() ?: '');
if ($languageCode === '' && $fallback) {
return $language->getFallbackLanguages(null, true);
}
return $fallback ? $language->getFallbackLanguages($languageCode, true) : [$languageCode];
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Pages/Traits/PageContentTrait.php | system/src/Grav/Framework/Flex/Pages/Traits/PageContentTrait.php | <?php
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Pages\Traits;
use Exception;
use Grav\Common\Config\Config;
use Grav\Common\Grav;
use Grav\Common\Markdown\Parsedown;
use Grav\Common\Markdown\ParsedownExtra;
use Grav\Common\Page\Header;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Page\Markdown\Excerpts;
use Grav\Common\Page\Media;
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.
*/
trait PageContentTrait
{
/** @var array */
protected static $headerProperties = [
'slug' => 'slug',
'routes' => false,
'title' => 'title',
'language' => 'language',
'template' => 'template',
'menu' => 'menu',
'routable' => 'routable',
'visible' => 'visible',
'redirect' => 'redirect',
'external_url' => false,
'order_dir' => 'orderDir',
'order_by' => 'orderBy',
'order_manual' => 'orderManual',
'dateformat' => 'dateformat',
'date' => 'date',
'markdown_extra' => false,
'taxonomy' => 'taxonomy',
'max_count' => 'maxCount',
'process' => 'process',
'published' => 'published',
'publish_date' => 'publishDate',
'unpublish_date' => 'unpublishDate',
'expires' => 'expires',
'cache_control' => 'cacheControl',
'etag' => 'eTag',
'last_modified' => 'lastModified',
'ssl' => 'ssl',
'template_format' => 'templateFormat',
'debugger' => false,
];
/** @var array */
protected static $calculatedProperties = [
'name' => 'name',
'parent' => 'parent',
'parent_key' => 'parentStorageKey',
'folder' => 'folder',
'order' => 'order',
'template' => 'template',
];
/** @var object|null */
protected $header;
/** @var string|null */
protected $_summary;
/** @var string|null */
protected $_content;
/**
* Method to normalize the route.
*
* @param string $route
* @return string
* @internal
*/
public static function normalizeRoute($route): string
{
$case_insensitive = Grav::instance()['config']->get('system.force_lowercase_urls');
return $case_insensitive ? mb_strtolower($route) : $route;
}
/**
* @inheritdoc
* @return Header
*/
public function header($var = null)
{
if (null !== $var) {
$this->setProperty('header', $var);
}
return $this->getProperty('header');
}
/**
* @inheritdoc
*/
public function summary($size = null, $textOnly = false): string
{
return $this->processSummary($size, $textOnly);
}
/**
* @inheritdoc
*/
public function setSummary($summary): void
{
$this->_summary = $summary;
}
/**
* @inheritdoc
* @throws Exception
*/
public function content($var = null): string
{
if (null !== $var) {
$this->_content = $var;
}
return $this->_content ?? $this->processContent($this->getRawContent());
}
/**
* @inheritdoc
*/
public function getRawContent(): string
{
return $this->_content ?? $this->getArrayProperty('markdown') ?? '';
}
/**
* @inheritdoc
*/
public function setRawContent($content): void
{
$this->_content = $content ?? '';
}
/**
* @inheritdoc
*/
public function rawMarkdown($var = null): string
{
if ($var !== null) {
$this->setProperty('markdown', $var);
}
return $this->getProperty('markdown') ?? '';
}
/**
* @inheritdoc
*
* Implement by calling:
*
* $test = new \stdClass();
* $value = $this->pageContentValue($name, $test);
* if ($value !== $test) {
* return $value;
* }
* return parent::value($name, $default);
*/
abstract public function value($name, $default = null, $separator = null);
/**
* @inheritdoc
*/
public function media($var = null): Media
{
if ($var instanceof Media) {
$this->setProperty('media', $var);
}
return $this->getProperty('media');
}
/**
* @inheritdoc
*/
public function title($var = null): string
{
return $this->loadHeaderProperty(
'title',
$var,
function ($value) {
return trim($value ?? ($this->root() ? '<root>' : ucfirst($this->slug())));
}
);
}
/**
* @inheritdoc
*/
public function menu($var = null): string
{
return $this->loadHeaderProperty(
'menu',
$var,
function ($value) {
return trim($value ?: $this->title());
}
);
}
/**
* @inheritdoc
*/
public function visible($var = null): bool
{
$value = $this->loadHeaderProperty(
'visible',
$var,
function ($value) {
return ($value ?? $this->order() !== false) && !$this->isModule();
}
);
return $value && $this->published();
}
/**
* @inheritdoc
*/
public function published($var = null): bool
{
return $this->loadHeaderProperty(
'published',
$var,
static function ($value) {
return (bool)($value ?? true);
}
);
}
/**
* @inheritdoc
*/
public function publishDate($var = null): ?int
{
return $this->loadHeaderProperty(
'publish_date',
$var,
function ($value) {
return $value ? Utils::date2timestamp($value, $this->getProperty('dateformat')) : null;
}
);
}
/**
* @inheritdoc
*/
public function unpublishDate($var = null): ?int
{
return $this->loadHeaderProperty(
'unpublish_date',
$var,
function ($value) {
return $value ? Utils::date2timestamp($value, $this->getProperty('dateformat')) : null;
}
);
}
/**
* @inheritdoc
*/
public function process($var = null): array
{
return $this->loadHeaderProperty(
'process',
$var,
function ($value) {
$value = array_replace(Grav::instance()['config']->get('system.pages.process', []), is_array($value) ? $value : []);
foreach ($value as $process => $status) {
$value[$process] = (bool)$status;
}
return $value;
}
);
}
/**
* @inheritdoc
*/
public function slug($var = null)
{
return $this->loadHeaderProperty(
'slug',
$var,
function ($value) {
if (is_string($value)) {
return $value;
}
$folder = $this->folder();
if (null === $folder) {
return null;
}
$folder = preg_replace(static::PAGE_ORDER_PREFIX_REGEX, '', $folder);
if (null === $folder) {
return null;
}
return static::normalizeRoute($folder);
}
);
}
/**
* @inheritdoc
*/
public function order($var = null)
{
$property = $this->loadProperty(
'order',
$var,
function ($value) {
if (null === $value) {
$folder = $this->folder();
if (null !== $folder) {
preg_match(static::PAGE_ORDER_REGEX, $folder, $order);
}
$value = $order[1] ?? false;
}
if ($value === '') {
$value = false;
}
if ($value !== false) {
$value = (int)$value;
}
return $value;
}
);
return $property !== false ? sprintf('%02d.', $property) : false;
}
/**
* @inheritdoc
*/
public function id($var = null): string
{
$property = 'id';
$value = null === $var ? $this->getProperty($property) : null;
if (null === $value) {
$value = $this->language() . ($var ?? ($this->modified() . md5('flex-' . $this->getFlexType() . '-' . $this->getKey())));
$this->setProperty($property, $value);
if ($this->doHasProperty($property)) {
$value = $this->getProperty($property);
}
}
return $value;
}
/**
* @inheritdoc
*/
public function modified($var = null): int
{
$property = 'modified';
$value = null === $var ? $this->getProperty($property) : null;
if (null === $value) {
$value = (int)($var ?: $this->getTimestamp());
$this->setProperty($property, $value);
if ($this->doHasProperty($property)) {
$value = $this->getProperty($property);
}
}
return $value;
}
/**
* @inheritdoc
*/
public function lastModified($var = null): bool
{
return $this->loadHeaderProperty(
'last_modified',
$var,
static function ($value) {
return (bool)($value ?? Grav::instance()['config']->get('system.pages.last_modified'));
}
);
}
/**
* @inheritdoc
*/
public function date($var = null): int
{
return $this->loadHeaderProperty(
'date',
$var,
function ($value) {
$value = $value ? Utils::date2timestamp($value, $this->getProperty('dateformat')) : false;
return $value ?: $this->modified();
}
);
}
/**
* @inheritdoc
*/
public function dateformat($var = null): ?string
{
return $this->loadHeaderProperty(
'dateformat',
$var,
static function ($value) {
return $value;
}
);
}
/**
* @inheritdoc
*/
public function taxonomy($var = null): array
{
return $this->loadHeaderProperty(
'taxonomy',
$var,
static function ($value) {
if (is_array($value)) {
// make sure first level are arrays
array_walk($value, static function (&$val) {
$val = (array) $val;
});
// make sure all values are strings
array_walk_recursive($value, static function (&$val) {
$val = (string) $val;
});
}
return $value ?? [];
}
);
}
/**
* @inheritdoc
*/
public function shouldProcess($process): bool
{
$test = $this->process();
return !empty($test[$process]);
}
/**
* @inheritdoc
*/
public function isPage(): bool
{
return !in_array($this->template(), ['', 'folder'], true);
}
/**
* @inheritdoc
*/
public function isDir(): bool
{
return !$this->isPage();
}
/**
* @return bool
*/
public function isModule(): bool
{
return $this->modularTwig();
}
/**
* @param Header|stdClass|array|null $value
* @return Header
*/
protected function offsetLoad_header($value)
{
if ($value instanceof Header) {
return $value;
}
if (null === $value) {
$value = [];
} 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() : [];
}
/**
* @param string $name
* @param mixed|null $default
* @return mixed
*/
protected function pageContentValue($name, $default = null)
{
switch ($name) {
case 'frontmatter':
$frontmatter = $this->getArrayProperty('frontmatter');
if ($frontmatter === null) {
$header = $this->prepareStorage()['header'] ?? null;
if ($header) {
$formatter = new YamlFormatter();
$frontmatter = $formatter->encode($header);
} else {
$frontmatter = '';
}
}
return $frontmatter;
case 'content':
return $this->getProperty('markdown');
case 'order':
return (string)$this->order();
case 'menu':
return $this->menu();
case 'ordering':
return $this->order() !== false ? '1' : '0';
case 'folder':
$folder = $this->folder();
return null !== $folder ? preg_replace(static::PAGE_ORDER_PREFIX_REGEX, '', $folder) : '';
case 'slug':
return $this->slug();
case 'published':
return $this->published();
case 'visible':
return $this->visible();
case 'media':
return $this->media()->all();
case 'media.file':
return $this->media()->files();
case 'media.video':
return $this->media()->videos();
case 'media.image':
return $this->media()->images();
case 'media.audio':
return $this->media()->audios();
}
return $default;
}
/**
* @param int|null $size
* @param bool $textOnly
* @return string
*/
protected function processSummary($size = null, $textOnly = false): string
{
$config = (array)Grav::instance()['config']->get('site.summary');
$config_page = (array)$this->getNestedProperty('header.summary');
if ($config_page) {
$config = array_merge($config, $config_page);
}
// Summary is not enabled, return the whole content.
if (empty($config['enabled'])) {
return $this->content();
}
$content = $this->_summary ?? $this->content();
if ($textOnly) {
$content = strip_tags($content);
}
$content_size = mb_strwidth($content, 'utf-8');
$summary_size = $this->_summary !== null ? $content_size : $this->getProperty('summary_size');
// Return calculated summary based on summary divider's position.
$format = $config['format'] ?? '';
// Return entire page content on wrong/unknown format.
if ($format !== 'long' && $format !== 'short') {
return $content;
}
if ($format === 'short' && null !== $summary_size) {
// Slice the string on breakpoint.
if ($content_size > $summary_size) {
return mb_substr($content, 0, $summary_size);
}
return $content;
}
// If needed, get summary size from the config.
$size = $size ?? $config['size'] ?? null;
// Return calculated summary based on defaults.
$size = is_numeric($size) ? (int)$size : -1;
if ($size < 0) {
$size = 300;
}
// If the size is zero or smaller than the summary limit, return the entire page content.
if ($size === 0 || $content_size <= $size) {
return $content;
}
// Only return string but not html, wrap whatever html tag you want when using.
if ($textOnly) {
return mb_strimwidth($content, 0, $size, '...', 'UTF-8');
}
$summary = Utils::truncateHTML($content, $size);
return html_entity_decode($summary, ENT_COMPAT | ENT_HTML5, 'UTF-8');
}
/**
* Gets and Sets the content based on content portion of the .md file
*
* @param string $content
* @return string
* @throws Exception
*/
protected function processContent($content): string
{
$content = is_string($content) ? $content : '';
$grav = Grav::instance();
/** @var Config $config */
$config = $grav['config'];
$process_markdown = $this->shouldProcess('markdown');
$process_twig = $this->shouldProcess('twig') || $this->isModule();
$cache_enable = $this->getNestedProperty('header.cache_enable') ?? $config->get('system.cache.enabled', true);
$twig_first = $this->getNestedProperty('header.twig_first') ?? $config->get('system.pages.twig_first', false);
$never_cache_twig = $this->getNestedProperty('header.never_cache_twig') ?? $config->get('system.pages.never_cache_twig', false);
if ($cache_enable) {
$cache = $this->getCache('render');
$key = md5($this->getCacheKey() . '-content');
$cached = $cache->get($key);
if ($cached && $cached['checksum'] === $this->getCacheChecksum()) {
$this->_content = $cached['content'] ?? '';
$this->_content_meta = $cached['content_meta'] ?? null;
if ($process_twig && $never_cache_twig) {
$this->_content = $this->processTwig($this->_content);
}
}
}
if (null === $this->_content) {
$markdown_options = [];
if ($process_markdown) {
// Build markdown options.
$markdown_options = (array)$config->get('system.pages.markdown');
$markdown_page_options = (array)$this->getNestedProperty('header.markdown');
if ($markdown_page_options) {
$markdown_options = array_merge($markdown_options, $markdown_page_options);
}
// pages.markdown_extra is deprecated, but still check it...
if (!isset($markdown_options['extra'])) {
$extra = $this->getNestedProperty('header.markdown_extra') ?? $config->get('system.pages.markdown_extra');
if (null !== $extra) {
user_error('Configuration option \'system.pages.markdown_extra\' is deprecated since Grav 1.5, use \'system.pages.markdown.extra\' instead', E_USER_DEPRECATED);
$markdown_options['extra'] = $extra;
}
}
}
$options = [
'markdown' => $markdown_options,
'images' => $config->get('system.images', [])
];
$this->_content = $content;
$grav->fireEvent('onPageContentRaw', new Event(['page' => $this]));
if ($twig_first && !$never_cache_twig) {
if ($process_twig) {
$this->_content = $this->processTwig($this->_content);
}
if ($process_markdown) {
$this->_content = $this->processMarkdown($this->_content, $options);
}
// Content Processed but not cached yet
$grav->fireEvent('onPageContentProcessed', new Event(['page' => $this]));
} else {
if ($process_markdown) {
$options['keep_twig'] = $process_twig;
$this->_content = $this->processMarkdown($this->_content, $options);
}
// Content Processed but not cached yet
$grav->fireEvent('onPageContentProcessed', new Event(['page' => $this]));
if ($cache_enable && $never_cache_twig) {
$this->cachePageContent();
}
if ($process_twig) {
\assert(is_string($this->_content));
$this->_content = $this->processTwig($this->_content);
}
}
if ($cache_enable && !$never_cache_twig) {
$this->cachePageContent();
}
}
\assert(is_string($this->_content));
// Handle summary divider
$delimiter = $config->get('site.summary.delimiter', '===');
$divider_pos = mb_strpos($this->_content, "<p>{$delimiter}</p>");
if ($divider_pos !== false) {
$this->setProperty('summary_size', $divider_pos);
$this->_content = str_replace("<p>{$delimiter}</p>", '', $this->_content);
}
// Fire event when Page::content() is called
$grav->fireEvent('onPageContent', new Event(['page' => $this]));
return $this->_content;
}
/**
* Process the Twig page content.
*
* @param string $content
* @return string
*/
protected function processTwig($content): string
{
/** @var Twig $twig */
$twig = Grav::instance()['twig'];
/** @var PageInterface $this */
return $twig->processPage($this, $content);
}
/**
* Process the Markdown content.
*
* Uses Parsedown or Parsedown Extra depending on configuration.
*
* @param string $content
* @param array $options
* @return string
* @throws Exception
*/
protected function processMarkdown($content, array $options = []): string
{
/** @var PageInterface $self */
$self = $this;
$excerpts = new Excerpts($self, $options);
// Initialize the preferred variant of markdown parser.
if (isset($options['extra'])) {
$parsedown = new ParsedownExtra($excerpts);
} else {
$parsedown = new Parsedown($excerpts);
}
$keepTwig = (bool)($options['keep_twig'] ?? false);
if ($keepTwig) {
$token = [
'/' . Utils::generateRandomString(3),
Utils::generateRandomString(3) . '/'
];
// Base64 encode any twig.
$content = preg_replace_callback(
['/({#.*?#})/mu', '/({{.*?}})/mu', '/({%.*?%})/mu'],
static function ($matches) use ($token) { return $token[0] . base64_encode($matches[1]) . $token[1]; },
$content
);
}
$content = $parsedown->text($content);
if ($keepTwig) {
// Base64 decode the encoded twig.
$content = preg_replace_callback(
['`' . $token[0] . '([A-Za-z0-9+/]+={0,2})' . $token[1] . '`mu'],
static function ($matches) { return base64_decode($matches[1]); },
$content
);
}
return $content;
}
abstract protected function loadHeaderProperty(string $property, $var, callable $filter);
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Storage/FolderStorage.php | system/src/Grav/Framework/Flex/Storage/FolderStorage.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Storage;
use FilesystemIterator;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Grav;
use Grav\Common\Utils;
use Grav\Framework\Filesystem\Filesystem;
use Grav\Framework\Flex\Interfaces\FlexStorageInterface;
use RocketTheme\Toolbox\File\File;
use InvalidArgumentException;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use SplFileInfo;
use function array_key_exists;
use function basename;
use function count;
use function is_scalar;
use function is_string;
use function mb_strpos;
use function mb_substr;
/**
* Class FolderStorage
* @package Grav\Framework\Flex\Storage
*/
class FolderStorage extends AbstractFilesystemStorage
{
/** @var string Folder where all the data is stored. */
protected $dataFolder;
/** @var string Pattern to access an object. */
protected $dataPattern = '{FOLDER}/{KEY}/{FILE}{EXT}';
/** @var string[] */
protected $variables = ['FOLDER' => '%1$s', 'KEY' => '%2$s', 'KEY:2' => '%3$s', 'FILE' => '%4$s', 'EXT' => '%5$s'];
/** @var string Filename for the object. */
protected $dataFile;
/** @var string File extension for the object. */
protected $dataExt;
/** @var bool */
protected $prefixed;
/** @var bool */
protected $indexed;
/** @var array */
protected $meta = [];
/**
* {@inheritdoc}
*/
public function __construct(array $options)
{
if (!isset($options['folder'])) {
throw new InvalidArgumentException("Argument \$options is missing 'folder'");
}
$this->initDataFormatter($options['formatter'] ?? []);
$this->initOptions($options);
}
/**
* @return bool
*/
public function isIndexed(): bool
{
return $this->indexed;
}
/**
* @return void
*/
public function clearCache(): void
{
$this->meta = [];
}
/**
* @param string[] $keys
* @param bool $reload
* @return array
*/
public function getMetaData(array $keys, bool $reload = false): array
{
$list = [];
foreach ($keys as $key) {
$list[$key] = $this->getObjectMeta((string)$key, $reload);
}
return $list;
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::getExistingKeys()
*/
public function getExistingKeys(): array
{
return $this->buildIndex();
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::hasKey()
*/
public function hasKey(string $key): bool
{
$meta = $this->getObjectMeta($key);
return array_key_exists('exists', $meta) ? $meta['exists'] : !empty($meta['storage_timestamp']);
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::createRows()
*/
public function createRows(array $rows): array
{
$list = [];
foreach ($rows as $key => $row) {
$list[$key] = $this->saveRow('@@', $row);
}
return $list;
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::readRows()
*/
public function readRows(array $rows, array &$fetched = null): array
{
$list = [];
foreach ($rows as $key => $row) {
if (null === $row || is_scalar($row)) {
// Only load rows which haven't been loaded before.
$key = (string)$key;
$list[$key] = $this->loadRow($key);
if (null !== $fetched) {
$fetched[$key] = $list[$key];
}
} else {
// Keep the row if it has been loaded.
$list[$key] = $row;
}
}
return $list;
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::updateRows()
*/
public function updateRows(array $rows): array
{
$list = [];
foreach ($rows as $key => $row) {
$key = (string)$key;
$list[$key] = $this->hasKey($key) ? $this->saveRow($key, $row) : null;
}
return $list;
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::deleteRows()
*/
public function deleteRows(array $rows): array
{
$list = [];
$baseMediaPath = $this->getMediaPath();
foreach ($rows as $key => $row) {
$key = (string)$key;
if (!$this->hasKey($key)) {
$list[$key] = null;
} else {
$path = $this->getPathFromKey($key);
$file = $this->getFile($path);
$list[$key] = $this->deleteFile($file);
if ($this->canDeleteFolder($key)) {
$storagePath = $this->getStoragePath($key);
$mediaPath = $this->getMediaPath($key);
if ($storagePath) {
$this->deleteFolder($storagePath, true);
}
if ($mediaPath && $mediaPath !== $storagePath && $mediaPath !== $baseMediaPath) {
$this->deleteFolder($mediaPath, true);
}
}
}
}
return $list;
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::replaceRows()
*/
public function replaceRows(array $rows): array
{
$list = [];
foreach ($rows as $key => $row) {
$key = (string)$key;
$list[$key] = $this->saveRow($key, $row);
}
return $list;
}
/**
* @param string $src
* @param string $dst
* @return bool
* @throws RuntimeException
*/
public function copyRow(string $src, string $dst): bool
{
if ($this->hasKey($dst)) {
throw new RuntimeException("Cannot copy object: key '{$dst}' is already taken");
}
if (!$this->hasKey($src)) {
return false;
}
$srcPath = $this->getStoragePath($src);
$dstPath = $this->getStoragePath($dst);
if (!$srcPath || !$dstPath) {
return false;
}
return $this->copyFolder($srcPath, $dstPath);
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::renameRow()
* @throws RuntimeException
*/
public function renameRow(string $src, string $dst): bool
{
if (!$this->hasKey($src)) {
return false;
}
$srcPath = $this->getStoragePath($src);
$dstPath = $this->getStoragePath($dst);
if (!$srcPath || !$dstPath) {
throw new RuntimeException("Destination path '{$dst}' is empty");
}
if ($srcPath === $dstPath) {
return true;
}
if ($this->hasKey($dst)) {
throw new RuntimeException("Cannot rename object '{$src}': key '{$dst}' is already taken $srcPath $dstPath");
}
return $this->moveFolder($srcPath, $dstPath);
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::getStoragePath()
*/
public function getStoragePath(string $key = null): ?string
{
if (null === $key || $key === '') {
$path = $this->dataFolder;
} else {
$parts = $this->parseKey($key, false);
$options = [
$this->dataFolder, // {FOLDER}
$parts['key'], // {KEY}
$parts['key:2'], // {KEY:2}
'***', // {FILE}
'***' // {EXT}
];
$path = rtrim(explode('***', sprintf($this->dataPattern, ...$options))[0], '/');
}
return $path;
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::getMediaPath()
*/
public function getMediaPath(string $key = null): ?string
{
return $this->getStoragePath($key);
}
/**
* Get filesystem path from the key.
*
* @param string $key
* @return string
*/
public function getPathFromKey(string $key): string
{
$parts = $this->parseKey($key);
$options = [
$this->dataFolder, // {FOLDER}
$parts['key'], // {KEY}
$parts['key:2'], // {KEY:2}
$parts['file'], // {FILE}
$this->dataExt // {EXT}
];
return sprintf($this->dataPattern, ...$options);
}
/**
* @param string $key
* @param bool $variations
* @return array
*/
public function parseKey(string $key, bool $variations = true): array
{
$keys = [
'key' => $key,
'key:2' => mb_substr($key, 0, 2),
];
if ($variations) {
$keys['file'] = $this->dataFile;
}
return $keys;
}
/**
* Get key from the filesystem path.
*
* @param string $path
* @return string
*/
protected function getKeyFromPath(string $path): string
{
return Utils::basename($path);
}
/**
* Prepares the row for saving and returns the storage key for the record.
*
* @param array $row
* @return void
*/
protected function prepareRow(array &$row): void
{
if (array_key_exists($this->keyField, $row)) {
$key = $row[$this->keyField];
if ($key === $this->normalizeKey($key)) {
unset($row[$this->keyField]);
}
}
}
/**
* @param string $key
* @return array
*/
protected function loadRow(string $key): ?array
{
$path = $this->getPathFromKey($key);
$file = $this->getFile($path);
try {
$data = (array)$file->content();
if (isset($data[0])) {
throw new RuntimeException('Broken object file');
}
// Add key field to the object.
$keyField = $this->keyField;
if ($keyField !== 'storage_key' && !isset($data[$keyField])) {
$data[$keyField] = $key;
}
} catch (RuntimeException $e) {
$data = ['__ERROR' => $e->getMessage()];
} finally {
$file->free();
unset($file);
}
$data['__META'] = $this->getObjectMeta($key);
return $data;
}
/**
* @param string $key
* @param array $row
* @return array
*/
protected function saveRow(string $key, array $row): array
{
try {
if (isset($row[$this->keyField])) {
$key = $row[$this->keyField];
}
if (strpos($key, '@@') !== false) {
$key = $this->getNewKey();
}
$key = $this->normalizeKey($key);
// Check if the row already exists and if the key has been changed.
$oldKey = $row['__META']['storage_key'] ?? null;
if (is_string($oldKey) && $oldKey !== $key) {
$isCopy = $row['__META']['copy'] ?? false;
if ($isCopy) {
$this->copyRow($oldKey, $key);
} else {
$this->renameRow($oldKey, $key);
}
}
$this->prepareRow($row);
unset($row['__META'], $row['__ERROR']);
$path = $this->getPathFromKey($key);
$file = $this->getFile($path);
$file->save($row);
} catch (RuntimeException $e) {
throw new RuntimeException(sprintf('Flex saveFile(%s): %s', $path ?? $key, $e->getMessage()));
} finally {
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$locator->clearCache();
if (isset($file)) {
$file->free();
unset($file);
}
}
$row['__META'] = $this->getObjectMeta($key, true);
return $row;
}
/**
* @param File $file
* @return array|string
*/
protected function deleteFile(File $file)
{
$filename = $file->filename();
try {
$data = $file->content();
if ($file->exists()) {
$file->delete();
}
} catch (RuntimeException $e) {
throw new RuntimeException(sprintf('Flex deleteFile(%s): %s', $filename, $e->getMessage()));
} finally {
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$locator->clearCache();
$file->free();
}
return $data;
}
/**
* @param string $src
* @param string $dst
* @return bool
*/
protected function copyFolder(string $src, string $dst): bool
{
try {
Folder::copy($this->resolvePath($src), $this->resolvePath($dst));
} catch (RuntimeException $e) {
throw new RuntimeException(sprintf('Flex copyFolder(%s, %s): %s', $src, $dst, $e->getMessage()));
} finally {
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$locator->clearCache();
}
return true;
}
/**
* @param string $src
* @param string $dst
* @return bool
*/
protected function moveFolder(string $src, string $dst): bool
{
try {
Folder::move($this->resolvePath($src), $this->resolvePath($dst));
} catch (RuntimeException $e) {
throw new RuntimeException(sprintf('Flex moveFolder(%s, %s): %s', $src, $dst, $e->getMessage()));
} finally {
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$locator->clearCache();
}
return true;
}
/**
* @param string $path
* @param bool $include_target
* @return bool
*/
protected function deleteFolder(string $path, bool $include_target = false): bool
{
try {
return Folder::delete($this->resolvePath($path), $include_target);
} catch (RuntimeException $e) {
throw new RuntimeException(sprintf('Flex deleteFolder(%s): %s', $path, $e->getMessage()));
} finally {
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$locator->clearCache();
}
}
/**
* @param string $key
* @return bool
*/
protected function canDeleteFolder(string $key): bool
{
return true;
}
/**
* Returns list of all stored keys in [key => timestamp] pairs.
*
* @return array
*/
protected function buildIndex(): array
{
$this->clearCache();
$path = $this->getStoragePath();
if (!$path || !file_exists($path)) {
return [];
}
if ($this->prefixed) {
$list = $this->buildPrefixedIndexFromFilesystem($path);
} else {
$list = $this->buildIndexFromFilesystem($path);
}
ksort($list, SORT_NATURAL | SORT_FLAG_CASE);
return $list;
}
/**
* @param string $key
* @param bool $reload
* @return array
*/
protected function getObjectMeta(string $key, bool $reload = false): array
{
if (!$reload && isset($this->meta[$key])) {
return $this->meta[$key];
}
if ($key && strpos($key, '@@') === false) {
$filename = $this->getPathFromKey($key);
$modified = is_file($filename) ? filemtime($filename) : 0;
} else {
$modified = 0;
}
$meta = [
'storage_key' => $key,
'storage_timestamp' => $modified
];
$this->meta[$key] = $meta;
return $meta;
}
/**
* @param string $path
* @return array
*/
protected function buildIndexFromFilesystem($path)
{
$flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS;
$iterator = new FilesystemIterator($path, $flags);
$list = [];
/** @var SplFileInfo $info */
foreach ($iterator as $filename => $info) {
if (!$info->isDir() || strpos($info->getFilename(), '.') === 0) {
continue;
}
$key = $this->getKeyFromPath($filename);
$meta = $this->getObjectMeta($key);
if ($meta['storage_timestamp']) {
$list[$key] = $meta;
}
}
return $list;
}
/**
* @param string $path
* @return array
*/
protected function buildPrefixedIndexFromFilesystem($path)
{
$flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS;
$iterator = new FilesystemIterator($path, $flags);
$list = [[]];
/** @var SplFileInfo $info */
foreach ($iterator as $filename => $info) {
if (!$info->isDir() || strpos($info->getFilename(), '.') === 0) {
continue;
}
$list[] = $this->buildIndexFromFilesystem($filename);
}
return array_merge(...$list);
}
/**
* @return string
*/
protected function getNewKey(): string
{
// Make sure that the file doesn't exist.
do {
$key = $this->generateKey();
} while (file_exists($this->getPathFromKey($key)));
return $key;
}
/**
* @param array $options
* @return void
*/
protected function initOptions(array $options): void
{
$extension = $this->dataFormatter->getDefaultFileExtension();
/** @var string $pattern */
$pattern = !empty($options['pattern']) ? $options['pattern'] : $this->dataPattern;
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$folder = $options['folder'];
if ($locator->isStream($folder)) {
$folder = $locator->getResource($folder, false);
}
$this->dataFolder = $folder;
$this->dataFile = $options['file'] ?? 'item';
$this->dataExt = $extension;
if (mb_strpos($pattern, '{FILE}') === false && mb_strpos($pattern, '{EXT}') === false) {
if (isset($options['file'])) {
$pattern .= '/{FILE}{EXT}';
} else {
$filesystem = Filesystem::getInstance(true);
$this->dataFile = Utils::basename($pattern, $extension);
$pattern = $filesystem->dirname($pattern) . '/{FILE}{EXT}';
}
}
$this->prefixed = (bool)($options['prefixed'] ?? strpos($pattern, '/{KEY:2}/'));
$this->indexed = (bool)($options['indexed'] ?? false);
$this->keyField = $options['key'] ?? 'storage_key';
$this->keyLen = (int)($options['key_len'] ?? 32);
$this->caseSensitive = (bool)($options['case_sensitive'] ?? true);
$pattern = Utils::simpleTemplate($pattern, $this->variables);
if (!$pattern) {
throw new RuntimeException('Bad storage folder pattern');
}
$this->dataPattern = $pattern;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Storage/AbstractFilesystemStorage.php | system/src/Grav/Framework/Flex/Storage/AbstractFilesystemStorage.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Storage;
use Grav\Common\File\CompiledJsonFile;
use Grav\Common\File\CompiledMarkdownFile;
use Grav\Common\File\CompiledYamlFile;
use Grav\Common\Grav;
use Grav\Framework\File\Formatter\JsonFormatter;
use Grav\Framework\File\Formatter\MarkdownFormatter;
use Grav\Framework\File\Formatter\YamlFormatter;
use Grav\Framework\File\Interfaces\FileFormatterInterface;
use Grav\Framework\Flex\Interfaces\FlexStorageInterface;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use function is_array;
/**
* Class AbstractFilesystemStorage
* @package Grav\Framework\Flex\Storage
*/
abstract class AbstractFilesystemStorage implements FlexStorageInterface
{
/** @var FileFormatterInterface */
protected $dataFormatter;
/** @var string */
protected $keyField = 'storage_key';
/** @var int */
protected $keyLen = 32;
/** @var bool */
protected $caseSensitive = true;
/**
* @return bool
*/
public function isIndexed(): bool
{
return false;
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::hasKeys()
*/
public function hasKeys(array $keys): array
{
$list = [];
foreach ($keys as $key) {
$list[$key] = $this->hasKey((string)$key);
}
return $list;
}
/**
* {@inheritDoc}
* @see FlexStorageInterface::getKeyField()
*/
public function getKeyField(): string
{
return $this->keyField;
}
/**
* @param array $keys
* @param bool $includeParams
* @return string
*/
public function buildStorageKey(array $keys, bool $includeParams = true): string
{
$key = $keys['key'] ?? '';
$params = $includeParams ? $this->buildStorageKeyParams($keys) : '';
return $params ? "{$key}|{$params}" : $key;
}
/**
* @param array $keys
* @return string
*/
public function buildStorageKeyParams(array $keys): string
{
return '';
}
/**
* @param array $row
* @return array
*/
public function extractKeysFromRow(array $row): array
{
return [
'key' => $this->normalizeKey($row[$this->keyField] ?? '')
];
}
/**
* @param string $key
* @return array
*/
public function extractKeysFromStorageKey(string $key): array
{
return [
'key' => $key
];
}
/**
* @param string|array $formatter
* @return void
*/
protected function initDataFormatter($formatter): void
{
// Initialize formatter.
if (!is_array($formatter)) {
$formatter = ['class' => $formatter];
}
$formatterClassName = $formatter['class'] ?? JsonFormatter::class;
$formatterOptions = $formatter['options'] ?? [];
if (!is_a($formatterClassName, FileFormatterInterface::class, true)) {
throw new \InvalidArgumentException('Bad Data Formatter');
}
$this->dataFormatter = new $formatterClassName($formatterOptions);
}
/**
* @param string $filename
* @return string|null
*/
protected function detectDataFormatter(string $filename): ?string
{
if (preg_match('|(\.[a-z0-9]*)$|ui', $filename, $matches)) {
switch ($matches[1]) {
case '.json':
return JsonFormatter::class;
case '.yaml':
return YamlFormatter::class;
case '.md':
return MarkdownFormatter::class;
}
}
return null;
}
/**
* @param string $filename
* @return CompiledJsonFile|CompiledYamlFile|CompiledMarkdownFile
*/
protected function getFile(string $filename)
{
$filename = $this->resolvePath($filename);
// TODO: start using the new file classes.
switch ($this->dataFormatter->getDefaultFileExtension()) {
case '.json':
$file = CompiledJsonFile::instance($filename);
break;
case '.yaml':
$file = CompiledYamlFile::instance($filename);
break;
case '.md':
$file = CompiledMarkdownFile::instance($filename);
break;
default:
throw new RuntimeException('Unknown extension type ' . $this->dataFormatter->getDefaultFileExtension());
}
return $file;
}
/**
* @param string $path
* @return string
*/
protected function resolvePath(string $path): string
{
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
if (!$locator->isStream($path)) {
return GRAV_ROOT . "/{$path}";
}
return $locator->getResource($path);
}
/**
* Generates a random, unique key for the row.
*
* @return string
*/
protected function generateKey(): string
{
return substr(hash('sha256', random_bytes($this->keyLen)), 0, $this->keyLen);
}
/**
* @param string $key
* @return string
*/
public function normalizeKey(string $key): string
{
if ($this->caseSensitive === true) {
return $key;
}
return mb_strtolower($key);
}
/**
* Checks if a key is valid.
*
* @param string $key
* @return bool
*/
protected function validateKey(string $key): bool
{
return $key && (bool) preg_match('/^[^\\/?*:;{}\\\\\\n]+$/u', $key);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Flex/Storage/SimpleStorage.php | system/src/Grav/Framework/Flex/Storage/SimpleStorage.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Flex\Storage;
use Grav\Common\Data\Data;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Utils;
use Grav\Framework\Filesystem\Filesystem;
use InvalidArgumentException;
use LogicException;
use RuntimeException;
use function is_scalar;
use function is_string;
/**
* Class SimpleStorage
* @package Grav\Framework\Flex\Storage
*/
class SimpleStorage extends AbstractFilesystemStorage
{
/** @var string */
protected $dataFolder;
/** @var string */
protected $dataPattern;
/** @var string|null */
protected $prefix;
/** @var array|null */
protected $data;
/** @var int */
protected $modified = 0;
/**
* {@inheritdoc}
* @see FlexStorageInterface::__construct()
*/
public function __construct(array $options)
{
if (!isset($options['folder'])) {
throw new InvalidArgumentException("Argument \$options is missing 'folder'");
}
$formatter = $options['formatter'] ?? $this->detectDataFormatter($options['folder']);
$this->initDataFormatter($formatter);
$filesystem = Filesystem::getInstance(true);
$extension = $this->dataFormatter->getDefaultFileExtension();
$pattern = Utils::basename($options['folder']);
$this->dataPattern = Utils::basename($pattern, $extension) . $extension;
$this->dataFolder = $filesystem->dirname($options['folder']);
$this->keyField = $options['key'] ?? 'storage_key';
$this->keyLen = (int)($options['key_len'] ?? 32);
$this->prefix = $options['prefix'] ?? null;
// Make sure that the data folder exists.
if (!file_exists($this->dataFolder)) {
try {
Folder::create($this->dataFolder);
} catch (RuntimeException $e) {
throw new RuntimeException(sprintf('Flex: %s', $e->getMessage()));
}
}
}
/**
* @return void
*/
public function clearCache(): void
{
$this->data = null;
$this->modified = 0;
}
/**
* @param string[] $keys
* @param bool $reload
* @return array
*/
public function getMetaData(array $keys, bool $reload = false): array
{
if (null === $this->data || $reload) {
$this->buildIndex();
}
$list = [];
foreach ($keys as $key) {
$list[$key] = $this->getObjectMeta((string)$key);
}
return $list;
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::getExistingKeys()
*/
public function getExistingKeys(): array
{
return $this->buildIndex();
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::hasKey()
*/
public function hasKey(string $key): bool
{
if (null === $this->data) {
$this->buildIndex();
}
return $key && strpos($key, '@@') === false && isset($this->data[$key]);
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::createRows()
*/
public function createRows(array $rows): array
{
if (null === $this->data) {
$this->buildIndex();
}
$list = [];
foreach ($rows as $key => $row) {
$list[$key] = $this->saveRow('@@', $rows);
}
if ($list) {
$this->save();
}
return $list;
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::readRows()
*/
public function readRows(array $rows, array &$fetched = null): array
{
if (null === $this->data) {
$this->buildIndex();
}
$list = [];
foreach ($rows as $key => $row) {
if (null === $row || is_scalar($row)) {
// Only load rows which haven't been loaded before.
$key = (string)$key;
$list[$key] = $this->hasKey($key) ? $this->loadRow($key) : null;
if (null !== $fetched) {
$fetched[$key] = $list[$key];
}
} else {
// Keep the row if it has been loaded.
$list[$key] = $row;
}
}
return $list;
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::updateRows()
*/
public function updateRows(array $rows): array
{
if (null === $this->data) {
$this->buildIndex();
}
$save = false;
$list = [];
foreach ($rows as $key => $row) {
$key = (string)$key;
if ($this->hasKey($key)) {
$list[$key] = $this->saveRow($key, $row);
$save = true;
} else {
$list[$key] = null;
}
}
if ($save) {
$this->save();
}
return $list;
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::deleteRows()
*/
public function deleteRows(array $rows): array
{
if (null === $this->data) {
$this->buildIndex();
}
$list = [];
foreach ($rows as $key => $row) {
$key = (string)$key;
if ($this->hasKey($key)) {
unset($this->data[$key]);
$list[$key] = $row;
}
}
if ($list) {
$this->save();
}
return $list;
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::replaceRows()
*/
public function replaceRows(array $rows): array
{
if (null === $this->data) {
$this->buildIndex();
}
$list = [];
foreach ($rows as $key => $row) {
$list[$key] = $this->saveRow((string)$key, $row);
}
if ($list) {
$this->save();
}
return $list;
}
/**
* @param string $src
* @param string $dst
* @return bool
*/
public function copyRow(string $src, string $dst): bool
{
if ($this->hasKey($dst)) {
throw new RuntimeException("Cannot copy object: key '{$dst}' is already taken");
}
if (!$this->hasKey($src)) {
return false;
}
$this->data[$dst] = $this->data[$src];
return true;
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::renameRow()
*/
public function renameRow(string $src, string $dst): bool
{
if (null === $this->data) {
$this->buildIndex();
}
if ($this->hasKey($dst)) {
throw new RuntimeException("Cannot rename object: key '{$dst}' is already taken");
}
if (!$this->hasKey($src)) {
return false;
}
// Change single key in the array without changing the order or value.
$keys = array_keys($this->data);
$keys[array_search($src, $keys, true)] = $dst;
$data = array_combine($keys, $this->data);
if (false === $data) {
throw new LogicException('Bad data');
}
$this->data = $data;
return true;
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::getStoragePath()
*/
public function getStoragePath(string $key = null): ?string
{
return $this->dataFolder . '/' . $this->dataPattern;
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::getMediaPath()
*/
public function getMediaPath(string $key = null): ?string
{
return null;
}
/**
* Prepares the row for saving and returns the storage key for the record.
*
* @param array $row
*/
protected function prepareRow(array &$row): void
{
unset($row[$this->keyField]);
}
/**
* @param string $key
* @return array
*/
protected function loadRow(string $key): ?array
{
$data = $this->data[$key] ?? [];
if ($this->keyField !== 'storage_key') {
$data[$this->keyField] = $key;
}
$data['__META'] = $this->getObjectMeta($key);
return $data;
}
/**
* @param string $key
* @param array $row
* @return array
*/
protected function saveRow(string $key, array $row): array
{
try {
if (isset($row[$this->keyField])) {
$key = $row[$this->keyField];
}
if (strpos($key, '@@') !== false) {
$key = $this->getNewKey();
}
// Check if the row already exists and if the key has been changed.
$oldKey = $row['__META']['storage_key'] ?? null;
if (is_string($oldKey) && $oldKey !== $key) {
$isCopy = $row['__META']['copy'] ?? false;
if ($isCopy) {
$this->copyRow($oldKey, $key);
} else {
$this->renameRow($oldKey, $key);
}
}
$this->prepareRow($row);
unset($row['__META'], $row['__ERROR']);
$this->data[$key] = $row;
} catch (RuntimeException $e) {
throw new RuntimeException(sprintf('Flex saveRow(%s): %s', $key, $e->getMessage()));
}
$row['__META'] = $this->getObjectMeta($key, true);
return $row;
}
/**
* @param string $key
* @param bool $variations
* @return array
*/
public function parseKey(string $key, bool $variations = true): array
{
return [
'key' => $key,
];
}
protected function save(): void
{
if (null === $this->data) {
$this->buildIndex();
}
try {
$path = $this->getStoragePath();
if (!$path) {
throw new RuntimeException('Storage path is not defined');
}
$file = $this->getFile($path);
if ($this->prefix) {
$data = new Data((array)$file->content());
$content = $data->set($this->prefix, $this->data)->toArray();
} else {
$content = $this->data;
}
$file->save($content);
$this->modified = (int)$file->modified(); // cast false to 0
} catch (RuntimeException $e) {
throw new RuntimeException(sprintf('Flex save(): %s', $e->getMessage()));
} finally {
if (isset($file)) {
$file->free();
unset($file);
}
}
}
/**
* Get key from the filesystem path.
*
* @param string $path
* @return string
*/
protected function getKeyFromPath(string $path): string
{
return Utils::basename($path);
}
/**
* Returns list of all stored keys in [key => timestamp] pairs.
*
* @return array
*/
protected function buildIndex(): array
{
$path = $this->getStoragePath();
if (!$path) {
$this->data = [];
return [];
}
$file = $this->getFile($path);
$this->modified = (int)$file->modified(); // cast false to 0
$content = (array) $file->content();
if ($this->prefix) {
$data = new Data($content);
$content = $data->get($this->prefix, []);
}
$file->free();
unset($file);
$this->data = $content;
$list = [];
foreach ($this->data as $key => $info) {
$list[$key] = $this->getObjectMeta((string)$key);
}
return $list;
}
/**
* @param string $key
* @param bool $reload
* @return array
*/
protected function getObjectMeta(string $key, bool $reload = false): array
{
$modified = isset($this->data[$key]) ? $this->modified : 0;
return [
'storage_key' => $key,
'key' => $key,
'storage_timestamp' => $modified
];
}
/**
* @return string
*/
protected function getNewKey(): string
{
if (null === $this->data) {
$this->buildIndex();
}
// Make sure that the key doesn't exist.
do {
$key = $this->generateKey();
} while (isset($this->data[$key]));
return $key;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.