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/Flex/Storage/FileStorage.php | system/src/Grav/Framework/Flex/Storage/FileStorage.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\Utils;
use Grav\Framework\Flex\Interfaces\FlexStorageInterface;
use RuntimeException;
use SplFileInfo;
/**
* Class FileStorage
* @package Grav\Framework\Flex\Storage
*/
class FileStorage extends FolderStorage
{
/**
* {@inheritdoc}
* @see FlexStorageInterface::__construct()
*/
public function __construct(array $options)
{
$this->dataPattern = '{FOLDER}/{KEY}{EXT}';
if (!isset($options['formatter']) && isset($options['pattern'])) {
$options['formatter'] = $this->detectDataFormatter($options['pattern']);
}
parent::__construct($options);
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::getMediaPath()
*/
public function getMediaPath(string $key = null): ?string
{
$path = $this->getStoragePath();
if (!$path) {
return null;
}
return $key ? "{$path}/{$key}" : $path;
}
/**
* @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;
}
return true;
}
/**
* {@inheritdoc}
* @see FlexStorageInterface::renameRow()
*/
public function renameRow(string $src, string $dst): bool
{
if (!$this->hasKey($src)) {
return false;
}
// Remove old file.
$path = $this->getPathFromKey($src);
$file = $this->getFile($path);
$file->delete();
$file->free();
unset($file);
return true;
}
/**
* @param string $src
* @param string $dst
* @return bool
*/
protected function copyFolder(string $src, string $dst): bool
{
// Nothing to copy.
return true;
}
/**
* @param string $src
* @param string $dst
* @return bool
*/
protected function moveFolder(string $src, string $dst): bool
{
// Nothing to move.
return true;
}
/**
* @param string $key
* @return bool
*/
protected function canDeleteFolder(string $key): bool
{
return false;
}
/**
* {@inheritdoc}
*/
protected function getKeyFromPath(string $path): string
{
return Utils::basename($path, $this->dataFormatter->getDefaultFileExtension());
}
/**
* {@inheritdoc}
*/
protected function buildIndex(): array
{
$this->clearCache();
$path = $this->getStoragePath();
if (!$path || !file_exists($path)) {
return [];
}
$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->isFile() || !($key = $this->getKeyFromPath($filename)) || strpos($info->getFilename(), '.') === 0) {
continue;
}
$list[$key] = $this->getObjectMeta($key);
}
ksort($list, SORT_NATURAL | SORT_FLAG_CASE);
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/Route/Route.php | system/src/Grav/Framework/Route/Route.php | <?php
/**
* @package Grav\Framework\Route
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Route;
use Grav\Framework\Uri\Uri;
use Grav\Framework\Uri\UriFactory;
use InvalidArgumentException;
use function array_slice;
/**
* Implements Grav Route.
*
* @package Grav\Framework\Route
*/
class Route
{
/** @var string */
private $root = '';
/** @var string */
private $language = '';
/** @var string */
private $route = '';
/** @var string */
private $extension = '';
/** @var array */
private $gravParams = [];
/** @var array */
private $queryParams = [];
/**
* You can use `RouteFactory` functions to create new `Route` objects.
*
* @param array $parts
* @throws InvalidArgumentException
*/
public function __construct(array $parts = [])
{
$this->initParts($parts);
}
/**
* @return array
*/
public function getParts()
{
return [
'path' => $this->getUriPath(true),
'query' => $this->getUriQuery(),
'grav' => [
'root' => $this->root,
'language' => $this->language,
'route' => $this->route,
'extension' => $this->extension,
'grav_params' => $this->gravParams,
'query_params' => $this->queryParams,
],
];
}
/**
* @return string
*/
public function getRootPrefix()
{
return $this->root;
}
/**
* @return string
*/
public function getLanguage()
{
return $this->language;
}
/**
* @return string
*/
public function getLanguagePrefix()
{
return $this->language !== '' ? '/' . $this->language : '';
}
/**
* @param string|null $language
* @return string
*/
public function getBase(string $language = null): string
{
$parts = [$this->root];
if (null === $language) {
$language = $this->language;
}
if ($language !== '') {
$parts[] = $language;
}
return implode('/', $parts);
}
/**
* @param int $offset
* @param int|null $length
* @return string
*/
public function getRoute($offset = 0, $length = null)
{
if ($offset !== 0 || $length !== null) {
return ($offset === 0 ? '/' : '') . implode('/', $this->getRouteParts($offset, $length));
}
return '/' . $this->route;
}
/**
* @return string
*/
public function getExtension()
{
return $this->extension;
}
/**
* @param int $offset
* @param int|null $length
* @return array
*/
public function getRouteParts($offset = 0, $length = null)
{
$parts = explode('/', $this->route);
if ($offset !== 0 || $length !== null) {
$parts = array_slice($parts, $offset, $length);
}
return $parts;
}
/**
* Return array of both query and Grav parameters.
*
* If a parameter exists in both, prefer Grav parameter.
*
* @return array
*/
public function getParams()
{
return $this->gravParams + $this->queryParams;
}
/**
* @return array
*/
public function getGravParams()
{
return $this->gravParams;
}
/**
* @return array
*/
public function getQueryParams()
{
return $this->queryParams;
}
/**
* Return value of the parameter, looking into both Grav parameters and query parameters.
*
* If the parameter exists in both, return Grav parameter.
*
* @param string $param
* @return string|array|null
*/
public function getParam($param)
{
return $this->getGravParam($param) ?? $this->getQueryParam($param);
}
/**
* @param string $param
* @return string|null
*/
public function getGravParam($param)
{
return $this->gravParams[$param] ?? null;
}
/**
* @param string $param
* @return string|array|null
*/
public function getQueryParam($param)
{
return $this->queryParams[$param] ?? null;
}
/**
* Allow the ability to set the route to something else
*
* @param string $route
* @return Route
*/
public function withRoute($route)
{
$new = $this->copy();
$new->route = $route;
return $new;
}
/**
* Allow the ability to set the root to something else
*
* @param string $root
* @return Route
*/
public function withRoot($root)
{
$new = $this->copy();
$new->root = $root;
return $new;
}
/**
* @param string|null $language
* @return Route
*/
public function withLanguage($language)
{
$new = $this->copy();
$new->language = $language ?? '';
return $new;
}
/**
* @param string $path
* @return Route
*/
public function withAddedPath($path)
{
$new = $this->copy();
$new->route .= '/' . ltrim($path, '/');
return $new;
}
/**
* @param string $extension
* @return Route
*/
public function withExtension($extension)
{
$new = $this->copy();
$new->extension = $extension;
return $new;
}
/**
* @param string $param
* @param mixed $value
* @return Route
*/
public function withGravParam($param, $value)
{
return $this->withParam('gravParams', $param, null !== $value ? (string)$value : null);
}
/**
* @param string $param
* @param mixed $value
* @return Route
*/
public function withQueryParam($param, $value)
{
return $this->withParam('queryParams', $param, $value);
}
/**
* @return Route
*/
public function withoutParams()
{
return $this->withoutGravParams()->withoutQueryParams();
}
/**
* @return Route
*/
public function withoutGravParams()
{
$new = $this->copy();
$new->gravParams = [];
return $new;
}
/**
* @return Route
*/
public function withoutQueryParams()
{
$new = $this->copy();
$new->queryParams = [];
return $new;
}
/**
* @return Uri
*/
public function getUri()
{
return UriFactory::createFromParts($this->getParts());
}
/**
* @param bool $includeRoot
* @return string
*/
public function toString(bool $includeRoot = false)
{
$url = $this->getUriPath($includeRoot);
if ($this->queryParams) {
$url .= '?' . $this->getUriQuery();
}
return rtrim($url,'/');
}
/**
* @return string
* @deprecated 1.6 Use ->toString(true) or ->getUri() instead.
*/
#[\ReturnTypeWillChange]
public function __toString()
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() will change in the future to return route, not relative url: use ->toString(true) or ->getUri() instead.', E_USER_DEPRECATED);
return $this->toString(true);
}
/**
* @param string $type
* @param string $param
* @param mixed $value
* @return Route
*/
protected function withParam($type, $param, $value)
{
$values = $this->{$type} ?? [];
$oldValue = $values[$param] ?? null;
if ($oldValue === $value) {
return $this;
}
$new = $this->copy();
if ($value === null) {
unset($values[$param]);
} else {
$values[$param] = $value;
}
$new->{$type} = $values;
return $new;
}
/**
* @return Route
*/
protected function copy()
{
return clone $this;
}
/**
* @param bool $includeRoot
* @return string
*/
protected function getUriPath($includeRoot = false)
{
$parts = $includeRoot ? [$this->root] : [''];
if ($this->language !== '') {
$parts[] = $this->language;
}
$parts[] = $this->extension ? $this->route . '.' . $this->extension : $this->route;
if ($this->gravParams) {
$parts[] = RouteFactory::buildParams($this->gravParams);
}
return implode('/', $parts);
}
/**
* @return string
*/
protected function getUriQuery()
{
return UriFactory::buildQuery($this->queryParams);
}
/**
* @param array $parts
* @return void
*/
protected function initParts(array $parts)
{
if (isset($parts['grav'])) {
$gravParts = $parts['grav'];
$this->root = $gravParts['root'];
$this->language = $gravParts['language'];
$this->route = $gravParts['route'];
$this->extension = $gravParts['extension'] ?? '';
$this->gravParams = $gravParts['params'] ?? [];
$this->queryParams = $parts['query_params'] ?? [];
} else {
$this->root = RouteFactory::getRoot();
$this->language = RouteFactory::getLanguage();
$path = $parts['path'] ?? '/';
if (isset($parts['params'])) {
$this->route = trim(rawurldecode($path), '/');
$this->gravParams = $parts['params'];
} else {
$this->route = trim(RouteFactory::stripParams($path, true), '/');
$this->gravParams = RouteFactory::getParams($path);
}
if (isset($parts['query'])) {
$this->queryParams = UriFactory::parseQuery($parts['query']);
}
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Route/RouteFactory.php | system/src/Grav/Framework/Route/RouteFactory.php | <?php
/**
* @package Grav\Framework\Route
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Route;
use Grav\Common\Uri;
use function dirname;
use function strlen;
/**
* Class RouteFactory
* @package Grav\Framework\Route
*/
class RouteFactory
{
/** @var string */
private static $root = '';
/** @var string */
private static $language = '';
/** @var string */
private static $delimiter = ':';
/**
* @param array $parts
* @return Route
*/
public static function createFromParts(array $parts): Route
{
return new Route($parts);
}
/**
* @param Uri $uri
* @return Route
*/
public static function createFromLegacyUri(Uri $uri): Route
{
$parts = $uri->toArray();
$parts += [
'grav' => []
];
$path = $parts['path'] ?? '';
$parts['grav'] += [
'root' => self::$root,
'language' => self::$language,
'route' => trim($path, '/'),
'params' => $parts['params'] ?? [],
];
return static::createFromParts($parts);
}
/**
* @param string $path
* @return Route
*/
public static function createFromString(string $path): Route
{
$path = ltrim($path, '/');
if (self::$language && mb_strpos($path, self::$language) === 0) {
$path = ltrim(mb_substr($path, mb_strlen(self::$language)), '/');
}
$parts = [
'path' => $path,
'query' => '',
'query_params' => [],
'grav' => [
'root' => self::$root,
'language' => self::$language,
'route' => static::trimParams($path),
'params' => static::getParams($path)
],
];
return new Route($parts);
}
/**
* @return string
*/
public static function getRoot(): string
{
return self::$root;
}
/**
* @param string $root
*/
public static function setRoot($root): void
{
self::$root = rtrim($root, '/');
}
/**
* @return string
*/
public static function getLanguage(): string
{
return self::$language;
}
/**
* @param string $language
*/
public static function setLanguage(string $language): void
{
self::$language = trim($language, '/');
}
/**
* @return string
*/
public static function getParamValueDelimiter(): string
{
return self::$delimiter;
}
/**
* @param string $delimiter
*/
public static function setParamValueDelimiter(string $delimiter): void
{
self::$delimiter = $delimiter ?: ':';
}
/**
* @param array $params
* @return string
*/
public static function buildParams(array $params): string
{
if (!$params) {
return '';
}
$delimiter = self::$delimiter;
$output = [];
foreach ($params as $key => $value) {
$output[] = "{$key}{$delimiter}{$value}";
}
return implode('/', $output);
}
/**
* @param string $path
* @param bool $decode
* @return string
*/
public static function stripParams(string $path, bool $decode = false): string
{
$pos = strpos($path, self::$delimiter);
if ($pos === false) {
return $path;
}
$path = dirname(substr($path, 0, $pos));
if ($path === '.') {
return '';
}
return $decode ? rawurldecode($path) : $path;
}
/**
* @param string $path
* @return array
*/
public static function getParams(string $path): array
{
$params = ltrim(substr($path, strlen(static::stripParams($path))), '/');
return $params !== '' ? static::parseParams($params) : [];
}
/**
* @param string $str
* @return string
*/
public static function trimParams(string $str): string
{
if ($str === '') {
return $str;
}
$delimiter = self::$delimiter;
/** @var array $params */
$params = explode('/', $str);
$list = [];
foreach ($params as $param) {
if (mb_strpos($param, $delimiter) === false) {
$list[] = $param;
}
}
return implode('/', $list);
}
/**
* @param string $str
* @return array
*/
public static function parseParams(string $str): array
{
if ($str === '') {
return [];
}
$delimiter = self::$delimiter;
/** @var array $params */
$params = explode('/', $str);
$list = [];
foreach ($params as &$param) {
/** @var array $parts */
$parts = explode($delimiter, $param, 2);
if (isset($parts[1])) {
$var = rawurldecode($parts[0]);
$val = rawurldecode($parts[1]);
$list[$var] = $val;
}
}
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/Media/MediaObject.php | system/src/Grav/Framework/Media/MediaObject.php | <?php declare(strict_types=1);
namespace Grav\Framework\Media;
use Grav\Common\Page\Medium\ImageMedium;
use Grav\Framework\Contracts\Media\MediaObjectInterface;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
use Grav\Framework\Media\Interfaces\MediaObjectInterface as GravMediaObjectInterface;
use Grav\Framework\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Throwable;
/**
* Class MediaObject
*/
class MediaObject implements MediaObjectInterface
{
/** @var string */
static public $placeholderImage = 'image://media/thumb.png';
/** @var FlexObjectInterface */
public $object;
/** @var GravMediaObjectInterface|null */
public $media;
/** @var string|null */
private $field;
/** @var string */
private $filename;
/**
* MediaObject constructor.
* @param string|null $field
* @param string $filename
* @param GravMediaObjectInterface|null $media
* @param FlexObjectInterface $object
*/
public function __construct(?string $field, string $filename, ?GravMediaObjectInterface $media, FlexObjectInterface $object)
{
$this->field = $field;
$this->filename = $filename;
$this->media = $media;
$this->object = $object;
}
/**
* @return string
*/
public function getType(): string
{
return 'media';
}
/**
* @return string
*/
public function getId(): string
{
$field = $this->field;
$object = $this->object;
$path = $field ? "/{$field}/" : '/media/';
return $object->getType() . '/' . $object->getKey() . $path . basename($this->filename);
}
/**
* @return bool
*/
public function exists(): bool
{
return $this->media !== null;
}
/**
* @return array
*/
public function getMeta(): array
{
if (!isset($this->media)) {
return [];
}
return $this->media->getMeta();
}
/**
* @param string $field
* @return mixed|null
*/
public function get(string $field)
{
if (!isset($this->media)) {
return null;
}
return $this->media->get($field);
}
/**
* @return string
*/
public function getUrl(): string
{
if (!isset($this->media)) {
return '';
}
return $this->media->url();
}
/**
* Create media response.
*
* @param array $actions
* @return Response
*/
public function createResponse(array $actions): ResponseInterface
{
if (!isset($this->media)) {
return $this->create404Response($actions);
}
$media = $this->media;
if ($actions) {
$media = $this->processMediaActions($media, $actions);
}
// FIXME: This only works for images
if (!$media instanceof ImageMedium) {
throw new \RuntimeException('Not Implemented', 500);
}
$filename = $media->path(false);
$time = filemtime($filename);
$size = filesize($filename);
$body = fopen($filename, 'rb');
$headers = [
'Content-Type' => $media->get('mime'),
'Last-Modified' => gmdate('D, d M Y H:i:s', $time) . ' GMT',
'ETag' => sprintf('%x-%x', $size, $time)
];
return new Response(200, $headers, $body);
}
/**
* Process media actions
*
* @param GravMediaObjectInterface $medium
* @param array $actions
* @return GravMediaObjectInterface
*/
protected function processMediaActions(GravMediaObjectInterface $medium, array $actions): GravMediaObjectInterface
{
// loop through actions for the image and call them
foreach ($actions as $method => $params) {
$matches = [];
if (preg_match('/\[(.*)]/', $params, $matches)) {
$args = [explode(',', $matches[1])];
} else {
$args = explode(',', $params);
}
try {
$medium->{$method}(...$args);
} catch (Throwable $e) {
// Ignore all errors for now and just skip the action.
}
}
return $medium;
}
/**
* @param array $actions
* @return Response
*/
protected function create404Response(array $actions): Response
{
// Display placeholder image.
$filename = static::$placeholderImage;
$time = filemtime($filename);
$size = filesize($filename);
$body = fopen($filename, 'rb');
$headers = [
'Content-Type' => 'image/svg',
'Last-Modified' => gmdate('D, d M Y H:i:s', $time) . ' GMT',
'ETag' => sprintf('%x-%x', $size, $time)
];
return new Response(404, $headers, $body);
}
/**
* @return array
*/
public function jsonSerialize(): array
{
return [
'type' => $this->getType(),
'id' => $this->getId()
];
}
/**
* @return string[]
*/
public function __debugInfo(): array
{
return $this->jsonSerialize();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Media/MediaIdentifier.php | system/src/Grav/Framework/Media/MediaIdentifier.php | <?php declare(strict_types=1);
namespace Grav\Framework\Media;
use Grav\Common\Grav;
use Grav\Common\User\Interfaces\UserInterface;
use Grav\Framework\Contracts\Media\MediaObjectInterface;
use Grav\Framework\Flex\Flex;
use Grav\Framework\Flex\FlexFormFlash;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
use Grav\Framework\Object\Identifiers\Identifier;
/**
* Interface IdentifierInterface
*
* @template T of MediaObjectInterface
* @extends Identifier<T>
*/
class MediaIdentifier extends Identifier
{
/** @var MediaObjectInterface|null */
private $object = null;
/**
* @param MediaObjectInterface $object
* @return MediaIdentifier<T>
*/
public static function createFromObject(MediaObjectInterface $object): MediaIdentifier
{
$instance = new static($object->getId());
$instance->setObject($object);
return $instance;
}
/**
* @param string $id
*/
public function __construct(string $id)
{
parent::__construct($id, 'media');
}
/**
* @return T
*/
public function getObject(): ?MediaObjectInterface
{
if (!isset($this->object)) {
$type = $this->getType();
$id = $this->getId();
$parts = explode('/', $id);
if ($type === 'media' && str_starts_with($id, 'uploads/')) {
array_shift($parts);
[, $folder, $uniqueId, $field, $filename] = $this->findFlash($parts);
$flash = $this->getFlash($folder, $uniqueId);
if ($flash->exists()) {
$uploadedFile = $flash->getFilesByField($field)[$filename] ?? null;
$this->object = UploadedMediaObject::createFromFlash($flash, $field, $filename, $uploadedFile);
}
} else {
$type = array_shift($parts);
$key = array_shift($parts);
$field = array_shift($parts);
$filename = implode('/', $parts);
$flexObject = $this->getFlexObject($type, $key);
if ($flexObject && method_exists($flexObject, 'getMediaField') && method_exists($flexObject, 'getMedia')) {
$media = $field !== 'media' ? $flexObject->getMediaField($field) : $flexObject->getMedia();
$image = null;
if ($media) {
$image = $media[$filename];
}
$this->object = new MediaObject($field, $filename, $image, $flexObject);
}
}
if (!isset($this->object)) {
throw new \RuntimeException(sprintf('Object not found for identifier {type: "%s", id: "%s"}', $type, $id));
}
}
return $this->object;
}
/**
* @param T $object
*/
public function setObject(MediaObjectInterface $object): void
{
$type = $this->getType();
$objectType = $object->getType();
if ($type !== $objectType) {
throw new \RuntimeException(sprintf('Object has to be type %s, %s given', $type, $objectType));
}
$this->object = $object;
}
protected function findFlash(array $parts): ?array
{
$type = array_shift($parts);
if ($type === 'account') {
/** @var UserInterface|null $user */
$user = Grav::instance()['user'] ?? null;
$folder = $user->getMediaFolder();
} else {
$folder = 'tmp://';
}
if (!$folder) {
return null;
}
do {
$part = array_shift($parts);
$folder .= "/{$part}";
} while (!str_starts_with($part, 'flex-'));
$uniqueId = array_shift($parts);
$field = array_shift($parts);
$filename = implode('/', $parts);
return [$type, $folder, $uniqueId, $field, $filename];
}
protected function getFlash(string $folder, string $uniqueId): FlexFormFlash
{
$config = [
'unique_id' => $uniqueId,
'folder' => $folder
];
return new FlexFormFlash($config);
}
protected function getFlexObject(string $type, string $key): ?FlexObjectInterface
{
/** @var Flex $flex */
$flex = Grav::instance()['flex'];
return $flex->getObject($key, $type);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Media/UploadedMediaObject.php | system/src/Grav/Framework/Media/UploadedMediaObject.php | <?php declare(strict_types=1);
namespace Grav\Framework\Media;
use Grav\Framework\Contracts\Media\MediaObjectInterface;
use Grav\Framework\Flex\FlexFormFlash;
use Grav\Framework\Form\Interfaces\FormFlashInterface;
use Grav\Framework\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UploadedFileInterface;
/**
* Class UploadedMediaObject
*/
class UploadedMediaObject implements MediaObjectInterface
{
/** @var string */
static public $placeholderImage = 'image://media/thumb.png';
/** @var FormFlashInterface */
public $object;
/** @var string */
private $id;
/** @var string|null */
private $field;
/** @var string */
private $filename;
/** @var array */
private $meta;
/** @var UploadedFileInterface|null */
private $uploadedFile;
/**
* @param FlexFormFlash $flash
* @param string|null $field
* @param string $filename
* @param UploadedFileInterface|null $uploadedFile
* @return static
*/
public static function createFromFlash(FlexFormFlash $flash, ?string $field, string $filename, ?UploadedFileInterface $uploadedFile = null)
{
$id = $flash->getId();
return new static($id, $field, $filename, $uploadedFile);
}
/**
* @param string $id
* @param string|null $field
* @param string $filename
* @param UploadedFileInterface|null $uploadedFile
*/
public function __construct(string $id, ?string $field, string $filename, ?UploadedFileInterface $uploadedFile = null)
{
$this->id = $id;
$this->field = $field;
$this->filename = $filename;
$this->uploadedFile = $uploadedFile;
if ($uploadedFile) {
$this->meta = [
'filename' => $uploadedFile->getClientFilename(),
'mime' => $uploadedFile->getClientMediaType(),
'size' => $uploadedFile->getSize()
];
} else {
$this->meta = [];
}
}
/**
* @return string
*/
public function getType(): string
{
return 'media';
}
/**
* @return string
*/
public function getId(): string
{
$id = $this->id;
$field = $this->field;
$path = $field ? "/{$field}/" : '';
return 'uploads/' . $id . $path . basename($this->filename);
}
/**
* @return bool
*/
public function exists(): bool
{
//return $this->uploadedFile !== null;
return false;
}
/**
* @return array
*/
public function getMeta(): array
{
return $this->meta;
}
/**
* @param string $field
* @return mixed|null
*/
public function get(string $field)
{
return $this->meta[$field] ?? null;
}
/**
* @return string
*/
public function getUrl(): string
{
return '';
}
/**
* @return UploadedFileInterface|null
*/
public function getUploadedFile(): ?UploadedFileInterface
{
return $this->uploadedFile;
}
/**
* @param array $actions
* @return Response
*/
public function createResponse(array $actions): ResponseInterface
{
// Display placeholder image.
$filename = static::$placeholderImage;
$time = filemtime($filename);
$size = filesize($filename);
$body = fopen($filename, 'rb');
$headers = [
'Content-Type' => 'image/svg',
'Last-Modified' => gmdate('D, d M Y H:i:s', $time) . ' GMT',
'ETag' => sprintf('%x-%x', $size, $time)
];
return new Response(404, $headers, $body);
}
/**
* @return array
*/
public function jsonSerialize(): array
{
return [
'type' => $this->getType(),
'id' => $this->getId()
];
}
/**
* @return string[]
*/
public function __debugInfo(): array
{
return $this->jsonSerialize();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Media/Interfaces/MediaCollectionInterface.php | system/src/Grav/Framework/Media/Interfaces/MediaCollectionInterface.php | <?php
/**
* @package Grav\Framework\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Media\Interfaces;
use ArrayAccess;
use Countable;
use Iterator;
/**
* Class implements media collection interface.
* @extends ArrayAccess<string,MediaObjectInterface>
* @extends Iterator<string,MediaObjectInterface>
*/
interface MediaCollectionInterface extends ArrayAccess, Countable, Iterator
{
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Media/Interfaces/MediaManipulationInterface.php | system/src/Grav/Framework/Media/Interfaces/MediaManipulationInterface.php | <?php
declare(strict_types=1);
/**
* @package Grav\Framework\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Media\Interfaces;
use Grav\Common\Media\Interfaces\MediaInterface;
use Psr\Http\Message\UploadedFileInterface;
/**
* Interface MediaManipulationInterface
* @package Grav\Framework\Media\Interfaces
* @deprecated 1.7 Not used currently
*/
interface MediaManipulationInterface extends MediaInterface
{
/**
* @param UploadedFileInterface $uploadedFile
*/
public function uploadMediaFile(UploadedFileInterface $uploadedFile): void;
/**
* @param string $filename
*/
public function deleteMediaFile(string $filename): void;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Media/Interfaces/MediaObjectInterface.php | system/src/Grav/Framework/Media/Interfaces/MediaObjectInterface.php | <?php
/**
* @package Grav\Framework\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Media\Interfaces;
use Psr\Http\Message\UploadedFileInterface;
/**
* Class implements media object interface.
*
* @property UploadedFileInterface|null $uploaded_file
*/
interface MediaObjectInterface
{
/**
* Returns an array containing the file metadata
*
* @return array
*/
public function getMeta();
/**
* Return URL to file.
*
* @param bool $reset
* @return string
*/
public function url($reset = true);
/**
* Get value by using dot notation for nested arrays/objects.
*
* @example $value = $this->get('this.is.my.nested.variable');
*
* @param string $name Dot separated path to the requested value.
* @param mixed $default Default value (or null).
* @param string|null $separator Separator, defaults to '.'
* @return mixed Value.
*/
public function get($name, $default = null, $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/Media/Interfaces/MediaInterface.php | system/src/Grav/Framework/Media/Interfaces/MediaInterface.php | <?php
/**
* @package Grav\Framework\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Media\Interfaces;
/**
* Class implements media interface.
*/
interface MediaInterface
{
/**
* Gets the associated media collection.
*
* @return MediaCollectionInterface Collection of associated media.
*/
public function getMedia();
/**
* Get filesystem path to the associated media.
*
* @return string|null Media path or null if the object doesn't have media folder.
*/
public function getMediaFolder();
/**
* Get display order for the associated media.
*
* @return array Empty array means default ordering.
*/
public function getMediaOrder();
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Session/SessionInterface.php | system/src/Grav/Framework/Session/SessionInterface.php | <?php
/**
* @package Grav\Framework\Session
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Session;
use ArrayIterator;
use IteratorAggregate;
use RuntimeException;
/**
* Class Session
* @package Grav\Framework\Session
* @extends IteratorAggregate<array-key,mixed>
*/
interface SessionInterface extends IteratorAggregate
{
/**
* Get current session instance.
*
* @return Session
* @throws RuntimeException
*/
public static function getInstance();
/**
* Get session ID
*
* @return string|null Session ID
*/
public function getId();
/**
* Set session ID
*
* @param string $id Session ID
* @return $this
*/
public function setId($id);
/**
* Get session name
*
* @return string|null
*/
public function getName();
/**
* Set session name
*
* @param string $name
* @return $this
*/
public function setName($name);
/**
* Sets session.* ini variables.
*
* @param array $options
* @return void
* @see http://php.net/session.configuration
*/
public function setOptions(array $options);
/**
* Starts the session storage
*
* @param bool $readonly
* @return $this
* @throws RuntimeException
*/
public function start($readonly = false);
/**
* Invalidates the current session.
*
* @return $this
*/
public function invalidate();
/**
* Force the session to be saved and closed
*
* @return $this
*/
public function close();
/**
* Free all session variables.
*
* @return $this
*/
public function clear();
/**
* Returns all session variables.
*
* @return array
*/
public function getAll();
/**
* Retrieve an external iterator
*
* @return ArrayIterator Return an ArrayIterator of $_SESSION
* @phpstan-return ArrayIterator<array-key,mixed>
*/
#[\ReturnTypeWillChange]
public function getIterator();
/**
* Checks if the session was started.
*
* @return bool
*/
public function isStarted();
/**
* Checks if session variable is defined.
*
* @param string $name
* @return bool
*/
#[\ReturnTypeWillChange]
public function __isset($name);
/**
* Returns session variable.
*
* @param string $name
* @return mixed
*/
#[\ReturnTypeWillChange]
public function __get($name);
/**
* Sets session variable.
*
* @param string $name
* @param mixed $value
* @return void
*/
#[\ReturnTypeWillChange]
public function __set($name, $value);
/**
* Removes session variable.
*
* @param string $name
* @return void
*/
#[\ReturnTypeWillChange]
public function __unset($name);
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Session/Messages.php | system/src/Grav/Framework/Session/Messages.php | <?php
/**
* @package Grav\Framework\Session
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Session;
use Grav\Framework\Compat\Serializable;
use function array_key_exists;
/**
* Implements session messages.
*/
class Messages implements \Serializable
{
use Serializable;
/** @var array */
protected $messages = [];
/** @var bool */
protected $isCleared = false;
/**
* Add message to the queue.
*
* @param string $message
* @param string $scope
* @return $this
*/
public function add(string $message, string $scope = 'default'): Messages
{
$key = md5($scope . '~' . $message);
$item = ['message' => $message, 'scope' => $scope];
// don't add duplicates
if (!array_key_exists($key, $this->messages)) {
$this->messages[$key] = $item;
}
return $this;
}
/**
* Clear message queue.
*
* @param string|null $scope
* @return $this
*/
public function clear(string $scope = null): Messages
{
if ($scope === null) {
if ($this->messages !== []) {
$this->isCleared = true;
$this->messages = [];
}
} else {
foreach ($this->messages as $key => $message) {
if ($message['scope'] === $scope) {
$this->isCleared = true;
unset($this->messages[$key]);
}
}
}
return $this;
}
/**
* @return bool
*/
public function isCleared(): bool
{
return $this->isCleared;
}
/**
* Fetch all messages.
*
* @param string|null $scope
* @return array
*/
public function all(string $scope = null): array
{
if ($scope === null) {
return array_values($this->messages);
}
$messages = [];
foreach ($this->messages as $message) {
if ($message['scope'] === $scope) {
$messages[] = $message;
}
}
return $messages;
}
/**
* Fetch and clear message queue.
*
* @param string|null $scope
* @return array
*/
public function fetch(string $scope = null): array
{
$messages = $this->all($scope);
$this->clear($scope);
return $messages;
}
/**
* @return array
*/
public function __serialize(): array
{
return [
'messages' => $this->messages
];
}
/**
* @param array $data
* @return void
*/
public function __unserialize(array $data): void
{
$this->messages = $data['messages'];
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Session/Session.php | system/src/Grav/Framework/Session/Session.php | <?php
/**
* @package Grav\Framework\Session
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Session;
use ArrayIterator;
use Exception;
use Throwable;
use Grav\Common\Debugger;
use Grav\Common\Grav;
use Grav\Common\User\Interfaces\UserInterface;
use Grav\Framework\Session\Exceptions\SessionException;
use RuntimeException;
use function is_array;
use function is_bool;
use function is_string;
/**
* Class Session
* @package Grav\Framework\Session
*/
class Session implements SessionInterface
{
/** @var array */
protected $options = [];
/** @var bool */
protected $started = false;
/** @var Session */
protected static $instance;
/**
* @inheritdoc
*/
public static function getInstance()
{
if (null === self::$instance) {
throw new RuntimeException("Session hasn't been initialized.", 500);
}
return self::$instance;
}
/**
* Session constructor.
*
* @param array $options
*/
public function __construct(array $options = [])
{
// Session is a singleton.
if (\PHP_SAPI === 'cli') {
self::$instance = $this;
return;
}
if (null !== self::$instance) {
throw new RuntimeException('Session has already been initialized.', 500);
}
// Destroy any existing sessions started with session.auto_start
if ($this->isSessionStarted()) {
session_unset();
session_destroy();
}
// Set default options.
$options += [
'cache_limiter' => 'nocache',
'use_trans_sid' => 0,
'use_cookies' => 1,
'lazy_write' => 1,
'use_strict_mode' => 1
];
$this->setOptions($options);
session_register_shutdown();
self::$instance = $this;
}
/**
* @inheritdoc
*/
public function getId()
{
return session_id() ?: null;
}
/**
* @inheritdoc
*/
public function setId($id)
{
session_id($id);
return $this;
}
/**
* @inheritdoc
*/
public function getName()
{
return session_name() ?: null;
}
/**
* @inheritdoc
*/
public function setName($name)
{
session_name($name);
return $this;
}
/**
* @inheritdoc
*/
public function setOptions(array $options)
{
if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
return;
}
$allowedOptions = [
'save_path' => true,
'name' => true,
'save_handler' => true,
'gc_probability' => true,
'gc_divisor' => true,
'gc_maxlifetime' => true,
'serialize_handler' => true,
'cookie_lifetime' => true,
'cookie_path' => true,
'cookie_domain' => true,
'cookie_secure' => true,
'cookie_httponly' => true,
'use_strict_mode' => true,
'use_cookies' => true,
'use_only_cookies' => true,
'cookie_samesite' => true,
'referer_check' => true,
'cache_limiter' => true,
'cache_expire' => true,
'use_trans_sid' => true,
'trans_sid_tags' => true,
'trans_sid_hosts' => true,
'sid_length' => true,
'sid_bits_per_character' => true,
'upload_progress.enabled' => true,
'upload_progress.cleanup' => true,
'upload_progress.prefix' => true,
'upload_progress.name' => true,
'upload_progress.freq' => true,
'upload_progress.min-freq' => true,
'lazy_write' => true
];
foreach ($options as $key => $value) {
if (is_array($value)) {
// Allow nested options.
foreach ($value as $key2 => $value2) {
$ckey = "{$key}.{$key2}";
if (isset($value2, $allowedOptions[$ckey])) {
$this->setOption($ckey, $value2);
}
}
} elseif (isset($value, $allowedOptions[$key])) {
$this->setOption($key, $value);
}
}
}
/**
* @inheritdoc
*/
public function start($readonly = false)
{
if (\PHP_SAPI === 'cli') {
return $this;
}
$sessionName = $this->getName();
if (null === $sessionName) {
return $this;
}
$sessionExists = isset($_COOKIE[$sessionName]);
// Protection against invalid session cookie names throwing exception: http://php.net/manual/en/function.session-id.php#116836
if ($sessionExists && !preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $_COOKIE[$sessionName])) {
unset($_COOKIE[$sessionName]);
$sessionExists = false;
}
$options = $this->options;
if ($readonly) {
$options['read_and_close'] = '1';
}
try {
$success = @session_start($options);
if (!$success) {
$last = error_get_last();
$error = $last ? $last['message'] : 'Unknown error';
throw new RuntimeException($error);
}
// Handle changing session id.
if ($this->__isset('session_destroyed')) {
$newId = $this->__get('session_new_id');
if (!$newId || $this->__get('session_destroyed') < time() - 300) {
// Should not happen usually. This could be attack or due to unstable network. Destroy this session.
$this->invalidate();
throw new RuntimeException('Obsolete session access.', 500);
}
// Not fully expired yet. Could be lost cookie by unstable network. Start session with new session id.
session_write_close();
// Start session with new session id.
$useStrictMode = $options['use_strict_mode'] ?? 0;
if ($useStrictMode) {
ini_set('session.use_strict_mode', '0');
}
session_id($newId);
if ($useStrictMode) {
ini_set('session.use_strict_mode', '1');
}
$success = @session_start($options);
if (!$success) {
$last = error_get_last();
$error = $last ? $last['message'] : 'Unknown error';
throw new RuntimeException($error);
}
}
} catch (Exception $e) {
throw new SessionException('Failed to start session: ' . $e->getMessage(), 500);
}
$this->started = true;
$this->onSessionStart();
try {
$user = $this->__get('user');
if ($user && (!$user instanceof UserInterface || (method_exists($user, 'isValid') && !$user->isValid()))) {
throw new RuntimeException('Bad user');
}
} catch (Throwable $e) {
$this->invalidate();
throw new SessionException('Invalid User object, session destroyed.', 500);
}
// Extend the lifetime of the session.
if ($sessionExists) {
$this->setCookie();
}
return $this;
}
/**
* Regenerate session id but keep the current session information.
*
* Session id must be regenerated on login, logout or after long time has been passed.
*
* @return $this
* @since 1.7
*/
public function regenerateId()
{
if (!$this->isSessionStarted()) {
return $this;
}
// TODO: session_create_id() segfaults in PHP 7.3 (PHP bug #73461), remove phpstan rule when removing this one.
if (PHP_VERSION_ID < 70400) {
$newId = 0;
} else {
// Session id creation may fail with some session storages.
$newId = @session_create_id() ?: 0;
}
// Set destroyed timestamp for the old session as well as pointer to the new id.
$this->__set('session_destroyed', time());
$this->__set('session_new_id', $newId);
// Keep the old session alive to avoid lost sessions by unstable network.
if (!$newId) {
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$debugger->addMessage('Session fixation lost session detection is turned of due to server limitations.', 'warning');
session_regenerate_id(false);
} else {
session_write_close();
// Start session with new session id.
$useStrictMode = $this->options['use_strict_mode'] ?? 0;
if ($useStrictMode) {
ini_set('session.use_strict_mode', '0');
}
session_id($newId);
if ($useStrictMode) {
ini_set('session.use_strict_mode', '1');
}
$this->removeCookie();
$this->onBeforeSessionStart();
$success = @session_start($this->options);
if (!$success) {
$last = error_get_last();
$error = $last ? $last['message'] : 'Unknown error';
throw new RuntimeException($error);
}
$this->onSessionStart();
}
// New session does not have these.
$this->__unset('session_destroyed');
$this->__unset('session_new_id');
return $this;
}
/**
* @inheritdoc
*/
public function invalidate()
{
$name = $this->getName();
if (null !== $name) {
$this->removeCookie();
setcookie(
$name,
'',
$this->getCookieOptions(-42000)
);
}
if ($this->isSessionStarted()) {
session_unset();
session_destroy();
}
$this->started = false;
return $this;
}
/**
* @inheritdoc
*/
public function close()
{
if ($this->started) {
session_write_close();
}
$this->started = false;
return $this;
}
/**
* @inheritdoc
*/
public function clear()
{
session_unset();
return $this;
}
/**
* @inheritdoc
*/
public function getAll()
{
return $_SESSION;
}
/**
* @inheritdoc
*/
#[\ReturnTypeWillChange]
public function getIterator()
{
return new ArrayIterator($_SESSION);
}
/**
* @inheritdoc
*/
public function isStarted()
{
return $this->started;
}
/**
* @inheritdoc
*/
#[\ReturnTypeWillChange]
public function __isset($name)
{
return isset($_SESSION[$name]);
}
/**
* @inheritdoc
*/
#[\ReturnTypeWillChange]
public function __get($name)
{
return $_SESSION[$name] ?? null;
}
/**
* @inheritdoc
*/
#[\ReturnTypeWillChange]
public function __set($name, $value)
{
$_SESSION[$name] = $value;
}
/**
* @inheritdoc
*/
#[\ReturnTypeWillChange]
public function __unset($name)
{
unset($_SESSION[$name]);
}
/**
* http://php.net/manual/en/function.session-status.php#113468
* Check if session is started nicely.
* @return bool
*/
protected function isSessionStarted()
{
return \PHP_SAPI !== 'cli' ? \PHP_SESSION_ACTIVE === session_status() : false;
}
protected function onBeforeSessionStart(): void
{
}
protected function onSessionStart(): void
{
}
/**
* Store something in cookie temporarily.
*
* @param int|null $lifetime
* @return array
*/
public function getCookieOptions(int $lifetime = null): array
{
$params = session_get_cookie_params();
return [
'expires' => time() + ($lifetime ?? $params['lifetime']),
'path' => $params['path'],
'domain' => $params['domain'],
'secure' => $params['secure'],
'httponly' => $params['httponly'],
'samesite' => $params['samesite']
];
}
/**
* @return void
*/
protected function setCookie(): void
{
$this->removeCookie();
$sessionName = $this->getName();
$sessionId = $this->getId();
if (null === $sessionName || null === $sessionId) {
return;
}
setcookie(
$sessionName,
$sessionId,
$this->getCookieOptions()
);
}
protected function removeCookie(): void
{
$search = " {$this->getName()}=";
$cookies = [];
$found = false;
foreach (headers_list() as $header) {
// Identify cookie headers
if (strpos($header, 'Set-Cookie:') === 0) {
// Add all but session cookie(s).
if (!str_contains($header, $search)) {
$cookies[] = $header;
} else {
$found = true;
}
}
}
// Nothing to do.
if (false === $found) {
return;
}
// Remove all cookies and put back all but session cookie.
header_remove('Set-Cookie');
foreach($cookies as $cookie) {
header($cookie, false);
}
}
/**
* @param string $key
* @param mixed $value
* @return void
*/
protected function setOption($key, $value)
{
if (!is_string($value)) {
if (is_bool($value)) {
$value = $value ? '1' : '0';
} else {
$value = (string)$value;
}
}
$this->options[$key] = $value;
ini_set("session.{$key}", $value);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Framework/Session/Exceptions/SessionException.php | system/src/Grav/Framework/Session/Exceptions/SessionException.php | <?php
/**
* @package Grav\Framework\Session
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Framework\Session\Exceptions;
use RuntimeException;
/**
* Class SessionException
* @package Grav\Framework\Session\Exceptions
*/
class SessionException extends RuntimeException
{
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Installer/VersionUpdate.php | system/src/Grav/Installer/VersionUpdate.php | <?php
namespace Grav\Installer;
use Closure;
use Grav\Common\Utils;
/**
* Class VersionUpdate
* @package Grav\Installer
*/
final class VersionUpdate
{
/** @var string */
private $revision;
/** @var string */
private $version;
/** @var string */
private $date;
/** @var string */
private $patch;
/** @var VersionUpdater */
private $updater;
/** @var callable[] */
private $methods;
public function __construct(string $file, VersionUpdater $updater)
{
$name = basename($file, '.php');
$this->revision = $name;
[$this->version, $this->date, $this->patch] = explode('_', $name);
$this->updater = $updater;
$this->methods = require $file;
}
public function getRevision(): string
{
return $this->revision;
}
public function getVersion(): string
{
return $this->version;
}
public function getDate(): string
{
return $this->date;
}
public function getPatch(): string
{
return $this->patch;
}
public function getUpdater(): VersionUpdater
{
return $this->updater;
}
/**
* Run right before installation.
*/
public function preflight(VersionUpdater $updater): void
{
$method = $this->methods['preflight'] ?? null;
if ($method instanceof Closure) {
$method->call($this);
}
}
/**
* Runs right after installation.
*/
public function postflight(VersionUpdater $updater): void
{
$method = $this->methods['postflight'] ?? null;
if ($method instanceof Closure) {
$method->call($this);
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Installer/Install.php | system/src/Grav/Installer/Install.php | <?php
/**
* @package Grav\Installer
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Installer;
use Composer\Autoload\ClassLoader;
use Exception;
use Grav\Common\Cache;
use Grav\Common\GPM\Installer;
use Grav\Common\Grav;
use Grav\Common\Plugins;
use RuntimeException;
use function class_exists;
use function dirname;
use function function_exists;
use function is_string;
/**
* Grav installer.
*
* NOTE: This class can be initialized during upgrade from an older version of Grav. Make sure it runs there!
*/
final class Install
{
/** @var int Installer version. */
public $version = 1;
/** @var array */
public $requires = [
'php' => [
'name' => 'PHP',
'versions' => [
'8.1' => '8.1.0',
'8.0' => '8.0.0',
'7.4' => '7.4.1',
'7.3' => '7.3.6',
'' => '8.0.13'
]
],
'grav' => [
'name' => 'Grav',
'versions' => [
'1.6' => '1.6.0',
'' => '1.6.28'
]
],
'plugins' => [
'admin' => [
'name' => 'Admin',
'optional' => true,
'versions' => [
'1.9' => '1.9.0',
'' => '1.9.13'
]
],
'email' => [
'name' => 'Email',
'optional' => true,
'versions' => [
'3.0' => '3.0.0',
'' => '3.0.10'
]
],
'form' => [
'name' => 'Form',
'optional' => true,
'versions' => [
'4.1' => '4.1.0',
'4.0' => '4.0.0',
'3.0' => '3.0.0',
'' => '4.1.2'
]
],
'login' => [
'name' => 'Login',
'optional' => true,
'versions' => [
'3.3' => '3.3.0',
'3.0' => '3.0.0',
'' => '3.3.6'
]
],
]
];
/** @var array */
public $ignores = [
'backup',
'cache',
'images',
'logs',
'tmp',
'user',
'.htaccess',
'robots.txt'
];
/** @var array */
private $classMap = [
InstallException::class => __DIR__ . '/InstallException.php',
Versions::class => __DIR__ . '/Versions.php',
VersionUpdate::class => __DIR__ . '/VersionUpdate.php',
VersionUpdater::class => __DIR__ . '/VersionUpdater.php',
YamlUpdater::class => __DIR__ . '/YamlUpdater.php',
];
/** @var string|null */
private $zip;
/** @var string|null */
private $location;
/** @var VersionUpdater|null */
private $updater;
/** @var static */
private static $instance;
/**
* @return static
*/
public static function instance()
{
if (null === self::$instance) {
self::$instance = new static();
}
return self::$instance;
}
private function __construct()
{
}
/**
* @param string|null $zip
* @return $this
*/
public function setZip(?string $zip)
{
$this->zip = $zip;
return $this;
}
/**
* @param string|null $zip
* @return void
*/
#[\ReturnTypeWillChange]
public function __invoke(?string $zip)
{
$this->zip = $zip;
$failedRequirements = $this->checkRequirements();
if ($failedRequirements) {
$error = ['Following requirements have failed:'];
foreach ($failedRequirements as $name => $req) {
$error[] = "{$req['title']} >= <strong>v{$req['minimum']}</strong> required, you have <strong>v{$req['installed']}</strong>";
}
$errors = implode("<br />\n", $error);
if (\defined('GRAV_CLI') && GRAV_CLI) {
$errors = "\n\n" . strip_tags($errors) . "\n\n";
$errors .= <<<ERR
Please install Grav 1.6.31 first by running following commands:
wget -q https://getgrav.org/download/core/grav-update/1.6.31 -O tmp/grav-update-v1.6.31.zip
bin/gpm direct-install -y tmp/grav-update-v1.6.31.zip
rm tmp/grav-update.zip
ERR;
}
throw new RuntimeException($errors);
}
$this->prepare();
$this->install();
$this->finalize();
}
/**
* NOTE: This method can only be called after $grav['plugins']->init().
*
* @return array List of failed requirements. If the list is empty, installation can go on.
*/
public function checkRequirements(): array
{
$results = [];
$this->checkVersion($results, 'php', 'php', $this->requires['php'], PHP_VERSION);
$this->checkVersion($results, 'grav', 'grav', $this->requires['grav'], GRAV_VERSION);
$this->checkPlugins($results, $this->requires['plugins']);
return $results;
}
/**
* @return void
* @throws RuntimeException
*/
public function prepare(): void
{
// Locate the new Grav update and the target site from the filesystem.
$location = realpath(__DIR__);
$target = realpath(GRAV_ROOT . '/index.php');
if (!$location) {
throw new RuntimeException('Internal Error', 500);
}
if ($target && dirname($location, 4) === dirname($target)) {
// We cannot copy files into themselves, abort!
throw new RuntimeException('Grav has already been installed here!', 400);
}
// Load the installer classes.
foreach ($this->classMap as $class_name => $path) {
// Make sure that none of the Grav\Installer classes have been loaded, otherwise installation may fail!
if (class_exists($class_name, false)) {
throw new RuntimeException(sprintf('Cannot update Grav, class %s has already been loaded!', $class_name), 500);
}
require $path;
}
$this->legacySupport();
$this->location = dirname($location, 4);
$versions = Versions::instance(USER_DIR . 'config/versions.yaml');
$this->updater = new VersionUpdater('core/grav', __DIR__ . '/updates', $this->getVersion(), $versions);
$this->updater->preflight();
}
/**
* @return void
* @throws RuntimeException
*/
public function install(): void
{
if (!$this->location) {
throw new RuntimeException('Oops, installer was run without prepare()!', 500);
}
try {
if (null === $this->updater) {
$versions = Versions::instance(USER_DIR . 'config/versions.yaml');
$this->updater = new VersionUpdater('core/grav', __DIR__ . '/updates', $this->getVersion(), $versions);
}
// Update user/config/version.yaml before copying the files to avoid frontend from setting the version schema.
$this->updater->install();
Installer::install(
$this->zip ?? '',
GRAV_ROOT,
['sophisticated' => true, 'overwrite' => true, 'ignore_symlinks' => true, 'ignores' => $this->ignores],
$this->location,
!($this->zip && is_file($this->zip))
);
} catch (Exception $e) {
Installer::setError($e->getMessage());
}
$errorCode = Installer::lastErrorCode();
$success = !(is_string($errorCode) || ($errorCode & (Installer::ZIP_OPEN_ERROR | Installer::ZIP_EXTRACT_ERROR)));
if (!$success) {
throw new RuntimeException(Installer::lastErrorMsg());
}
}
/**
* @return void
* @throws RuntimeException
*/
public function finalize(): void
{
// Finalize can be run without installing Grav first.
if (null === $this->updater) {
$versions = Versions::instance(USER_DIR . 'config/versions.yaml');
$this->updater = new VersionUpdater('core/grav', __DIR__ . '/updates', GRAV_VERSION, $versions);
$this->updater->install();
}
$this->updater->postflight();
Cache::clearCache('all');
clearstatcache();
if (function_exists('opcache_reset')) {
@opcache_reset();
}
}
/**
* @param array $results
* @param string $type
* @param string $name
* @param array $check
* @param string|null $version
* @return void
*/
protected function checkVersion(array &$results, $type, $name, array $check, $version): void
{
if (null === $version && !empty($check['optional'])) {
return;
}
$major = $minor = 0;
$versions = $check['versions'] ?? [];
foreach ($versions as $major => $minor) {
if (!$major || version_compare($version ?? '0', $major, '<')) {
continue;
}
if (version_compare($version ?? '0', $minor, '>=')) {
return;
}
break;
}
if (!$major) {
$minor = reset($versions);
}
$recommended = end($versions);
if (version_compare($recommended, $minor, '<=')) {
$recommended = null;
}
$results[$name] = [
'type' => $type,
'name' => $name,
'title' => $check['name'] ?? $name,
'installed' => $version,
'minimum' => $minor,
'recommended' => $recommended
];
}
/**
* @param array $results
* @param array $plugins
* @return void
*/
protected function checkPlugins(array &$results, array $plugins): void
{
if (!class_exists('Plugins')) {
return;
}
foreach ($plugins as $name => $check) {
$plugin = Plugins::get($name);
if (!$plugin) {
$this->checkVersion($results, 'plugin', $name, $check, null);
continue;
}
$blueprint = $plugin->blueprints();
$version = (string)$blueprint->get('version');
$check['name'] = ($blueprint->get('name') ?? $check['name'] ?? $name) . ' Plugin';
$this->checkVersion($results, 'plugin', $name, $check, $version);
}
}
/**
* @return string
*/
protected function getVersion(): string
{
$definesFile = "{$this->location}/system/defines.php";
$content = file_get_contents($definesFile);
if (false === $content) {
return '';
}
preg_match("/define\('GRAV_VERSION', '([^']+)'\);/mu", $content, $matches);
return $matches[1] ?? '';
}
protected function legacySupport(): void
{
// Support install for Grav 1.6.0 - 1.6.20 by loading the original class from the older version of Grav.
class_exists(\Grav\Console\Cli\CacheCommand::class, true);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Installer/Versions.php | system/src/Grav/Installer/Versions.php | <?php
/**
* @package Grav\Installer
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Installer;
use Symfony\Component\Yaml\Yaml;
use function is_array;
use function is_string;
/**
* Grav Versions
*
* NOTE: This class can be initialized during upgrade from an older version of Grav. Make sure it runs there!
*/
final class Versions
{
/** @var string */
protected $filename;
/** @var array */
protected $items;
/** @var bool */
protected $updated = false;
/** @var self[] */
protected static $instance;
/**
* @param string|null $filename
* @return self
*/
public static function instance(string $filename = null): self
{
$filename = $filename ?? USER_DIR . 'config/versions.yaml';
if (!isset(self::$instance[$filename])) {
self::$instance[$filename] = new self($filename);
}
return self::$instance[$filename];
}
/**
* @return bool True if the file was updated.
*/
public function save(): bool
{
if (!$this->updated) {
return false;
}
file_put_contents($this->filename, Yaml::dump($this->items, 4, 2));
$this->updated = false;
return true;
}
/**
* @return array
*/
public function getAll(): array
{
return $this->items;
}
/**
* @return array|null
*/
public function getGrav(): ?array
{
return $this->get('core/grav');
}
/**
* @return array
*/
public function getPlugins(): array
{
return $this->get('plugins', []);
}
/**
* @param string $name
* @return array|null
*/
public function getPlugin(string $name): ?array
{
return $this->get("plugins/{$name}");
}
/**
* @return array
*/
public function getThemes(): array
{
return $this->get('themes', []);
}
/**
* @param string $name
* @return array|null
*/
public function getTheme(string $name): ?array
{
return $this->get("themes/{$name}");
}
/**
* @param string $extension
* @return array|null
*/
public function getExtension(string $extension): ?array
{
return $this->get($extension);
}
/**
* @param string $extension
* @param array|null $value
*/
public function setExtension(string $extension, ?array $value): void
{
if (null !== $value) {
$this->set($extension, $value);
} else {
$this->undef($extension);
}
}
/**
* @param string $extension
* @return string|null
*/
public function getVersion(string $extension): ?string
{
$version = $this->get("{$extension}/version", null);
return is_string($version) ? $version : null;
}
/**
* @param string $extension
* @param string|null $version
*/
public function setVersion(string $extension, ?string $version): void
{
$this->updateHistory($extension, $version);
}
/**
* NOTE: Updates also history.
*
* @param string $extension
* @param string|null $version
*/
public function updateVersion(string $extension, ?string $version): void
{
$this->set("{$extension}/version", $version);
$this->updateHistory($extension, $version);
}
/**
* @param string $extension
* @return string|null
*/
public function getSchema(string $extension): ?string
{
$version = $this->get("{$extension}/schema", null);
return is_string($version) ? $version : null;
}
/**
* @param string $extension
* @param string|null $schema
*/
public function setSchema(string $extension, ?string $schema): void
{
if (null !== $schema) {
$this->set("{$extension}/schema", $schema);
} else {
$this->undef("{$extension}/schema");
}
}
/**
* @param string $extension
* @return array
*/
public function getHistory(string $extension): array
{
$name = "{$extension}/history";
$history = $this->get($name, []);
// Fix for broken Grav 1.6 history
if ($extension === 'grav') {
$history = $this->fixHistory($history);
}
return $history;
}
/**
* @param string $extension
* @param string|null $version
*/
public function updateHistory(string $extension, ?string $version): void
{
$name = "{$extension}/history";
$history = $this->getHistory($extension);
$history[] = ['version' => $version, 'date' => gmdate('Y-m-d H:i:s')];
$this->set($name, $history);
}
/**
* Clears extension history. Useful when creating skeletons.
*
* @param string $extension
*/
public function removeHistory(string $extension): void
{
$this->undef("{$extension}/history");
}
/**
* @param array $history
* @return array
*/
private function fixHistory(array $history): array
{
if (isset($history['version'], $history['date'])) {
$fix = [['version' => $history['version'], 'date' => $history['date']]];
unset($history['version'], $history['date']);
$history = array_merge($fix, $history);
}
return $history;
}
/**
* Get value by using dot notation for nested arrays/objects.
*
* @param string $name Slash separated path to the requested value.
* @param mixed $default Default value (or null).
* @return mixed Value.
*/
private function get(string $name, $default = null)
{
$path = explode('/', $name);
$current = $this->items;
foreach ($path as $field) {
if (is_array($current) && isset($current[$field])) {
$current = $current[$field];
} else {
return $default;
}
}
return $current;
}
/**
* Set value by using dot notation for nested arrays/objects.
*
* @param string $name Slash separated path to the requested value.
* @param mixed $value New value.
*/
private function set(string $name, $value): void
{
$path = explode('/', $name);
$current = &$this->items;
foreach ($path as $field) {
// Handle arrays and scalars.
if (!is_array($current)) {
$current = [$field => []];
} elseif (!isset($current[$field])) {
$current[$field] = [];
}
$current = &$current[$field];
}
$current = $value;
$this->updated = true;
}
/**
* Unset value by using dot notation for nested arrays/objects.
*
* @param string $name Dot separated path to the requested value.
*/
private function undef(string $name): void
{
$path = $name !== '' ? explode('/', $name) : [];
if (!$path) {
return;
}
$var = array_pop($path);
$current = &$this->items;
foreach ($path as $field) {
if (!is_array($current) || !isset($current[$field])) {
return;
}
$current = &$current[$field];
}
unset($current[$var]);
$this->updated = true;
}
private function __construct(string $filename)
{
$this->filename = $filename;
$content = is_file($filename) ? file_get_contents($filename) : null;
if (false === $content) {
throw new \RuntimeException('Versions file cannot be read');
}
$this->items = $content ? Yaml::parse($content) : [];
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Installer/InstallException.php | system/src/Grav/Installer/InstallException.php | <?php
/**
* @package Grav\Installer
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Installer;
use Throwable;
/**
* Class InstallException
* @package Grav\Installer
*/
class InstallException extends \RuntimeException
{
/**
* InstallException constructor.
* @param string $message
* @param Throwable $previous
*/
public function __construct(string $message, Throwable $previous)
{
parent::__construct($message, $previous->getCode(), $previous);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Installer/YamlUpdater.php | system/src/Grav/Installer/YamlUpdater.php | <?php
/**
* @package Grav\Installer
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Installer;
use Grav\Common\Utils;
use Symfony\Component\Yaml\Yaml;
use function assert;
use function count;
use function is_array;
use function strlen;
/**
* Grav YAML updater.
*
* NOTE: This class can be initialized during upgrade from an older version of Grav. Make sure it runs there!
*/
final class YamlUpdater
{
/** @var string */
protected $filename;
/** @var string[] */
protected $lines;
/** @var array */
protected $comments;
/** @var array */
protected $items;
/** @var bool */
protected $updated = false;
/** @var self[] */
protected static $instance;
public static function instance(string $filename): self
{
if (!isset(self::$instance[$filename])) {
self::$instance[$filename] = new self($filename);
}
return self::$instance[$filename];
}
/**
* @return bool
*/
public function save(): bool
{
if (!$this->updated) {
return false;
}
try {
if (!$this->isHandWritten()) {
$yaml = Yaml::dump($this->items, 5, 2);
} else {
$yaml = implode("\n", $this->lines);
$items = Yaml::parse($yaml);
if ($items !== $this->items) {
throw new \RuntimeException('Failed saving the content');
}
}
file_put_contents($this->filename, $yaml);
} catch (\Exception $e) {
throw new \RuntimeException('Failed to update ' . basename($this->filename) . ': ' . $e->getMessage());
}
return true;
}
/**
* @return bool
*/
public function isHandWritten(): bool
{
return !empty($this->comments);
}
/**
* @return array
*/
public function getComments(): array
{
$comments = [];
foreach ($this->lines as $i => $line) {
if ($this->isLineEmpty($line)) {
$comments[$i+1] = $line;
} elseif ($comment = $this->getInlineComment($line)) {
$comments[$i+1] = $comment;
}
}
return $comments;
}
/**
* @param string $variable
* @param mixed $value
*/
public function define(string $variable, $value): void
{
// If variable has already value, we're good.
if ($this->get($variable) !== null) {
return;
}
// If one of the parents isn't array, we're good, too.
if (!$this->canDefine($variable)) {
return;
}
$this->set($variable, $value);
if (!$this->isHandWritten()) {
return;
}
$parts = explode('.', $variable);
$lineNos = $this->findPath($this->lines, $parts);
$count = count($lineNos);
$last = array_key_last($lineNos);
$value = explode("\n", trim(Yaml::dump([$last => $this->get(implode('.', array_keys($lineNos)))], max(0, 5-$count), 2)));
$currentLine = array_pop($lineNos) ?: 0;
$parentLine = array_pop($lineNos);
if ($parentLine !== null) {
$c = $this->getLineIndentation($this->lines[$parentLine] ?? '');
$n = $this->getLineIndentation($this->lines[$parentLine+1] ?? $this->lines[$parentLine] ?? '');
$indent = $n > $c ? $n : $c + 2;
} else {
$indent = 0;
array_unshift($value, '');
}
$spaces = str_repeat(' ', $indent);
foreach ($value as &$line) {
$line = $spaces . $line;
}
unset($line);
array_splice($this->lines, abs($currentLine)+1, 0, $value);
}
public function undefine(string $variable): void
{
// If variable does not have value, we're good.
if ($this->get($variable) === null) {
return;
}
// If one of the parents isn't array, we're good, too.
if (!$this->canDefine($variable)) {
return;
}
$this->undef($variable);
if (!$this->isHandWritten()) {
return;
}
// TODO: support also removing property from handwritten configuration file.
}
private function __construct(string $filename)
{
$content = is_file($filename) ? (string)file_get_contents($filename) : '';
$content = rtrim(str_replace(["\r\n", "\r"], "\n", $content));
$this->filename = $filename;
$this->lines = explode("\n", $content);
$this->comments = $this->getComments();
$this->items = $content ? Yaml::parse($content) : [];
}
/**
* Return array of offsets for the parent nodes. Negative value means position, but not found.
*
* @param array $lines
* @param array $parts
* @return int[]
*/
private function findPath(array $lines, array $parts)
{
$test = true;
$indent = -1;
$current = array_shift($parts);
$j = 1;
$found = [];
$space = '';
foreach ($lines as $i => $line) {
if ($this->isLineEmpty($line)) {
if ($this->isLineComment($line) && $this->getLineIndentation($line) > $indent) {
$j = $i;
}
continue;
}
if ($test === true) {
$test = false;
$spaces = strlen($line) - strlen(ltrim($line, ' '));
if ($spaces <= $indent) {
$found[$current] = -$j;
return $found;
}
$indent = $spaces;
$space = $indent ? str_repeat(' ', $indent) : '';
}
if (0 === \strncmp($line, $space, strlen($space))) {
$pattern = "/^{$space}(['\"]?){$current}\\1\:/";
if (preg_match($pattern, $line)) {
$found[$current] = $i;
$current = array_shift($parts);
if ($current === null) {
return $found;
}
$test = true;
}
} else {
$found[$current] = -$j;
return $found;
}
$j = $i;
}
$found[$current] = -$j;
return $found;
}
/**
* Returns true if the current line is blank or if it is a comment line.
*
* @param string $line Contents of the line
* @return bool Returns true if the current line is empty or if it is a comment line, false otherwise
*/
private function isLineEmpty(string $line): bool
{
return $this->isLineBlank($line) || $this->isLineComment($line);
}
/**
* Returns true if the current line is blank.
*
* @param string $line Contents of the line
* @return bool Returns true if the current line is blank, false otherwise
*/
private function isLineBlank(string $line): bool
{
return '' === trim($line, ' ');
}
/**
* Returns true if the current line is a comment line.
*
* @param string $line Contents of the line
* @return bool Returns true if the current line is a comment line, false otherwise
*/
private function isLineComment(string $line): bool
{
//checking explicitly the first char of the trim is faster than loops or strpos
$ltrimmedLine = ltrim($line, ' ');
return '' !== $ltrimmedLine && '#' === $ltrimmedLine[0];
}
/**
* @param string $line
* @return bool
*/
private function isInlineComment(string $line): bool
{
return $this->getInlineComment($line) !== null;
}
/**
* @param string $line
* @return string|null
*/
private function getInlineComment(string $line): ?string
{
$pos = strpos($line, ' #');
if (false === $pos) {
return null;
}
$parts = explode(' #', $line);
$part = '';
while ($part .= array_shift($parts)) {
// Remove quoted values.
$part = preg_replace('/(([\'"])[^\2]*\2)/', '', $part);
assert(null !== $part);
$part = preg_split('/[\'"]/', $part, 2);
assert(false !== $part);
if (!isset($part[1])) {
$part = $part[0];
array_unshift($parts, str_repeat(' ', strlen($part) - strlen(trim($part, ' '))));
break;
}
$part = $part[1];
}
return implode(' #', $parts);
}
/**
* Returns the current line indentation.
*
* @param string $line
* @return int The current line indentation
*/
private function getLineIndentation(string $line): int
{
return \strlen($line) - \strlen(ltrim($line, ' '));
}
/**
* Get value by using dot notation for nested arrays/objects.
*
* @param string $name Dot separated path to the requested value.
* @param mixed $default Default value (or null).
* @return mixed Value.
*/
private function get(string $name, $default = null)
{
$path = explode('.', $name);
$current = $this->items;
foreach ($path as $field) {
if (is_array($current) && isset($current[$field])) {
$current = $current[$field];
} else {
return $default;
}
}
return $current;
}
/**
* Set value by using dot notation for nested arrays/objects.
*
* @param string $name Dot separated path to the requested value.
* @param mixed $value New value.
*/
private function set(string $name, $value): void
{
$path = explode('.', $name);
$current = &$this->items;
foreach ($path as $field) {
// Handle arrays and scalars.
if (!is_array($current)) {
$current = [$field => []];
} elseif (!isset($current[$field])) {
$current[$field] = [];
}
$current = &$current[$field];
}
$current = $value;
$this->updated = true;
}
/**
* Unset value by using dot notation for nested arrays/objects.
*
* @param string $name Dot separated path to the requested value.
*/
private function undef(string $name): void
{
$path = $name !== '' ? explode('.', $name) : [];
if (!$path) {
return;
}
$var = array_pop($path);
$current = &$this->items;
foreach ($path as $field) {
if (!is_array($current) || !isset($current[$field])) {
return;
}
$current = &$current[$field];
}
unset($current[$var]);
$this->updated = true;
}
/**
* Get value by using dot notation for nested arrays/objects.
*
* @param string $name Dot separated path to the requested value.
* @return bool
*/
private function canDefine(string $name): bool
{
$path = explode('.', $name);
$current = $this->items;
foreach ($path as $field) {
if (is_array($current)) {
if (!isset($current[$field])) {
return true;
}
$current = $current[$field];
} else {
return false;
}
}
return true;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Installer/VersionUpdater.php | system/src/Grav/Installer/VersionUpdater.php | <?php
namespace Grav\Installer;
use DirectoryIterator;
/**
* Class VersionUpdater
* @package Grav\Installer
*/
final class VersionUpdater
{
/** @var string */
private $name;
/** @var string */
private $path;
/** @var string */
private $version;
/** @var Versions */
private $versions;
/** @var VersionUpdate[] */
private $updates;
/**
* VersionUpdater constructor.
* @param string $name
* @param string $path
* @param string $version
* @param Versions $versions
*/
public function __construct(string $name, string $path, string $version, Versions $versions)
{
$this->name = $name;
$this->path = $path;
$this->version = $version;
$this->versions = $versions;
$this->loadUpdates();
}
/**
* Pre-installation method.
*/
public function preflight(): void
{
foreach ($this->updates as $revision => $update) {
$update->preflight($this);
}
}
/**
* Install method.
*/
public function install(): void
{
$versions = $this->getVersions();
$versions->updateVersion($this->name, $this->version);
$versions->save();
}
/**
* Post-installation method.
*/
public function postflight(): void
{
$versions = $this->getVersions();
foreach ($this->updates as $revision => $update) {
$update->postflight($this);
$versions->setSchema($this->name, $revision);
$versions->save();
}
}
/**
* @return Versions
*/
public function getVersions(): Versions
{
return $this->versions;
}
/**
* @param string|null $name
* @return string|null
*/
public function getExtensionVersion(string $name = null): ?string
{
return $this->versions->getVersion($name ?? $this->name);
}
/**
* @param string|null $name
* @return string|null
*/
public function getExtensionSchema(string $name = null): ?string
{
return $this->versions->getSchema($name ?? $this->name);
}
/**
* @param string|null $name
* @return array
*/
public function getExtensionHistory(string $name = null): array
{
return $this->versions->getHistory($name ?? $this->name);
}
protected function loadUpdates(): void
{
$this->updates = [];
$schema = $this->getExtensionSchema();
$iterator = new DirectoryIterator($this->path);
foreach ($iterator as $item) {
if (!$item->isFile() || $item->getExtension() !== 'php') {
continue;
}
$revision = $item->getBasename('.php');
if (!$schema || version_compare($revision, $schema, '>')) {
$realPath = $item->getRealPath();
if ($realPath) {
$this->updates[$revision] = new VersionUpdate($realPath, $this);
}
}
}
uksort($this->updates, 'version_compare');
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Installer/updates/1.7.0_2020-11-20_1.php | system/src/Grav/Installer/updates/1.7.0_2020-11-20_1.php | <?php
use Grav\Installer\InstallException;
use Grav\Installer\VersionUpdate;
use Grav\Installer\YamlUpdater;
return [
'preflight' => null,
'postflight' =>
function () {
/** @var VersionUpdate $this */
try {
// Keep old defaults for backwards compatibility.
$yaml = YamlUpdater::instance(GRAV_ROOT . '/user/config/system.yaml');
$yaml->define('twig.autoescape', false);
$yaml->define('strict_mode.yaml_compat', true);
$yaml->define('strict_mode.twig_compat', true);
$yaml->define('strict_mode.blueprint_compat', true);
$yaml->save();
} catch (\Exception $e) {
throw new InstallException('Could not update system configuration to maintain backwards compatibility', $e);
}
}
];
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Events/SessionStartEvent.php | system/src/Grav/Events/SessionStartEvent.php | <?php
/**
* @package Grav\Events
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Events;
use Grav\Framework\Session\SessionInterface;
use Symfony\Contracts\EventDispatcher\Event;
/**
* Plugins Loaded Event
*
* This event is called from $grav['session']->start() right after successful session_start() call.
*
* @property SessionInterface $session Session instance.
*/
class SessionStartEvent extends Event
{
/** @var SessionInterface */
public $session;
public function __construct(SessionInterface $session)
{
$this->session = $session;
}
public function __debugInfo(): array
{
return (array)$this;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Events/PluginsLoadedEvent.php | system/src/Grav/Events/PluginsLoadedEvent.php | <?php
/**
* @package Grav\Events
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Events;
use Grav\Common\Grav;
use Grav\Common\Plugins;
use Symfony\Contracts\EventDispatcher\Event;
/**
* Plugins Loaded Event
*
* This event is called from InitializeProcessor.
*
* This is the first event plugin can see. Please avoid using this event if possible.
*
* @property Grav $grav Grav container.
* @property Plugins $plugins Plugins instance.
*/
class PluginsLoadedEvent extends Event
{
/** @var Grav */
public $grav;
/** @var Plugins */
public $plugins;
/**
* PluginsLoadedEvent constructor.
* @param Grav $grav
* @param Plugins $plugins
*/
public function __construct(Grav $grav, Plugins $plugins)
{
$this->grav = $grav;
$this->plugins = $plugins;
}
/**
* @return array
*/
public function __debugInfo(): array
{
return [
'plugins' => $this->plugins
];
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Events/PermissionsRegisterEvent.php | system/src/Grav/Events/PermissionsRegisterEvent.php | <?php
/**
* @package Grav\Events
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Events;
use Grav\Framework\Acl\Permissions;
use Symfony\Contracts\EventDispatcher\Event;
/**
* Permissions Register Event
*
* This event is called the first time $grav['permissions'] is being called.
*
* Use this event to register any new permission types you use in your plugins.
*
* @property Permissions $permissions Permissions instance.
*/
class PermissionsRegisterEvent extends Event
{
/** @var Permissions */
public $permissions;
/**
* PermissionsRegisterEvent constructor.
* @param Permissions $permissions
*/
public function __construct(Permissions $permissions)
{
$this->permissions = $permissions;
}
/**
* @return array
*/
public function __debugInfo(): array
{
return (array)$this;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Events/TypesEvent.php | system/src/Grav/Events/TypesEvent.php | <?php
/**
* @package Grav\Events
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Events;
use Grav\Framework\Flex\Flex;
use RocketTheme\Toolbox\Event\Event;
class TypesEvent extends Event
{
public $types;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Events/PageEvent.php | system/src/Grav/Events/PageEvent.php | <?php
/**
* @package Grav\Events
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Events;
use Grav\Framework\Flex\Flex;
use RocketTheme\Toolbox\Event\Event;
class PageEvent extends Event
{
public $page;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Events/FlexRegisterEvent.php | system/src/Grav/Events/FlexRegisterEvent.php | <?php
/**
* @package Grav\Events
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Events;
use Grav\Framework\Flex\Flex;
use Symfony\Contracts\EventDispatcher\Event;
/**
* Flex Register Event
*
* This event is called the first time $grav['flex'] is being called.
*
* Use this event to register enabled Directories to Flex.
*
* @property Flex $flex Flex instance.
*/
class FlexRegisterEvent extends Event
{
/** @var Flex */
public $flex;
/**
* FlexRegisterEvent constructor.
* @param Flex $flex
*/
public function __construct(Flex $flex)
{
$this->flex = $flex;
}
/**
* @return array
*/
public function __debugInfo(): array
{
return (array)$this;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Events/BeforeSessionStartEvent.php | system/src/Grav/Events/BeforeSessionStartEvent.php | <?php
/**
* @package Grav\Events
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Events;
use Grav\Framework\Session\SessionInterface;
use Symfony\Contracts\EventDispatcher\Event;
/**
* Plugins Loaded Event
*
* This event is called from $grav['session']->start() right before session_start() call.
*
* @property SessionInterface $session Session instance.
*/
class BeforeSessionStartEvent extends Event
{
/** @var SessionInterface */
public $session;
public function __construct(SessionInterface $session)
{
$this->session = $session;
}
public function __debugInfo(): array
{
return (array)$this;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/_bootstrap.php | tests/_bootstrap.php | <?php
namespace Grav;
use Codeception\Util\Fixtures;
use Faker\Factory;
use Grav\Common\Grav;
ini_set('error_log', __DIR__ . '/error.log');
$grav = function () {
Grav::resetInstance();
$grav = Grav::instance();
$grav['config']->init();
// This must be set first before the other init
$grav['config']->set('system.languages.supported', ['en', 'fr', 'vi']);
$grav['config']->set('system.languages.default_lang', 'en');
foreach (array_keys($grav['setup']->getStreams()) as $stream) {
@stream_wrapper_unregister($stream);
}
$grav['streams'];
$grav['uri']->init();
$grav['debugger']->init();
$grav['assets']->init();
$grav['config']->set('system.cache.enabled', false);
$grav['locator']->addPath('tests', '', 'tests', false);
return $grav;
};
Fixtures::add('grav', $grav);
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/phpstan/phpstan-bootstrap.php | tests/phpstan/phpstan-bootstrap.php | <?php declare(strict_types=1);
/**
*To help phpstan dealing with LogicException in Common\User\User.php
*/
define('GRAV_USER_INSTANCE', 'FLEX');
define('GRAV_REQUEST_TIME', microtime(true));
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/phpstan/plugins-bootstrap.php | tests/phpstan/plugins-bootstrap.php | <?php
use Grav\Common\Grav;
use Grav\Common\Plugin;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
\define('GRAV_CLI', true);
\define('GRAV_REQUEST_TIME', microtime(true));
\define('GRAV_USER_INSTANCE', 'FLEX');
$autoload = require __DIR__ . '/../../vendor/autoload.php';
if (!ini_get('date.timezone')) {
date_default_timezone_set('UTC');
}
if (!file_exists(GRAV_ROOT . '/index.php')) {
exit('FATAL: Must be run from ROOT directory of Grav!');
}
$grav = Grav::instance(['loader' => $autoload]);
$grav->setup('tests');
$grav['config']->init();
// Find all plugins in Grav installation and autoload their classes.
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$iterator = $locator->getIterator('plugins://');
/** @var DirectoryIterator $directory */
foreach ($iterator as $directory) {
if (!$directory->isDir()) {
continue;
}
$plugin = $directory->getBasename();
$file = $directory->getPathname() . '/' . $plugin . '.php';
$classloader = null;
if (file_exists($file)) {
require_once $file;
$pluginClass = "\\Grav\\Plugin\\{$plugin}Plugin";
if (is_subclass_of($pluginClass, Plugin::class, true)) {
$class = new $pluginClass($plugin, $grav);
if (is_callable([$class, 'autoload'])) {
$classloader = $class->autoload();
}
}
}
if (null === $classloader) {
$autoloader = $directory->getPathname() . '/vendor/autoload.php';
if (file_exists($autoloader)) {
require $autoloader;
}
}
}
define('GANTRY_DEBUGGER', true);
define('GANTRY5_DEBUG', true);
define('GANTRY5_PLATFORM', 'grav');
define('GANTRY5_ROOT', GRAV_ROOT);
define('GANTRY5_VERSION', '@version@');
define('GANTRY5_VERSION_DATE', '@versiondate@');
define('GANTRYADMIN_PATH', '');
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/phpstan/classes/Toolbox/UniformResourceLocatorExtension.php | tests/phpstan/classes/Toolbox/UniformResourceLocatorExtension.php | <?php
namespace PHPStan\Toolbox;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Type\DynamicMethodReturnTypeExtension;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
/**
* Extension to handle UniformResourceLocator return types.
*/
class UniformResourceLocatorExtension implements DynamicMethodReturnTypeExtension
{
/**
* @return string
*/
public function getClass(): string
{
return UniformResourceLocator::class;
}
/**
* @param MethodReflection $methodReflection
* @return bool
*/
public function isMethodSupported(MethodReflection $methodReflection): bool
{
return $methodReflection->getName() === 'findResource';
}
/**
* @param MethodReflection $methodReflection
* @param MethodCall $methodCall
* @param Scope $scope
* @return Type
*/
public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): Type
{
$first = $methodCall->getArgs()[2] ?? false;
if ($first) {
return new StringType();
}
return ParametersAcceptorSelector::selectSingle($methodReflection->getVariants())->getReturnType();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/acceptance/_bootstrap.php | tests/acceptance/_bootstrap.php | <?php
// Here you can initialize variables that will be available to your tests
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/unit/_bootstrap.php | tests/unit/_bootstrap.php | <?php
// Here you can initialize variables that will be available to your tests
define('GRAV_CLI', true);
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/unit/Grav/Common/InflectorTest.php | tests/unit/Grav/Common/InflectorTest.php | <?php
use Codeception\Util\Fixtures;
use Grav\Common\Grav;
use Grav\Common\Inflector;
use Grav\Common\Utils;
/**
* Class InflectorTest
*/
class InflectorTest extends \Codeception\TestCase\Test
{
/** @var Grav $grav */
protected $grav;
/** @var Inflector $uri */
protected $inflector;
protected function _before(): void
{
$grav = Fixtures::get('grav');
$this->grav = $grav();
$this->inflector = $this->grav['inflector'];
}
protected function _after(): void
{
}
public function testPluralize(): void
{
self::assertSame('words', $this->inflector->pluralize('word'));
self::assertSame('kisses', $this->inflector->pluralize('kiss'));
self::assertSame('volcanoes', $this->inflector->pluralize('volcanoe'));
self::assertSame('cherries', $this->inflector->pluralize('cherry'));
self::assertSame('days', $this->inflector->pluralize('day'));
self::assertSame('knives', $this->inflector->pluralize('knife'));
}
public function testSingularize(): void
{
self::assertSame('word', $this->inflector->singularize('words'));
self::assertSame('kiss', $this->inflector->singularize('kisses'));
self::assertSame('volcanoe', $this->inflector->singularize('volcanoe'));
self::assertSame('cherry', $this->inflector->singularize('cherries'));
self::assertSame('day', $this->inflector->singularize('days'));
self::assertSame('knife', $this->inflector->singularize('knives'));
}
public function testTitleize(): void
{
self::assertSame('This String Is Titleized', $this->inflector->titleize('ThisStringIsTitleized'));
self::assertSame('This String Is Titleized', $this->inflector->titleize('this string is titleized'));
self::assertSame('This String Is Titleized', $this->inflector->titleize('this_string_is_titleized'));
self::assertSame('This String Is Titleized', $this->inflector->titleize('this-string-is-titleized'));
self::assertSame('Échelle Synoptique', $this->inflector->titleize('échelle synoptique'));
self::assertSame('This string is titleized', $this->inflector->titleize('ThisStringIsTitleized', 'first'));
self::assertSame('This string is titleized', $this->inflector->titleize('this string is titleized', 'first'));
self::assertSame('This string is titleized', $this->inflector->titleize('this_string_is_titleized', 'first'));
self::assertSame('This string is titleized', $this->inflector->titleize('this-string-is-titleized', 'first'));
self::assertSame('Échelle synoptique', $this->inflector->titleize('échelle synoptique', 'first'));
}
public function testCamelize(): void
{
self::assertSame('ThisStringIsCamelized', $this->inflector->camelize('This String Is Camelized'));
self::assertSame('ThisStringIsCamelized', $this->inflector->camelize('thisStringIsCamelized'));
self::assertSame('ThisStringIsCamelized', $this->inflector->camelize('This_String_Is_Camelized'));
self::assertSame('ThisStringIsCamelized', $this->inflector->camelize('this string is camelized'));
self::assertSame('GravSPrettyCoolMy1', $this->inflector->camelize("Grav's Pretty Cool. My #1!"));
}
public function testUnderscorize(): void
{
self::assertSame('this_string_is_underscorized', $this->inflector->underscorize('This String Is Underscorized'));
self::assertSame('this_string_is_underscorized', $this->inflector->underscorize('ThisStringIsUnderscorized'));
self::assertSame('this_string_is_underscorized', $this->inflector->underscorize('This_String_Is_Underscorized'));
self::assertSame('this_string_is_underscorized', $this->inflector->underscorize('This-String-Is-Underscorized'));
}
public function testHyphenize(): void
{
self::assertSame('this-string-is-hyphenized', $this->inflector->hyphenize('This String Is Hyphenized'));
self::assertSame('this-string-is-hyphenized', $this->inflector->hyphenize('ThisStringIsHyphenized'));
self::assertSame('this-string-is-hyphenized', $this->inflector->hyphenize('This-String-Is-Hyphenized'));
self::assertSame('this-string-is-hyphenized', $this->inflector->hyphenize('This_String_Is_Hyphenized'));
}
public function testHumanize(): void
{
//self::assertSame('This string is humanized', $this->inflector->humanize('ThisStringIsHumanized'));
self::assertSame('This string is humanized', $this->inflector->humanize('this_string_is_humanized'));
//self::assertSame('This string is humanized', $this->inflector->humanize('this-string-is-humanized'));
self::assertSame('This String Is Humanized', $this->inflector->humanize('this_string_is_humanized', 'all'));
//self::assertSame('This String Is Humanized', $this->inflector->humanize('this-string-is-humanized'), 'all');
}
public function testVariablize(): void
{
self::assertSame('thisStringIsVariablized', $this->inflector->variablize('This String Is Variablized'));
self::assertSame('thisStringIsVariablized', $this->inflector->variablize('ThisStringIsVariablized'));
self::assertSame('thisStringIsVariablized', $this->inflector->variablize('This_String_Is_Variablized'));
self::assertSame('thisStringIsVariablized', $this->inflector->variablize('this string is variablized'));
self::assertSame('gravSPrettyCoolMy1', $this->inflector->variablize("Grav's Pretty Cool. My #1!"));
}
public function testTableize(): void
{
self::assertSame('people', $this->inflector->tableize('Person'));
self::assertSame('pages', $this->inflector->tableize('Page'));
self::assertSame('blog_pages', $this->inflector->tableize('BlogPage'));
self::assertSame('admin_dependencies', $this->inflector->tableize('adminDependency'));
self::assertSame('admin_dependencies', $this->inflector->tableize('admin-dependency'));
self::assertSame('admin_dependencies', $this->inflector->tableize('admin_dependency'));
}
public function testClassify(): void
{
self::assertSame('Person', $this->inflector->classify('people'));
self::assertSame('Page', $this->inflector->classify('pages'));
self::assertSame('BlogPage', $this->inflector->classify('blog_pages'));
self::assertSame('AdminDependency', $this->inflector->classify('admin_dependencies'));
}
public function testOrdinalize(): void
{
self::assertSame('1st', $this->inflector->ordinalize(1));
self::assertSame('2nd', $this->inflector->ordinalize(2));
self::assertSame('3rd', $this->inflector->ordinalize(3));
self::assertSame('4th', $this->inflector->ordinalize(4));
self::assertSame('5th', $this->inflector->ordinalize(5));
self::assertSame('16th', $this->inflector->ordinalize(16));
self::assertSame('51st', $this->inflector->ordinalize(51));
self::assertSame('111th', $this->inflector->ordinalize(111));
self::assertSame('123rd', $this->inflector->ordinalize(123));
}
public function testMonthize(): void
{
self::assertSame(0, $this->inflector->monthize(10));
self::assertSame(1, $this->inflector->monthize(33));
self::assertSame(1, $this->inflector->monthize(41));
self::assertSame(11, $this->inflector->monthize(364));
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/unit/Grav/Common/UriTest.php | tests/unit/Grav/Common/UriTest.php | <?php
use Codeception\Util\Fixtures;
use Grav\Common\Config\Config;
use Grav\Common\Grav;
use Grav\Common\Uri;
use Grav\Common\Utils;
/**
* Class UriTest
*/
class UriTest extends \Codeception\TestCase\Test
{
/** @var Grav $grav */
protected $grav;
/** @var Uri $uri */
protected $uri;
/** @var Config $config */
protected $config;
protected $tests = [
'/path' => [
'scheme' => '',
'user' => null,
'password' => null,
'host' => null,
'port' => null,
'path' => '/path',
'query' => '',
'fragment' => null,
'route' => '/path',
'paths' => ['path'],
'params' => null,
'url' => '/path',
'environment' => 'unknown',
'basename' => 'path',
'base' => '',
'currentPage' => 1,
'rootUrl' => '',
'extension' => null,
'addNonce' => '/path/nonce:{{nonce}}',
],
'//localhost/' => [
'scheme' => '//',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => null,
'path' => '/',
'query' => '',
'fragment' => null,
'route' => '/',
'paths' => [],
'params' => null,
'url' => '/',
'environment' => 'localhost',
'basename' => '',
'base' => '//localhost',
'currentPage' => 1,
'rootUrl' => '//localhost',
'extension' => null,
'addNonce' => '//localhost/nonce:{{nonce}}',
],
'http://localhost/' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 80,
'path' => '/',
'query' => '',
'fragment' => null,
'route' => '/',
'paths' => [],
'params' => null,
'url' => '/',
'environment' => 'localhost',
'basename' => '',
'base' => 'http://localhost',
'currentPage' => 1,
'rootUrl' => 'http://localhost',
'extension' => null,
'addNonce' => 'http://localhost/nonce:{{nonce}}',
],
'http://127.0.0.1/' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => '127.0.0.1',
'port' => 80,
'path' => '/',
'query' => '',
'fragment' => null,
'route' => '/',
'paths' => [],
'params' => null,
'url' => '/',
'environment' => 'localhost',
'basename' => '',
'base' => 'http://127.0.0.1',
'currentPage' => 1,
'rootUrl' => 'http://127.0.0.1',
'extension' => null,
'addNonce' => 'http://127.0.0.1/nonce:{{nonce}}',
],
'https://localhost/' => [
'scheme' => 'https://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 443,
'path' => '/',
'query' => '',
'fragment' => null,
'route' => '/',
'paths' => [],
'params' => null,
'url' => '/',
'environment' => 'localhost',
'basename' => '',
'base' => 'https://localhost',
'currentPage' => 1,
'rootUrl' => 'https://localhost',
'extension' => null,
'addNonce' => 'https://localhost/nonce:{{nonce}}',
],
'http://localhost:8080/grav/it/ueper' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 8080,
'path' => '/grav/it/ueper',
'query' => '',
'fragment' => null,
'route' => '/grav/it/ueper',
'paths' => ['grav', 'it', 'ueper'],
'params' => null,
'url' => '/grav/it/ueper',
'environment' => 'localhost',
'basename' => 'ueper',
'base' => 'http://localhost:8080',
'currentPage' => 1,
'rootUrl' => 'http://localhost:8080',
'extension' => null,
'addNonce' => 'http://localhost:8080/grav/it/ueper/nonce:{{nonce}}',
],
'http://localhost:8080/grav/it/ueper:xxx' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 8080,
'path' => '/grav/it',
'query' => '',
'fragment' => null,
'route' => '/grav/it',
'paths' => ['grav', 'it'],
'params' => '/ueper:xxx',
'url' => '/grav/it',
'environment' => 'localhost',
'basename' => 'it',
'base' => 'http://localhost:8080',
'currentPage' => 1,
'rootUrl' => 'http://localhost:8080',
'extension' => null,
'addNonce' => 'http://localhost:8080/grav/it/ueper:xxx/nonce:{{nonce}}',
],
'http://localhost:8080/grav/it/ueper:xxx/page:/test:yyy' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 8080,
'path' => '/grav/it',
'query' => '',
'fragment' => null,
'route' => '/grav/it',
'paths' => ['grav', 'it'],
'params' => '/ueper:xxx/page:/test:yyy',
'url' => '/grav/it',
'environment' => 'localhost',
'basename' => 'it',
'base' => 'http://localhost:8080',
'currentPage' => 1,
'rootUrl' => 'http://localhost:8080',
'extension' => null,
'addNonce' => 'http://localhost:8080/grav/it/ueper:xxx/page:/test:yyy/nonce:{{nonce}}',
],
'http://localhost:8080/grav/it/ueper?test=x' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 8080,
'path' => '/grav/it/ueper',
'query' => 'test=x',
'fragment' => null,
'route' => '/grav/it/ueper',
'paths' => ['grav', 'it', 'ueper'],
'params' => null,
'url' => '/grav/it/ueper',
'environment' => 'localhost',
'basename' => 'ueper',
'base' => 'http://localhost:8080',
'currentPage' => 1,
'rootUrl' => 'http://localhost:8080',
'extension' => null,
'addNonce' => 'http://localhost:8080/grav/it/ueper/nonce:{{nonce}}?test=x',
],
'http://localhost:80/grav/it/ueper?test=x' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 80,
'path' => '/grav/it/ueper',
'query' => 'test=x',
'fragment' => null,
'route' => '/grav/it/ueper',
'paths' => ['grav', 'it', 'ueper'],
'params' => null,
'url' => '/grav/it/ueper',
'environment' => 'localhost',
'basename' => 'ueper',
'base' => 'http://localhost:80',
'currentPage' => 1,
'rootUrl' => 'http://localhost:80',
'extension' => null,
'addNonce' => 'http://localhost:80/grav/it/ueper/nonce:{{nonce}}?test=x',
],
'http://localhost/grav/it/ueper?test=x' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 80,
'path' => '/grav/it/ueper',
'query' => 'test=x',
'fragment' => null,
'route' => '/grav/it/ueper',
'paths' => ['grav', 'it', 'ueper'],
'params' => null,
'url' => '/grav/it/ueper',
'environment' => 'localhost',
'basename' => 'ueper',
'base' => 'http://localhost',
'currentPage' => 1,
'rootUrl' => 'http://localhost',
'extension' => null,
'addNonce' => 'http://localhost/grav/it/ueper/nonce:{{nonce}}?test=x',
],
'http://grav/grav/it/ueper' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'grav',
'port' => 80,
'path' => '/grav/it/ueper',
'query' => '',
'fragment' => null,
'route' => '/grav/it/ueper',
'paths' => ['grav', 'it', 'ueper'],
'params' => null,
'url' => '/grav/it/ueper',
'environment' => 'grav',
'basename' => 'ueper',
'base' => 'http://grav',
'currentPage' => 1,
'rootUrl' => 'http://grav',
'extension' => null,
'addNonce' => 'http://grav/grav/it/ueper/nonce:{{nonce}}',
],
'https://username:password@api.getgrav.com:4040/v1/post/128/page:x/?all=1' => [
'scheme' => 'https://',
'user' => 'username',
'password' => 'password',
'host' => 'api.getgrav.com',
'port' => 4040,
'path' => '/v1/post/128/', // FIXME <-
'query' => 'all=1',
'fragment' => null,
'route' => '/v1/post/128',
'paths' => ['v1', 'post', '128'],
'params' => '/page:x',
'url' => '/v1/post/128',
'environment' => 'api.getgrav.com',
'basename' => '128',
'base' => 'https://api.getgrav.com:4040',
'currentPage' => 1,
'rootUrl' => 'https://api.getgrav.com:4040',
'extension' => null,
'addNonce' => 'https://username:password@api.getgrav.com:4040/v1/post/128/page:x/nonce:{{nonce}}?all=1',
'toOriginalString' => 'https://username:password@api.getgrav.com:4040/v1/post/128/page:x?all=1'
],
'https://google.com:443/' => [
'scheme' => 'https://',
'user' => null,
'password' => null,
'host' => 'google.com',
'port' => 443,
'path' => '/',
'query' => '',
'fragment' => null,
'route' => '/',
'paths' => [],
'params' => null,
'url' => '/',
'environment' => 'google.com',
'basename' => '',
'base' => 'https://google.com:443',
'currentPage' => 1,
'rootUrl' => 'https://google.com:443',
'extension' => null,
'addNonce' => 'https://google.com:443/nonce:{{nonce}}',
],
// Path tests.
'http://localhost:8080/a/b/c/d' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 8080,
'path' => '/a/b/c/d',
'query' => '',
'fragment' => null,
'route' => '/a/b/c/d',
'paths' => ['a', 'b', 'c', 'd'],
'params' => null,
'url' => '/a/b/c/d',
'environment' => 'localhost',
'basename' => 'd',
'base' => 'http://localhost:8080',
'currentPage' => 1,
'rootUrl' => 'http://localhost:8080',
'extension' => null,
'addNonce' => 'http://localhost:8080/a/b/c/d/nonce:{{nonce}}',
],
'http://localhost:8080/a/b/c/d/e/f/a/b/c/d/e/f/a/b/c/d/e/f' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 8080,
'path' => '/a/b/c/d/e/f/a/b/c/d/e/f/a/b/c/d/e/f',
'query' => '',
'fragment' => null,
'route' => '/a/b/c/d/e/f/a/b/c/d/e/f/a/b/c/d/e/f',
'paths' => ['a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'c', 'd', 'e', 'f'],
'params' => null,
'url' => '/a/b/c/d/e/f/a/b/c/d/e/f/a/b/c/d/e/f',
'environment' => 'localhost',
'basename' => 'f',
'base' => 'http://localhost:8080',
'currentPage' => 1,
'rootUrl' => 'http://localhost:8080',
'extension' => null,
'addNonce' => 'http://localhost:8080/a/b/c/d/e/f/a/b/c/d/e/f/a/b/c/d/e/f/nonce:{{nonce}}',
],
'http://localhost/this is the path/my page' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 80,
'path' => '/this%20is%20the%20path/my%20page',
'query' => '',
'fragment' => null,
'route' => '/this%20is%20the%20path/my%20page',
'paths' => ['this%20is%20the%20path', 'my%20page'],
'params' => null,
'url' => '/this%20is%20the%20path/my%20page',
'environment' => 'localhost',
'basename' => 'my%20page',
'base' => 'http://localhost',
'currentPage' => 1,
'rootUrl' => 'http://localhost',
'extension' => null,
'addNonce' => 'http://localhost/this%20is%20the%20path/my%20page/nonce:{{nonce}}',
'toOriginalString' => 'http://localhost/this%20is%20the%20path/my%20page'
],
'http://localhost/pölöpölö/päläpälä' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 80,
'path' => '/p%C3%B6l%C3%B6p%C3%B6l%C3%B6/p%C3%A4l%C3%A4p%C3%A4l%C3%A4',
'query' => '',
'fragment' => null,
'route' => '/p%C3%B6l%C3%B6p%C3%B6l%C3%B6/p%C3%A4l%C3%A4p%C3%A4l%C3%A4',
'paths' => ['p%C3%B6l%C3%B6p%C3%B6l%C3%B6', 'p%C3%A4l%C3%A4p%C3%A4l%C3%A4'],
'params' => null,
'url' => '/p%C3%B6l%C3%B6p%C3%B6l%C3%B6/p%C3%A4l%C3%A4p%C3%A4l%C3%A4',
'environment' => 'localhost',
'basename' => 'p%C3%A4l%C3%A4p%C3%A4l%C3%A4',
'base' => 'http://localhost',
'currentPage' => 1,
'rootUrl' => 'http://localhost',
'extension' => null,
'addNonce' => 'http://localhost/p%C3%B6l%C3%B6p%C3%B6l%C3%B6/p%C3%A4l%C3%A4p%C3%A4l%C3%A4/nonce:{{nonce}}',
'toOriginalString' => 'http://localhost/p%C3%B6l%C3%B6p%C3%B6l%C3%B6/p%C3%A4l%C3%A4p%C3%A4l%C3%A4'
],
// Query params tests.
'http://localhost:8080/grav/it/ueper?test=x&test2=y' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 8080,
'path' => '/grav/it/ueper',
'query' => 'test=x&test2=y',
'fragment' => null,
'route' => '/grav/it/ueper',
'paths' => ['grav', 'it', 'ueper'],
'params' => null,
'url' => '/grav/it/ueper',
'environment' => 'localhost',
'basename' => 'ueper',
'base' => 'http://localhost:8080',
'currentPage' => 1,
'rootUrl' => 'http://localhost:8080',
'extension' => null,
'addNonce' => 'http://localhost:8080/grav/it/ueper/nonce:{{nonce}}?test=x&test2=y',
],
'http://localhost:8080/grav/it/ueper?test=x&test2=y&test3=x&test4=y' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 8080,
'path' => '/grav/it/ueper',
'query' => 'test=x&test2=y&test3=x&test4=y',
'fragment' => null,
'route' => '/grav/it/ueper',
'paths' => ['grav', 'it', 'ueper'],
'params' => null,
'url' => '/grav/it/ueper',
'environment' => 'localhost',
'basename' => 'ueper',
'base' => 'http://localhost:8080',
'currentPage' => 1,
'rootUrl' => 'http://localhost:8080',
'extension' => null,
'addNonce' => 'http://localhost:8080/grav/it/ueper/nonce:{{nonce}}?test=x&test2=y&test3=x&test4=y',
],
'http://localhost:8080/grav/it/ueper?test=x&test2=y&test3=x&test4=y/test' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 8080,
'path' => '/grav/it/ueper',
'query' => 'test=x&test2=y&test3=x&test4=y%2Ftest',
'fragment' => null,
'route' => '/grav/it/ueper',
'paths' => ['grav', 'it', 'ueper'],
'params' => null,
'url' => '/grav/it/ueper',
'environment' => 'localhost',
'basename' => 'ueper',
'base' => 'http://localhost:8080',
'currentPage' => 1,
'rootUrl' => 'http://localhost:8080',
'extension' => null,
'addNonce' => 'http://localhost:8080/grav/it/ueper/nonce:{{nonce}}?test=x&test2=y&test3=x&test4=y/test',
],
// Port tests.
'http://localhost/a-page' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 80,
'path' => '/a-page',
'query' => '',
'fragment' => null,
'route' => '/a-page',
'paths' => ['a-page'],
'params' => null,
'url' => '/a-page',
'environment' => 'localhost',
'basename' => 'a-page',
'base' => 'http://localhost',
'currentPage' => 1,
'rootUrl' => 'http://localhost',
'extension' => null,
'addNonce' => 'http://localhost/a-page/nonce:{{nonce}}',
],
'http://localhost:8080/a-page' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 8080,
'path' => '/a-page',
'query' => '',
'fragment' => null,
'route' => '/a-page',
'paths' => ['a-page'],
'params' => null,
'url' => '/a-page',
'environment' => 'localhost',
'basename' => 'a-page',
'base' => 'http://localhost:8080',
'currentPage' => 1,
'rootUrl' => 'http://localhost:8080',
'extension' => null,
'addNonce' => 'http://localhost:8080/a-page/nonce:{{nonce}}',
],
'http://localhost:443/a-page' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 443,
'path' => '/a-page',
'query' => '',
'fragment' => null,
'route' => '/a-page',
'paths' => ['a-page'],
'params' => null,
'url' => '/a-page',
'environment' => 'localhost',
'basename' => 'a-page',
'base' => 'http://localhost:443',
'currentPage' => 1,
'rootUrl' => 'http://localhost:443',
'extension' => null,
'addNonce' => 'http://localhost:443/a-page/nonce:{{nonce}}',
],
// Extension tests.
'http://localhost/a-page.html' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 80,
'path' => '/a-page',
'query' => '',
'fragment' => null,
'route' => '/a-page',
'paths' => ['a-page'],
'params' => null,
'url' => '/a-page',
'environment' => 'localhost',
'basename' => 'a-page.html',
'base' => 'http://localhost',
'currentPage' => 1,
'rootUrl' => 'http://localhost',
'extension' => 'html',
'addNonce' => 'http://localhost/a-page.html/nonce:{{nonce}}',
'toOriginalString' => 'http://localhost/a-page.html',
],
'http://localhost/a-page.json' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 80,
'path' => '/a-page',
'query' => '',
'fragment' => null,
'route' => '/a-page',
'paths' => ['a-page'],
'params' => null,
'url' => '/a-page',
'environment' => 'localhost',
'basename' => 'a-page.json',
'base' => 'http://localhost',
'currentPage' => 1,
'rootUrl' => 'http://localhost',
'extension' => 'json',
'addNonce' => 'http://localhost/a-page.json/nonce:{{nonce}}',
'toOriginalString' => 'http://localhost/a-page.json',
],
'http://localhost/admin/ajax.json/task:getnewsfeed' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 80,
'path' => '/admin/ajax',
'query' => '',
'fragment' => null,
'route' => '/admin/ajax',
'paths' => ['admin', 'ajax'],
'params' => '/task:getnewsfeed',
'url' => '/admin/ajax',
'environment' => 'localhost',
'basename' => 'ajax.json',
'base' => 'http://localhost',
'currentPage' => 1,
'rootUrl' => 'http://localhost',
'extension' => 'json',
'addNonce' => 'http://localhost/admin/ajax.json/task:getnewsfeed/nonce:{{nonce}}',
'toOriginalString' => 'http://localhost/admin/ajax.json/task:getnewsfeed',
],
'http://localhost/grav/admin/media.json/route:L1VzZXJzL3JodWsvd29ya3NwYWNlL2dyYXYtZGVtby1zYW1wbGVyL3VzZXIvYXNzZXRzL3FRMXB4Vk1ERTNJZzh5Ni5qcGc=/task:removeFileFromBlueprint/proute:/blueprint:Y29uZmlnL2RldGFpbHM=/type:config/field:deep.nested.custom_file/path:dXNlci9hc3NldHMvcVExcHhWTURFM0lnOHk2LmpwZw==' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 80,
'path' => '/grav/admin/media',
'query' => '',
'fragment' => null,
'route' => '/grav/admin/media',
'paths' => ['grav','admin','media'],
'params' => '/route:L1VzZXJzL3JodWsvd29ya3NwYWNlL2dyYXYtZGVtby1zYW1wbGVyL3VzZXIvYXNzZXRzL3FRMXB4Vk1ERTNJZzh5Ni5qcGc=/task:removeFileFromBlueprint/proute:/blueprint:Y29uZmlnL2RldGFpbHM=/type:config/field:deep.nested.custom_file/path:dXNlci9hc3NldHMvcVExcHhWTURFM0lnOHk2LmpwZw==',
'url' => '/grav/admin/media',
'environment' => 'localhost',
'basename' => 'media.json',
'base' => 'http://localhost',
'currentPage' => 1,
'rootUrl' => 'http://localhost',
'extension' => 'json',
'addNonce' => 'http://localhost/grav/admin/media.json/route:L1VzZXJzL3JodWsvd29ya3NwYWNlL2dyYXYtZGVtby1zYW1wbGVyL3VzZXIvYXNzZXRzL3FRMXB4Vk1ERTNJZzh5Ni5qcGc=/task:removeFileFromBlueprint/proute:/blueprint:Y29uZmlnL2RldGFpbHM=/type:config/field:deep.nested.custom_file/path:dXNlci9hc3NldHMvcVExcHhWTURFM0lnOHk2LmpwZw==/nonce:{{nonce}}',
'toOriginalString' => 'http://localhost/grav/admin/media.json/route:L1VzZXJzL3JodWsvd29ya3NwYWNlL2dyYXYtZGVtby1zYW1wbGVyL3VzZXIvYXNzZXRzL3FRMXB4Vk1ERTNJZzh5Ni5qcGc=/task:removeFileFromBlueprint/proute:/blueprint:Y29uZmlnL2RldGFpbHM=/type:config/field:deep.nested.custom_file/path:dXNlci9hc3NldHMvcVExcHhWTURFM0lnOHk2LmpwZw==',
],
'http://localhost/a-page.foo' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 80,
'path' => '/a-page.foo',
'query' => '',
'fragment' => null,
'route' => '/a-page.foo',
'paths' => ['a-page.foo'],
'params' => null,
'url' => '/a-page.foo',
'environment' => 'localhost',
'basename' => 'a-page.foo',
'base' => 'http://localhost',
'currentPage' => 1,
'rootUrl' => 'http://localhost',
'extension' => 'foo',
'addNonce' => 'http://localhost/a-page.foo/nonce:{{nonce}}',
'toOriginalString' => 'http://localhost/a-page.foo'
],
// Fragment tests.
'http://localhost:8080/a/b/c#my-fragment' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 8080,
'path' => '/a/b/c',
'query' => '',
'fragment' => 'my-fragment',
'route' => '/a/b/c',
'paths' => ['a', 'b', 'c'],
'params' => null,
'url' => '/a/b/c',
'environment' => 'localhost',
'basename' => 'c',
'base' => 'http://localhost:8080',
'currentPage' => 1,
'rootUrl' => 'http://localhost:8080',
'extension' => null,
'addNonce' => 'http://localhost:8080/a/b/c/nonce:{{nonce}}#my-fragment',
],
// Attacks.
'"><script>alert</script>://localhost' => [
'scheme' => '',
'user' => null,
'password' => null,
'host' => null,
'port' => null,
'path' => '/localhost',
'query' => '',
'fragment' => null,
'route' => '/localhost',
'paths' => ['localhost'],
'params' => '/script%3E:',
'url' => '/localhost',
'environment' => 'unknown',
'basename' => 'localhost',
'base' => '',
'currentPage' => 1,
'rootUrl' => '',
'extension' => null,
//'addNonce' => '%22%3E%3Cscript%3Ealert%3C/localhost/script%3E:/nonce:{{nonce}}', // FIXME <-
'toOriginalString' => '/localhost/script%3E:' // FIXME <-
],
'http://"><script>alert</script>' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'unknown',
'port' => 80,
'path' => '/script%3E',
'query' => '',
'fragment' => null,
'route' => '/script%3E',
'paths' => ['script%3E'],
'params' => null,
'url' => '/script%3E',
'environment' => 'unknown',
'basename' => 'script%3E',
'base' => 'http://unknown',
'currentPage' => 1,
'rootUrl' => 'http://unknown',
'extension' => null,
'addNonce' => 'http://unknown/script%3E/nonce:{{nonce}}',
'toOriginalString' => 'http://unknown/script%3E'
],
'http://localhost/"><script>alert</script>' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 80,
'path' => '/%22%3E%3Cscript%3Ealert%3C/script%3E',
'query' => '',
'fragment' => null,
'route' => '/%22%3E%3Cscript%3Ealert%3C/script%3E',
'paths' => ['%22%3E%3Cscript%3Ealert%3C', 'script%3E'],
'params' => null,
'url' => '/%22%3E%3Cscript%3Ealert%3C/script%3E',
'environment' => 'localhost',
'basename' => 'script%3E',
'base' => 'http://localhost',
'currentPage' => 1,
'rootUrl' => 'http://localhost',
'extension' => null,
'addNonce' => 'http://localhost/%22%3E%3Cscript%3Ealert%3C/script%3E/nonce:{{nonce}}',
'toOriginalString' => 'http://localhost/%22%3E%3Cscript%3Ealert%3C/script%3E'
],
'http://localhost/something/p1:foo/p2:"><script>alert</script>' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 80,
'path' => '/something/script%3E',
'query' => '',
'fragment' => null,
'route' => '/something/script%3E',
'paths' => ['something', 'script%3E'],
'params' => '/p1:foo/p2:%22%3E%3Cscript%3Ealert%3C',
'url' => '/something/script%3E',
'environment' => 'localhost',
'basename' => 'script%3E',
'base' => 'http://localhost',
'currentPage' => 1,
'rootUrl' => 'http://localhost',
'extension' => null,
//'addNonce' => 'http://localhost/something/script%3E/p1:foo/p2:%22%3E%3Cscript%3Ealert%3C/nonce:{{nonce}}', // FIXME <-
'toOriginalString' => 'http://localhost/something/script%3E/p1:foo/p2:%22%3E%3Cscript%3Ealert%3C'
],
'http://localhost/something?p="><script>alert</script>' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 80,
'path' => '/something',
'query' => 'p=%22%3E%3Cscript%3Ealert%3C%2Fscript%3E',
'fragment' => null,
'route' => '/something',
'paths' => ['something'],
'params' => null,
'url' => '/something',
'environment' => 'localhost',
'basename' => 'something',
'base' => 'http://localhost',
'currentPage' => 1,
'rootUrl' => 'http://localhost',
'extension' => null,
'addNonce' => 'http://localhost/something/nonce:{{nonce}}?p=%22%3E%3Cscript%3Ealert%3C/script%3E',
'toOriginalString' => 'http://localhost/something?p=%22%3E%3Cscript%3Ealert%3C/script%3E'
],
'http://localhost/something#"><script>alert</script>' => [
'scheme' => 'http://',
'user' => null,
'password' => null,
'host' => 'localhost',
'port' => 80,
'path' => '/something',
'query' => '',
'fragment' => '%22%3E%3Cscript%3Ealert%3C/script%3E',
'route' => '/something',
'paths' => ['something'],
'params' => null,
'url' => '/something',
'environment' => 'localhost',
'basename' => 'something',
'base' => 'http://localhost',
'currentPage' => 1,
'rootUrl' => 'http://localhost',
'extension' => null,
'addNonce' => 'http://localhost/something/nonce:{{nonce}}#%22%3E%3Cscript%3Ealert%3C/script%3E',
'toOriginalString' => 'http://localhost/something#%22%3E%3Cscript%3Ealert%3C/script%3E'
],
'https://www.getgrav.org/something/"><script>eval(atob("aGlzdG9yeS5wdXNoU3RhdGUoJycsJycsJy8nKTskKCdoZWFkLGJvZHknKS5odG1sKCcnKS5sb2FkKCcvJyk7JC5wb3N0KCcvYWRtaW4nLGZ1bmN0aW9uKGRhdGEpeyQucG9zdCgkKGRhdGEpLmZpbmQoJ1tpZD1hZG1pbi11c2VyLWRldGFpbHNdIGEnKS5hdHRyKCdocmVmJykseydhZG1pbi1ub25jZSc6JChkYXRhKS5maW5kKCdbZGF0YS1jbGVhci1jYWNoZV0nKS5hdHRyKCdkYXRhLWNsZWFyLWNhY2hlJykuc3BsaXQoJzonKS5wb3AoKS50cmltKCksJ2RhdGFbcGFzc3dvcmRdJzonSW0zdjFsaDR4eDByJywndGFzayc6J3NhdmUnfSl9KQ=="))</script><' => [
'scheme' => 'https://',
'user' => null,
'password' => null,
'host' => 'www.getgrav.org',
'port' => 443,
'path' => '/something/%22%3E%3Cscript%3Eeval%28atob%28%22aGlzdG9yeS5wdXNoU3RhdGUoJycsJycsJy8nKTskKCdoZWFkLGJvZHknKS5odG1sKCcnKS5sb2FkKCcvJyk7JC5wb3N0KCcvYWRtaW4nLGZ1bmN0aW9uKGRhdGEpeyQucG9zdCgkKGRhdGEpLmZpbmQoJ1tpZD1hZG1pbi11c2VyLWRldGFpbHNdIGEnKS5hdHRyKCdocmVmJykseydhZG1pbi1ub25jZSc6JChkYXRhKS5maW5kKCdbZGF0YS1jbGVhci1jYWNoZV0nKS5hdHRyKCdkYXRhLWNsZWFyLWNhY2hlJykuc3BsaXQoJzonKS5wb3AoKS50cmltKCksJ2RhdGFbcGFzc3dvcmRdJzonSW0zdjFsaDR4eDByJywndGFzayc6J3NhdmUnfSl9KQ==%22%29%29%3C/script%3E%3C',
'query' => '',
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | true |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/unit/Grav/Common/ComposerTest.php | tests/unit/Grav/Common/ComposerTest.php | <?php
use Codeception\Util\Fixtures;
use Grav\Common\Composer;
class ComposerTest extends \Codeception\TestCase\Test
{
protected function _before(): void
{
}
protected function _after(): void
{
}
public function testGetComposerLocation(): void
{
$composerLocation = Composer::getComposerLocation();
self::assertIsString($composerLocation);
self::assertSame('/', $composerLocation[0]);
}
public function testGetComposerExecutor(): void
{
$composerExecutor = Composer::getComposerExecutor();
self::assertIsString($composerExecutor);
self::assertSame('/', $composerExecutor[0]);
self::assertNotNull(strstr($composerExecutor, 'php'));
self::assertNotNull(strstr($composerExecutor, 'composer'));
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/unit/Grav/Common/BrowserTest.php | tests/unit/Grav/Common/BrowserTest.php | <?php
use Codeception\Util\Fixtures;
use Grav\Common\Grav;
/**
* Class BrowserTest
*/
class BrowserTest extends \Codeception\TestCase\Test
{
/** @var Grav $grav */
protected $grav;
protected function _before(): void
{
$grav = Fixtures::get('grav');
$this->grav = $grav();
}
protected function _after(): void
{
}
public function testGetBrowser(): void
{
/* Already covered by PhpUserAgent tests */
}
public function testGetPlatform(): void
{
/* Already covered by PhpUserAgent tests */
}
public function testGetLongVersion(): void
{
/* Already covered by PhpUserAgent tests */
}
public function testGetVersion(): void
{
/* Already covered by PhpUserAgent tests */
}
public function testIsHuman(): void
{
//Already Partially covered by PhpUserAgent tests
//Make sure it recognizes the test as not human
self::assertFalse($this->grav['browser']->isHuman());
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/unit/Grav/Common/UtilsTest.php | tests/unit/Grav/Common/UtilsTest.php | <?php
use Codeception\Util\Fixtures;
use Grav\Common\Grav;
use Grav\Common\Uri;
use Grav\Common\Utils;
/**
* Class UtilsTest
*/
class UtilsTest extends \Codeception\TestCase\Test
{
/** @var Grav $grav */
protected $grav;
/** @var Uri $uri */
protected $uri;
protected function _before(): void
{
$grav = Fixtures::get('grav');
$this->grav = $grav();
$this->uri = $this->grav['uri'];
}
protected function _after(): void
{
}
public function testStartsWith(): void
{
self::assertTrue(Utils::startsWith('english', 'en'));
self::assertTrue(Utils::startsWith('English', 'En'));
self::assertTrue(Utils::startsWith('ENGLISH', 'EN'));
self::assertTrue(Utils::startsWith(
'ENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISH',
'EN'
));
self::assertFalse(Utils::startsWith('english', 'En'));
self::assertFalse(Utils::startsWith('English', 'EN'));
self::assertFalse(Utils::startsWith('ENGLISH', 'en'));
self::assertFalse(Utils::startsWith(
'ENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISH',
'e'
));
self::assertTrue(Utils::startsWith('english', 'En', false));
self::assertTrue(Utils::startsWith('English', 'EN', false));
self::assertTrue(Utils::startsWith('ENGLISH', 'en', false));
self::assertTrue(Utils::startsWith(
'ENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISH',
'e',
false
));
}
public function testEndsWith(): void
{
self::assertTrue(Utils::endsWith('english', 'sh'));
self::assertTrue(Utils::endsWith('EngliSh', 'Sh'));
self::assertTrue(Utils::endsWith('ENGLISH', 'SH'));
self::assertTrue(Utils::endsWith(
'ENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISH',
'ENGLISH'
));
self::assertFalse(Utils::endsWith('english', 'de'));
self::assertFalse(Utils::endsWith('EngliSh', 'sh'));
self::assertFalse(Utils::endsWith('ENGLISH', 'Sh'));
self::assertFalse(Utils::endsWith(
'ENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISH',
'DEUSTCH'
));
self::assertTrue(Utils::endsWith('english', 'SH', false));
self::assertTrue(Utils::endsWith('EngliSh', 'sH', false));
self::assertTrue(Utils::endsWith('ENGLISH', 'sh', false));
self::assertTrue(Utils::endsWith(
'ENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISH',
'english',
false
));
}
public function testContains(): void
{
self::assertTrue(Utils::contains('english', 'nglis'));
self::assertTrue(Utils::contains('EngliSh', 'gliSh'));
self::assertTrue(Utils::contains('ENGLISH', 'ENGLI'));
self::assertTrue(Utils::contains(
'ENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISH',
'ENGLISH'
));
self::assertFalse(Utils::contains('EngliSh', 'GLI'));
self::assertFalse(Utils::contains('EngliSh', 'English'));
self::assertFalse(Utils::contains('ENGLISH', 'SCH'));
self::assertFalse(Utils::contains(
'ENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISH',
'DEUSTCH'
));
self::assertTrue(Utils::contains('EngliSh', 'GLI', false));
self::assertTrue(Utils::contains('EngliSh', 'ENGLISH', false));
self::assertTrue(Utils::contains('ENGLISH', 'ish', false));
self::assertTrue(Utils::contains(
'ENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISH',
'english',
false
));
}
public function testSubstrToString(): void
{
self::assertEquals('en', Utils::substrToString('english', 'glish'));
self::assertEquals('english', Utils::substrToString('english', 'test'));
self::assertNotEquals('en', Utils::substrToString('english', 'lish'));
self::assertEquals('en', Utils::substrToString('english', 'GLISH', false));
self::assertEquals('english', Utils::substrToString('english', 'TEST', false));
self::assertNotEquals('en', Utils::substrToString('english', 'LISH', false));
}
public function testMergeObjects(): void
{
$obj1 = new stdClass();
$obj1->test1 = 'x';
$obj2 = new stdClass();
$obj2->test2 = 'y';
$objMerged = Utils::mergeObjects($obj1, $obj2);
self::arrayHasKey('test1', (array) $objMerged);
self::arrayHasKey('test2', (array) $objMerged);
}
public function testDateFormats(): void
{
$dateFormats = Utils::dateFormats();
self::assertIsArray($dateFormats);
self::assertContainsOnly('string', $dateFormats);
$default_format = $this->grav['config']->get('system.pages.dateformat.default');
if ($default_format !== null) {
self::assertArrayHasKey($default_format, $dateFormats);
}
}
public function testTruncate(): void
{
self::assertEquals('engli' . '…', Utils::truncate('english', 5));
self::assertEquals('english', Utils::truncate('english'));
self::assertEquals('This is a string to truncate', Utils::truncate('This is a string to truncate'));
self::assertEquals('Th' . '…', Utils::truncate('This is a string to truncate', 2));
self::assertEquals('engli' . '...', Utils::truncate('english', 5, true, " ", "..."));
self::assertEquals('english', Utils::truncate('english'));
self::assertEquals('This is a string to truncate', Utils::truncate('This is a string to truncate'));
self::assertEquals('This' . '…', Utils::truncate('This is a string to truncate', 3, true));
self::assertEquals('<input' . '…', Utils::truncate('<input type="file" id="file" multiple />', 6, true));
}
public function testSafeTruncate(): void
{
self::assertEquals('This' . '…', Utils::safeTruncate('This is a string to truncate', 1));
self::assertEquals('This' . '…', Utils::safeTruncate('This is a string to truncate', 4));
self::assertEquals('This is' . '…', Utils::safeTruncate('This is a string to truncate', 5));
}
public function testTruncateHtml(): void
{
self::assertEquals('T...', Utils::truncateHtml('This is a string to truncate', 1));
self::assertEquals('This is...', Utils::truncateHtml('This is a string to truncate', 7));
self::assertEquals('<p>T...</p>', Utils::truncateHtml('<p>This is a string to truncate</p>', 1));
self::assertEquals('<p>This...</p>', Utils::truncateHtml('<p>This is a string to truncate</p>', 4));
self::assertEquals('<p>This is a...</p>', Utils::truncateHtml('<p>This is a string to truncate</p>', 10));
self::assertEquals('<p>This is a string to truncate</p>', Utils::truncateHtml('<p>This is a string to truncate</p>', 100));
self::assertEquals('<input type="file" id="file" multiple />', Utils::truncateHtml('<input type="file" id="file" multiple />', 6));
self::assertEquals('<ol><li>item 1 <i>so...</i></li></ol>', Utils::truncateHtml('<ol><li>item 1 <i>something</i></li><li>item 2 <strong>bold</strong></li></ol>', 10));
self::assertEquals("<p>This is a string.</p>\n<p>It splits two lines.</p>", Utils::truncateHtml("<p>This is a string.</p>\n<p>It splits two lines.</p>", 100));
}
public function testSafeTruncateHtml(): void
{
self::assertEquals('This...', Utils::safeTruncateHtml('This is a string to truncate', 1));
self::assertEquals('This is a...', Utils::safeTruncateHtml('This is a string to truncate', 3));
self::assertEquals('<p>This...</p>', Utils::safeTruncateHtml('<p>This is a string to truncate</p>', 1));
self::assertEquals('<p>This is...</p>', Utils::safeTruncateHtml('<p>This is a string to truncate</p>', 2));
self::assertEquals('<p>This is a string to...</p>', Utils::safeTruncateHtml('<p>This is a string to truncate</p>', 5));
self::assertEquals('<p>This is a string to truncate</p>', Utils::safeTruncateHtml('<p>This is a string to truncate</p>', 20));
self::assertEquals('<input type="file" id="file" multiple />', Utils::safeTruncateHtml('<input type="file" id="file" multiple />', 6));
self::assertEquals('<ol><li>item 1 <i>something</i></li><li>item 2...</li></ol>', Utils::safeTruncateHtml('<ol><li>item 1 <i>something</i></li><li>item 2 <strong>bold</strong></li></ol>', 5));
}
public function testGenerateRandomString(): void
{
self::assertNotEquals(Utils::generateRandomString(), Utils::generateRandomString());
self::assertNotEquals(Utils::generateRandomString(20), Utils::generateRandomString(20));
}
public function download(): void
{
}
public function testGetMimeByExtension(): void
{
self::assertEquals('application/octet-stream', Utils::getMimeByExtension(''));
self::assertEquals('text/html', Utils::getMimeByExtension('html'));
self::assertEquals('application/json', Utils::getMimeByExtension('json'));
self::assertEquals('application/atom+xml', Utils::getMimeByExtension('atom'));
self::assertEquals('application/rss+xml', Utils::getMimeByExtension('rss'));
self::assertEquals('image/jpeg', Utils::getMimeByExtension('jpg'));
self::assertEquals('image/png', Utils::getMimeByExtension('png'));
self::assertEquals('text/plain', Utils::getMimeByExtension('txt'));
self::assertEquals('application/msword', Utils::getMimeByExtension('doc'));
self::assertEquals('application/octet-stream', Utils::getMimeByExtension('foo'));
self::assertEquals('foo/bar', Utils::getMimeByExtension('foo', 'foo/bar'));
self::assertEquals('text/html', Utils::getMimeByExtension('foo', 'text/html'));
}
public function testGetExtensionByMime(): void
{
self::assertEquals('html', Utils::getExtensionByMime('*/*'));
self::assertEquals('html', Utils::getExtensionByMime('text/*'));
self::assertEquals('html', Utils::getExtensionByMime('text/html'));
self::assertEquals('json', Utils::getExtensionByMime('application/json'));
self::assertEquals('atom', Utils::getExtensionByMime('application/atom+xml'));
self::assertEquals('rss', Utils::getExtensionByMime('application/rss+xml'));
self::assertEquals('jpg', Utils::getExtensionByMime('image/jpeg'));
self::assertEquals('png', Utils::getExtensionByMime('image/png'));
self::assertEquals('txt', Utils::getExtensionByMime('text/plain'));
self::assertEquals('doc', Utils::getExtensionByMime('application/msword'));
self::assertEquals('html', Utils::getExtensionByMime('foo/bar'));
self::assertEquals('baz', Utils::getExtensionByMime('foo/bar', 'baz'));
}
public function testNormalizePath(): void
{
self::assertEquals('/test', Utils::normalizePath('/test'));
self::assertEquals('test', Utils::normalizePath('test'));
self::assertEquals('test', Utils::normalizePath('../test'));
self::assertEquals('/test', Utils::normalizePath('/../test'));
self::assertEquals('/test2', Utils::normalizePath('/test/../test2'));
self::assertEquals('/test3', Utils::normalizePath('/test/../test2/../test3'));
self::assertEquals('//cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.css', Utils::normalizePath('//cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.css'));
self::assertEquals('//use.fontawesome.com/releases/v5.8.1/css/all.css', Utils::normalizePath('//use.fontawesome.com/releases/v5.8.1/css/all.css'));
self::assertEquals('//use.fontawesome.com/releases/v5.8.1/webfonts/fa-brands-400.eot', Utils::normalizePath('//use.fontawesome.com/releases/v5.8.1/css/../webfonts/fa-brands-400.eot'));
self::assertEquals('http://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.css', Utils::normalizePath('http://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.css'));
self::assertEquals('http://use.fontawesome.com/releases/v5.8.1/css/all.css', Utils::normalizePath('http://use.fontawesome.com/releases/v5.8.1/css/all.css'));
self::assertEquals('http://use.fontawesome.com/releases/v5.8.1/webfonts/fa-brands-400.eot', Utils::normalizePath('http://use.fontawesome.com/releases/v5.8.1/css/../webfonts/fa-brands-400.eot'));
self::assertEquals('https://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.css', Utils::normalizePath('https://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.css'));
self::assertEquals('https://use.fontawesome.com/releases/v5.8.1/css/all.css', Utils::normalizePath('https://use.fontawesome.com/releases/v5.8.1/css/all.css'));
self::assertEquals('https://use.fontawesome.com/releases/v5.8.1/webfonts/fa-brands-400.eot', Utils::normalizePath('https://use.fontawesome.com/releases/v5.8.1/css/../webfonts/fa-brands-400.eot'));
}
public function testIsFunctionDisabled(): void
{
$disabledFunctions = explode(',', ini_get('disable_functions'));
if ($disabledFunctions[0]) {
self::assertEquals(Utils::isFunctionDisabled($disabledFunctions[0]), true);
}
}
public function testTimezones(): void
{
$timezones = Utils::timezones();
self::assertIsArray($timezones);
self::assertContainsOnly('string', $timezones);
}
public function testArrayFilterRecursive(): void
{
$array = [
'test' => '',
'test2' => 'test2'
];
$array = Utils::arrayFilterRecursive($array, function ($k, $v) {
return !(is_null($v) || $v === '');
});
self::assertContainsOnly('string', $array);
self::assertArrayNotHasKey('test', $array);
self::assertArrayHasKey('test2', $array);
self::assertEquals('test2', $array['test2']);
}
public function testPathPrefixedByLangCode(): void
{
$languagesEnabled = $this->grav['config']->get('system.languages.supported', []);
$arrayOfLanguages = ['en', 'de', 'it', 'es', 'dk', 'el'];
$languagesNotEnabled = array_diff($arrayOfLanguages, $languagesEnabled);
$oneLanguageNotEnabled = reset($languagesNotEnabled);
if (count($languagesEnabled)) {
$languageCodePathPrefix = Utils::pathPrefixedByLangCode('/' . $languagesEnabled[0] . '/test');
$this->assertIsString($languageCodePathPrefix);
$this->assertTrue(in_array($languageCodePathPrefix, $languagesEnabled));
}
self::assertFalse(Utils::pathPrefixedByLangCode('/' . $oneLanguageNotEnabled . '/test'));
self::assertFalse(Utils::pathPrefixedByLangCode('/test'));
self::assertFalse(Utils::pathPrefixedByLangCode('/xx'));
self::assertFalse(Utils::pathPrefixedByLangCode('/xx/'));
self::assertFalse(Utils::pathPrefixedByLangCode('/'));
}
public function testDate2timestamp(): void
{
$timestamp = strtotime('10 September 2000');
self::assertSame($timestamp, Utils::date2timestamp('10 September 2000'));
self::assertSame($timestamp, Utils::date2timestamp('2000-09-10 00:00:00'));
}
public function testResolve(): void
{
$array = [
'test' => [
'test2' => 'test2Value'
]
];
self::assertEquals('test2Value', Utils::resolve($array, 'test.test2'));
}
public function testGetDotNotation(): void
{
$array = [
'test' => [
'test2' => 'test2Value',
'test3' => [
'test4' => 'test4Value'
]
]
];
self::assertEquals('test2Value', Utils::getDotNotation($array, 'test.test2'));
self::assertEquals('test4Value', Utils::getDotNotation($array, 'test.test3.test4'));
self::assertEquals('defaultValue', Utils::getDotNotation($array, 'test.non_existent', 'defaultValue'));
}
public function testSetDotNotation(): void
{
$array = [
'test' => [
'test2' => 'test2Value',
'test3' => [
'test4' => 'test4Value'
]
]
];
$new = [
'test1' => 'test1Value'
];
Utils::setDotNotation($array, 'test.test3.test4', $new);
self::assertEquals('test1Value', $array['test']['test3']['test4']['test1']);
}
public function testIsPositive(): void
{
self::assertTrue(Utils::isPositive(true));
self::assertTrue(Utils::isPositive(1));
self::assertTrue(Utils::isPositive('1'));
self::assertTrue(Utils::isPositive('yes'));
self::assertTrue(Utils::isPositive('on'));
self::assertTrue(Utils::isPositive('true'));
self::assertFalse(Utils::isPositive(false));
self::assertFalse(Utils::isPositive(0));
self::assertFalse(Utils::isPositive('0'));
self::assertFalse(Utils::isPositive('no'));
self::assertFalse(Utils::isPositive('off'));
self::assertFalse(Utils::isPositive('false'));
self::assertFalse(Utils::isPositive('some'));
self::assertFalse(Utils::isPositive(2));
}
public function testGetNonce(): void
{
self::assertIsString(Utils::getNonce('test-action'));
self::assertIsString(Utils::getNonce('test-action', true));
self::assertSame(Utils::getNonce('test-action'), Utils::getNonce('test-action'));
self::assertNotSame(Utils::getNonce('test-action'), Utils::getNonce('test-action2'));
}
public function testVerifyNonce(): void
{
self::assertTrue(Utils::verifyNonce(Utils::getNonce('test-action'), 'test-action'));
}
public function testGetPagePathFromToken(): void
{
self::assertEquals('', Utils::getPagePathFromToken(''));
self::assertEquals('/test/path', Utils::getPagePathFromToken('/test/path'));
}
public function testUrl(): void
{
$this->uri->initializeWithUrl('http://testing.dev/path1/path2')->init();
// Fail hard
self::assertSame(false, Utils::url('', true));
self::assertSame(false, Utils::url(''));
self::assertSame(false, Utils::url(new stdClass()));
self::assertSame(false, Utils::url(['foo','bar','baz']));
self::assertSame(false, Utils::url('user://does/not/exist'));
// Fail Gracefully
self::assertSame('/', Utils::url('/', false, true));
self::assertSame('/', Utils::url('', false, true));
self::assertSame('/', Utils::url(new stdClass(), false, true));
self::assertSame('/', Utils::url(['foo','bar','baz'], false, true));
self::assertSame('/user/does/not/exist', Utils::url('user://does/not/exist', false, true));
// Simple paths
self::assertSame('/', Utils::url('/'));
self::assertSame('/path1', Utils::url('/path1'));
self::assertSame('/path1/path2', Utils::url('/path1/path2'));
self::assertSame('/random/path1/path2', Utils::url('/random/path1/path2'));
self::assertSame('/foobar.jpg', Utils::url('/foobar.jpg'));
self::assertSame('/path1/foobar.jpg', Utils::url('/path1/foobar.jpg'));
self::assertSame('/path1/path2/foobar.jpg', Utils::url('/path1/path2/foobar.jpg'));
self::assertSame('/random/path1/path2/foobar.jpg', Utils::url('/random/path1/path2/foobar.jpg'));
// Simple paths with domain
self::assertSame('http://testing.dev/', Utils::url('/', true));
self::assertSame('http://testing.dev/path1', Utils::url('/path1', true));
self::assertSame('http://testing.dev/path1/path2', Utils::url('/path1/path2', true));
self::assertSame('http://testing.dev/random/path1/path2', Utils::url('/random/path1/path2', true));
self::assertSame('http://testing.dev/foobar.jpg', Utils::url('/foobar.jpg', true));
self::assertSame('http://testing.dev/path1/foobar.jpg', Utils::url('/path1/foobar.jpg', true));
self::assertSame('http://testing.dev/path1/path2/foobar.jpg', Utils::url('/path1/path2/foobar.jpg', true));
self::assertSame('http://testing.dev/random/path1/path2/foobar.jpg', Utils::url('/random/path1/path2/foobar.jpg', true));
// Relative paths from Grav root.
self::assertSame('/subdir', Utils::url('subdir'));
self::assertSame('/subdir/path1', Utils::url('subdir/path1'));
self::assertSame('/subdir/path1/path2', Utils::url('subdir/path1/path2'));
self::assertSame('/path1', Utils::url('path1'));
self::assertSame('/path1/path2', Utils::url('path1/path2'));
self::assertSame('/foobar.jpg', Utils::url('foobar.jpg'));
self::assertSame('http://testing.dev/foobar.jpg', Utils::url('foobar.jpg', true));
// Relative paths from Grav root with domain.
self::assertSame('http://testing.dev/foobar.jpg', Utils::url('foobar.jpg', true));
self::assertSame('http://testing.dev/foobar.jpg', Utils::url('/foobar.jpg', true));
self::assertSame('http://testing.dev/path1/foobar.jpg', Utils::url('/path1/foobar.jpg', true));
// All Non-existing streams should be treated as external URI / protocol.
self::assertSame('http://domain.com/path', Utils::url('http://domain.com/path'));
self::assertSame('ftp://domain.com/path', Utils::url('ftp://domain.com/path'));
self::assertSame('sftp://domain.com/path', Utils::url('sftp://domain.com/path'));
self::assertSame('ssh://domain.com', Utils::url('ssh://domain.com'));
self::assertSame('pop://domain.com', Utils::url('pop://domain.com'));
self::assertSame('foo://bar/baz', Utils::url('foo://bar/baz'));
self::assertSame('foo://bar/baz', Utils::url('foo://bar/baz', true));
self::assertSame('mailto:joe@domain.com', Utils::url('mailto:joe@domain.com', true)); // FIXME <-
}
public function testUrlWithRoot(): void
{
$this->uri->initializeWithUrlAndRootPath('http://testing.dev/subdir/path1/path2', '/subdir')->init();
// Fail hard
self::assertSame(false, Utils::url('', true));
self::assertSame(false, Utils::url(''));
self::assertSame(false, Utils::url(new stdClass()));
self::assertSame(false, Utils::url(['foo','bar','baz']));
self::assertSame(false, Utils::url('user://does/not/exist'));
// Fail Gracefully
self::assertSame('/subdir/', Utils::url('/', false, true));
self::assertSame('/subdir/', Utils::url('', false, true));
self::assertSame('/subdir/', Utils::url(new stdClass(), false, true));
self::assertSame('/subdir/', Utils::url(['foo','bar','baz'], false, true));
self::assertSame('/subdir/user/does/not/exist', Utils::url('user://does/not/exist', false, true));
// Simple paths
self::assertSame('/subdir/', Utils::url('/'));
self::assertSame('/subdir/path1', Utils::url('/path1'));
self::assertSame('/subdir/path1/path2', Utils::url('/path1/path2'));
self::assertSame('/subdir/random/path1/path2', Utils::url('/random/path1/path2'));
self::assertSame('/subdir/foobar.jpg', Utils::url('/foobar.jpg'));
self::assertSame('/subdir/path1/foobar.jpg', Utils::url('/path1/foobar.jpg'));
self::assertSame('/subdir/path1/path2/foobar.jpg', Utils::url('/path1/path2/foobar.jpg'));
self::assertSame('/subdir/random/path1/path2/foobar.jpg', Utils::url('/random/path1/path2/foobar.jpg'));
// Simple paths with domain
self::assertSame('http://testing.dev/subdir/', Utils::url('/', true));
self::assertSame('http://testing.dev/subdir/path1', Utils::url('/path1', true));
self::assertSame('http://testing.dev/subdir/path1/path2', Utils::url('/path1/path2', true));
self::assertSame('http://testing.dev/subdir/random/path1/path2', Utils::url('/random/path1/path2', true));
self::assertSame('http://testing.dev/subdir/foobar.jpg', Utils::url('/foobar.jpg', true));
self::assertSame('http://testing.dev/subdir/path1/foobar.jpg', Utils::url('/path1/foobar.jpg', true));
self::assertSame('http://testing.dev/subdir/path1/path2/foobar.jpg', Utils::url('/path1/path2/foobar.jpg', true));
self::assertSame('http://testing.dev/subdir/random/path1/path2/foobar.jpg', Utils::url('/random/path1/path2/foobar.jpg', true));
// Absolute Paths including the grav base.
self::assertSame('/subdir/', Utils::url('/subdir'));
self::assertSame('/subdir/', Utils::url('/subdir/'));
self::assertSame('/subdir/path1', Utils::url('/subdir/path1'));
self::assertSame('/subdir/path1/path2', Utils::url('/subdir/path1/path2'));
self::assertSame('/subdir/foobar.jpg', Utils::url('/subdir/foobar.jpg'));
self::assertSame('/subdir/path1/foobar.jpg', Utils::url('/subdir/path1/foobar.jpg'));
// Absolute paths from Grav root with domain.
self::assertSame('http://testing.dev/subdir/', Utils::url('/subdir', true));
self::assertSame('http://testing.dev/subdir/', Utils::url('/subdir/', true));
self::assertSame('http://testing.dev/subdir/path1', Utils::url('/subdir/path1', true));
self::assertSame('http://testing.dev/subdir/path1/path2', Utils::url('/subdir/path1/path2', true));
self::assertSame('http://testing.dev/subdir/foobar.jpg', Utils::url('/subdir/foobar.jpg', true));
self::assertSame('http://testing.dev/subdir/path1/foobar.jpg', Utils::url('/subdir/path1/foobar.jpg', true));
// Relative paths from Grav root.
self::assertSame('/subdir/sub', Utils::url('/sub'));
self::assertSame('/subdir/subdir', Utils::url('subdir'));
self::assertSame('/subdir/subdir2/sub', Utils::url('/subdir2/sub'));
self::assertSame('/subdir/subdir/path1', Utils::url('subdir/path1'));
self::assertSame('/subdir/subdir/path1/path2', Utils::url('subdir/path1/path2'));
self::assertSame('/subdir/path1', Utils::url('path1'));
self::assertSame('/subdir/path1/path2', Utils::url('path1/path2'));
self::assertSame('/subdir/foobar.jpg', Utils::url('foobar.jpg'));
self::assertSame('http://testing.dev/subdir/foobar.jpg', Utils::url('foobar.jpg', true));
// All Non-existing streams should be treated as external URI / protocol.
self::assertSame('http://domain.com/path', Utils::url('http://domain.com/path'));
self::assertSame('ftp://domain.com/path', Utils::url('ftp://domain.com/path'));
self::assertSame('sftp://domain.com/path', Utils::url('sftp://domain.com/path'));
self::assertSame('ssh://domain.com', Utils::url('ssh://domain.com'));
self::assertSame('pop://domain.com', Utils::url('pop://domain.com'));
self::assertSame('foo://bar/baz', Utils::url('foo://bar/baz'));
self::assertSame('foo://bar/baz', Utils::url('foo://bar/baz', true));
// self::assertSame('mailto:joe@domain.com', Utils::url('mailto:joe@domain.com', true)); // FIXME <-
}
public function testUrlWithStreams(): void
{
}
public function testUrlwithExternals(): void
{
$this->uri->initializeWithUrl('http://testing.dev/path1/path2')->init();
self::assertSame('http://foo.com', Utils::url('http://foo.com'));
self::assertSame('https://foo.com', Utils::url('https://foo.com'));
self::assertSame('//foo.com', Utils::url('//foo.com'));
self::assertSame('//foo.com?param=x', Utils::url('//foo.com?param=x'));
}
public function testCheckFilename(): void
{
// configure extension for consistent results
/** @var \Grav\Common\Config\Config $config */
$config = $this->grav['config'];
$config->set('security.uploads_dangerous_extensions', ['php', 'html', 'htm', 'exe', 'js']);
self::assertFalse(Utils::checkFilename('foo.php'));
self::assertFalse(Utils::checkFilename('foo.PHP'));
self::assertFalse(Utils::checkFilename('bar.js'));
self::assertTrue(Utils::checkFilename('foo.json'));
self::assertTrue(Utils::checkFilename('foo.xml'));
self::assertTrue(Utils::checkFilename('foo.yaml'));
self::assertTrue(Utils::checkFilename('foo.yml'));
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/unit/Grav/Common/AssetsTest.php | tests/unit/Grav/Common/AssetsTest.php | <?php
use Codeception\Util\Fixtures;
use Grav\Common\Grav;
use Grav\Common\Assets;
/**
* Class AssetsTest
*/
class AssetsTest extends \Codeception\TestCase\Test
{
/** @var Grav $grav */
protected $grav;
/** @var Assets $assets */
protected $assets;
protected function _before(): void
{
$grav = Fixtures::get('grav');
$this->grav = $grav();
$this->assets = $this->grav['assets'];
}
protected function _after(): void
{
}
public function testAddingAssets(): void
{
//test add()
$this->assets->add('test.css');
$css = $this->assets->css();
self::assertSame('<link href="/test.css" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
$array = $this->assets->getCss();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type":"css",
"elements":{
"asset":"\/test.css",
"asset_type":"css",
"order":0,
"group":"head",
"position":"pipeline",
"priority":10,
"attributes":{
"type":"text\/css",
"rel":"stylesheet"
},
"modified":false,
"query":""
}
}';
self::assertJsonStringEqualsJsonString($expected, $actual);
$this->assets->add('test.js');
$js = $this->assets->js();
self::assertSame('<script src="/test.js"></script>' . PHP_EOL, $js);
$array = $this->assets->getJs();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type":"js",
"elements":{
"asset":"\/test.js",
"asset_type":"js",
"order":0,
"group":"head",
"position":"pipeline",
"priority":10,
"attributes":[
],
"modified":false,
"query":""
}
}';
self::assertJsonStringEqualsJsonString($expected, $actual);
//test addCss(). Test adding asset to a separate group
$this->assets->reset();
$this->assets->addCSS('test.css');
$css = $this->assets->css();
self::assertSame('<link href="/test.css" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
$array = $this->assets->getCss();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type":"css",
"elements":{
"asset":"\/test.css",
"asset_type":"css",
"order":0,
"group":"head",
"position":"pipeline",
"priority":10,
"attributes":{
"type":"text\/css",
"rel":"stylesheet"
},
"modified":false,
"query":""
}
}';
self::assertJsonStringEqualsJsonString($expected, $actual);
//test addCss(). Testing with remote URL
$this->assets->reset();
$this->assets->addCSS('http://www.somesite.com/test.css');
$css = $this->assets->css();
self::assertSame('<link href="http://www.somesite.com/test.css" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
$array = $this->assets->getCss();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type":"css",
"elements":{
"asset":"http:\/\/www.somesite.com\/test.css",
"asset_type":"css",
"order":0,
"group":"head",
"position":"pipeline",
"priority":10,
"attributes":{
"type":"text\/css",
"rel":"stylesheet"
},
"query":""
}
}';
self::assertJsonStringEqualsJsonString($expected, $actual);
//test addCss() adding asset to a separate group, and with an alternate rel attribute
$this->assets->reset();
$this->assets->addCSS('test.css', ['group' => 'alternate', 'rel' => 'alternate']);
$css = $this->assets->css('alternate');
self::assertSame('<link href="/test.css" type="text/css" rel="alternate">' . PHP_EOL, $css);
//test addJs()
$this->assets->reset();
$this->assets->addJs('test.js');
$js = $this->assets->js();
self::assertSame('<script src="/test.js"></script>' . PHP_EOL, $js);
$array = $this->assets->getJs();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type":"js",
"elements":{
"asset":"\/test.js",
"asset_type":"js",
"order":0,
"group":"head",
"position":"pipeline",
"priority":10,
"attributes":[],
"modified":false,
"query":""
}
}';
self::assertJsonStringEqualsJsonString($expected, $actual);
//Test CSS Groups
$this->assets->reset();
$this->assets->addCSS('test.css', ['group' => 'footer']);
$css = $this->assets->css();
self::assertEmpty($css);
$css = $this->assets->css('footer');
self::assertSame('<link href="/test.css" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
$array = $this->assets->getCss();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type": "css",
"elements": {
"asset": "/test.css",
"asset_type": "css",
"order": 0,
"group": "footer",
"position": "pipeline",
"priority": 10,
"attributes": {
"type": "text/css",
"rel": "stylesheet"
},
"modified": false,
"query": ""
}
}
';
self::assertJsonStringEqualsJsonString($expected, $actual);
//Test JS Groups
$this->assets->reset();
$this->assets->addJs('test.js', ['group' => 'footer']);
$js = $this->assets->js();
self::assertEmpty($js);
$js = $this->assets->js('footer');
self::assertSame('<script src="/test.js"></script>' . PHP_EOL, $js);
$array = $this->assets->getJs();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type": "js",
"elements": {
"asset": "/test.js",
"asset_type": "js",
"order": 0,
"group": "footer",
"position": "pipeline",
"priority": 10,
"attributes": [],
"modified": false,
"query": ""
}
}';
self::assertJsonStringEqualsJsonString($expected, $actual);
//Test async / defer
$this->assets->reset();
$this->assets->addJs('test.js', ['loading' => 'async']);
$js = $this->assets->js();
self::assertSame('<script src="/test.js" async></script>' . PHP_EOL, $js);
$array = $this->assets->getJs();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type": "js",
"elements": {
"asset": "/test.js",
"asset_type": "js",
"order": 0,
"group": "head",
"position": "pipeline",
"priority": 10,
"attributes": {
"loading": "async"
},
"modified": false,
"query": ""
}
}';
self::assertJsonStringEqualsJsonString($expected, $actual);
$this->assets->reset();
$this->assets->addJs('test.js', ['loading' => 'defer']);
$js = $this->assets->js();
self::assertSame('<script src="/test.js" defer></script>' . PHP_EOL, $js);
$array = $this->assets->getJs();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type": "js",
"elements": {
"asset": "/test.js",
"asset_type": "js",
"order": 0,
"group": "head",
"position": "pipeline",
"priority": 10,
"attributes": {
"loading": "defer"
},
"modified": false,
"query": ""
}
}';
self::assertJsonStringEqualsJsonString($expected, $actual);
//Test inline
$this->assets->reset();
$this->assets->setJsPipeline(true);
$this->assets->addJs('/system/assets/jquery/jquery-3.x.min.js');
$js = $this->assets->js('head', ['loading' => 'inline']);
self::assertStringContainsString('"jquery",[],function()', $js);
$this->assets->reset();
$this->assets->setCssPipeline(true);
$this->assets->addCss('/system/assets/debugger/phpdebugbar.css');
$css = $this->assets->css('head', ['loading' => 'inline']);
self::assertStringContainsString('div.phpdebugbar', $css);
$this->assets->reset();
$this->assets->setCssPipeline(true);
$this->assets->addCss('https://fonts.googleapis.com/css?family=Roboto');
$css = $this->assets->css('head', ['loading' => 'inline']);
self::assertStringContainsString('font-family:\'Roboto\';', $css);
//Test adding media queries
$this->assets->reset();
$this->assets->add('test.css', ['media' => 'only screen and (min-width: 640px)']);
$css = $this->assets->css();
self::assertSame('<link href="/test.css" type="text/css" rel="stylesheet" media="only screen and (min-width: 640px)">' . PHP_EOL, $css);
}
public function testAddingAssetPropertiesWithArray(): void
{
//Test adding assets with object to define properties
$this->assets->reset();
$this->assets->addJs('test.js', ['loading' => 'async']);
$js = $this->assets->js();
self::assertSame('<script src="/test.js" async></script>' . PHP_EOL, $js);
$this->assets->reset();
}
public function testAddingJSAssetPropertiesWithArrayFromCollection(): void
{
//Test adding properties with array
$this->assets->reset();
$this->assets->addJs('jquery', ['loading' => 'async']);
$js = $this->assets->js();
self::assertSame('<script src="/system/assets/jquery/jquery-3.x.min.js" async></script>' . PHP_EOL, $js);
//Test priority too
$this->assets->reset();
$this->assets->addJs('jquery', ['loading' => 'async', 'priority' => 1]);
$this->assets->addJs('test.js', ['loading' => 'async', 'priority' => 2]);
$js = $this->assets->js();
self::assertSame('<script src="/test.js" async></script>' . PHP_EOL .
'<script src="/system/assets/jquery/jquery-3.x.min.js" async></script>' . PHP_EOL, $js);
//Test multiple groups
$this->assets->reset();
$this->assets->addJs('jquery', ['loading' => 'async', 'priority' => 1, 'group' => 'footer']);
$this->assets->addJs('test.js', ['loading' => 'async', 'priority' => 2]);
$js = $this->assets->js();
self::assertSame('<script src="/test.js" async></script>' . PHP_EOL, $js);
$js = $this->assets->js('footer');
self::assertSame('<script src="/system/assets/jquery/jquery-3.x.min.js" async></script>' . PHP_EOL, $js);
//Test adding array of assets
//Test priority too
$this->assets->reset();
$this->assets->addJs(['jquery', 'test.js'], ['loading' => 'async']);
$js = $this->assets->js();
self::assertSame('<script src="/system/assets/jquery/jquery-3.x.min.js" async></script>' . PHP_EOL .
'<script src="/test.js" async></script>' . PHP_EOL, $js);
}
public function testAddingLegacyFormat(): void
{
// regular CSS add
//test addCss(). Test adding asset to a separate group
$this->assets->reset();
$this->assets->addCSS('test.css', 15, true, 'bottom', 'async');
$css = $this->assets->css('bottom');
self::assertSame('<link href="/test.css" type="text/css" rel="stylesheet" async>' . PHP_EOL, $css);
$array = $this->assets->getCss();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type":"css",
"elements":{
"asset":"\/test.css",
"asset_type":"css",
"order":0,
"group":"bottom",
"position":"pipeline",
"priority":15,
"attributes":{
"type":"text\/css",
"rel":"stylesheet",
"loading":"async"
},
"modified":false,
"query":""
}
}';
self::assertJsonStringEqualsJsonString($expected, $actual);
$this->assets->reset();
$this->assets->addJs('test.js', 15, false, 'defer', 'bottom');
$js = $this->assets->js('bottom');
self::assertSame('<script src="/test.js" defer></script>' . PHP_EOL, $js);
$array = $this->assets->getJs();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type": "js",
"elements": {
"asset": "/test.js",
"asset_type": "js",
"order": 0,
"group": "bottom",
"position": "after",
"priority": 15,
"attributes": {
"loading": "defer"
},
"modified": false,
"query": ""
}
}';
self::assertJsonStringEqualsJsonString($expected, $actual);
$this->assets->reset();
$this->assets->addInlineCss('body { color: black }', 15, 'bottom');
$css = $this->assets->css('bottom');
self::assertSame('<style>' . PHP_EOL . 'body { color: black }' . PHP_EOL . '</style>' . PHP_EOL, $css);
$this->assets->reset();
$this->assets->addInlineJs('alert("test")', 15, 'bottom', ['id' => 'foo']);
$js = $this->assets->js('bottom');
self::assertSame('<script id="foo">' . PHP_EOL . 'alert("test")' . PHP_EOL . '</script>' . PHP_EOL, $js);
}
public function testAddingCSSAssetPropertiesWithArrayFromCollection(): void
{
$this->assets->registerCollection('test', ['/system/assets/whoops.css']);
//Test priority too
$this->assets->reset();
$this->assets->addCss('test', ['priority' => 1]);
$this->assets->addCss('test.css', ['priority' => 2]);
$css = $this->assets->css();
self::assertSame('<link href="/test.css" type="text/css" rel="stylesheet">' . PHP_EOL .
'<link href="/system/assets/whoops.css" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
//Test multiple groups
$this->assets->reset();
$this->assets->addCss('test', ['priority' => 1, 'group' => 'footer']);
$this->assets->addCss('test.css', ['priority' => 2]);
$css = $this->assets->css();
self::assertSame('<link href="/test.css" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
$css = $this->assets->css('footer');
self::assertSame('<link href="/system/assets/whoops.css" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
//Test adding array of assets
//Test priority too
$this->assets->reset();
$this->assets->addCss(['test', 'test.css'], ['loading' => 'async']);
$css = $this->assets->css();
self::assertSame('<link href="/system/assets/whoops.css" type="text/css" rel="stylesheet" async>' . PHP_EOL .
'<link href="/test.css" type="text/css" rel="stylesheet" async>' . PHP_EOL, $css);
}
public function testAddingAssetPropertiesWithArrayFromCollectionAndParameters(): void
{
$this->assets->registerCollection('collection_multi_params', [
'foo.js' => [ 'defer' => true ],
'bar.js' => [ 'integrity' => 'sha512-abc123' ],
'foobar.css' => [ 'defer' => null, 'loading' => null ]
]);
// # Test adding properties with array
$this->assets->addJs('collection_multi_params', ['loading' => 'async']);
$js = $this->assets->js();
// expected output
$expected = [
'<script src="/foo.js" async defer="1"></script>',
'<script src="/bar.js" async integrity="sha512-abc123"></script>',
'<script src="/foobar.css"></script>',
];
self::assertCount(count($expected), array_filter(explode("\n", $js)));
self::assertSame(implode("\n", $expected) . PHP_EOL, $js);
// # Test priority as second argument + render JS should not have any css
$this->assets->reset();
$this->assets->add('low_priority.js', 1);
$this->assets->add('collection_multi_params', 2);
$js = $this->assets->js();
// expected output
$expected = [
'<script src="/foo.js" defer="1"></script>',
'<script src="/bar.js" integrity="sha512-abc123"></script>',
'<script src="/low_priority.js"></script>',
];
self::assertCount(3, array_filter(explode("\n", $js)));
self::assertSame(implode("\n", $expected) . PHP_EOL, $js);
// # Test rendering CSS, should not have any JS
$this->assets->reset();
$this->assets->add('collection_multi_params', [ 'class' => '__classname' ]);
$css = $this->assets->css();
// expected output
$expected = [
'<link href="/foobar.css" type="text/css" rel="stylesheet" class="__classname">',
];
self::assertCount(1, array_filter(explode("\n", $css)));
self::assertSame(implode("\n", $expected) . PHP_EOL, $css);
}
public function testPriorityOfAssets(): void
{
$this->assets->reset();
$this->assets->add('test.css');
$this->assets->add('test-after.css');
$css = $this->assets->css();
self::assertSame('<link href="/test.css" type="text/css" rel="stylesheet">' . PHP_EOL .
'<link href="/test-after.css" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
//----------------
$this->assets->reset();
$this->assets->add('test-after.css', 1);
$this->assets->add('test.css', 2);
$css = $this->assets->css();
self::assertSame('<link href="/test.css" type="text/css" rel="stylesheet">' . PHP_EOL .
'<link href="/test-after.css" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
//----------------
$this->assets->reset();
$this->assets->add('test-after.css', 1);
$this->assets->add('test.css', 2);
$this->assets->add('test-before.css', 3);
$css = $this->assets->css();
self::assertSame('<link href="/test-before.css" type="text/css" rel="stylesheet">' . PHP_EOL .
'<link href="/test.css" type="text/css" rel="stylesheet">' . PHP_EOL .
'<link href="/test-after.css" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
}
public function testPipeline(): void
{
$this->assets->reset();
//File not existing. Pipeline searches for that file without reaching it. Output is empty.
$this->assets->add('test.css', null, true);
$this->assets->setCssPipeline(true);
$css = $this->assets->css();
self::assertRegExp('#<link href=\"\/assets\/(.*).css\" type=\"text\/css\" rel=\"stylesheet\">#', $css);
//Add a core Grav CSS file, which is found. Pipeline will now return a file
$this->assets->add('/system/assets/debugger/phpdebugbar', null, true);
$css = $this->assets->css();
self::assertRegExp('#<link href=\"\/assets\/(.*).css\" type=\"text\/css\" rel=\"stylesheet\">#', $css);
}
public function testPipelineWithTimestamp(): void
{
$this->assets->reset();
$this->assets->setTimestamp('foo');
$this->assets->setCssPipeline(true);
//Add a core Grav CSS file, which is found. Pipeline will now return a file
$this->assets->add('/system/assets/debugger.css', null, true);
$css = $this->assets->css();
self::assertRegExp('#<link href=\"\/assets\/(.*).css\?foo\" type=\"text\/css\" rel=\"stylesheet\">#', $css);
}
public function testInline(): void
{
$this->assets->reset();
//File not existing. Pipeline searches for that file without reaching it. Output is empty.
$this->assets->add('test.css', ['loading' => 'inline']);
$css = $this->assets->css();
self::assertSame("<style>\n\n</style>\n", $css);
$this->assets->reset();
//Add a core Grav CSS file, which is found. Pipeline will now return its content.
$this->assets->addCss('https://fonts.googleapis.com/css?family=Roboto', ['loading' => 'inline']);
$this->assets->addCss('/system/assets/debugger/phpdebugbar.css', ['loading' => 'inline']);
$css = $this->assets->css();
self::assertStringContainsString('font-family: \'Roboto\';', $css);
self::assertStringContainsString('div.phpdebugbar-header', $css);
}
public function testInlinePipeline(): void
{
$this->assets->reset();
$this->assets->setCssPipeline(true);
//File not existing. Pipeline searches for that file without reaching it. Output is empty.
$this->assets->add('test.css');
$css = $this->assets->css('head', ['loading' => 'inline']);
self::assertSame("<style>\n\n</style>\n", $css);
//Add a core Grav CSS file, which is found. Pipeline will now return its content.
$this->assets->addCss('https://fonts.googleapis.com/css?family=Roboto', null, true);
$this->assets->add('/system/assets/debugger/phpdebugbar.css', null, true);
$css = $this->assets->css('head', ['loading' => 'inline']);
self::assertStringContainsString('font-family:\'Roboto\';', $css);
self::assertStringContainsString('div.phpdebugbar', $css);
}
public function testAddAsyncJs(): void
{
$this->assets->reset();
$this->assets->addAsyncJs('jquery');
$js = $this->assets->js();
self::assertSame('<script src="/system/assets/jquery/jquery-3.x.min.js" async></script>' . PHP_EOL, $js);
}
public function testAddDeferJs(): void
{
$this->assets->reset();
$this->assets->addDeferJs('jquery');
$js = $this->assets->js();
self::assertSame('<script src="/system/assets/jquery/jquery-3.x.min.js" defer></script>' . PHP_EOL, $js);
}
public function testTimestamps(): void
{
// local CSS nothing extra
$this->assets->reset();
$this->assets->setTimestamp('foo');
$this->assets->addCSS('test.css');
$css = $this->assets->css();
self::assertSame('<link href="/test.css?foo" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
// local CSS already with param
$this->assets->reset();
$this->assets->setTimestamp('foo');
$this->assets->addCSS('test.css?bar');
$css = $this->assets->css();
self::assertSame('<link href="/test.css?bar&foo" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
// external CSS already
$this->assets->reset();
$this->assets->setTimestamp('foo');
$this->assets->addCSS('http://somesite.com/test.css');
$css = $this->assets->css();
self::assertSame('<link href="http://somesite.com/test.css?foo" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
// external CSS already with param
$this->assets->reset();
$this->assets->setTimestamp('foo');
$this->assets->addCSS('http://somesite.com/test.css?bar');
$css = $this->assets->css();
self::assertSame('<link href="http://somesite.com/test.css?bar&foo" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
// local JS nothing extra
$this->assets->reset();
$this->assets->setTimestamp('foo');
$this->assets->addJs('test.js');
$css = $this->assets->js();
self::assertSame('<script src="/test.js?foo"></script>' . PHP_EOL, $css);
// local JS already with param
$this->assets->reset();
$this->assets->setTimestamp('foo');
$this->assets->addJs('test.js?bar');
$css = $this->assets->js();
self::assertSame('<script src="/test.js?bar&foo"></script>' . PHP_EOL, $css);
// external JS already
$this->assets->reset();
$this->assets->setTimestamp('foo');
$this->assets->addJs('http://somesite.com/test.js');
$css = $this->assets->js();
self::assertSame('<script src="http://somesite.com/test.js?foo"></script>' . PHP_EOL, $css);
// external JS already with param
$this->assets->reset();
$this->assets->setTimestamp('foo');
$this->assets->addJs('http://somesite.com/test.js?bar');
$css = $this->assets->js();
self::assertSame('<script src="http://somesite.com/test.js?bar&foo"></script>' . PHP_EOL, $css);
}
public function testAddInlineCss(): void
{
$this->assets->reset();
$this->assets->addInlineCss('body { color: black }');
$css = $this->assets->css();
self::assertSame('<style>' . PHP_EOL . 'body { color: black }' . PHP_EOL . '</style>' . PHP_EOL, $css);
}
public function testAddInlineJs(): void
{
$this->assets->reset();
$this->assets->addInlineJs('alert("test")');
$js = $this->assets->js();
self::assertSame('<script>' . PHP_EOL . 'alert("test")' . PHP_EOL . '</script>' . PHP_EOL, $js);
}
public function testGetCollections(): void
{
self::assertIsArray($this->assets->getCollections());
self::assertContains('jquery', array_keys($this->assets->getCollections()));
self::assertContains('system://assets/jquery/jquery-3.x.min.js', $this->assets->getCollections());
}
public function testExists(): void
{
self::assertTrue($this->assets->exists('jquery'));
self::assertFalse($this->assets->exists('another-unexisting-library'));
}
public function testRegisterCollection(): void
{
$this->assets->registerCollection('debugger', ['/system/assets/debugger.css']);
self::assertTrue($this->assets->exists('debugger'));
self::assertContains('debugger', array_keys($this->assets->getCollections()));
}
public function testRegisterCollectionWithParameters(): void
{
$this->assets->registerCollection('collection_multi_params', [
'foo.js' => [ 'defer' => true ],
'bar.js' => [ 'integrity' => 'sha512-abc123' ],
'foobar.css' => [ 'defer' => null ],
]);
self::assertTrue($this->assets->exists('collection_multi_params'));
$collection = $this->assets->getCollections()['collection_multi_params'];
self::assertArrayHasKey('foo.js', $collection);
self::assertArrayHasKey('bar.js', $collection);
self::assertArrayHasKey('foobar.css', $collection);
self::assertArrayHasKey('defer', $collection['foo.js']);
self::assertArrayHasKey('defer', $collection['foobar.css']);
self::assertNull($collection['foobar.css']['defer']);
self::assertTrue($collection['foo.js']['defer']);
}
public function testReset(): void
{
$this->assets->addInlineJs('alert("test")');
$this->assets->reset();
self::assertCount(0, (array) $this->assets->getJs());
$this->assets->addAsyncJs('jquery');
$this->assets->reset();
self::assertCount(0, (array) $this->assets->getJs());
$this->assets->addInlineCss('body { color: black }');
$this->assets->reset();
self::assertCount(0, (array) $this->assets->getCss());
$this->assets->add('/system/assets/debugger.css', null, true);
$this->assets->reset();
self::assertCount(0, (array) $this->assets->getCss());
}
public function testResetJs(): void
{
$this->assets->addInlineJs('alert("test")');
$this->assets->resetJs();
self::assertCount(0, (array) $this->assets->getJs());
$this->assets->addAsyncJs('jquery');
$this->assets->resetJs();
self::assertCount(0, (array) $this->assets->getJs());
}
public function testResetCss(): void
{
$this->assets->addInlineCss('body { color: black }');
$this->assets->resetCss();
self::assertCount(0, (array) $this->assets->getCss());
$this->assets->add('/system/assets/debugger.css', null, true);
$this->assets->resetCss();
self::assertCount(0, (array) $this->assets->getCss());
}
public function testAddDirCss(): void
{
$this->assets->addDirCss('/system');
self::assertIsArray($this->assets->getCss());
self::assertGreaterThan(0, (array) $this->assets->getCss());
self::assertIsArray($this->assets->getJs());
self::assertCount(0, (array) $this->assets->getJs());
$this->assets->reset();
$this->assets->addDirCss('/system/assets');
self::assertIsArray($this->assets->getCss());
self::assertGreaterThan(0, (array) $this->assets->getCss());
self::assertIsArray($this->assets->getJs());
self::assertCount(0, (array) $this->assets->getJs());
$this->assets->reset();
$this->assets->addDirJs('/system');
self::assertIsArray($this->assets->getCss());
self::assertCount(0, (array) $this->assets->getCss());
self::assertIsArray($this->assets->getJs());
self::assertGreaterThan(0, (array) $this->assets->getJs());
$this->assets->reset();
$this->assets->addDirJs('/system/assets');
self::assertIsArray($this->assets->getCss());
self::assertCount(0, (array) $this->assets->getCss());
self::assertIsArray($this->assets->getJs());
self::assertGreaterThan(0, (array) $this->assets->getJs());
$this->assets->reset();
$this->assets->addDir('/system/assets');
self::assertIsArray($this->assets->getCss());
self::assertGreaterThan(0, (array) $this->assets->getCss());
self::assertIsArray($this->assets->getJs());
self::assertGreaterThan(0, (array) $this->assets->getJs());
//Use streams
$this->assets->reset();
$this->assets->addDir('system://assets');
self::assertIsArray($this->assets->getCss());
self::assertGreaterThan(0, (array) $this->assets->getCss());
self::assertIsArray($this->assets->getJs());
self::assertGreaterThan(0, (array) $this->assets->getJs());
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/unit/Grav/Common/Markdown/ParsedownTest.php | tests/unit/Grav/Common/Markdown/ParsedownTest.php | <?php
use Codeception\Util\Fixtures;
use Grav\Common\Grav;
use Grav\Common\Page\Markdown\Excerpts;
use Grav\Common\Uri;
use Grav\Common\Config\Config;
use Grav\Common\Page\Pages;
use Grav\Common\Markdown\Parsedown;
use Grav\Common\Language\Language;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
/**
* Class ParsedownTest
*/
class ParsedownTest extends \Codeception\TestCase\Test
{
/** @var Parsedown $parsedown */
protected $parsedown;
/** @var Grav $grav */
protected $grav;
/** @var Pages $pages */
protected $pages;
/** @var Config $config */
protected $config;
/** @var Uri $uri */
protected $uri;
/** @var Language $language */
protected $language;
protected $old_home;
protected function _before(): void
{
$grav = Fixtures::get('grav');
$this->grav = $grav();
$this->pages = $this->grav['pages'];
$this->config = $this->grav['config'];
$this->uri = $this->grav['uri'];
$this->language = $this->grav['language'];
$this->old_home = $this->config->get('system.home.alias');
$this->config->set('system.home.alias', '/item1');
$this->config->set('system.absolute_urls', false);
$this->config->set('system.languages.supported', []);
unset($this->grav['language']);
$this->grav['language'] = new Language($this->grav);
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$locator->addPath('page', '', 'tests/fake/nested-site/user/pages', false);
$this->pages->init();
$defaults = [
'markdown' => [
'extra' => false,
'auto_line_breaks' => false,
'auto_url_links' => false,
'escape_markup' => false,
'special_chars' => ['>' => 'gt', '<' => 'lt'],
],
'images' => $this->config->get('system.images', [])
];
$page = $this->pages->find('/item2/item2-2');
$excerpts = new Excerpts($page, $defaults);
$this->parsedown = new Parsedown($excerpts);
}
protected function _after(): void
{
$this->config->set('system.home.alias', $this->old_home);
}
public function testImages(): void
{
$this->config->set('system.languages.supported', ['fr','en']);
unset($this->grav['language']);
$this->grav['language'] = new Language($this->grav);
$this->uri->initializeWithURL('http://testing.dev/fr/item2/item2-2')->init();
self::assertSame(
'<p><img alt="" src="/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
self::assertRegexp(
'|<p><img alt="" src="\/images\/.*-cache-image.jpe?g\?foo=1" \/><\/p>|',
$this->parsedown->text('')
);
$this->uri->initializeWithURL('http://testing.dev/item2/item2-2')->init();
self::assertSame(
'<p><img alt="" src="/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
self::assertRegexp(
'|<p><img alt="" src="\/images\/.*-cache-image.jpe?g\?foo=1" \/><\/p>|',
$this->parsedown->text('')
);
self::assertRegexp(
'|<p><img alt="" src="\/images\/.*-home-cache-image.jpe?g" \/><\/p>|',
$this->parsedown->text('')
);
self::assertSame(
'<p><img src="/item2/item2-2/missing-image.jpg" alt="" /></p>',
$this->parsedown->text('')
);
self::assertSame(
'<p><img src="/home-missing-image.jpg" alt="" /></p>',
$this->parsedown->text('')
);
self::assertSame(
'<p><img src="/home-missing-image.jpg" alt="" /></p>',
$this->parsedown->text('')
);
self::assertSame(
'<p><img src="https://getgrav-grav.netdna-ssl.com/user/pages/media/grav-logo.svg" alt="" /></p>',
$this->parsedown->text('')
);
}
public function testImagesSubDir(): void
{
$this->config->set('system.images.cache_all', false);
$this->uri->initializeWithUrlAndRootPath('http://testing.dev/subdir/item2/item2-2', '/subdir')->init();
self::assertRegexp(
'|<p><img alt="" src="\/subdir\/images\/.*-home-cache-image.jpe?g" \/><\/p>|',
$this->parsedown->text('')
);
self::assertSame(
'<p><img alt="" src="/subdir/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
self::assertRegexp(
'|<p><img alt="" src="\/subdir\/images\/.*-cache-image.jpe?g" \/><\/p>|',
$this->parsedown->text('')
);
self::assertSame(
'<p><img src="/subdir/item2/item2-2/missing-image.jpg" alt="" /></p>',
$this->parsedown->text('')
);
self::assertSame(
'<p><img src="/subdir/home-missing-image.jpg" alt="" /></p>',
$this->parsedown->text('')
);
}
public function testImagesAbsoluteUrls(): void
{
$this->config->set('system.absolute_urls', true);
$this->uri->initializeWithURL('http://testing.dev/item2/item2-2')->init();
self::assertSame(
'<p><img alt="" src="http://testing.dev/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
self::assertRegexp(
'|<p><img alt="" src="http:\/\/testing.dev\/images\/.*-cache-image.jpe?g" \/><\/p>|',
$this->parsedown->text('')
);
self::assertRegexp(
'|<p><img alt="" src="http:\/\/testing.dev\/images\/.*-home-cache-image.jpe?g" \/><\/p>|',
$this->parsedown->text('')
);
self::assertSame(
'<p><img src="http://testing.dev/item2/item2-2/missing-image.jpg" alt="" /></p>',
$this->parsedown->text('')
);
self::assertSame(
'<p><img src="http://testing.dev/home-missing-image.jpg" alt="" /></p>',
$this->parsedown->text('')
);
}
public function testImagesSubDirAbsoluteUrls(): void
{
$this->config->set('system.absolute_urls', true);
$this->uri->initializeWithUrlAndRootPath('http://testing.dev/subdir/item2/item2-2', '/subdir')->init();
self::assertSame(
'<p><img alt="" src="http://testing.dev/subdir/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
self::assertRegexp(
'|<p><img alt="" src="http:\/\/testing.dev\/subdir\/images\/.*-cache-image.jpe?g" \/><\/p>|',
$this->parsedown->text('')
);
self::assertRegexp(
'|<p><img alt="" src="http:\/\/testing.dev\/subdir\/images\/.*-home-cache-image.jpe?g" \/><\/p>|',
$this->parsedown->text('')
);
self::assertSame(
'<p><img src="http://testing.dev/subdir/item2/item2-2/missing-image.jpg" alt="" /></p>',
$this->parsedown->text('')
);
self::assertSame(
'<p><img src="http://testing.dev/subdir/home-missing-image.jpg" alt="" /></p>',
$this->parsedown->text('')
);
}
public function testImagesAttributes(): void
{
$this->uri->initializeWithURL('http://testing.dev/item2/item2-2')->init();
self::assertSame(
'<p><img title="My Title" alt="" src="/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
self::assertSame(
'<p><img alt="" class="foo" src="/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
self::assertSame(
'<p><img alt="" class="foo bar" src="/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
self::assertSame(
'<p><img alt="" id="foo" src="/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
self::assertSame(
'<p><img alt="Alt Text" id="foo" src="/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
self::assertSame(
'<p><img alt="Alt Text" class="bar" id="foo" src="/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
self::assertSame(
'<p><img title="My Title" alt="Alt Text" class="bar" id="foo" src="/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
}
public function testImagesDefaults(): void
{
/**
* Testing default 'loading'
*/
$this->setImagesDefaults(['loading' => 'auto']);
// loading should NOT be added to image by default
self::assertSame(
'<p><img alt="" src="/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
// loading="lazy" should be added when default is overridden by ?loading=lazy
self::assertSame(
'<p><img loading="lazy" alt="" src="/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
$this->setImagesDefaults(['loading' => 'lazy']);
// loading="lazy" should be added by default
self::assertSame(
'<p><img loading="lazy" alt="" src="/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
// loading should not be added when default is overridden by ?loading=auto
self::assertSame(
'<p><img alt="" src="/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
// loading="eager" should be added when default is overridden by ?loading=eager
self::assertSame(
'<p><img loading="eager" alt="" src="/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
}
public function testCLSAutoSizes(): void
{
$this->config->set('system.images.cls.auto_sizes', false);
$this->uri->initializeWithURL('http://testing.dev/item2/item2-2')->init();
self::assertSame(
'<p><img alt="" src="/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
self::assertSame(
'<p><img height="1" width="1" alt="" src="/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
self::assertSame(
'<p><img alt="" src="/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" width="1024" height="768" /></p>',
$this->parsedown->text('')
);
$this->config->set('system.images.cls.auto_sizes', true);
self::assertSame(
'<p><img alt="" src="/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" width="1024" height="768" /></p>',
$this->parsedown->text('')
);
self::assertSame(
'<p><img height="1" width="1" alt="" src="/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
self::assertSame(
'<p><img alt="" src="/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
self::assertRegExp(
'/width="400" height="200"/',
$this->parsedown->text('')
);
$this->config->set('system.images.cls.retina_scale', 2);
self::assertRegExp(
'/width="400" height="200"/',
$this->parsedown->text('')
);
$this->config->set('system.images.cls.retina_scale', 4);
self::assertRegExp(
'/width="200" height="100"/',
$this->parsedown->text('')
);
self::assertRegExp(
'/width="266" height="133"/',
$this->parsedown->text('')
);
$this->config->set('system.images.cls.aspect_ratio', true);
self::assertRegExp(
'/style="--aspect-ratio: 800\/400;"/',
$this->parsedown->text('')
);
$this->config->set('system.images.cls.aspect_ratio', false);
self::assertRegExp(
'/style="--aspect-ratio: 800\/400;"/',
$this->parsedown->text('')
);
}
public function testRootImages(): void
{
$this->uri->initializeWithURL('http://testing.dev/')->init();
$defaults = [
'markdown' => [
'extra' => false,
'auto_line_breaks' => false,
'auto_url_links' => false,
'escape_markup' => false,
'special_chars' => ['>' => 'gt', '<' => 'lt'],
],
'images' => $this->config->get('system.images', [])
];
$page = $this->pages->find('/');
$excerpts = new Excerpts($page, $defaults);
$this->parsedown = new Parsedown($excerpts);
self::assertSame(
'<p><img alt="" src="/tests/fake/nested-site/user/pages/01.item1/home-sample-image.jpg" /></p>',
$this->parsedown->text('')
);
self::assertRegexp(
'|<p><img alt="" src="\/images\/.*-home-cache-image.jpe?g" \/><\/p>|',
$this->parsedown->text('')
);
self::assertRegexp(
'|<p><img alt="" src="\/images\/.*-home-cache-image.jpe?g\?foo=1" \/><\/p>|',
$this->parsedown->text('')
);
self::assertSame(
'<p><img src="/home-missing-image.jpg" alt="" /></p>',
$this->parsedown->text('')
);
$this->config->set('system.languages.supported', ['fr','en']);
unset($this->grav['language']);
$this->grav['language'] = new Language($this->grav);
$this->uri->initializeWithURL('http://testing.dev/fr/item2/item2-2')->init();
self::assertSame(
'<p><img alt="" src="/tests/fake/nested-site/user/pages/01.item1/home-sample-image.jpg" /></p>',
$this->parsedown->text('')
);
}
public function testRootImagesSubDirAbsoluteUrls(): void
{
$this->config->set('system.absolute_urls', true);
$this->uri->initializeWithUrlAndRootPath('http://testing.dev/subdir/item2/item2-2', '/subdir')->init();
self::assertSame(
'<p><img alt="" src="http://testing.dev/subdir/tests/fake/nested-site/user/pages/02.item2/02.item2-2/sample-image.jpg" /></p>',
$this->parsedown->text('')
);
self::assertRegexp(
'|<p><img alt="" src="http:\/\/testing.dev\/subdir\/images\/.*-cache-image.jpe?g" \/><\/p>|',
$this->parsedown->text('')
);
self::assertRegexp(
'|<p><img alt="" src="http:\/\/testing.dev\/subdir\/images\/.*-home-cache-image.jpe?g" \/><\/p>|',
$this->parsedown->text('')
);
self::assertSame(
'<p><img src="http://testing.dev/subdir/item2/item2-2/missing-image.jpg" alt="" /></p>',
$this->parsedown->text('')
);
self::assertSame(
'<p><img src="http://testing.dev/subdir/home-missing-image.jpg" alt="" /></p>',
$this->parsedown->text('')
);
}
public function testRootAbsoluteLinks(): void
{
$this->uri->initializeWithURL('http://testing.dev/')->init();
$defaults = [
'markdown' => [
'extra' => false,
'auto_line_breaks' => false,
'auto_url_links' => false,
'escape_markup' => false,
'special_chars' => ['>' => 'gt', '<' => 'lt'],
],
'images' => $this->config->get('system.images', [])
];
$page = $this->pages->find('/');
$excerpts = new Excerpts($page, $defaults);
$this->parsedown = new Parsedown($excerpts);
self::assertSame(
'<p><a href="/item1/item1-3">Down a Level</a></p>',
$this->parsedown->text('[Down a Level](item1-3)')
);
self::assertSame(
'<p><a href="/item2">Peer Page</a></p>',
$this->parsedown->text('[Peer Page](../item2)')
);
self::assertSame(
'<p><a href="/?foo=bar">With Query</a></p>',
$this->parsedown->text('[With Query](?foo=bar)')
);
self::assertSame(
'<p><a href="/foo:bar">With Param</a></p>',
$this->parsedown->text('[With Param](/foo:bar)')
);
self::assertSame(
'<p><a href="#foo">With Anchor</a></p>',
$this->parsedown->text('[With Anchor](#foo)')
);
$this->config->set('system.languages.supported', ['fr','en']);
unset($this->grav['language']);
$this->grav['language'] = new Language($this->grav);
$this->uri->initializeWithURL('http://testing.dev/fr/item2/item2-2')->init();
self::assertSame(
'<p><a href="/fr/item2">Peer Page</a></p>',
$this->parsedown->text('[Peer Page](../item2)')
);
self::assertSame(
'<p><a href="/fr/item1/item1-3">Down a Level</a></p>',
$this->parsedown->text('[Down a Level](item1-3)')
);
self::assertSame(
'<p><a href="/fr/?foo=bar">With Query</a></p>',
$this->parsedown->text('[With Query](?foo=bar)')
);
self::assertSame(
'<p><a href="/fr/foo:bar">With Param</a></p>',
$this->parsedown->text('[With Param](/foo:bar)')
);
self::assertSame(
'<p><a href="#foo">With Anchor</a></p>',
$this->parsedown->text('[With Anchor](#foo)')
);
}
public function testAnchorLinksLangRelativeUrls(): void
{
$this->config->set('system.languages.supported', ['fr','en']);
unset($this->grav['language']);
$this->grav['language'] = new Language($this->grav);
$this->uri->initializeWithURL('http://testing.dev/fr/item2/item2-2')->init();
self::assertSame(
'<p><a href="#foo">Current Anchor</a></p>',
$this->parsedown->text('[Current Anchor](#foo)')
);
self::assertSame(
'<p><a href="/fr/#foo">Root Anchor</a></p>',
$this->parsedown->text('[Root Anchor](/#foo)')
);
self::assertSame(
'<p><a href="/fr/item2/item2-1#foo">Peer Anchor</a></p>',
$this->parsedown->text('[Peer Anchor](../item2-1#foo)')
);
self::assertSame(
'<p><a href="/fr/item2/item2-1#foo">Peer Anchor 2</a></p>',
$this->parsedown->text('[Peer Anchor 2](../item2-1/#foo)')
);
}
public function testAnchorLinksLangAbsoluteUrls(): void
{
$this->config->set('system.absolute_urls', true);
$this->config->set('system.languages.supported', ['fr','en']);
unset($this->grav['language']);
$this->grav['language'] = new Language($this->grav);
$this->uri->initializeWithURL('http://testing.dev/fr/item2/item2-2')->init();
self::assertSame(
'<p><a href="#foo">Current Anchor</a></p>',
$this->parsedown->text('[Current Anchor](#foo)')
);
self::assertSame(
'<p><a href="http://testing.dev/fr/item2/item2-1#foo">Peer Anchor</a></p>',
$this->parsedown->text('[Peer Anchor](../item2-1#foo)')
);
self::assertSame(
'<p><a href="http://testing.dev/fr/item2/item2-1#foo">Peer Anchor 2</a></p>',
$this->parsedown->text('[Peer Anchor 2](../item2-1/#foo)')
);
self::assertSame(
'<p><a href="http://testing.dev/fr/#foo">Root Anchor</a></p>',
$this->parsedown->text('[Root Anchor](/#foo)')
);
}
public function testExternalLinks(): void
{
self::assertSame(
'<p><a href="http://www.cnn.com">cnn.com</a></p>',
$this->parsedown->text('[cnn.com](http://www.cnn.com)')
);
self::assertSame(
'<p><a href="https://www.google.com">google.com</a></p>',
$this->parsedown->text('[google.com](https://www.google.com)')
);
self::assertSame(
'<p><a href="https://github.com/getgrav/grav/issues/new?title=%5Badd-resource%5D%20New%20Plugin%2FTheme&body=Hello%20%2A%2AThere%2A%2A">complex url</a></p>',
$this->parsedown->text('[complex url](https://github.com/getgrav/grav/issues/new?title=[add-resource]%20New%20Plugin/Theme&body=Hello%20**There**)')
);
}
public function testExternalLinksSubDir(): void
{
$this->uri->initializeWithUrlAndRootPath('http://testing.dev/subdir/item2/item2-2', '/subdir')->init();
self::assertSame(
'<p><a href="http://www.cnn.com">cnn.com</a></p>',
$this->parsedown->text('[cnn.com](http://www.cnn.com)')
);
self::assertSame(
'<p><a href="https://www.google.com">google.com</a></p>',
$this->parsedown->text('[google.com](https://www.google.com)')
);
}
public function testExternalLinksSubDirAbsoluteUrls(): void
{
$this->config->set('system.absolute_urls', true);
$this->uri->initializeWithUrlAndRootPath('http://testing.dev/subdir/item2/item2-2', '/subdir')->init();
self::assertSame(
'<p><a href="http://www.cnn.com">cnn.com</a></p>',
$this->parsedown->text('[cnn.com](http://www.cnn.com)')
);
self::assertSame(
'<p><a href="https://www.google.com">google.com</a></p>',
$this->parsedown->text('[google.com](https://www.google.com)')
);
}
public function testAnchorLinksRelativeUrls(): void
{
$this->uri->initializeWithURL('http://testing.dev/item2/item2-2')->init();
self::assertSame(
'<p><a href="#foo">Current Anchor</a></p>',
$this->parsedown->text('[Current Anchor](#foo)')
);
self::assertSame(
'<p><a href="/#foo">Root Anchor</a></p>',
$this->parsedown->text('[Root Anchor](/#foo)')
);
self::assertSame(
'<p><a href="/item2/item2-1#foo">Peer Anchor</a></p>',
$this->parsedown->text('[Peer Anchor](../item2-1#foo)')
);
self::assertSame(
'<p><a href="/item2/item2-1#foo">Peer Anchor 2</a></p>',
$this->parsedown->text('[Peer Anchor 2](../item2-1/#foo)')
);
}
public function testAnchorLinksAbsoluteUrls(): void
{
$this->config->set('system.absolute_urls', true);
$this->uri->initializeWithURL('http://testing.dev/item2/item2-2')->init();
self::assertSame(
'<p><a href="#foo">Current Anchor</a></p>',
$this->parsedown->text('[Current Anchor](#foo)')
);
self::assertSame(
'<p><a href="http://testing.dev/item2/item2-1#foo">Peer Anchor</a></p>',
$this->parsedown->text('[Peer Anchor](../item2-1#foo)')
);
self::assertSame(
'<p><a href="http://testing.dev/item2/item2-1#foo">Peer Anchor 2</a></p>',
$this->parsedown->text('[Peer Anchor 2](../item2-1/#foo)')
);
self::assertSame(
'<p><a href="http://testing.dev/#foo">Root Anchor</a></p>',
$this->parsedown->text('[Root Anchor](/#foo)')
);
}
public function testAnchorLinksWithPortAbsoluteUrls(): void
{
$this->config->set('system.absolute_urls', true);
$this->uri->initializeWithURL('http://testing.dev:8080/item2/item2-2')->init();
self::assertSame(
'<p><a href="http://testing.dev:8080/item2/item2-1#foo">Peer Anchor</a></p>',
$this->parsedown->text('[Peer Anchor](../item2-1#foo)')
);
self::assertSame(
'<p><a href="http://testing.dev:8080/item2/item2-1#foo">Peer Anchor 2</a></p>',
$this->parsedown->text('[Peer Anchor 2](../item2-1/#foo)')
);
self::assertSame(
'<p><a href="#foo">Current Anchor</a></p>',
$this->parsedown->text('[Current Anchor](#foo)')
);
self::assertSame(
'<p><a href="http://testing.dev:8080/#foo">Root Anchor</a></p>',
$this->parsedown->text('[Root Anchor](/#foo)')
);
}
public function testAnchorLinksSubDirRelativeUrls(): void
{
$this->uri->initializeWithUrlAndRootPath('http://testing.dev/subdir/item2/item2-2', '/subdir')->init();
self::assertSame(
'<p><a href="/subdir/item2/item2-1#foo">Peer Anchor</a></p>',
$this->parsedown->text('[Peer Anchor](../item2-1#foo)')
);
self::assertSame(
'<p><a href="/subdir/item2/item2-1#foo">Peer Anchor 2</a></p>',
$this->parsedown->text('[Peer Anchor 2](../item2-1/#foo)')
);
self::assertSame(
'<p><a href="#foo">Current Anchor</a></p>',
$this->parsedown->text('[Current Anchor](#foo)')
);
self::assertSame(
'<p><a href="/subdir/#foo">Root Anchor</a></p>',
$this->parsedown->text('[Root Anchor](/#foo)')
);
}
public function testAnchorLinksSubDirAbsoluteUrls(): void
{
$this->config->set('system.absolute_urls', true);
$this->uri->initializeWithUrlAndRootPath('http://testing.dev/subdir/item2/item2-2', '/subdir')->init();
self::assertSame(
'<p><a href="http://testing.dev/subdir/item2/item2-1#foo">Peer Anchor</a></p>',
$this->parsedown->text('[Peer Anchor](../item2-1#foo)')
);
self::assertSame(
'<p><a href="http://testing.dev/subdir/item2/item2-1#foo">Peer Anchor 2</a></p>',
$this->parsedown->text('[Peer Anchor 2](../item2-1/#foo)')
);
self::assertSame(
'<p><a href="#foo">Current Anchor</a></p>',
$this->parsedown->text('[Current Anchor](#foo)')
);
self::assertSame(
'<p><a href="http://testing.dev/subdir/#foo">Root Anchor</a></p>',
$this->parsedown->text('[Root Anchor](/#foo)')
);
}
public function testSlugRelativeLinks(): void
{
$this->uri->initializeWithURL('http://testing.dev/item2/item2-2')->init();
self::assertSame(
'<p><a href="/">Up to Root Level</a></p>',
$this->parsedown->text('[Up to Root Level](../..)')
);
self::assertSame(
'<p><a href="/item2/item2-1">Peer Page</a></p>',
$this->parsedown->text('[Peer Page](../item2-1)')
);
self::assertSame(
'<p><a href="/item2/item2-2/item2-2-1">Down a Level</a></p>',
$this->parsedown->text('[Down a Level](item2-2-1)')
);
self::assertSame(
'<p><a href="/item2">Up a Level</a></p>',
$this->parsedown->text('[Up a Level](..)')
);
self::assertSame(
'<p><a href="/item3/item3-3">Up and Down</a></p>',
$this->parsedown->text('[Up and Down](../../item3/item3-3)')
);
self::assertSame(
'<p><a href="/item2/item2-2/item2-2-1?foo=bar">Down a Level with Query</a></p>',
$this->parsedown->text('[Down a Level with Query](item2-2-1?foo=bar)')
);
self::assertSame(
'<p><a href="/item2?foo=bar">Up a Level with Query</a></p>',
$this->parsedown->text('[Up a Level with Query](../?foo=bar)')
);
self::assertSame(
'<p><a href="/item3/item3-3?foo=bar">Up and Down with Query</a></p>',
$this->parsedown->text('[Up and Down with Query](../../item3/item3-3?foo=bar)')
);
self::assertSame(
'<p><a href="/item3/item3-3/foo:bar">Up and Down with Param</a></p>',
$this->parsedown->text('[Up and Down with Param](../../item3/item3-3/foo:bar)')
);
self::assertSame(
'<p><a href="/item3/item3-3#foo">Up and Down with Anchor</a></p>',
$this->parsedown->text('[Up and Down with Anchor](../../item3/item3-3#foo)')
);
}
public function testSlugRelativeLinksAbsoluteUrls(): void
{
$this->config->set('system.absolute_urls', true);
$this->uri->initializeWithURL('http://testing.dev/item2/item2-2')->init();
self::assertSame(
'<p><a href="http://testing.dev/item2/item2-1">Peer Page</a></p>',
$this->parsedown->text('[Peer Page](../item2-1)')
);
self::assertSame(
'<p><a href="http://testing.dev/item2/item2-2/item2-2-1">Down a Level</a></p>',
$this->parsedown->text('[Down a Level](item2-2-1)')
);
self::assertSame(
'<p><a href="http://testing.dev/item2">Up a Level</a></p>',
$this->parsedown->text('[Up a Level](..)')
);
self::assertSame(
'<p><a href="http://testing.dev/">Up to Root Level</a></p>',
$this->parsedown->text('[Up to Root Level](../..)')
);
self::assertSame(
'<p><a href="http://testing.dev/item3/item3-3">Up and Down</a></p>',
$this->parsedown->text('[Up and Down](../../item3/item3-3)')
);
self::assertSame(
'<p><a href="http://testing.dev/item2/item2-2/item2-2-1?foo=bar">Down a Level with Query</a></p>',
$this->parsedown->text('[Down a Level with Query](item2-2-1?foo=bar)')
);
self::assertSame(
'<p><a href="http://testing.dev/item2?foo=bar">Up a Level with Query</a></p>',
$this->parsedown->text('[Up a Level with Query](../?foo=bar)')
);
self::assertSame(
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | true |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/unit/Grav/Common/Helpers/ExcerptsTest.php | tests/unit/Grav/Common/Helpers/ExcerptsTest.php | <?php
use Codeception\Util\Fixtures;
use Grav\Common\Helpers\Excerpts;
use Grav\Common\Grav;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Uri;
use Grav\Common\Config\Config;
use Grav\Common\Page\Pages;
use Grav\Common\Language\Language;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
/**
* Class ExcerptsTest
*/
class ExcerptsTest extends \Codeception\TestCase\Test
{
/** @var Parsedown $parsedown */
protected $parsedown;
/** @var Grav $grav */
protected $grav;
/** @var PageInterface $page */
protected $page;
/** @var Pages $pages */
protected $pages;
/** @var Config $config */
protected $config;
/** @var Uri $uri */
protected $uri;
/** @var Language $language */
protected $language;
protected $old_home;
protected function _before(): void
{
$grav = Fixtures::get('grav');
$this->grav = $grav();
$this->pages = $this->grav['pages'];
$this->config = $this->grav['config'];
$this->uri = $this->grav['uri'];
$this->language = $this->grav['language'];
$this->old_home = $this->config->get('system.home.alias');
$this->config->set('system.home.alias', '/item1');
$this->config->set('system.absolute_urls', false);
$this->config->set('system.languages.supported', []);
unset($this->grav['language']);
$this->grav['language'] = new Language($this->grav);
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$locator->addPath('page', '', 'tests/fake/nested-site/user/pages', false);
$this->pages->init();
$defaults = [
'extra' => false,
'auto_line_breaks' => false,
'auto_url_links' => false,
'escape_markup' => false,
'special_chars' => ['>' => 'gt', '<' => 'lt'],
];
$this->page = $this->pages->find('/item2/item2-2');
$this->uri->initializeWithURL('http://testing.dev/item2/item2-2')->init();
}
protected function _after(): void
{
$this->config->set('system.home.alias', $this->old_home);
}
public function testProcessImageHtml(): void
{
self::assertRegexp(
'|<img alt="Sample Image" src="\/images\/.*-sample-image.jpe?g\" data-src="sample-image\.jpg\?cropZoom=300,300" \/>|',
Excerpts::processImageHtml('<img src="sample-image.jpg?cropZoom=300,300" alt="Sample Image" />', $this->page)
);
self::assertRegexp(
'|<img alt="Sample Image" class="foo" src="\/images\/.*-sample-image.jpe?g\" data-src="sample-image\.jpg\?classes=foo" \/>|',
Excerpts::processImageHtml('<img src="sample-image.jpg?classes=foo" alt="Sample Image" />', $this->page)
);
}
public function testNoProcess(): void
{
self::assertStringStartsWith(
'<a href="https://play.google.com/store/apps/details?hl=de" id="org.jitsi.meet" target="_blank"',
Excerpts::processLinkHtml('<a href="https://play.google.com/store/apps/details?id=org.jitsi.meet&hl=de&target=_blank">regular process</a>')
);
self::assertStringStartsWith(
'<a href="https://play.google.com/store/apps/details?id=org.jitsi.meet&hl=de&target=_blank"',
Excerpts::processLinkHtml('<a href="https://play.google.com/store/apps/details?id=org.jitsi.meet&hl=de&target=_blank&noprocess">noprocess</a>')
);
self::assertStringStartsWith(
'<a href="https://play.google.com/store/apps/details?id=org.jitsi.meet&hl=de" target="_blank"',
Excerpts::processLinkHtml('<a href="https://play.google.com/store/apps/details?id=org.jitsi.meet&hl=de&target=_blank&noprocess=id">noprocess=id</a>')
);
}
public function testTarget(): void
{
self::assertStringStartsWith(
'<a href="https://play.google.com/store/apps/details" target="_blank"',
Excerpts::processLinkHtml('<a href="https://play.google.com/store/apps/details?target=_blank">only target</a>')
);
self::assertStringStartsWith(
'<a href="https://meet.weikamp.biz/Support" rel="nofollow" target="_blank"',
Excerpts::processLinkHtml('<a href="https://meet.weikamp.biz/Support?rel=nofollow&target=_blank">target and rel</a>')
);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/unit/Grav/Common/Twig/Extensions/GravExtensionTest.php | tests/unit/Grav/Common/Twig/Extensions/GravExtensionTest.php | <?php
use Codeception\Util\Fixtures;
use Grav\Common\Grav;
use Grav\Common\Twig\Extension\GravExtension;
/**
* Class GravExtensionTest
*/
class GravExtensionTest extends \Codeception\TestCase\Test
{
/** @var Grav $grav */
protected $grav;
/** @var GravExtension $twig_ext */
protected $twig_ext;
protected function _before(): void
{
$this->grav = Fixtures::get('grav');
$this->twig_ext = new GravExtension();
}
public function testInflectorFilter(): void
{
self::assertSame('people', $this->twig_ext->inflectorFilter('plural', 'person'));
self::assertSame('shoe', $this->twig_ext->inflectorFilter('singular', 'shoes'));
self::assertSame('Welcome Page', $this->twig_ext->inflectorFilter('title', 'welcome page'));
self::assertSame('SendEmail', $this->twig_ext->inflectorFilter('camel', 'send_email'));
self::assertSame('camel_cased', $this->twig_ext->inflectorFilter('underscor', 'CamelCased'));
self::assertSame('something-text', $this->twig_ext->inflectorFilter('hyphen', 'Something Text'));
self::assertSame('Something text to read', $this->twig_ext->inflectorFilter('human', 'something_text_to_read'));
self::assertSame(5, $this->twig_ext->inflectorFilter('month', '175'));
self::assertSame('10th', $this->twig_ext->inflectorFilter('ordinal', '10'));
}
public function testMd5Filter(): void
{
self::assertSame(md5('grav'), $this->twig_ext->md5Filter('grav'));
self::assertSame(md5('devs@getgrav.org'), $this->twig_ext->md5Filter('devs@getgrav.org'));
}
public function testKsortFilter(): void
{
$object = array("name"=>"Bob","age"=>8,"colour"=>"red");
self::assertSame(array("age"=>8,"colour"=>"red","name"=>"Bob"), $this->twig_ext->ksortFilter($object));
}
public function testContainsFilter(): void
{
self::assertTrue($this->twig_ext->containsFilter('grav', 'grav'));
self::assertTrue($this->twig_ext->containsFilter('So, I found this new cms, called grav, and it\'s pretty awesome guys', 'grav'));
}
public function testNicetimeFilter(): void
{
$now = time();
$threeMinutes = time() - (60*3);
$threeHours = time() - (60*60*3);
$threeDays = time() - (60*60*24*3);
$threeMonths = time() - (60*60*24*30*3);
$threeYears = time() - (60*60*24*365*3);
$measures = ['minutes','hours','days','months','years'];
self::assertSame('No date provided', $this->twig_ext->nicetimeFunc(null));
for ($i=0; $i<count($measures); $i++) {
$time = 'three' . ucfirst($measures[$i]);
self::assertSame('3 ' . $measures[$i] . ' ago', $this->twig_ext->nicetimeFunc($$time));
}
}
public function testRandomizeFilter(): void
{
$array = [1,2,3,4,5];
self::assertContains(2, $this->twig_ext->randomizeFilter($array));
self::assertSame($array, $this->twig_ext->randomizeFilter($array, 5));
self::assertSame($array[0], $this->twig_ext->randomizeFilter($array, 1)[0]);
self::assertSame($array[3], $this->twig_ext->randomizeFilter($array, 4)[3]);
self::assertSame($array[1], $this->twig_ext->randomizeFilter($array, 4)[1]);
}
public function testModulusFilter(): void
{
self::assertSame(3, $this->twig_ext->modulusFilter(3, 4));
self::assertSame(1, $this->twig_ext->modulusFilter(11, 2));
self::assertSame(0, $this->twig_ext->modulusFilter(10, 2));
self::assertSame(2, $this->twig_ext->modulusFilter(10, 4));
}
public function testAbsoluteUrlFilter(): void
{
}
public function testMarkdownFilter(): void
{
}
public function testStartsWithFilter(): void
{
}
public function testEndsWithFilter(): void
{
}
public function testDefinedDefaultFilter(): void
{
}
public function testRtrimFilter(): void
{
}
public function testLtrimFilter(): void
{
}
public function testRepeatFunc(): void
{
}
public function testRegexReplace(): void
{
}
public function testUrlFunc(): void
{
}
public function testEvaluateFunc(): void
{
}
public function testDump(): void
{
}
public function testGistFunc(): void
{
}
public function testRandomStringFunc(): void
{
}
public function testPadFilter(): void
{
}
public function testArrayFunc(): void
{
self::assertSame(
'this is my text',
$this->twig_ext->regexReplace('<p>this is my text</p>', '(<\/?p>)', '')
);
self::assertSame(
'<i>this is my text</i>',
$this->twig_ext->regexReplace('<p>this is my text</p>', ['(<p>)','(<\/p>)'], ['<i>','</i>'])
);
}
public function testArrayKeyValue(): void
{
self::assertSame(
['meat' => 'steak'],
$this->twig_ext->arrayKeyValueFunc('meat', 'steak')
);
self::assertSame(
['fruit' => 'apple', 'meat' => 'steak'],
$this->twig_ext->arrayKeyValueFunc('meat', 'steak', ['fruit' => 'apple'])
);
}
public function stringFunc(): void
{
}
public function testRangeFunc(): void
{
$hundred = [];
for ($i = 0; $i <= 100; $i++) {
$hundred[] = $i;
}
self::assertSame([0], $this->twig_ext->rangeFunc(0, 0));
self::assertSame([0, 1, 2], $this->twig_ext->rangeFunc(0, 2));
self::assertSame([0, 5, 10, 15], $this->twig_ext->rangeFunc(0, 16, 5));
// default (min 0, max 100, step 1)
self::assertSame($hundred, $this->twig_ext->rangeFunc());
// 95 items, starting from 5, (min 5, max 100, step 1)
self::assertSame(array_slice($hundred, 5), $this->twig_ext->rangeFunc(5));
// reversed range
self::assertSame(array_reverse($hundred), $this->twig_ext->rangeFunc(100, 0));
self::assertSame([4, 2, 0], $this->twig_ext->rangeFunc(4, 0, 2));
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/unit/Grav/Common/Page/PagesTest.php | tests/unit/Grav/Common/Page/PagesTest.php | <?php
use Codeception\Util\Fixtures;
use Grav\Common\Grav;
use Grav\Common\Page\Pages;
use Grav\Common\Page\Page;
use Grav\Common\Page\Interfaces\PageInterface;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
/**
* Class PagesTest
*/
class PagesTest extends \Codeception\TestCase\Test
{
/** @var Grav $grav */
protected $grav;
/** @var Pages $pages */
protected $pages;
/** @var PageInterface $root_page */
protected $root_page;
protected function _before(): void
{
$grav = Fixtures::get('grav');
$this->grav = $grav();
$this->pages = $this->grav['pages'];
$this->grav['config']->set('system.home.alias', '/home');
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$locator->addPath('page', '', 'tests/fake/simple-site/user/pages', false);
$this->pages->init();
}
public function testBase(): void
{
self::assertSame('', $this->pages->base());
$this->pages->base('/test');
self::assertSame('/test', $this->pages->base());
$this->pages->base('');
self::assertSame($this->pages->base(), '');
}
public function testLastModified(): void
{
self::assertNull($this->pages->lastModified());
$this->pages->lastModified('test');
self::assertSame('test', $this->pages->lastModified());
}
public function testInstances(): void
{
self::assertIsArray($this->pages->instances());
foreach ($this->pages->instances() as $instance) {
self::assertInstanceOf(PageInterface::class, $instance);
}
}
public function testRoutes(): void
{
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$folder = $locator->findResource('tests://');
self::assertIsArray($this->pages->routes());
self::assertSame($folder . '/fake/simple-site/user/pages/01.home', $this->pages->routes()['/']);
self::assertSame($folder . '/fake/simple-site/user/pages/01.home', $this->pages->routes()['/home']);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog', $this->pages->routes()['/blog']);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog/post-one', $this->pages->routes()['/blog/post-one']);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog/post-two', $this->pages->routes()['/blog/post-two']);
self::assertSame($folder . '/fake/simple-site/user/pages/03.about', $this->pages->routes()['/about']);
}
public function testAddPage(): void
{
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$folder = $locator->findResource('tests://');
$path = $folder . '/fake/single-pages/01.simple-page/default.md';
$aPage = new Page();
$aPage->init(new \SplFileInfo($path));
$this->pages->addPage($aPage, '/new-page');
self::assertContains('/new-page', array_keys($this->pages->routes()));
self::assertSame($folder . '/fake/single-pages/01.simple-page', $this->pages->routes()['/new-page']);
}
public function testSort(): void
{
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$folder = $locator->findResource('tests://');
$aPage = $this->pages->find('/blog');
$subPagesSorted = $this->pages->sort($aPage);
self::assertIsArray($subPagesSorted);
self::assertCount(2, $subPagesSorted);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog/post-one', array_keys($subPagesSorted)[0]);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog/post-two', array_keys($subPagesSorted)[1]);
self::assertContains($folder . '/fake/simple-site/user/pages/02.blog/post-one', array_keys($subPagesSorted));
self::assertContains($folder . '/fake/simple-site/user/pages/02.blog/post-two', array_keys($subPagesSorted));
self::assertSame(['slug' => 'post-one'], $subPagesSorted[$folder . '/fake/simple-site/user/pages/02.blog/post-one']);
self::assertSame(['slug' => 'post-two'], $subPagesSorted[$folder . '/fake/simple-site/user/pages/02.blog/post-two']);
$subPagesSorted = $this->pages->sort($aPage, null, 'desc');
self::assertIsArray($subPagesSorted);
self::assertCount(2, $subPagesSorted);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog/post-two', array_keys($subPagesSorted)[0]);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog/post-one', array_keys($subPagesSorted)[1]);
self::assertContains($folder . '/fake/simple-site/user/pages/02.blog/post-one', array_keys($subPagesSorted));
self::assertContains($folder . '/fake/simple-site/user/pages/02.blog/post-two', array_keys($subPagesSorted));
self::assertSame(['slug' => 'post-one'], $subPagesSorted[$folder . '/fake/simple-site/user/pages/02.blog/post-one']);
self::assertSame(['slug' => 'post-two'], $subPagesSorted[$folder . '/fake/simple-site/user/pages/02.blog/post-two']);
}
public function testSortCollection(): void
{
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$folder = $locator->findResource('tests://');
$aPage = $this->pages->find('/blog');
$subPagesSorted = $this->pages->sortCollection($aPage->children(), $aPage->orderBy());
self::assertIsArray($subPagesSorted);
self::assertCount(2, $subPagesSorted);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog/post-one', array_keys($subPagesSorted)[0]);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog/post-two', array_keys($subPagesSorted)[1]);
self::assertContains($folder . '/fake/simple-site/user/pages/02.blog/post-one', array_keys($subPagesSorted));
self::assertContains($folder . '/fake/simple-site/user/pages/02.blog/post-two', array_keys($subPagesSorted));
self::assertSame(['slug' => 'post-one'], $subPagesSorted[$folder . '/fake/simple-site/user/pages/02.blog/post-one']);
self::assertSame(['slug' => 'post-two'], $subPagesSorted[$folder . '/fake/simple-site/user/pages/02.blog/post-two']);
$subPagesSorted = $this->pages->sortCollection($aPage->children(), $aPage->orderBy(), 'desc');
self::assertIsArray($subPagesSorted);
self::assertCount(2, $subPagesSorted);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog/post-two', array_keys($subPagesSorted)[0]);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog/post-one', array_keys($subPagesSorted)[1]);
self::assertContains($folder . '/fake/simple-site/user/pages/02.blog/post-one', array_keys($subPagesSorted));
self::assertContains($folder . '/fake/simple-site/user/pages/02.blog/post-two', array_keys($subPagesSorted));
self::assertSame(['slug' => 'post-one'], $subPagesSorted[$folder . '/fake/simple-site/user/pages/02.blog/post-one']);
self::assertSame(['slug' => 'post-two'], $subPagesSorted[$folder . '/fake/simple-site/user/pages/02.blog/post-two']);
}
public function testGet(): void
{
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$folder = $locator->findResource('tests://');
//Page existing
$aPage = $this->pages->get($folder . '/fake/simple-site/user/pages/03.about');
self::assertInstanceOf(PageInterface::class, $aPage);
//Page not existing
$anotherPage = $this->pages->get($folder . '/fake/simple-site/user/pages/03.non-existing');
self::assertNull($anotherPage);
}
public function testChildren(): void
{
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$folder = $locator->findResource('tests://');
//Page existing
$children = $this->pages->children($folder . '/fake/simple-site/user/pages/02.blog');
self::assertInstanceOf('Grav\Common\Page\Collection', $children);
//Page not existing
$children = $this->pages->children($folder . '/fake/whatever/non-existing');
self::assertSame([], $children->toArray());
}
public function testDispatch(): void
{
$aPage = $this->pages->dispatch('/blog');
self::assertInstanceOf(PageInterface::class, $aPage);
$aPage = $this->pages->dispatch('/about');
self::assertInstanceOf(PageInterface::class, $aPage);
$aPage = $this->pages->dispatch('/blog/post-one');
self::assertInstanceOf(PageInterface::class, $aPage);
//Page not existing
$aPage = $this->pages->dispatch('/non-existing');
self::assertNull($aPage);
}
public function testRoot(): void
{
$root = $this->pages->root();
self::assertInstanceOf(PageInterface::class, $root);
self::assertSame('pages', $root->folder());
}
public function testBlueprints(): void
{
}
public function testAll()
{
self::assertIsObject($this->pages->all());
self::assertIsArray($this->pages->all()->toArray());
foreach ($this->pages->all() as $page) {
self::assertInstanceOf(PageInterface::class, $page);
}
}
public function testGetList(): void
{
$list = $this->pages->getList();
self::assertIsArray($list);
self::assertSame('—-▸ Home', $list['/']);
self::assertSame('—-▸ Blog', $list['/blog']);
}
public function testTranslatedLanguages(): void
{
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$folder = $locator->findResource('tests://');
$page = $this->pages->get($folder . '/fake/simple-site/user/pages/04.page-translated');
$this->assertInstanceOf(PageInterface::class, $page);
$translatedLanguages = $page->translatedLanguages();
$this->assertIsArray($translatedLanguages);
$this->assertSame(["en" => "/page-translated", "fr" => "/page-translated"], $translatedLanguages);
}
public function testLongPathTranslatedLanguages(): void
{
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$folder = $locator->findResource('tests://');
$page = $this->pages->get($folder . '/fake/simple-site/user/pages/05.translatedlong/part2');
$this->assertInstanceOf(PageInterface::class, $page);
$translatedLanguages = $page->translatedLanguages();
$this->assertIsArray($translatedLanguages);
$this->assertSame(["en" => "/translatedlong/part2", "fr" => "/translatedlong/part2"], $translatedLanguages);
}
public function testGetTypes(): void
{
}
public function testTypes(): void
{
}
public function testModularTypes(): void
{
}
public function testPageTypes(): void
{
}
public function testAccessLevels(): void
{
}
public function testParents(): void
{
}
public function testParentsRawRoutes(): void
{
}
public function testGetHomeRoute(): void
{
}
public function testResetPages(): void
{
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/unit/Grav/Common/Language/LanguageCodesTest.php | tests/unit/Grav/Common/Language/LanguageCodesTest.php | <?php
use Grav\Common\Language\LanguageCodes;
/**
* Class ParsedownTest
*/
class LanguageCodesTest extends \Codeception\TestCase\Test
{
public function testRtl(): void
{
self::assertSame(
'ltr',
LanguageCodes::getOrientation('en')
);
self::assertSame(
'rtl',
LanguageCodes::getOrientation('ar')
);
self::assertSame(
'rtl',
LanguageCodes::getOrientation('he')
);
self::assertTrue(LanguageCodes::isRtl('ar'));
self::assertFalse(LanguageCodes::isRtl('fr'));
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/unit/Grav/Common/GPM/GPMTest.php | tests/unit/Grav/Common/GPM/GPMTest.php | <?php
use Codeception\Util\Fixtures;
use Grav\Common\Grav;
use Grav\Common\GPM\GPM;
define('EXCEPTION_BAD_FORMAT', 1);
define('EXCEPTION_INCOMPATIBLE_VERSIONS', 2);
/**
* Class GpmStub
*/
class GpmStub extends GPM
{
/** @var array */
public $data;
/**
* @inheritdoc
*/
public function findPackage($search, $ignore_exception = false)
{
return $this->data[$search] ?? false;
}
/**
* @inheritdoc
*/
public function findPackages($searches = [])
{
return $this->data;
}
}
/**
* Class InstallCommandTest
*/
class GpmTest extends \Codeception\TestCase\Test
{
/** @var Grav $grav */
protected $grav;
/** @var GpmStub */
protected $gpm;
protected function _before(): void
{
$this->grav = Fixtures::get('grav');
$this->gpm = new GpmStub();
}
protected function _after(): void
{
}
public function testCalculateMergedDependenciesOfPackages(): void
{
//////////////////////////////////////////////////////////////////////////////////////////
// First working example
//////////////////////////////////////////////////////////////////////////////////////////
$this->gpm->data = [
'admin' => (object)[
'dependencies' => [
['name' => 'grav', 'version' => '>=1.0.10'],
['name' => 'form', 'version' => '~2.0'],
['name' => 'login', 'version' => '>=2.0'],
['name' => 'errors', 'version' => '*'],
['name' => 'problems'],
]
],
'test' => (object)[
'dependencies' => [
['name' => 'errors', 'version' => '>=1.0']
]
],
'grav',
'form' => (object)[
'dependencies' => [
['name' => 'errors', 'version' => '>=3.2']
]
]
];
$packages = ['admin', 'test'];
$dependencies = $this->gpm->calculateMergedDependenciesOfPackages($packages);
self::assertIsArray($dependencies);
self::assertCount(5, $dependencies);
self::assertSame('>=1.0.10', $dependencies['grav']);
self::assertArrayHasKey('errors', $dependencies);
self::assertArrayHasKey('problems', $dependencies);
//////////////////////////////////////////////////////////////////////////////////////////
// Second working example
//////////////////////////////////////////////////////////////////////////////////////////
$packages = ['admin', 'form'];
$dependencies = $this->gpm->calculateMergedDependenciesOfPackages($packages);
self::assertIsArray($dependencies);
self::assertCount(5, $dependencies);
self::assertSame('>=3.2', $dependencies['errors']);
//////////////////////////////////////////////////////////////////////////////////////////
// Third working example
//////////////////////////////////////////////////////////////////////////////////////////
$this->gpm->data = [
'admin' => (object)[
'dependencies' => [
['name' => 'errors', 'version' => '>=4.0'],
]
],
'test' => (object)[
'dependencies' => [
['name' => 'errors', 'version' => '>=1.0']
]
],
'another' => (object)[
'dependencies' => [
['name' => 'errors', 'version' => '>=3.2']
]
]
];
$packages = ['admin', 'test', 'another'];
$dependencies = $this->gpm->calculateMergedDependenciesOfPackages($packages);
self::assertIsArray($dependencies);
self::assertCount(1, $dependencies);
self::assertSame('>=4.0', $dependencies['errors']);
//////////////////////////////////////////////////////////////////////////////////////////
// Test alpha / beta / rc
//////////////////////////////////////////////////////////////////////////////////////////
$this->gpm->data = [
'admin' => (object)[
'dependencies' => [
['name' => 'package1', 'version' => '>=4.0.0-rc1'],
['name' => 'package4', 'version' => '>=3.2.0'],
]
],
'test' => (object)[
'dependencies' => [
['name' => 'package1', 'version' => '>=4.0.0-rc2'],
['name' => 'package2', 'version' => '>=3.2.0-alpha'],
['name' => 'package3', 'version' => '>=3.2.0-alpha.2'],
['name' => 'package4', 'version' => '>=3.2.0-alpha'],
]
],
'another' => (object)[
'dependencies' => [
['name' => 'package2', 'version' => '>=3.2.0-beta.11'],
['name' => 'package3', 'version' => '>=3.2.0-alpha.1'],
['name' => 'package4', 'version' => '>=3.2.0-beta'],
]
]
];
$packages = ['admin', 'test', 'another'];
$dependencies = $this->gpm->calculateMergedDependenciesOfPackages($packages);
self::assertSame('>=4.0.0-rc2', $dependencies['package1']);
self::assertSame('>=3.2.0-beta.11', $dependencies['package2']);
self::assertSame('>=3.2.0-alpha.2', $dependencies['package3']);
self::assertSame('>=3.2.0', $dependencies['package4']);
//////////////////////////////////////////////////////////////////////////////////////////
// Raise exception if no version is specified
//////////////////////////////////////////////////////////////////////////////////////////
$this->gpm->data = [
'admin' => (object)[
'dependencies' => [
['name' => 'errors', 'version' => '>=4.0'],
]
],
'test' => (object)[
'dependencies' => [
['name' => 'errors', 'version' => '>=']
]
],
];
$packages = ['admin', 'test'];
try {
$this->gpm->calculateMergedDependenciesOfPackages($packages);
self::fail('Expected Exception not thrown');
} catch (Exception $e) {
self::assertEquals(EXCEPTION_BAD_FORMAT, $e->getCode());
self::assertStringStartsWith('Bad format for version of dependency', $e->getMessage());
}
//////////////////////////////////////////////////////////////////////////////////////////
// Raise exception if incompatible versions are specified
//////////////////////////////////////////////////////////////////////////////////////////
$this->gpm->data = [
'admin' => (object)[
'dependencies' => [
['name' => 'errors', 'version' => '~4.0'],
]
],
'test' => (object)[
'dependencies' => [
['name' => 'errors', 'version' => '~3.0']
]
],
];
$packages = ['admin', 'test'];
try {
$this->gpm->calculateMergedDependenciesOfPackages($packages);
self::fail('Expected Exception not thrown');
} catch (Exception $e) {
self::assertEquals(EXCEPTION_INCOMPATIBLE_VERSIONS, $e->getCode());
self::assertStringEndsWith('required in two incompatible versions', $e->getMessage());
}
//////////////////////////////////////////////////////////////////////////////////////////
// Test dependencies of dependencies
//////////////////////////////////////////////////////////////////////////////////////////
$this->gpm->data = [
'admin' => (object)[
'dependencies' => [
['name' => 'grav', 'version' => '>=1.0.10'],
['name' => 'form', 'version' => '~2.0'],
['name' => 'login', 'version' => '>=2.0'],
['name' => 'errors', 'version' => '*'],
['name' => 'problems'],
]
],
'login' => (object)[
'dependencies' => [
['name' => 'antimatter', 'version' => '>=1.0']
]
],
'grav',
'antimatter' => (object)[
'dependencies' => [
['name' => 'something', 'version' => '>=3.2']
]
]
];
$packages = ['admin'];
$dependencies = $this->gpm->calculateMergedDependenciesOfPackages($packages);
self::assertIsArray($dependencies);
self::assertCount(7, $dependencies);
self::assertSame('>=1.0.10', $dependencies['grav']);
self::assertArrayHasKey('errors', $dependencies);
self::assertArrayHasKey('problems', $dependencies);
self::assertArrayHasKey('antimatter', $dependencies);
self::assertArrayHasKey('something', $dependencies);
self::assertSame('>=3.2', $dependencies['something']);
}
public function testVersionFormatIsNextSignificantRelease(): void
{
self::assertFalse($this->gpm->versionFormatIsNextSignificantRelease('>=1.0'));
self::assertFalse($this->gpm->versionFormatIsNextSignificantRelease('>=2.3.4'));
self::assertFalse($this->gpm->versionFormatIsNextSignificantRelease('>=2.3.x'));
self::assertFalse($this->gpm->versionFormatIsNextSignificantRelease('1.0'));
self::assertTrue($this->gpm->versionFormatIsNextSignificantRelease('~2.3.x'));
self::assertTrue($this->gpm->versionFormatIsNextSignificantRelease('~2.0'));
}
public function testVersionFormatIsEqualOrHigher(): void
{
self::assertTrue($this->gpm->versionFormatIsEqualOrHigher('>=1.0'));
self::assertTrue($this->gpm->versionFormatIsEqualOrHigher('>=2.3.4'));
self::assertTrue($this->gpm->versionFormatIsEqualOrHigher('>=2.3.x'));
self::assertFalse($this->gpm->versionFormatIsEqualOrHigher('~2.3.x'));
self::assertFalse($this->gpm->versionFormatIsEqualOrHigher('1.0'));
}
public function testCheckNextSignificantReleasesAreCompatible(): void
{
/*
* ~1.0 is equivalent to >=1.0 < 2.0.0
* ~1.2 is equivalent to >=1.2 <2.0.0
* ~1.2.3 is equivalent to >=1.2.3 <1.3.0
*/
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('1.0', '1.2'));
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('1.2', '1.0'));
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('1.0', '1.0.10'));
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('1.1', '1.1.10'));
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('30.0', '30.10'));
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('1.0', '1.1.10'));
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('1.0', '1.8'));
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('1.0.1', '1.1'));
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('2.0.0-beta', '2.0'));
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('2.0.0-rc.1', '2.0'));
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('2.0', '2.0.0-alpha'));
self::assertFalse($this->gpm->checkNextSignificantReleasesAreCompatible('1.0', '2.2'));
self::assertFalse($this->gpm->checkNextSignificantReleasesAreCompatible('1.0.0-beta.1', '2.0'));
self::assertFalse($this->gpm->checkNextSignificantReleasesAreCompatible('0.9.99', '1.0.0'));
self::assertFalse($this->gpm->checkNextSignificantReleasesAreCompatible('0.9.99', '1.0.10'));
self::assertFalse($this->gpm->checkNextSignificantReleasesAreCompatible('0.9.99', '1.0.10.2'));
}
public function testCalculateVersionNumberFromDependencyVersion(): void
{
self::assertSame('2.0', $this->gpm->calculateVersionNumberFromDependencyVersion('>=2.0'));
self::assertSame('2.0.2', $this->gpm->calculateVersionNumberFromDependencyVersion('>=2.0.2'));
self::assertSame('2.0.2', $this->gpm->calculateVersionNumberFromDependencyVersion('~2.0.2'));
self::assertSame('1', $this->gpm->calculateVersionNumberFromDependencyVersion('~1'));
self::assertNull($this->gpm->calculateVersionNumberFromDependencyVersion(''));
self::assertNull($this->gpm->calculateVersionNumberFromDependencyVersion('*'));
self::assertSame('2.0.2', $this->gpm->calculateVersionNumberFromDependencyVersion('2.0.2'));
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/unit/Grav/Common/Data/BlueprintTest.php | tests/unit/Grav/Common/Data/BlueprintTest.php | <?php
use Grav\Common\Config\Config;
use Grav\Common\Data\Blueprint;
use Grav\Common\Grav;
/**
* Class InstallCommandTest
*/
class BlueprintTest extends \Codeception\TestCase\Test
{
/**
*/
public function testValidateStrict(): void
{
$blueprint = $this->loadBlueprint('strict');
$blueprint->validate(['test' => 'string']);
}
/**
* @depends testValidateStrict
*/
public function testValidateStrictRequired(): void
{
$blueprint = $this->loadBlueprint('strict');
$this->expectException(\Grav\Common\Data\ValidationException::class);
$blueprint->validate([]);
}
/**
* @depends testValidateStrict
*/
public function testValidateStrictExtra(): void
{
$blueprint = $this->loadBlueprint('strict');
$blueprint->validate(['test' => 'string', 'wrong' => 'field']);
}
/**
* @depends testValidateStrict
*/
public function testValidateStrictExtraException(): void
{
$blueprint = $this->loadBlueprint('strict');
/** @var Config $config */
$config = Grav::instance()['config'];
$var = 'system.strict_mode.blueprint_strict_compat';
$config->set($var, false);
$this->expectException(\Grav\Common\Data\ValidationException::class);
$blueprint->validate(['test' => 'string', 'wrong' => 'field']);
$config->set($var, true);
}
/**
* @param string $filename
* @return Blueprint
*/
protected function loadBlueprint($filename): Blueprint
{
$blueprint = new Blueprint('strict');
$blueprint->setContext(dirname(__DIR__, 3). '/data/blueprints');
$blueprint->load()->init();
return $blueprint;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/unit/Grav/Console/Gpm/InstallCommandTest.php | tests/unit/Grav/Console/Gpm/InstallCommandTest.php | <?php
use Codeception\Util\Fixtures;
use Grav\Common\Grav;
use Grav\Console\Gpm\InstallCommand;
/**
* Class InstallCommandTest
*/
class InstallCommandTest extends \Codeception\TestCase\Test
{
/** @var Grav $grav */
protected $grav;
/** @var InstallCommand */
protected $installCommand;
protected function _before(): void
{
$this->grav = Fixtures::get('grav');
$this->installCommand = new InstallCommand();
}
protected function _after(): void
{
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/unit/Grav/Framework/File/Formatter/CsvFormatterTest.php | tests/unit/Grav/Framework/File/Formatter/CsvFormatterTest.php | <?php
use Grav\Framework\File\Formatter\CsvFormatter;
/**
* Class CsvFormatterTest
*/
class CsvFormatterTest extends \Codeception\TestCase\Test
{
public function testEncodeWithAssocColumns(): void
{
$data = [
['col1' => 1, 'col2' => 2, 'col3' => 3],
['col1' => 'aaa', 'col2' => 'bbb', 'col3' => 'ccc'],
];
$encoded = (new CsvFormatter())->encode($data);
$lines = array_filter(explode(PHP_EOL, $encoded));
self::assertCount(3, $lines);
self::assertEquals('col1,col2,col3', $lines[0]);
}
/**
* TBD - If indexes are all numeric, what's the purpose
* of displaying header
*/
public function testEncodeWithIndexColumns(): void
{
$data = [
[0 => 1, 1 => 2, 2 => 3],
];
$encoded = (new CsvFormatter())->encode($data);
$lines = array_filter(explode(PHP_EOL, $encoded));
self::assertCount(2, $lines);
self::assertEquals('0,1,2', $lines[0]);
}
public function testEncodeEmptyData(): void
{
$encoded = (new CsvFormatter())->encode([]);
self::assertEquals('', $encoded);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/unit/Grav/Framework/Filesystem/FilesystemTest.php | tests/unit/Grav/Framework/Filesystem/FilesystemTest.php | <?php
use Grav\Framework\Filesystem\Filesystem;
/**
* Class FilesystemTest
*/
class FilesystemTest extends \Codeception\TestCase\Test
{
protected $class;
protected $tests = [
'' => [
'parent' => '',
'normalize' => '',
'dirname' => '',
'pathinfo' => [
'basename' => '',
'filename' => '',
]
],
'.' => [
'parent' => '',
'normalize' => '',
'dirname' => '.',
'pathinfo' => [
'dirname' => '.',
'basename' => '.',
'extension' => '',
'filename' => '',
]
],
'./' => [
'parent' => '',
'normalize' => '',
'dirname' => '.',
'pathinfo' => [
'dirname' => '.',
'basename' => '.',
'extension' => '',
'filename' => '',
]
],
'././.' => [
'parent' => '',
'normalize' => '',
'dirname' => './.',
'pathinfo' => [
'dirname' => './.',
'basename' => '.',
'extension' => '',
'filename' => '',
]
],
'.file' => [
'parent' => '.',
'normalize' => '.file',
'dirname' => '.',
'pathinfo' => [
'dirname' => '.',
'basename' => '.file',
'extension' => 'file',
'filename' => '',
]
],
'/' => [
'parent' => '',
'normalize' => '/',
'dirname' => '/',
'pathinfo' => [
'dirname' => '/',
'basename' => '',
'filename' => '',
]
],
'/absolute' => [
'parent' => '/',
'normalize' => '/absolute',
'dirname' => '/',
'pathinfo' => [
'dirname' => '/',
'basename' => 'absolute',
'filename' => 'absolute',
]
],
'/absolute/' => [
'parent' => '/',
'normalize' => '/absolute',
'dirname' => '/',
'pathinfo' => [
'dirname' => '/',
'basename' => 'absolute',
'filename' => 'absolute',
]
],
'/very/long/absolute/path' => [
'parent' => '/very/long/absolute',
'normalize' => '/very/long/absolute/path',
'dirname' => '/very/long/absolute',
'pathinfo' => [
'dirname' => '/very/long/absolute',
'basename' => 'path',
'filename' => 'path',
]
],
'/very/long/absolute/../path' => [
'parent' => '/very/long',
'normalize' => '/very/long/path',
'dirname' => '/very/long/absolute/..',
'pathinfo' => [
'dirname' => '/very/long/absolute/..',
'basename' => 'path',
'filename' => 'path',
]
],
'relative' => [
'parent' => '.',
'normalize' => 'relative',
'dirname' => '.',
'pathinfo' => [
'dirname' => '.',
'basename' => 'relative',
'filename' => 'relative',
]
],
'very/long/relative/path' => [
'parent' => 'very/long/relative',
'normalize' => 'very/long/relative/path',
'dirname' => 'very/long/relative',
'pathinfo' => [
'dirname' => 'very/long/relative',
'basename' => 'path',
'filename' => 'path',
]
],
'path/to/file.jpg' => [
'parent' => 'path/to',
'normalize' => 'path/to/file.jpg',
'dirname' => 'path/to',
'pathinfo' => [
'dirname' => 'path/to',
'basename' => 'file.jpg',
'extension' => 'jpg',
'filename' => 'file',
]
],
'user://' => [
'parent' => '',
'normalize' => 'user://',
'dirname' => 'user://',
'pathinfo' => [
'dirname' => 'user://',
'basename' => '',
'filename' => '',
'scheme' => 'user',
]
],
'user://.' => [
'parent' => '',
'normalize' => 'user://',
'dirname' => 'user://',
'pathinfo' => [
'dirname' => 'user://',
'basename' => '',
'filename' => '',
'scheme' => 'user',
]
],
'user://././.' => [
'parent' => '',
'normalize' => 'user://',
'dirname' => 'user://',
'pathinfo' => [
'dirname' => 'user://',
'basename' => '',
'filename' => '',
'scheme' => 'user',
]
],
'user://./././file' => [
'parent' => 'user://',
'normalize' => 'user://file',
'dirname' => 'user://',
'pathinfo' => [
'dirname' => 'user://',
'basename' => 'file',
'filename' => 'file',
'scheme' => 'user',
]
],
'user://./././folder/file' => [
'parent' => 'user://folder',
'normalize' => 'user://folder/file',
'dirname' => 'user://folder',
'pathinfo' => [
'dirname' => 'user://folder',
'basename' => 'file',
'filename' => 'file',
'scheme' => 'user',
]
],
'user://.file' => [
'parent' => 'user://',
'normalize' => 'user://.file',
'dirname' => 'user://',
'pathinfo' => [
'dirname' => 'user://',
'basename' => '.file',
'extension' => 'file',
'filename' => '',
'scheme' => 'user',
]
],
'user:///' => [
'parent' => '',
'normalize' => 'user:///',
'dirname' => 'user:///',
'pathinfo' => [
'dirname' => 'user:///',
'basename' => '',
'filename' => '',
'scheme' => 'user',
]
],
'user:///absolute' => [
'parent' => 'user:///',
'normalize' => 'user:///absolute',
'dirname' => 'user:///',
'pathinfo' => [
'dirname' => 'user:///',
'basename' => 'absolute',
'filename' => 'absolute',
'scheme' => 'user',
]
],
'user:///very/long/absolute/path' => [
'parent' => 'user:///very/long/absolute',
'normalize' => 'user:///very/long/absolute/path',
'dirname' => 'user:///very/long/absolute',
'pathinfo' => [
'dirname' => 'user:///very/long/absolute',
'basename' => 'path',
'filename' => 'path',
'scheme' => 'user',
]
],
'user://relative' => [
'parent' => 'user://',
'normalize' => 'user://relative',
'dirname' => 'user://',
'pathinfo' => [
'dirname' => 'user://',
'basename' => 'relative',
'filename' => 'relative',
'scheme' => 'user',
]
],
'user://very/long/relative/path' => [
'parent' => 'user://very/long/relative',
'normalize' => 'user://very/long/relative/path',
'dirname' => 'user://very/long/relative',
'pathinfo' => [
'dirname' => 'user://very/long/relative',
'basename' => 'path',
'filename' => 'path',
'scheme' => 'user',
]
],
'user://path/to/file.jpg' => [
'parent' => 'user://path/to',
'normalize' => 'user://path/to/file.jpg',
'dirname' => 'user://path/to',
'pathinfo' => [
'dirname' => 'user://path/to',
'basename' => 'file.jpg',
'extension' => 'jpg',
'filename' => 'file',
'scheme' => 'user',
]
],
];
protected function _before(): void
{
$this->class = Filesystem::getInstance();
}
protected function _after(): void
{
unset($this->class);
}
/**
* @param array $tests
* @param string $method
*/
protected function runTestSet(array $tests, $method): void
{
$class = $this->class;
foreach ($tests as $path => $candidates) {
if (!array_key_exists($method, $candidates)) {
continue;
}
$expected = $candidates[$method];
$result = $class->{$method}($path);
self::assertSame($expected, $result, "Test {$method}('{$path}')");
if (function_exists($method) && !strpos($path, '://')) {
$cmp_result = $method($path);
self::assertSame($cmp_result, $result, "Compare to original {$method}('{$path}')");
}
}
}
public function testParent(): void
{
$this->runTestSet($this->tests, 'parent');
}
public function testNormalize(): void
{
$this->runTestSet($this->tests, 'normalize');
}
public function testDirname(): void
{
$this->runTestSet($this->tests, 'dirname');
}
public function testPathinfo(): void
{
$this->runTestSet($this->tests, 'pathinfo');
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/_support/AcceptanceTester.php | tests/_support/AcceptanceTester.php | <?php
/**
* Inherited Methods
* @method void wantToTest($text)
* @method void wantTo($text)
* @method void execute($callable)
* @method void expectTo($prediction)
* @method void expect($prediction)
* @method void amGoingTo($argumentation)
* @method void am($role)
* @method void lookForwardTo($achieveValue)
* @method void comment($description)
* @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL)
*
* @SuppressWarnings(PHPMD)
*/
class AcceptanceTester extends \Codeception\Actor
{
use _generated\AcceptanceTesterActions;
/**
* Define custom actions here
*/
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/_support/UnitTester.php | tests/_support/UnitTester.php | <?php
/**
* Inherited Methods
* @method void wantToTest($text)
* @method void wantTo($text)
* @method void execute($callable)
* @method void expectTo($prediction)
* @method void expect($prediction)
* @method void amGoingTo($argumentation)
* @method void am($role)
* @method void lookForwardTo($achieveValue)
* @method void comment($description)
* @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL)
*
* @SuppressWarnings(PHPMD)
*/
class UnitTester extends \Codeception\Actor
{
use _generated\UnitTesterActions;
/**
* Define custom actions here
*/
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/_support/FunctionalTester.php | tests/_support/FunctionalTester.php | <?php
/**
* Inherited Methods
* @method void wantToTest($text)
* @method void wantTo($text)
* @method void execute($callable)
* @method void expectTo($prediction)
* @method void expect($prediction)
* @method void amGoingTo($argumentation)
* @method void am($role)
* @method void lookForwardTo($achieveValue)
* @method void comment($description)
* @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL)
*
* @SuppressWarnings(PHPMD)
*/
class FunctionalTester extends \Codeception\Actor
{
use _generated\FunctionalTesterActions;
/**
* Define custom actions here
*/
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/_support/Helper/Functional.php | tests/_support/Helper/Functional.php | <?php
namespace Helper;
// here you can define custom actions
// all public methods declared in helper class will be available in $I
class Functional extends \Codeception\Module
{
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/_support/Helper/Unit.php | tests/_support/Helper/Unit.php | <?php
namespace Helper;
use Codeception;
// here you can define custom actions
// all public methods declared in helper class will be available in $I
/**
* Class Unit
* @package Helper
*/
class Unit extends Codeception\Module
{
/**
* HOOK: used after configuration is loaded
*/
public function _initialize()
{
}
/**
* HOOK: on every Actor class initialization
*/
public function _cleanup()
{
}
/**
* HOOK: before suite
*
* @param array $settings
*/
public function _beforeSuite($settings = [])
{
}
/**
* HOOK: after suite
**/
public function _afterSuite()
{
}
/**
* HOOK: before each step
*
* @param Codeception\Step $step*
*/
public function _beforeStep(Codeception\Step $step)
{
}
/**
* HOOK: after each step
*
* @param Codeception\Step $step
*/
public function _afterStep(Codeception\Step $step)
{
}
/**
* HOOK: before each suite
*
* @param Codeception\TestCase $test
*/
public function _before(Codeception\TestCase $test)
{
}
/**
* HOOK: before each suite
*
* @param Codeception\TestCase $test
*/
public function _after(Codeception\TestCase $test)
{
}
/**
* HOOK: on fail
*
* @param Codeception\TestCase $test
* @param $fail
*/
public function _failed(Codeception\TestCase $test, $fail)
{
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/_support/Helper/Acceptance.php | tests/_support/Helper/Acceptance.php | <?php
namespace Helper;
// here you can define custom actions
// all public methods declared in helper class will be available in $I
class Acceptance extends \Codeception\Module
{
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/functional/_bootstrap.php | tests/functional/_bootstrap.php | <?php
// Here you can initialize variables that will be available to your tests
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/tests/functional/Grav/Console/DirectInstallCommandTest.php | tests/functional/Grav/Console/DirectInstallCommandTest.php | <?php
use Codeception\Util\Fixtures;
use Grav\Common\Grav;
use Grav\Console\Gpm\DirectInstallCommand;
/**
* Class DirectInstallCommandTest
*/
class DirectInstallCommandTest extends \Codeception\TestCase\Test
{
/** @var Grav $grav */
protected $grav;
/** @var DirectInstallCommand */
protected $directInstall;
protected function _before(): void
{
$this->grav = Fixtures::get('grav');
$this->directInstallCommand = new DirectInstallCommand();
}
}
/**
* Why this test file is empty
*
* Wasn't able to call a symfony\console. Kept having $output problem.
* symfony console \NullOutput didn't cut it.
*
* We would also need to Mock tests since downloading packages would
* make tests slow and unreliable. But it's not worth the time ATM.
*
* Look at Gpm/InstallCommandTest.php
*
* For the full story: https://git.io/vSlI3
*/
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/.phan/config.php | .phan/config.php | <?php
return [
"target_php_version" => null,
'pretend_newer_core_functions_exist' => true,
'allow_missing_properties' => false,
'null_casts_as_any_type' => false,
'null_casts_as_array' => false,
'array_casts_as_null' => false,
'strict_method_checking' => true,
'quick_mode' => false,
'simplify_ast' => false,
'directory_list' => [
'.',
],
"exclude_analysis_directory_list" => [
'vendor/'
],
'exclude_file_list' => [
'system/src/Grav/Common/Errors/Resources/layout.html.php',
'tests/_support/AcceptanceTester.php',
'tests/_support/FunctionalTester.php',
'tests/_support/UnitTester.php',
],
'autoload_internal_extension_signatures' => [
'memcached' => '.phan/internal_stubs/memcached.phan_php',
'memcache' => '.phan/internal_stubs/memcache.phan_php',
'redis' => '.phan/internal_stubs/Redis.phan_php',
],
'plugins' => [
'AlwaysReturnPlugin',
'UnreachableCodePlugin',
'DuplicateArrayKeyPlugin',
'PregRegexCheckerPlugin',
'PrintfCheckerPlugin',
],
'suppress_issue_types' => [
'PhanUnreferencedUseNormal',
'PhanTypeObjectUnsetDeclaredProperty',
'PhanTraitParentReference',
'PhanTypeInvalidThrowsIsInterface',
'PhanRequiredTraitNotAdded',
'PhanDeprecatedFunction', // Uncomment this to see all the deprecated calls
]
];
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/test_unified_scripts.php | test_unified_scripts.php | <?php
require_once 'vendor/autoload.php';
use Livewire\V4\Compiler\SingleFileComponentCompiler;
use Illuminate\Support\Facades\File;
// Test unified script extraction
$compiler = new SingleFileComponentCompiler('/tmp/livewire_test_cache');
// Test 1: Regular JavaScript (no imports)
echo "=== TEST 1: Regular JavaScript ===\n";
$regularJsComponent = '@php
new class extends Livewire\Component {
public $count = 0;
public function increment() { $this->count++; }
}
@endphp
<div>
<h1>Count: {{ $count }}</h1>
<button wire:click="increment">+</button>
</div>
<script>
console.log("Regular JavaScript");
document.addEventListener("DOMContentLoaded", function() {
console.log("Component loaded");
});
</script>';
file_put_contents('/tmp/regular-component.livewire.php', $regularJsComponent);
$result1 = $compiler->compile('/tmp/regular-component.livewire.php');
echo "✅ View is clean (no scripts): " . (!str_contains(file_get_contents($result1->viewPath), '<script') ? 'YES' : 'NO') . "\n";
echo "✅ Script file generated: " . ($result1->hasScripts() && file_exists($result1->scriptPath) ? 'YES' : 'NO') . "\n";
if ($result1->hasScripts()) {
$scriptContent = file_get_contents($result1->scriptPath);
echo "✅ Script wrapped in export default: " . (str_contains($scriptContent, 'export default function run()') ? 'YES' : 'NO') . "\n";
echo "Script content:\n" . $scriptContent . "\n\n";
}
// Test 2: ES6 Imports
echo "=== TEST 2: ES6 Imports ===\n";
$es6Component = '@php
new class extends Livewire\Component {
public $count = 0;
public function increment() { $this->count++; }
}
@endphp
<div>
<h1>Count: {{ $count }}</h1>
<button wire:click="increment">+</button>
</div>
<script>
import { animate } from "https://cdn.jsdelivr.net/npm/animejs/+esm";
import { debounce } from "https://cdn.skypack.dev/lodash-es";
console.log("ES6 JavaScript with imports");
const button = document.querySelector("button");
const counter = document.querySelector("h1");
const debouncedAnimate = debounce(() => {
animate({
targets: counter,
scale: [1, 1.2, 1],
duration: 300
});
}, 100);
button.addEventListener("click", debouncedAnimate);
</script>';
file_put_contents('/tmp/es6-component.livewire.php', $es6Component);
$result2 = $compiler->compile('/tmp/es6-component.livewire.php');
echo "✅ View is clean (no scripts): " . (!str_contains(file_get_contents($result2->viewPath), '<script') ? 'YES' : 'NO') . "\n";
echo "✅ Script file generated: " . ($result2->hasScripts() && file_exists($result2->scriptPath) ? 'YES' : 'NO') . "\n";
if ($result2->hasScripts()) {
$scriptContent = file_get_contents($result2->scriptPath);
echo "✅ Imports hoisted: " . (str_contains($scriptContent, '// Hoisted imports') ? 'YES' : 'NO') . "\n";
echo "✅ Script wrapped in export default: " . (str_contains($scriptContent, 'export default function run()') ? 'YES' : 'NO') . "\n";
echo "✅ Import statements at top: " . (strpos($scriptContent, 'import { animate }') < strpos($scriptContent, 'export default') ? 'YES' : 'NO') . "\n";
echo "Script content:\n" . $scriptContent . "\n\n";
}
// Cleanup
unlink('/tmp/regular-component.livewire.php');
unlink('/tmp/es6-component.livewire.php');
echo "🎉 Unified script extraction working correctly!\n"; | php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/scripts/laravel.php | scripts/laravel.php | <?php
require __DIR__.'/../vendor/autoload.php';
$__commands = [];
$__name = '';
$__version = '';
class AppServiceProvider extends \Illuminate\Support\ServiceProvider
{
function boot()
{
foreach ($GLOBALS['__commands'] as $command) {
app(\Illuminate\Contracts\Console\Kernel::class)->registerCommand($command);
}
invade(app(\Illuminate\Contracts\Console\Kernel::class))->artisan->setName($GLOBALS['__name']);
invade(app(\Illuminate\Contracts\Console\Kernel::class))->artisan->setVersion($GLOBALS['__version']);
}
}
$root = sys_get_temp_dir().'/__lwcmdcache';
$cacheDir = $root.'/cache';
$viewsDir = $cacheDir.'/views';
if (! file_exists($cacheDir)) mkdir($cacheDir);
if (! file_exists($viewsDir)) mkdir($viewsDir);
$packagesCache = $cacheDir.'/packages.php';
file_put_contents($packagesCache, '<?php return [];');
$servicesCache = $cacheDir.'/services.php';
$appConfigCache = $cacheDir.'/config.php';
$routesCache = $cacheDir.'/routes.php';
$eventsCache = $cacheDir.'/events.php';
$_ENV['APP_PACKAGES_CACHE'] = $packagesCache;
$_ENV['APP_SERVICES_CACHE'] = $servicesCache;
$_ENV['APP_CONFIG_CACHE'] = $appConfigCache;
$_ENV['APP_ROUTES_CACHE'] = $routesCache;
$_ENV['APP_EVENTS_CACHE'] = $eventsCache;
$app = new Illuminate\Foundation\Application($root);
$app->singleton(Illuminate\Contracts\Console\Kernel::class, \Illuminate\Foundation\Console\Kernel::class);
$app->singleton(Illuminate\Contracts\Debug\ExceptionHandler::class, Illuminate\Foundation\Exceptions\Handler::class);
$app->bind(\Illuminate\Foundation\Bootstrap\LoadConfiguration::class, function () {
return new class extends \Illuminate\Foundation\Bootstrap\LoadConfiguration {
protected function loadConfigurationFiles($app, $repository)
{
$appConfig = [
'name' => 'Laravel',
'debug' => true,
'url' => 'http://localhost',
'timezone' => 'UTC',
'locale' => 'en',
'fallback_locale' => 'en',
'faker_locale' => 'en_US',
'key' => 'base64:Q7XKMi5sWNh2TNevn51dDjl67B/IyyqzptgAyE2rppU=',
'cipher' => 'AES-256-CBC',
'maintenance' => ['driver' => 'file'],
'providers' => [
// Illuminate\Auth\AuthServiceProvider::class,
// Illuminate\Broadcasting\BroadcastServiceProvider::class,
// Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
// Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
// Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
// Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
// Illuminate\Foundation\Providers\FoundationServiceProvider::class,
// Illuminate\Hashing\HashServiceProvider::class,
// Illuminate\Mail\MailServiceProvider::class,
// Illuminate\Notifications\NotificationServiceProvider::class,
// Illuminate\Pagination\PaginationServiceProvider::class,
// Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
// Illuminate\Redis\RedisServiceProvider::class,
// Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
// Illuminate\Session\SessionServiceProvider::class,
// Illuminate\Translation\TranslationServiceProvider::class,
// Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
AppServiceProvider::class,
// App\Providers\AppServiceProvider::class,
// App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
// App\Providers\EventServiceProvider::class,
// App\Providers\RouteServiceProvider::class,
],
'aliases' => \Illuminate\Support\Facades\Facade::defaultAliases()->merge([
// 'ExampleClass' => App\Example\ExampleClass::class,
])->toArray(),
];
$repository->set('app', $appConfig);
$repository->set('view', ['compiled' => $GLOBALS['root'].'/cache/views']);
$repository->set('database', [
'default' => 'sqlite',
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
],
]
]);
}
};
});
return [
function ($name, $version = '') use (&$__name, &$__version) {
$__name = $name;
$__version = $version;
},
function ($name, $callback) use (&$__commands) {
$command = new \Illuminate\Foundation\Console\ClosureCommand($name, $callback);
$__commands[] = $command;
return $command;
},
function () use (&$commands, $app) {
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$input = new Symfony\Component\Console\Input\ArgvInput;
$output = new Symfony\Component\Console\Output\ConsoleOutput;
$status = $kernel->handle($input, $output);
$kernel->terminate($input, $status);
exit($status);
},
];
function invade($obj)
{
return new class($obj) {
public $obj;
public $reflected;
public function __construct($obj)
{
$this->obj = $obj;
$this->reflected = new ReflectionClass($obj);
}
public function __get($name)
{
$property = $this->reflected->getProperty($name);
return $property->getValue($this->obj);
}
public function __set($name, $value)
{
$property = $this->reflected->getProperty($name);
$property->setValue($this->obj, $value);
}
public function __call($name, $params)
{
$method = $this->reflected->getMethod($name);
return $method->invoke($this->obj, ...$params);
}
};
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/HttpKernel.php | legacy_tests/HttpKernel.php | <?php
namespace LegacyTests;
use Illuminate\Foundation\Http\Kernel;
class HttpKernel extends Kernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\Illuminate\Foundation\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\Illuminate\Cookie\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \Orchestra\Testbench\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
/**
* The priority-sorted list of middleware.
*
* This forces non-global middleware to always be in the given order.
*
* @var array
*/
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Illuminate\Auth\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/AppLayoutWithProperties.php | legacy_tests/AppLayoutWithProperties.php | <?php
namespace LegacyTests;
use Illuminate\View\Component;
class AppLayoutWithProperties extends Component
{
public function render()
{
return view('layouts.app-from-class-component-with-properties', [
'foo' => 'bar',
]);
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/AppLayoutWithConstructor.php | legacy_tests/AppLayoutWithConstructor.php | <?php
namespace LegacyTests;
use Illuminate\View\Component;
class AppLayoutWithConstructor extends Component
{
public $foo;
public function __construct($foo = 'bar')
{
$this->foo = $foo;
}
public function render()
{
return view('layouts.app-from-class-component');
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/TestEnum.php | legacy_tests/TestEnum.php | <?php
namespace LegacyTests;
enum TestEnum: string
{
case TEST = 'Be excellent to each other';
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/AppLayout.php | legacy_tests/AppLayout.php | <?php
namespace LegacyTests;
use Illuminate\View\Component;
class AppLayout extends Component
{
public $foo = 'bar';
public function render()
{
return view('layouts.app-from-class-component');
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DuskCommand.php | legacy_tests/Browser/DuskCommand.php | <?php
namespace LegacyTests\Browser;
use Psy\Command\Command;
use Psy\Output\ShellOutput;
use Psy\Formatter\CodeFormatter;
use ReflectionClass;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class DuskCommand extends Command
{
public $e;
public $testCase;
public function __construct($testCase, $e, $colorMode = null)
{
$this->e = $e;
$this->testCase = $testCase;
parent::__construct();
}
protected function configure()
{
$this->setName('dusk');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$file = (new ReflectionClass($this->testCase))->getFileName();
$line = collect($this->e->getTrace())
->first(function ($entry) use ($file) {
return ($entry['file'] ?? '') === $file;
})['line'];
$info = [
'file' => $file,
'line' => $line,
];
$num = 2;
$lineNum = $info['line'];
$startLine = max($lineNum - $num, 1);
$endLine = $lineNum + $num;
$code = file_get_contents($info['file']);
if ($output instanceof ShellOutput) {
$output->startPaging();
}
$output->writeln(sprintf('From <info>%s:%s</info>:', $this->replaceCwd($info['file']), $lineNum));
$output->write(CodeFormatter::formatCode($code, $startLine, $endLine, $lineNum), false);
$output->writeln("\n".$this->e->getMessage());
if ($output instanceof ShellOutput) {
$output->stopPaging();
}
return 0;
}
private function replaceCwd($file)
{
$cwd = getcwd();
if ($cwd === false) {
return $file;
}
$cwd = rtrim($cwd, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
return preg_replace('/^' . preg_quote($cwd, '/') . '/', '', $file);
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/TestCase.php | legacy_tests/Browser/TestCase.php | <?php
namespace LegacyTests\Browser;
use Throwable;
use Sushi\Sushi;
use Psy\Shell;
use Orchestra\Testbench\Dusk\TestCase as BaseTestCase;
use Orchestra\Testbench\Dusk\Options as DuskOptions;
use Livewire\LivewireServiceProvider;
use Laravel\Dusk\Browser;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Foundation\Auth\User as AuthUser;
use Illuminate\Database\Eloquent\Model;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Exception;
use Closure;
use Livewire\Features\SupportTesting\ShowDuskComponent;
class TestCase extends BaseTestCase
{
use SupportsSafari;
public static $useSafari = false;
public static $useAlpineV3 = false;
function visitLivewireComponent($browser, $classes, $queryString = '')
{
$classes = (array) $classes;
$this->registerComponentForNextTest($classes);
$url = '/livewire-dusk/'.urlencode(head($classes)).$queryString;
return $browser->visit($url)->waitForLivewireToLoad();
}
function registerComponentForNextTest($components)
{
$tmp = __DIR__ . '/_runtime_components.json';
file_put_contents($tmp, json_encode($components, JSON_PRETTY_PRINT));
}
function wipeRuntimeComponentRegistration()
{
$tmp = __DIR__ . '/_runtime_components.json';
file_exists($tmp) && unlink($tmp);
}
public function setUp(): void
{
if (isset($_SERVER['CI'])) {
DuskOptions::withoutUI();
}
Browser::mixin(new \Livewire\Features\SupportTesting\DuskBrowserMacros);
$this->afterApplicationCreated(function () {
$this->makeACleanSlate();
});
$this->beforeApplicationDestroyed(function () {
$this->makeACleanSlate();
});
parent::setUp();
// $thing = get_class($this);
$isUsingAlpineV3 = static::$useAlpineV3;
$this->tweakApplication(function () use ($isUsingAlpineV3) {
$tmp = __DIR__ . '/_runtime_components.json';
if (file_exists($tmp)) {
// We can't just "require" this file because of race conditions...
$components = json_decode(file_get_contents($tmp));
foreach ($components as $name => $class) {
if (is_numeric($name)) {
app('livewire')->component($class);
} else {
app('livewire')->component($name, $class);
}
}
}
// // Autoload all Livewire components in this test suite.
// collect(File::allFiles(__DIR__))
// ->map(function ($file) {
// return 'Tests\\Browser\\'.str($file->getRelativePathname())->before('.php')->replace('/', '\\');
// })
// ->filter(function ($computedClassName) {
// return class_exists($computedClassName);
// })
// ->filter(function ($class) {
// return is_subclass_of($class, Component::class);
// })->each(function ($componentClass) {
// app('livewire')->component($componentClass);
// });
// Route::get(
// '/livewire-dusk/tests/browser/sync-history-without-mount/{id}',
// \LegacyTests\Browser\SyncHistory\ComponentWithMount::class
// )->middleware('web')->name('sync-history-without-mount');
// // This needs to be registered for Dusk to test the route-parameter binding
// // See: \LegacyTests\Browser\SyncHistory\Test.php
// Route::get(
// '/livewire-dusk/tests/browser/sync-history/{step}',
// \LegacyTests\Browser\SyncHistory\Component::class
// )->middleware('web')->name('sync-history');
// Route::get(
// '/livewire-dusk/tests/browser/sync-history-without-query-string/{step}',
// \LegacyTests\Browser\SyncHistory\ComponentWithoutQueryString::class
// )->middleware('web')->name('sync-history-without-query-string');
// Route::get(
// '/livewire-dusk/tests/browser/sync-history-with-optional-parameter/{step?}',
// \LegacyTests\Browser\SyncHistory\ComponentWithOptionalParameter::class
// )->middleware('web')->name('sync-history-with-optional-parameter');
// // The following two routes belong together. The first one serves a view which in return
// // loads and renders a component dynamically. There may not be a POST route for the first one.
// Route::get('/livewire-dusk/tests/browser/load-dynamic-component', function () {
// return View::file(__DIR__ . '/DynamicComponentLoading/view-load-dynamic-component.blade.php');
// })->middleware('web')->name('load-dynamic-component');
// Route::post('/livewire-dusk/tests/browser/dynamic-component', function () {
// return View::file(__DIR__ . '/DynamicComponentLoading/view-dynamic-component.blade.php');
// })->middleware('web')->name('dynamic-component');
Route::get('/livewire-dusk/{component}', ShowDuskComponent::class)->middleware('web');
Route::middleware('web')->get('/entangle-turbo', function () {
return view('turbo', [
'link' => '/livewire-dusk/' . urlencode(\LegacyTests\Browser\Alpine\Entangle\ToggleEntangledTurbo::class),
]);
})->name('entangle-turbo');
// app('session')->put('_token', 'this-is-a-hack-because-something-about-validating-the-csrf-token-is-broken');
// app('config')->set('view.paths', [
// __DIR__.'/views',
// resource_path('views'),
// ]);
config()->set('app.debug', true);
});
}
protected function tearDown(): void
{
$this->wipeRuntimeComponentRegistration();
$this->removeApplicationTweaks();
parent::tearDown();
}
// We don't want to deal with screenshots or console logs.
protected function storeConsoleLogsFor($browsers) {}
protected function captureFailuresFor($browsers) {}
public function makeACleanSlate()
{
Artisan::call('view:clear');
File::deleteDirectory($this->livewireViewsPath());
File::cleanDirectory(__DIR__.'/downloads');
File::deleteDirectory($this->livewireClassesPath());
File::delete(app()->bootstrapPath('cache/livewire-components.php'));
}
protected function getPackageProviders($app)
{
return [
LivewireServiceProvider::class,
];
}
protected function getEnvironmentSetUp($app)
{
$app['config']->set('view.paths', [
__DIR__.'/views',
resource_path('views'),
]);
// Override layout and page namespaces to use the test views instead of testbench's...
$app['view']->addNamespace('layouts', __DIR__.'/views/layouts');
$app['view']->addNamespace('pages', __DIR__.'/views/pages');
$app['config']->set('app.key', 'base64:Hupx3yAySikrM2/edkZQNQHslgDWYfiBfCuSThJ5SK8=');
$app['config']->set('database.default', 'testbench');
$app['config']->set('database.connections.testbench', [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
]);
$app['config']->set('auth.providers.users.model', User::class);
$app['config']->set('filesystems.disks.dusk-downloads', [
'driver' => 'local',
'root' => __DIR__.'/downloads',
]);
}
protected function resolveApplicationHttpKernel($app)
{
$app->singleton('Illuminate\Contracts\Http\Kernel', 'LegacyTests\HttpKernel');
}
protected function livewireClassesPath($path = '')
{
return app_path('Livewire'.($path ? '/'.$path : ''));
}
protected function livewireViewsPath($path = '')
{
return resource_path('views').'/livewire'.($path ? '/'.$path : '');
}
protected function driver(): RemoteWebDriver
{
$options = DuskOptions::getChromeOptions();
$options->setExperimentalOption('prefs', [
'download.default_directory' => __DIR__.'/downloads',
]);
// $options->addArguments([
// 'auto-open-devtools-for-tabs',
// ]);
return static::$useSafari
? RemoteWebDriver::create(
'http://localhost:9515', DesiredCapabilities::safari()
)
: RemoteWebDriver::create(
'http://localhost:9515',
DesiredCapabilities::chrome()->setCapability(
ChromeOptions::CAPABILITY,
$options
)
);
}
public function browse(Closure $callback)
{
parent::browse(function (...$browsers) use ($callback) {
try {
$callback(...$browsers);
} catch (Exception|Throwable $e) {
if (DuskOptions::hasUI()) $this->breakIntoATinkerShell($browsers, $e);
throw $e;
}
});
}
public function breakIntoATinkerShell($browsers, $e)
{
$sh = new Shell();
$sh->add(new DuskCommand($this, $e));
$sh->setScopeVariables([
'browsers' => $browsers,
]);
$sh->addInput('dusk');
$sh->setBoundObject($this);
$sh->run();
return $sh->getScopeVariables(false);
}
}
class User extends AuthUser
{
use Sushi;
public function posts()
{
return $this->hasMany(Post::class);
}
protected $rows = [
[
'name' => 'First User',
'email' => 'first@laravel-livewire.com',
'password' => '',
],
[
'name' => 'Second user',
'email' => 'second@laravel-livewire.com',
'password' => '',
],
];
}
class Post extends Model
{
use Sushi;
public function user()
{
return $this->belongsTo(User::class);
}
protected $rows = [
['title' => 'First', 'user_id' => 1],
['title' => 'Second', 'user_id' => 2],
];
}
class PostPolicy
{
public function update(User $user, Post $post)
{
return (int) $post->user_id === (int) $user->id;
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/SupportsSafari.php | legacy_tests/Browser/SupportsSafari.php | <?php
namespace LegacyTests\Browser;
// Thanks to https://github.com/appstract/laravel-dusk-safari for most of this source.
trait SupportsSafari
{
protected static $safariProcess;
protected static function defineChromeDriver(): void
{
if (static::$useSafari) {
static::startSafariDriver();
} else {
static::startChromeDriver(['--port=9515']);
}
}
public function onlyRunOnChrome()
{
static::$useSafari && $this->markTestSkipped();
}
public static function startSafariDriver()
{
static::$safariProcess = new \Symfony\Component\Process\Process([
'/usr/bin/safaridriver', '-p 9515',
]);
static::$safariProcess->start();
static::afterClass(function () {
if (static::$safariProcess) {
static::$safariProcess->stop();
}
});
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/_runtime_components.php | legacy_tests/Browser/_runtime_components.php | <?php
return [
\LegacyTests\Browser\Events\Component::class,
]; | php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/SupportStringables/Test.php | legacy_tests/Browser/SupportStringables/Test.php | <?php
namespace LegacyTests\Browser\SupportStringables;
use Illuminate\Support\Str;
use Livewire\Livewire;
use Tests\TestCase;
class Test extends TestCase
{
public function test_stringable_support()
{
Livewire::test(new class extends \Livewire\Component {
public $string;
public function mount()
{
$this->string = Str::of('Be excellent to each other');
}
public function render()
{
return <<<'HTML'
<div>
{{ $string }}
</div>
HTML;
}
})
->assertSee('Be excellent to each other')
;
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/Dirty/Test.php | legacy_tests/Browser/Dirty/Test.php | <?php
namespace LegacyTests\Browser\Dirty;
use Livewire\Component;
use Livewire\Livewire;
use Tests\BrowserTestCase;
class Test extends BrowserTestCase
{
public function test_wire_dirty()
{
Livewire::visit(new class extends Component {
public $foo = '';
public $bar = '';
public $baz = '';
public $bob = '';
public function render()
{
return <<<HTML
<div>
<input wire:model.lazy="foo" wire:dirty.class="foo-dirty" dusk="foo">
<input wire:model.lazy="bar" wire:dirty.class.remove="bar-dirty" class="bar-dirty" dusk="bar">
<span wire:dirty.class="baz-dirty" wire:target="baz" dusk="baz.target"><input wire:model.lazy="baz" dusk="baz.input"></span>
<span wire:dirty wire:target="bob" dusk="bob.target">Dirty Indicator</span><input wire:model.lazy="bob" dusk="bob.input">
<button type="button" dusk="dummy"></button>
</div>
HTML;
}
})
/**
* Add class for dirty data.
*/
->assertSourceMissing(' class="foo-dirty"')
->type('@foo', 'bar')
->assertSourceHas(' class="foo-dirty"')
->pause(150)
->waitForLivewire()->click('@dummy')
->assertSourceMissing(' class="foo-dirty"')
/**
* Remove class.
*/
->assertSourceHas(' class="bar-dirty"')
->type('@bar', 'baz')
->assertSourceMissing(' class="bar-dirty"')
->pause(150)
->waitForLivewire()->click('@dummy')
->pause(25)
->assertSourceHas(' class="bar-dirty"')
/**
* Set dirty using wire:target
*/
->assertSourceMissing(' class="baz-dirty"')
->type('@baz.input', 'baz')
->assertSourceHas(' class="baz-dirty"')
->pause(150)
->waitForLivewire()->click('@dummy')
->pause(25)
->assertSourceMissing(' class="baz-dirty"')
/**
* wire:dirty without modifiers, but with wire:target
*/
->assertMissing('@bob.target')
->type('@bob.input', 'baz')
->assertVisible('@bob.target')
->pause(150)
->waitForLivewire()->click('@dummy')
->pause(25)
->assertMissing('@bob.target')
;
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/SupportCollections/Test.php | legacy_tests/Browser/SupportCollections/Test.php | <?php
namespace LegacyTests\Browser\SupportCollections;
use LegacyTests\Browser\TestCase;
class Test extends TestCase
{
public function test()
{
$this->browse(function ($browser) {
$this->visitLivewireComponent($browser, Component::class)
->assertSeeIn('@things', 'foo')
->assertDontSeeIn('@things', 'bar')
->assertSeeIn('@unordered', 'foo')
->assertSeeIn('@unordered', 'bar')
->waitForLivewire()->click('@add-bar')
->assertSeeIn('@things', 'bar')
->assertSeeIn('@unordered', 'foo')
->assertSeeIn('@unordered', 'bar')
->assertSeeIn('@unordered', 'baz')
;
});
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/SupportCollections/Component.php | legacy_tests/Browser/SupportCollections/Component.php | <?php
namespace LegacyTests\Browser\SupportCollections;
use Livewire\Component as BaseComponent;
class Component extends BaseComponent
{
public $things;
public $unorderedKeyedThings;
public function mount()
{
$this->things = collect('foo');
$this->unorderedKeyedThings = collect([
2 => 'foo',
1 => 'bar',
]);
}
public function addBar()
{
$this->things->push('bar');
$this->unorderedKeyedThings[3] = 'baz';
}
public function render()
{
return <<<'HTML'
<div>
<button wire:click="addBar" dusk="add-bar">Add Bar</button>
<div dusk="things">
@foreach ($things as $thing)
<h1>{{ $thing }}</h1>
@endforeach
</div>
<div dusk="unordered">
@foreach ($unorderedKeyedThings as $thing)
<h1>{{ $thing }}</h1>
@endforeach
</div>
</div>
HTML;
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DynamicComponentLoading/view-clickable-component.blade.php | legacy_tests/Browser/DynamicComponentLoading/view-clickable-component.blade.php | <div>
<button id="click_me" wire:click="clickMe">Click me</button>
@if($success)
<h1>Test succeeded</h1>
@endif
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DynamicComponentLoading/Test.php | legacy_tests/Browser/DynamicComponentLoading/Test.php | <?php
namespace LegacyTests\Browser\DynamicComponentLoading;
use Illuminate\Support\Facades\File;
use Laravel\Dusk\Browser;
use LegacyTests\Browser\TestCase;
class Test extends TestCase
{
public function test_that_component_loaded_dynamically_via_post_action_causes_no_method_not_allowed()
{
$this->markTestSkipped(); // @todo: Josh Hanley
File::makeDirectory($this->livewireClassesPath('App'), 0755, true);
$this->browse(function (Browser $browser) {
$browser->visit(route('load-dynamic-component', [], false))
->waitForText('Step 1 Active')
->waitFor('#click_me')
->click('#click_me')
->waitForText('Test succeeded')
->assertSee('Test succeeded');
});
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DynamicComponentLoading/ClickableComponent.php | legacy_tests/Browser/DynamicComponentLoading/ClickableComponent.php | <?php
namespace LegacyTests\Browser\DynamicComponentLoading;
use Illuminate\Support\Facades\View;
use Livewire\Component as BaseComponent;
class ClickableComponent extends BaseComponent
{
public $success = false;
public function clickMe()
{
// Calling this method should never fail, even if the component is loaded dynamically via POST.
// By setting the component property here, we can draw the final message for the test to succeed.
$this->success = true;
}
public function render()
{
return View::file(__DIR__.'/view-clickable-component.blade.php');
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DynamicComponentLoading/view-load-dynamic-component.blade.php | legacy_tests/Browser/DynamicComponentLoading/view-load-dynamic-component.blade.php | @extends('layouts.app-for-normal-views')
@section('content')
<div>
<h1>Step 1 Active</h1>
<div id="load_target"></div>
</div>
@endsection
@push('scripts')
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
fetch('{{ route("dynamic-component") }}', {
method: 'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
})
.then(res => res.text())
.then(res => document.getElementById('load_target').innerHTML = res)
.then(x => window.livewire.rescan());
});
</script>
@endpush
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DynamicComponentLoading/view-dynamic-component.blade.php | legacy_tests/Browser/DynamicComponentLoading/view-dynamic-component.blade.php | @extends('layouts.app-for-normal-views')
@section('content')
<div>
@livewire(\Tests\Browser\DynamicComponentLoading\ClickableComponent::class)
</div>
@endsection
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/InputTextarea/Test.php | legacy_tests/Browser/DataBinding/InputTextarea/Test.php | <?php
namespace LegacyTests\Browser\DataBinding\InputTextarea;
use Laravel\Dusk\Browser;
use LegacyTests\Browser\TestCase;
class Test extends TestCase
{
public function test()
{
$this->browse(function (Browser $browser) {
$this->visitLivewireComponent($browser, Component::class)
/**
* Can change value
*/
->assertDontSeeIn('@foo.output', 'changed')
->waitForLivewire()->click('@foo.change')
->assertSeeIn('@foo.output', 'changed')
/**
* Class change works as expected and doesn't wipe the textarea's value
*/
->assertInputValue('@foo', 'changed')
->assertSourceMissing('class="foo"')
->waitForLivewire()->click('@foo.add-class')
->assertInputValue('@foo', 'changed')
->assertSourceHas('class="foo"')
/**
* Value will change if marked as dirty AND input is focused.
*/
->waitForLivewire(function ($b) {
$b->click('@foo');
$b->script('window.Livewire.first().updateFooTo("changed-again")');
})
->assertInputValue('@foo', 'changed-again')
/**
* Value won't change if focused but NOT dirty.
*/
// @todo: waiting to see if we need to bring this "unintrusive" V2 functionality back...
// ->waitForLivewire(function ($b) {
// $b->click('@foo');
// $b->script('window.Livewire.first().set("foo", "changed-alot")');
// })
// ->assertSeeIn('@foo.output', 'changed-alot')
// ->assertInputValue('@foo', 'changed-again')
/**
* Can set lazy value
*/
->click('@baz') // Set focus.
->type('@baz', 'lazy')
->pause(150) // Wait for the amount of time it would have taken to do a round trip.
->assertDontSeeIn('@baz.output', 'lazy')
->waitForLivewire()->click('@refresh') // Blur input and send action.
->assertSeeIn('@baz.output', 'lazy')
/**
* Can set deferred value
*/
->click('@bob') // Set focus.
->type('@bob', 'deferred')
->assertDontSeeIn('@bob.output', 'deferred')
->click('@foo') // Blur input to make sure this is more thans "lazy".
->pause(150) // Pause for upper-bound of most round-trip lengths.
->assertDontSeeIn('@bob.output', 'deferred')
->waitForLivewire()->click('@refresh')
->assertSeeIn('@bob.output', 'deferred')
;
});
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/InputTextarea/view.blade.php | legacy_tests/Browser/DataBinding/InputTextarea/view.blade.php | <div>
<textarea wire:model.live="foo" dusk="foo" class="{{ $showFooClass ? 'foo' : '' }}"></textarea><span dusk="foo.output">{{ $foo }}</span>
<button wire:click="updateFooTo('changed')" dusk="foo.change">Change Foo</button>
<button wire:click="$set('showFooClass', true)" dusk="foo.add-class">Add Class</button>
<textarea wire:model.blur="baz" dusk="baz"></textarea><span dusk="baz.output">{{ $baz }}</span>
<textarea wire:model="bob" dusk="bob"></textarea><span dusk="bob.output">{{ $bob }}</span>
<button type="button" wire:click="$refresh" dusk="refresh">Refresh</button>
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/InputTextarea/Component.php | legacy_tests/Browser/DataBinding/InputTextarea/Component.php | <?php
namespace LegacyTests\Browser\DataBinding\InputTextarea;
use Illuminate\Support\Facades\View;
use Livewire\Component as BaseComponent;
class Component extends BaseComponent
{
public $foo = 'initial';
public $bar = '';
public $baz = '';
public $bob = '';
public $showFooClass = false;
public function updateFooTo($value)
{
$this->foo = $value;
}
public function render()
{
return View::file(__DIR__.'/view.blade.php');
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/DirtyDetection/Test.php | legacy_tests/Browser/DataBinding/DirtyDetection/Test.php | <?php
namespace LegacyTests\Browser\DataBinding\DirtyDetection;
use Laravel\Dusk\Browser;
use LegacyTests\Browser\TestCase;
class Test extends TestCase
{
public function test()
{
$this->browse(function (Browser $browser) {
$this->visitLivewireComponent($browser, Component::class)
/**
* If a value is changed server-side, the input updates.
*/
->assertValue('@foo.input', 'initial')
->waitForLivewire()->click('@foo.button')
->assertValue('@foo.input', 'changed')
/**
* If an uninitialized nested value is reset server-side, the input updates.
*/
->assertValue('@bar.input', '')
->type('@bar.input', 'changed')
->pause(250)
->waitForLivewire()->click('@bar.button')
->assertValue('@bar.input', '')
;
});
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/DirtyDetection/view.blade.php | legacy_tests/Browser/DataBinding/DirtyDetection/view.blade.php | <div>
<input wire:model.live="foo" dusk="foo.input">
<button wire:click="changeFoo" dusk="foo.button">Change Foo</button>
<input wire:model.live="bar.baz" dusk="bar.input">
<button wire:click="resetBar" dusk="bar.button">Change BarBaz</button>
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/DirtyDetection/Component.php | legacy_tests/Browser/DataBinding/DirtyDetection/Component.php | <?php
namespace LegacyTests\Browser\DataBinding\DirtyDetection;
use Illuminate\Support\Facades\View;
use Livewire\Component as BaseComponent;
class Component extends BaseComponent
{
public $foo = 'initial';
public $bar = [];
public function changeFoo()
{
$this->foo = 'changed';
}
public function resetBar()
{
$this->reset('bar');
}
public function render()
{
return View::file(__DIR__.'/view.blade.php');
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/InputText/EmptyWireModelComponent.php | legacy_tests/Browser/DataBinding/InputText/EmptyWireModelComponent.php | <?php
namespace LegacyTests\Browser\DataBinding\InputText;
use Livewire\Component as BaseComponent;
class EmptyWireModelComponent extends BaseComponent
{
public function render()
{
return <<<'HTML'
<div>
<input type="text" wire:model dusk="input" />
</div>
HTML;
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/InputText/Test.php | legacy_tests/Browser/DataBinding/InputText/Test.php | <?php
namespace LegacyTests\Browser\DataBinding\InputText;
use Laravel\Dusk\Browser;
use LegacyTests\Browser\TestCase;
class Test extends TestCase
{
public function test()
{
$this->browse(function (Browser $browser) {
$this->visitLivewireComponent($browser, Component::class)
/**
* Has initial value.
*/
->assertInputValue('@foo', 'initial')
/**
* Can set value
*/
->waitForLivewire()->type('@foo', 'subsequent')
->assertSeeIn('@foo.output', 'subsequent')
/**
* Can change value
*/
->assertDontSeeIn('@foo.output', 'changed')
->waitForLivewire()->click('@foo.change')
->assertSeeIn('@foo.output', 'changed')
/**
* Value will change if marked as dirty AND input is focused.
*/
->waitForLivewire(function ($b) {
$b->click('@foo')
->tap(function ($b) { $b->script('window.Livewire.first().updateFooTo("changed-again")'); });
})
->assertInputValue('@foo', 'changed-again')
/**
* Value won't change if focused but NOT dirty.
*/
// @todo: waiting to see if we need to bring this "unintrusive" V2 functionality back...
// ->waitForLivewire(function ($b) {
// $b->click('@foo')
// ->tap(function ($b) { $b->script('window.Livewire.first().set("foo", "changed-alot")'); });
// })
// ->assertSeeIn('@foo.output', 'changed-alot')
// ->assertInputValue('@foo', 'changed-again')
/**
* Can set nested value
*/
->waitForLivewire()->type('@bar', 'nested')
->assertSeeIn('@bar.output', '{"baz":{"bob":"nested"}}')
/**
* Can set lazy value
*/
->click('@baz') // Set focus.
->type('@baz', 'lazy')
->pause(150) // Wait for the amount of time it would have taken to do a round trip.
->assertDontSeeIn('@baz.output', 'lazy')
->waitForLivewire()->click('@refresh') // Blur input and send action.
->assertSeeIn('@baz.output', 'lazy')
/**
* Can set deferred value
*/
->click('@bob') // Set focus.
->type('@bob', 'deferred')
->assertDontSeeIn('@bob.output', 'deferred')
->click('@foo') // Blur input to make sure this is more thans "lazy".
->pause(150) // Pause for upper-bound of most round-trip lengths.
->assertDontSeeIn('@bob.output', 'deferred')
->waitForLivewire()->click('@refresh')
->assertSeeIn('@bob.output', 'deferred')
;
});
}
public function test_it_provides_a_nice_warning_in_console_for_an_empty_wire_model()
{
$this->browse(function (Browser $browser) {
$this->visitLivewireComponent($browser, EmptyWireModelComponent::class)
->assertConsoleLogHasWarning('Livewire: [wire:model] is missing a value.')
;
});
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/InputText/view.blade.php | legacy_tests/Browser/DataBinding/InputText/view.blade.php | <div>
<input type="text" wire:model.live="foo" dusk="foo"><span dusk="foo.output">{{ $foo }}</span>
<button wire:click="updateFooTo('changed')" dusk="foo.change">Change Foo</button>
<input type="text" wire:model.live="bar.baz.bob" dusk="bar"><span dusk="bar.output">@json($bar)</span>
<input type="text" wire:model.lazy="baz" dusk="baz"><span dusk="baz.output">{{ $baz }}</span>
<input type="text" wire:model="bob" dusk="bob"><span dusk="bob.output">{{ $bob }}</span>
<button type="button" wire:click="$refresh" dusk="refresh">Refresh</button>
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/InputText/Component.php | legacy_tests/Browser/DataBinding/InputText/Component.php | <?php
namespace LegacyTests\Browser\DataBinding\InputText;
use Illuminate\Support\Facades\View;
use Livewire\Component as BaseComponent;
class Component extends BaseComponent
{
public $foo = 'initial';
public $bar = [];
public $baz = '';
public $bob = '';
public function updateFooTo($value)
{
$this->foo = $value;
}
public function render()
{
return View::file(__DIR__.'/view.blade.php');
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/InputCheckboxRadio/Test.php | legacy_tests/Browser/DataBinding/InputCheckboxRadio/Test.php | <?php
namespace LegacyTests\Browser\DataBinding\InputCheckboxRadio;
use Laravel\Dusk\Browser;
use LegacyTests\Browser\TestCase;
class Test extends TestCase
{
public function test()
{
$this->browse(function (Browser $browser) {
$this->visitLivewireComponent($browser, Component::class)
/**
* Has initial value.
*/
->assertChecked('@foo')
->assertSeeIn('@foo.output', 'true')
/**
* Can set value
*/
->waitForLivewire()->uncheck('@foo')
->assertNotChecked('@foo')
->assertSeeIn('@foo.output', 'false')
/**
* Can set value from an array
*/
->assertNotChecked('@bar.a')->assertChecked('@bar.b')->assertNotChecked('@bar.c')
->assertSeeIn('@bar.output', '["b"]')
->waitForLivewire()->check('@bar.c')
->assertNotChecked('@bar.a')->assertChecked('@bar.b')->assertChecked('@bar.c')
->assertSeeIn('@bar.output', '["b","c"]')
/**
* Can set value from a number
*/
// @note: Not sure why someone would want to bind a non-boolean value to a checkbox.
// Because V3 uses Alpine's x-model under the hood, this breaks. If it's considered
// breaking and people need it, we can see about matching the behavior of V2...
// ->assertChecked('@baz')
;
});
}
public function test_checkboxes_fuzzy_match_integer_values()
{
$this->browse(function (Browser $browser) {
$this->visitLivewireComponent($browser, CheckboxesWithIntsComponent::class)
// ->tinker()
->assertNotChecked('@int1')
->assertChecked('@int2')
->assertChecked('@int3')
->waitForLivewire()->uncheck('@int2')
->assertNotChecked('@int1')
->assertNotChecked('@int2')
->assertChecked('@int3')
->waitForLivewire()->uncheck('@int3')
->assertNotChecked('@int1')
->assertNotChecked('@int2')
->assertNotChecked('@int3')
->waitForLivewire()->check('@int2')
->assertNotChecked('@int1')
->assertChecked('@int2')
->assertNotChecked('@int3')
;
});
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/InputCheckboxRadio/CheckboxesWithIntsComponent.php | legacy_tests/Browser/DataBinding/InputCheckboxRadio/CheckboxesWithIntsComponent.php | <?php
namespace LegacyTests\Browser\DataBinding\InputCheckboxRadio;
use Livewire\Component as BaseComponent;
class CheckboxesWithIntsComponent extends BaseComponent
{
public $data = [2, 3];
public function render()
{
return <<< 'HTML'
<div>
<input dusk="int1" wire:model.live="data" type="checkbox" value="1" />
<input dusk="int2" wire:model.live="data" type="checkbox" value="2" />
<input dusk="int3" wire:model.live="data" type="checkbox" value="3" />
<div dusk="output">{{ json_encode($data) }}</div>
</div>
HTML;
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/InputCheckboxRadio/view.blade.php | legacy_tests/Browser/DataBinding/InputCheckboxRadio/view.blade.php | <div>
<input type="checkbox" wire:model.live="foo" dusk="foo"><span dusk="foo.output">@json($foo)</span>
<input type="checkbox" wire:model.live="bar" value="a" dusk="bar.a">
<input type="checkbox" wire:model.live="bar" value="b" dusk="bar.b">
<input type="checkbox" wire:model.live="bar" value="c" dusk="bar.c">
<span dusk="bar.output">@json($bar)</span>
<input type="checkbox" wire:model.live="baz" dusk="baz" value="2">
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/InputCheckboxRadio/Component.php | legacy_tests/Browser/DataBinding/InputCheckboxRadio/Component.php | <?php
namespace LegacyTests\Browser\DataBinding\InputCheckboxRadio;
use Illuminate\Support\Facades\View;
use Livewire\Component as BaseComponent;
class Component extends BaseComponent
{
public $foo = true;
public $bar = ['b'];
public $baz = 2;
public function updateFooTo($value)
{
$this->foo = $value;
}
public function render()
{
return View::file(__DIR__.'/view.blade.php');
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/AutoFill/Test.php | legacy_tests/Browser/DataBinding/AutoFill/Test.php | <?php
namespace LegacyTests\Browser\DataBinding\AutoFill;
use LegacyTests\Browser\TestCase;
class Test extends TestCase
{
public function test()
{
// This is a manual test for Safari.
// We can't test this automically because
// Safari's automation mode disables autofill.
//
// Test steps:
// - Comment out the "markTextSkipped" below
// - Run test in chrome
// - Copy the URL and paste it into Safari
// - Autofill the email/password fields
// - Assert both fields are filled
// - Assert both values are synced with Livewire
$this->markTestSkipped();
$this->browse(function ($browser) {
$this->visitLivewireComponent($browser, Component::class)->tinker();
});
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/AutoFill/view.blade.php | legacy_tests/Browser/DataBinding/AutoFill/view.blade.php | <div>
<div>{{ $email }}</div>
<div>{{ $password }}</div>
<form action="{{ url()->current() }}" method="GET">
<label for="email">Email</label>
<input name="email" id="email" type="email" autocomplete="on" dusk="email" wire:model.blur="email">
<label for="password">Password</label>
<input name="password" id="password" type="password" autocomplete="on" dusk="password" wire:model.live="password">
<button dusk="submit">Submit</button>
</form>
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/AutoFill/Component.php | legacy_tests/Browser/DataBinding/AutoFill/Component.php | <?php
namespace LegacyTests\Browser\DataBinding\AutoFill;
use Illuminate\Support\Facades\View;
use Livewire\Component as BaseComponent;
class Component extends BaseComponent
{
public $email = '';
public $password = '';
public function render()
{
return View::file(__DIR__.'/view.blade.php');
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/InputSelect/SelectWithSelectedOnOption.php | legacy_tests/Browser/DataBinding/InputSelect/SelectWithSelectedOnOption.php | <?php
namespace LegacyTests\Browser\DataBinding\InputSelect;
use Livewire\Component as BaseComponent;
class SelectWithSelectedOnOption extends BaseComponent
{
public $selectedOption = '3';
public function render()
{
return <<<'HTML'
<div>
<h1 dusk="output">{{ $selectedOption }}</h1>
<select wire:model.live="selectedOption" dusk="select-input">
<option value="1" @if($selectedOption == '1') selected @endif>Option 1</option>
<option value="2" @if($selectedOption == '2') selected @endif>Option 2</option>
<option value="3" @if($selectedOption == '3') selected @endif>Option 3</option>
<option value="4" @if($selectedOption == '4') selected @endif>Option 4</option>
<option value="5" @if($selectedOption == '5') selected @endif>Option 5</option>
</select>
</div>
HTML;
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/InputSelect/Test.php | legacy_tests/Browser/DataBinding/InputSelect/Test.php | <?php
namespace LegacyTests\Browser\DataBinding\InputSelect;
use Laravel\Dusk\Browser;
use LegacyTests\Browser\TestCase;
class Test extends TestCase
{
public function test()
{
$this->browse(function (Browser $browser) {
$this->visitLivewireComponent($browser, Component::class)
/**
* Standard select.
*/
->assertDontSeeIn('@single.output', 'bar')
->waitForLivewire()->select('@single.input', 'bar')
->assertSelected('@single.input', 'bar')
->assertSeeIn('@single.output', 'bar')
/**
* Standard select with value attributes.
*/
->assertDontSeeIn('@single-value.output', 'par')
->waitForLivewire()->select('@single-value.input', 'par')
->assertSelected('@single-value.input', 'par')
->assertSeeIn('@single-value.output', 'par')
/**
* Standard select with value attributes.
*/
->assertSeeIn('@single-number.output', '3')
->assertSelected('@single-number.input', '3')
->waitForLivewire()->select('@single-number.input', '4')
->assertSeeIn('@single-number.output', '4')
->assertSelected('@single-number.input', '4')
/**
* Select with placeholder default.
*/
->assertSelected('@placeholder.input', '')
->assertDontSeeIn('@placeholder.output', 'foo')
->waitForLivewire()->select('@placeholder.input', 'foo')
->assertSelected('@placeholder.input', 'foo')
->assertSeeIn('@placeholder.output', 'foo')
/**
* Select multiple.
*/
->assertDontSeeIn('@multiple.output', 'bar')
->waitForLivewire()->select('@multiple.input', ['bar'])
->assertSelected('@multiple.input', 'bar')
->assertSeeIn('@multiple.output', 'bar')
->waitForLivewire()->select('@multiple.input', ['bar', 'baz'])
->assertSelected('@multiple.input', 'baz')
->assertSeeIn('@multiple.output', 'bar')
->assertSeeIn('@multiple.output', 'baz');
});
}
public function test_it_can_handle_having_selected_on_an_option()
{
$this->browse(function (Browser $browser) {
$this->visitLivewireComponent($browser, SelectWithSelectedOnOption::class)
->assertSeeIn('@output', '3')
->assertSelected('@select-input', '3')
->waitForLivewire()->select('@select-input', '4')
->assertSeeIn('@output', '4')
->assertSelected('@select-input', '4')
;
});
}
// @note: I think I'm skipping this test for V3 as we should just defer to what x-model in Alpine does.
// We can always uncomment this and get it working if it's a breaking change for people.
// public function test_it_renders_wire_model_selected_option_even_if_html_selected_is_different()
// {
// $this->browse(function (Browser $browser) {
// $this->visitLivewireComponent($browser, SelectWithIncorrectSelectedOnOption::class)
// ->assertSeeIn('@output', '3')
// ->assertSelected('@select-input', '3')
// ->waitForLivewire()->click('@toggle')
// ->assertSeeIn('@output', '3')
// ->assertSelected('@select-input', '3')
// ->waitForLivewire()->select('@select-input', '2')
// ->assertSeeIn('@output', '2')
// ->assertSelected('@select-input', '2')
// ;
// });
// }
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/InputSelect/SelectWithIncorrectSelectedOnOption.php | legacy_tests/Browser/DataBinding/InputSelect/SelectWithIncorrectSelectedOnOption.php | <?php
namespace LegacyTests\Browser\DataBinding\InputSelect;
use Livewire\Component as BaseComponent;
class SelectWithIncorrectSelectedOnOption extends BaseComponent
{
public $selectedOption = '3';
public $showOtherSelected = false;
public function render()
{
return <<<'HTML'
<div>
<h1 dusk="output">{{ $selectedOption }}</h1>
<select wire:model.live="selectedOption" dusk="select-input">
<option value="1" @if(! $showOtherSelected && $selectedOption == '1') selected @endif>Option 1</option>
<option value="2" @if(! $showOtherSelected && $selectedOption == '2') selected @endif>Option 2</option>
<option value="3" @if(! $showOtherSelected && $selectedOption == '3') selected @endif>Option 3</option>
<option value="4" @if($showOtherSelected || (! $showOtherSelected && $selectedOption == '4')) selected @endif>Option 4</option>
<option value="5" @if(! $showOtherSelected && $selectedOption == '5') selected @endif>Option 5</option>
</select>
<button wire:click="$toggle('showOtherSelected')" dusk="toggle">Toggle</button>
</div>
HTML;
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/legacy_tests/Browser/DataBinding/InputSelect/view.blade.php | legacy_tests/Browser/DataBinding/InputSelect/view.blade.php | <div>
<h1 dusk="single.output">{{ $single }}</h1>
<select wire:model.live="single" dusk="single.input">
<option>foo</option>
<option>bar</option>
<option>baz</option>
</select>
<h1 dusk="single-value.output">{{ $singleValue }}</h1>
<select wire:model.live="singleValue" dusk="single-value.input">
<option value="poo">foo</option>
<option value="par">bar</option>
<option value="paz">baz</option>
</select>
<h1 dusk="single-number.output">{{ $singleNumber }}</h1>
<select wire:model.live="singleNumber" dusk="single-number.input">
<option value="2">foo</option>
<option value="3">bar</option>
<option value="4">baz</option>
</select>
<h1 dusk="placeholder.output">{{ $placeholder }}</h1>
<select wire:model.live="placeholder" dusk="placeholder.input">
<option value="" disabled>Placeholder</option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
</select>
<h1 dusk="multiple.output">@json($multiple)</h1>
<select wire:model.live.debounce="multiple" multiple dusk="multiple.input">
<option>foo</option>
<option>bar</option>
<option>baz</option>
</select>
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.