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 |
|---|---|---|---|---|---|---|---|---|
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/IncomingRequest.php | system/HTTP/IncomingRequest.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\HTTP\Exceptions\HTTPException;
use CodeIgniter\HTTP\Files\FileCollection;
use CodeIgniter\HTTP\Files\UploadedFile;
use Config\App;
use Config\Services;
use Locale;
use stdClass;
/**
* Class IncomingRequest
*
* Represents an incoming, server-side HTTP request.
*
* Per the HTTP specification, this interface includes properties for
* each of the following:
*
* - Protocol version
* - HTTP method
* - URI
* - Headers
* - Message body
*
* Additionally, it encapsulates all data as it has arrived to the
* application from the CGI and/or PHP environment, including:
*
* - The values represented in $_SERVER.
* - Any cookies provided (generally via $_COOKIE)
* - Query string arguments (generally via $_GET, or as parsed via parse_str())
* - Upload files, if any (as represented by $_FILES)
* - Deserialized body binds (generally from $_POST)
*
* @see \CodeIgniter\HTTP\IncomingRequestTest
*/
class IncomingRequest extends Request
{
/**
* The URI for this request.
*
* Note: This WILL NOT match the actual URL in the browser since for
* everything this cares about (and the router, etc) is the portion
* AFTER the baseURL. So, if hosted in a sub-folder this will
* appear different than actual URI path. If you need that use getPath().
*
* @var URI
*/
protected $uri;
/**
* The detected URI path (relative to the baseURL).
*
* Note: current_url() uses this to build its URI,
* so this becomes the source for the "current URL"
* when working with the share request instance.
*
* @var string|null
*/
protected $path;
/**
* File collection
*
* @var FileCollection|null
*/
protected $files;
/**
* Negotiator
*
* @var Negotiate|null
*/
protected $negotiator;
/**
* The default Locale this request
* should operate under.
*
* @var string
*/
protected $defaultLocale;
/**
* The current locale of the application.
* Default value is set in app/Config/App.php
*
* @var string
*/
protected $locale;
/**
* Stores the valid locale codes.
*
* @var array
*/
protected $validLocales = [];
/**
* Holds the old data from a redirect.
*
* @var array
*/
protected $oldInput = [];
/**
* The user agent this request is from.
*
* @var UserAgent
*/
protected $userAgent;
/**
* Constructor
*
* @param App $config
* @param string|null $body
*/
public function __construct($config, ?URI $uri = null, $body = 'php://input', ?UserAgent $userAgent = null)
{
if (! $uri instanceof URI || ! $userAgent instanceof UserAgent) {
throw new InvalidArgumentException('You must supply the parameters: uri, userAgent.');
}
$this->populateHeaders();
if (
$body === 'php://input'
// php://input is not available with enctype="multipart/form-data".
// See https://www.php.net/manual/en/wrappers.php.php#wrappers.php.input
&& ! str_contains($this->getHeaderLine('Content-Type'), 'multipart/form-data')
&& (int) $this->getHeaderLine('Content-Length') <= $this->getPostMaxSize()
) {
// Get our body from php://input
$body = file_get_contents('php://input');
}
// If file_get_contents() returns false or empty string, set null.
if ($body === false || $body === '') {
$body = null;
}
$this->uri = $uri;
$this->body = $body;
$this->userAgent = $userAgent;
$this->validLocales = $config->supportedLocales;
parent::__construct($config);
if ($uri instanceof SiteURI) {
$this->setPath($uri->getRoutePath());
} else {
$this->setPath($uri->getPath());
}
$this->detectLocale($config);
}
private function getPostMaxSize(): int
{
$postMaxSize = ini_get('post_max_size');
return match (strtoupper(substr($postMaxSize, -1))) {
'G' => (int) str_replace('G', '', $postMaxSize) * 1024 ** 3,
'M' => (int) str_replace('M', '', $postMaxSize) * 1024 ** 2,
'K' => (int) str_replace('K', '', $postMaxSize) * 1024,
default => (int) $postMaxSize,
};
}
/**
* Handles setting up the locale, perhaps auto-detecting through
* content negotiation.
*
* @param App $config
*
* @return void
*/
public function detectLocale($config)
{
$this->locale = $this->defaultLocale = $config->defaultLocale;
if (! $config->negotiateLocale) {
return;
}
$this->setLocale($this->negotiate('language', $config->supportedLocales));
}
/**
* Sets up our URI object based on the information we have. This is
* either provided by the user in the baseURL Config setting, or
* determined from the environment as needed.
*
* @return void
*
* @deprecated 4.4.0 No longer used.
*/
protected function detectURI(string $protocol, string $baseURL)
{
$this->setPath($this->detectPath($this->config->uriProtocol), $this->config);
}
/**
* Detects the relative path based on
* the URIProtocol Config setting.
*
* @deprecated 4.4.0 Moved to SiteURIFactory.
*/
public function detectPath(string $protocol = ''): string
{
if ($protocol === '') {
$protocol = 'REQUEST_URI';
}
$this->path = match ($protocol) {
'REQUEST_URI' => $this->parseRequestURI(),
'QUERY_STRING' => $this->parseQueryString(),
default => $this->fetchGlobal('server', $protocol) ?? $this->parseRequestURI(),
};
return $this->path;
}
/**
* Will parse the REQUEST_URI and automatically detect the URI from it,
* fixing the query string if necessary.
*
* @return string The URI it found.
*
* @deprecated 4.4.0 Moved to SiteURIFactory.
*/
protected function parseRequestURI(): string
{
if (! isset($_SERVER['REQUEST_URI'], $_SERVER['SCRIPT_NAME'])) {
return '';
}
// parse_url() returns false if no host is present, but the path or query string
// contains a colon followed by a number. So we attach a dummy host since
// REQUEST_URI does not include the host. This allows us to parse out the query string and path.
$parts = parse_url('http://dummy' . $_SERVER['REQUEST_URI']);
$query = $parts['query'] ?? '';
$uri = $parts['path'] ?? '';
// Strip the SCRIPT_NAME path from the URI
if (
$uri !== '' && isset($_SERVER['SCRIPT_NAME'][0])
&& pathinfo($_SERVER['SCRIPT_NAME'], PATHINFO_EXTENSION) === 'php'
) {
// Compare each segment, dropping them until there is no match
$segments = $keep = explode('/', $uri);
foreach (explode('/', $_SERVER['SCRIPT_NAME']) as $i => $segment) {
// If these segments are not the same then we're done
if (! isset($segments[$i]) || $segment !== $segments[$i]) {
break;
}
array_shift($keep);
}
$uri = implode('/', $keep);
}
// This section ensures that even on servers that require the URI to contain the query string (Nginx) a correct
// URI is found, and also fixes the QUERY_STRING Server var and $_GET array.
if (trim($uri, '/') === '' && str_starts_with($query, '/')) {
$query = explode('?', $query, 2);
$uri = $query[0];
$_SERVER['QUERY_STRING'] = $query[1] ?? '';
} else {
$_SERVER['QUERY_STRING'] = $query;
}
// Update our globals for values likely to been have changed
parse_str($_SERVER['QUERY_STRING'], $_GET);
$this->populateGlobals('server');
$this->populateGlobals('get');
$uri = URI::removeDotSegments($uri);
return ($uri === '/' || $uri === '') ? '/' : ltrim($uri, '/');
}
/**
* Parse QUERY_STRING
*
* Will parse QUERY_STRING and automatically detect the URI from it.
*
* @deprecated 4.4.0 Moved to SiteURIFactory.
*/
protected function parseQueryString(): string
{
$uri = $_SERVER['QUERY_STRING'] ?? @getenv('QUERY_STRING');
if (trim($uri, '/') === '') {
return '/';
}
if (str_starts_with($uri, '/')) {
$uri = explode('?', $uri, 2);
$_SERVER['QUERY_STRING'] = $uri[1] ?? '';
$uri = $uri[0];
}
// Update our globals for values likely to been have changed
parse_str($_SERVER['QUERY_STRING'], $_GET);
$this->populateGlobals('server');
$this->populateGlobals('get');
$uri = URI::removeDotSegments($uri);
return ($uri === '/' || $uri === '') ? '/' : ltrim($uri, '/');
}
/**
* Provides a convenient way to work with the Negotiate class
* for content negotiation.
*/
public function negotiate(string $type, array $supported, bool $strictMatch = false): string
{
if ($this->negotiator === null) {
$this->negotiator = Services::negotiator($this, true);
}
return match (strtolower($type)) {
'media' => $this->negotiator->media($supported, $strictMatch),
'charset' => $this->negotiator->charset($supported),
'encoding' => $this->negotiator->encoding($supported),
'language' => $this->negotiator->language($supported),
default => throw HTTPException::forInvalidNegotiationType($type),
};
}
/**
* Checks this request type.
*/
public function is(string $type): bool
{
$valueUpper = strtoupper($type);
$httpMethods = Method::all();
if (in_array($valueUpper, $httpMethods, true)) {
return $this->getMethod() === $valueUpper;
}
if ($valueUpper === 'JSON') {
return str_contains($this->getHeaderLine('Content-Type'), 'application/json');
}
if ($valueUpper === 'AJAX') {
return $this->isAJAX();
}
throw new InvalidArgumentException('Unknown type: ' . $type);
}
/**
* Determines if this request was made from the command line (CLI).
*/
public function isCLI(): bool
{
return false;
}
/**
* Test to see if a request contains the HTTP_X_REQUESTED_WITH header.
*/
public function isAJAX(): bool
{
return $this->hasHeader('X-Requested-With')
&& strtolower($this->header('X-Requested-With')->getValue()) === 'xmlhttprequest';
}
/**
* Attempts to detect if the current connection is secure through
* a few different methods.
*/
public function isSecure(): bool
{
if (! empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
return true;
}
if ($this->hasHeader('X-Forwarded-Proto') && $this->header('X-Forwarded-Proto')->getValue() === 'https') {
return true;
}
return $this->hasHeader('Front-End-Https') && ! empty($this->header('Front-End-Https')->getValue()) && strtolower($this->header('Front-End-Https')->getValue()) !== 'off';
}
/**
* Sets the URI path relative to baseURL.
*
* Note: Since current_url() accesses the shared request
* instance, this can be used to change the "current URL"
* for testing.
*
* @param string $path URI path relative to baseURL
* @param App|null $config Optional alternate config to use
*
* @return $this
*
* @deprecated 4.4.0 This method will be private. The parameter $config is deprecated. No longer used.
*/
public function setPath(string $path, ?App $config = null)
{
$this->path = $path;
return $this;
}
/**
* Returns the URI path relative to baseURL,
* running detection as necessary.
*/
public function getPath(): string
{
return $this->path;
}
/**
* Sets the locale string for this request.
*
* @return IncomingRequest
*/
public function setLocale(string $locale)
{
// If it's not a valid locale, set it
// to the default locale for the site.
if (! in_array($locale, $this->validLocales, true)) {
$locale = $this->defaultLocale;
}
$this->locale = $locale;
Locale::setDefault($locale);
return $this;
}
/**
* Set the valid locales.
*
* @return $this
*/
public function setValidLocales(array $locales)
{
$this->validLocales = $locales;
return $this;
}
/**
* Gets the current locale, with a fallback to the default
* locale if none is set.
*/
public function getLocale(): string
{
return $this->locale;
}
/**
* Returns the default locale as set in app/Config/App.php
*/
public function getDefaultLocale(): string
{
return $this->defaultLocale;
}
/**
* Fetch an item from JSON input stream with fallback to $_REQUEST object. This is the simplest way
* to grab data from the request object and can be used in lieu of the
* other get* methods in most cases.
*
* @param array|string|null $index
* @param int|null $filter Filter constant
* @param array|int|null $flags
*
* @return array|bool|float|int|stdClass|string|null
*/
public function getVar($index = null, $filter = null, $flags = null)
{
if (
str_contains($this->getHeaderLine('Content-Type'), 'application/json')
&& $this->body !== null
) {
return $this->getJsonVar($index, false, $filter, $flags);
}
return $this->fetchGlobal('request', $index, $filter, $flags);
}
/**
* A convenience method that grabs the raw input stream and decodes
* the JSON into an array.
*
* If $assoc == true, then all objects in the response will be converted
* to associative arrays.
*
* @param bool $assoc Whether to return objects as associative arrays
* @param int $depth How many levels deep to decode
* @param int $options Bitmask of options
*
* @see http://php.net/manual/en/function.json-decode.php
*
* @return array|bool|float|int|stdClass|null
*
* @throws HTTPException When the body is invalid as JSON.
*/
public function getJSON(bool $assoc = false, int $depth = 512, int $options = 0)
{
if ($this->body === null) {
return null;
}
$result = json_decode($this->body, $assoc, $depth, $options);
if (json_last_error() !== JSON_ERROR_NONE) {
throw HTTPException::forInvalidJSON(json_last_error_msg());
}
return $result;
}
/**
* Get a specific variable from a JSON input stream
*
* @param array|string|null $index The variable that you want which can use dot syntax for getting specific values.
* @param bool $assoc If true, return the result as an associative array.
* @param int|null $filter Filter Constant
* @param array|int|null $flags Option
*
* @return array|bool|float|int|stdClass|string|null
*/
public function getJsonVar($index = null, bool $assoc = false, ?int $filter = null, $flags = null)
{
helper('array');
$data = $this->getJSON(true);
if (! is_array($data)) {
return null;
}
if (is_string($index)) {
$data = dot_array_search($index, $data);
} elseif (is_array($index)) {
$result = [];
foreach ($index as $key) {
$result[$key] = dot_array_search($key, $data);
}
[$data, $result] = [$result, null];
}
if ($data === null) {
return null;
}
$filter ??= FILTER_DEFAULT;
$flags = is_array($flags) ? $flags : (is_numeric($flags) ? (int) $flags : 0);
if ($filter !== FILTER_DEFAULT
|| (
(is_numeric($flags) && $flags !== 0)
|| is_array($flags) && $flags !== []
)
) {
if (is_array($data)) {
// Iterate over array and append filter and flags
array_walk_recursive($data, static function (&$val) use ($filter, $flags): void {
$valType = gettype($val);
$val = filter_var($val, $filter, $flags);
if (in_array($valType, ['int', 'integer', 'float', 'double', 'bool', 'boolean'], true) && $val !== false) {
settype($val, $valType);
}
});
} else {
$dataType = gettype($data);
$data = filter_var($data, $filter, $flags);
if (in_array($dataType, ['int', 'integer', 'float', 'double', 'bool', 'boolean'], true) && $data !== false) {
settype($data, $dataType);
}
}
}
if (! $assoc) {
if (is_array($index)) {
foreach ($data as &$val) {
$val = is_array($val) ? json_decode(json_encode($val)) : $val;
}
return $data;
}
return json_decode(json_encode($data));
}
return $data;
}
/**
* A convenience method that grabs the raw input stream(send method in PUT, PATCH, DELETE) and decodes
* the String into an array.
*
* @return array
*/
public function getRawInput()
{
parse_str($this->body ?? '', $output);
return $output;
}
/**
* Gets a specific variable from raw input stream (send method in PUT, PATCH, DELETE).
*
* @param array|string|null $index The variable that you want which can use dot syntax for getting specific values.
* @param int|null $filter Filter Constant
* @param array|int|null $flags Option
*
* @return array|bool|float|int|object|string|null
*/
public function getRawInputVar($index = null, ?int $filter = null, $flags = null)
{
helper('array');
parse_str($this->body ?? '', $output);
if (is_string($index)) {
$output = dot_array_search($index, $output);
} elseif (is_array($index)) {
$data = [];
foreach ($index as $key) {
$data[$key] = dot_array_search($key, $output);
}
[$output, $data] = [$data, null];
}
$filter ??= FILTER_DEFAULT;
$flags = is_array($flags) ? $flags : (is_numeric($flags) ? (int) $flags : 0);
if (is_array($output)
&& (
$filter !== FILTER_DEFAULT
|| (
(is_numeric($flags) && $flags !== 0)
|| is_array($flags) && $flags !== []
)
)
) {
// Iterate over array and append filter and flags
array_walk_recursive($output, static function (&$val) use ($filter, $flags): void {
$val = filter_var($val, $filter, $flags);
});
return $output;
}
if (is_string($output)) {
return filter_var($output, $filter, $flags);
}
return $output;
}
/**
* Fetch an item from GET data.
*
* @param array|string|null $index Index for item to fetch from $_GET.
* @param int|null $filter A filter name to apply.
* @param array|int|null $flags
*
* @return array|bool|float|int|object|string|null
*/
public function getGet($index = null, $filter = null, $flags = null)
{
return $this->fetchGlobal('get', $index, $filter, $flags);
}
/**
* Fetch an item from POST.
*
* @param array|string|null $index Index for item to fetch from $_POST.
* @param int|null $filter A filter name to apply
* @param array|int|null $flags
*
* @return array|bool|float|int|object|string|null
*/
public function getPost($index = null, $filter = null, $flags = null)
{
return $this->fetchGlobal('post', $index, $filter, $flags);
}
/**
* Fetch an item from POST data with fallback to GET.
*
* @param array|string|null $index Index for item to fetch from $_POST or $_GET
* @param int|null $filter A filter name to apply
* @param array|int|null $flags
*
* @return array|bool|float|int|object|string|null
*/
public function getPostGet($index = null, $filter = null, $flags = null)
{
if ($index === null) {
return array_merge($this->getGet($index, $filter, $flags), $this->getPost($index, $filter, $flags));
}
// Use $_POST directly here, since filter_has_var only
// checks the initial POST data, not anything that might
// have been added since.
return isset($_POST[$index])
? $this->getPost($index, $filter, $flags)
: (isset($_GET[$index]) ? $this->getGet($index, $filter, $flags) : $this->getPost($index, $filter, $flags));
}
/**
* Fetch an item from GET data with fallback to POST.
*
* @param array|string|null $index Index for item to be fetched from $_GET or $_POST
* @param int|null $filter A filter name to apply
* @param array|int|null $flags
*
* @return array|bool|float|int|object|string|null
*/
public function getGetPost($index = null, $filter = null, $flags = null)
{
if ($index === null) {
return array_merge($this->getPost($index, $filter, $flags), $this->getGet($index, $filter, $flags));
}
// Use $_GET directly here, since filter_has_var only
// checks the initial GET data, not anything that might
// have been added since.
return isset($_GET[$index])
? $this->getGet($index, $filter, $flags)
: (isset($_POST[$index]) ? $this->getPost($index, $filter, $flags) : $this->getGet($index, $filter, $flags));
}
/**
* Fetch an item from the COOKIE array.
*
* @param array|string|null $index Index for item to be fetched from $_COOKIE
* @param int|null $filter A filter name to be applied
* @param array|int|null $flags
*
* @return array|bool|float|int|object|string|null
*/
public function getCookie($index = null, $filter = null, $flags = null)
{
return $this->fetchGlobal('cookie', $index, $filter, $flags);
}
/**
* Fetch the user agent string
*
* @return UserAgent
*/
public function getUserAgent()
{
return $this->userAgent;
}
/**
* Attempts to get old Input data that has been flashed to the session
* with redirect_with_input(). It first checks for the data in the old
* POST data, then the old GET data and finally check for dot arrays
*
* @return array|string|null
*/
public function getOldInput(string $key)
{
// If the session hasn't been started, we're done.
if (! isset($_SESSION)) {
return null;
}
// Get previously saved in session
$old = session('_ci_old_input');
// If no data was previously saved, we're done.
if ($old === null) {
return null;
}
// Check for the value in the POST array first.
if (isset($old['post'][$key])) {
return $old['post'][$key];
}
// Next check in the GET array.
if (isset($old['get'][$key])) {
return $old['get'][$key];
}
helper('array');
// Check for an array value in POST.
if (isset($old['post'])) {
$value = dot_array_search($key, $old['post']);
if ($value !== null) {
return $value;
}
}
// Check for an array value in GET.
if (isset($old['get'])) {
$value = dot_array_search($key, $old['get']);
if ($value !== null) {
return $value;
}
}
// requested session key not found
return null;
}
/**
* Returns an array of all files that have been uploaded with this
* request. Each file is represented by an UploadedFile instance.
*/
public function getFiles(): array
{
if ($this->files === null) {
$this->files = new FileCollection();
}
return $this->files->all(); // return all files
}
/**
* Verify if a file exist, by the name of the input field used to upload it, in the collection
* of uploaded files and if is have been uploaded with multiple option.
*
* @return array|null
*/
public function getFileMultiple(string $fileID)
{
if ($this->files === null) {
$this->files = new FileCollection();
}
return $this->files->getFileMultiple($fileID);
}
/**
* Retrieves a single file by the name of the input field used
* to upload it.
*
* @return UploadedFile|null
*/
public function getFile(string $fileID)
{
if ($this->files === null) {
$this->files = new FileCollection();
}
return $this->files->getFile($fileID);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/Response.php | system/HTTP/Response.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP;
use CodeIgniter\Cookie\Cookie;
use CodeIgniter\Cookie\CookieStore;
use CodeIgniter\HTTP\Exceptions\HTTPException;
use Config\App;
use Config\Cookie as CookieConfig;
/**
* Representation of an outgoing, server-side response.
*
* Per the HTTP specification, this interface includes properties for
* each of the following:
*
* - Protocol version
* - Status code and reason phrase
* - Headers
* - Message body
*
* @see \CodeIgniter\HTTP\ResponseTest
*/
class Response extends Message implements ResponseInterface
{
use ResponseTrait;
/**
* HTTP status codes
*
* @var array
*/
protected static $statusCodes = [
// 1xx: Informational
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing', // http://www.iana.org/go/rfc2518
103 => 'Early Hints', // http://www.ietf.org/rfc/rfc8297.txt
// 2xx: Success
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information', // 1.1
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status', // http://www.iana.org/go/rfc4918
208 => 'Already Reported', // http://www.iana.org/go/rfc5842
226 => 'IM Used', // 1.1; http://www.ietf.org/rfc/rfc3229.txt
// 3xx: Redirection
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found', // Formerly 'Moved Temporarily'
303 => 'See Other', // 1.1
304 => 'Not Modified',
305 => 'Use Proxy', // 1.1
306 => 'Switch Proxy', // No longer used
307 => 'Temporary Redirect', // 1.1
308 => 'Permanent Redirect', // 1.1; Experimental; http://www.ietf.org/rfc/rfc7238.txt
// 4xx: Client error
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Content Too Large', // https://www.iana.org/assignments/http-status-codes/http-status-codes.xml
414 => 'URI Too Long', // https://www.iana.org/assignments/http-status-codes/http-status-codes.xml
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
418 => "I'm a teapot", // April's Fools joke; http://www.ietf.org/rfc/rfc2324.txt
// 419 (Authentication Timeout) is a non-standard status code with unknown origin
421 => 'Misdirected Request', // http://www.iana.org/go/rfc7540 Section 9.1.2
422 => 'Unprocessable Content', // https://www.iana.org/assignments/http-status-codes/http-status-codes.xml
423 => 'Locked', // http://www.iana.org/go/rfc4918
424 => 'Failed Dependency', // http://www.iana.org/go/rfc4918
425 => 'Too Early', // https://datatracker.ietf.org/doc/draft-ietf-httpbis-replay/
426 => 'Upgrade Required',
428 => 'Precondition Required', // 1.1; http://www.ietf.org/rfc/rfc6585.txt
429 => 'Too Many Requests', // 1.1; http://www.ietf.org/rfc/rfc6585.txt
431 => 'Request Header Fields Too Large', // 1.1; http://www.ietf.org/rfc/rfc6585.txt
451 => 'Unavailable For Legal Reasons', // http://tools.ietf.org/html/rfc7725
499 => 'Client Closed Request', // http://lxr.nginx.org/source/src/http/ngx_http_request.h#0133
// 5xx: Server error
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates', // 1.1; http://www.ietf.org/rfc/rfc2295.txt
507 => 'Insufficient Storage', // http://www.iana.org/go/rfc4918
508 => 'Loop Detected', // http://www.iana.org/go/rfc5842
510 => 'Not Extended', // http://www.ietf.org/rfc/rfc2774.txt
511 => 'Network Authentication Required', // http://www.ietf.org/rfc/rfc6585.txt
599 => 'Network Connect Timeout Error', // https://httpstatuses.com/599
];
/**
* The current reason phrase for this response.
* If empty string, will use the default provided for the status code.
*
* @var string
*/
protected $reason = '';
/**
* The current status code for this response.
* The status code is a 3-digit integer result code of the server's attempt
* to understand and satisfy the request.
*
* @var int
*/
protected $statusCode = 200;
/**
* If true, will not write output. Useful during testing.
*
* @var bool
*
* @internal Used for framework testing, should not be relied on otherwise
*/
protected $pretend = false;
/**
* Constructor
*
* @param App $config
*
* @todo Recommend removing reliance on config injection
*
* @deprecated 4.5.0 The param $config is no longer used.
*/
public function __construct($config) // @phpstan-ignore-line
{
// Default to a non-caching page.
// Also ensures that a Cache-control header exists.
$this->noCache();
// We need CSP object even if not enabled to avoid calls to non existing methods
$this->CSP = service('csp');
$this->cookieStore = new CookieStore([]);
$cookie = config(CookieConfig::class);
Cookie::setDefaults($cookie);
// Default to an HTML Content-Type. Devs can override if needed.
$this->setContentType('text/html');
}
/**
* Turns "pretend" mode on or off to aid in testing.
*
* Note that this is not a part of the interface so
* should not be relied on outside of internal testing.
*
* @return $this
*
* @internal For testing purposes only.
* @testTag only available to test code
*/
public function pretend(bool $pretend = true)
{
$this->pretend = $pretend;
return $this;
}
/**
* Gets the response status code.
*
* The status code is a 3-digit integer result code of the server's attempt
* to understand and satisfy the request.
*
* @return int Status code.
*/
public function getStatusCode(): int
{
if (empty($this->statusCode)) {
throw HTTPException::forMissingResponseStatus();
}
return $this->statusCode;
}
/**
* Gets the response reason phrase associated with the status code.
*
* Because a reason phrase is not a required element in a response
* status line, the reason phrase value MAY be null. Implementations MAY
* choose to return the default RFC 7231 recommended reason phrase (or those
* listed in the IANA HTTP Status Code Registry) for the response's
* status code.
*
* @see http://tools.ietf.org/html/rfc7231#section-6
* @see http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
*
* @return string Reason phrase; must return an empty string if none present.
*/
public function getReasonPhrase()
{
if ($this->reason === '') {
return ! empty($this->statusCode) ? static::$statusCodes[$this->statusCode] : '';
}
return $this->reason;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/ResponseInterface.php | system/HTTP/ResponseInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP;
use CodeIgniter\Cookie\Cookie;
use CodeIgniter\Cookie\CookieStore;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\HTTP\Exceptions\HTTPException;
use CodeIgniter\Pager\PagerInterface;
use DateTime;
/**
* Representation of an outgoing, server-side response.
* Most of these methods are supplied by ResponseTrait.
*
* Per the HTTP specification, this interface includes properties for
* each of the following:
*
* - Protocol version
* - Status code and reason phrase
* - Headers
* - Message body
*/
interface ResponseInterface extends MessageInterface
{
/**
* Constants for status codes.
* From https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
*/
// Informational
public const HTTP_CONTINUE = 100;
public const HTTP_SWITCHING_PROTOCOLS = 101;
public const HTTP_PROCESSING = 102;
public const HTTP_EARLY_HINTS = 103;
public const HTTP_OK = 200;
public const HTTP_CREATED = 201;
public const HTTP_ACCEPTED = 202;
public const HTTP_NONAUTHORITATIVE_INFORMATION = 203;
public const HTTP_NO_CONTENT = 204;
public const HTTP_RESET_CONTENT = 205;
public const HTTP_PARTIAL_CONTENT = 206;
public const HTTP_MULTI_STATUS = 207;
public const HTTP_ALREADY_REPORTED = 208;
public const HTTP_IM_USED = 226;
public const HTTP_MULTIPLE_CHOICES = 300;
public const HTTP_MOVED_PERMANENTLY = 301;
public const HTTP_FOUND = 302;
public const HTTP_SEE_OTHER = 303;
public const HTTP_NOT_MODIFIED = 304;
public const HTTP_USE_PROXY = 305;
public const HTTP_SWITCH_PROXY = 306;
public const HTTP_TEMPORARY_REDIRECT = 307;
public const HTTP_PERMANENT_REDIRECT = 308;
public const HTTP_BAD_REQUEST = 400;
public const HTTP_UNAUTHORIZED = 401;
public const HTTP_PAYMENT_REQUIRED = 402;
public const HTTP_FORBIDDEN = 403;
public const HTTP_NOT_FOUND = 404;
public const HTTP_METHOD_NOT_ALLOWED = 405;
public const HTTP_NOT_ACCEPTABLE = 406;
public const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
public const HTTP_REQUEST_TIMEOUT = 408;
public const HTTP_CONFLICT = 409;
public const HTTP_GONE = 410;
public const HTTP_LENGTH_REQUIRED = 411;
public const HTTP_PRECONDITION_FAILED = 412;
public const HTTP_PAYLOAD_TOO_LARGE = 413;
public const HTTP_URI_TOO_LONG = 414;
public const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
public const HTTP_RANGE_NOT_SATISFIABLE = 416;
public const HTTP_EXPECTATION_FAILED = 417;
public const HTTP_IM_A_TEAPOT = 418;
public const HTTP_MISDIRECTED_REQUEST = 421;
public const HTTP_UNPROCESSABLE_ENTITY = 422;
public const HTTP_LOCKED = 423;
public const HTTP_FAILED_DEPENDENCY = 424;
public const HTTP_TOO_EARLY = 425;
public const HTTP_UPGRADE_REQUIRED = 426;
public const HTTP_PRECONDITION_REQUIRED = 428;
public const HTTP_TOO_MANY_REQUESTS = 429;
public const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431;
public const HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451;
public const HTTP_CLIENT_CLOSED_REQUEST = 499;
public const HTTP_INTERNAL_SERVER_ERROR = 500;
public const HTTP_NOT_IMPLEMENTED = 501;
public const HTTP_BAD_GATEWAY = 502;
public const HTTP_SERVICE_UNAVAILABLE = 503;
public const HTTP_GATEWAY_TIMEOUT = 504;
public const HTTP_HTTP_VERSION_NOT_SUPPORTED = 505;
public const HTTP_VARIANT_ALSO_NEGOTIATES = 506;
public const HTTP_INSUFFICIENT_STORAGE = 507;
public const HTTP_LOOP_DETECTED = 508;
public const HTTP_NOT_EXTENDED = 510;
public const HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511;
public const HTTP_NETWORK_CONNECT_TIMEOUT_ERROR = 599;
/**
* Gets the response status code.
*
* The status code is a 3-digit integer result code of the server's attempt
* to understand and satisfy the request.
*
* @return int Status code.
*/
public function getStatusCode(): int;
/**
* Return an instance with the specified status code and, optionally, reason phrase.
*
* If no reason phrase is specified, will default recommended reason phrase for
* the response's status code.
*
* @see http://tools.ietf.org/html/rfc7231#section-6
* @see http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
*
* @param int $code The 3-digit integer result code to set.
* @param string $reason The reason phrase to use with the
* provided status code; if none is provided, will
* default to the IANA name.
*
* @return $this
*
* @throws HTTPException For invalid status code arguments.
*/
public function setStatusCode(int $code, string $reason = '');
/**
* Gets the response reason phrase associated with the status code.
*
* Because a reason phrase is not a required element in a response
* status line, the reason phrase value MAY be null. Implementations MAY
* choose to return the default RFC 7231 recommended reason phrase (or those
* listed in the IANA HTTP Status Code Registry) for the response's
* status code.
*
* @see http://tools.ietf.org/html/rfc7231#section-6
* @see http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
*
* @return string Reason phrase; must return an empty string if none present.
*/
public function getReasonPhrase();
// --------------------------------------------------------------------
// Convenience Methods
// --------------------------------------------------------------------
/**
* Sets the date header
*
* @return $this
*/
public function setDate(DateTime $date);
/**
* Sets the Last-Modified date header.
*
* $date can be either a string representation of the date or,
* preferably, an instance of DateTime.
*
* @param DateTime|string $date
*
* @return $this
*/
public function setLastModified($date);
/**
* Set the Link Header
*
* @see http://tools.ietf.org/html/rfc5988
*
* @return $this
*
* @todo Recommend moving to Pager
*/
public function setLink(PagerInterface $pager);
/**
* Sets the Content Type header for this response with the mime type
* and, optionally, the charset.
*
* @return $this
*/
public function setContentType(string $mime, string $charset = 'UTF-8');
// --------------------------------------------------------------------
// Formatter Methods
// --------------------------------------------------------------------
/**
* Converts the $body into JSON and sets the Content Type header.
*
* @param array|object|string $body
*
* @return $this
*/
public function setJSON($body, bool $unencoded = false);
/**
* Returns the current body, converted to JSON is it isn't already.
*
* @return bool|string|null
*
* @throws InvalidArgumentException If the body property is not array.
*/
public function getJSON();
/**
* Converts $body into XML, and sets the correct Content-Type.
*
* @param array|string $body
*
* @return $this
*/
public function setXML($body);
/**
* Retrieves the current body into XML and returns it.
*
* @return bool|string|null
*
* @throws InvalidArgumentException If the body property is not array.
*/
public function getXML();
// --------------------------------------------------------------------
// Cache Control Methods
//
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
// --------------------------------------------------------------------
/**
* Sets the appropriate headers to ensure this response
* is not cached by the browsers.
*
* @return $this
*/
public function noCache();
/**
* A shortcut method that allows the developer to set all of the
* cache-control headers in one method call.
*
* The options array is used to provide the cache-control directives
* for the header. It might look something like:
*
* $options = [
* 'max-age' => 300,
* 's-maxage' => 900
* 'etag' => 'abcde',
* ];
*
* Typical options are:
* - etag
* - last-modified
* - max-age
* - s-maxage
* - private
* - public
* - must-revalidate
* - proxy-revalidate
* - no-transform
*
* @return $this
*/
public function setCache(array $options = []);
// --------------------------------------------------------------------
// Output Methods
// --------------------------------------------------------------------
/**
* Sends the output to the browser.
*
* @return $this
*/
public function send();
/**
* Sends the headers of this HTTP request to the browser.
*
* @return $this
*/
public function sendHeaders();
/**
* Sends the Body of the message to the browser.
*
* @return $this
*/
public function sendBody();
// --------------------------------------------------------------------
// Cookie Methods
// --------------------------------------------------------------------
/**
* Set a cookie
*
* Accepts an arbitrary number of binds (up to 7) or an associative
* array in the first parameter containing all the values.
*
* @param array|Cookie|string $name Cookie name / array containing binds / Cookie object
* @param string $value Cookie value
* @param int $expire Cookie expiration time in seconds
* @param string $domain Cookie domain (e.g.: '.yourdomain.com')
* @param string $path Cookie path (default: '/')
* @param string $prefix Cookie name prefix
* @param bool $secure Whether to only transfer cookies via SSL
* @param bool $httponly Whether only make the cookie accessible via HTTP (no javascript)
* @param string|null $samesite
*
* @return $this
*/
public function setCookie(
$name,
$value = '',
$expire = 0,
$domain = '',
$path = '/',
$prefix = '',
$secure = false,
$httponly = false,
$samesite = null,
);
/**
* Checks to see if the Response has a specified cookie or not.
*/
public function hasCookie(string $name, ?string $value = null, string $prefix = ''): bool;
/**
* Returns the cookie
*
* @return array<string, Cookie>|Cookie|null
*/
public function getCookie(?string $name = null, string $prefix = '');
/**
* Sets a cookie to be deleted when the response is sent.
*
* @return $this
*/
public function deleteCookie(string $name = '', string $domain = '', string $path = '/', string $prefix = '');
/**
* Returns all cookies currently set.
*
* @return array<string, Cookie>
*/
public function getCookies();
/**
* Returns the `CookieStore` instance.
*
* @return CookieStore
*/
public function getCookieStore();
// --------------------------------------------------------------------
// Response Methods
// --------------------------------------------------------------------
/**
* Perform a redirect to a new URL, in two flavors: header or location.
*
* @param string $uri The URI to redirect to
* @param int $code The type of redirection, defaults to 302
*
* @return $this
*
* @throws HTTPException For invalid status code.
*/
public function redirect(string $uri, string $method = 'auto', ?int $code = null);
/**
* Force a download.
*
* Generates the headers that force a download to happen. And
* sends the file to the browser.
*
* @param string $filename The path to the file to send
* @param string|null $data The data to be downloaded
* @param bool $setMime Whether to try and send the actual MIME type
*
* @return DownloadResponse|null
*/
public function download(string $filename = '', $data = '', bool $setMime = false);
// --------------------------------------------------------------------
// CSP Methods
// --------------------------------------------------------------------
/**
* Get Content Security Policy handler.
*/
public function getCSP(): ContentSecurityPolicy;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/RequestTrait.php | system/HTTP/RequestTrait.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP;
use CodeIgniter\Exceptions\ConfigException;
use CodeIgniter\Validation\FormatRules;
use Config\App;
/**
* Request Trait
*
* Additional methods to make a PSR-7 Request class
* compliant with the framework's own RequestInterface.
*
* @see https://github.com/php-fig/http-message/blob/master/src/RequestInterface.php
*/
trait RequestTrait
{
/**
* Configuration settings.
*
* @var App
*/
protected $config;
/**
* IP address of the current user.
*
* @var string
*
* @deprecated Will become private in a future release
*/
protected $ipAddress = '';
/**
* Stores values we've retrieved from PHP globals.
*
* @var array{get?: array, post?: array, request?: array, cookie?: array, server?: array}
*/
protected $globals = [];
/**
* Gets the user's IP address.
*
* @return string IP address if it can be detected.
* If the IP address is not a valid IP address,
* then will return '0.0.0.0'.
*/
public function getIPAddress(): string
{
if ($this->ipAddress !== '') {
return $this->ipAddress;
}
$ipValidator = [
new FormatRules(),
'valid_ip',
];
$proxyIPs = $this->config->proxyIPs;
if (! empty($proxyIPs) && (! is_array($proxyIPs) || is_int(array_key_first($proxyIPs)))) {
throw new ConfigException(
'You must set an array with Proxy IP address key and HTTP header name value in Config\App::$proxyIPs.',
);
}
$this->ipAddress = $this->getServer('REMOTE_ADDR');
// If this is a CLI request, $this->ipAddress is null.
if ($this->ipAddress === null) {
return $this->ipAddress = '0.0.0.0';
}
// @TODO Extract all this IP address logic to another class.
foreach ($proxyIPs as $proxyIP => $header) {
// Check if we have an IP address or a subnet
if (! str_contains($proxyIP, '/')) {
// An IP address (and not a subnet) is specified.
// We can compare right away.
if ($proxyIP === $this->ipAddress) {
$spoof = $this->getClientIP($header);
if ($spoof !== null) {
$this->ipAddress = $spoof;
break;
}
}
continue;
}
// We have a subnet ... now the heavy lifting begins
if (! isset($separator)) {
$separator = $ipValidator($this->ipAddress, 'ipv6') ? ':' : '.';
}
// If the proxy entry doesn't match the IP protocol - skip it
if (! str_contains($proxyIP, $separator)) {
continue;
}
// Convert the REMOTE_ADDR IP address to binary, if needed
if (! isset($ip, $sprintf)) {
if ($separator === ':') {
// Make sure we're having the "full" IPv6 format
$ip = explode(':', str_replace('::', str_repeat(':', 9 - substr_count($this->ipAddress, ':')), $this->ipAddress));
for ($j = 0; $j < 8; $j++) {
$ip[$j] = intval($ip[$j], 16);
}
$sprintf = '%016b%016b%016b%016b%016b%016b%016b%016b';
} else {
$ip = explode('.', $this->ipAddress);
$sprintf = '%08b%08b%08b%08b';
}
$ip = vsprintf($sprintf, $ip);
}
// Split the netmask length off the network address
sscanf($proxyIP, '%[^/]/%d', $netaddr, $masklen);
// Again, an IPv6 address is most likely in a compressed form
if ($separator === ':') {
$netaddr = explode(':', str_replace('::', str_repeat(':', 9 - substr_count($netaddr, ':')), $netaddr));
for ($i = 0; $i < 8; $i++) {
$netaddr[$i] = intval($netaddr[$i], 16);
}
} else {
$netaddr = explode('.', $netaddr);
}
// Convert to binary and finally compare
if (strncmp($ip, vsprintf($sprintf, $netaddr), $masklen) === 0) {
$spoof = $this->getClientIP($header);
if ($spoof !== null) {
$this->ipAddress = $spoof;
break;
}
}
}
if (! $ipValidator($this->ipAddress)) {
return $this->ipAddress = '0.0.0.0';
}
return $this->ipAddress;
}
/**
* Gets the client IP address from the HTTP header.
*/
private function getClientIP(string $header): ?string
{
$ipValidator = [
new FormatRules(),
'valid_ip',
];
$spoof = null;
$headerObj = $this->header($header);
if ($headerObj !== null) {
$spoof = $headerObj->getValue();
// Some proxies typically list the whole chain of IP
// addresses through which the client has reached us.
// e.g. client_ip, proxy_ip1, proxy_ip2, etc.
sscanf($spoof, '%[^,]', $spoof);
if (! $ipValidator($spoof)) {
$spoof = null;
}
}
return $spoof;
}
/**
* Fetch an item from the $_SERVER array.
*
* @param array|string|null $index Index for item to be fetched from $_SERVER
* @param int|null $filter A filter name to be applied
* @param array|int|null $flags
*
* @return mixed
*/
public function getServer($index = null, $filter = null, $flags = null)
{
return $this->fetchGlobal('server', $index, $filter, $flags);
}
/**
* Fetch an item from the $_ENV array.
*
* @param array|string|null $index Index for item to be fetched from $_ENV
* @param int|null $filter A filter name to be applied
* @param array|int|null $flags
*
* @return mixed
*
* @deprecated 4.4.4 This method does not work from the beginning. Use `env()`.
*/
public function getEnv($index = null, $filter = null, $flags = null)
{
// @phpstan-ignore-next-line
return $this->fetchGlobal('env', $index, $filter, $flags);
}
/**
* Allows manually setting the value of PHP global, like $_GET, $_POST, etc.
*
* @param 'cookie'|'get'|'post'|'request'|'server' $name Superglobal name (lowercase)
* @param mixed $value
*
* @return $this
*/
public function setGlobal(string $name, $value)
{
$this->globals[$name] = $value;
return $this;
}
/**
* Fetches one or more items from a global, like cookies, get, post, etc.
* Can optionally filter the input when you retrieve it by passing in
* a filter.
*
* If $type is an array, it must conform to the input allowed by the
* filter_input_array method.
*
* http://php.net/manual/en/filter.filters.sanitize.php
*
* @param 'cookie'|'get'|'post'|'request'|'server' $name Superglobal name (lowercase)
* @param array|int|string|null $index
* @param int|null $filter Filter constant
* @param array|int|null $flags Options
*
* @return array|bool|float|int|object|string|null
*/
public function fetchGlobal(string $name, $index = null, ?int $filter = null, $flags = null)
{
if (! isset($this->globals[$name])) {
$this->populateGlobals($name);
}
// Null filters cause null values to return.
$filter ??= FILTER_DEFAULT;
$flags = is_array($flags) ? $flags : (is_numeric($flags) ? (int) $flags : 0);
// Return all values when $index is null
if ($index === null) {
$values = [];
foreach ($this->globals[$name] as $key => $value) {
$values[$key] = is_array($value)
? $this->fetchGlobal($name, $key, $filter, $flags)
: filter_var($value, $filter, $flags);
}
return $values;
}
// allow fetching multiple keys at once
if (is_array($index)) {
$output = [];
foreach ($index as $key) {
$output[$key] = $this->fetchGlobal($name, $key, $filter, $flags);
}
return $output;
}
// Does the index contain array notation?
if (is_string($index) && ($count = preg_match_all('/(?:^[^\[]+)|\[[^]]*\]/', $index, $matches)) > 1) {
$value = $this->globals[$name];
for ($i = 0; $i < $count; $i++) {
$key = trim($matches[0][$i], '[]');
if ($key === '') { // Empty notation will return the value as array
break;
}
if (isset($value[$key])) {
$value = $value[$key];
} else {
return null;
}
}
}
if (! isset($value)) {
$value = $this->globals[$name][$index] ?? null;
}
if (is_array($value)
&& (
$filter !== FILTER_DEFAULT
|| (
(is_numeric($flags) && $flags !== 0)
|| is_array($flags) && $flags !== []
)
)
) {
// Iterate over array and append filter and flags
array_walk_recursive($value, static function (&$val) use ($filter, $flags): void {
$val = filter_var($val, $filter, $flags);
});
return $value;
}
// Cannot filter these types of data automatically...
if (is_array($value) || is_object($value) || $value === null) {
return $value;
}
return filter_var($value, $filter, $flags);
}
/**
* Saves a copy of the current state of one of several PHP globals,
* so we can retrieve them later.
*
* @param 'cookie'|'get'|'post'|'request'|'server' $name Superglobal name (lowercase)
*
* @return void
*/
protected function populateGlobals(string $name)
{
if (! isset($this->globals[$name])) {
$this->globals[$name] = [];
}
// Don't populate ENV as it might contain
// sensitive data that we don't want to get logged.
switch ($name) {
case 'get':
$this->globals['get'] = $_GET;
break;
case 'post':
$this->globals['post'] = $_POST;
break;
case 'request':
$this->globals['request'] = $_REQUEST;
break;
case 'cookie':
$this->globals['cookie'] = $_COOKIE;
break;
case 'server':
$this->globals['server'] = $_SERVER;
break;
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/RedirectResponse.php | system/HTTP/RedirectResponse.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP;
use CodeIgniter\Cookie\CookieStore;
use CodeIgniter\HTTP\Exceptions\HTTPException;
/**
* Handle a redirect response
*
* @see \CodeIgniter\HTTP\RedirectResponseTest
*/
class RedirectResponse extends Response
{
/**
* Sets the URI to redirect to and, optionally, the HTTP status code to use.
* If no code is provided it will be automatically determined.
*
* @param string $uri The URI path (relative to baseURL) to redirect to
* @param int|null $code HTTP status code
*
* @return $this
*/
public function to(string $uri, ?int $code = null, string $method = 'auto')
{
// If it appears to be a relative URL, then convert to full URL
// for better security.
if (! str_starts_with($uri, 'http')) {
$uri = site_url($uri);
}
return $this->redirect($uri, $method, $code);
}
/**
* Sets the URI to redirect to but as a reverse-routed or named route
* instead of a raw URI.
*
* @param string $route Route name or Controller::method
*
* @return $this
*
* @throws HTTPException
*/
public function route(string $route, array $params = [], ?int $code = null, string $method = 'auto')
{
$namedRoute = $route;
$route = service('routes')->reverseRoute($route, ...$params);
if (! $route) {
throw HTTPException::forInvalidRedirectRoute($namedRoute);
}
return $this->redirect(site_url($route), $method, $code);
}
/**
* Helper function to return to previous page.
*
* Example:
* return redirect()->back();
*
* @return $this
*/
public function back(?int $code = null, string $method = 'auto')
{
service('session');
return $this->redirect(previous_url(), $method, $code);
}
/**
* Sets the current $_GET and $_POST arrays in the session.
* This also saves the validation errors.
*
* It will then be available via the 'old()' helper function.
*
* @return $this
*/
public function withInput()
{
$session = service('session');
$session->setFlashdata('_ci_old_input', [
'get' => $_GET ?? [], // @phpstan-ignore nullCoalesce.variable
'post' => $_POST ?? [], // @phpstan-ignore nullCoalesce.variable
]);
$this->withErrors();
return $this;
}
/**
* Sets validation errors in the session.
*
* If the validation has any errors, transmit those back
* so they can be displayed when the validation is handled
* within a method different than displaying the form.
*
* @return $this
*/
private function withErrors(): self
{
$validation = service('validation');
if ($validation->getErrors() !== []) {
service('session')->setFlashdata('_ci_validation_errors', $validation->getErrors());
}
return $this;
}
/**
* Adds a key and message to the session as Flashdata.
*
* @param array|string $message
*
* @return $this
*/
public function with(string $key, $message)
{
service('session')->setFlashdata($key, $message);
return $this;
}
/**
* Copies any cookies from the global Response instance
* into this RedirectResponse. Useful when you've just
* set a cookie but need ensure that's actually sent
* with the response instead of lost.
*
* @return $this|RedirectResponse
*/
public function withCookies()
{
$this->cookieStore = new CookieStore(service('response')->getCookies());
return $this;
}
/**
* Copies any headers from the global Response instance
* into this RedirectResponse. Useful when you've just
* set a header be need to ensure its actually sent
* with the redirect response.
*
* @return $this|RedirectResponse
*/
public function withHeaders()
{
foreach (service('response')->headers() as $name => $value) {
if ($value instanceof Header) {
$this->setHeader($name, $value->getValue());
} else {
foreach ($value as $header) {
$this->addHeader($name, $header->getValue());
}
}
}
return $this;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/CLIRequest.php | system/HTTP/CLIRequest.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP;
use CodeIgniter\Exceptions\RuntimeException;
use Config\App;
use Locale;
/**
* Represents a request from the command-line. Provides additional
* tools to interact with that request since CLI requests are not
* static like HTTP requests might be.
*
* Portions of this code were initially from the FuelPHP Framework,
* version 1.7.x, and used here under the MIT license they were
* originally made available under.
*
* http://fuelphp.com
*
* @see \CodeIgniter\HTTP\CLIRequestTest
*/
class CLIRequest extends Request
{
/**
* Stores the segments of our cli "URI" command.
*
* @var array
*/
protected $segments = [];
/**
* Command line options and their values.
*
* @var array
*/
protected $options = [];
/**
* Command line arguments (segments and options).
*
* @var array
*/
protected $args = [];
/**
* Set the expected HTTP verb
*
* @var string
*/
protected $method = 'CLI';
/**
* Constructor
*/
public function __construct(App $config)
{
if (! is_cli()) {
throw new RuntimeException(static::class . ' needs to run from the command line.'); // @codeCoverageIgnore
}
parent::__construct($config);
// Don't terminate the script when the cli's tty goes away
ignore_user_abort(true);
$this->parseCommand();
// Set SiteURI for this request
$this->uri = new SiteURI($config, $this->getPath());
}
/**
* Returns the "path" of the request script so that it can be used
* in routing to the appropriate controller/method.
*
* The path is determined by treating the command line arguments
* as if it were a URL - up until we hit our first option.
*
* Example:
* php index.php users 21 profile -foo bar
*
* // Routes to /users/21/profile (index is removed for routing sake)
* // with the option foo = bar.
*/
public function getPath(): string
{
return implode('/', $this->segments);
}
/**
* Returns an associative array of all CLI options found, with
* their values.
*/
public function getOptions(): array
{
return $this->options;
}
/**
* Returns an array of all CLI arguments (segments and options).
*/
public function getArgs(): array
{
return $this->args;
}
/**
* Returns the path segments.
*/
public function getSegments(): array
{
return $this->segments;
}
/**
* Returns the value for a single CLI option that was passed in.
*
* @return string|null
*/
public function getOption(string $key)
{
return $this->options[$key] ?? null;
}
/**
* Returns the options as a string, suitable for passing along on
* the CLI to other commands.
*
* Example:
* $options = [
* 'foo' => 'bar',
* 'baz' => 'queue some stuff'
* ];
*
* getOptionString() = '-foo bar -baz "queue some stuff"'
*/
public function getOptionString(bool $useLongOpts = false): string
{
if ($this->options === []) {
return '';
}
$out = '';
foreach ($this->options as $name => $value) {
if ($useLongOpts && mb_strlen($name) > 1) {
$out .= "--{$name} ";
} else {
$out .= "-{$name} ";
}
if ($value === null) {
continue;
}
if (mb_strpos($value, ' ') !== false) {
$out .= '"' . $value . '" ';
} else {
$out .= "{$value} ";
}
}
return trim($out);
}
/**
* Parses the command line it was called from and collects all options
* and valid segments.
*
* NOTE: I tried to use getopt but had it fail occasionally to find
* any options, where argv has always had our back.
*
* @return void
*/
protected function parseCommand()
{
$args = $this->getServer('argv');
array_shift($args); // Scrap index.php
$optionValue = false;
foreach ($args as $i => $arg) {
if (mb_strpos($arg, '-') !== 0) {
if ($optionValue) {
$optionValue = false;
} else {
$this->segments[] = $arg;
$this->args[] = $arg;
}
continue;
}
$arg = ltrim($arg, '-');
$value = null;
if (isset($args[$i + 1]) && mb_strpos($args[$i + 1], '-') !== 0) {
$value = $args[$i + 1];
$optionValue = true;
}
$this->options[$arg] = $value;
$this->args[$arg] = $value;
}
}
/**
* Determines if this request was made from the command line (CLI).
*/
public function isCLI(): bool
{
return true;
}
/**
* Fetch an item from GET data.
*
* @param array|string|null $index Index for item to fetch from $_GET.
* @param int|null $filter A filter name to apply.
* @param array|int|null $flags
*
* @return array|null
*/
public function getGet($index = null, $filter = null, $flags = null)
{
return $this->returnNullOrEmptyArray($index);
}
/**
* Fetch an item from POST.
*
* @param array|string|null $index Index for item to fetch from $_POST.
* @param int|null $filter A filter name to apply
* @param array|int|null $flags
*
* @return array|null
*/
public function getPost($index = null, $filter = null, $flags = null)
{
return $this->returnNullOrEmptyArray($index);
}
/**
* Fetch an item from POST data with fallback to GET.
*
* @param array|string|null $index Index for item to fetch from $_POST or $_GET
* @param int|null $filter A filter name to apply
* @param array|int|null $flags
*
* @return array|null
*/
public function getPostGet($index = null, $filter = null, $flags = null)
{
return $this->returnNullOrEmptyArray($index);
}
/**
* Fetch an item from GET data with fallback to POST.
*
* @param array|string|null $index Index for item to be fetched from $_GET or $_POST
* @param int|null $filter A filter name to apply
* @param array|int|null $flags
*
* @return array|null
*/
public function getGetPost($index = null, $filter = null, $flags = null)
{
return $this->returnNullOrEmptyArray($index);
}
/**
* This is a place holder for calls from cookie_helper get_cookie().
*
* @param array|string|null $index Index for item to be fetched from $_COOKIE
* @param int|null $filter A filter name to be applied
* @param mixed $flags
*
* @return array|null
*/
public function getCookie($index = null, $filter = null, $flags = null)
{
return $this->returnNullOrEmptyArray($index);
}
/**
* @param array|string|null $index
*
* @return array|null
*/
private function returnNullOrEmptyArray($index)
{
return ($index === null || is_array($index)) ? [] : null;
}
/**
* Gets the current locale, with a fallback to the default
* locale if none is set.
*/
public function getLocale(): string
{
return Locale::getDefault();
}
/**
* Checks this request type.
*/
public function is(string $type): bool
{
return false;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/ResponseTrait.php | system/HTTP/ResponseTrait.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP;
use CodeIgniter\Cookie\Cookie;
use CodeIgniter\Cookie\CookieStore;
use CodeIgniter\Cookie\Exceptions\CookieException;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\HTTP\Exceptions\HTTPException;
use CodeIgniter\I18n\Time;
use CodeIgniter\Pager\PagerInterface;
use CodeIgniter\Security\Exceptions\SecurityException;
use Config\Cookie as CookieConfig;
use DateTime;
use DateTimeZone;
/**
* Response Trait
*
* Additional methods to make a PSR-7 Response class
* compliant with the framework's own ResponseInterface.
*
* @see https://github.com/php-fig/http-message/blob/master/src/ResponseInterface.php
*/
trait ResponseTrait
{
/**
* Content security policy handler
*
* @var ContentSecurityPolicy
*/
protected $CSP;
/**
* CookieStore instance.
*
* @var CookieStore
*/
protected $cookieStore;
/**
* Type of format the body is in.
* Valid: html, json, xml
*
* @var string
*/
protected $bodyFormat = 'html';
/**
* Return an instance with the specified status code and, optionally, reason phrase.
*
* If no reason phrase is specified, will default recommended reason phrase for
* the response's status code.
*
* @see http://tools.ietf.org/html/rfc7231#section-6
* @see http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
*
* @param int $code The 3-digit integer result code to set.
* @param string $reason The reason phrase to use with the
* provided status code; if none is provided, will
* default to the IANA name.
*
* @return $this
*
* @throws HTTPException For invalid status code arguments.
*/
public function setStatusCode(int $code, string $reason = '')
{
// Valid range?
if ($code < 100 || $code > 599) {
throw HTTPException::forInvalidStatusCode($code);
}
// Unknown and no message?
if (! array_key_exists($code, static::$statusCodes) && ($reason === '')) {
throw HTTPException::forUnkownStatusCode($code);
}
$this->statusCode = $code;
$this->reason = ($reason !== '') ? $reason : static::$statusCodes[$code];
return $this;
}
// --------------------------------------------------------------------
// Convenience Methods
// --------------------------------------------------------------------
/**
* Sets the date header
*
* @return $this
*/
public function setDate(DateTime $date)
{
$date->setTimezone(new DateTimeZone('UTC'));
$this->setHeader('Date', $date->format('D, d M Y H:i:s') . ' GMT');
return $this;
}
/**
* Set the Link Header
*
* @see http://tools.ietf.org/html/rfc5988
*
* @return $this
*
* @todo Recommend moving to Pager
*/
public function setLink(PagerInterface $pager)
{
$links = '';
$previous = $pager->getPreviousPageURI();
if (is_string($previous) && $previous !== '') {
$links .= '<' . $pager->getPageURI($pager->getFirstPage()) . '>; rel="first",';
$links .= '<' . $previous . '>; rel="prev"';
}
$next = $pager->getNextPageURI();
if (is_string($next) && $next !== '' && is_string($previous) && $previous !== '') {
$links .= ',';
}
if (is_string($next) && $next !== '') {
$links .= '<' . $next . '>; rel="next",';
$links .= '<' . $pager->getPageURI($pager->getLastPage()) . '>; rel="last"';
}
$this->setHeader('Link', $links);
return $this;
}
/**
* Sets the Content Type header for this response with the mime type
* and, optionally, the charset.
*
* @return $this
*/
public function setContentType(string $mime, string $charset = 'UTF-8')
{
// add charset attribute if not already there and provided as parm
if ((strpos($mime, 'charset=') < 1) && ($charset !== '')) {
$mime .= '; charset=' . $charset;
}
$this->removeHeader('Content-Type'); // replace existing content type
$this->setHeader('Content-Type', $mime);
return $this;
}
/**
* Converts the $body into JSON and sets the Content Type header.
*
* @param array|object|string $body
*
* @return $this
*/
public function setJSON($body, bool $unencoded = false)
{
$this->body = $this->formatBody($body, 'json' . ($unencoded ? '-unencoded' : ''));
return $this;
}
/**
* Returns the current body, converted to JSON is it isn't already.
*
* @return string|null
*
* @throws InvalidArgumentException If the body property is not array.
*/
public function getJSON()
{
$body = $this->body;
if ($this->bodyFormat !== 'json') {
$body = service('format')->getFormatter('application/json')->format($body);
}
return $body ?: null;
}
/**
* Converts $body into XML, and sets the correct Content-Type.
*
* @param array|string $body
*
* @return $this
*/
public function setXML($body)
{
$this->body = $this->formatBody($body, 'xml');
return $this;
}
/**
* Retrieves the current body into XML and returns it.
*
* @return bool|string|null
*
* @throws InvalidArgumentException If the body property is not array.
*/
public function getXML()
{
$body = $this->body;
if ($this->bodyFormat !== 'xml') {
$body = service('format')->getFormatter('application/xml')->format($body);
}
return $body;
}
/**
* Handles conversion of the data into the appropriate format,
* and sets the correct Content-Type header for our response.
*
* @param array|object|string $body
* @param string $format Valid: json, xml
*
* @return false|string
*
* @throws InvalidArgumentException If the body property is not string or array.
*/
protected function formatBody($body, string $format)
{
$this->bodyFormat = ($format === 'json-unencoded' ? 'json' : $format);
$mime = "application/{$this->bodyFormat}";
$this->setContentType($mime);
// Nothing much to do for a string...
if (! is_string($body) || $format === 'json-unencoded') {
$body = service('format')->getFormatter($mime)->format($body);
}
return $body;
}
// --------------------------------------------------------------------
// Cache Control Methods
//
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
// --------------------------------------------------------------------
/**
* Sets the appropriate headers to ensure this response
* is not cached by the browsers.
*
* @return $this
*
* @todo Recommend researching these directives, might need: 'private', 'no-transform', 'no-store', 'must-revalidate'
*
* @see DownloadResponse::noCache()
*/
public function noCache()
{
$this->removeHeader('Cache-Control');
$this->setHeader('Cache-Control', ['no-store', 'max-age=0', 'no-cache']);
return $this;
}
/**
* A shortcut method that allows the developer to set all of the
* cache-control headers in one method call.
*
* The options array is used to provide the cache-control directives
* for the header. It might look something like:
*
* $options = [
* 'max-age' => 300,
* 's-maxage' => 900
* 'etag' => 'abcde',
* ];
*
* Typical options are:
* - etag
* - last-modified
* - max-age
* - s-maxage
* - private
* - public
* - must-revalidate
* - proxy-revalidate
* - no-transform
*
* @return $this
*/
public function setCache(array $options = [])
{
if ($options === []) {
return $this;
}
$this->removeHeader('Cache-Control');
$this->removeHeader('ETag');
// ETag
if (isset($options['etag'])) {
$this->setHeader('ETag', $options['etag']);
unset($options['etag']);
}
// Last Modified
if (isset($options['last-modified'])) {
$this->setLastModified($options['last-modified']);
unset($options['last-modified']);
}
$this->setHeader('Cache-Control', $options);
return $this;
}
/**
* Sets the Last-Modified date header.
*
* $date can be either a string representation of the date or,
* preferably, an instance of DateTime.
*
* @param DateTime|string $date
*
* @return $this
*/
public function setLastModified($date)
{
if ($date instanceof DateTime) {
$date->setTimezone(new DateTimeZone('UTC'));
$this->setHeader('Last-Modified', $date->format('D, d M Y H:i:s') . ' GMT');
} elseif (is_string($date)) {
$this->setHeader('Last-Modified', $date);
}
return $this;
}
// --------------------------------------------------------------------
// Output Methods
// --------------------------------------------------------------------
/**
* Sends the output to the browser.
*
* @return $this
*/
public function send()
{
// If we're enforcing a Content Security Policy,
// we need to give it a chance to build out it's headers.
if ($this->CSP->enabled()) {
$this->CSP->finalize($this);
} else {
$this->body = str_replace(['{csp-style-nonce}', '{csp-script-nonce}'], '', $this->body ?? '');
}
$this->sendHeaders();
$this->sendCookies();
$this->sendBody();
return $this;
}
/**
* Sends the headers of this HTTP response to the browser.
*
* @return $this
*/
public function sendHeaders()
{
// Have the headers already been sent?
if ($this->pretend || headers_sent()) {
return $this;
}
// Per spec, MUST be sent with each request, if possible.
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
if (! isset($this->headers['Date']) && PHP_SAPI !== 'cli-server') {
$this->setDate(DateTime::createFromFormat('U', (string) Time::now()->getTimestamp()));
}
// HTTP Status
header(sprintf('HTTP/%s %s %s', $this->getProtocolVersion(), $this->getStatusCode(), $this->getReasonPhrase()), true, $this->getStatusCode());
// Send all of our headers
foreach ($this->headers() as $name => $value) {
if ($value instanceof Header) {
header(
$name . ': ' . $value->getValueLine(),
true,
$this->getStatusCode(),
);
} else {
$replace = true;
foreach ($value as $header) {
header(
$name . ': ' . $header->getValueLine(),
$replace,
$this->getStatusCode(),
);
$replace = false;
}
}
}
return $this;
}
/**
* Sends the Body of the message to the browser.
*
* @return $this
*/
public function sendBody()
{
echo $this->body;
return $this;
}
/**
* Perform a redirect to a new URL, in two flavors: header or location.
*
* @param string $uri The URI to redirect to
* @param int|null $code The type of redirection, defaults to 302
*
* @return $this
*
* @throws HTTPException For invalid status code.
*/
public function redirect(string $uri, string $method = 'auto', ?int $code = null)
{
// IIS environment likely? Use 'refresh' for better compatibility
if (
$method === 'auto'
&& isset($_SERVER['SERVER_SOFTWARE'])
&& str_contains($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS')
) {
$method = 'refresh';
} elseif ($method !== 'refresh' && $code === null) {
// override status code for HTTP/1.1 & higher
if (
isset($_SERVER['SERVER_PROTOCOL'], $_SERVER['REQUEST_METHOD'])
&& $this->getProtocolVersion() >= 1.1
) {
if ($_SERVER['REQUEST_METHOD'] === Method::GET) {
$code = 302;
} elseif (in_array($_SERVER['REQUEST_METHOD'], [Method::POST, Method::PUT, Method::DELETE], true)) {
// reference: https://en.wikipedia.org/wiki/Post/Redirect/Get
$code = 303;
} else {
$code = 307;
}
}
}
if ($code === null) {
$code = 302;
}
match ($method) {
'refresh' => $this->setHeader('Refresh', '0;url=' . $uri),
default => $this->setHeader('Location', $uri),
};
$this->setStatusCode($code);
return $this;
}
/**
* Set a cookie
*
* Accepts an arbitrary number of binds (up to 7) or an associative
* array in the first parameter containing all the values.
*
* @param array|Cookie|string $name Cookie name / array containing binds / Cookie object
* @param string $value Cookie value
* @param int $expire Cookie expiration time in seconds
* @param string $domain Cookie domain (e.g.: '.yourdomain.com')
* @param string $path Cookie path (default: '/')
* @param string $prefix Cookie name prefix ('': the default prefix)
* @param bool|null $secure Whether to only transfer cookies via SSL
* @param bool|null $httponly Whether only make the cookie accessible via HTTP (no javascript)
* @param string|null $samesite
*
* @return $this
*/
public function setCookie(
$name,
$value = '',
$expire = 0,
$domain = '',
$path = '/',
$prefix = '',
$secure = null,
$httponly = null,
$samesite = null,
) {
if ($name instanceof Cookie) {
$this->cookieStore = $this->cookieStore->put($name);
return $this;
}
$cookieConfig = config(CookieConfig::class);
$secure ??= $cookieConfig->secure;
$httponly ??= $cookieConfig->httponly;
$samesite ??= $cookieConfig->samesite;
if (is_array($name)) {
// always leave 'name' in last place, as the loop will break otherwise, due to ${$item}
foreach (['samesite', 'value', 'expire', 'domain', 'path', 'prefix', 'secure', 'httponly', 'name'] as $item) {
if (isset($name[$item])) {
${$item} = $name[$item];
}
}
}
if (is_numeric($expire)) {
$expire = $expire > 0 ? Time::now()->getTimestamp() + $expire : 0;
}
$cookie = new Cookie($name, $value, [
'expires' => $expire ?: 0,
'domain' => $domain,
'path' => $path,
'prefix' => $prefix,
'secure' => $secure,
'httponly' => $httponly,
'samesite' => $samesite ?? '',
]);
$this->cookieStore = $this->cookieStore->put($cookie);
return $this;
}
/**
* Returns the `CookieStore` instance.
*
* @return CookieStore
*/
public function getCookieStore()
{
return $this->cookieStore;
}
/**
* Checks to see if the Response has a specified cookie or not.
*/
public function hasCookie(string $name, ?string $value = null, string $prefix = ''): bool
{
$prefix = $prefix !== '' ? $prefix : Cookie::setDefaults()['prefix']; // to retain BC
return $this->cookieStore->has($name, $prefix, $value);
}
/**
* Returns the cookie
*
* @param string $prefix Cookie prefix.
* '': the default prefix
*
* @return array<string, Cookie>|Cookie|null
*/
public function getCookie(?string $name = null, string $prefix = '')
{
if ((string) $name === '') {
return $this->cookieStore->display();
}
try {
$prefix = $prefix !== '' ? $prefix : Cookie::setDefaults()['prefix']; // to retain BC
return $this->cookieStore->get($name, $prefix);
} catch (CookieException $e) {
log_message('error', (string) $e);
return null;
}
}
/**
* Sets a cookie to be deleted when the response is sent.
*
* @return $this
*/
public function deleteCookie(string $name = '', string $domain = '', string $path = '/', string $prefix = '')
{
if ($name === '') {
return $this;
}
$prefix = $prefix !== '' ? $prefix : Cookie::setDefaults()['prefix']; // to retain BC
$prefixed = $prefix . $name;
$store = $this->cookieStore;
$found = false;
/** @var Cookie $cookie */
foreach ($store as $cookie) {
if ($cookie->getPrefixedName() === $prefixed) {
if ($domain !== $cookie->getDomain()) {
continue;
}
if ($path !== $cookie->getPath()) {
continue;
}
$cookie = $cookie->withValue('')->withExpired();
$found = true;
$this->cookieStore = $store->put($cookie);
break;
}
}
if (! $found) {
$this->setCookie($name, '', 0, $domain, $path, $prefix);
}
return $this;
}
/**
* Returns all cookies currently set.
*
* @return array<string, Cookie>
*/
public function getCookies()
{
return $this->cookieStore->display();
}
/**
* Actually sets the cookies.
*
* @return void
*/
protected function sendCookies()
{
if ($this->pretend) {
return;
}
$this->dispatchCookies();
}
private function dispatchCookies(): void
{
/** @var IncomingRequest $request */
$request = service('request');
foreach ($this->cookieStore->display() as $cookie) {
if ($cookie->isSecure() && ! $request->isSecure()) {
throw SecurityException::forInsecureCookie();
}
$name = $cookie->getPrefixedName();
$value = $cookie->getValue();
$options = $cookie->getOptions();
if ($cookie->isRaw()) {
$this->doSetRawCookie($name, $value, $options);
} else {
$this->doSetCookie($name, $value, $options);
}
}
$this->cookieStore->clear();
}
/**
* Extracted call to `setrawcookie()` in order to run unit tests on it.
*
* @codeCoverageIgnore
*/
private function doSetRawCookie(string $name, string $value, array $options): void
{
setrawcookie($name, $value, $options);
}
/**
* Extracted call to `setcookie()` in order to run unit tests on it.
*
* @codeCoverageIgnore
*/
private function doSetCookie(string $name, string $value, array $options): void
{
setcookie($name, $value, $options);
}
/**
* Force a download.
*
* Generates the headers that force a download to happen. And
* sends the file to the browser.
*
* @param string $filename The name you want the downloaded file to be named
* or the path to the file to send
* @param string|null $data The data to be downloaded. Set null if the $filename is the file path
* @param bool $setMime Whether to try and send the actual MIME type
*
* @return DownloadResponse|null
*/
public function download(string $filename = '', $data = '', bool $setMime = false)
{
if ($filename === '' || $data === '') {
return null;
}
$filepath = '';
if ($data === null) {
$filepath = $filename;
$filename = explode('/', str_replace(DIRECTORY_SEPARATOR, '/', $filename));
$filename = end($filename);
}
$response = new DownloadResponse($filename, $setMime);
if ($filepath !== '') {
$response->setFilePath($filepath);
} elseif ($data !== null) {
$response->setBinary($data);
}
return $response;
}
public function getCSP(): ContentSecurityPolicy
{
return $this->CSP;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/OutgoingRequestInterface.php | system/HTTP/OutgoingRequestInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP;
use CodeIgniter\Exceptions\InvalidArgumentException;
/**
* Representation of an outgoing, client-side request.
*
* Corresponds to Psr7\RequestInterface.
*/
interface OutgoingRequestInterface extends MessageInterface
{
/**
* Retrieves the HTTP method of the request.
*
* @return string Returns the request method.
*/
public function getMethod(): string;
/**
* Return an instance with the provided HTTP method.
*
* While HTTP method names are typically all uppercase characters, HTTP
* method names are case-sensitive and thus implementations SHOULD NOT
* modify the given string.
*
* This method MUST be implemented in such a way as to retain the
* immutability of the message, and MUST return an instance that has the
* changed request method.
*
* @param string $method Case-sensitive method.
*
* @return static
*
* @throws InvalidArgumentException for invalid HTTP methods.
*/
public function withMethod($method);
/**
* Retrieves the URI instance.
*
* @see http://tools.ietf.org/html/rfc3986#section-4.3
*
* @return URI
*/
public function getUri();
/**
* Returns an instance with the provided URI.
*
* This method MUST update the Host header of the returned request by
* default if the URI contains a host component. If the URI does not
* contain a host component, any pre-existing Host header MUST be carried
* over to the returned request.
*
* You can opt-in to preserving the original state of the Host header by
* setting `$preserveHost` to `true`. When `$preserveHost` is set to
* `true`, this method interacts with the Host header in the following ways:
*
* - If the Host header is missing or empty, and the new URI contains
* a host component, this method MUST update the Host header in the returned
* request.
* - If the Host header is missing or empty, and the new URI does not contain a
* host component, this method MUST NOT update the Host header in the returned
* request.
* - If a Host header is present and non-empty, this method MUST NOT update
* the Host header in the returned request.
*
* This method MUST be implemented in such a way as to retain the
* immutability of the message, and MUST return an instance that has the
* new UriInterface instance.
*
* @see http://tools.ietf.org/html/rfc3986#section-4.3
*
* @param URI $uri New request URI to use.
* @param bool $preserveHost Preserve the original state of the Host header.
*
* @return static
*/
public function withUri(URI $uri, $preserveHost = false);
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/UserAgent.php | system/HTTP/UserAgent.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP;
use Config\UserAgents;
use Stringable;
/**
* Abstraction for an HTTP user agent
*
* @see \CodeIgniter\HTTP\UserAgentTest
*/
class UserAgent implements Stringable
{
/**
* Current user-agent
*
* @var string
*/
protected $agent = '';
/**
* Flag for if the user-agent belongs to a browser
*
* @var bool
*/
protected $isBrowser = false;
/**
* Flag for if the user-agent is a robot
*
* @var bool
*/
protected $isRobot = false;
/**
* Flag for if the user-agent is a mobile browser
*
* @var bool
*/
protected $isMobile = false;
/**
* Holds the config file contents.
*
* @var UserAgents
*/
protected $config;
/**
* Current user-agent platform
*
* @var string
*/
protected $platform = '';
/**
* Current user-agent browser
*
* @var string
*/
protected $browser = '';
/**
* Current user-agent version
*
* @var string
*/
protected $version = '';
/**
* Current user-agent mobile name
*
* @var string
*/
protected $mobile = '';
/**
* Current user-agent robot name
*
* @var string
*/
protected $robot = '';
/**
* HTTP Referer
*
* @var bool|string|null
*/
protected $referrer;
/**
* Constructor
*
* Sets the User Agent and runs the compilation routine
*/
public function __construct(?UserAgents $config = null)
{
$this->config = $config ?? config(UserAgents::class);
if (isset($_SERVER['HTTP_USER_AGENT'])) {
$this->agent = trim($_SERVER['HTTP_USER_AGENT']);
$this->compileData();
}
}
/**
* Is Browser
*/
public function isBrowser(?string $key = null): bool
{
if (! $this->isBrowser) {
return false;
}
// No need to be specific, it's a browser
if ((string) $key === '') {
return true;
}
// Check for a specific browser
return isset($this->config->browsers[$key]) && $this->browser === $this->config->browsers[$key];
}
/**
* Is Robot
*/
public function isRobot(?string $key = null): bool
{
if (! $this->isRobot) {
return false;
}
// No need to be specific, it's a robot
if ((string) $key === '') {
return true;
}
// Check for a specific robot
return isset($this->config->robots[$key]) && $this->robot === $this->config->robots[$key];
}
/**
* Is Mobile
*/
public function isMobile(?string $key = null): bool
{
if (! $this->isMobile) {
return false;
}
// No need to be specific, it's a mobile
if ((string) $key === '') {
return true;
}
// Check for a specific robot
return isset($this->config->mobiles[$key]) && $this->mobile === $this->config->mobiles[$key];
}
/**
* Is this a referral from another site?
*/
public function isReferral(): bool
{
if (! isset($this->referrer)) {
if (empty($_SERVER['HTTP_REFERER'])) {
$this->referrer = false;
} else {
$refererHost = @parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
$ownHost = parse_url(\base_url(), PHP_URL_HOST);
$this->referrer = ($refererHost && $refererHost !== $ownHost);
}
}
return $this->referrer;
}
/**
* Agent String
*/
public function getAgentString(): string
{
return $this->agent;
}
/**
* Get Platform
*/
public function getPlatform(): string
{
return $this->platform;
}
/**
* Get Browser Name
*/
public function getBrowser(): string
{
return $this->browser;
}
/**
* Get the Browser Version
*/
public function getVersion(): string
{
return $this->version;
}
/**
* Get The Robot Name
*/
public function getRobot(): string
{
return $this->robot;
}
/**
* Get the Mobile Device
*/
public function getMobile(): string
{
return $this->mobile;
}
/**
* Get the referrer
*/
public function getReferrer(): string
{
return empty($_SERVER['HTTP_REFERER']) ? '' : trim($_SERVER['HTTP_REFERER']);
}
/**
* Parse a custom user-agent string
*
* @return void
*/
public function parse(string $string)
{
// Reset values
$this->isBrowser = false;
$this->isRobot = false;
$this->isMobile = false;
$this->browser = '';
$this->version = '';
$this->mobile = '';
$this->robot = '';
// Set the new user-agent string and parse it, unless empty
$this->agent = $string;
if ($string !== '') {
$this->compileData();
}
}
/**
* Compile the User Agent Data
*
* @return void
*/
protected function compileData()
{
$this->setPlatform();
foreach (['setRobot', 'setBrowser', 'setMobile'] as $function) {
if ($this->{$function}()) {
break;
}
}
}
/**
* Set the Platform
*/
protected function setPlatform(): bool
{
if (is_array($this->config->platforms) && $this->config->platforms !== []) {
foreach ($this->config->platforms as $key => $val) {
if (preg_match('|' . preg_quote($key, '|') . '|i', $this->agent)) {
$this->platform = $val;
return true;
}
}
}
$this->platform = 'Unknown Platform';
return false;
}
/**
* Set the Browser
*/
protected function setBrowser(): bool
{
if (is_array($this->config->browsers) && $this->config->browsers !== []) {
foreach ($this->config->browsers as $key => $val) {
if (preg_match('|' . $key . '.*?([0-9\.]+)|i', $this->agent, $match)) {
$this->isBrowser = true;
$this->version = $match[1];
$this->browser = $val;
$this->setMobile();
return true;
}
}
}
return false;
}
/**
* Set the Robot
*/
protected function setRobot(): bool
{
if (is_array($this->config->robots) && $this->config->robots !== []) {
foreach ($this->config->robots as $key => $val) {
if (preg_match('|' . preg_quote($key, '|') . '|i', $this->agent)) {
$this->isRobot = true;
$this->robot = $val;
$this->setMobile();
return true;
}
}
}
return false;
}
/**
* Set the Mobile Device
*/
protected function setMobile(): bool
{
if (is_array($this->config->mobiles) && $this->config->mobiles !== []) {
foreach ($this->config->mobiles as $key => $val) {
if (false !== (stripos($this->agent, $key))) {
$this->isMobile = true;
$this->mobile = $val;
return true;
}
}
}
return false;
}
/**
* Outputs the original Agent String when cast as a string.
*/
public function __toString(): string
{
return $this->getAgentString();
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/Negotiate.php | system/HTTP/Negotiate.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP;
use CodeIgniter\HTTP\Exceptions\HTTPException;
use Config\Feature;
/**
* Class Negotiate
*
* Provides methods to negotiate with the HTTP headers to determine the best
* type match between what the application supports and what the requesting
* server wants.
*
* @see http://tools.ietf.org/html/rfc7231#section-5.3
* @see \CodeIgniter\HTTP\NegotiateTest
*/
class Negotiate
{
/**
* Request
*
* @var IncomingRequest
*/
protected $request;
/**
* Constructor
*/
public function __construct(?RequestInterface $request = null)
{
if ($request instanceof RequestInterface) {
assert($request instanceof IncomingRequest);
$this->request = $request;
}
}
/**
* Stores the request instance to grab the headers from.
*
* @return $this
*/
public function setRequest(RequestInterface $request)
{
assert($request instanceof IncomingRequest);
$this->request = $request;
return $this;
}
/**
* Determines the best content-type to use based on the $supported
* types the application says it supports, and the types requested
* by the client.
*
* If no match is found, the first, highest-ranking client requested
* type is returned.
*
* @param bool $strictMatch If TRUE, will return an empty string when no match found.
* If FALSE, will return the first supported element.
*/
public function media(array $supported, bool $strictMatch = false): string
{
return $this->getBestMatch($supported, $this->request->getHeaderLine('accept'), true, $strictMatch);
}
/**
* Determines the best charset to use based on the $supported
* types the application says it supports, and the types requested
* by the client.
*
* If no match is found, the first, highest-ranking client requested
* type is returned.
*/
public function charset(array $supported): string
{
$match = $this->getBestMatch(
$supported,
$this->request->getHeaderLine('accept-charset'),
false,
true,
);
// If no charset is shown as a match, ignore the directive
// as allowed by the RFC, and tell it a default value.
if ($match === '') {
return 'utf-8';
}
return $match;
}
/**
* Determines the best encoding type to use based on the $supported
* types the application says it supports, and the types requested
* by the client.
*
* If no match is found, the first, highest-ranking client requested
* type is returned.
*/
public function encoding(array $supported = []): string
{
$supported[] = 'identity';
return $this->getBestMatch($supported, $this->request->getHeaderLine('accept-encoding'));
}
/**
* Determines the best language to use based on the $supported
* types the application says it supports, and the types requested
* by the client.
*
* If strict locale negotiation is disabled and no match is found, the first, highest-ranking client requested
* type is returned.
*/
public function language(array $supported): string
{
if (config(Feature::class)->strictLocaleNegotiation) {
return $this->getBestLocaleMatch($supported, $this->request->getHeaderLine('accept-language'));
}
return $this->getBestMatch($supported, $this->request->getHeaderLine('accept-language'), false, false, true);
}
// --------------------------------------------------------------------
// Utility Methods
// --------------------------------------------------------------------
/**
* Does the grunt work of comparing any of the app-supported values
* against a given Accept* header string.
*
* Portions of this code base on Aura.Accept library.
*
* @param array $supported App-supported values
* @param string $header header string
* @param bool $enforceTypes If TRUE, will compare media types and sub-types.
* @param bool $strictMatch If TRUE, will return empty string on no match.
* If FALSE, will return the first supported element.
* @param bool $matchLocales If TRUE, will match locale sub-types to a broad type (fr-FR = fr)
*
* @return string Best match
*/
protected function getBestMatch(
array $supported,
?string $header = null,
bool $enforceTypes = false,
bool $strictMatch = false,
bool $matchLocales = false,
): string {
if ($supported === []) {
throw HTTPException::forEmptySupportedNegotiations();
}
if ($header === null || $header === '') {
return $strictMatch ? '' : $supported[0];
}
$acceptable = $this->parseHeader($header);
foreach ($acceptable as $accept) {
// if acceptable quality is zero, skip it.
if ($accept['q'] === 0.0) {
continue;
}
// if acceptable value is "anything", return the first available
if ($accept['value'] === '*' || $accept['value'] === '*/*') {
return $supported[0];
}
// If an acceptable value is supported, return it
foreach ($supported as $available) {
if ($this->match($accept, $available, $enforceTypes, $matchLocales)) {
return $available;
}
}
}
// No matches? Return the first supported element.
return $strictMatch ? '' : $supported[0];
}
/**
* Try to find the best matching locale. It supports strict locale comparison.
*
* If Config\App::$supportedLocales have "en-US" and "en-GB" locales, they can be recognized
* as two different locales. This method checks first for the strict match, then fallback
* to the most general locale (in this case "en") ISO 639-1 and finally to the locale variant
* "en-*" (ISO 639-1 plus "wildcard" for ISO 3166-1 alpha-2).
*
* If nothing from above is matched, then it returns the first option from the $supportedLocales array.
*
* @param list<string> $supportedLocales App-supported values
* @param ?string $header Compatible 'Accept-Language' header string
*/
protected function getBestLocaleMatch(array $supportedLocales, ?string $header): string
{
if ($supportedLocales === []) {
throw HTTPException::forEmptySupportedNegotiations();
}
if ($header === null || $header === '') {
return $supportedLocales[0];
}
$acceptable = $this->parseHeader($header);
$fallbackLocales = [];
foreach ($acceptable as $accept) {
// if acceptable quality is zero, skip it.
if ($accept['q'] === 0.0) {
continue;
}
// if acceptable value is "anything", return the first available
if ($accept['value'] === '*') {
return $supportedLocales[0];
}
// look for exact match
if (in_array($accept['value'], $supportedLocales, true)) {
return $accept['value'];
}
// set a fallback locale
$fallbackLocales[] = strtok($accept['value'], '-');
}
foreach ($fallbackLocales as $fallbackLocale) {
// look for exact match
if (in_array($fallbackLocale, $supportedLocales, true)) {
return $fallbackLocale;
}
// look for regional locale match
foreach ($supportedLocales as $locale) {
if (str_starts_with($locale, $fallbackLocale . '-')) {
return $locale;
}
}
}
return $supportedLocales[0];
}
/**
* Parses an Accept* header into it's multiple values.
*
* This is based on code from Aura.Accept library.
*/
public function parseHeader(string $header): array
{
$results = [];
$acceptable = explode(',', $header);
foreach ($acceptable as $value) {
$pairs = explode(';', $value);
$value = $pairs[0];
unset($pairs[0]);
$parameters = [];
foreach ($pairs as $pair) {
if (preg_match(
'/^(?P<name>.+?)=(?P<quoted>"|\')?(?P<value>.*?)(?:\k<quoted>)?$/',
$pair,
$param,
)) {
$parameters[trim($param['name'])] = trim($param['value']);
}
}
$quality = 1.0;
if (array_key_exists('q', $parameters)) {
$quality = $parameters['q'];
unset($parameters['q']);
}
$results[] = [
'value' => trim($value),
'q' => (float) $quality,
'params' => $parameters,
];
}
// Sort to get the highest results first
usort($results, static function ($a, $b): int {
if ($a['q'] === $b['q']) {
$aAst = substr_count($a['value'], '*');
$bAst = substr_count($b['value'], '*');
// '*/*' has lower precedence than 'text/*',
// and 'text/*' has lower priority than 'text/plain'
//
// This seems backwards, but needs to be that way
// due to the way PHP7 handles ordering or array
// elements created by reference.
if ($aAst > $bAst) {
return 1;
}
// If the counts are the same, but one element
// has more params than another, it has higher precedence.
//
// This seems backwards, but needs to be that way
// due to the way PHP7 handles ordering or array
// elements created by reference.
if ($aAst === $bAst) {
return count($b['params']) - count($a['params']);
}
return 0;
}
// Still here? Higher q values have precedence.
return ($a['q'] > $b['q']) ? -1 : 1;
});
return $results;
}
/**
* Match-maker
*
* @param bool $matchLocales
*/
protected function match(array $acceptable, string $supported, bool $enforceTypes = false, $matchLocales = false): bool
{
$supported = $this->parseHeader($supported);
if (count($supported) === 1) {
$supported = $supported[0];
}
// Is it an exact match?
if ($acceptable['value'] === $supported['value']) {
return $this->matchParameters($acceptable, $supported);
}
// Do we need to compare types/sub-types? Only used
// by negotiateMedia().
if ($enforceTypes) {
return $this->matchTypes($acceptable, $supported);
}
// Do we need to match locales against broader locales?
if ($matchLocales) {
return $this->matchLocales($acceptable, $supported);
}
return false;
}
/**
* Checks two Accept values with matching 'values' to see if their
* 'params' are the same.
*/
protected function matchParameters(array $acceptable, array $supported): bool
{
if (count($acceptable['params']) !== count($supported['params'])) {
return false;
}
foreach ($supported['params'] as $label => $value) {
if (! isset($acceptable['params'][$label])
|| $acceptable['params'][$label] !== $value
) {
return false;
}
}
return true;
}
/**
* Compares the types/subtypes of an acceptable Media type and
* the supported string.
*/
public function matchTypes(array $acceptable, array $supported): bool
{
// PHPDocumentor v2 cannot parse yet the shorter list syntax,
// causing no API generation for the file.
[$aType, $aSubType] = explode('/', $acceptable['value']);
[$sType, $sSubType] = explode('/', $supported['value']);
// If the types don't match, we're done.
if ($aType !== $sType) {
return false;
}
// If there's an asterisk, we're cool
if ($aSubType === '*') {
return true;
}
// Otherwise, subtypes must match also.
return $aSubType === $sSubType;
}
/**
* Will match locales against their broader pairs, so that fr-FR would
* match a supported localed of fr
*/
public function matchLocales(array $acceptable, array $supported): bool
{
$aBroad = mb_strpos($acceptable['value'], '-') > 0
? mb_substr($acceptable['value'], 0, mb_strpos($acceptable['value'], '-'))
: $acceptable['value'];
$sBroad = mb_strpos($supported['value'], '-') > 0
? mb_substr($supported['value'], 0, mb_strpos($supported['value'], '-'))
: $supported['value'];
return strtolower($aBroad) === strtolower($sBroad);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/Header.php | system/HTTP/Header.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP;
use InvalidArgumentException;
use Stringable;
/**
* Class Header
*
* Represents a single HTTP header.
*
* @see \CodeIgniter\HTTP\HeaderTest
*/
class Header implements Stringable
{
/**
* The name of the header.
*
* @var string
*/
protected $name;
/**
* The value of the header. May have more than one
* value. If so, will be an array of strings.
* E.g.,
* [
* 'foo',
* [
* 'bar' => 'fizz',
* ],
* 'baz' => 'buzz',
* ]
*
* @var array<int|string, array<string, string>|string>|string
*/
protected $value;
/**
* Header constructor. name is mandatory, if a value is provided, it will be set.
*
* @param array<int|string, array<string, string>|string>|string|null $value
*/
public function __construct(string $name, $value = null)
{
$this->setName($name);
$this->setValue($value);
}
/**
* Returns the name of the header, in the same case it was set.
*/
public function getName(): string
{
return $this->name;
}
/**
* Gets the raw value of the header. This may return either a string
* or an array, depending on whether the header has multiple values or not.
*
* @return array<int|string, array<string, string>|string>|string
*/
public function getValue()
{
return $this->value;
}
/**
* Sets the name of the header, overwriting any previous value.
*
* @return $this
*
* @throws InvalidArgumentException
*/
public function setName(string $name)
{
$this->validateName($name);
$this->name = $name;
return $this;
}
/**
* Sets the value of the header, overwriting any previous value(s).
*
* @param array<int|string, array<string, string>|string>|string|null $value
*
* @return $this
*
* @throws InvalidArgumentException
*/
public function setValue($value = null)
{
$value = is_array($value) ? $value : (string) $value;
$this->validateValue($value);
$this->value = $value;
return $this;
}
/**
* Appends a value to the list of values for this header. If the
* header is a single value string, it will be converted to an array.
*
* @param array<string, string>|string|null $value
*
* @return $this
*
* @throws InvalidArgumentException
*/
public function appendValue($value = null)
{
if ($value === null) {
return $this;
}
$this->validateValue($value);
if (! is_array($this->value)) {
$this->value = [$this->value];
}
if (! in_array($value, $this->value, true)) {
$this->value[] = is_array($value) ? $value : (string) $value;
}
return $this;
}
/**
* Prepends a value to the list of values for this header. If the
* header is a single value string, it will be converted to an array.
*
* @param array<string, string>|string|null $value
*
* @return $this
*
* @throws InvalidArgumentException
*/
public function prependValue($value = null)
{
if ($value === null) {
return $this;
}
$this->validateValue($value);
if (! is_array($this->value)) {
$this->value = [$this->value];
}
array_unshift($this->value, $value);
return $this;
}
/**
* Retrieves a comma-separated string of the values for a single header.
*
* NOTE: Not all header values may be appropriately represented using
* comma concatenation. For such headers, use getHeader() instead
* and supply your own delimiter when concatenating.
*
* @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
*/
public function getValueLine(): string
{
if (is_string($this->value)) {
return $this->value;
}
if (! is_array($this->value)) {
return '';
}
$options = [];
foreach ($this->value as $key => $value) {
if (is_string($key) && ! is_array($value)) {
$options[] = $key . '=' . $value;
} elseif (is_array($value)) {
$key = key($value);
$options[] = $key . '=' . $value[$key];
} elseif (is_numeric($key)) {
$options[] = $value;
}
}
return implode(', ', $options);
}
/**
* Returns a representation of the entire header string, including
* the header name and all values converted to the proper format.
*/
public function __toString(): string
{
return $this->name . ': ' . $this->getValueLine();
}
/**
* Validate header name.
*
* Regex is based on code from a guzzlehttp/psr7 library.
*
* @see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2
*
* @throws InvalidArgumentException
*/
private function validateName(string $name): void
{
if (preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/D', $name) !== 1) {
throw new InvalidArgumentException('The header name is not valid as per RFC 7230.');
}
}
/**
* Validate header value.
*
* Regex is based on code from a guzzlehttp/psr7 library.
*
* @see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2
*
* @param array<int|string, array<string, string>|string>|int|string $value
*
* @throws InvalidArgumentException
*/
private function validateValue(array|int|string $value): void
{
if (is_int($value)) {
return;
}
if (is_array($value)) {
foreach ($value as $key => $val) {
$this->validateValue($key);
$this->validateValue($val);
}
return;
}
// The regular expression excludes obs-fold per RFC 7230#3.2.4, as sending folded lines
// is deprecated and rare. This obscure HTTP/1.1 feature is unlikely to impact legitimate
// use cases. Libraries like Guzzle and AMPHP follow the same principle.
if (preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*$/D', $value) !== 1) {
throw new InvalidArgumentException('The header value is not valid as per RFC 7230.');
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/Message.php | system/HTTP/Message.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP;
use CodeIgniter\Exceptions\InvalidArgumentException;
/**
* An HTTP message
*
* @see \CodeIgniter\HTTP\MessageTest
*/
class Message implements MessageInterface
{
use MessageTrait;
/**
* Protocol version
*
* @var string
*/
protected $protocolVersion;
/**
* List of valid protocol versions
*
* @var array
*/
protected $validProtocolVersions = [
'1.0',
'1.1',
'2.0',
'3.0',
];
/**
* Message body
*
* @var string|null
*/
protected $body;
/**
* Returns the Message's body.
*
* @return string|null
*/
public function getBody()
{
return $this->body;
}
/**
* Returns an array containing all headers.
*
* @return array<string, Header> An array of the request headers
*
* @deprecated Use Message::headers() to make room for PSR-7
*
* @TODO Incompatible return value with PSR-7
*
* @codeCoverageIgnore
*/
public function getHeaders(): array
{
return $this->headers();
}
/**
* Returns a single header object. If multiple headers with the same
* name exist, then will return an array of header objects.
*
* @return array|Header|null
*
* @deprecated Use Message::header() to make room for PSR-7
*
* @TODO Incompatible return value with PSR-7
*
* @codeCoverageIgnore
*/
public function getHeader(string $name)
{
return $this->header($name);
}
/**
* Determines whether a header exists.
*/
public function hasHeader(string $name): bool
{
$origName = $this->getHeaderName($name);
return isset($this->headers[$origName]);
}
/**
* Retrieves a comma-separated string of the values for a single header.
*
* This method returns all of the header values of the given
* case-insensitive header name as a string concatenated together using
* a comma.
*
* NOTE: Not all header values may be appropriately represented using
* comma concatenation. For such headers, use getHeader() instead
* and supply your own delimiter when concatenating.
*/
public function getHeaderLine(string $name): string
{
if ($this->hasMultipleHeaders($name)) {
throw new InvalidArgumentException(
'The header "' . $name . '" already has multiple headers.'
. ' You cannot use getHeaderLine().',
);
}
$origName = $this->getHeaderName($name);
if (! array_key_exists($origName, $this->headers)) {
return '';
}
return $this->headers[$origName]->getValueLine();
}
/**
* Returns the HTTP Protocol Version.
*/
public function getProtocolVersion(): string
{
return $this->protocolVersion ?? '1.1';
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/SiteURI.php | system/HTTP/SiteURI.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP;
use CodeIgniter\Exceptions\BadMethodCallException;
use CodeIgniter\Exceptions\ConfigException;
use CodeIgniter\HTTP\Exceptions\HTTPException;
use Config\App;
/**
* URI for the application site
*
* @see \CodeIgniter\HTTP\SiteURITest
*/
class SiteURI extends URI
{
/**
* The current baseURL.
*/
private readonly URI $baseURL;
/**
* The path part of baseURL.
*
* The baseURL "http://example.com/" → '/'
* The baseURL "http://localhost:8888/ci431/public/" → '/ci431/public/'
*/
private string $basePathWithoutIndexPage;
/**
* The Index File.
*/
private readonly string $indexPage;
/**
* List of URI segments in baseURL and indexPage.
*
* If the URI is "http://localhost:8888/ci431/public/index.php/test?a=b",
* and the baseURL is "http://localhost:8888/ci431/public/", then:
* $baseSegments = [
* 0 => 'ci431',
* 1 => 'public',
* 2 => 'index.php',
* ];
*/
private array $baseSegments;
/**
* List of URI segments after indexPage.
*
* The word "URI Segments" originally means only the URI path part relative
* to the baseURL.
*
* If the URI is "http://localhost:8888/ci431/public/index.php/test?a=b",
* and the baseURL is "http://localhost:8888/ci431/public/", then:
* $segments = [
* 0 => 'test',
* ];
*
* @var array<int, string>
*
* @deprecated This property will be private.
*/
protected $segments;
/**
* URI path relative to baseURL.
*
* If the baseURL contains sub folders, this value will be different from
* the current URI path.
*
* This value never starts with '/'.
*/
private string $routePath;
/**
* @param string $relativePath URI path relative to baseURL. May include
* queries or fragments.
* @param string|null $host Optional current hostname.
* @param 'http'|'https'|null $scheme Optional scheme. 'http' or 'https'.
*/
public function __construct(
App $configApp,
string $relativePath = '',
?string $host = null,
?string $scheme = null,
) {
$this->indexPage = $configApp->indexPage;
$this->baseURL = $this->determineBaseURL($configApp, $host, $scheme);
$this->setBasePath();
// Fix routePath, query, fragment
[$routePath, $query, $fragment] = $this->parseRelativePath($relativePath);
// Fix indexPage and routePath
$indexPageRoutePath = $this->getIndexPageRoutePath($routePath);
// Fix the current URI
$uri = $this->baseURL . $indexPageRoutePath;
// applyParts
$parts = parse_url($uri);
if ($parts === false) {
throw HTTPException::forUnableToParseURI($uri);
}
$parts['query'] = $query;
$parts['fragment'] = $fragment;
$this->applyParts($parts);
$this->setRoutePath($routePath);
}
private function parseRelativePath(string $relativePath): array
{
$parts = parse_url('http://dummy/' . $relativePath);
if ($parts === false) {
throw HTTPException::forUnableToParseURI($relativePath);
}
$routePath = $relativePath === '/' ? '/' : ltrim($parts['path'], '/');
$query = $parts['query'] ?? '';
$fragment = $parts['fragment'] ?? '';
return [$routePath, $query, $fragment];
}
private function determineBaseURL(
App $configApp,
?string $host,
?string $scheme,
): URI {
$baseURL = $this->normalizeBaseURL($configApp);
$uri = new URI($baseURL);
// Update scheme
if ($scheme !== null && $scheme !== '') {
$uri->setScheme($scheme);
} elseif ($configApp->forceGlobalSecureRequests) {
$uri->setScheme('https');
}
// Update host
if ($host !== null) {
$uri->setHost($host);
}
return $uri;
}
private function getIndexPageRoutePath(string $routePath): string
{
// Remove starting slash unless it is `/`.
if ($routePath !== '' && $routePath[0] === '/' && $routePath !== '/') {
$routePath = ltrim($routePath, '/');
}
// Check for an index page
$indexPage = '';
if ($this->indexPage !== '') {
$indexPage = $this->indexPage;
// Check if we need a separator
if ($routePath !== '' && $routePath[0] !== '/' && $routePath[0] !== '?') {
$indexPage .= '/';
}
}
$indexPageRoutePath = $indexPage . $routePath;
if ($indexPageRoutePath === '/') {
$indexPageRoutePath = '';
}
return $indexPageRoutePath;
}
private function normalizeBaseURL(App $configApp): string
{
// It's possible the user forgot a trailing slash on their
// baseURL, so let's help them out.
$baseURL = rtrim($configApp->baseURL, '/ ') . '/';
// Validate baseURL
if (filter_var($baseURL, FILTER_VALIDATE_URL) === false) {
throw new ConfigException(
'Config\App::$baseURL "' . $baseURL . '" is not a valid URL.',
);
}
return $baseURL;
}
/**
* Sets basePathWithoutIndexPage and baseSegments.
*/
private function setBasePath(): void
{
$this->basePathWithoutIndexPage = $this->baseURL->getPath();
$this->baseSegments = $this->convertToSegments($this->basePathWithoutIndexPage);
if ($this->indexPage !== '') {
$this->baseSegments[] = $this->indexPage;
}
}
/**
* @deprecated
*/
public function setBaseURL(string $baseURL): void
{
throw new BadMethodCallException('Cannot use this method.');
}
/**
* @deprecated
*/
public function setURI(?string $uri = null)
{
throw new BadMethodCallException('Cannot use this method.');
}
/**
* Returns the baseURL.
*
* @interal
*/
public function getBaseURL(): string
{
return (string) $this->baseURL;
}
/**
* Returns the URI path relative to baseURL.
*
* @return string The Route path.
*/
public function getRoutePath(): string
{
return $this->routePath;
}
/**
* Formats the URI as a string.
*/
public function __toString(): string
{
return static::createURIString(
$this->getScheme(),
$this->getAuthority(),
$this->getPath(),
$this->getQuery(),
$this->getFragment(),
);
}
/**
* Sets the route path (and segments).
*
* @return $this
*/
public function setPath(string $path)
{
$this->setRoutePath($path);
return $this;
}
/**
* Sets the route path (and segments).
*/
private function setRoutePath(string $routePath): void
{
$routePath = $this->filterPath($routePath);
$indexPageRoutePath = $this->getIndexPageRoutePath($routePath);
$this->path = $this->basePathWithoutIndexPage . $indexPageRoutePath;
$this->routePath = ltrim($routePath, '/');
$this->segments = $this->convertToSegments($this->routePath);
}
/**
* Converts path to segments
*/
private function convertToSegments(string $path): array
{
$tempPath = trim($path, '/');
return ($tempPath === '') ? [] : explode('/', $tempPath);
}
/**
* Sets the path portion of the URI based on segments.
*
* @return $this
*
* @deprecated This method will be private.
*/
public function refreshPath()
{
$allSegments = array_merge($this->baseSegments, $this->segments);
$this->path = '/' . $this->filterPath(implode('/', $allSegments));
if ($this->routePath === '/' && $this->path !== '/') {
$this->path .= '/';
}
$this->routePath = $this->filterPath(implode('/', $this->segments));
return $this;
}
/**
* Saves our parts from a parse_url() call.
*
* @param array{
* host?: string,
* user?: string,
* path?: string,
* query?: string,
* fragment?: string,
* scheme?: string,
* port?: int,
* pass?: string,
* } $parts
*/
protected function applyParts(array $parts): void
{
if (isset($parts['host']) && $parts['host'] !== '') {
$this->host = $parts['host'];
}
if (isset($parts['user']) && $parts['user'] !== '') {
$this->user = $parts['user'];
}
if (isset($parts['path']) && $parts['path'] !== '') {
$this->path = $this->filterPath($parts['path']);
}
if (isset($parts['query']) && $parts['query'] !== '') {
$this->setQuery($parts['query']);
}
if (isset($parts['fragment']) && $parts['fragment'] !== '') {
$this->fragment = $parts['fragment'];
}
if (isset($parts['scheme'])) {
$this->setScheme(rtrim($parts['scheme'], ':/'));
} else {
$this->setScheme('http');
}
if (isset($parts['port'])) {
// Valid port numbers are enforced by earlier parse_url or setPort()
$this->port = $parts['port'];
}
if (isset($parts['pass'])) {
$this->password = $parts['pass'];
}
}
/**
* For base_url() helper.
*
* @param array|string $relativePath URI string or array of URI segments.
* @param string|null $scheme URI scheme. E.g., http, ftp. If empty
* string '' is set, a protocol-relative
* link is returned.
*/
public function baseUrl($relativePath = '', ?string $scheme = null): string
{
$relativePath = $this->stringifyRelativePath($relativePath);
$config = clone config(App::class);
$config->indexPage = '';
$host = $this->getHost();
$uri = new self($config, $relativePath, $host, $scheme);
// Support protocol-relative links
if ($scheme === '') {
return substr((string) $uri, strlen($uri->getScheme()) + 1);
}
return (string) $uri;
}
/**
* @param array|string $relativePath URI string or array of URI segments
*/
private function stringifyRelativePath($relativePath): string
{
if (is_array($relativePath)) {
$relativePath = implode('/', $relativePath);
}
return $relativePath;
}
/**
* For site_url() helper.
*
* @param array|string $relativePath URI string or array of URI segments.
* @param string|null $scheme URI scheme. E.g., http, ftp. If empty
* string '' is set, a protocol-relative
* link is returned.
* @param App|null $config Alternate configuration to use.
*/
public function siteUrl($relativePath = '', ?string $scheme = null, ?App $config = null): string
{
$relativePath = $this->stringifyRelativePath($relativePath);
// Check current host.
$host = $config instanceof App ? null : $this->getHost();
$config ??= config(App::class);
$uri = new self($config, $relativePath, $host, $scheme);
// Support protocol-relative links
if ($scheme === '') {
return substr((string) $uri, strlen($uri->getScheme()) + 1);
}
return (string) $uri;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/OutgoingRequest.php | system/HTTP/OutgoingRequest.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP;
/**
* Representation of an outgoing, client-side request.
*
* @see \CodeIgniter\HTTP\OutgoingRequestTest
*/
class OutgoingRequest extends Message implements OutgoingRequestInterface
{
/**
* Request method.
*
* @var string
*/
protected $method;
/**
* A URI instance.
*
* @var URI|null
*/
protected $uri;
/**
* @param string $method HTTP method
* @param string|null $body
*/
public function __construct(
string $method,
?URI $uri = null,
array $headers = [],
$body = null,
string $version = '1.1',
) {
$this->method = $method;
$this->uri = $uri;
foreach ($headers as $header => $value) {
$this->setHeader($header, $value);
}
$this->body = $body;
$this->protocolVersion = $version;
if (! $this->hasHeader('Host') && $this->uri->getHost() !== '') {
$this->setHeader('Host', $this->getHostFromUri($this->uri));
}
}
private function getHostFromUri(URI $uri): string
{
$host = $uri->getHost();
return $host . ($uri->getPort() > 0 ? ':' . $uri->getPort() : '');
}
/**
* Retrieves the HTTP method of the request.
*
* @return string Returns the request method (always uppercase)
*/
public function getMethod(): string
{
return $this->method;
}
/**
* Sets the request method. Used when spoofing the request.
*
* @return $this
*
* @deprecated Use withMethod() instead for immutability
*/
public function setMethod(string $method)
{
$this->method = $method;
return $this;
}
/**
* Returns an instance with the specified method.
*
* @param string $method
*
* @return static
*/
public function withMethod($method)
{
$request = clone $this;
$request->method = $method;
return $request;
}
/**
* Retrieves the URI instance.
*
* @return URI|null
*/
public function getUri()
{
return $this->uri;
}
/**
* Returns an instance with the provided URI.
*
* @param URI $uri New request URI to use.
* @param bool $preserveHost Preserve the original state of the Host header.
*
* @return static
*/
public function withUri(URI $uri, $preserveHost = false)
{
$request = clone $this;
$request->uri = $uri;
if ($preserveHost) {
if ($this->isHostHeaderMissingOrEmpty() && $uri->getHost() !== '') {
$request->setHeader('Host', $this->getHostFromUri($uri));
return $request;
}
if ($this->isHostHeaderMissingOrEmpty() && $uri->getHost() === '') {
return $request;
}
if (! $this->isHostHeaderMissingOrEmpty()) {
return $request;
}
}
if ($uri->getHost() !== '') {
$request->setHeader('Host', $this->getHostFromUri($uri));
}
return $request;
}
private function isHostHeaderMissingOrEmpty(): bool
{
if (! $this->hasHeader('Host')) {
return true;
}
return $this->header('Host')->getValue() === '';
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/SiteURIFactory.php | system/HTTP/SiteURIFactory.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP;
use CodeIgniter\HTTP\Exceptions\HTTPException;
use CodeIgniter\Superglobals;
use Config\App;
/**
* Creates SiteURI using superglobals.
*
* This class also updates superglobal $_SERVER and $_GET.
*
* @see \CodeIgniter\HTTP\SiteURIFactoryTest
*/
final class SiteURIFactory
{
public function __construct(private readonly App $appConfig, private readonly Superglobals $superglobals)
{
}
/**
* Create the current URI object from superglobals.
*
* This method updates superglobal $_SERVER and $_GET.
*/
public function createFromGlobals(): SiteURI
{
$routePath = $this->detectRoutePath();
return $this->createURIFromRoutePath($routePath);
}
/**
* Create the SiteURI object from URI string.
*
* @internal Used for testing purposes only.
* @testTag
*/
public function createFromString(string $uri): SiteURI
{
// Validate URI
if (filter_var($uri, FILTER_VALIDATE_URL) === false) {
throw HTTPException::forUnableToParseURI($uri);
}
$parts = parse_url($uri);
if ($parts === false) {
throw HTTPException::forUnableToParseURI($uri);
}
$query = $fragment = '';
if (isset($parts['query'])) {
$query = '?' . $parts['query'];
}
if (isset($parts['fragment'])) {
$fragment = '#' . $parts['fragment'];
}
$relativePath = ($parts['path'] ?? '') . $query . $fragment;
$host = $this->getValidHost($parts['host']);
return new SiteURI($this->appConfig, $relativePath, $host, $parts['scheme']);
}
/**
* Detects the current URI path relative to baseURL based on the URIProtocol
* Config setting.
*
* @param string $protocol URIProtocol
*
* @return string The route path
*
* @internal Used for testing purposes only.
* @testTag
*/
public function detectRoutePath(string $protocol = ''): string
{
if ($protocol === '') {
$protocol = $this->appConfig->uriProtocol;
}
$routePath = match ($protocol) {
'REQUEST_URI' => $this->parseRequestURI(),
'QUERY_STRING' => $this->parseQueryString(),
default => $this->superglobals->server($protocol) ?? $this->parseRequestURI(),
};
return ($routePath === '/' || $routePath === '') ? '/' : ltrim($routePath, '/');
}
/**
* Will parse the REQUEST_URI and automatically detect the URI from it,
* fixing the query string if necessary.
*
* This method updates superglobal $_SERVER and $_GET.
*
* @return string The route path (before normalization).
*/
private function parseRequestURI(): string
{
if (
$this->superglobals->server('REQUEST_URI') === null
|| $this->superglobals->server('SCRIPT_NAME') === null
) {
return '';
}
// parse_url() returns false if no host is present, but the path or query
// string contains a colon followed by a number. So we attach a dummy
// host since REQUEST_URI does not include the host. This allows us to
// parse out the query string and path.
$parts = parse_url('http://dummy' . $this->superglobals->server('REQUEST_URI'));
$query = $parts['query'] ?? '';
$path = $parts['path'] ?? '';
// Strip the SCRIPT_NAME path from the URI
if (
$path !== '' && $this->superglobals->server('SCRIPT_NAME') !== ''
&& pathinfo($this->superglobals->server('SCRIPT_NAME'), PATHINFO_EXTENSION) === 'php'
) {
// Compare each segment, dropping them until there is no match
$segments = explode('/', rawurldecode($path));
$keep = explode('/', $path);
foreach (explode('/', $this->superglobals->server('SCRIPT_NAME')) as $i => $segment) {
// If these segments are not the same then we're done
if (! isset($segments[$i]) || $segment !== $segments[$i]) {
break;
}
array_shift($keep);
}
$path = implode('/', $keep);
}
// Cleanup: if indexPage is still visible in the path, remove it
if ($this->appConfig->indexPage !== '' && str_starts_with($path, $this->appConfig->indexPage)) {
$remainingPath = substr($path, strlen($this->appConfig->indexPage));
// Only remove if followed by '/' (route) or nothing (root)
if ($remainingPath === '' || str_starts_with($remainingPath, '/')) {
$path = ltrim($remainingPath, '/');
}
}
// This section ensures that even on servers that require the URI to
// contain the query string (Nginx) a correct URI is found, and also
// fixes the QUERY_STRING Server var and $_GET array.
if (trim($path, '/') === '' && str_starts_with($query, '/')) {
$parts = explode('?', $query, 2);
$path = $parts[0];
$newQuery = $query[1] ?? '';
$this->superglobals->setServer('QUERY_STRING', $newQuery);
} else {
$this->superglobals->setServer('QUERY_STRING', $query);
}
// Update our global GET for values likely to have been changed
parse_str($this->superglobals->server('QUERY_STRING'), $get);
$this->superglobals->setGetArray($get);
return URI::removeDotSegments($path);
}
/**
* Will parse QUERY_STRING and automatically detect the URI from it.
*
* This method updates superglobal $_SERVER and $_GET.
*
* @return string The route path (before normalization).
*/
private function parseQueryString(): string
{
$query = $this->superglobals->server('QUERY_STRING') ?? (string) getenv('QUERY_STRING');
if (trim($query, '/') === '') {
return '/';
}
if (str_starts_with($query, '/')) {
$parts = explode('?', $query, 2);
$path = $parts[0];
$newQuery = $parts[1] ?? '';
$this->superglobals->setServer('QUERY_STRING', $newQuery);
} else {
$path = $query;
}
// Update our global GET for values likely to have been changed
parse_str($this->superglobals->server('QUERY_STRING'), $get);
$this->superglobals->setGetArray($get);
return URI::removeDotSegments($path);
}
/**
* Create current URI object.
*
* @param string $routePath URI path relative to baseURL
*/
private function createURIFromRoutePath(string $routePath): SiteURI
{
$query = $this->superglobals->server('QUERY_STRING') ?? '';
$relativePath = $query !== '' ? $routePath . '?' . $query : $routePath;
return new SiteURI($this->appConfig, $relativePath, $this->getHost());
}
/**
* @return string|null The current hostname. Returns null if no valid host.
*/
private function getHost(): ?string
{
$httpHostPort = $this->superglobals->server('HTTP_HOST') ?? null;
if ($httpHostPort !== null) {
[$httpHost] = explode(':', $httpHostPort, 2);
return $this->getValidHost($httpHost);
}
return null;
}
/**
* @return string|null The valid hostname. Returns null if not valid.
*/
private function getValidHost(string $host): ?string
{
if (in_array($host, $this->appConfig->allowedHostnames, true)) {
return $host;
}
return null;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/Files/UploadedFileInterface.php | system/HTTP/Files/UploadedFileInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP\Files;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\Exceptions\RuntimeException;
/**
* Value object representing a single file uploaded through an
* HTTP request. Used by the IncomingRequest class to
* provide files.
*
* Typically, implementors will extend the SplFileInfo class.
*/
interface UploadedFileInterface
{
/**
* Accepts the file information as would be filled in from the $_FILES array.
*
* @param string $path The temporary location of the uploaded file.
* @param string $originalName The client-provided filename.
* @param string|null $mimeType The type of file as provided by PHP
* @param int|null $size The size of the file, in bytes
* @param int|null $error The error constant of the upload (one of PHP's UPLOADERRXXX constants)
* @param string|null $clientPath The webkit relative path of the uploaded file.
*/
public function __construct(string $path, string $originalName, ?string $mimeType = null, ?int $size = null, ?int $error = null, ?string $clientPath = null);
/**
* Move the uploaded file to a new location.
*
* $targetPath may be an absolute path, or a relative path. If it is a
* relative path, resolution should be the same as used by PHP's rename()
* function.
*
* The original file MUST be removed on completion.
*
* If this method is called more than once, any subsequent calls MUST raise
* an exception.
*
* When used in an SAPI environment where $_FILES is populated, when writing
* files via moveTo(), is_uploaded_file() and move_uploaded_file() SHOULD be
* used to ensure permissions and upload status are verified correctly.
*
* If you wish to move to a stream, use getStream(), as SAPI operations
* cannot guarantee writing to stream destinations.
*
* @see http://php.net/is_uploaded_file
* @see http://php.net/move_uploaded_file
*
* @param string $targetPath Path to which to move the uploaded file.
* @param string|null $name the name to rename the file to.
*
* @return bool
*
* @throws InvalidArgumentException if the $path specified is invalid.
* @throws RuntimeException on the second or subsequent call to the method.
*/
public function move(string $targetPath, ?string $name = null);
/**
* Returns whether the file has been moved or not. If it has,
* the move() method will not work and certain properties, like
* the tempName, will no longer be available.
*/
public function hasMoved(): bool;
/**
* Retrieve the error associated with the uploaded file.
*
* The return value MUST be one of PHP's UPLOAD_ERR_XXX constants.
*
* If the file was uploaded successfully, this method MUST return
* UPLOAD_ERR_OK.
*
* Implementations SHOULD return the value stored in the "error" key of
* the file in the $_FILES array.
*
* @see http://php.net/manual/en/features.file-upload.errors.php
*
* @return int One of PHP's UPLOAD_ERR_XXX constants.
*/
public function getError(): int;
/**
* Retrieve the filename sent by the client.
*
* Do not trust the value returned by this method. A client could send
* a malicious filename with the intention to corrupt or hack your
* application.
*
* Implementations SHOULD return the value stored in the "name" key of
* the file in the $_FILES array.
*
* @return string The filename sent by the client or null if none
* was provided.
*/
public function getName(): string;
/**
* Gets the temporary filename where the file was uploaded to.
*/
public function getTempName(): string;
/**
* (PHP 8.1+)
* Returns the webkit relative path of the uploaded file on directory uploads.
*/
public function getClientPath(): ?string;
/**
* Returns the original file extension, based on the file name that
* was uploaded. This is NOT a trusted source.
* For a trusted version, use guessExtension() instead.
*/
public function getClientExtension(): string;
/**
* Returns the mime type as provided by the client.
* This is NOT a trusted value.
* For a trusted version, use getMimeType() instead.
*/
public function getClientMimeType(): string;
/**
* Returns whether the file was uploaded successfully, based on whether
* it was uploaded via HTTP and has no errors.
*/
public function isValid(): bool;
/**
* Returns the destination path for the move operation where overwriting is not expected.
*
* First, it checks whether the delimiter is present in the filename, if it is, then it checks whether the
* last element is an integer as there may be cases that the delimiter may be present in the filename.
* For the all other cases, it appends an integer starting from zero before the file's extension.
*/
public function getDestination(string $destination, string $delimiter = '_', int $i = 0): string;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/Files/FileCollection.php | system/HTTP/Files/FileCollection.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP\Files;
use RecursiveArrayIterator;
use RecursiveIteratorIterator;
/**
* Class FileCollection
*
* Provides easy access to uploaded files for a request.
*
* @see \CodeIgniter\HTTP\Files\FileCollectionTest
*/
class FileCollection
{
/**
* An array of UploadedFile instances for any files
* uploaded as part of this request.
* Populated the first time either files(), file(), or hasFile()
* is called.
*
* @var array|null
*/
protected $files;
/**
* Returns an array of all uploaded files that were found.
* Each element in the array will be an instance of UploadedFile.
* The key of each element will be the client filename.
*
* @return array|null
*/
public function all()
{
$this->populateFiles();
return $this->files;
}
/**
* Attempts to get a single file from the collection of uploaded files.
*
* @return UploadedFile|null
*/
public function getFile(string $name)
{
$this->populateFiles();
if ($this->hasFile($name)) {
if (str_contains($name, '.')) {
$name = explode('.', $name);
$uploadedFile = $this->getValueDotNotationSyntax($name, $this->files);
return $uploadedFile instanceof UploadedFile ? $uploadedFile : null;
}
if (array_key_exists($name, $this->files)) {
$uploadedFile = $this->files[$name];
return $uploadedFile instanceof UploadedFile ? $uploadedFile : null;
}
}
return null;
}
/**
* Verify if a file exist in the collection of uploaded files and is have been uploaded with multiple option.
*
* @return list<UploadedFile>|null
*/
public function getFileMultiple(string $name)
{
$this->populateFiles();
if ($this->hasFile($name)) {
if (str_contains($name, '.')) {
$name = explode('.', $name);
$uploadedFile = $this->getValueDotNotationSyntax($name, $this->files);
return (is_array($uploadedFile) && ($uploadedFile[array_key_first($uploadedFile)] instanceof UploadedFile)) ?
$uploadedFile : null;
}
if (array_key_exists($name, $this->files)) {
$uploadedFile = $this->files[$name];
return (is_array($uploadedFile) && ($uploadedFile[array_key_first($uploadedFile)] instanceof UploadedFile)) ?
$uploadedFile : null;
}
}
return null;
}
/**
* Checks whether an uploaded file with name $fileID exists in
* this request.
*
* @param string $fileID The name of the uploaded file (from the input)
*/
public function hasFile(string $fileID): bool
{
$this->populateFiles();
if (str_contains($fileID, '.')) {
$segments = explode('.', $fileID);
$el = $this->files;
foreach ($segments as $segment) {
if (! array_key_exists($segment, $el)) {
return false;
}
$el = $el[$segment];
}
return true;
}
return isset($this->files[$fileID]);
}
/**
* Taking information from the $_FILES array, it creates an instance
* of UploadedFile for each one, saving the results to this->files.
*
* Called by files(), file(), and hasFile()
*
* @return void
*/
protected function populateFiles()
{
if (is_array($this->files)) {
return;
}
$this->files = [];
if ($_FILES === []) {
return;
}
$files = $this->fixFilesArray($_FILES);
foreach ($files as $name => $file) {
$this->files[$name] = $this->createFileObject($file);
}
}
/**
* Given a file array, will create UploadedFile instances. Will
* loop over an array and create objects for each.
*
* @return list<UploadedFile>|UploadedFile
*/
protected function createFileObject(array $array)
{
if (! isset($array['name'])) {
$output = [];
foreach ($array as $key => $values) {
if (! is_array($values)) {
continue;
}
$output[$key] = $this->createFileObject($values);
}
return $output;
}
return new UploadedFile(
$array['tmp_name'] ?? null,
$array['name'] ?? null,
$array['type'] ?? null,
($array['size'] ?? null) === null ? null : (int) $array['size'],
$array['error'] ?? null,
$array['full_path'] ?? null,
);
}
/**
* Reformats the odd $_FILES array into something much more like
* we would expect, with each object having its own array.
*
* Thanks to Jack Sleight on the PHP Manual page for the basis
* of this method.
*
* @see http://php.net/manual/en/reserved.variables.files.php#118294
*/
protected function fixFilesArray(array $data): array
{
$output = [];
foreach ($data as $name => $array) {
foreach ($array as $field => $value) {
$pointer = &$output[$name];
if (! is_array($value)) {
$pointer[$field] = $value;
continue;
}
$stack = [&$pointer];
$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($value),
RecursiveIteratorIterator::SELF_FIRST,
);
foreach ($iterator as $key => $val) {
array_splice($stack, $iterator->getDepth() + 1);
$pointer = &$stack[count($stack) - 1];
$pointer = &$pointer[$key];
$stack[] = &$pointer;
// RecursiveIteratorIterator::hasChildren() can be used. RecursiveIteratorIterator
// forwards all unknown method calls to the underlying RecursiveIterator internally.
// See https://github.com/php/doc-en/issues/787#issuecomment-881446121
if (! $iterator->hasChildren()) {
$pointer[$field] = $val;
}
}
}
}
return $output;
}
/**
* Navigate through an array looking for a particular index
*
* @param array $index The index sequence we are navigating down
* @param array $value The portion of the array to process
*
* @return list<UploadedFile>|UploadedFile|null
*/
protected function getValueDotNotationSyntax(array $index, array $value)
{
$currentIndex = array_shift($index);
if (isset($currentIndex) && $index !== [] && array_key_exists($currentIndex, $value) && is_array($value[$currentIndex])) {
return $this->getValueDotNotationSyntax($index, $value[$currentIndex]);
}
return $value[$currentIndex] ?? null;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/Files/UploadedFile.php | system/HTTP/Files/UploadedFile.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP\Files;
use CodeIgniter\Files\File;
use CodeIgniter\HTTP\Exceptions\HTTPException;
use Config\Mimes;
use Exception;
/**
* Value object representing a single file uploaded through an
* HTTP request. Used by the IncomingRequest class to
* provide files.
*
* Typically, implementors will extend the SplFileInfo class.
*/
class UploadedFile extends File implements UploadedFileInterface
{
/**
* The path to the temporary file.
*
* @var string
*/
protected $path;
/**
* The webkit relative path of the file.
*
* @var string
*/
protected $clientPath;
/**
* The original filename as provided by the client.
*
* @var string
*/
protected $originalName;
/**
* The filename given to a file during a move.
*
* @var string
*/
protected $name;
/**
* The type of file as provided by PHP
*
* @var string
*/
protected $originalMimeType;
/**
* The error constant of the upload
* (one of PHP's UPLOADERRXXX constants)
*
* @var int
*/
protected $error;
/**
* Whether the file has been moved already or not.
*
* @var bool
*/
protected $hasMoved = false;
/**
* Accepts the file information as would be filled in from the $_FILES array.
*
* @param string $path The temporary location of the uploaded file.
* @param string $originalName The client-provided filename.
* @param string|null $mimeType The type of file as provided by PHP
* @param int|null $size The size of the file, in bytes
* @param int|null $error The error constant of the upload (one of PHP's UPLOADERRXXX constants)
* @param string|null $clientPath The webkit relative path of the uploaded file.
*/
public function __construct(string $path, string $originalName, ?string $mimeType = null, ?int $size = null, ?int $error = null, ?string $clientPath = null)
{
$this->path = $path;
$this->name = $originalName;
$this->originalName = $originalName;
$this->originalMimeType = $mimeType;
$this->size = $size;
$this->error = $error;
$this->clientPath = $clientPath;
parent::__construct($path, false);
}
/**
* Move the uploaded file to a new location.
*
* $targetPath may be an absolute path, or a relative path. If it is a
* relative path, resolution should be the same as used by PHP's rename()
* function.
*
* The original file MUST be removed on completion.
*
* If this method is called more than once, any subsequent calls MUST raise
* an exception.
*
* When used in an SAPI environment where $_FILES is populated, when writing
* files via moveTo(), is_uploaded_file() and move_uploaded_file() SHOULD be
* used to ensure permissions and upload status are verified correctly.
*
* If you wish to move to a stream, use getStream(), as SAPI operations
* cannot guarantee writing to stream destinations.
*
* @see http://php.net/is_uploaded_file
* @see http://php.net/move_uploaded_file
*
* @param string $targetPath Path to which to move the uploaded file.
* @param string|null $name the name to rename the file to.
* @param bool $overwrite State for indicating whether to overwrite the previously generated file with the same
* name or not.
*
* @return bool
*/
public function move(string $targetPath, ?string $name = null, bool $overwrite = false)
{
$targetPath = rtrim($targetPath, '/') . '/';
$targetPath = $this->setPath($targetPath); // set the target path
if ($this->hasMoved) {
throw HTTPException::forAlreadyMoved();
}
if (! $this->isValid()) {
throw HTTPException::forInvalidFile();
}
$name ??= $this->getName();
$destination = $overwrite ? $targetPath . $name : $this->getDestination($targetPath . $name);
try {
$this->hasMoved = move_uploaded_file($this->path, $destination);
} catch (Exception) {
$error = error_get_last();
$message = strip_tags($error['message'] ?? '');
throw HTTPException::forMoveFailed(basename($this->path), $targetPath, $message);
}
if ($this->hasMoved === false) {
$message = 'move_uploaded_file() returned false';
throw HTTPException::forMoveFailed(basename($this->path), $targetPath, $message);
}
@chmod($targetPath, 0777 & ~umask());
// Success, so store our new information
$this->path = $targetPath;
$this->name = basename($destination);
return true;
}
/**
* create file target path if
* the set path does not exist
*
* @return string The path set or created.
*/
protected function setPath(string $path): string
{
if (! is_dir($path)) {
mkdir($path, 0777, true);
// create the index.html file
if (! is_file($path . 'index.html')) {
$file = fopen($path . 'index.html', 'x+b');
fclose($file);
}
}
return $path;
}
/**
* Returns whether the file has been moved or not. If it has,
* the move() method will not work and certain properties, like
* the tempName, will no longer be available.
*/
public function hasMoved(): bool
{
return $this->hasMoved;
}
/**
* Retrieve the error associated with the uploaded file.
*
* The return value MUST be one of PHP's UPLOAD_ERR_XXX constants.
*
* If the file was uploaded successfully, this method MUST return
* UPLOAD_ERR_OK.
*
* Implementations SHOULD return the value stored in the "error" key of
* the file in the $_FILES array.
*
* @see http://php.net/manual/en/features.file-upload.errors.php
*
* @return int One of PHP's UPLOAD_ERR_XXX constants.
*/
public function getError(): int
{
return $this->error ?? UPLOAD_ERR_OK;
}
/**
* Get error string
*/
public function getErrorString(): string
{
$errors = [
UPLOAD_ERR_OK => lang('HTTP.uploadErrOk'),
UPLOAD_ERR_INI_SIZE => lang('HTTP.uploadErrIniSize'),
UPLOAD_ERR_FORM_SIZE => lang('HTTP.uploadErrFormSize'),
UPLOAD_ERR_PARTIAL => lang('HTTP.uploadErrPartial'),
UPLOAD_ERR_NO_FILE => lang('HTTP.uploadErrNoFile'),
UPLOAD_ERR_CANT_WRITE => lang('HTTP.uploadErrCantWrite'),
UPLOAD_ERR_NO_TMP_DIR => lang('HTTP.uploadErrNoTmpDir'),
UPLOAD_ERR_EXTENSION => lang('HTTP.uploadErrExtension'),
];
$error = $this->error ?? UPLOAD_ERR_OK;
return sprintf($errors[$error] ?? lang('HTTP.uploadErrUnknown'), $this->getName());
}
/**
* Returns the mime type as provided by the client.
* This is NOT a trusted value.
* For a trusted version, use getMimeType() instead.
*
* @return string The media type sent by the client or null if none was provided.
*/
public function getClientMimeType(): string
{
return $this->originalMimeType;
}
/**
* Retrieve the filename. This will typically be the filename sent
* by the client, and should not be trusted. If the file has been
* moved, this will return the final name of the moved file.
*
* @return string The filename sent by the client or null if none was provided.
*/
public function getName(): string
{
return $this->name;
}
/**
* Returns the name of the file as provided by the client during upload.
*/
public function getClientName(): string
{
return $this->originalName;
}
/**
* (PHP 8.1+)
* Returns the webkit relative path of the uploaded file on directory uploads.
*/
public function getClientPath(): ?string
{
return $this->clientPath;
}
/**
* Gets the temporary filename where the file was uploaded to.
*/
public function getTempName(): string
{
return $this->path;
}
/**
* Overrides SPLFileInfo's to work with uploaded files, since
* the temp file that's been uploaded doesn't have an extension.
*
* This method tries to guess the extension from the files mime
* type but will return the clientExtension if it fails to do so.
*
* This method will always return a more or less helpfull extension
* but might be insecure if the mime type is not matched. Consider
* using guessExtension for a more safe version.
*/
public function getExtension(): string
{
$guessExtension = $this->guessExtension();
return $guessExtension !== '' ? $guessExtension : $this->getClientExtension();
}
/**
* Attempts to determine the best file extension from the file's
* mime type. In contrast to getExtension, this method will return
* an empty string if it fails to determine an extension instead of
* falling back to the unsecure clientExtension.
*/
public function guessExtension(): string
{
return Mimes::guessExtensionFromType($this->getMimeType(), $this->getClientExtension()) ?? '';
}
/**
* Returns the original file extension, based on the file name that
* was uploaded. This is NOT a trusted source.
* For a trusted version, use guessExtension() instead.
*/
public function getClientExtension(): string
{
return pathinfo($this->originalName, PATHINFO_EXTENSION);
}
/**
* Returns whether the file was uploaded successfully, based on whether
* it was uploaded via HTTP and has no errors.
*/
public function isValid(): bool
{
return is_uploaded_file($this->path) && $this->error === UPLOAD_ERR_OK;
}
/**
* Save the uploaded file to a new location.
*
* By default, upload files are saved in writable/uploads directory. The YYYYMMDD folder
* and random file name will be created.
*
* @param string|null $folderName the folder name to writable/uploads directory.
* @param string|null $fileName the name to rename the file to.
*
* @return string file full path
*/
public function store(?string $folderName = null, ?string $fileName = null): string
{
$folderName = rtrim($folderName ?? date('Ymd'), '/') . '/';
$fileName ??= $this->getRandomName();
// Move the uploaded file to a new location.
$this->move(WRITEPATH . 'uploads/' . $folderName, $fileName);
return $folderName . $this->name;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/Exceptions/HTTPException.php | system/HTTP/Exceptions/HTTPException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP\Exceptions;
use CodeIgniter\Exceptions\FrameworkException;
/**
* Things that can go wrong with HTTP
*/
class HTTPException extends FrameworkException implements ExceptionInterface
{
/**
* For CurlRequest
*
* @return HTTPException
*
* @codeCoverageIgnore
*/
public static function forMissingCurl()
{
return new static(lang('HTTP.missingCurl'));
}
/**
* For CurlRequest
*
* @return HTTPException
*/
public static function forSSLCertNotFound(string $cert)
{
return new static(lang('HTTP.sslCertNotFound', [$cert]));
}
/**
* For CurlRequest
*
* @return HTTPException
*/
public static function forInvalidSSLKey(string $key)
{
return new static(lang('HTTP.invalidSSLKey', [$key]));
}
/**
* For CurlRequest
*
* @return HTTPException
*
* @codeCoverageIgnore
*/
public static function forCurlError(string $errorNum, string $error)
{
return new static(lang('HTTP.curlError', [$errorNum, $error]));
}
/**
* For IncomingRequest
*
* @return HTTPException
*/
public static function forInvalidNegotiationType(string $type)
{
return new static(lang('HTTP.invalidNegotiationType', [$type]));
}
/**
* Thrown in IncomingRequest when the json_decode() produces
* an error code other than JSON_ERROR_NONE.
*
* @param string $error The error message
*
* @return static
*/
public static function forInvalidJSON(?string $error = null)
{
return new static(lang('HTTP.invalidJSON', [$error]));
}
/**
* For Message
*
* @return HTTPException
*/
public static function forInvalidHTTPProtocol(string $invalidVersion)
{
return new static(lang('HTTP.invalidHTTPProtocol', [$invalidVersion]));
}
/**
* For Negotiate
*
* @return HTTPException
*/
public static function forEmptySupportedNegotiations()
{
return new static(lang('HTTP.emptySupportedNegotiations'));
}
/**
* For RedirectResponse
*
* @return HTTPException
*/
public static function forInvalidRedirectRoute(string $route)
{
return new static(lang('HTTP.invalidRoute', [$route]));
}
/**
* For Response
*
* @return HTTPException
*/
public static function forMissingResponseStatus()
{
return new static(lang('HTTP.missingResponseStatus'));
}
/**
* For Response
*
* @return HTTPException
*/
public static function forInvalidStatusCode(int $code)
{
return new static(lang('HTTP.invalidStatusCode', [$code]));
}
/**
* For Response
*
* @return HTTPException
*/
public static function forUnkownStatusCode(int $code)
{
return new static(lang('HTTP.unknownStatusCode', [$code]));
}
/**
* For URI
*
* @return HTTPException
*/
public static function forUnableToParseURI(string $uri)
{
return new static(lang('HTTP.cannotParseURI', [$uri]));
}
/**
* For URI
*
* @return HTTPException
*/
public static function forURISegmentOutOfRange(int $segment)
{
return new static(lang('HTTP.segmentOutOfRange', [$segment]));
}
/**
* For URI
*
* @return HTTPException
*/
public static function forInvalidPort(int $port)
{
return new static(lang('HTTP.invalidPort', [$port]));
}
/**
* For URI
*
* @return HTTPException
*/
public static function forMalformedQueryString()
{
return new static(lang('HTTP.malformedQueryString'));
}
/**
* For Uploaded file move
*
* @return HTTPException
*/
public static function forAlreadyMoved()
{
return new static(lang('HTTP.alreadyMoved'));
}
/**
* For Uploaded file move
*
* @return HTTPException
*/
public static function forInvalidFile(?string $path = null)
{
return new static(lang('HTTP.invalidFile'));
}
/**
* For Uploaded file move
*
* @return HTTPException
*/
public static function forMoveFailed(string $source, string $target, string $error)
{
return new static(lang('HTTP.moveFailed', [$source, $target, $error]));
}
/**
* For Invalid SameSite attribute setting
*
* @return HTTPException
*
* @deprecated Use `CookieException::forInvalidSameSite()` instead.
*
* @codeCoverageIgnore
*/
public static function forInvalidSameSiteSetting(string $samesite)
{
return new static(lang('Security.invalidSameSiteSetting', [$samesite]));
}
/**
* Thrown when the JSON format is not supported.
* This is specifically for cases where data validation is expected to work with key-value structures.
*
* @return HTTPException
*/
public static function forUnsupportedJSONFormat()
{
return new static(lang('HTTP.unsupportedJSONFormat'));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/Exceptions/ExceptionInterface.php | system/HTTP/Exceptions/ExceptionInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP\Exceptions;
/**
* Provides a domain-level interface for broad capture
* of all HTTP-related exceptions.
*
* catch (\CodeIgniter\HTTP\Exceptions\ExceptionInterface) { ... }
*/
interface ExceptionInterface extends \CodeIgniter\Exceptions\ExceptionInterface
{
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/Exceptions/RedirectException.php | system/HTTP/Exceptions/RedirectException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP\Exceptions;
use CodeIgniter\Exceptions\HTTPExceptionInterface;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\Exceptions\LogicException;
use CodeIgniter\Exceptions\RuntimeException;
use CodeIgniter\HTTP\ResponsableInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Throwable;
/**
* RedirectException
*/
class RedirectException extends RuntimeException implements ExceptionInterface, ResponsableInterface, HTTPExceptionInterface
{
/**
* HTTP status code for redirects
*
* @var int
*/
protected $code = 302;
protected ?ResponseInterface $response = null;
/**
* @param ResponseInterface|string $message Response object or a string containing a relative URI.
* @param int $code HTTP status code to redirect if $message is a string.
*/
public function __construct($message = '', int $code = 0, ?Throwable $previous = null)
{
if (! is_string($message) && ! $message instanceof ResponseInterface) {
throw new InvalidArgumentException(
'RedirectException::__construct() first argument must be a string or ResponseInterface',
0,
$this,
);
}
if ($message instanceof ResponseInterface) {
$this->response = $message;
$message = '';
if ($this->response->getHeaderLine('Location') === '' && $this->response->getHeaderLine('Refresh') === '') {
throw new LogicException(
'The Response object passed to RedirectException does not contain a redirect address.',
);
}
if ($this->response->getStatusCode() < 301 || $this->response->getStatusCode() > 308) {
$this->response->setStatusCode($this->code);
}
}
parent::__construct($message, $code, $previous);
}
public function getResponse(): ResponseInterface
{
if (! $this->response instanceof ResponseInterface) {
$this->response = service('response')->redirect(
base_url($this->getMessage()),
'auto',
$this->getCode(),
);
}
$location = $this->response->getHeaderLine('Location');
service(('logger'))->info(sprintf(
'REDIRECTED ROUTE at %s',
$location !== '' ? $location : substr($this->response->getHeaderLine('Refresh'), 6),
));
return $this->response;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/Exceptions/BadRequestException.php | system/HTTP/Exceptions/BadRequestException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP\Exceptions;
use CodeIgniter\Exceptions\HTTPExceptionInterface;
use CodeIgniter\Exceptions\RuntimeException;
/**
* 400 Bad Request
*/
class BadRequestException extends RuntimeException implements HTTPExceptionInterface
{
/**
* HTTP status code for Bad Request
*
* @var int
*/
protected $code = 400; // @phpstan-ignore-line
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/CLI/GeneratorTrait.php | system/CLI/GeneratorTrait.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\CLI;
use Config\Generators;
use Throwable;
/**
* GeneratorTrait contains a collection of methods
* to build the commands that generates a file.
*/
trait GeneratorTrait
{
/**
* Component Name
*
* @var string
*/
protected $component;
/**
* File directory
*
* @var string
*/
protected $directory;
/**
* (Optional) View template path
*
* We use special namespaced paths like:
* `CodeIgniter\Commands\Generators\Views\cell.tpl.php`.
*/
protected ?string $templatePath = null;
/**
* View template name for fallback
*
* @var string
*/
protected $template;
/**
* Language string key for required class names.
*
* @var string
*/
protected $classNameLang = '';
/**
* Namespace to use for class.
* Leave null to use the default namespace.
*/
protected ?string $namespace = null;
/**
* Whether to require class name.
*
* @internal
*
* @var bool
*/
private $hasClassName = true;
/**
* Whether to sort class imports.
*
* @internal
*
* @var bool
*/
private $sortImports = true;
/**
* Whether the `--suffix` option has any effect.
*
* @internal
*
* @var bool
*/
private $enabledSuffixing = true;
/**
* The params array for easy access by other methods.
*
* @internal
*
* @var array<int|string, string|null>
*/
private $params = [];
/**
* Execute the command.
*
* @param array<int|string, string|null> $params
*
* @deprecated use generateClass() instead
*/
protected function execute(array $params): void
{
$this->generateClass($params);
}
/**
* Generates a class file from an existing template.
*
* @param array<int|string, string|null> $params
*/
protected function generateClass(array $params): void
{
$this->params = $params;
// Get the fully qualified class name from the input.
$class = $this->qualifyClassName();
// Get the file path from class name.
$target = $this->buildPath($class);
// Check if path is empty.
if ($target === '') {
return;
}
$this->generateFile($target, $this->buildContent($class));
}
/**
* Generate a view file from an existing template.
*
* @param string $view namespaced view name that is generated
* @param array<int|string, string|null> $params
*/
protected function generateView(string $view, array $params): void
{
$this->params = $params;
$target = $this->buildPath($view);
// Check if path is empty.
if ($target === '') {
return;
}
$this->generateFile($target, $this->buildContent($view));
}
/**
* Handles writing the file to disk, and all of the safety checks around that.
*
* @param string $target file path
*/
private function generateFile(string $target, string $content): void
{
if ($this->getOption('namespace') === 'CodeIgniter') {
// @codeCoverageIgnoreStart
CLI::write(lang('CLI.generator.usingCINamespace'), 'yellow');
CLI::newLine();
if (
CLI::prompt(
'Are you sure you want to continue?',
['y', 'n'],
'required',
) === 'n'
) {
CLI::newLine();
CLI::write(lang('CLI.generator.cancelOperation'), 'yellow');
CLI::newLine();
return;
}
CLI::newLine();
// @codeCoverageIgnoreEnd
}
$isFile = is_file($target);
// Overwriting files unknowingly is a serious annoyance, So we'll check if
// we are duplicating things, If 'force' option is not supplied, we bail.
if (! $this->getOption('force') && $isFile) {
CLI::error(
lang('CLI.generator.fileExist', [clean_path($target)]),
'light_gray',
'red',
);
CLI::newLine();
return;
}
// Check if the directory to save the file is existing.
$dir = dirname($target);
if (! is_dir($dir)) {
mkdir($dir, 0755, true);
}
helper('filesystem');
// Build the class based on the details we have, We'll be getting our file
// contents from the template, and then we'll do the necessary replacements.
if (! write_file($target, $content)) {
// @codeCoverageIgnoreStart
CLI::error(
lang('CLI.generator.fileError', [clean_path($target)]),
'light_gray',
'red',
);
CLI::newLine();
return;
// @codeCoverageIgnoreEnd
}
if ($this->getOption('force') && $isFile) {
CLI::write(
lang('CLI.generator.fileOverwrite', [clean_path($target)]),
'yellow',
);
CLI::newLine();
return;
}
CLI::write(
lang('CLI.generator.fileCreate', [clean_path($target)]),
'green',
);
CLI::newLine();
}
/**
* Prepare options and do the necessary replacements.
*
* @param string $class namespaced classname or namespaced view.
*
* @return string generated file content
*/
protected function prepare(string $class): string
{
return $this->parseTemplate($class);
}
/**
* Change file basename before saving.
*
* Useful for components where the file name has a date.
*/
protected function basename(string $filename): string
{
return basename($filename);
}
/**
* Parses the class name and checks if it is already qualified.
*/
protected function qualifyClassName(): string
{
$class = $this->normalizeInputClassName();
// Gets the namespace from input. Don't forget the ending backslash!
$namespace = $this->getNamespace() . '\\';
if (str_starts_with($class, $namespace)) {
return $class; // @codeCoverageIgnore
}
$directoryString = ($this->directory !== null) ? $this->directory . '\\' : '';
return $namespace . $directoryString . str_replace('/', '\\', $class);
}
private function normalizeInputClassName(): string
{
// Gets the class name from input.
$class = $this->params[0] ?? CLI::getSegment(2);
if ($class === null && $this->hasClassName) {
$nameField = $this->classNameLang !== ''
? $this->classNameLang
: 'CLI.generator.className.default';
$class = CLI::prompt(lang($nameField), null, 'required');
// Reassign the class name to the params array in case
// the class name is requested again
$this->params[0] = $class;
CLI::newLine();
}
helper('inflector');
$component = singular($this->component);
/**
* @see https://regex101.com/r/a5KNCR/2
*/
$pattern = sprintf('/([a-z][a-z0-9_\/\\\\]+)(%s)$/i', $component);
if (preg_match($pattern, $class, $matches) === 1) {
$class = $matches[1] . ucfirst($matches[2]);
}
if (
$this->enabledSuffixing && $this->getOption('suffix')
&& preg_match($pattern, $class) !== 1
) {
$class .= ucfirst($component);
}
// Trims input, normalize separators, and ensure that all paths are in Pascalcase.
return ltrim(
implode(
'\\',
array_map(
pascalize(...),
explode('\\', str_replace('/', '\\', trim($class))),
),
),
'\\/',
);
}
/**
* Gets the generator view as defined in the `Config\Generators::$views`,
* with fallback to `$template` when the defined view does not exist.
*
* @param array<string, mixed> $data
*/
protected function renderTemplate(array $data = []): string
{
try {
$template = $this->templatePath ?? config(Generators::class)->views[$this->name];
return view($template, $data, ['debug' => false]);
} catch (Throwable $e) {
log_message('error', (string) $e);
return view(
"CodeIgniter\\Commands\\Generators\\Views\\{$this->template}",
$data,
['debug' => false],
);
}
}
/**
* Performs pseudo-variables contained within view file.
*
* @param string $class namespaced classname or namespaced view.
* @param list<string> $search
* @param list<string> $replace
* @param array<string, bool|string|null> $data
*
* @return string generated file content
*/
protected function parseTemplate(
string $class,
array $search = [],
array $replace = [],
array $data = [],
): string {
// Retrieves the namespace part from the fully qualified class name.
$namespace = trim(
implode(
'\\',
array_slice(explode('\\', $class), 0, -1),
),
'\\',
);
$search[] = '<@php';
$search[] = '{namespace}';
$search[] = '{class}';
$replace[] = '<?php';
$replace[] = $namespace;
$replace[] = str_replace($namespace . '\\', '', $class);
return str_replace($search, $replace, $this->renderTemplate($data));
}
/**
* Builds the contents for class being generated, doing all
* the replacements necessary, and alphabetically sorts the
* imports for a given template.
*/
protected function buildContent(string $class): string
{
$template = $this->prepare($class);
if (
$this->sortImports
&& preg_match(
'/(?P<imports>(?:^use [^;]+;$\n?)+)/m',
$template,
$match,
)
) {
$imports = explode("\n", trim($match['imports']));
sort($imports);
return str_replace(trim($match['imports']), implode("\n", $imports), $template);
}
return $template;
}
/**
* Builds the file path from the class name.
*
* @param string $class namespaced classname or namespaced view.
*/
protected function buildPath(string $class): string
{
$namespace = $this->getNamespace();
// Check if the namespace is actually defined and we are not just typing gibberish.
$base = service('autoloader')->getNamespace($namespace);
if (! $base = reset($base)) {
CLI::error(
lang('CLI.namespaceNotDefined', [$namespace]),
'light_gray',
'red',
);
CLI::newLine();
return '';
}
$realpath = realpath($base);
$base = ($realpath !== false) ? $realpath : $base;
$file = $base . DIRECTORY_SEPARATOR
. str_replace(
'\\',
DIRECTORY_SEPARATOR,
trim(str_replace($namespace . '\\', '', $class), '\\'),
) . '.php';
return implode(
DIRECTORY_SEPARATOR,
array_slice(
explode(DIRECTORY_SEPARATOR, $file),
0,
-1,
),
) . DIRECTORY_SEPARATOR . $this->basename($file);
}
/**
* Gets the namespace from the command-line option,
* or the default namespace if the option is not set.
* Can be overridden by directly setting $this->namespace.
*/
protected function getNamespace(): string
{
return $this->namespace ?? trim(
str_replace(
'/',
'\\',
$this->getOption('namespace') ?? APP_NAMESPACE,
),
'\\',
);
}
/**
* Allows child generators to modify the internal `$hasClassName` flag.
*
* @return $this
*/
protected function setHasClassName(bool $hasClassName)
{
$this->hasClassName = $hasClassName;
return $this;
}
/**
* Allows child generators to modify the internal `$sortImports` flag.
*
* @return $this
*/
protected function setSortImports(bool $sortImports)
{
$this->sortImports = $sortImports;
return $this;
}
/**
* Allows child generators to modify the internal `$enabledSuffixing` flag.
*
* @return $this
*/
protected function setEnabledSuffixing(bool $enabledSuffixing)
{
$this->enabledSuffixing = $enabledSuffixing;
return $this;
}
/**
* Gets a single command-line option. Returns TRUE if the option exists,
* but doesn't have a value, and is simply acting as a flag.
*/
protected function getOption(string $name): bool|string|null
{
if (! array_key_exists($name, $this->params)) {
return CLI::getOption($name);
}
return $this->params[$name] ?? true;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/CLI/Console.php | system/CLI/Console.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\CLI;
use CodeIgniter\CodeIgniter;
use Config\App;
use Config\Services;
use Exception;
/**
* Console
*
* @see \CodeIgniter\CLI\ConsoleTest
*/
class Console
{
/**
* Runs the current command discovered on the CLI.
*
* @return int|void Exit code
*
* @throws Exception
*/
public function run()
{
// Create CLIRequest
$appConfig = config(App::class);
Services::createRequest($appConfig, true);
// Load Routes
service('routes')->loadRoutes();
$params = array_merge(CLI::getSegments(), CLI::getOptions());
$params = $this->parseParamsForHelpOption($params);
$command = array_shift($params) ?? 'list';
return service('commands')->run($command, $params);
}
/**
* Displays basic information about the Console.
*
* @return void
*/
public function showHeader(bool $suppress = false)
{
if ($suppress) {
return;
}
CLI::write(sprintf(
'CodeIgniter v%s Command Line Tool - Server Time: %s',
CodeIgniter::CI_VERSION,
date('Y-m-d H:i:s \\U\\T\\CP'),
), 'green');
CLI::newLine();
}
/**
* Introspects the `$params` passed for presence of the
* `--help` option.
*
* If present, it will be found as `['help' => null]`.
* We'll remove that as an option from `$params` and
* unshift it as argument instead.
*
* @param array<int|string, string|null> $params
*/
private function parseParamsForHelpOption(array $params): array
{
if (array_key_exists('help', $params)) {
unset($params['help']);
$params = $params === [] ? ['list'] : $params;
array_unshift($params, 'help');
}
return $params;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/CLI/Commands.php | system/CLI/Commands.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\CLI;
use CodeIgniter\Autoloader\FileLocatorInterface;
use CodeIgniter\Events\Events;
use CodeIgniter\Log\Logger;
use ReflectionClass;
use ReflectionException;
/**
* Core functionality for running, listing, etc commands.
*
* @phpstan-type commands_list array<string, array{'class': class-string<BaseCommand>, 'file': string, 'group': string,'description': string}>
*/
class Commands
{
/**
* The found commands.
*
* @var commands_list
*/
protected $commands = [];
/**
* Logger instance.
*
* @var Logger
*/
protected $logger;
/**
* Constructor
*
* @param Logger|null $logger
*/
public function __construct($logger = null)
{
$this->logger = $logger ?? service('logger');
$this->discoverCommands();
}
/**
* Runs a command given
*
* @param array<int|string, string|null> $params
*
* @return int Exit code
*/
public function run(string $command, array $params)
{
if (! $this->verifyCommand($command, $this->commands)) {
return EXIT_ERROR;
}
// The file would have already been loaded during the
// createCommandList function...
$className = $this->commands[$command]['class'];
$class = new $className($this->logger, $this);
Events::trigger('pre_command');
$exit = $class->run($params);
Events::trigger('post_command');
return $exit;
}
/**
* Provide access to the list of commands.
*
* @return commands_list
*/
public function getCommands()
{
return $this->commands;
}
/**
* Discovers all commands in the framework and within user code,
* and collects instances of them to work with.
*
* @return void
*/
public function discoverCommands()
{
if ($this->commands !== []) {
return;
}
/** @var FileLocatorInterface */
$locator = service('locator');
$files = $locator->listFiles('Commands/');
// If no matching command files were found, bail
// This should never happen in unit testing.
if ($files === []) {
return; // @codeCoverageIgnore
}
// Loop over each file checking to see if a command with that
// alias exists in the class.
foreach ($files as $file) {
/** @var class-string<BaseCommand>|false */
$className = $locator->findQualifiedNameFromPath($file);
if ($className === false || ! class_exists($className)) {
continue;
}
try {
$class = new ReflectionClass($className);
if (! $class->isInstantiable() || ! $class->isSubclassOf(BaseCommand::class)) {
continue;
}
$class = new $className($this->logger, $this);
if (isset($class->group) && ! isset($this->commands[$class->name])) {
$this->commands[$class->name] = [
'class' => $className,
'file' => $file,
'group' => $class->group,
'description' => $class->description,
];
}
unset($class);
} catch (ReflectionException $e) {
$this->logger->error($e->getMessage());
}
}
asort($this->commands);
}
/**
* Verifies if the command being sought is found
* in the commands list.
*
* @param commands_list $commands
*/
public function verifyCommand(string $command, array $commands): bool
{
if (isset($commands[$command])) {
return true;
}
$message = lang('CLI.commandNotFound', [$command]);
$alternatives = $this->getCommandAlternatives($command, $commands);
if ($alternatives !== []) {
if (count($alternatives) === 1) {
$message .= "\n\n" . lang('CLI.altCommandSingular') . "\n ";
} else {
$message .= "\n\n" . lang('CLI.altCommandPlural') . "\n ";
}
$message .= implode("\n ", $alternatives);
}
CLI::error($message);
CLI::newLine();
return false;
}
/**
* Finds alternative of `$name` among collection
* of commands.
*
* @param commands_list $collection
*
* @return list<string>
*/
protected function getCommandAlternatives(string $name, array $collection): array
{
/** @var array<string, int> */
$alternatives = [];
/** @var string $commandName */
foreach (array_keys($collection) as $commandName) {
$lev = levenshtein($name, $commandName);
if ($lev <= strlen($commandName) / 3 || str_contains($commandName, $name)) {
$alternatives[$commandName] = $lev;
}
}
ksort($alternatives, SORT_NATURAL | SORT_FLAG_CASE);
return array_keys($alternatives);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/CLI/InputOutput.php | system/CLI/InputOutput.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\CLI;
/**
* Input and Output for CLI.
*/
class InputOutput
{
/**
* Is the readline library on the system?
*/
private readonly bool $readlineSupport;
public function __construct()
{
// Readline is an extension for PHP that makes interactivity with PHP
// much more bash-like.
// http://www.php.net/manual/en/readline.installation.php
$this->readlineSupport = extension_loaded('readline');
}
/**
* Get input from the shell, using readline or the standard STDIN
*
* Named options must be in the following formats:
* php index.php user -v --v -name=John --name=John
*
* @param string|null $prefix You may specify a string with which to prompt the user.
*/
public function input(?string $prefix = null): string
{
// readline() can't be tested.
if ($this->readlineSupport && ENVIRONMENT !== 'testing') {
return readline($prefix); // @codeCoverageIgnore
}
echo $prefix;
$input = fgets(fopen('php://stdin', 'rb'));
if ($input === false) {
$input = '';
}
return $input;
}
/**
* While the library is intended for use on CLI commands,
* commands can be called from controllers and elsewhere
* so we need a way to allow them to still work.
*
* For now, just echo the content, but look into a better
* solution down the road.
*
* @param resource $handle
*/
public function fwrite($handle, string $string): void
{
if (! is_cli()) {
echo $string;
return;
}
fwrite($handle, $string);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/CLI/CLI.php | system/CLI/CLI.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\CLI;
use CodeIgniter\CLI\Exceptions\CLIException;
use CodeIgniter\Exceptions\InvalidArgumentException;
use Throwable;
/**
* Set of static methods useful for CLI request handling.
*
* Portions of this code were initially from the FuelPHP Framework,
* version 1.7.x, and used here under the MIT license they were
* originally made available under. Reference: http://fuelphp.com
*
* Some of the code in this class is Windows-specific, and not
* possible to test using travis-ci. It has been phpunit-annotated
* to prevent messing up code coverage.
*
* @see \CodeIgniter\CLI\CLITest
*/
class CLI
{
/**
* Is the readline library on the system?
*
* @var bool
*
* @deprecated 4.4.2 Should be protected, and no longer used.
* @TODO Fix to camelCase in the next major version.
*/
public static $readline_support = false;
/**
* The message displayed at prompts.
*
* @var string
*
* @deprecated 4.4.2 Should be protected.
* @TODO Fix to camelCase in the next major version.
*/
public static $wait_msg = 'Press any key to continue...';
/**
* Has the class already been initialized?
*
* @var bool
*/
protected static $initialized = false;
/**
* Foreground color list
*
* @var array<string, string>
*
* @TODO Fix to camelCase in the next major version.
*/
protected static $foreground_colors = [
'black' => '0;30',
'dark_gray' => '1;30',
'blue' => '0;34',
'dark_blue' => '0;34',
'light_blue' => '1;34',
'green' => '0;32',
'light_green' => '1;32',
'cyan' => '0;36',
'light_cyan' => '1;36',
'red' => '0;31',
'light_red' => '1;31',
'purple' => '0;35',
'light_purple' => '1;35',
'yellow' => '0;33',
'light_yellow' => '1;33',
'light_gray' => '0;37',
'white' => '1;37',
];
/**
* Background color list
*
* @var array<string, string>
*
* @TODO Fix to camelCase in the next major version.
*/
protected static $background_colors = [
'black' => '40',
'red' => '41',
'green' => '42',
'yellow' => '43',
'blue' => '44',
'magenta' => '45',
'cyan' => '46',
'light_gray' => '47',
];
/**
* List of array segments.
*
* @var list<string>
*/
protected static $segments = [];
/**
* @var array<string, string|null>
*/
protected static $options = [];
/**
* Helps track internally whether the last
* output was a "write" or a "print" to
* keep the output clean and as expected.
*
* @var string|null
*/
protected static $lastWrite;
/**
* Height of the CLI window
*
* @var int|null
*/
protected static $height;
/**
* Width of the CLI window
*
* @var int|null
*/
protected static $width;
/**
* Whether the current stream supports colored output.
*
* @var bool
*/
protected static $isColored = false;
/**
* Input and Output for CLI.
*/
protected static ?InputOutput $io = null;
/**
* Static "constructor".
*
* @return void
*/
public static function init()
{
if (is_cli()) {
// Readline is an extension for PHP that makes interactivity with PHP
// much more bash-like.
// http://www.php.net/manual/en/readline.installation.php
static::$readline_support = extension_loaded('readline');
// clear segments & options to keep testing clean
static::$segments = [];
static::$options = [];
// Check our stream resource for color support
static::$isColored = static::hasColorSupport(STDOUT);
static::parseCommandLine();
static::$initialized = true;
} elseif (! defined('STDOUT')) {
// If the command is being called from a controller
// we need to define STDOUT ourselves
// For "! defined('STDOUT')" see: https://github.com/codeigniter4/CodeIgniter4/issues/7047
define('STDOUT', 'php://output'); // @codeCoverageIgnore
}
static::resetInputOutput();
}
/**
* Get input from the shell, using readline or the standard STDIN
*
* Named options must be in the following formats:
* php index.php user -v --v -name=John --name=John
*
* @param string|null $prefix You may specify a string with which to prompt the user.
*/
public static function input(?string $prefix = null): string
{
return static::$io->input($prefix);
}
/**
* Asks the user for input.
*
* Usage:
*
* // Takes any input
* $color = CLI::prompt('What is your favorite color?');
*
* // Takes any input, but offers default
* $color = CLI::prompt('What is your favourite color?', 'white');
*
* // Will validate options with the in_list rule and accept only if one of the list
* $color = CLI::prompt('What is your favourite color?', array('red','blue'));
*
* // Do not provide options but requires a valid email
* $email = CLI::prompt('What is your email?', null, 'required|valid_email');
*
* @param string $field Output "field" question
* @param list<int|string>|string $options String to a default value, array to a list of options (the first option will be the default value)
* @param array|string|null $validation Validation rules
*
* @return string The user input
*/
public static function prompt(string $field, $options = null, $validation = null): string
{
$extraOutput = '';
$default = '';
if (isset($validation) && ! is_array($validation) && ! is_string($validation)) {
throw new InvalidArgumentException('$rules can only be of type string|array');
}
if (! is_array($validation)) {
$validation = ($validation !== null) ? explode('|', $validation) : [];
}
if (is_string($options)) {
$extraOutput = ' [' . static::color($options, 'green') . ']';
$default = $options;
}
if (is_array($options) && $options !== []) {
$opts = $options;
$extraOutputDefault = static::color((string) $opts[0], 'green');
unset($opts[0]);
if ($opts === []) {
$extraOutput = $extraOutputDefault;
} else {
$extraOutput = '[' . $extraOutputDefault . ', ' . implode(', ', $opts) . ']';
$validation[] = 'in_list[' . implode(', ', $options) . ']';
}
$default = $options[0];
}
static::fwrite(STDOUT, $field . (trim($field) !== '' ? ' ' : '') . $extraOutput . ': ');
// Read the input from keyboard.
$input = trim(static::$io->input());
$input = ($input === '') ? (string) $default : $input;
if ($validation !== []) {
while (! static::validate('"' . trim($field) . '"', $input, $validation)) {
$input = static::prompt($field, $options, $validation);
}
}
return $input;
}
/**
* prompt(), but based on the option's key
*
* @param array|string $text Output "field" text or an one or two value array where the first value is the text before listing the options
* and the second value the text before asking to select one option. Provide empty string to omit
* @param array $options A list of options (array(key => description)), the first option will be the default value
* @param array|string|null $validation Validation rules
*
* @return string The selected key of $options
*/
public static function promptByKey($text, array $options, $validation = null): string
{
if (is_string($text)) {
$text = [$text];
} elseif (! is_array($text)) {
throw new InvalidArgumentException('$text can only be of type string|array');
}
CLI::isZeroOptions($options);
if (($line = array_shift($text)) !== null) {
CLI::write($line);
}
CLI::printKeysAndValues($options);
return static::prompt(PHP_EOL . array_shift($text), array_keys($options), $validation);
}
/**
* This method is the same as promptByKey(), but this method supports multiple keys, separated by commas.
*
* @param string $text Output "field" text or an one or two value array where the first value is the text before listing the options
* and the second value the text before asking to select one option. Provide empty string to omit
* @param array $options A list of options (array(key => description)), the first option will be the default value
*
* @return array The selected key(s) and value(s) of $options
*/
public static function promptByMultipleKeys(string $text, array $options): array
{
CLI::isZeroOptions($options);
$extraOutputDefault = static::color('0', 'green');
$opts = $options;
unset($opts[0]);
if ($opts === []) {
$extraOutput = $extraOutputDefault;
} else {
$optsKey = [];
foreach (array_keys($opts) as $key) {
$optsKey[] = $key;
}
$extraOutput = '[' . $extraOutputDefault . ', ' . implode(', ', $optsKey) . ']';
$extraOutput = 'You can specify multiple values separated by commas.' . PHP_EOL . $extraOutput;
}
CLI::write($text);
CLI::printKeysAndValues($options);
CLI::newLine();
$input = static::prompt($extraOutput);
$input = ($input === '') ? '0' : $input; // 0 is default
// validation
while (true) {
$pattern = preg_match_all('/^\d+(,\d+)*$/', trim($input));
// separate input by comma and convert all to an int[]
$inputToArray = array_map(static fn ($value): int => (int) $value, explode(',', $input));
// find max from key of $options
$maxOptions = array_key_last($options);
// find max from input
$maxInput = max($inputToArray);
// return the prompt again if $input contain(s) non-numeric character, except a comma.
// And if max from $options less than max from input,
// it means user tried to access null value in $options
if ($pattern < 1 || $maxOptions < $maxInput) {
static::error('Please select correctly.');
CLI::newLine();
$input = static::prompt($extraOutput);
$input = ($input === '') ? '0' : $input;
} else {
break;
}
}
$input = [];
foreach ($options as $key => $description) {
foreach ($inputToArray as $inputKey) {
if ($key === $inputKey) {
$input[$key] = $description;
}
}
}
return $input;
}
// --------------------------------------------------------------------
// Utility for promptBy...
// --------------------------------------------------------------------
/**
* Validation for $options in promptByKey() and promptByMultipleKeys(). Return an error if $options is an empty array.
*/
private static function isZeroOptions(array $options): void
{
if ($options === []) {
throw new InvalidArgumentException('No options to select from were provided');
}
}
/**
* Print each key and value one by one
*/
private static function printKeysAndValues(array $options): void
{
// +2 for the square brackets around the key
$keyMaxLength = max(array_map(mb_strwidth(...), array_keys($options))) + 2;
foreach ($options as $key => $description) {
$name = str_pad(' [' . $key . '] ', $keyMaxLength + 4, ' ');
CLI::write(CLI::color($name, 'green') . CLI::wrap($description, 125, $keyMaxLength + 4));
}
}
// --------------------------------------------------------------------
// End Utility for promptBy...
// --------------------------------------------------------------------
/**
* Validate one prompt "field" at a time
*
* @param string $field Prompt "field" output
* @param string $value Input value
* @param array|string $rules Validation rules
*/
protected static function validate(string $field, string $value, $rules): bool
{
$label = $field;
$field = 'temp';
$validation = service('validation', null, false);
$validation->setRules([
$field => [
'label' => $label,
'rules' => $rules,
],
]);
$validation->run([$field => $value]);
if ($validation->hasError($field)) {
static::error($validation->getError($field));
return false;
}
return true;
}
/**
* Outputs a string to the CLI without any surrounding newlines.
* Useful for showing repeating elements on a single line.
*
* @return void
*/
public static function print(string $text = '', ?string $foreground = null, ?string $background = null)
{
if ((string) $foreground !== '' || (string) $background !== '') {
$text = static::color($text, $foreground, $background);
}
static::$lastWrite = null;
static::fwrite(STDOUT, $text);
}
/**
* Outputs a string to the cli on its own line.
*
* @return void
*/
public static function write(string $text = '', ?string $foreground = null, ?string $background = null)
{
if ((string) $foreground !== '' || (string) $background !== '') {
$text = static::color($text, $foreground, $background);
}
if (static::$lastWrite !== 'write') {
$text = PHP_EOL . $text;
static::$lastWrite = 'write';
}
static::fwrite(STDOUT, $text . PHP_EOL);
}
/**
* Outputs an error to the CLI using STDERR instead of STDOUT
*
* @return void
*/
public static function error(string $text, string $foreground = 'light_red', ?string $background = null)
{
// Check color support for STDERR
$stdout = static::$isColored;
static::$isColored = static::hasColorSupport(STDERR);
if ($foreground !== '' || (string) $background !== '') {
$text = static::color($text, $foreground, $background);
}
static::fwrite(STDERR, $text . PHP_EOL);
// return STDOUT color support
static::$isColored = $stdout;
}
/**
* Beeps a certain number of times.
*
* @param int $num The number of times to beep
*
* @return void
*/
public static function beep(int $num = 1)
{
echo str_repeat("\x07", $num);
}
/**
* Waits a certain number of seconds, optionally showing a wait message and
* waiting for a key press.
*
* @param int $seconds Number of seconds
* @param bool $countdown Show a countdown or not
*
* @return void
*/
public static function wait(int $seconds, bool $countdown = false)
{
if ($countdown) {
$time = $seconds;
while ($time > 0) {
static::fwrite(STDOUT, $time . '... ');
sleep(1);
$time--;
}
static::write();
} elseif ($seconds > 0) {
sleep($seconds);
} else {
static::write(static::$wait_msg);
static::$io->input();
}
}
/**
* if operating system === windows
*
* @deprecated 4.3.0 Use `is_windows()` instead
*/
public static function isWindows(): bool
{
return is_windows();
}
/**
* Enter a number of empty lines
*
* @return void
*/
public static function newLine(int $num = 1)
{
// Do it once or more, write with empty string gives us a new line
for ($i = 0; $i < $num; $i++) {
static::write();
}
}
/**
* Clears the screen of output
*
* @return void
*/
public static function clearScreen()
{
// Unix systems, and Windows with VT100 Terminal support (i.e. Win10)
// can handle CSI sequences. For lower than Win10 we just shove in 40 new lines.
is_windows() && ! static::streamSupports('sapi_windows_vt100_support', STDOUT)
? static::newLine(40)
: static::fwrite(STDOUT, "\033[H\033[2J");
}
/**
* Returns the given text with the correct color codes for a foreground and
* optionally a background color.
*
* @param string $text The text to color
* @param string $foreground The foreground color
* @param string|null $background The background color
* @param string|null $format Other formatting to apply. Currently only 'underline' is understood
*
* @return string The color coded string
*/
public static function color(string $text, string $foreground, ?string $background = null, ?string $format = null): string
{
if (! static::$isColored || $text === '') {
return $text;
}
if (! array_key_exists($foreground, static::$foreground_colors)) {
throw CLIException::forInvalidColor('foreground', $foreground);
}
if ((string) $background !== '' && ! array_key_exists($background, static::$background_colors)) {
throw CLIException::forInvalidColor('background', $background);
}
$newText = '';
// Detect if color method was already in use with this text
if (str_contains($text, "\033[0m")) {
$pattern = '/\\033\\[0;.+?\\033\\[0m/u';
preg_match_all($pattern, $text, $matches);
$coloredStrings = $matches[0];
// No colored string found. Invalid strings with no `\033[0;??`.
if ($coloredStrings === []) {
return $newText . self::getColoredText($text, $foreground, $background, $format);
}
$nonColoredText = preg_replace(
$pattern,
'<<__colored_string__>>',
$text,
);
$nonColoredChunks = preg_split(
'/<<__colored_string__>>/u',
$nonColoredText,
);
foreach ($nonColoredChunks as $i => $chunk) {
if ($chunk !== '') {
$newText .= self::getColoredText($chunk, $foreground, $background, $format);
}
if (isset($coloredStrings[$i])) {
$newText .= $coloredStrings[$i];
}
}
} else {
$newText .= self::getColoredText($text, $foreground, $background, $format);
}
return $newText;
}
private static function getColoredText(string $text, string $foreground, ?string $background, ?string $format): string
{
$string = "\033[" . static::$foreground_colors[$foreground] . 'm';
if ((string) $background !== '') {
$string .= "\033[" . static::$background_colors[$background] . 'm';
}
if ($format === 'underline') {
$string .= "\033[4m";
}
return $string . $text . "\033[0m";
}
/**
* Get the number of characters in string having encoded characters
* and ignores styles set by the color() function
*/
public static function strlen(?string $string): int
{
if ((string) $string === '') {
return 0;
}
foreach (static::$foreground_colors as $color) {
$string = strtr($string, ["\033[" . $color . 'm' => '']);
}
foreach (static::$background_colors as $color) {
$string = strtr($string, ["\033[" . $color . 'm' => '']);
}
$string = strtr($string, ["\033[4m" => '', "\033[0m" => '']);
return mb_strwidth($string);
}
/**
* Checks whether the current stream resource supports or
* refers to a valid terminal type device.
*
* @param resource $resource
*/
public static function streamSupports(string $function, $resource): bool
{
if (ENVIRONMENT === 'testing') {
// In the current setup of the tests we cannot fully check
// if the stream supports the function since we are using
// filtered streams.
return function_exists($function);
}
return function_exists($function) && @$function($resource); // @codeCoverageIgnore
}
/**
* Returns true if the stream resource supports colors.
*
* This is tricky on Windows, because Cygwin, Msys2 etc. emulate pseudo
* terminals via named pipes, so we can only check the environment.
*
* Reference: https://github.com/composer/xdebug-handler/blob/master/src/Process.php
*
* @param resource $resource
*/
public static function hasColorSupport($resource): bool
{
// Follow https://no-color.org/
if (isset($_SERVER['NO_COLOR']) || getenv('NO_COLOR') !== false) {
return false;
}
if (getenv('TERM_PROGRAM') === 'Hyper') {
return true;
}
if (is_windows()) {
// @codeCoverageIgnoreStart
return static::streamSupports('sapi_windows_vt100_support', $resource)
|| isset($_SERVER['ANSICON'])
|| getenv('ANSICON') !== false
|| getenv('ConEmuANSI') === 'ON'
|| getenv('TERM') === 'xterm';
// @codeCoverageIgnoreEnd
}
return static::streamSupports('stream_isatty', $resource);
}
/**
* Attempts to determine the width of the viewable CLI window.
*/
public static function getWidth(int $default = 80): int
{
if (static::$width === null) {
static::generateDimensions();
}
return static::$width ?: $default;
}
/**
* Attempts to determine the height of the viewable CLI window.
*/
public static function getHeight(int $default = 32): int
{
if (static::$height === null) {
static::generateDimensions();
}
return static::$height ?: $default;
}
/**
* Populates the CLI's dimensions.
*
* @return void
*/
public static function generateDimensions()
{
try {
if (is_windows()) {
// Shells such as `Cygwin` and `Git bash` returns incorrect values
// when executing `mode CON`, so we use `tput` instead
if (getenv('TERM') || (($shell = getenv('SHELL')) && preg_match('/(?:bash|zsh)(?:\.exe)?$/', $shell))) {
static::$height = (int) exec('tput lines');
static::$width = (int) exec('tput cols');
} else {
$return = -1;
$output = [];
exec('mode CON', $output, $return);
// Look for the next lines ending in ": <number>"
// Searching for "Columns:" or "Lines:" will fail on non-English locales
if ($return === 0 && $output !== [] && preg_match('/:\s*(\d+)\n[^:]+:\s*(\d+)\n/', implode("\n", $output), $matches)) {
static::$height = (int) $matches[1];
static::$width = (int) $matches[2];
}
}
} elseif (($size = exec('stty size')) && preg_match('/(\d+)\s+(\d+)/', $size, $matches)) {
static::$height = (int) $matches[1];
static::$width = (int) $matches[2];
} else {
static::$height = (int) exec('tput lines');
static::$width = (int) exec('tput cols');
}
} catch (Throwable $e) {
// Reset the dimensions so that the default values will be returned later.
// Then let the developer know of the error.
static::$height = null;
static::$width = null;
log_message('error', (string) $e);
}
}
/**
* Displays a progress bar on the CLI. You must call it repeatedly
* to update it. Set $thisStep = false to erase the progress bar.
*
* @param bool|int $thisStep
*
* @return void
*/
public static function showProgress($thisStep = 1, int $totalSteps = 10)
{
static $inProgress = false;
// restore cursor position when progress is continuing.
if ($inProgress !== false && $inProgress <= $thisStep) {
static::fwrite(STDOUT, "\033[1A");
}
$inProgress = $thisStep;
if ($thisStep !== false) {
// Don't allow div by zero or negative numbers....
$thisStep = abs($thisStep);
$totalSteps = $totalSteps < 1 ? 1 : $totalSteps;
$percent = (int) (($thisStep / $totalSteps) * 100);
$step = (int) round($percent / 10);
// Write the progress bar
static::fwrite(STDOUT, "[\033[32m" . str_repeat('#', $step) . str_repeat('.', 10 - $step) . "\033[0m]");
// Textual representation...
static::fwrite(STDOUT, sprintf(' %3d%% Complete', $percent) . PHP_EOL);
} else {
static::fwrite(STDOUT, "\007");
}
}
/**
* Takes a string and writes it to the command line, wrapping to a maximum
* width. If no maximum width is specified, will wrap to the window's max
* width.
*
* If an int is passed into $pad_left, then all strings after the first
* will pad with that many spaces to the left. Useful when printing
* short descriptions that need to start on an existing line.
*/
public static function wrap(?string $string = null, int $max = 0, int $padLeft = 0): string
{
if ((string) $string === '') {
return '';
}
if ($max === 0) {
$max = self::getWidth();
}
if (self::getWidth() < $max) {
$max = self::getWidth();
}
$max -= $padLeft;
$lines = wordwrap($string, $max, PHP_EOL);
if ($padLeft > 0) {
$lines = explode(PHP_EOL, $lines);
$first = true;
array_walk($lines, static function (&$line) use ($padLeft, &$first): void {
if (! $first) {
$line = str_repeat(' ', $padLeft) . $line;
} else {
$first = false;
}
});
$lines = implode(PHP_EOL, $lines);
}
return $lines;
}
// --------------------------------------------------------------------
// Command-Line 'URI' support
// --------------------------------------------------------------------
/**
* Parses the command line it was called from and collects all
* options and valid segments.
*
* @return void
*/
protected static function parseCommandLine()
{
$args = $_SERVER['argv'] ?? [];
array_shift($args); // scrap invoking program
$optionValue = false;
foreach ($args as $i => $arg) {
// If there's no "-" at the beginning, then
// this is probably an argument or an option value
if (mb_strpos($arg, '-') !== 0) {
if ($optionValue) {
// We have already included this in the previous
// iteration, so reset this flag
$optionValue = false;
} else {
// Yup, it's a segment
static::$segments[] = $arg;
}
continue;
}
$arg = ltrim($arg, '-');
$value = null;
if (isset($args[$i + 1]) && mb_strpos($args[$i + 1], '-') !== 0) {
$value = $args[$i + 1];
$optionValue = true;
}
static::$options[$arg] = $value;
}
}
/**
* Returns the command line string portions of the arguments, minus
* any options, as a string. This is used to pass along to the main
* CodeIgniter application.
*/
public static function getURI(): string
{
return implode('/', static::$segments);
}
/**
* Returns an individual segment.
*
* This ignores any options that might have been dispersed between
* valid segments in the command:
*
* // segment(3) is 'three', not '-f' or 'anOption'
* > php spark one two -f anOption three
*
* **IMPORTANT:** The index here is one-based instead of zero-based.
*
* @return string|null
*/
public static function getSegment(int $index)
{
return static::$segments[$index - 1] ?? null;
}
/**
* Returns the raw array of segments found.
*
* @return list<string>
*/
public static function getSegments(): array
{
return static::$segments;
}
/**
* Gets a single command-line option. Returns TRUE if the option
* exists, but doesn't have a value, and is simply acting as a flag.
*
* @return string|true|null
*/
public static function getOption(string $name)
{
if (! array_key_exists($name, static::$options)) {
return null;
}
// If the option didn't have a value, simply return TRUE
// so they know it was set, otherwise return the actual value.
$val = static::$options[$name] ?? true;
return $val;
}
/**
* Returns the raw array of options found.
*
* @return array<string, string|null>
*/
public static function getOptions(): array
{
return static::$options;
}
/**
* Returns the options as a string, suitable for passing along on
* the CLI to other commands.
*
* @param bool $useLongOpts Use '--' for long options?
* @param bool $trim Trim final string output?
*/
public static function getOptionString(bool $useLongOpts = false, bool $trim = false): string
{
if (static::$options === []) {
return '';
}
$out = '';
foreach (static::$options as $name => $value) {
if ($useLongOpts && mb_strlen($name) > 1) {
$out .= "--{$name} ";
} else {
$out .= "-{$name} ";
}
if ($value === null) {
continue;
}
if (mb_strpos($value, ' ') !== false) {
$out .= "\"{$value}\" ";
} elseif ($value !== null) {
$out .= "{$value} ";
}
}
return $trim ? trim($out) : $out;
}
/**
* Returns a well formatted table
*
* @param array $tbody List of rows
* @param array $thead List of columns
*
* @return void
*/
public static function table(array $tbody, array $thead = [])
{
// All the rows in the table will be here until the end
$tableRows = [];
// We need only indexes and not keys
if ($thead !== []) {
$tableRows[] = array_values($thead);
}
foreach ($tbody as $tr) {
$tableRows[] = array_values($tr);
}
// Yes, it really is necessary to know this count
$totalRows = count($tableRows);
// Store all columns lengths
// $all_cols_lengths[row][column] = length
$allColsLengths = [];
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | true |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/CLI/BaseCommand.php | system/CLI/BaseCommand.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\CLI;
use Config\Exceptions;
use Psr\Log\LoggerInterface;
use ReflectionException;
use Throwable;
/**
* BaseCommand is the base class used in creating CLI commands.
*
* @property array<string, string> $arguments
* @property Commands $commands
* @property string $description
* @property string $group
* @property LoggerInterface $logger
* @property string $name
* @property array<string, string> $options
* @property string $usage
*/
abstract class BaseCommand
{
/**
* The group the command is lumped under
* when listing commands.
*
* @var string
*/
protected $group;
/**
* The Command's name
*
* @var string
*/
protected $name;
/**
* the Command's usage description
*
* @var string
*/
protected $usage;
/**
* the Command's short description
*
* @var string
*/
protected $description;
/**
* the Command's options description
*
* @var array<string, string>
*/
protected $options = [];
/**
* the Command's Arguments description
*
* @var array<string, string>
*/
protected $arguments = [];
/**
* The Logger to use for a command
*
* @var LoggerInterface
*/
protected $logger;
/**
* Instance of Commands so
* commands can call other commands.
*
* @var Commands
*/
protected $commands;
public function __construct(LoggerInterface $logger, Commands $commands)
{
$this->logger = $logger;
$this->commands = $commands;
}
/**
* Actually execute a command.
*
* @param array<int|string, string|null> $params
*
* @return int|void
*/
abstract public function run(array $params);
/**
* Can be used by a command to run other commands.
*
* @param array<int|string, string|null> $params
*
* @return int|void
*
* @throws ReflectionException
*/
protected function call(string $command, array $params = [])
{
return $this->commands->run($command, $params);
}
/**
* A simple method to display an error with line/file, in child commands.
*
* @return void
*/
protected function showError(Throwable $e)
{
$exception = $e;
$message = $e->getMessage();
$config = config(Exceptions::class);
require $config->errorViewPath . '/cli/error_exception.php';
}
/**
* Show Help includes (Usage, Arguments, Description, Options).
*
* @return void
*/
public function showHelp()
{
CLI::write(lang('CLI.helpUsage'), 'yellow');
if (isset($this->usage)) {
$usage = $this->usage;
} else {
$usage = $this->name;
if ($this->arguments !== []) {
$usage .= ' [arguments]';
}
}
CLI::write($this->setPad($usage, 0, 0, 2));
if (isset($this->description)) {
CLI::newLine();
CLI::write(lang('CLI.helpDescription'), 'yellow');
CLI::write($this->setPad($this->description, 0, 0, 2));
}
if ($this->arguments !== []) {
CLI::newLine();
CLI::write(lang('CLI.helpArguments'), 'yellow');
$length = max(array_map(strlen(...), array_keys($this->arguments)));
foreach ($this->arguments as $argument => $description) {
CLI::write(CLI::color($this->setPad($argument, $length, 2, 2), 'green') . $description);
}
}
if ($this->options !== []) {
CLI::newLine();
CLI::write(lang('CLI.helpOptions'), 'yellow');
$length = max(array_map(strlen(...), array_keys($this->options)));
foreach ($this->options as $option => $description) {
CLI::write(CLI::color($this->setPad($option, $length, 2, 2), 'green') . $description);
}
}
}
/**
* Pads our string out so that all titles are the same length to nicely line up descriptions.
*
* @param int $extra How many extra spaces to add at the end
*/
public function setPad(string $item, int $max, int $extra = 2, int $indent = 0): string
{
$max += $extra + $indent;
return str_pad(str_repeat(' ', $indent) . $item, $max);
}
/**
* Get pad for $key => $value array output
*
* @param array<string, string> $array
*
* @deprecated Use setPad() instead.
*
* @codeCoverageIgnore
*/
public function getPad(array $array, int $pad): int
{
$max = 0;
foreach (array_keys($array) as $key) {
$max = max($max, strlen($key));
}
return $max + $pad;
}
/**
* Makes it simple to access our protected properties.
*
* @return array<string, string>|Commands|LoggerInterface|string|null
*/
public function __get(string $key)
{
return $this->{$key} ?? null;
}
/**
* Makes it simple to check our protected properties.
*/
public function __isset(string $key): bool
{
return isset($this->{$key});
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/CLI/Exceptions/CLIException.php | system/CLI/Exceptions/CLIException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\CLI\Exceptions;
use CodeIgniter\Exceptions\DebugTraceableTrait;
use CodeIgniter\Exceptions\RuntimeException;
/**
* CLIException
*/
class CLIException extends RuntimeException
{
use DebugTraceableTrait;
/**
* Thrown when `$color` specified for `$type` is not within the
* allowed list of colors.
*
* @return CLIException
*/
public static function forInvalidColor(string $type, string $color)
{
return new static(lang('CLI.invalidColor', [$type, $color]));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Throttle/Throttler.php | system/Throttle/Throttler.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Throttle;
use CodeIgniter\Cache\CacheInterface;
use CodeIgniter\I18n\Time;
/**
* Class Throttler
*
* Uses an implementation of the Token Bucket algorithm to implement a
* "rolling window" type of throttling that can be used for rate limiting
* an API or any other request.
*
* Each "token" in the "bucket" is equivalent to a single request
* for the purposes of this implementation.
*
* @see https://en.wikipedia.org/wiki/Token_bucket
*/
class Throttler implements ThrottlerInterface
{
/**
* Container for throttle counters.
*
* @var CacheInterface
*/
protected $cache;
/**
* The number of seconds until the next token is available.
*
* @var int
*/
protected $tokenTime = 0;
/**
* The prefix applied to all keys to
* minimize potential conflicts.
*
* @var string
*/
protected $prefix = 'throttler_';
/**
* Timestamp to use (during testing)
*
* @var int
*/
protected $testTime;
/**
* Constructor.
*/
public function __construct(CacheInterface $cache)
{
$this->cache = $cache;
}
/**
* Returns the number of seconds until the next available token will
* be released for usage.
*/
public function getTokenTime(): int
{
return $this->tokenTime;
}
/**
* Restricts the number of requests made by a single IP address within
* a set number of seconds.
*
* Example:
*
* if (! $throttler->check($request->ipAddress(), 60, MINUTE)) {
* die('You submitted over 60 requests within a minute.');
* }
*
* @param string $key The name to use as the "bucket" name.
* @param int $capacity The number of requests the "bucket" can hold
* @param int $seconds The time it takes the "bucket" to completely refill
* @param int $cost The number of tokens this action uses.
*
* @internal param int $maxRequests
*/
public function check(string $key, int $capacity, int $seconds, int $cost = 1): bool
{
$tokenName = $this->prefix . $key;
// Number of tokens to add back per second
$rate = $capacity / $seconds;
// Number of seconds to get one token
$refresh = 1 / $rate;
/** @var float|int|null $tokens */
$tokens = $this->cache->get($tokenName);
// Check to see if the bucket has even been created yet.
if ($tokens === null) {
// If it hasn't been created, then we'll set it to the maximum
// capacity - 1, and save it to the cache.
$tokens = $capacity - $cost;
$this->cache->save($tokenName, $tokens, $seconds);
$this->cache->save($tokenName . 'Time', $this->time(), $seconds);
$this->tokenTime = 0;
return true;
}
// If $tokens > 0, then we need to replenish the bucket
// based on how long it's been since the last update.
$throttleTime = $this->cache->get($tokenName . 'Time');
$elapsed = $this->time() - $throttleTime;
// Add tokens based up on number per second that
// should be refilled, then checked against capacity
// to be sure the bucket didn't overflow.
$tokens += $rate * $elapsed;
$tokens = min($tokens, $capacity);
// If $tokens >= 1, then we are safe to perform the action, but
// we need to decrement the number of available tokens.
if ($tokens >= 1) {
$tokens -= $cost;
$this->cache->save($tokenName, $tokens, $seconds);
$this->cache->save($tokenName . 'Time', $this->time(), $seconds);
$this->tokenTime = 0;
return true;
}
// How many seconds till a new token is available.
// We must have a minimum wait of 1 second for a new token.
// Primarily stored to allow devs to report back to users.
$newTokenAvailable = (int) round((1 - $tokens) * $refresh);
$this->tokenTime = max(1, $newTokenAvailable);
return false;
}
/**
* @param string $key The name of the bucket
*/
public function remove(string $key): self
{
$tokenName = $this->prefix . $key;
$this->cache->delete($tokenName);
$this->cache->delete($tokenName . 'Time');
return $this;
}
/**
* Used during testing to set the current timestamp to use.
*
* @return $this
*/
public function setTestTime(int $time)
{
$this->testTime = $time;
return $this;
}
/**
* Return the test time, defaulting to current.
*
* @TODO should be private
*/
public function time(): int
{
return $this->testTime ?? Time::now()->getTimestamp();
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Throttle/ThrottlerInterface.php | system/Throttle/ThrottlerInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Throttle;
/**
* Expected behavior of a Throttler
*/
interface ThrottlerInterface
{
/**
* Restricts the number of requests made by a single key within
* a set number of seconds.
*
* Example:
*
* if (! $throttler->checkIPAddress($request->ipAddress(), 60, MINUTE))
* {
* die('You submitted over 60 requests within a minute.');
* }
*
* @param string $key The name to use as the "bucket" name.
* @param int $capacity The number of requests the "bucket" can hold
* @param int $seconds The time it takes the "bucket" to completely refill
* @param int $cost The number of tokens this action uses.
*
* @return bool
*/
public function check(string $key, int $capacity, int $seconds, int $cost);
/**
* Returns the number of seconds until the next available token will
* be released for usage.
*/
public function getTokenTime(): int;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Router/RouteCollection.php | system/Router/RouteCollection.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Router;
use Closure;
use CodeIgniter\Autoloader\FileLocatorInterface;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\HTTP\Method;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Router\Exceptions\RouterException;
use Config\App;
use Config\Modules;
use Config\Routing;
/**
* @todo Implement nested resource routing (See CakePHP)
* @see \CodeIgniter\Router\RouteCollectionTest
*/
class RouteCollection implements RouteCollectionInterface
{
/**
* The namespace to be added to any Controllers.
* Defaults to the global namespaces (\).
*
* This must have a trailing backslash (\).
*
* @var string
*/
protected $defaultNamespace = '\\';
/**
* The name of the default controller to use
* when no other controller is specified.
*
* Not used here. Pass-thru value for Router class.
*
* @var string
*/
protected $defaultController = 'Home';
/**
* The name of the default method to use
* when no other method has been specified.
*
* Not used here. Pass-thru value for Router class.
*
* @var string
*/
protected $defaultMethod = 'index';
/**
* The placeholder used when routing 'resources'
* when no other placeholder has been specified.
*
* @var string
*/
protected $defaultPlaceholder = 'any';
/**
* Whether to convert dashes to underscores in URI.
*
* Not used here. Pass-thru value for Router class.
*
* @var bool
*/
protected $translateURIDashes = false;
/**
* Whether to match URI against Controllers
* when it doesn't match defined routes.
*
* Not used here. Pass-thru value for Router class.
*
* @var bool
*/
protected $autoRoute = false;
/**
* A callable that will be shown
* when the route cannot be matched.
*
* @var (Closure(string): (ResponseInterface|string|void))|string
*/
protected $override404;
/**
* An array of files that would contain route definitions.
*/
protected array $routeFiles = [];
/**
* Defined placeholders that can be used
* within the
*
* @var array<string, string>
*/
protected $placeholders = [
'any' => '.*',
'segment' => '[^/]+',
'alphanum' => '[a-zA-Z0-9]+',
'num' => '[0-9]+',
'alpha' => '[a-zA-Z]+',
'hash' => '[^/]+',
];
/**
* An array of all routes and their mappings.
*
* @var array
*
* [
* verb => [
* routeKey(regex) => [
* 'name' => routeName
* 'handler' => handler,
* 'from' => from,
* ],
* ],
* // redirect route
* '*' => [
* routeKey(regex)(from) => [
* 'name' => routeName
* 'handler' => [routeKey(regex)(to) => handler],
* 'from' => from,
* 'redirect' => statusCode,
* ],
* ],
* ]
*/
protected $routes = [
'*' => [],
Method::OPTIONS => [],
Method::GET => [],
Method::HEAD => [],
Method::POST => [],
Method::PATCH => [],
Method::PUT => [],
Method::DELETE => [],
Method::TRACE => [],
Method::CONNECT => [],
'CLI' => [],
];
/**
* Array of routes names
*
* @var array
*
* [
* verb => [
* routeName => routeKey(regex)
* ],
* ]
*/
protected $routesNames = [
'*' => [],
Method::OPTIONS => [],
Method::GET => [],
Method::HEAD => [],
Method::POST => [],
Method::PATCH => [],
Method::PUT => [],
Method::DELETE => [],
Method::TRACE => [],
Method::CONNECT => [],
'CLI' => [],
];
/**
* Array of routes options
*
* @var array
*
* [
* verb => [
* routeKey(regex) => [
* key => value,
* ]
* ],
* ]
*/
protected $routesOptions = [];
/**
* The current method that the script is being called by.
*
* @var string HTTP verb like `GET`,`POST` or `*` or `CLI`
*/
protected $HTTPVerb = '*';
/**
* The default list of HTTP methods (and CLI for command line usage)
* that is allowed if no other method is provided.
*
* @var list<string>
*/
public $defaultHTTPMethods = Router::HTTP_METHODS;
/**
* The name of the current group, if any.
*
* @var string|null
*/
protected $group;
/**
* The current subdomain.
*
* @var string|null
*/
protected $currentSubdomain;
/**
* Stores copy of current options being
* applied during creation.
*
* @var array|null
*/
protected $currentOptions;
/**
* A little performance booster.
*
* @var bool
*/
protected $didDiscover = false;
/**
* Handle to the file locator to use.
*
* @var FileLocatorInterface
*/
protected $fileLocator;
/**
* Handle to the modules config.
*
* @var Modules
*/
protected $moduleConfig;
/**
* Flag for sorting routes by priority.
*
* @var bool
*/
protected $prioritize = false;
/**
* Route priority detection flag.
*
* @var bool
*/
protected $prioritizeDetected = false;
/**
* The current hostname from $_SERVER['HTTP_HOST']
*/
private ?string $httpHost = null;
/**
* Flag to limit or not the routes with {locale} placeholder to App::$supportedLocales
*/
protected bool $useSupportedLocalesOnly = false;
/**
* Constructor
*/
public function __construct(FileLocatorInterface $locator, Modules $moduleConfig, Routing $routing)
{
$this->fileLocator = $locator;
$this->moduleConfig = $moduleConfig;
$this->httpHost = service('request')->getServer('HTTP_HOST');
// Setup based on config file. Let routes file override.
$this->defaultNamespace = rtrim($routing->defaultNamespace, '\\') . '\\';
$this->defaultController = $routing->defaultController;
$this->defaultMethod = $routing->defaultMethod;
$this->translateURIDashes = $routing->translateURIDashes;
$this->override404 = $routing->override404;
$this->autoRoute = $routing->autoRoute;
$this->routeFiles = $routing->routeFiles;
$this->prioritize = $routing->prioritize;
// Normalize the path string in routeFiles array.
foreach ($this->routeFiles as $routeKey => $routesFile) {
$realpath = realpath($routesFile);
$this->routeFiles[$routeKey] = ($realpath === false) ? $routesFile : $realpath;
}
}
/**
* Loads main routes file and discover routes.
*
* Loads only once unless reset.
*
* @return $this
*/
public function loadRoutes(string $routesFile = APPPATH . 'Config/Routes.php')
{
if ($this->didDiscover) {
return $this;
}
// Normalize the path string in routesFile
$realpath = realpath($routesFile);
$routesFile = ($realpath === false) ? $routesFile : $realpath;
// Include the passed in routesFile if it doesn't exist.
// Only keeping that around for BC purposes for now.
$routeFiles = $this->routeFiles;
if (! in_array($routesFile, $routeFiles, true)) {
$routeFiles[] = $routesFile;
}
// We need this var in local scope
// so route files can access it.
$routes = $this;
foreach ($routeFiles as $routesFile) {
if (! is_file($routesFile)) {
log_message('warning', sprintf('Routes file not found: "%s"', $routesFile));
continue;
}
require $routesFile;
}
$this->discoverRoutes();
return $this;
}
/**
* Will attempt to discover any additional routes, either through
* the local PSR4 namespaces, or through selected Composer packages.
*
* @return void
*/
protected function discoverRoutes()
{
if ($this->didDiscover) {
return;
}
// We need this var in local scope
// so route files can access it.
$routes = $this;
if ($this->moduleConfig->shouldDiscover('routes')) {
$files = $this->fileLocator->search('Config/Routes.php');
foreach ($files as $file) {
// Don't include our main file again...
if (in_array($file, $this->routeFiles, true)) {
continue;
}
include $file;
}
}
$this->didDiscover = true;
}
/**
* Registers a new constraint with the system. Constraints are used
* by the routes as placeholders for regular expressions to make defining
* the routes more human-friendly.
*
* You can pass an associative array as $placeholder, and have
* multiple placeholders added at once.
*
* @param array|string $placeholder
*/
public function addPlaceholder($placeholder, ?string $pattern = null): RouteCollectionInterface
{
if (! is_array($placeholder)) {
$placeholder = [$placeholder => $pattern];
}
$this->placeholders = array_merge($this->placeholders, $placeholder);
return $this;
}
/**
* For `spark routes`
*
* @return array<string, string>
*
* @internal
*/
public function getPlaceholders(): array
{
return $this->placeholders;
}
/**
* Sets the default namespace to use for Controllers when no other
* namespace has been specified.
*/
public function setDefaultNamespace(string $value): RouteCollectionInterface
{
$this->defaultNamespace = esc(strip_tags($value));
$this->defaultNamespace = rtrim($this->defaultNamespace, '\\') . '\\';
return $this;
}
/**
* Sets the default controller to use when no other controller has been
* specified.
*/
public function setDefaultController(string $value): RouteCollectionInterface
{
$this->defaultController = esc(strip_tags($value));
return $this;
}
/**
* Sets the default method to call on the controller when no other
* method has been set in the route.
*/
public function setDefaultMethod(string $value): RouteCollectionInterface
{
$this->defaultMethod = esc(strip_tags($value));
return $this;
}
/**
* Tells the system whether to convert dashes in URI strings into
* underscores. In some search engines, including Google, dashes
* create more meaning and make it easier for the search engine to
* find words and meaning in the URI for better SEO. But it
* doesn't work well with PHP method names....
*/
public function setTranslateURIDashes(bool $value): RouteCollectionInterface
{
$this->translateURIDashes = $value;
return $this;
}
/**
* If TRUE, the system will attempt to match the URI against
* Controllers by matching each segment against folders/files
* in APPPATH/Controllers, when a match wasn't found against
* defined routes.
*
* If FALSE, will stop searching and do NO automatic routing.
*/
public function setAutoRoute(bool $value): RouteCollectionInterface
{
$this->autoRoute = $value;
return $this;
}
/**
* Sets the class/method that should be called if routing doesn't
* find a match. It can be either a closure or the controller/method
* name exactly like a route is defined: Users::index
*
* This setting is passed to the Router class and handled there.
*
* @param callable|string|null $callable
*/
public function set404Override($callable = null): RouteCollectionInterface
{
$this->override404 = $callable;
return $this;
}
/**
* Returns the 404 Override setting, which can be null, a closure
* or the controller/string.
*
* @return (Closure(string): (ResponseInterface|string|void))|string|null
*/
public function get404Override()
{
return $this->override404;
}
/**
* Sets the default constraint to be used in the system. Typically
* for use with the 'resource' method.
*/
public function setDefaultConstraint(string $placeholder): RouteCollectionInterface
{
if (array_key_exists($placeholder, $this->placeholders)) {
$this->defaultPlaceholder = $placeholder;
}
return $this;
}
/**
* Returns the name of the default controller. With Namespace.
*/
public function getDefaultController(): string
{
return $this->defaultController;
}
/**
* Returns the name of the default method to use within the controller.
*/
public function getDefaultMethod(): string
{
return $this->defaultMethod;
}
/**
* Returns the default namespace as set in the Routes config file.
*/
public function getDefaultNamespace(): string
{
return $this->defaultNamespace;
}
/**
* Returns the current value of the translateURIDashes setting.
*/
public function shouldTranslateURIDashes(): bool
{
return $this->translateURIDashes;
}
/**
* Returns the flag that tells whether to autoRoute URI against Controllers.
*/
public function shouldAutoRoute(): bool
{
return $this->autoRoute;
}
/**
* Returns the raw array of available routes.
*
* @param non-empty-string|null $verb HTTP verb like `GET`,`POST` or `*` or `CLI`.
* @param bool $includeWildcard Whether to include '*' routes.
*/
public function getRoutes(?string $verb = null, bool $includeWildcard = true): array
{
if ((string) $verb === '') {
$verb = $this->getHTTPVerb();
}
// Since this is the entry point for the Router,
// take a moment to do any route discovery
// we might need to do.
$this->discoverRoutes();
$routes = [];
if (isset($this->routes[$verb])) {
// Keep current verb's routes at the beginning, so they're matched
// before any of the generic, "add" routes.
$collection = $includeWildcard ? $this->routes[$verb] + ($this->routes['*'] ?? []) : $this->routes[$verb];
foreach ($collection as $routeKey => $r) {
$routes[$routeKey] = $r['handler'];
}
}
// sorting routes by priority
if ($this->prioritizeDetected && $this->prioritize && $routes !== []) {
$order = [];
foreach ($routes as $key => $value) {
$key = $key === '/' ? $key : ltrim($key, '/ ');
$priority = $this->getRoutesOptions($key, $verb)['priority'] ?? 0;
$order[$priority][$key] = $value;
}
ksort($order);
$routes = array_merge(...$order);
}
return $routes;
}
/**
* Returns one or all routes options
*
* @param string|null $verb HTTP verb like `GET`,`POST` or `*` or `CLI`.
*
* @return array<string, int|string> [key => value]
*/
public function getRoutesOptions(?string $from = null, ?string $verb = null): array
{
$options = $this->loadRoutesOptions($verb);
return ((string) $from !== '') ? $options[$from] ?? [] : $options;
}
/**
* Returns the current HTTP Verb being used.
*/
public function getHTTPVerb(): string
{
return $this->HTTPVerb;
}
/**
* Sets the current HTTP verb.
* Used primarily for testing.
*
* @param string $verb HTTP verb
*
* @return $this
*/
public function setHTTPVerb(string $verb)
{
if ($verb !== '*' && $verb === strtolower($verb)) {
@trigger_error(
'Passing lowercase HTTP method "' . $verb . '" is deprecated.'
. ' Use uppercase HTTP method like "' . strtoupper($verb) . '".',
E_USER_DEPRECATED,
);
}
/**
* @deprecated 4.5.0
* @TODO Remove strtoupper() in the future.
*/
$this->HTTPVerb = strtoupper($verb);
return $this;
}
/**
* A shortcut method to add a number of routes at a single time.
* It does not allow any options to be set on the route, or to
* define the method used.
*/
public function map(array $routes = [], ?array $options = null): RouteCollectionInterface
{
foreach ($routes as $from => $to) {
$this->add($from, $to, $options);
}
return $this;
}
/**
* Adds a single route to the collection.
*
* Example:
* $routes->add('news', 'Posts::index');
*
* @param array|(Closure(mixed...): (ResponseInterface|string|void))|string $to
*/
public function add(string $from, $to, ?array $options = null): RouteCollectionInterface
{
$this->create('*', $from, $to, $options);
return $this;
}
/**
* Adds a temporary redirect from one route to another. Used for
* redirecting traffic from old, non-existing routes to the new
* moved routes.
*
* @param string $from The pattern to match against
* @param string $to Either a route name or a URI to redirect to
* @param int $status The HTTP status code that should be returned with this redirect
*
* @return RouteCollection
*/
public function addRedirect(string $from, string $to, int $status = 302)
{
// Use the named route's pattern if this is a named route.
if (array_key_exists($to, $this->routesNames['*'])) {
$routeName = $to;
$routeKey = $this->routesNames['*'][$routeName];
$redirectTo = [$routeKey => $this->routes['*'][$routeKey]['handler']];
} elseif (array_key_exists($to, $this->routesNames[Method::GET])) {
$routeName = $to;
$routeKey = $this->routesNames[Method::GET][$routeName];
$redirectTo = [$routeKey => $this->routes[Method::GET][$routeKey]['handler']];
} else {
// The named route is not found.
$redirectTo = $to;
}
$this->create('*', $from, $redirectTo, ['redirect' => $status]);
return $this;
}
/**
* Determines if the route is a redirecting route.
*
* @param string $routeKey routeKey or route name
*/
public function isRedirect(string $routeKey): bool
{
if (isset($this->routes['*'][$routeKey]['redirect'])) {
return true;
}
// This logic is not used. Should be deprecated?
$routeName = $this->routes['*'][$routeKey]['name'] ?? null;
if ($routeName === $routeKey) {
$routeKey = $this->routesNames['*'][$routeName];
return isset($this->routes['*'][$routeKey]['redirect']);
}
return false;
}
/**
* Grabs the HTTP status code from a redirecting Route.
*
* @param string $routeKey routeKey or route name
*/
public function getRedirectCode(string $routeKey): int
{
if (isset($this->routes['*'][$routeKey]['redirect'])) {
return $this->routes['*'][$routeKey]['redirect'];
}
// This logic is not used. Should be deprecated?
$routeName = $this->routes['*'][$routeKey]['name'] ?? null;
if ($routeName === $routeKey) {
$routeKey = $this->routesNames['*'][$routeName];
return $this->routes['*'][$routeKey]['redirect'];
}
return 0;
}
/**
* Group a series of routes under a single URL segment. This is handy
* for grouping items into an admin area, like:
*
* Example:
* // Creates route: admin/users
* $route->group('admin', function() {
* $route->resource('users');
* });
*
* @param string $name The name to group/prefix the routes with.
* @param array|callable ...$params
*
* @return void
*/
public function group(string $name, ...$params)
{
$oldGroup = $this->group;
$oldOptions = $this->currentOptions;
// To register a route, we'll set a flag so that our router
// will see the group name.
// If the group name is empty, we go on using the previously built group name.
$this->group = $name !== '' ? trim($oldGroup . '/' . $name, '/') : $oldGroup;
$callback = array_pop($params);
if ($params !== [] && is_array($params[0])) {
$options = array_shift($params);
if (isset($options['filter'])) {
// Merge filters.
$currentFilter = (array) ($this->currentOptions['filter'] ?? []);
$options['filter'] = array_merge($currentFilter, (array) $options['filter']);
}
// Merge options other than filters.
$this->currentOptions = array_merge(
$this->currentOptions ?? [],
$options,
);
}
if (is_callable($callback)) {
$callback($this);
}
$this->group = $oldGroup;
$this->currentOptions = $oldOptions;
}
/*
* --------------------------------------------------------------------
* HTTP Verb-based routing
* --------------------------------------------------------------------
* Routing works here because, as the routes Config file is read in,
* the various HTTP verb-based routes will only be added to the in-memory
* routes if it is a call that should respond to that verb.
*
* The options array is typically used to pass in an 'as' or var, but may
* be expanded in the future. See the docblock for 'add' method above for
* current list of globally available options.
*/
/**
* Creates a collections of HTTP-verb based routes for a controller.
*
* Possible Options:
* 'controller' - Customize the name of the controller used in the 'to' route
* 'placeholder' - The regex used by the Router. Defaults to '(:any)'
* 'websafe' - - '1' if only GET and POST HTTP verbs are supported
*
* Example:
*
* $route->resource('photos');
*
* // Generates the following routes:
* HTTP Verb | Path | Action | Used for...
* ----------+-------------+---------------+-----------------
* GET /photos index an array of photo objects
* GET /photos/new new an empty photo object, with default properties
* GET /photos/{id}/edit edit a specific photo object, editable properties
* GET /photos/{id} show a specific photo object, all properties
* POST /photos create a new photo object, to add to the resource
* DELETE /photos/{id} delete deletes the specified photo object
* PUT/PATCH /photos/{id} update replacement properties for existing photo
*
* If 'websafe' option is present, the following paths are also available:
*
* POST /photos/{id}/delete delete
* POST /photos/{id} update
*
* @param string $name The name of the resource/controller to route to.
* @param array|null $options A list of possible ways to customize the routing.
*/
public function resource(string $name, ?array $options = null): RouteCollectionInterface
{
// In order to allow customization of the route the
// resources are sent to, we need to have a new name
// to store the values in.
$newName = implode('\\', array_map(ucfirst(...), explode('/', $name)));
// If a new controller is specified, then we replace the
// $name value with the name of the new controller.
if (isset($options['controller'])) {
$newName = ucfirst(esc(strip_tags($options['controller'])));
}
// In order to allow customization of allowed id values
// we need someplace to store them.
$id = $options['placeholder'] ?? $this->placeholders[$this->defaultPlaceholder] ?? '(:segment)';
// Make sure we capture back-references
$id = '(' . trim($id, '()') . ')';
$methods = isset($options['only']) ? (is_string($options['only']) ? explode(',', $options['only']) : $options['only']) : ['index', 'show', 'create', 'update', 'delete', 'new', 'edit'];
if (isset($options['except'])) {
$options['except'] = is_array($options['except']) ? $options['except'] : explode(',', $options['except']);
foreach ($methods as $i => $method) {
if (in_array($method, $options['except'], true)) {
unset($methods[$i]);
}
}
}
if (in_array('index', $methods, true)) {
$this->get($name, $newName . '::index', $options);
}
if (in_array('new', $methods, true)) {
$this->get($name . '/new', $newName . '::new', $options);
}
if (in_array('edit', $methods, true)) {
$this->get($name . '/' . $id . '/edit', $newName . '::edit/$1', $options);
}
if (in_array('show', $methods, true)) {
$this->get($name . '/' . $id, $newName . '::show/$1', $options);
}
if (in_array('create', $methods, true)) {
$this->post($name, $newName . '::create', $options);
}
if (in_array('update', $methods, true)) {
$this->put($name . '/' . $id, $newName . '::update/$1', $options);
$this->patch($name . '/' . $id, $newName . '::update/$1', $options);
}
if (in_array('delete', $methods, true)) {
$this->delete($name . '/' . $id, $newName . '::delete/$1', $options);
}
// Web Safe? delete needs checking before update because of method name
if (isset($options['websafe'])) {
if (in_array('delete', $methods, true)) {
$this->post($name . '/' . $id . '/delete', $newName . '::delete/$1', $options);
}
if (in_array('update', $methods, true)) {
$this->post($name . '/' . $id, $newName . '::update/$1', $options);
}
}
return $this;
}
/**
* Creates a collections of HTTP-verb based routes for a presenter controller.
*
* Possible Options:
* 'controller' - Customize the name of the controller used in the 'to' route
* 'placeholder' - The regex used by the Router. Defaults to '(:any)'
*
* Example:
*
* $route->presenter('photos');
*
* // Generates the following routes:
* HTTP Verb | Path | Action | Used for...
* ----------+-------------+---------------+-----------------
* GET /photos index showing all array of photo objects
* GET /photos/show/{id} show showing a specific photo object, all properties
* GET /photos/new new showing a form for an empty photo object, with default properties
* POST /photos/create create processing the form for a new photo
* GET /photos/edit/{id} edit show an editing form for a specific photo object, editable properties
* POST /photos/update/{id} update process the editing form data
* GET /photos/remove/{id} remove show a form to confirm deletion of a specific photo object
* POST /photos/delete/{id} delete deleting the specified photo object
*
* @param string $name The name of the controller to route to.
* @param array|null $options A list of possible ways to customize the routing.
*/
public function presenter(string $name, ?array $options = null): RouteCollectionInterface
{
// In order to allow customization of the route the
// resources are sent to, we need to have a new name
// to store the values in.
$newName = implode('\\', array_map(ucfirst(...), explode('/', $name)));
// If a new controller is specified, then we replace the
// $name value with the name of the new controller.
if (isset($options['controller'])) {
$newName = ucfirst(esc(strip_tags($options['controller'])));
}
// In order to allow customization of allowed id values
// we need someplace to store them.
$id = $options['placeholder'] ?? $this->placeholders[$this->defaultPlaceholder] ?? '(:segment)';
// Make sure we capture back-references
$id = '(' . trim($id, '()') . ')';
$methods = isset($options['only']) ? (is_string($options['only']) ? explode(',', $options['only']) : $options['only']) : ['index', 'show', 'new', 'create', 'edit', 'update', 'remove', 'delete'];
if (isset($options['except'])) {
$options['except'] = is_array($options['except']) ? $options['except'] : explode(',', $options['except']);
foreach ($methods as $i => $method) {
if (in_array($method, $options['except'], true)) {
unset($methods[$i]);
}
}
}
if (in_array('index', $methods, true)) {
$this->get($name, $newName . '::index', $options);
}
if (in_array('show', $methods, true)) {
$this->get($name . '/show/' . $id, $newName . '::show/$1', $options);
}
if (in_array('new', $methods, true)) {
$this->get($name . '/new', $newName . '::new', $options);
}
if (in_array('create', $methods, true)) {
$this->post($name . '/create', $newName . '::create', $options);
}
if (in_array('edit', $methods, true)) {
$this->get($name . '/edit/' . $id, $newName . '::edit/$1', $options);
}
if (in_array('update', $methods, true)) {
$this->post($name . '/update/' . $id, $newName . '::update/$1', $options);
}
if (in_array('remove', $methods, true)) {
$this->get($name . '/remove/' . $id, $newName . '::remove/$1', $options);
}
if (in_array('delete', $methods, true)) {
$this->post($name . '/delete/' . $id, $newName . '::delete/$1', $options);
}
if (in_array('show', $methods, true)) {
$this->get($name . '/' . $id, $newName . '::show/$1', $options);
}
if (in_array('create', $methods, true)) {
$this->post($name, $newName . '::create', $options);
}
return $this;
}
/**
* Specifies a single route to match for multiple HTTP Verbs.
*
* Example:
* $route->match( ['GET', 'POST'], 'users/(:num)', 'users/$1);
*
* @param array|(Closure(mixed...): (ResponseInterface|string|void))|string $to
*/
public function match(array $verbs = [], string $from = '', $to = '', ?array $options = null): RouteCollectionInterface
{
if ($from === '' || empty($to)) {
throw new InvalidArgumentException('You must supply the parameters: from, to.');
}
foreach ($verbs as $verb) {
if ($verb === strtolower($verb)) {
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | true |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Router/DefinedRouteCollector.php | system/Router/DefinedRouteCollector.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Router;
use Closure;
use Generator;
/**
* Collect all defined routes for display.
*
* @see \CodeIgniter\Router\DefinedRouteCollectorTest
*/
final class DefinedRouteCollector
{
public function __construct(private readonly RouteCollectionInterface $routeCollection)
{
}
/**
* @return Generator<array{method: string, route: string, name: string, handler: string}>
*/
public function collect(): Generator
{
$methods = Router::HTTP_METHODS;
foreach ($methods as $method) {
$routes = $this->routeCollection->getRoutes($method);
foreach ($routes as $route => $handler) {
// The route key should be a string, but it is stored as an array key,
// it might be an integer.
$route = (string) $route;
if (is_string($handler) || $handler instanceof Closure) {
if ($handler instanceof Closure) {
$view = $this->routeCollection->getRoutesOptions($route, $method)['view'] ?? false;
$handler = $view ? '(View) ' . $view : '(Closure)';
}
$routeName = $this->routeCollection->getRoutesOptions($route, $method)['as'] ?? $route;
yield [
'method' => $method,
'route' => $route,
'name' => $routeName,
'handler' => $handler,
];
}
}
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Router/RouterInterface.php | system/Router/RouterInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Router;
use Closure;
use CodeIgniter\HTTP\Request;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Expected behavior of a Router.
*/
interface RouterInterface
{
/**
* Stores a reference to the RouteCollection object.
*/
public function __construct(RouteCollectionInterface $routes, ?Request $request = null);
/**
* Finds the controller method corresponding to the URI.
*
* @param string|null $uri URI path relative to baseURL
*
* @return (Closure(mixed...): (ResponseInterface|string|void))|string Controller classname or Closure
*/
public function handle(?string $uri = null);
/**
* Returns the name of the matched controller.
*
* @return (Closure(mixed...): (ResponseInterface|string|void))|string Controller classname or Closure
*/
public function controllerName();
/**
* Returns the name of the method in the controller to run.
*
* @return string
*/
public function methodName();
/**
* Returns the binds that have been matched and collected
* during the parsing process as an array, ready to send to
* instance->method(...$params).
*
* @return array
*/
public function params();
/**
* Sets the value that should be used to match the index.php file. Defaults
* to index.php but this allows you to modify it in case you are using
* something like mod_rewrite to remove the page. This allows you to set
* it a blank.
*
* @param string $page
*
* @return RouterInterface
*/
public function setIndexPage($page);
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Router/RouteCollectionInterface.php | system/Router/RouteCollectionInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Router;
use Closure;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Interface RouteCollectionInterface
*
* A Route Collection's sole job is to hold a series of routes. The required
* number of methods is kept very small on purpose, but implementors may
* add a number of additional methods to customize how the routes are defined.
*/
interface RouteCollectionInterface
{
/**
* Adds a single route to the collection.
*
* @param string $from The route path (with placeholders or regex)
* @param array|(Closure(mixed...): (ResponseInterface|string|void))|string $to The route handler
* @param array|null $options The route options
*
* @return RouteCollectionInterface
*/
public function add(string $from, $to, ?array $options = null);
/**
* Registers a new constraint with the system. Constraints are used
* by the routes as placeholders for regular expressions to make defining
* the routes more human-friendly.
*
* You can pass an associative array as $placeholder, and have
* multiple placeholders added at once.
*
* @param array|string $placeholder
* @param string|null $pattern The regex pattern
*
* @return RouteCollectionInterface
*/
public function addPlaceholder($placeholder, ?string $pattern = null);
/**
* Sets the default namespace to use for Controllers when no other
* namespace has been specified.
*
* @return RouteCollectionInterface
*/
public function setDefaultNamespace(string $value);
/**
* Returns the default namespace.
*/
public function getDefaultNamespace(): string;
/**
* Sets the default controller to use when no other controller has been
* specified.
*
* @return RouteCollectionInterface
*
* @TODO The default controller is only for auto-routing. So this should be
* removed in the future.
*/
public function setDefaultController(string $value);
/**
* Sets the default method to call on the controller when no other
* method has been set in the route.
*
* @return RouteCollectionInterface
*/
public function setDefaultMethod(string $value);
/**
* Tells the system whether to convert dashes in URI strings into
* underscores. In some search engines, including Google, dashes
* create more meaning and make it easier for the search engine to
* find words and meaning in the URI for better SEO. But it
* doesn't work well with PHP method names....
*
* @return RouteCollectionInterface
*
* @TODO This method is only for auto-routing. So this should be removed in
* the future.
*/
public function setTranslateURIDashes(bool $value);
/**
* If TRUE, the system will attempt to match the URI against
* Controllers by matching each segment against folders/files
* in APPPATH/Controllers, when a match wasn't found against
* defined routes.
*
* If FALSE, will stop searching and do NO automatic routing.
*
* @TODO This method is only for auto-routing. So this should be removed in
* the future.
*/
public function setAutoRoute(bool $value): self;
/**
* Sets the class/method that should be called if routing doesn't
* find a match. It can be either a closure or the controller/method
* name exactly like a route is defined: Users::index
*
* This setting is passed to the Router class and handled there.
*
* @param callable|null $callable
*
* @TODO This method is not related to the route collection. So this should
* be removed in the future.
*/
public function set404Override($callable = null): self;
/**
* Returns the 404 Override setting, which can be null, a closure
* or the controller/string.
*
* @return (Closure(string): (ResponseInterface|string|void))|string|null
*
* @TODO This method is not related to the route collection. So this should
* be removed in the future.
*/
public function get404Override();
/**
* Returns the name of the default controller. With Namespace.
*
* @return string
*
* @TODO The default controller is only for auto-routing. So this should be
* removed in the future.
*/
public function getDefaultController();
/**
* Returns the name of the default method to use within the controller.
*
* @return string
*/
public function getDefaultMethod();
/**
* Returns the current value of the translateURIDashes setting.
*
* @return bool
*
* @TODO This method is only for auto-routing. So this should be removed in
* the future.
*/
public function shouldTranslateURIDashes();
/**
* Returns the flag that tells whether to autoRoute URI against Controllers.
*
* @return bool
*
* @TODO This method is only for auto-routing. So this should be removed in
* the future.
*/
public function shouldAutoRoute();
/**
* Returns the raw array of available routes.
*
* @param non-empty-string|null $verb HTTP verb like `GET`,`POST` or `*` or `CLI`.
* @param bool $includeWildcard Whether to include '*' routes.
*/
public function getRoutes(?string $verb = null, bool $includeWildcard = true): array;
/**
* Returns one or all routes options
*
* @param string|null $from The route path (with placeholders or regex)
* @param string|null $verb HTTP verb like `GET`,`POST` or `*` or `CLI`.
*
* @return array<string, int|string> [key => value]
*/
public function getRoutesOptions(?string $from = null, ?string $verb = null): array;
/**
* Sets the current HTTP verb.
*
* @param string $verb HTTP verb
*
* @return $this
*/
public function setHTTPVerb(string $verb);
/**
* Returns the current HTTP Verb being used.
*
* @return string
*/
public function getHTTPVerb();
/**
* Attempts to look up a route based on its destination.
*
* If a route exists:
*
* 'path/(:any)/(:any)' => 'Controller::method/$1/$2'
*
* This method allows you to know the Controller and method
* and get the route that leads to it.
*
* // Equals 'path/$param1/$param2'
* reverseRoute('Controller::method', $param1, $param2);
*
* @param string $search Named route or Controller::method
* @param int|string ...$params
*
* @return false|string The route (URI path relative to baseURL) or false if not found.
*/
public function reverseRoute(string $search, ...$params);
/**
* Determines if the route is a redirecting route.
*/
public function isRedirect(string $routeKey): bool;
/**
* Grabs the HTTP status code from a redirecting Route.
*/
public function getRedirectCode(string $routeKey): int;
/**
* Get the flag that limit or not the routes with {locale} placeholder to App::$supportedLocales
*/
public function shouldUseSupportedLocalesOnly(): bool;
/**
* Checks a route (using the "from") to see if it's filtered or not.
*
* @param string|null $verb HTTP verb like `GET`,`POST` or `*` or `CLI`.
*/
public function isFiltered(string $search, ?string $verb = null): bool;
/**
* Returns the filters that should be applied for a single route, along
* with any parameters it might have. Parameters are found by splitting
* the parameter name on a colon to separate the filter name from the parameter list,
* and the splitting the result on commas. So:
*
* 'role:admin,manager'
*
* has a filter of "role", with parameters of ['admin', 'manager'].
*
* @param string $search routeKey
* @param string|null $verb HTTP verb like `GET`,`POST` or `*` or `CLI`.
*
* @return list<string> filter_name or filter_name:arguments like 'role:admin,manager'
*/
public function getFiltersForRoute(string $search, ?string $verb = null): array;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Router/AutoRouter.php | system/Router/AutoRouter.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Router;
use Closure;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Router for Auto-Routing
*/
final class AutoRouter implements AutoRouterInterface
{
/**
* Sub-directory that contains the requested controller class.
* Primarily used by 'autoRoute'.
*/
private ?string $directory = null;
public function __construct(
/**
* List of CLI routes that do not contain '*' routes.
*
* @var array<string, (Closure(mixed...): (ResponseInterface|string|void))|string> [routeKey => handler]
*/
private readonly array $cliRoutes,
/**
* Default namespace for controllers.
*/
private readonly string $defaultNamespace,
/**
* The name of the controller class.
*/
private string $controller,
/**
* The name of the method to use.
*/
private string $method,
/**
* Whether dashes in URI's should be converted
* to underscores when determining method names.
*/
private bool $translateURIDashes,
) {
}
/**
* Attempts to match a URI path against Controllers and directories
* found in APPPATH/Controllers, to find a matching route.
*
* @param string $httpVerb HTTP verb like `GET`,`POST`
*
* @return array [directory_name, controller_name, controller_method, params]
*/
public function getRoute(string $uri, string $httpVerb): array
{
$segments = explode('/', $uri);
// WARNING: Directories get shifted out of the segments array.
$segments = $this->scanControllers($segments);
// If we don't have any segments left - use the default controller;
// If not empty, then the first segment should be the controller
if ($segments !== []) {
$this->controller = ucfirst(array_shift($segments));
}
$controllerName = $this->controllerName();
if (! $this->isValidSegment($controllerName)) {
throw new PageNotFoundException($this->controller . ' is not a valid controller name');
}
// Use the method name if it exists.
// If it doesn't, no biggie - the default method name
// has already been set.
if ($segments !== []) {
$this->method = array_shift($segments) ?: $this->method;
}
// Prevent access to initController method
if (strtolower($this->method) === 'initcontroller') {
throw PageNotFoundException::forPageNotFound();
}
/** @var array $params An array of params to the controller method. */
$params = [];
if ($segments !== []) {
$params = $segments;
}
// Ensure routes registered via $routes->cli() are not accessible via web.
if ($httpVerb !== 'CLI') {
$controller = '\\' . $this->defaultNamespace;
$controller .= $this->directory !== null ? str_replace('/', '\\', $this->directory) : '';
$controller .= $controllerName;
$controller = strtolower($controller);
$methodName = strtolower($this->methodName());
foreach ($this->cliRoutes as $handler) {
if (is_string($handler)) {
$handler = strtolower($handler);
// Like $routes->cli('hello/(:segment)', 'Home::$1')
if (str_contains($handler, '::$')) {
throw new PageNotFoundException(
'Cannot access CLI Route: ' . $uri,
);
}
if (str_starts_with($handler, $controller . '::' . $methodName)) {
throw new PageNotFoundException(
'Cannot access CLI Route: ' . $uri,
);
}
if ($handler === $controller) {
throw new PageNotFoundException(
'Cannot access CLI Route: ' . $uri,
);
}
}
}
}
// Load the file so that it's available for CodeIgniter.
$file = APPPATH . 'Controllers/' . $this->directory . $controllerName . '.php';
if (! is_file($file)) {
throw PageNotFoundException::forControllerNotFound($this->controller, $this->method);
}
include_once $file;
// Ensure the controller stores the fully-qualified class name
// We have to check for a length over 1, since by default it will be '\'
if (! str_contains($this->controller, '\\') && strlen($this->defaultNamespace) > 1) {
$this->controller = '\\' . ltrim(
str_replace(
'/',
'\\',
$this->defaultNamespace . $this->directory . $controllerName,
),
'\\',
);
}
return [$this->directory, $this->controllerName(), $this->methodName(), $params];
}
/**
* Tells the system whether we should translate URI dashes or not
* in the URI from a dash to an underscore.
*
* @deprecated This method should be removed.
*/
public function setTranslateURIDashes(bool $val = false): self
{
$this->translateURIDashes = $val;
return $this;
}
/**
* Scans the controller directory, attempting to locate a controller matching the supplied uri $segments
*
* @param array $segments URI segments
*
* @return array returns an array of remaining uri segments that don't map onto a directory
*/
private function scanControllers(array $segments): array
{
$segments = array_filter($segments, static fn ($segment): bool => $segment !== '');
// numerically reindex the array, removing gaps
$segments = array_values($segments);
// if a prior directory value has been set, just return segments and get out of here
if (isset($this->directory)) {
return $segments;
}
// Loop through our segments and return as soon as a controller
// is found or when such a directory doesn't exist
$c = count($segments);
while ($c-- > 0) {
$segmentConvert = ucfirst(
$this->translateURIDashes ? str_replace('-', '_', $segments[0]) : $segments[0],
);
// as soon as we encounter any segment that is not PSR-4 compliant, stop searching
if (! $this->isValidSegment($segmentConvert)) {
return $segments;
}
$test = APPPATH . 'Controllers/' . $this->directory . $segmentConvert;
// as long as each segment is *not* a controller file but does match a directory, add it to $this->directory
if (! is_file($test . '.php') && is_dir($test)) {
$this->setDirectory($segmentConvert, true, false);
array_shift($segments);
continue;
}
return $segments;
}
// This means that all segments were actually directories
return $segments;
}
/**
* Returns true if the supplied $segment string represents a valid PSR-4 compliant namespace/directory segment
*
* regex comes from https://www.php.net/manual/en/language.variables.basics.php
*/
private function isValidSegment(string $segment): bool
{
return (bool) preg_match('/^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$/', $segment);
}
/**
* Sets the sub-directory that the controller is in.
*
* @param bool $validate if true, checks to make sure $dir consists of only PSR4 compliant segments
*
* @deprecated This method should be removed.
*
* @return void
*/
public function setDirectory(?string $dir = null, bool $append = false, bool $validate = true)
{
if ((string) $dir === '') {
$this->directory = null;
return;
}
if ($validate) {
$segments = explode('/', trim($dir, '/'));
foreach ($segments as $segment) {
if (! $this->isValidSegment($segment)) {
return;
}
}
}
if (! $append || ((string) $this->directory === '')) {
$this->directory = trim($dir, '/') . '/';
} else {
$this->directory .= trim($dir, '/') . '/';
}
}
/**
* Returns the name of the sub-directory the controller is in,
* if any. Relative to APPPATH.'Controllers'.
*
* @deprecated This method should be removed.
*/
public function directory(): string
{
return ((string) $this->directory !== '') ? $this->directory : '';
}
private function controllerName(): string
{
return $this->translateURIDashes
? str_replace('-', '_', $this->controller)
: $this->controller;
}
private function methodName(): string
{
return $this->translateURIDashes
? str_replace('-', '_', $this->method)
: $this->method;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Router/Router.php | system/Router/Router.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Router;
use Closure;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\HTTP\Exceptions\BadRequestException;
use CodeIgniter\HTTP\Exceptions\RedirectException;
use CodeIgniter\HTTP\Method;
use CodeIgniter\HTTP\Request;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Router\Exceptions\RouterException;
use Config\App;
use Config\Feature;
use Config\Routing;
/**
* Request router.
*
* @see \CodeIgniter\Router\RouterTest
*/
class Router implements RouterInterface
{
/**
* List of allowed HTTP methods (and CLI for command line use).
*/
public const HTTP_METHODS = [
Method::GET,
Method::HEAD,
Method::POST,
Method::PATCH,
Method::PUT,
Method::DELETE,
Method::OPTIONS,
Method::TRACE,
Method::CONNECT,
'CLI',
];
/**
* A RouteCollection instance.
*
* @var RouteCollectionInterface
*/
protected $collection;
/**
* Sub-directory that contains the requested controller class.
* Primarily used by 'autoRoute'.
*
* @var string|null
*/
protected $directory;
/**
* The name of the controller class.
*
* @var (Closure(mixed...): (ResponseInterface|string|void))|string
*/
protected $controller;
/**
* The name of the method to use.
*
* @var string
*/
protected $method;
/**
* An array of binds that were collected
* so they can be sent to closure routes.
*
* @var array
*/
protected $params = [];
/**
* The name of the front controller.
*
* @var string
*/
protected $indexPage = 'index.php';
/**
* Whether dashes in URI's should be converted
* to underscores when determining method names.
*
* @var bool
*/
protected $translateURIDashes = false;
/**
* The route that was matched for this request.
*
* @var array|null
*/
protected $matchedRoute;
/**
* The options set for the matched route.
*
* @var array|null
*/
protected $matchedRouteOptions;
/**
* The locale that was detected in a route.
*
* @var string
*/
protected $detectedLocale;
/**
* The filter info from Route Collection
* if the matched route should be filtered.
*
* @var list<string>
*/
protected $filtersInfo = [];
protected ?AutoRouterInterface $autoRouter = null;
/**
* Permitted URI chars
*
* The default value is `''` (do not check) for backward compatibility.
*/
protected string $permittedURIChars = '';
/**
* Stores a reference to the RouteCollection object.
*/
public function __construct(RouteCollectionInterface $routes, ?Request $request = null)
{
$config = config(App::class);
if (isset($config->permittedURIChars)) {
$this->permittedURIChars = $config->permittedURIChars;
}
$this->collection = $routes;
// These are only for auto-routing
$this->controller = $this->collection->getDefaultController();
$this->method = $this->collection->getDefaultMethod();
$this->collection->setHTTPVerb($request->getMethod() === '' ? $_SERVER['REQUEST_METHOD'] : $request->getMethod());
$this->translateURIDashes = $this->collection->shouldTranslateURIDashes();
if ($this->collection->shouldAutoRoute()) {
$autoRoutesImproved = config(Feature::class)->autoRoutesImproved ?? false;
if ($autoRoutesImproved) {
assert($this->collection instanceof RouteCollection);
$this->autoRouter = new AutoRouterImproved(
$this->collection->getRegisteredControllers('*'),
$this->collection->getDefaultNamespace(),
$this->collection->getDefaultController(),
$this->collection->getDefaultMethod(),
$this->translateURIDashes,
);
} else {
$this->autoRouter = new AutoRouter(
$this->collection->getRoutes('CLI', false),
$this->collection->getDefaultNamespace(),
$this->collection->getDefaultController(),
$this->collection->getDefaultMethod(),
$this->translateURIDashes,
);
}
}
}
/**
* Finds the controller corresponding to the URI.
*
* @param string|null $uri URI path relative to baseURL
*
* @return (Closure(mixed...): (ResponseInterface|string|void))|string Controller classname or Closure
*
* @throws BadRequestException
* @throws PageNotFoundException
* @throws RedirectException
*/
public function handle(?string $uri = null)
{
// If we cannot find a URI to match against, then set it to root (`/`).
if ($uri === null || $uri === '') {
$uri = '/';
}
// Decode URL-encoded string
$uri = urldecode($uri);
$this->checkDisallowedChars($uri);
// Restart filterInfo
$this->filtersInfo = [];
// Checks defined routes
if ($this->checkRoutes($uri)) {
if ($this->collection->isFiltered($this->matchedRoute[0])) {
$this->filtersInfo = $this->collection->getFiltersForRoute($this->matchedRoute[0]);
}
return $this->controller;
}
// Still here? Then we can try to match the URI against
// Controllers/directories, but the application may not
// want this, like in the case of API's.
if (! $this->collection->shouldAutoRoute()) {
throw new PageNotFoundException(
"Can't find a route for '{$this->collection->getHTTPVerb()}: {$uri}'.",
);
}
// Checks auto routes
$this->autoRoute($uri);
return $this->controllerName();
}
/**
* Returns the filter info for the matched route, if any.
*
* @return list<string>
*/
public function getFilters(): array
{
return $this->filtersInfo;
}
/**
* Returns the name of the matched controller or closure.
*
* @return (Closure(mixed...): (ResponseInterface|string|void))|string Controller classname or Closure
*/
public function controllerName()
{
return $this->translateURIDashes && ! $this->controller instanceof Closure
? str_replace('-', '_', $this->controller)
: $this->controller;
}
/**
* Returns the name of the method to run in the
* chosen controller.
*/
public function methodName(): string
{
return $this->translateURIDashes
? str_replace('-', '_', $this->method)
: $this->method;
}
/**
* Returns the 404 Override settings from the Collection.
* If the override is a string, will split to controller/index array.
*
* @return array{string, string}|(Closure(string): (ResponseInterface|string|void))|null
*/
public function get404Override()
{
$route = $this->collection->get404Override();
if (is_string($route)) {
$routeArray = explode('::', $route);
return [
$routeArray[0], // Controller
$routeArray[1] ?? 'index', // Method
];
}
if (is_callable($route)) {
return $route;
}
return null;
}
/**
* Returns the binds that have been matched and collected
* during the parsing process as an array, ready to send to
* instance->method(...$params).
*/
public function params(): array
{
return $this->params;
}
/**
* Returns the name of the sub-directory the controller is in,
* if any. Relative to APPPATH.'Controllers'.
*
* Only used when auto-routing is turned on.
*/
public function directory(): string
{
if ($this->autoRouter instanceof AutoRouter) {
return $this->autoRouter->directory();
}
return '';
}
/**
* Returns the routing information that was matched for this
* request, if a route was defined.
*
* @return array|null
*/
public function getMatchedRoute()
{
return $this->matchedRoute;
}
/**
* Returns all options set for the matched route
*
* @return array|null
*/
public function getMatchedRouteOptions()
{
return $this->matchedRouteOptions;
}
/**
* Sets the value that should be used to match the index.php file. Defaults
* to index.php but this allows you to modify it in case you are using
* something like mod_rewrite to remove the page. This allows you to set
* it a blank.
*
* @param string $page
*/
public function setIndexPage($page): self
{
$this->indexPage = $page;
return $this;
}
/**
* Tells the system whether we should translate URI dashes or not
* in the URI from a dash to an underscore.
*
* @deprecated This method should be removed.
*/
public function setTranslateURIDashes(bool $val = false): self
{
if ($this->autoRouter instanceof AutoRouter) {
$this->autoRouter->setTranslateURIDashes($val);
return $this;
}
return $this;
}
/**
* Returns true/false based on whether the current route contained
* a {locale} placeholder.
*
* @return bool
*/
public function hasLocale()
{
return (bool) $this->detectedLocale;
}
/**
* Returns the detected locale, if any, or null.
*
* @return string
*/
public function getLocale()
{
return $this->detectedLocale;
}
/**
* Checks Defined Routes.
*
* Compares the uri string against the routes that the
* RouteCollection class defined for us, attempting to find a match.
* This method will modify $this->controller, etal as needed.
*
* @param string $uri The URI path to compare against the routes
*
* @return bool Whether the route was matched or not.
*
* @throws RedirectException
*/
protected function checkRoutes(string $uri): bool
{
$routes = $this->collection->getRoutes($this->collection->getHTTPVerb());
// Don't waste any time
if ($routes === []) {
return false;
}
$uri = $uri === '/'
? $uri
: trim($uri, '/ ');
// Loop through the route array looking for wildcards
foreach ($routes as $routeKey => $handler) {
$routeKey = $routeKey === '/'
? $routeKey
// $routeKey may be int, because it is an array key,
// and the URI `/1` is valid. The leading `/` is removed.
: ltrim((string) $routeKey, '/ ');
$matchedKey = $routeKey;
// Are we dealing with a locale?
if (str_contains($routeKey, '{locale}')) {
$routeKey = str_replace('{locale}', '[^/]+', $routeKey);
}
// Does the RegEx match?
if (preg_match('#^' . $routeKey . '$#u', $uri, $matches)) {
// Is this route supposed to redirect to another?
if ($this->collection->isRedirect($routeKey)) {
// replacing matched route groups with references: post/([0-9]+) -> post/$1
$redirectTo = preg_replace_callback('/(\([^\(]+\))/', static function (): string {
static $i = 1;
return '$' . $i++;
}, is_array($handler) ? key($handler) : $handler);
throw new RedirectException(
preg_replace('#\A' . $routeKey . '\z#u', $redirectTo, $uri),
$this->collection->getRedirectCode($routeKey),
);
}
// Store our locale so CodeIgniter object can
// assign it to the Request.
if (str_contains($matchedKey, '{locale}')) {
preg_match(
'#^' . str_replace('{locale}', '(?<locale>[^/]+)', $matchedKey) . '$#u',
$uri,
$matched,
);
if ($this->collection->shouldUseSupportedLocalesOnly()
&& ! in_array($matched['locale'], config(App::class)->supportedLocales, true)) {
// Throw exception to prevent the autorouter, if enabled,
// from trying to find a route
throw PageNotFoundException::forLocaleNotSupported($matched['locale']);
}
$this->detectedLocale = $matched['locale'];
unset($matched);
}
// Are we using Closures? If so, then we need
// to collect the params into an array
// so it can be passed to the controller method later.
if (! is_string($handler) && is_callable($handler)) {
$this->controller = $handler;
// Remove the original string from the matches array
array_shift($matches);
$this->params = $matches;
$this->setMatchedRoute($matchedKey, $handler);
return true;
}
if (str_contains($handler, '::')) {
[$controller, $methodAndParams] = explode('::', $handler);
} else {
$controller = $handler;
$methodAndParams = '';
}
// Checks `/` in controller name
if (str_contains($controller, '/')) {
throw RouterException::forInvalidControllerName($handler);
}
if (str_contains($handler, '$') && str_contains($routeKey, '(')) {
// Checks dynamic controller
if (str_contains($controller, '$')) {
throw RouterException::forDynamicController($handler);
}
if (config(Routing::class)->multipleSegmentsOneParam === false) {
// Using back-references
$segments = explode('/', preg_replace('#\A' . $routeKey . '\z#u', $handler, $uri));
} else {
if (str_contains($methodAndParams, '/')) {
[$method, $handlerParams] = explode('/', $methodAndParams, 2);
$params = explode('/', $handlerParams);
$handlerSegments = array_merge([$controller . '::' . $method], $params);
} else {
$handlerSegments = [$handler];
}
$segments = [];
foreach ($handlerSegments as $segment) {
$segments[] = $this->replaceBackReferences($segment, $matches);
}
}
} else {
$segments = explode('/', $handler);
}
$this->setRequest($segments);
$this->setMatchedRoute($matchedKey, $handler);
return true;
}
}
return false;
}
/**
* Replace string `$n` with `$matches[n]` value.
*/
private function replaceBackReferences(string $input, array $matches): string
{
$pattern = '/\$([1-' . count($matches) . '])/u';
return preg_replace_callback(
$pattern,
static function ($match) use ($matches) {
$index = (int) $match[1];
return $matches[$index] ?? '';
},
$input,
);
}
/**
* Checks Auto Routes.
*
* Attempts to match a URI path against Controllers and directories
* found in APPPATH/Controllers, to find a matching route.
*
* @return void
*/
public function autoRoute(string $uri)
{
[$this->directory, $this->controller, $this->method, $this->params]
= $this->autoRouter->getRoute($uri, $this->collection->getHTTPVerb());
}
/**
* Scans the controller directory, attempting to locate a controller matching the supplied uri $segments
*
* @param array $segments URI segments
*
* @return array returns an array of remaining uri segments that don't map onto a directory
*
* @deprecated this function name does not properly describe its behavior so it has been deprecated
*
* @codeCoverageIgnore
*/
protected function validateRequest(array $segments): array
{
return $this->scanControllers($segments);
}
/**
* Scans the controller directory, attempting to locate a controller matching the supplied uri $segments
*
* @param array $segments URI segments
*
* @return array returns an array of remaining uri segments that don't map onto a directory
*
* @deprecated Not used. Moved to AutoRouter class.
*/
protected function scanControllers(array $segments): array
{
$segments = array_filter($segments, static fn ($segment): bool => $segment !== '');
// numerically reindex the array, removing gaps
$segments = array_values($segments);
// if a prior directory value has been set, just return segments and get out of here
if (isset($this->directory)) {
return $segments;
}
// Loop through our segments and return as soon as a controller
// is found or when such a directory doesn't exist
$c = count($segments);
while ($c-- > 0) {
$segmentConvert = ucfirst($this->translateURIDashes === true ? str_replace('-', '_', $segments[0]) : $segments[0]);
// as soon as we encounter any segment that is not PSR-4 compliant, stop searching
if (! $this->isValidSegment($segmentConvert)) {
return $segments;
}
$test = APPPATH . 'Controllers/' . $this->directory . $segmentConvert;
// as long as each segment is *not* a controller file but does match a directory, add it to $this->directory
if (! is_file($test . '.php') && is_dir($test)) {
$this->setDirectory($segmentConvert, true, false);
array_shift($segments);
continue;
}
return $segments;
}
// This means that all segments were actually directories
return $segments;
}
/**
* Sets the sub-directory that the controller is in.
*
* @param bool $validate if true, checks to make sure $dir consists of only PSR4 compliant segments
*
* @return void
*
* @deprecated This method should be removed.
*/
public function setDirectory(?string $dir = null, bool $append = false, bool $validate = true)
{
if ($dir === null || $dir === '') {
$this->directory = null;
}
if ($this->autoRouter instanceof AutoRouter) {
$this->autoRouter->setDirectory($dir, $append, $validate);
}
}
/**
* Returns true if the supplied $segment string represents a valid PSR-4 compliant namespace/directory segment
*
* regex comes from https://www.php.net/manual/en/language.variables.basics.php
*
* @deprecated Moved to AutoRouter class.
*/
private function isValidSegment(string $segment): bool
{
return (bool) preg_match('/^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$/', $segment);
}
/**
* Set request route
*
* Takes an array of URI segments as input and sets the class/method
* to be called.
*
* @param array $segments URI segments
*
* @return void
*/
protected function setRequest(array $segments = [])
{
// If we don't have any segments - use the default controller;
if ($segments === []) {
return;
}
[$controller, $method] = array_pad(explode('::', $segments[0]), 2, null);
$this->controller = $controller;
// $this->method already contains the default method name,
// so don't overwrite it with emptiness.
if (! empty($method)) {
$this->method = $method;
}
array_shift($segments);
$this->params = $segments;
}
/**
* Sets the default controller based on the info set in the RouteCollection.
*
* @deprecated This was an unnecessary method, so it is no longer used.
*
* @return void
*/
protected function setDefaultController()
{
if (empty($this->controller)) {
throw RouterException::forMissingDefaultRoute();
}
sscanf($this->controller, '%[^/]/%s', $class, $this->method);
if (! is_file(APPPATH . 'Controllers/' . $this->directory . ucfirst($class) . '.php')) {
return;
}
$this->controller = ucfirst($class);
log_message('info', 'Used the default controller.');
}
/**
* @param callable|string $handler
*/
protected function setMatchedRoute(string $route, $handler): void
{
$this->matchedRoute = [$route, $handler];
$this->matchedRouteOptions = $this->collection->getRoutesOptions($route);
}
/**
* Checks disallowed characters
*/
private function checkDisallowedChars(string $uri): void
{
foreach (explode('/', $uri) as $segment) {
if ($segment !== '' && $this->permittedURIChars !== ''
&& preg_match('/\A[' . $this->permittedURIChars . ']+\z/iu', $segment) !== 1
) {
throw new BadRequestException(
'The URI you submitted has disallowed characters: "' . $segment . '"',
);
}
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Router/AutoRouterImproved.php | system/Router/AutoRouterImproved.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Router;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\Router\Exceptions\MethodNotFoundException;
use Config\Routing;
use ReflectionClass;
use ReflectionException;
/**
* New Secure Router for Auto-Routing
*
* @see \CodeIgniter\Router\AutoRouterImprovedTest
*/
final class AutoRouterImproved implements AutoRouterInterface
{
/**
* Sub-directory that contains the requested controller class.
*/
private ?string $directory = null;
/**
* The name of the controller class.
*/
private string $controller;
/**
* The name of the method to use.
*/
private string $method;
/**
* An array of params to the controller method.
*
* @var list<string>
*/
private array $params = [];
/**
* Whether to translate dashes in URIs for controller/method to CamelCase.
* E.g., blog-controller -> BlogController
*/
private readonly bool $translateUriToCamelCase;
/**
* The namespace for controllers.
*/
private string $namespace;
/**
* Map of URI segments and namespaces.
*
* The key is the first URI segment. The value is the controller namespace.
* E.g.,
* [
* 'blog' => 'Acme\Blog\Controllers',
* ]
*
* @var array [ uri_segment => namespace ]
*/
private array $moduleRoutes;
/**
* The URI segments.
*
* @var list<string>
*/
private array $segments = [];
/**
* The position of the Controller in the URI segments.
* Null for the default controller.
*/
private ?int $controllerPos = null;
/**
* The position of the Method in the URI segments.
* Null for the default method.
*/
private ?int $methodPos = null;
/**
* The position of the first Parameter in the URI segments.
* Null for the no parameters.
*/
private ?int $paramPos = null;
/**
* The current URI
*/
private ?string $uri = null;
/**
* @param list<class-string> $protectedControllers
* @param string $defaultController Short classname
*/
public function __construct(
/**
* List of controllers in Defined Routes that should not be accessed via this Auto-Routing.
*/
private readonly array $protectedControllers,
string $namespace,
private readonly string $defaultController,
/**
* The name of the default method without HTTP verb prefix.
*/
private readonly string $defaultMethod,
/**
* Whether dashes in URI's should be converted
* to underscores when determining method names.
*/
private readonly bool $translateURIDashes,
) {
$this->namespace = rtrim($namespace, '\\');
$routingConfig = config(Routing::class);
$this->moduleRoutes = $routingConfig->moduleRoutes;
$this->translateUriToCamelCase = $routingConfig->translateUriToCamelCase;
// Set the default values
$this->controller = $this->defaultController;
}
private function createSegments(string $uri): array
{
$segments = explode('/', $uri);
$segments = array_filter($segments, static fn ($segment): bool => $segment !== '');
// numerically reindex the array, removing gaps
return array_values($segments);
}
/**
* Search for the first controller corresponding to the URI segment.
*
* If there is a controller corresponding to the first segment, the search
* ends there. The remaining segments are parameters to the controller.
*
* @return bool true if a controller class is found.
*/
private function searchFirstController(): bool
{
$segments = $this->segments;
$controller = '\\' . $this->namespace;
$controllerPos = -1;
while ($segments !== []) {
$segment = array_shift($segments);
$controllerPos++;
$class = $this->translateURI($segment);
// as soon as we encounter any segment that is not PSR-4 compliant, stop searching
if (! $this->isValidSegment($class)) {
return false;
}
$controller .= '\\' . $class;
if (class_exists($controller)) {
$this->controller = $controller;
$this->controllerPos = $controllerPos;
$this->checkUriForController($controller);
// The first item may be a method name.
$this->params = $segments;
if ($segments !== []) {
$this->paramPos = $this->controllerPos + 1;
}
return true;
}
}
return false;
}
/**
* Search for the last default controller corresponding to the URI segments.
*
* @return bool true if a controller class is found.
*/
private function searchLastDefaultController(): bool
{
$segments = $this->segments;
$segmentCount = count($this->segments);
$paramPos = null;
$params = [];
while ($segments !== []) {
if ($segmentCount > count($segments)) {
$paramPos = count($segments);
}
$namespaces = array_map(
fn ($segment): string => $this->translateURI($segment),
$segments,
);
$controller = '\\' . $this->namespace
. '\\' . implode('\\', $namespaces)
. '\\' . $this->defaultController;
if (class_exists($controller)) {
$this->controller = $controller;
$this->params = $params;
if ($params !== []) {
$this->paramPos = $paramPos;
}
return true;
}
// Prepend the last element in $segments to the beginning of $params.
array_unshift($params, array_pop($segments));
}
// Check for the default controller in Controllers directory.
$controller = '\\' . $this->namespace
. '\\' . $this->defaultController;
if (class_exists($controller)) {
$this->controller = $controller;
$this->params = $params;
if ($params !== []) {
$this->paramPos = 0;
}
return true;
}
return false;
}
/**
* Finds controller, method and params from the URI.
*
* @param string $httpVerb HTTP verb like `GET`,`POST`
*
* @return array [directory_name, controller_name, controller_method, params]
*/
public function getRoute(string $uri, string $httpVerb): array
{
$this->uri = $uri;
$httpVerb = strtolower($httpVerb);
// Reset Controller method params.
$this->params = [];
$defaultMethod = $httpVerb . ucfirst($this->defaultMethod);
$this->method = $defaultMethod;
$this->segments = $this->createSegments($uri);
// Check for Module Routes.
if (
$this->segments !== []
&& array_key_exists($this->segments[0], $this->moduleRoutes)
) {
$uriSegment = array_shift($this->segments);
$this->namespace = rtrim($this->moduleRoutes[$uriSegment], '\\');
}
if ($this->searchFirstController()) {
// Controller is found.
$baseControllerName = class_basename($this->controller);
// Prevent access to default controller path
if (
strtolower($baseControllerName) === strtolower($this->defaultController)
) {
throw new PageNotFoundException(
'Cannot access the default controller "' . $this->controller . '" with the controller name URI path.',
);
}
} elseif ($this->searchLastDefaultController()) {
// The default Controller is found.
$baseControllerName = class_basename($this->controller);
} else {
// No Controller is found.
throw new PageNotFoundException('No controller is found for: ' . $uri);
}
// The first item may be a method name.
/** @var list<string> $params */
$params = $this->params;
$methodParam = array_shift($params);
$method = '';
if ($methodParam !== null) {
$method = $httpVerb . $this->translateURI($methodParam);
$this->checkUriForMethod($method);
}
if ($methodParam !== null && method_exists($this->controller, $method)) {
// Method is found.
$this->method = $method;
$this->params = $params;
// Update the positions.
$this->methodPos = $this->paramPos;
if ($params === []) {
$this->paramPos = null;
}
if ($this->paramPos !== null) {
$this->paramPos++;
}
// Prevent access to default controller's method
if (strtolower($baseControllerName) === strtolower($this->defaultController)) {
throw new PageNotFoundException(
'Cannot access the default controller "' . $this->controller . '::' . $this->method . '"',
);
}
// Prevent access to default method path
if (strtolower($this->method) === strtolower($defaultMethod)) {
throw new PageNotFoundException(
'Cannot access the default method "' . $this->method . '" with the method name URI path.',
);
}
} elseif (method_exists($this->controller, $defaultMethod)) {
// The default method is found.
$this->method = $defaultMethod;
} else {
// No method is found.
throw PageNotFoundException::forControllerNotFound($this->controller, $method);
}
// Ensure the controller is not defined in routes.
$this->protectDefinedRoutes();
// Ensure the controller does not have _remap() method.
$this->checkRemap();
// Ensure the URI segments for the controller and method do not contain
// underscores when $translateURIDashes is true.
$this->checkUnderscore();
// Check parameter count
try {
$this->checkParameters();
} catch (MethodNotFoundException) {
throw PageNotFoundException::forControllerNotFound($this->controller, $this->method);
}
$this->setDirectory();
return [$this->directory, $this->controller, $this->method, $this->params];
}
/**
* @internal For test purpose only.
*
* @return array<string, int|null>
*/
public function getPos(): array
{
return [
'controller' => $this->controllerPos,
'method' => $this->methodPos,
'params' => $this->paramPos,
];
}
/**
* Get the directory path from the controller and set it to the property.
*
* @return void
*/
private function setDirectory()
{
$segments = explode('\\', trim($this->controller, '\\'));
// Remove short classname.
array_pop($segments);
$namespaces = implode('\\', $segments);
$dir = str_replace(
'\\',
'/',
ltrim(substr($namespaces, strlen($this->namespace)), '\\'),
);
if ($dir !== '') {
$this->directory = $dir . '/';
}
}
private function protectDefinedRoutes(): void
{
$controller = strtolower($this->controller);
foreach ($this->protectedControllers as $controllerInRoutes) {
$routeLowerCase = strtolower($controllerInRoutes);
if ($routeLowerCase === $controller) {
throw new PageNotFoundException(
'Cannot access the controller in Defined Routes. Controller: ' . $controllerInRoutes,
);
}
}
}
private function checkParameters(): void
{
try {
$refClass = new ReflectionClass($this->controller);
} catch (ReflectionException) {
throw PageNotFoundException::forControllerNotFound($this->controller, $this->method);
}
try {
$refMethod = $refClass->getMethod($this->method);
$refParams = $refMethod->getParameters();
} catch (ReflectionException) {
throw new MethodNotFoundException();
}
if (! $refMethod->isPublic()) {
throw new MethodNotFoundException();
}
if (count($refParams) < count($this->params)) {
throw new PageNotFoundException(
'The param count in the URI are greater than the controller method params.'
. ' Handler:' . $this->controller . '::' . $this->method
. ', URI:' . $this->uri,
);
}
}
private function checkRemap(): void
{
try {
$refClass = new ReflectionClass($this->controller);
$refClass->getMethod('_remap');
throw new PageNotFoundException(
'AutoRouterImproved does not support `_remap()` method.'
. ' Controller:' . $this->controller,
);
} catch (ReflectionException) {
// Do nothing.
}
}
private function checkUnderscore(): void
{
if ($this->translateURIDashes === false) {
return;
}
$paramPos = $this->paramPos ?? count($this->segments);
for ($i = 0; $i < $paramPos; $i++) {
if (str_contains($this->segments[$i], '_')) {
throw new PageNotFoundException(
'AutoRouterImproved prohibits access to the URI'
. ' containing underscores ("' . $this->segments[$i] . '")'
. ' when $translateURIDashes is enabled.'
. ' Please use the dash.'
. ' Handler:' . $this->controller . '::' . $this->method
. ', URI:' . $this->uri,
);
}
}
}
/**
* Check URI for controller for $translateUriToCamelCase
*
* @param string $classname Controller classname that is generated from URI.
* The case may be a bit incorrect.
*/
private function checkUriForController(string $classname): void
{
if ($this->translateUriToCamelCase === false) {
return;
}
if (! in_array(ltrim($classname, '\\'), get_declared_classes(), true)) {
throw new PageNotFoundException(
'"' . $classname . '" is not found.',
);
}
}
/**
* Check URI for method for $translateUriToCamelCase
*
* @param string $method Controller method name that is generated from URI.
* The case may be a bit incorrect.
*/
private function checkUriForMethod(string $method): void
{
if ($this->translateUriToCamelCase === false) {
return;
}
if (
// For example, if `getSomeMethod()` exists in the controller, only
// the URI `controller/some-method` should be accessible. But if a
// visitor navigates to the URI `controller/somemethod`, `getSomemethod()`
// will be checked, and `method_exists()` will return true because
// method names in PHP are case-insensitive.
method_exists($this->controller, $method)
// But we do not permit `controller/somemethod`, so check the exact
// method name.
&& ! in_array($method, get_class_methods($this->controller), true)
) {
throw new PageNotFoundException(
'"' . $this->controller . '::' . $method . '()" is not found.',
);
}
}
/**
* Returns true if the supplied $segment string represents a valid PSR-4 compliant namespace/directory segment
*
* regex comes from https://www.php.net/manual/en/language.variables.basics.php
*/
private function isValidSegment(string $segment): bool
{
return (bool) preg_match('/^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$/', $segment);
}
/**
* Translates URI segment to CamelCase or replaces `-` with `_`.
*/
private function translateURI(string $segment): string
{
if ($this->translateUriToCamelCase) {
if (strtolower($segment) !== $segment) {
throw new PageNotFoundException(
'AutoRouterImproved prohibits access to the URI'
. ' containing uppercase letters ("' . $segment . '")'
. ' when $translateUriToCamelCase is enabled.'
. ' Please use the dash.'
. ' URI:' . $this->uri,
);
}
if (str_contains($segment, '--')) {
throw new PageNotFoundException(
'AutoRouterImproved prohibits access to the URI'
. ' containing double dash ("' . $segment . '")'
. ' when $translateUriToCamelCase is enabled.'
. ' Please use the single dash.'
. ' URI:' . $this->uri,
);
}
return str_replace(
' ',
'',
ucwords(
preg_replace('/[\-]+/', ' ', $segment),
),
);
}
$segment = ucfirst($segment);
if ($this->translateURIDashes) {
return str_replace('-', '_', $segment);
}
return $segment;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Router/AutoRouterInterface.php | system/Router/AutoRouterInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Router;
/**
* Expected behavior of a AutoRouter.
*/
interface AutoRouterInterface
{
/**
* Returns controller, method and params from the URI.
*
* @return array [directory_name, controller_name, controller_method, params]
*/
public function getRoute(string $uri, string $httpVerb): array;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Router/Exceptions/RouterException.php | system/Router/Exceptions/RouterException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Router\Exceptions;
use CodeIgniter\Exceptions\FrameworkException;
/**
* RouterException
*/
class RouterException extends FrameworkException implements ExceptionInterface
{
/**
* Thrown when the actual parameter type does not match
* the expected types.
*
* @return RouterException
*/
public static function forInvalidParameterType()
{
return new static(lang('Router.invalidParameterType'));
}
/**
* Thrown when a default route is not set.
*
* @return RouterException
*/
public static function forMissingDefaultRoute()
{
return new static(lang('Router.missingDefaultRoute'));
}
/**
* Throw when controller or its method is not found.
*
* @return RouterException
*/
public static function forControllerNotFound(string $controller, string $method)
{
return new static(lang('HTTP.controllerNotFound', [$controller, $method]));
}
/**
* Throw when route is not valid.
*
* @return RouterException
*/
public static function forInvalidRoute(string $route)
{
return new static(lang('HTTP.invalidRoute', [$route]));
}
/**
* Throw when dynamic controller.
*
* @return RouterException
*/
public static function forDynamicController(string $handler)
{
return new static(lang('Router.invalidDynamicController', [$handler]));
}
/**
* Throw when controller name has `/`.
*
* @return RouterException
*/
public static function forInvalidControllerName(string $handler)
{
return new static(lang('Router.invalidControllerName', [$handler]));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Router/Exceptions/ExceptionInterface.php | system/Router/Exceptions/ExceptionInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Router\Exceptions;
/**
* Provides a domain-level interface for broad capture
* of all Router-related exceptions.
*
* catch (\CodeIgniter\Router\Exceptions\ExceptionInterface) { ... }
*/
interface ExceptionInterface extends \CodeIgniter\Exceptions\ExceptionInterface
{
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Router/Exceptions/MethodNotFoundException.php | system/Router/Exceptions/MethodNotFoundException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Router\Exceptions;
use CodeIgniter\Exceptions\RuntimeException;
/**
* @internal
*/
final class MethodNotFoundException extends RuntimeException implements ExceptionInterface
{
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Validation/CreditCardRules.php | system/Validation/CreditCardRules.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Validation;
/**
* Class CreditCardRules
*
* Provides validation methods for common credit-card inputs.
*
* @see http://en.wikipedia.org/wiki/Credit_card_number
* @see \CodeIgniter\Validation\CreditCardRulesTest
*/
class CreditCardRules
{
/**
* The cards that we support, with the defining details:
*
* name - The type of card as found in the form. Must match the user's value
* length - List of possible lengths for the card number
* prefixes - List of possible prefixes for the card
* checkdigit - Boolean on whether we should do a modulus10 check on the numbers.
*
* @var array
*/
protected $cards = [
'American Express' => [
'name' => 'amex',
'length' => '15',
'prefixes' => '34,37',
'checkdigit' => true,
],
'China UnionPay' => [
'name' => 'unionpay',
'length' => '16,17,18,19',
'prefixes' => '62',
'checkdigit' => true,
],
'Dankort' => [
'name' => 'dankort',
'length' => '16',
'prefixes' => '5019,4175,4571,4',
'checkdigit' => true,
],
'DinersClub' => [
'name' => 'dinersclub',
'length' => '14,16',
'prefixes' => '300,301,302,303,304,305,309,36,38,39,54,55',
'checkdigit' => true,
],
'DinersClub CarteBlanche' => [
'name' => 'carteblanche',
'length' => '14',
'prefixes' => '300,301,302,303,304,305',
'checkdigit' => true,
],
'Discover Card' => [
'name' => 'discover',
'length' => '16,19',
'prefixes' => '6011,622,644,645,656,647,648,649,65',
'checkdigit' => true,
],
'InterPayment' => [
'name' => 'interpayment',
'length' => '16,17,18,19',
'prefixes' => '4',
'checkdigit' => true,
],
'JCB' => [
'name' => 'jcb',
'length' => '16,17,18,19',
'prefixes' => '352,353,354,355,356,357,358',
'checkdigit' => true,
],
'Maestro' => [
'name' => 'maestro',
'length' => '12,13,14,15,16,18,19',
'prefixes' => '50,56,57,58,59,60,61,62,63,64,65,66,67,68,69',
'checkdigit' => true,
],
'MasterCard' => [
'name' => 'mastercard',
'length' => '16',
'prefixes' => '51,52,53,54,55,22,23,24,25,26,27',
'checkdigit' => true,
],
'NSPK MIR' => [
'name' => 'mir',
'length' => '16',
'prefixes' => '2200,2201,2202,2203,2204',
'checkdigit' => true,
],
'Troy' => [
'name' => 'troy',
'length' => '16',
'prefixes' => '979200,979289',
'checkdigit' => true,
],
'UATP' => [
'name' => 'uatp',
'length' => '15',
'prefixes' => '1',
'checkdigit' => true,
],
'Verve' => [
'name' => 'verve',
'length' => '16,19',
'prefixes' => '506,650',
'checkdigit' => true,
],
'Visa' => [
'name' => 'visa',
'length' => '13,16,19',
'prefixes' => '4',
'checkdigit' => true,
],
// Canadian Cards
'BMO ABM Card' => [
'name' => 'bmoabm',
'length' => '16',
'prefixes' => '500',
'checkdigit' => false,
],
'CIBC Convenience Card' => [
'name' => 'cibc',
'length' => '16',
'prefixes' => '4506',
'checkdigit' => false,
],
'HSBC Canada Card' => [
'name' => 'hsbc',
'length' => '16',
'prefixes' => '56',
'checkdigit' => false,
],
'Royal Bank of Canada Client Card' => [
'name' => 'rbc',
'length' => '16',
'prefixes' => '45',
'checkdigit' => false,
],
'Scotiabank Scotia Card' => [
'name' => 'scotia',
'length' => '16',
'prefixes' => '4536',
'checkdigit' => false,
],
'TD Canada Trust Access Card' => [
'name' => 'tdtrust',
'length' => '16',
'prefixes' => '589297',
'checkdigit' => false,
],
];
/**
* Verifies that a credit card number is valid and matches the known
* formats for a wide number of credit card types. This does not verify
* that the card is a valid card, only that the number is formatted correctly.
*
* Example:
* $rules = [
* 'cc_num' => 'valid_cc_number[visa]'
* ];
*/
public function valid_cc_number(?string $ccNumber, string $type): bool
{
$type = strtolower($type);
$info = null;
// Get our card info based on provided name.
foreach ($this->cards as $card) {
if ($card['name'] === $type) {
$info = $card;
break;
}
}
// If empty, it's not a card type we recognize, or invalid type.
if ($info === null) {
return false;
}
// Make sure we have a valid length
if ((string) $ccNumber === '') {
return false;
}
// Remove any spaces and dashes
$ccNumber = str_replace([' ', '-'], '', $ccNumber);
// Non-numeric values cannot be a number...duh
if (! is_numeric($ccNumber)) {
return false;
}
// Make sure it's a valid length for this card
$lengths = explode(',', $info['length']);
if (! in_array((string) strlen($ccNumber), $lengths, true)) {
return false;
}
// Make sure it has a valid prefix
$prefixes = explode(',', $info['prefixes']);
$validPrefix = false;
foreach ($prefixes as $prefix) {
if (str_starts_with($ccNumber, $prefix)) {
$validPrefix = true;
break;
}
}
if ($validPrefix === false) {
return false;
}
// Still here? Then check the number against the Luhn algorithm, if required
// @see https://en.wikipedia.org/wiki/Luhn_algorithm
// @see https://gist.github.com/troelskn/1287893
if ($info['checkdigit'] === true) {
return $this->isValidLuhn($ccNumber);
}
return true;
}
/**
* Checks the given number to see if the number passing a Luhn check.
*/
protected function isValidLuhn(?string $number = null): bool
{
$number = (string) $number;
$sumTable = [
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
],
[
0,
2,
4,
6,
8,
1,
3,
5,
7,
9,
],
];
$sum = 0;
$flip = 0;
for ($i = strlen($number) - 1; $i >= 0; $i--) {
$sum += $sumTable[$flip++ & 0x1][$number[$i]];
}
return $sum % 10 === 0;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Validation/DotArrayFilter.php | system/Validation/DotArrayFilter.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Validation;
/**
* @see \CodeIgniter\Validation\DotArrayFilterTest
*/
final class DotArrayFilter
{
/**
* Creates a new array with only the elements specified in dot array syntax.
*
* @param array $indexes The dot array syntax pattern to use for filtering.
* @param array $array The array to filter.
*
* @return array The filtered array.
*/
public static function run(array $indexes, array $array): array
{
$result = [];
foreach ($indexes as $index) {
$segments = preg_split('/(?<!\\\\)\./', $index, -1, PREG_SPLIT_NO_EMPTY);
$segments = array_map(static fn ($key): string => str_replace('\.', '.', $key), $segments);
$filteredArray = self::filter($segments, $array);
if ($filteredArray !== []) {
$result = array_replace_recursive($result, $filteredArray);
}
}
return $result;
}
/**
* Used by `run()` to recursively filter the array with wildcards.
*
* @param array $indexes The dot array syntax pattern to use for filtering.
* @param array $array The array to filter.
*
* @return array The filtered array.
*/
private static function filter(array $indexes, array $array): array
{
// If there are no indexes left, return an empty array
if ($indexes === []) {
return [];
}
// Get the current index
$currentIndex = array_shift($indexes);
// If the current index doesn't exist and is not a wildcard, return an empty array
if (! isset($array[$currentIndex]) && $currentIndex !== '*') {
return [];
}
// Handle the wildcard '*' at the current level
if ($currentIndex === '*') {
$result = [];
// Iterate over all keys at this level
foreach ($array as $key => $value) {
if ($indexes === []) {
// If no indexes are left, capture the entire value
$result[$key] = $value;
} elseif (is_array($value)) {
// If there are still indexes left, continue filtering recursively
$filtered = self::filter($indexes, $value);
if ($filtered !== []) {
$result[$key] = $filtered;
}
}
}
return $result;
}
// If this is the last index, return the value
if ($indexes === []) {
return [$currentIndex => $array[$currentIndex] ?? []];
}
// If the current value is an array, recursively filter it
if (is_array($array[$currentIndex])) {
$filtered = self::filter($indexes, $array[$currentIndex]);
if ($filtered !== []) {
return [$currentIndex => $filtered];
}
}
return [];
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Validation/FormatRules.php | system/Validation/FormatRules.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Validation;
use DateTime;
/**
* Format validation Rules.
*
* @see \CodeIgniter\Validation\FormatRulesTest
*/
class FormatRules
{
/**
* Alpha
*
* @param string|null $str
*/
public function alpha($str = null): bool
{
if (! is_string($str)) {
$str = (string) $str;
}
return ctype_alpha($str);
}
/**
* Alpha with spaces.
*
* @param string|null $value Value.
*
* @return bool True if alpha with spaces, else false.
*/
public function alpha_space($value = null): bool
{
if ($value === null) {
return true;
}
if (! is_string($value)) {
$value = (string) $value;
}
// @see https://regex101.com/r/LhqHPO/1
return (bool) preg_match('/\A[A-Z ]+\z/i', $value);
}
/**
* Alphanumeric with underscores and dashes
*
* @see https://regex101.com/r/XfVY3d/1
*
* @param string|null $str
*/
public function alpha_dash($str = null): bool
{
if ($str === null) {
return false;
}
if (! is_string($str)) {
$str = (string) $str;
}
return preg_match('/\A[a-z0-9_-]+\z/i', $str) === 1;
}
/**
* Alphanumeric, spaces, and a limited set of punctuation characters.
* Accepted punctuation characters are: ~ tilde, ! exclamation,
* # number, $ dollar, % percent, & ampersand, * asterisk, - dash,
* _ underscore, + plus, = equals, | vertical bar, : colon, . period
* ~ ! # $ % & * - _ + = | : .
*
* @param string|null $str
*
* @return bool
*
* @see https://regex101.com/r/6N8dDY/1
*/
public function alpha_numeric_punct($str)
{
if ($str === null) {
return false;
}
if (! is_string($str)) {
$str = (string) $str;
}
return preg_match('/\A[A-Z0-9 ~!#$%\&\*\-_+=|:.]+\z/i', $str) === 1;
}
/**
* Alphanumeric
*
* @param string|null $str
*/
public function alpha_numeric($str = null): bool
{
if (! is_string($str)) {
$str = (string) $str;
}
return ctype_alnum($str);
}
/**
* Alphanumeric w/ spaces
*
* @param string|null $str
*/
public function alpha_numeric_space($str = null): bool
{
if (! is_string($str)) {
$str = (string) $str;
}
// @see https://regex101.com/r/0AZDME/1
return (bool) preg_match('/\A[A-Z0-9 ]+\z/i', $str);
}
/**
* Any type of string
*
* Note: we specifically do NOT type hint $str here so that
* it doesn't convert numbers into strings.
*
* @param string|null $str
*/
public function string($str = null): bool
{
return is_string($str);
}
/**
* Decimal number
*
* @param string|null $str
*/
public function decimal($str = null): bool
{
if (! is_string($str)) {
$str = (string) $str;
}
// @see https://regex101.com/r/HULifl/2/
return (bool) preg_match('/\A[-+]?\d{0,}\.?\d+\z/', $str);
}
/**
* String of hexidecimal characters
*
* @param string|null $str
*/
public function hex($str = null): bool
{
if (! is_string($str)) {
$str = (string) $str;
}
return ctype_xdigit($str);
}
/**
* Integer
*
* @param string|null $str
*/
public function integer($str = null): bool
{
if (! is_string($str)) {
$str = (string) $str;
}
return (bool) preg_match('/\A[\-+]?\d+\z/', $str);
}
/**
* Is a Natural number (0,1,2,3, etc.)
*
* @param string|null $str
*/
public function is_natural($str = null): bool
{
if (! is_string($str)) {
$str = (string) $str;
}
return ctype_digit($str);
}
/**
* Is a Natural number, but not a zero (1,2,3, etc.)
*
* @param string|null $str
*/
public function is_natural_no_zero($str = null): bool
{
if (! is_string($str)) {
$str = (string) $str;
}
return $str !== '0' && ctype_digit($str);
}
/**
* Numeric
*
* @param string|null $str
*/
public function numeric($str = null): bool
{
if (! is_string($str)) {
$str = (string) $str;
}
// @see https://regex101.com/r/bb9wtr/2
return (bool) preg_match('/\A[\-+]?\d*\.?\d+\z/', $str);
}
/**
* Compares value against a regular expression pattern.
*
* @param string|null $str
*/
public function regex_match($str, string $pattern): bool
{
if (! is_string($str)) {
$str = (string) $str;
}
if (! str_starts_with($pattern, '/')) {
$pattern = "/{$pattern}/";
}
return (bool) preg_match($pattern, $str);
}
/**
* Validates that the string is a valid timezone as per the
* timezone_identifiers_list function.
*
* @see http://php.net/manual/en/datetimezone.listidentifiers.php
*
* @param string|null $str
*/
public function timezone($str = null): bool
{
if (! is_string($str)) {
$str = (string) $str;
}
return in_array($str, timezone_identifiers_list(), true);
}
/**
* Valid Base64
*
* Tests a string for characters outside of the Base64 alphabet
* as defined by RFC 2045 http://www.faqs.org/rfcs/rfc2045
*
* @param string|null $str
*/
public function valid_base64($str = null): bool
{
if ($str === null) {
return false;
}
if (! is_string($str)) {
$str = (string) $str;
}
return base64_encode(base64_decode($str, true)) === $str;
}
/**
* Valid JSON
*
* @param string|null $str
*/
public function valid_json($str = null): bool
{
if (! is_string($str)) {
$str = (string) $str;
}
json_decode($str);
return json_last_error() === JSON_ERROR_NONE;
}
/**
* Checks for a correctly formatted email address
*
* @param string|null $str
*/
public function valid_email($str = null): bool
{
if (! is_string($str)) {
$str = (string) $str;
}
// @see https://regex101.com/r/wlJG1t/1/
if (function_exists('idn_to_ascii') && defined('INTL_IDNA_VARIANT_UTS46') && preg_match('#\A([^@]+)@(.+)\z#', $str, $matches)) {
$str = $matches[1] . '@' . idn_to_ascii($matches[2], 0, INTL_IDNA_VARIANT_UTS46);
}
return (bool) filter_var($str, FILTER_VALIDATE_EMAIL);
}
/**
* Validate a comma-separated list of email addresses.
*
* Example:
* valid_emails[one@example.com,two@example.com]
*
* @param string|null $str
*/
public function valid_emails($str = null): bool
{
if (! is_string($str)) {
$str = (string) $str;
}
foreach (explode(',', $str) as $email) {
$email = trim($email);
if ($email === '') {
return false;
}
if ($this->valid_email($email) === false) {
return false;
}
}
return true;
}
/**
* Validate an IP address (human readable format or binary string - inet_pton)
*
* @param string|null $ip
* @param string|null $which IP protocol: 'ipv4' or 'ipv6'
*/
public function valid_ip($ip = null, ?string $which = null): bool
{
if (! is_string($ip)) {
$ip = (string) $ip;
}
if ($ip === '') {
return false;
}
$option = match (strtolower($which ?? '')) {
'ipv4' => FILTER_FLAG_IPV4,
'ipv6' => FILTER_FLAG_IPV6,
default => 0,
};
return filter_var($ip, FILTER_VALIDATE_IP, $option) !== false
|| (! ctype_print($ip) && filter_var(inet_ntop($ip), FILTER_VALIDATE_IP, $option) !== false);
}
/**
* Checks a string to ensure it is (loosely) a URL.
*
* Warning: this rule will pass basic strings like
* "banana"; use valid_url_strict for a stricter rule.
*
* @param string|null $str
*/
public function valid_url($str = null): bool
{
if ($str === null || $str === '') {
return false;
}
if (! is_string($str)) {
$str = (string) $str;
}
if (preg_match('/\A(?:([^:]*)\:)?\/\/(.+)\z/', $str, $matches)) {
if (! in_array($matches[1], ['http', 'https'], true)) {
return false;
}
$str = $matches[2];
}
$str = 'http://' . $str;
return filter_var($str, FILTER_VALIDATE_URL) !== false;
}
/**
* Checks a URL to ensure it's formed correctly.
*
* @param string|null $str
* @param string|null $validSchemes comma separated list of allowed schemes
*/
public function valid_url_strict($str = null, ?string $validSchemes = null): bool
{
if ($str === null || $str === '' || $str === '0') {
return false;
}
if (! is_string($str)) {
$str = (string) $str;
}
// parse_url() may return null and false
$scheme = strtolower((string) parse_url($str, PHP_URL_SCHEME));
$validSchemes = explode(
',',
strtolower($validSchemes ?? 'http,https'),
);
return in_array($scheme, $validSchemes, true)
&& filter_var($str, FILTER_VALIDATE_URL) !== false;
}
/**
* Checks for a valid date and matches a given date format
*
* @param string|null $str
* @param non-empty-string|null $format
*/
public function valid_date($str = null, ?string $format = null): bool
{
if (! is_string($str)) {
$str = (string) $str;
}
if ($str === '') {
return false;
}
if ($format === null || $format === '') {
return strtotime($str) !== false;
}
$date = DateTime::createFromFormat($format, $str);
$errors = DateTime::getLastErrors();
if ($date === false) {
return false;
}
// PHP 8.2 or later.
if ($errors === false) {
return true;
}
return $errors['warning_count'] === 0 && $errors['error_count'] === 0;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Validation/Rules.php | system/Validation/Rules.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Validation;
use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\Helpers\Array\ArrayHelper;
use Config\Database;
/**
* Validation Rules.
*
* @see \CodeIgniter\Validation\RulesTest
*/
class Rules
{
/**
* The value does not match another field in $data.
*
* @param string|null $str
* @param array $data Other field/value pairs
*/
public function differs($str, string $field, array $data): bool
{
if (str_contains($field, '.')) {
return $str !== dot_array_search($field, $data);
}
return array_key_exists($field, $data) && $str !== $data[$field];
}
/**
* Equals the static value provided.
*
* @param string|null $str
*/
public function equals($str, string $val): bool
{
if (! is_string($str) && $str !== null) {
$str = (string) $str;
}
return $str === $val;
}
/**
* Returns true if $str is $val characters long.
* $val = "5" (one) | "5,8,12" (multiple values)
*
* @param string|null $str
*/
public function exact_length($str, string $val): bool
{
if (! is_string($str) && $str !== null) {
$str = (string) $str;
}
$val = explode(',', $val);
foreach ($val as $tmp) {
if (is_numeric($tmp) && (int) $tmp === mb_strlen($str ?? '')) {
return true;
}
}
return false;
}
/**
* Greater than
*
* @param string|null $str
*/
public function greater_than($str, string $min): bool
{
if (! is_string($str) && $str !== null) {
$str = (string) $str;
}
return is_numeric($str) && $str > $min;
}
/**
* Equal to or Greater than
*
* @param string|null $str
*/
public function greater_than_equal_to($str, string $min): bool
{
if (! is_string($str) && $str !== null) {
$str = (string) $str;
}
return is_numeric($str) && $str >= $min;
}
/**
* Checks the database to see if the given value exist.
* Can ignore records by field/value to filter (currently
* accept only one filter).
*
* Example:
* is_not_unique[dbGroup.table.field,where_field,where_value]
* is_not_unique[table.field,where_field,where_value]
* is_not_unique[menu.id,active,1]
*
* @param string|null $str
*/
public function is_not_unique($str, string $field, array $data): bool
{
[$builder, $whereField, $whereValue] = $this->prepareUniqueQuery($str, $field, $data);
if (
$whereField !== null && $whereField !== ''
&& $whereValue !== null && $whereValue !== ''
&& preg_match('/^\{(\w+)\}$/', $whereValue) !== 1
) {
$builder = $builder->where($whereField, $whereValue);
}
return $builder->get()->getRow() !== null;
}
/**
* Value should be within an array of values
*
* @param string|null $value
*/
public function in_list($value, string $list): bool
{
if (! is_string($value) && $value !== null) {
$value = (string) $value;
}
$list = array_map(trim(...), explode(',', $list));
return in_array($value, $list, true);
}
/**
* Checks the database to see if the given value is unique. Can
* ignore a single record by field/value to make it useful during
* record updates.
*
* Example:
* is_unique[dbGroup.table.field,ignore_field,ignore_value]
* is_unique[table.field,ignore_field,ignore_value]
* is_unique[users.email,id,5]
*
* @param string|null $str
*/
public function is_unique($str, string $field, array $data): bool
{
[$builder, $ignoreField, $ignoreValue] = $this->prepareUniqueQuery($str, $field, $data);
if (
$ignoreField !== null && $ignoreField !== ''
&& $ignoreValue !== null && $ignoreValue !== ''
&& preg_match('/^\{(\w+)\}$/', $ignoreValue) !== 1
) {
$builder = $builder->where("{$ignoreField} !=", $ignoreValue);
}
return $builder->get()->getRow() === null;
}
/**
* Prepares the database query for uniqueness checks.
*
* @param mixed $value The value to check.
* @param string $field The field parameters.
* @param array<string, mixed> $data Additional data.
*
* @return array{0: BaseBuilder, 1: string|null, 2: string|null}
*/
private function prepareUniqueQuery($value, string $field, array $data): array
{
if (! is_string($value) && $value !== null) {
$value = (string) $value;
}
// Split the field parameters and pad the array to ensure three elements.
[$field, $extraField, $extraValue] = array_pad(explode(',', $field), 3, null);
// Parse the field string to extract dbGroup, table, and field.
$parts = explode('.', $field, 3);
$numParts = count($parts);
if ($numParts === 3) {
[$dbGroup, $table, $field] = $parts;
} elseif ($numParts === 2) {
[$table, $field] = $parts;
} else {
throw new InvalidArgumentException('The field must be in the format "table.field" or "dbGroup.table.field".');
}
// Connect to the database.
$dbGroup ??= $data['DBGroup'] ?? null;
$builder = Database::connect($dbGroup)
->table($table)
->select('1')
->where($field, $value)
->limit(1);
return [$builder, $extraField, $extraValue];
}
/**
* Less than
*
* @param string|null $str
*/
public function less_than($str, string $max): bool
{
if (! is_string($str) && $str !== null) {
$str = (string) $str;
}
return is_numeric($str) && $str < $max;
}
/**
* Equal to or Less than
*
* @param string|null $str
*/
public function less_than_equal_to($str, string $max): bool
{
if (! is_string($str) && $str !== null) {
$str = (string) $str;
}
return is_numeric($str) && $str <= $max;
}
/**
* Matches the value of another field in $data.
*
* @param string|null $str
* @param array $data Other field/value pairs
*/
public function matches($str, string $field, array $data): bool
{
if (str_contains($field, '.')) {
return $str === dot_array_search($field, $data);
}
return isset($data[$field]) && $str === $data[$field];
}
/**
* Returns true if $str is $val or fewer characters in length.
*
* @param string|null $str
*/
public function max_length($str, string $val): bool
{
if (! is_string($str) && $str !== null) {
$str = (string) $str;
}
return is_numeric($val) && $val >= mb_strlen($str ?? '');
}
/**
* Returns true if $str is at least $val length.
*
* @param string|null $str
*/
public function min_length($str, string $val): bool
{
if (! is_string($str) && $str !== null) {
$str = (string) $str;
}
return is_numeric($val) && $val <= mb_strlen($str ?? '');
}
/**
* Does not equal the static value provided.
*
* @param string|null $str
*/
public function not_equals($str, string $val): bool
{
if (! is_string($str) && $str !== null) {
$str = (string) $str;
}
return $str !== $val;
}
/**
* Value should not be within an array of values.
*
* @param string|null $value
*/
public function not_in_list($value, string $list): bool
{
if (! is_string($value) && $value !== null) {
$value = (string) $value;
}
return ! $this->in_list($value, $list);
}
/**
* @param array|bool|float|int|object|string|null $str
*/
public function required($str = null): bool
{
if ($str === null) {
return false;
}
if (is_object($str)) {
return true;
}
if (is_array($str)) {
return $str !== [];
}
return trim((string) $str) !== '';
}
/**
* The field is required when any of the other required fields are present
* in the data.
*
* Example (field is required when the password field is present):
*
* required_with[password]
*
* @param string|null $str
* @param string|null $fields List of fields that we should check if present
* @param array $data Complete list of fields from the form
*/
public function required_with($str = null, ?string $fields = null, array $data = []): bool
{
if ($fields === null || $data === []) {
throw new InvalidArgumentException('You must supply the parameters: fields, data.');
}
// If the field is present we can safely assume that
// the field is here, no matter whether the corresponding
// search field is present or not.
$present = $this->required($str ?? '');
if ($present) {
return true;
}
// Still here? Then we fail this test if
// any of the fields are present in $data
// as $fields is the list
$requiredFields = [];
foreach (explode(',', $fields) as $field) {
if (
(array_key_exists($field, $data) && ! empty($data[$field]))
|| (str_contains($field, '.') && ! empty(dot_array_search($field, $data)))
) {
$requiredFields[] = $field;
}
}
return $requiredFields === [];
}
/**
* The field is required when all the other fields are present
* in the data but not required.
*
* Example (field is required when the id or email field is missing):
*
* required_without[id,email]
*
* @param string|null $str
* @param string|null $otherFields The param fields of required_without[].
* @param string|null $field This rule param fields aren't present, this field is required.
*/
public function required_without(
$str = null,
?string $otherFields = null,
array $data = [],
?string $error = null,
?string $field = null,
): bool {
if ($otherFields === null || $data === []) {
throw new InvalidArgumentException('You must supply the parameters: otherFields, data.');
}
// If the field is present we can safely assume that
// the field is here, no matter whether the corresponding
// search field is present or not.
$present = $this->required($str ?? '');
if ($present) {
return true;
}
// Still here? Then we fail this test if
// any of the fields are not present in $data
foreach (explode(',', $otherFields) as $otherField) {
if (
(! str_contains($otherField, '.'))
&& (! array_key_exists($otherField, $data)
|| empty($data[$otherField]))
) {
return false;
}
if (str_contains($otherField, '.')) {
if ($field === null) {
throw new InvalidArgumentException('You must supply the parameters: field.');
}
$fieldData = dot_array_search($otherField, $data);
$fieldSplitArray = explode('.', $field);
$fieldKey = $fieldSplitArray[1];
if (is_array($fieldData)) {
return ! empty(dot_array_search($otherField, $data)[$fieldKey]);
}
$nowField = str_replace('*', $fieldKey, $otherField);
$nowFieldVaule = dot_array_search($nowField, $data);
return null !== $nowFieldVaule;
}
}
return true;
}
/**
* The field exists in $data.
*
* @param array|bool|float|int|object|string|null $value The field value.
* @param string|null $param The rule's parameter.
* @param array $data The data to be validated.
* @param string|null $field The field name.
*/
public function field_exists(
$value = null,
?string $param = null,
array $data = [],
?string $error = null,
?string $field = null,
): bool {
if (str_contains($field, '.')) {
return ArrayHelper::dotKeyExists($field, $data);
}
return array_key_exists($field, $data);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Validation/FileRules.php | system/Validation/FileRules.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Validation;
use CodeIgniter\Validation\StrictRules\FileRules as StrictFileRules;
/**
* File validation rules
*
* @see \CodeIgniter\Validation\FileRulesTest
*/
class FileRules extends StrictFileRules
{
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Validation/ValidationInterface.php | system/Validation/ValidationInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Validation;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\HTTP\RequestInterface;
/**
* Expected behavior of a validator
*/
interface ValidationInterface
{
/**
* Runs the validation process, returning true/false determining whether
* validation was successful or not.
*
* @param array|null $data The array of data to validate.
* @param string|null $group The predefined group of rules to apply.
* @param array|BaseConnection|non-empty-string|null $dbGroup The database group to use.
*/
public function run(?array $data = null, ?string $group = null, $dbGroup = null): bool;
/**
* Check; runs the validation process, returning true or false
* determining whether or not validation was successful.
*
* @param array|bool|float|int|object|string|null $value Value to validate.
* @param array|string $rules
* @param list<string> $errors
* @param string|null $dbGroup The database group to use.
*
* @return bool True if valid, else false.
*/
public function check($value, $rules, array $errors = [], $dbGroup = null): bool;
/**
* Takes a Request object and grabs the input data to use from its
* array values.
*/
public function withRequest(RequestInterface $request): ValidationInterface;
/**
* Sets an individual rule and custom error messages for a single field.
*
* The custom error message should be just the messages that apply to
* this field, like so:
*
* [
* 'rule' => 'message',
* 'rule' => 'message',
* ]
*
* @param array|string $rules
*
* @return $this
*/
public function setRule(string $field, ?string $label, $rules, array $errors = []);
/**
* Stores the rules that should be used to validate the items.
*/
public function setRules(array $rules, array $messages = []): ValidationInterface;
/**
* Returns all of the rules currently defined.
*/
public function getRules(): array;
/**
* Checks to see if the rule for key $field has been set or not.
*/
public function hasRule(string $field): bool;
/**
* Get rule group.
*
* @param string $group Group.
*
* @return list<string> Rule group.
*/
public function getRuleGroup(string $group): array;
/**
* Set rule group.
*
* @param string $group Group.
*
* @return void
*/
public function setRuleGroup(string $group);
/**
* Returns the error for a specified $field (or empty string if not set).
*/
public function getError(string $field): string;
/**
* Returns the array of errors that were encountered during
* a run() call. The array should be in the following format:
*
* [
* 'field1' => 'error message',
* 'field2' => 'error message',
* ]
*
* @return array<string,string>
*/
public function getErrors(): array;
/**
* Sets the error for a specific field. Used by custom validation methods.
*/
public function setError(string $alias, string $error): ValidationInterface;
/**
* Resets the class to a blank slate. Should be called whenever
* you need to process more than one array.
*/
public function reset(): ValidationInterface;
/**
* Loads custom rule groups (if set) into the current rules.
*
* Rules can be pre-defined in Config\Validation and can
* be any name, but must all still be an array of the
* same format used with setRules(). Additionally, check
* for {group}_errors for an array of custom error messages.
*
* @param non-empty-string|null $group
*
* @return array
*/
public function loadRuleGroup(?string $group = null);
/**
* Checks to see if an error exists for the given field.
*/
public function hasError(string $field): bool;
/**
* Returns the rendered HTML of the errors as defined in $template.
*/
public function listErrors(string $template = 'list'): string;
/**
* Displays a single error in formatted HTML as defined in the $template view.
*/
public function showError(string $field, string $template = 'single'): string;
/**
* Returns the actual validated data.
*/
public function getValidated(): array;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Validation/Validation.php | system/Validation/Validation.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Validation;
use Closure;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\Exceptions\LogicException;
use CodeIgniter\HTTP\Exceptions\HTTPException;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\Method;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\Validation\Exceptions\ValidationException;
use CodeIgniter\View\RendererInterface;
/**
* Validator
*
* @see \CodeIgniter\Validation\ValidationTest
*/
class Validation implements ValidationInterface
{
/**
* Files to load with validation functions.
*
* @var array
*/
protected $ruleSetFiles;
/**
* The loaded instances of our validation files.
*
* @var array
*/
protected $ruleSetInstances = [];
/**
* Stores the actual rules that should be run against $data.
*
* @var array<array-key, array{label?: string, rules: list<string>}>
*
* [
* field1 => [
* 'label' => label,
* 'rules' => [
* rule1, rule2, ...
* ],
* ],
* ]
*/
protected $rules = [];
/**
* The data that should be validated,
* where 'key' is the alias, with value.
*
* @var array
*/
protected $data = [];
/**
* The data that was actually validated.
*
* @var array
*/
protected $validated = [];
/**
* Any generated errors during validation.
* 'key' is the alias, 'value' is the message.
*
* @var array
*/
protected $errors = [];
/**
* Stores custom error message to use
* during validation. Where 'key' is the alias.
*
* @var array
*/
protected $customErrors = [];
/**
* Our configuration.
*
* @var object{ruleSets: list<class-string>}
*/
protected $config;
/**
* The view renderer used to render validation messages.
*
* @var RendererInterface
*/
protected $view;
/**
* Validation constructor.
*
* @param object{ruleSets: list<class-string>} $config
*/
public function __construct($config, RendererInterface $view)
{
$this->ruleSetFiles = $config->ruleSets;
$this->config = $config;
$this->view = $view;
$this->loadRuleSets();
}
/**
* Runs the validation process, returning true/false determining whether
* validation was successful or not.
*
* @param array|null $data The array of data to validate.
* @param string|null $group The predefined group of rules to apply.
* @param array|BaseConnection|non-empty-string|null $dbGroup The database group to use.
*/
public function run(?array $data = null, ?string $group = null, $dbGroup = null): bool
{
if ($data === null) {
$data = $this->data;
} else {
// Store data to validate.
$this->data = $data;
}
// `DBGroup` is a reserved name. For is_unique and is_not_unique
$data['DBGroup'] = $dbGroup;
$this->loadRuleGroup($group);
// If no rules exist, we return false to ensure
// the developer didn't forget to set the rules.
if ($this->rules === []) {
return false;
}
// Replace any placeholders (e.g. {id}) in the rules with
// the value found in $data, if any.
$this->rules = $this->fillPlaceholders($this->rules, $data);
// Need this for searching arrays in validation.
helper('array');
// Run through each rule. If we have any field set for
// this rule, then we need to run them through!
foreach ($this->rules as $field => $setup) {
// An array key might be int.
$field = (string) $field;
$rules = $setup['rules'];
if (is_string($rules)) {
$rules = $this->splitRules($rules);
}
if (str_contains($field, '*')) {
$flattenedArray = array_flatten_with_dots($data);
$values = array_filter(
$flattenedArray,
static fn ($key): bool => preg_match(self::getRegex($field), $key) === 1,
ARRAY_FILTER_USE_KEY,
);
// if keys not found
$values = $values !== [] ? $values : [$field => null];
} else {
$values = dot_array_search($field, $data);
}
if ($values === []) {
// We'll process the values right away if an empty array
$this->processRules($field, $setup['label'] ?? $field, $values, $rules, $data, $field);
continue;
}
if (str_contains($field, '*')) {
// Process multiple fields
foreach ($values as $dotField => $value) {
$this->processRules($dotField, $setup['label'] ?? $field, $value, $rules, $data, $field);
}
} else {
// Process single field
$this->processRules($field, $setup['label'] ?? $field, $values, $rules, $data, $field);
}
}
if ($this->getErrors() === []) {
// Store data that was actually validated.
$this->validated = DotArrayFilter::run(
array_keys($this->rules),
$this->data,
);
return true;
}
return false;
}
/**
* Returns regex pattern for key with dot array syntax.
*/
private static function getRegex(string $field): string
{
return '/\A'
. str_replace(
['\.\*', '\*\.'],
['\.[^.]+', '[^.]+\.'],
preg_quote($field, '/'),
)
. '\z/';
}
/**
* Runs the validation process, returning true or false determining whether
* validation was successful or not.
*
* @param array|bool|float|int|object|string|null $value The data to validate.
* @param array|string $rules The validation rules.
* @param list<string> $errors The custom error message.
* @param string|null $dbGroup The database group to use.
*/
public function check($value, $rules, array $errors = [], $dbGroup = null): bool
{
$this->reset();
return $this->setRule(
'check',
null,
$rules,
$errors,
)->run(
['check' => $value],
null,
$dbGroup,
);
}
/**
* Returns the actual validated data.
*/
public function getValidated(): array
{
return $this->validated;
}
/**
* Runs all of $rules against $field, until one fails, or
* all of them have been processed. If one fails, it adds
* the error to $this->errors and moves on to the next,
* so that we can collect all of the first errors.
*
* @param array|string $value
* @param array $rules
* @param array $data The array of data to validate, with `DBGroup`.
* @param string|null $originalField The original asterisk field name like "foo.*.bar".
*/
protected function processRules(
string $field,
?string $label,
$value,
$rules = null, // @TODO remove `= null`
?array $data = null, // @TODO remove `= null`
?string $originalField = null,
): bool {
if ($data === null) {
throw new InvalidArgumentException('You must supply the parameter: data.');
}
$rules = $this->processIfExist($field, $rules, $data);
if ($rules === true) {
return true;
}
$rules = $this->processPermitEmpty($value, $rules, $data);
if ($rules === true) {
return true;
}
foreach ($rules as $i => $rule) {
$isCallable = is_callable($rule);
$stringCallable = $isCallable && is_string($rule);
$arrayCallable = $isCallable && is_array($rule);
$passed = false;
/** @var string|null $param */
$param = null;
if (! $isCallable && preg_match('/(.*?)\[(.*)\]/', $rule, $match)) {
$rule = $match[1];
$param = $match[2];
}
// Placeholder for custom errors from the rules.
$error = null;
// If it's a callable, call and get out of here.
if ($this->isClosure($rule)) {
$passed = $rule($value, $data, $error, $field);
} elseif ($isCallable) {
$passed = $stringCallable ? $rule($value) : $rule($value, $data, $error, $field);
} else {
$found = false;
// Check in our rulesets
foreach ($this->ruleSetInstances as $set) {
if (! method_exists($set, $rule)) {
continue;
}
$found = true;
if ($rule === 'field_exists') {
$passed = $set->{$rule}($value, $param, $data, $error, $originalField);
} else {
$passed = ($param === null)
? $set->{$rule}($value, $error)
: $set->{$rule}($value, $param, $data, $error, $field);
}
break;
}
// If the rule wasn't found anywhere, we
// should throw an exception so the developer can find it.
if (! $found) {
throw ValidationException::forRuleNotFound($rule);
}
}
// Set the error message if we didn't survive.
if ($passed === false) {
// if the $value is an array, convert it to as string representation
if (is_array($value)) {
$value = $this->isStringList($value)
? '[' . implode(', ', $value) . ']'
: json_encode($value);
} elseif (is_object($value)) {
$value = json_encode($value);
}
$fieldForErrors = ($rule === 'field_exists') ? $originalField : $field;
// @phpstan-ignore-next-line $error may be set by rule methods.
$this->errors[$fieldForErrors] = $error ?? $this->getErrorMessage(
($this->isClosure($rule) || $arrayCallable) ? (string) $i : $rule,
$field,
$label,
$param,
(string) $value,
$originalField,
);
return false;
}
}
return true;
}
/**
* @param array $data The array of data to validate, with `DBGroup`.
*
* @return array|true The modified rules or true if we return early
*/
private function processIfExist(string $field, array $rules, array $data)
{
if (in_array('if_exist', $rules, true)) {
$flattenedData = array_flatten_with_dots($data);
$ifExistField = $field;
if (str_contains($field, '.*')) {
// We'll change the dot notation into a PCRE pattern that can be used later
$ifExistField = str_replace('\.\*', '\.(?:[^\.]+)', preg_quote($field, '/'));
$dataIsExisting = false;
$pattern = sprintf('/%s/u', $ifExistField);
foreach (array_keys($flattenedData) as $item) {
if (preg_match($pattern, $item) === 1) {
$dataIsExisting = true;
break;
}
}
} elseif (str_contains($field, '.')) {
$dataIsExisting = array_key_exists($ifExistField, $flattenedData);
} else {
$dataIsExisting = array_key_exists($ifExistField, $data);
}
if (! $dataIsExisting) {
// we return early if `if_exist` is not satisfied. we have nothing to do here.
return true;
}
// Otherwise remove the if_exist rule and continue the process
$rules = array_filter($rules, static fn ($rule): bool => $rule instanceof Closure || $rule !== 'if_exist');
}
return $rules;
}
/**
* @param array|string $value
* @param array $data The array of data to validate, with `DBGroup`.
*
* @return array|true The modified rules or true if we return early
*/
private function processPermitEmpty($value, array $rules, array $data)
{
if (in_array('permit_empty', $rules, true)) {
if (
! in_array('required', $rules, true)
&& (is_array($value) ? $value === [] : trim((string) $value) === '')
) {
$passed = true;
foreach ($rules as $rule) {
if (! $this->isClosure($rule) && preg_match('/(.*?)\[(.*)\]/', $rule, $match)) {
$rule = $match[1];
$param = $match[2];
if (! in_array($rule, ['required_with', 'required_without'], true)) {
continue;
}
// Check in our rulesets
foreach ($this->ruleSetInstances as $set) {
if (! method_exists($set, $rule)) {
continue;
}
$passed = $passed && $set->{$rule}($value, $param, $data);
break;
}
}
}
if ($passed) {
return true;
}
}
$rules = array_filter($rules, static fn ($rule): bool => $rule instanceof Closure || $rule !== 'permit_empty');
}
return $rules;
}
/**
* @param Closure(bool|float|int|list<mixed>|object|string|null, bool|float|int|list<mixed>|object|string|null, string|null, string|null): (bool|string) $rule
*/
private function isClosure($rule): bool
{
return $rule instanceof Closure;
}
/**
* Is the array a string list `list<string>`?
*/
private function isStringList(array $array): bool
{
$expectedKey = 0;
foreach ($array as $key => $val) {
// Note: also covers PHP array key conversion, e.g. '5' and 5.1 both become 5
if (! is_int($key)) {
return false;
}
if ($key !== $expectedKey) {
return false;
}
$expectedKey++;
if (! is_string($val)) {
return false;
}
}
return true;
}
/**
* Takes a Request object and grabs the input data to use from its
* array values.
*/
public function withRequest(RequestInterface $request): ValidationInterface
{
/** @var IncomingRequest $request */
if (str_contains($request->getHeaderLine('Content-Type'), 'application/json')) {
$this->data = $request->getJSON(true);
if (! is_array($this->data)) {
throw HTTPException::forUnsupportedJSONFormat();
}
return $this;
}
if (in_array($request->getMethod(), [Method::PUT, Method::PATCH, Method::DELETE], true)
&& ! str_contains($request->getHeaderLine('Content-Type'), 'multipart/form-data')
) {
$this->data = $request->getRawInput();
} else {
$this->data = $request->getVar() ?? [];
}
return $this;
}
/**
* Sets (or adds) an individual rule and custom error messages for a single
* field.
*
* The custom error message should be just the messages that apply to
* this field, like so:
* [
* 'rule1' => 'message1',
* 'rule2' => 'message2',
* ]
*
* @param array|string $rules The validation rules.
* @param array $errors The custom error message.
*
* @return $this
*
* @throws InvalidArgumentException
*/
public function setRule(string $field, ?string $label, $rules, array $errors = [])
{
if (! is_array($rules) && ! is_string($rules)) {
throw new InvalidArgumentException('$rules must be of type string|array');
}
$ruleSet = [
$field => [
'label' => $label,
'rules' => $rules,
],
];
if ($errors !== []) {
$ruleSet[$field]['errors'] = $errors;
}
$this->setRules(array_merge($this->getRules(), $ruleSet), $this->customErrors);
return $this;
}
/**
* Stores the rules that should be used to validate the items.
*
* Rules should be an array formatted like:
* [
* 'field' => 'rule1|rule2'
* ]
*
* The $errors array should be formatted like:
* [
* 'field' => [
* 'rule1' => 'message1',
* 'rule2' => 'message2',
* ],
* ]
*
* @param array $errors An array of custom error messages
*/
public function setRules(array $rules, array $errors = []): ValidationInterface
{
$this->customErrors = $errors;
foreach ($rules as $field => &$rule) {
if (is_array($rule)) {
if (array_key_exists('errors', $rule)) {
$this->customErrors[$field] = $rule['errors'];
unset($rule['errors']);
}
// if $rule is already a rule collection, just move it to "rules"
// transforming [foo => [required, foobar]] to [foo => [rules => [required, foobar]]]
if (! array_key_exists('rules', $rule)) {
$rule = ['rules' => $rule];
}
}
if (isset($rule['rules']) && is_string($rule['rules'])) {
$rule['rules'] = $this->splitRules($rule['rules']);
}
if (is_string($rule)) {
$rule = ['rules' => $this->splitRules($rule)];
}
}
$this->rules = $rules;
return $this;
}
/**
* Returns all of the rules currently defined.
*/
public function getRules(): array
{
return $this->rules;
}
/**
* Checks to see if the rule for key $field has been set or not.
*/
public function hasRule(string $field): bool
{
return array_key_exists($field, $this->rules);
}
/**
* Get rule group.
*
* @param string $group Group.
*
* @return list<string> Rule group.
*
* @throws ValidationException If group not found.
*/
public function getRuleGroup(string $group): array
{
if (! isset($this->config->{$group})) {
throw ValidationException::forGroupNotFound($group);
}
if (! is_array($this->config->{$group})) {
throw ValidationException::forGroupNotArray($group);
}
return $this->config->{$group};
}
/**
* Set rule group.
*
* @param string $group Group.
*
* @return void
*
* @throws ValidationException If group not found.
*/
public function setRuleGroup(string $group)
{
$rules = $this->getRuleGroup($group);
$this->setRules($rules);
$errorName = $group . '_errors';
if (isset($this->config->{$errorName})) {
$this->customErrors = $this->config->{$errorName};
}
}
/**
* Returns the rendered HTML of the errors as defined in $template.
*
* You can also use validation_list_errors() in Form helper.
*/
public function listErrors(string $template = 'list'): string
{
if (! array_key_exists($template, $this->config->templates)) {
throw ValidationException::forInvalidTemplate($template);
}
return $this->view
->setVar('errors', $this->getErrors())
->render($this->config->templates[$template]);
}
/**
* Displays a single error in formatted HTML as defined in the $template view.
*
* You can also use validation_show_error() in Form helper.
*/
public function showError(string $field, string $template = 'single'): string
{
if (! array_key_exists($field, $this->getErrors())) {
return '';
}
if (! array_key_exists($template, $this->config->templates)) {
throw ValidationException::forInvalidTemplate($template);
}
return $this->view
->setVar('error', $this->getError($field))
->render($this->config->templates[$template]);
}
/**
* Loads all of the rulesets classes that have been defined in the
* Config\Validation and stores them locally so we can use them.
*
* @return void
*/
protected function loadRuleSets()
{
if ($this->ruleSetFiles === [] || $this->ruleSetFiles === null) {
throw ValidationException::forNoRuleSets();
}
foreach ($this->ruleSetFiles as $file) {
$this->ruleSetInstances[] = new $file();
}
}
/**
* Loads custom rule groups (if set) into the current rules.
*
* Rules can be pre-defined in Config\Validation and can
* be any name, but must all still be an array of the
* same format used with setRules(). Additionally, check
* for {group}_errors for an array of custom error messages.
*
* @param non-empty-string|null $group
*
* @return array<int, array> [rules, customErrors]
*
* @throws ValidationException
*/
public function loadRuleGroup(?string $group = null)
{
if ($group === null || $group === '') {
return [];
}
if (! isset($this->config->{$group})) {
throw ValidationException::forGroupNotFound($group);
}
if (! is_array($this->config->{$group})) {
throw ValidationException::forGroupNotArray($group);
}
$this->setRules($this->config->{$group});
// If {group}_errors exists in the config file,
// then override our custom errors with them.
$errorName = $group . '_errors';
if (isset($this->config->{$errorName})) {
$this->customErrors = $this->config->{$errorName};
}
return [$this->rules, $this->customErrors];
}
/**
* Replace any placeholders within the rules with the values that
* match the 'key' of any properties being set. For example, if
* we had the following $data array:
*
* [ 'id' => 13 ]
*
* and the following rule:
*
* 'is_unique[users,email,id,{id}]'
*
* The value of {id} would be replaced with the actual id in the form data:
*
* 'is_unique[users,email,id,13]'
*/
protected function fillPlaceholders(array $rules, array $data): array
{
foreach ($rules as &$rule) {
$ruleSet = $rule['rules'];
foreach ($ruleSet as &$row) {
if (is_string($row)) {
$placeholderFields = $this->retrievePlaceholders($row, $data);
foreach ($placeholderFields as $field) {
$validator ??= service('validation', null, false);
assert($validator instanceof Validation);
$placeholderRules = $rules[$field]['rules'] ?? null;
// Check if the validation rule for the placeholder exists
if ($placeholderRules === null) {
throw new LogicException(
'No validation rules for the placeholder: "' . $field
. '". You must set the validation rules for the field.'
. ' See <https://codeigniter4.github.io/userguide/libraries/validation.html#validation-placeholders>.',
);
}
// Check if the rule does not have placeholders
foreach ($placeholderRules as $placeholderRule) {
if ($this->retrievePlaceholders($placeholderRule, $data) !== []) {
throw new LogicException(
'The placeholder field cannot use placeholder: ' . $field,
);
}
}
// Validate the placeholder field
$dbGroup = $data['DBGroup'] ?? null;
if (! $validator->check($data[$field], $placeholderRules, [], $dbGroup)) {
// if fails, do nothing
continue;
}
// Replace the placeholder in the rule
$ruleSet = str_replace('{' . $field . '}', (string) $data[$field], $ruleSet);
}
}
}
$rule['rules'] = $ruleSet;
}
return $rules;
}
/**
* Retrieves valid placeholder fields.
*/
private function retrievePlaceholders(string $rule, array $data): array
{
preg_match_all('/{(.+?)}/', $rule, $matches);
return array_intersect($matches[1], array_keys($data));
}
/**
* Checks to see if an error exists for the given field.
*/
public function hasError(string $field): bool
{
return (bool) preg_grep(self::getRegex($field), array_keys($this->getErrors()));
}
/**
* Returns the error(s) for a specified $field (or empty string if not
* set).
*/
public function getError(?string $field = null): string
{
if ($field === null && count($this->rules) === 1) {
$field = array_key_first($this->rules);
}
$errors = array_filter(
$this->getErrors(),
static fn ($key): bool => preg_match(self::getRegex($field), $key) === 1,
ARRAY_FILTER_USE_KEY,
);
return implode("\n", $errors);
}
/**
* Returns the array of errors that were encountered during
* a run() call. The array should be in the following format:
*
* [
* 'field1' => 'error message',
* 'field2' => 'error message',
* ]
*
* @return array<string, string>
*
* @codeCoverageIgnore
*/
public function getErrors(): array
{
return $this->errors;
}
/**
* Sets the error for a specific field. Used by custom validation methods.
*/
public function setError(string $field, string $error): ValidationInterface
{
$this->errors[$field] = $error;
return $this;
}
/**
* Attempts to find the appropriate error message
*
* @param non-empty-string|null $label
* @param string|null $value The value that caused the validation to fail.
*/
protected function getErrorMessage(
string $rule,
string $field,
?string $label = null,
?string $param = null,
?string $value = null,
?string $originalField = null,
): string {
$param ??= '';
$args = [
'field' => ($label === null || $label === '') ? $field : lang($label),
'param' => (! isset($this->rules[$param]['label'])) ? $param : lang($this->rules[$param]['label']),
'value' => $value ?? '',
];
// Check if custom message has been defined by user
if (isset($this->customErrors[$field][$rule])) {
return lang($this->customErrors[$field][$rule], $args);
}
if (null !== $originalField && isset($this->customErrors[$originalField][$rule])) {
return lang($this->customErrors[$originalField][$rule], $args);
}
// Try to grab a localized version of the message...
// lang() will return the rule name back if not found,
// so there will always be a string being returned.
return lang('Validation.' . $rule, $args);
}
/**
* Split rules string by pipe operator.
*/
protected function splitRules(string $rules): array
{
if (! str_contains($rules, '|')) {
return [$rules];
}
$string = $rules;
$rules = [];
$length = strlen($string);
$cursor = 0;
while ($cursor < $length) {
$pos = strpos($string, '|', $cursor);
if ($pos === false) {
// we're in the last rule
$pos = $length;
}
$rule = substr($string, $cursor, $pos - $cursor);
while (
(substr_count($rule, '[') - substr_count($rule, '\['))
!== (substr_count($rule, ']') - substr_count($rule, '\]'))
) {
// the pipe is inside the brackets causing the closing bracket to
// not be included. so, we adjust the rule to include that portion.
$pos = strpos($string, '|', $cursor + strlen($rule) + 1) ?: $length;
$rule = substr($string, $cursor, $pos - $cursor);
}
$rules[] = $rule;
$cursor += strlen($rule) + 1; // +1 to exclude the pipe
}
return array_unique($rules);
}
/**
* Resets the class to a blank slate. Should be called whenever
* you need to process more than one array.
*/
public function reset(): ValidationInterface
{
$this->data = [];
$this->validated = [];
$this->rules = [];
$this->errors = [];
$this->customErrors = [];
return $this;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Validation/StrictRules/CreditCardRules.php | system/Validation/StrictRules/CreditCardRules.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Validation\StrictRules;
use CodeIgniter\Validation\CreditCardRules as NonStrictCreditCardRules;
/**
* Class CreditCardRules
*
* Provides validation methods for common credit-card inputs.
*
* @see http://en.wikipedia.org/wiki/Credit_card_number
* @see \CodeIgniter\Validation\StrictRules\CreditCardRulesTest
*/
class CreditCardRules
{
private readonly NonStrictCreditCardRules $nonStrictCreditCardRules;
public function __construct()
{
$this->nonStrictCreditCardRules = new NonStrictCreditCardRules();
}
/**
* Verifies that a credit card number is valid and matches the known
* formats for a wide number of credit card types. This does not verify
* that the card is a valid card, only that the number is formatted correctly.
*
* Example:
* $rules = [
* 'cc_num' => 'valid_cc_number[visa]'
* ];
*
* @param array|bool|float|int|object|string|null $ccNumber
*/
public function valid_cc_number($ccNumber, string $type): bool
{
if (! is_string($ccNumber)) {
return false;
}
return $this->nonStrictCreditCardRules->valid_cc_number($ccNumber, $type);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Validation/StrictRules/FormatRules.php | system/Validation/StrictRules/FormatRules.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Validation\StrictRules;
use CodeIgniter\Validation\FormatRules as NonStrictFormatRules;
/**
* Format validation Rules.
*
* @see \CodeIgniter\Validation\StrictRules\FormatRulesTest
*/
class FormatRules
{
private readonly NonStrictFormatRules $nonStrictFormatRules;
public function __construct()
{
$this->nonStrictFormatRules = new NonStrictFormatRules();
}
/**
* Alpha
*
* @param array|bool|float|int|object|string|null $str
*/
public function alpha($str = null): bool
{
if (! is_string($str)) {
return false;
}
return $this->nonStrictFormatRules->alpha($str);
}
/**
* Alpha with spaces.
*
* @param array|bool|float|int|object|string|null $value Value.
*
* @return bool True if alpha with spaces, else false.
*/
public function alpha_space($value = null): bool
{
if (! is_string($value)) {
return false;
}
return $this->nonStrictFormatRules->alpha_space($value);
}
/**
* Alphanumeric with underscores and dashes
*
* @param array|bool|float|int|object|string|null $str
*/
public function alpha_dash($str = null): bool
{
if (is_int($str)) {
$str = (string) $str;
}
if (! is_string($str)) {
return false;
}
return $this->nonStrictFormatRules->alpha_dash($str);
}
/**
* Alphanumeric, spaces, and a limited set of punctuation characters.
* Accepted punctuation characters are: ~ tilde, ! exclamation,
* # number, $ dollar, % percent, & ampersand, * asterisk, - dash,
* _ underscore, + plus, = equals, | vertical bar, : colon, . period
* ~ ! # $ % & * - _ + = | : .
*
* @param array|bool|float|int|object|string|null $str
*
* @return bool
*/
public function alpha_numeric_punct($str)
{
if (is_int($str) || is_float($str)) {
$str = (string) $str;
}
if (! is_string($str)) {
return false;
}
return $this->nonStrictFormatRules->alpha_numeric_punct($str);
}
/**
* Alphanumeric
*
* @param array|bool|float|int|object|string|null $str
*/
public function alpha_numeric($str = null): bool
{
if (is_int($str)) {
$str = (string) $str;
}
if (! is_string($str)) {
return false;
}
return $this->nonStrictFormatRules->alpha_numeric($str);
}
/**
* Alphanumeric w/ spaces
*
* @param array|bool|float|int|object|string|null $str
*/
public function alpha_numeric_space($str = null): bool
{
if (is_int($str)) {
$str = (string) $str;
}
if (! is_string($str)) {
return false;
}
return $this->nonStrictFormatRules->alpha_numeric_space($str);
}
/**
* Any type of string
*
* @param array|bool|float|int|object|string|null $str
*/
public function string($str = null): bool
{
return $this->nonStrictFormatRules->string($str);
}
/**
* Decimal number
*
* @param array|bool|float|int|object|string|null $str
*/
public function decimal($str = null): bool
{
if (is_int($str) || is_float($str)) {
$str = (string) $str;
}
if (! is_string($str)) {
return false;
}
return $this->nonStrictFormatRules->decimal($str);
}
/**
* String of hexidecimal characters
*
* @param array|bool|float|int|object|string|null $str
*/
public function hex($str = null): bool
{
if (is_int($str)) {
$str = (string) $str;
}
if (! is_string($str)) {
return false;
}
return $this->nonStrictFormatRules->hex($str);
}
/**
* Integer
*
* @param array|bool|float|int|object|string|null $str
*/
public function integer($str = null): bool
{
if (is_int($str)) {
$str = (string) $str;
}
if (! is_string($str)) {
return false;
}
return $this->nonStrictFormatRules->integer($str);
}
/**
* Is a Natural number (0,1,2,3, etc.)
*
* @param array|bool|float|int|object|string|null $str
*/
public function is_natural($str = null): bool
{
if (is_int($str)) {
$str = (string) $str;
}
if (! is_string($str)) {
return false;
}
return $this->nonStrictFormatRules->is_natural($str);
}
/**
* Is a Natural number, but not a zero (1,2,3, etc.)
*
* @param array|bool|float|int|object|string|null $str
*/
public function is_natural_no_zero($str = null): bool
{
if (is_int($str)) {
$str = (string) $str;
}
if (! is_string($str)) {
return false;
}
return $this->nonStrictFormatRules->is_natural_no_zero($str);
}
/**
* Numeric
*
* @param array|bool|float|int|object|string|null $str
*/
public function numeric($str = null): bool
{
if (is_int($str) || is_float($str)) {
$str = (string) $str;
}
if (! is_string($str)) {
return false;
}
return $this->nonStrictFormatRules->numeric($str);
}
/**
* Compares value against a regular expression pattern.
*
* @param array|bool|float|int|object|string|null $str
*/
public function regex_match($str, string $pattern): bool
{
if (! is_string($str)) {
return false;
}
return $this->nonStrictFormatRules->regex_match($str, $pattern);
}
/**
* Validates that the string is a valid timezone as per the
* timezone_identifiers_list function.
*
* @see http://php.net/manual/en/datetimezone.listidentifiers.php
*
* @param array|bool|float|int|object|string|null $str
*/
public function timezone($str = null): bool
{
if (! is_string($str)) {
return false;
}
return $this->nonStrictFormatRules->timezone($str);
}
/**
* Valid Base64
*
* Tests a string for characters outside of the Base64 alphabet
* as defined by RFC 2045 http://www.faqs.org/rfcs/rfc2045
*
* @param array|bool|float|int|object|string|null $str
*/
public function valid_base64($str = null): bool
{
if (! is_string($str)) {
return false;
}
return $this->nonStrictFormatRules->valid_base64($str);
}
/**
* Valid JSON
*
* @param array|bool|float|int|object|string|null $str
*/
public function valid_json($str = null): bool
{
if (! is_string($str)) {
return false;
}
return $this->nonStrictFormatRules->valid_json($str);
}
/**
* Checks for a correctly formatted email address
*
* @param array|bool|float|int|object|string|null $str
*/
public function valid_email($str = null): bool
{
if (! is_string($str)) {
return false;
}
return $this->nonStrictFormatRules->valid_email($str);
}
/**
* Validate a comma-separated list of email addresses.
*
* Example:
* valid_emails[one@example.com,two@example.com]
*
* @param array|bool|float|int|object|string|null $str
*/
public function valid_emails($str = null): bool
{
if (! is_string($str)) {
return false;
}
return $this->nonStrictFormatRules->valid_emails($str);
}
/**
* Validate an IP address (human readable format or binary string - inet_pton)
*
* @param array|bool|float|int|object|string|null $ip
* @param string|null $which IP protocol: 'ipv4' or 'ipv6'
*/
public function valid_ip($ip = null, ?string $which = null): bool
{
if (! is_string($ip)) {
return false;
}
return $this->nonStrictFormatRules->valid_ip($ip, $which);
}
/**
* Checks a string to ensure it is (loosely) a URL.
*
* Warning: this rule will pass basic strings like
* "banana"; use valid_url_strict for a stricter rule.
*
* @param array|bool|float|int|object|string|null $str
*/
public function valid_url($str = null): bool
{
if (! is_string($str)) {
return false;
}
return $this->nonStrictFormatRules->valid_url($str);
}
/**
* Checks a URL to ensure it's formed correctly.
*
* @param array|bool|float|int|object|string|null $str
* @param string|null $validSchemes comma separated list of allowed schemes
*/
public function valid_url_strict($str = null, ?string $validSchemes = null): bool
{
if (! is_string($str)) {
return false;
}
return $this->nonStrictFormatRules->valid_url_strict($str, $validSchemes);
}
/**
* Checks for a valid date and matches a given date format
*
* @param array|bool|float|int|object|string|null $str
*/
public function valid_date($str = null, ?string $format = null): bool
{
if (! is_string($str)) {
return false;
}
return $this->nonStrictFormatRules->valid_date($str, $format);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Validation/StrictRules/Rules.php | system/Validation/StrictRules/Rules.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Validation\StrictRules;
use CodeIgniter\Helpers\Array\ArrayHelper;
use CodeIgniter\Validation\Rules as NonStrictRules;
/**
* Validation Rules.
*
* @see \CodeIgniter\Validation\StrictRules\RulesTest
*/
class Rules
{
private readonly NonStrictRules $nonStrictRules;
public function __construct()
{
$this->nonStrictRules = new NonStrictRules();
}
/**
* The value does not match another field in $data.
*
* @param array|bool|float|int|object|string|null $str
* @param array $data Other field/value pairs
*/
public function differs(
$str,
string $otherField,
array $data,
?string $error = null,
?string $field = null,
): bool {
if (str_contains($otherField, '.')) {
return $str !== dot_array_search($otherField, $data);
}
if (! array_key_exists($otherField, $data)) {
return false;
}
if (str_contains($field, '.')) {
if (! ArrayHelper::dotKeyExists($field, $data)) {
return false;
}
} elseif (! array_key_exists($field, $data)) {
return false;
}
return $str !== ($data[$otherField] ?? null);
}
/**
* Equals the static value provided.
*
* @param array|bool|float|int|object|string|null $str
*/
public function equals($str, string $val): bool
{
return $this->nonStrictRules->equals($str, $val);
}
/**
* Returns true if $str is $val characters long.
* $val = "5" (one) | "5,8,12" (multiple values)
*
* @param array|bool|float|int|object|string|null $str
*/
public function exact_length($str, string $val): bool
{
if (is_int($str) || is_float($str)) {
$str = (string) $str;
}
if (! is_string($str)) {
return false;
}
return $this->nonStrictRules->exact_length($str, $val);
}
/**
* Greater than
*
* @param array|bool|float|int|object|string|null $str expects int|string
*/
public function greater_than($str, string $min): bool
{
if (is_int($str) || is_float($str)) {
$str = (string) $str;
}
if (! is_string($str)) {
return false;
}
return $this->nonStrictRules->greater_than($str, $min);
}
/**
* Equal to or Greater than
*
* @param array|bool|float|int|object|string|null $str expects int|string
*/
public function greater_than_equal_to($str, string $min): bool
{
if (is_int($str) || is_float($str)) {
$str = (string) $str;
}
if (! is_string($str)) {
return false;
}
return $this->nonStrictRules->greater_than_equal_to($str, $min);
}
/**
* Checks the database to see if the given value exist.
* Can ignore records by field/value to filter (currently
* accept only one filter).
*
* Example:
* is_not_unique[dbGroup.table.field,where_field,where_value]
* is_not_unique[table.field,where_field,where_value]
* is_not_unique[menu.id,active,1]
*
* @param array|bool|float|int|object|string|null $str
*/
public function is_not_unique($str, string $field, array $data): bool
{
if (is_object($str) || is_array($str)) {
return false;
}
return $this->nonStrictRules->is_not_unique($str, $field, $data);
}
/**
* Value should be within an array of values
*
* @param array|bool|float|int|object|string|null $value
*/
public function in_list($value, string $list): bool
{
if (is_int($value) || is_float($value)) {
$value = (string) $value;
}
if (! is_string($value)) {
return false;
}
return $this->nonStrictRules->in_list($value, $list);
}
/**
* Checks the database to see if the given value is unique. Can
* ignore a single record by field/value to make it useful during
* record updates.
*
* Example:
* is_unique[dbGroup.table.field,ignore_field,ignore_value]
* is_unique[table.field,ignore_field,ignore_value]
* is_unique[users.email,id,5]
*
* @param array|bool|float|int|object|string|null $str
*/
public function is_unique($str, string $field, array $data): bool
{
if (is_object($str) || is_array($str)) {
return false;
}
return $this->nonStrictRules->is_unique($str, $field, $data);
}
/**
* Less than
*
* @param array|bool|float|int|object|string|null $str expects int|string
*/
public function less_than($str, string $max): bool
{
if (is_int($str) || is_float($str)) {
$str = (string) $str;
}
if (! is_string($str)) {
return false;
}
return $this->nonStrictRules->less_than($str, $max);
}
/**
* Equal to or Less than
*
* @param array|bool|float|int|object|string|null $str expects int|string
*/
public function less_than_equal_to($str, string $max): bool
{
if (is_int($str) || is_float($str)) {
$str = (string) $str;
}
if (! is_string($str)) {
return false;
}
return $this->nonStrictRules->less_than_equal_to($str, $max);
}
/**
* Matches the value of another field in $data.
*
* @param array|bool|float|int|object|string|null $str
* @param array $data Other field/value pairs
*/
public function matches(
$str,
string $otherField,
array $data,
?string $error = null,
?string $field = null,
): bool {
if (str_contains($otherField, '.')) {
return $str === dot_array_search($otherField, $data);
}
if (! array_key_exists($otherField, $data)) {
return false;
}
if (str_contains($field, '.')) {
if (! ArrayHelper::dotKeyExists($field, $data)) {
return false;
}
} elseif (! array_key_exists($field, $data)) {
return false;
}
return $str === ($data[$otherField] ?? null);
}
/**
* Returns true if $str is $val or fewer characters in length.
*
* @param array|bool|float|int|object|string|null $str
*/
public function max_length($str, string $val): bool
{
if (is_int($str) || is_float($str) || null === $str) {
$str = (string) $str;
}
if (! is_string($str)) {
return false;
}
return $this->nonStrictRules->max_length($str, $val);
}
/**
* Returns true if $str is at least $val length.
*
* @param array|bool|float|int|object|string|null $str
*/
public function min_length($str, string $val): bool
{
if (is_int($str) || is_float($str)) {
$str = (string) $str;
}
if (! is_string($str)) {
return false;
}
return $this->nonStrictRules->min_length($str, $val);
}
/**
* Does not equal the static value provided.
*
* @param array|bool|float|int|object|string|null $str
*/
public function not_equals($str, string $val): bool
{
return $this->nonStrictRules->not_equals($str, $val);
}
/**
* Value should not be within an array of values.
*
* @param array|bool|float|int|object|string|null $value
*/
public function not_in_list($value, string $list): bool
{
if (null === $value) {
return true;
}
if (is_int($value) || is_float($value)) {
$value = (string) $value;
}
if (! is_string($value)) {
return false;
}
return $this->nonStrictRules->not_in_list($value, $list);
}
/**
* @param array|bool|float|int|object|string|null $str
*/
public function required($str = null): bool
{
return $this->nonStrictRules->required($str);
}
/**
* The field is required when any of the other required fields are present
* in the data.
*
* Example (field is required when the password field is present):
*
* required_with[password]
*
* @param array|bool|float|int|object|string|null $str
* @param string|null $fields List of fields that we should check if present
* @param array $data Complete list of fields from the form
*/
public function required_with($str = null, ?string $fields = null, array $data = []): bool
{
return $this->nonStrictRules->required_with($str, $fields, $data);
}
/**
* The field is required when all the other fields are present
* in the data but not required.
*
* Example (field is required when the id or email field is missing):
*
* required_without[id,email]
*
* @param array|bool|float|int|object|string|null $str
* @param string|null $otherFields The param fields of required_without[].
* @param string|null $field This rule param fields aren't present, this field is required.
*/
public function required_without(
$str = null,
?string $otherFields = null,
array $data = [],
?string $error = null,
?string $field = null,
): bool {
return $this->nonStrictRules->required_without($str, $otherFields, $data, $error, $field);
}
/**
* The field exists in $data.
*
* @param array|bool|float|int|object|string|null $value The field value.
* @param string|null $param The rule's parameter.
* @param array $data The data to be validated.
* @param string|null $field The field name.
*/
public function field_exists(
$value = null,
?string $param = null,
array $data = [],
?string $error = null,
?string $field = null,
): bool {
if (str_contains($field, '.')) {
return ArrayHelper::dotKeyExists($field, $data);
}
return array_key_exists($field, $data);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Validation/StrictRules/FileRules.php | system/Validation/StrictRules/FileRules.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Validation\StrictRules;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use Config\Mimes;
/**
* File validation rules
*
* @see \CodeIgniter\Validation\StrictRules\FileRulesTest
*/
class FileRules
{
/**
* Request instance. So we can get access to the files.
*
* @var IncomingRequest
*/
protected $request;
/**
* Constructor.
*/
public function __construct(?RequestInterface $request = null)
{
if (! $request instanceof RequestInterface) {
$request = service('request');
}
assert($request instanceof IncomingRequest || $request instanceof CLIRequest);
$this->request = $request;
}
/**
* Verifies that $name is the name of a valid uploaded file.
*/
public function uploaded(?string $blank, string $name): bool
{
$files = $this->request->getFileMultiple($name);
if ($files === null) {
$files = [$this->request->getFile($name)];
}
foreach ($files as $file) {
if ($file === null) {
return false;
}
if (ENVIRONMENT === 'testing') {
if ($file->getError() !== 0) {
return false;
}
} else {
// Note: cannot unit test this; no way to over-ride ENVIRONMENT?
// @codeCoverageIgnoreStart
if (! $file->isValid()) {
return false;
}
// @codeCoverageIgnoreEnd
}
}
return true;
}
/**
* Verifies if the file's size in Kilobytes is no larger than the parameter.
*/
public function max_size(?string $blank, string $params): bool
{
// Grab the file name off the top of the $params
// after we split it.
$paramArray = explode(',', $params);
if (count($paramArray) !== 2) {
throw new InvalidArgumentException('Invalid max_size parameter: "' . $params . '"');
}
$name = array_shift($paramArray);
$files = $this->request->getFileMultiple($name);
if ($files === null) {
$files = [$this->request->getFile($name)];
}
foreach ($files as $file) {
if ($file === null) {
return false;
}
if ($file->getError() === UPLOAD_ERR_NO_FILE) {
return true;
}
if ($file->getError() === UPLOAD_ERR_INI_SIZE) {
return false;
}
if ($file->getSize() / 1024 > $paramArray[0]) {
return false;
}
}
return true;
}
/**
* Uses the mime config file to determine if a file is considered an "image",
* which for our purposes basically means that it's a raster image or svg.
*/
public function is_image(?string $blank, string $params): bool
{
// Grab the file name off the top of the $params
// after we split it.
$params = explode(',', $params);
$name = array_shift($params);
$files = $this->request->getFileMultiple($name);
if ($files === null) {
$files = [$this->request->getFile($name)];
}
foreach ($files as $file) {
if ($file === null) {
return false;
}
if ($file->getError() === UPLOAD_ERR_NO_FILE) {
return true;
}
// We know that our mimes list always has the first mime
// start with `image` even when then are multiple accepted types.
$type = Mimes::guessTypeFromExtension($file->getExtension()) ?? '';
if (mb_strpos($type, 'image') !== 0) {
return false;
}
}
return true;
}
/**
* Checks to see if an uploaded file's mime type matches one in the parameter.
*/
public function mime_in(?string $blank, string $params): bool
{
// Grab the file name off the top of the $params
// after we split it.
$params = explode(',', $params);
$name = array_shift($params);
$files = $this->request->getFileMultiple($name);
if ($files === null) {
$files = [$this->request->getFile($name)];
}
foreach ($files as $file) {
if ($file === null) {
return false;
}
if ($file->getError() === UPLOAD_ERR_NO_FILE) {
return true;
}
if (! in_array($file->getMimeType(), $params, true)) {
return false;
}
}
return true;
}
/**
* Checks to see if an uploaded file's extension matches one in the parameter.
*/
public function ext_in(?string $blank, string $params): bool
{
// Grab the file name off the top of the $params
// after we split it.
$params = explode(',', $params);
$name = array_shift($params);
$files = $this->request->getFileMultiple($name);
if ($files === null) {
$files = [$this->request->getFile($name)];
}
foreach ($files as $file) {
if ($file === null) {
return false;
}
if ($file->getError() === UPLOAD_ERR_NO_FILE) {
return true;
}
if (! in_array($file->guessExtension(), $params, true)) {
return false;
}
}
return true;
}
/**
* Checks an uploaded file to verify that the dimensions are within
* a specified allowable dimension.
*/
public function max_dims(?string $blank, string $params): bool
{
// Grab the file name off the top of the $params
// after we split it.
$params = explode(',', $params);
$name = array_shift($params);
$files = $this->request->getFileMultiple($name);
if ($files === null) {
$files = [$this->request->getFile($name)];
}
foreach ($files as $file) {
if ($file === null) {
return false;
}
if ($file->getError() === UPLOAD_ERR_NO_FILE) {
return true;
}
// Get Parameter sizes
$allowedWidth = $params[0] ?? 0;
$allowedHeight = $params[1] ?? 0;
// Get uploaded image size
$info = getimagesize($file->getTempName());
if ($info === false) {
// Cannot get the image size.
return false;
}
$fileWidth = $info[0];
$fileHeight = $info[1];
if ($fileWidth > $allowedWidth || $fileHeight > $allowedHeight) {
return false;
}
}
return true;
}
/**
* Checks an uploaded file to verify that the dimensions are greater than
* a specified dimension.
*/
public function min_dims(?string $blank, string $params): bool
{
// Grab the file name off the top of the $params
// after we split it.
$params = explode(',', $params);
$name = array_shift($params);
$files = $this->request->getFileMultiple($name);
if ($files === null) {
$files = [$this->request->getFile($name)];
}
foreach ($files as $file) {
if ($file === null) {
return false;
}
if ($file->getError() === UPLOAD_ERR_NO_FILE) {
return true;
}
// Get Parameter sizes
$minimumWidth = $params[0] ?? 0;
$minimumHeight = $params[1] ?? 0;
// Get uploaded image size
$info = getimagesize($file->getTempName());
if ($info === false) {
// Cannot get the image size.
return false;
}
$fileWidth = $info[0];
$fileHeight = $info[1];
if ($fileWidth < $minimumWidth || $fileHeight < $minimumHeight) {
return false;
}
}
return true;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Validation/Exceptions/ValidationException.php | system/Validation/Exceptions/ValidationException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Validation\Exceptions;
use CodeIgniter\Exceptions\FrameworkException;
class ValidationException extends FrameworkException
{
/**
* Throws when the validation rule is not found.
*
* @return static
*/
public static function forRuleNotFound(?string $rule = null)
{
return new static(lang('Validation.ruleNotFound', [$rule]));
}
/**
* Throws when the group value of config is not set.
*
* @return static
*/
public static function forGroupNotFound(?string $group = null)
{
return new static(lang('Validation.groupNotFound', [$group]));
}
/**
* Throws when the group value of config is not array type.
*
* @return static
*/
public static function forGroupNotArray(?string $group = null)
{
return new static(lang('Validation.groupNotArray', [$group]));
}
/**
* Throws when the template of config is invalid.
*
* @return static
*/
public static function forInvalidTemplate(?string $template = null)
{
return new static(lang('Validation.invalidTemplate', [$template]));
}
/**
* Throws when there is no any rule set.
*
* @return static
*/
public static function forNoRuleSets()
{
return new static(lang('Validation.noRuleSets'));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Validation/Views/list.php | system/Validation/Views/list.php | <?php if (isset($errors) && $errors !== []) : ?>
<div class="errors" role="alert">
<ul>
<?php foreach ($errors as $error) : ?>
<li><?= esc($error) ?></li>
<?php endforeach ?>
</ul>
</div>
<?php endif ?>
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Validation/Views/single.php | system/Validation/Views/single.php | <span class="help-block"><?= esc($error) ?></span>
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Honeypot/Honeypot.php | system/Honeypot/Honeypot.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Honeypot;
use CodeIgniter\Honeypot\Exceptions\HoneypotException;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Honeypot as HoneypotConfig;
/**
* class Honeypot
*
* @see \CodeIgniter\Honeypot\HoneypotTest
*/
class Honeypot
{
/**
* Our configuration.
*
* @var HoneypotConfig
*/
protected $config;
/**
* Constructor.
*
* @throws HoneypotException
*/
public function __construct(HoneypotConfig $config)
{
$this->config = $config;
if ($this->config->container === '' || ! str_contains($this->config->container, '{template}')) {
$this->config->container = '<div style="display:none">{template}</div>';
}
$this->config->containerId ??= 'hpc';
if ($this->config->template === '') {
throw HoneypotException::forNoTemplate();
}
if ($this->config->name === '') {
throw HoneypotException::forNoNameField();
}
}
/**
* Checks the request if honeypot field has data.
*
* @return bool
*/
public function hasContent(RequestInterface $request)
{
assert($request instanceof IncomingRequest);
return ! empty($request->getPost($this->config->name));
}
/**
* Attaches Honeypot template to response.
*
* @return void
*/
public function attachHoneypot(ResponseInterface $response)
{
if ($response->getBody() === null) {
return;
}
if ($response->getCSP()->enabled()) {
// Add id attribute to the container tag.
$this->config->container = str_ireplace(
'>{template}',
' id="' . $this->config->containerId . '">{template}',
$this->config->container,
);
}
$prepField = $this->prepareTemplate($this->config->template);
$bodyBefore = $response->getBody();
$bodyAfter = str_ireplace('</form>', $prepField . '</form>', $bodyBefore);
if ($response->getCSP()->enabled() && ($bodyBefore !== $bodyAfter)) {
// Add style tag for the container tag in the head tag.
$style = '<style ' . csp_style_nonce() . '>#' . $this->config->containerId . ' { display:none }</style>';
$bodyAfter = str_ireplace('</head>', $style . '</head>', $bodyAfter);
}
$response->setBody($bodyAfter);
}
/**
* Prepares the template by adding label
* content and field name.
*/
protected function prepareTemplate(string $template): string
{
$template = str_ireplace('{label}', $this->config->label, $template);
$template = str_ireplace('{name}', $this->config->name, $template);
if ($this->config->hidden) {
$template = str_ireplace('{template}', $template, $this->config->container);
}
return $template;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Honeypot/Exceptions/HoneypotException.php | system/Honeypot/Exceptions/HoneypotException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Honeypot\Exceptions;
use CodeIgniter\Exceptions\ConfigException;
class HoneypotException extends ConfigException
{
/**
* Thrown when the template value of config is empty.
*
* @return static
*/
public static function forNoTemplate()
{
return new static(lang('Honeypot.noTemplate'));
}
/**
* Thrown when the name value of config is empty.
*
* @return static
*/
public static function forNoNameField()
{
return new static(lang('Honeypot.noNameField'));
}
/**
* Thrown when the hidden value of config is false.
*
* @return static
*/
public static function forNoHiddenValue()
{
return new static(lang('Honeypot.noHiddenValue'));
}
/**
* Thrown when there are no data in the request of honeypot field.
*
* @return static
*/
public static function isBot()
{
return new static(lang('Honeypot.theClientIsABot'));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Escaper/Escaper.php | system/ThirdParty/Escaper/Escaper.php | <?php
declare(strict_types=1);
namespace Laminas\Escaper;
use function assert;
use function bin2hex;
use function ctype_digit;
use function hexdec;
use function htmlspecialchars;
use function in_array;
use function is_string;
use function mb_convert_encoding;
use function ord;
use function preg_match;
use function preg_replace_callback;
use function rawurlencode;
use function sprintf;
use function strlen;
use function strtolower;
use function strtoupper;
use function substr;
use const ENT_QUOTES;
use const ENT_SUBSTITUTE;
/**
* Context specific methods for use in secure output escaping
*
* @final
*/
class Escaper implements EscaperInterface
{
/**
* Entity Map mapping Unicode codepoints to any available named HTML entities.
*
* While HTML supports far more named entities, the lowest common denominator
* has become HTML5's XML Serialisation which is restricted to the those named
* entities that XML supports. Using HTML entities would result in this error:
* XML Parsing Error: undefined entity
*
* @var array<int, string>
*/
protected static $htmlNamedEntityMap = [
34 => 'quot', // quotation mark
38 => 'amp', // ampersand
60 => 'lt', // less-than sign
62 => 'gt', // greater-than sign
];
/**
* Current encoding for escaping. If not UTF-8, we convert strings from this encoding
* pre-escaping and back to this encoding post-escaping.
*
* @var non-empty-string
*/
protected $encoding = 'utf-8';
/**
* Holds the value of the special flags passed as second parameter to
* htmlspecialchars().
*
* @var int
*/
protected $htmlSpecialCharsFlags;
/**
* Static Matcher which escapes characters for HTML Attribute contexts
*
* @var callable
* @psalm-var callable(array<array-key, string>):string
*/
protected $htmlAttrMatcher;
/**
* Static Matcher which escapes characters for Javascript contexts
*
* @var callable
* @psalm-var callable(array<array-key, string>):string
*/
protected $jsMatcher;
/**
* Static Matcher which escapes characters for CSS Attribute contexts
*
* @var callable
* @psalm-var callable(array<array-key, string>):string
*/
protected $cssMatcher;
/**
* List of all encoding supported by this class
*
* @var list<non-empty-string>
*/
protected $supportedEncodings = [
'iso-8859-1',
'iso8859-1',
'iso-8859-5',
'iso8859-5',
'iso-8859-15',
'iso8859-15',
'utf-8',
'cp866',
'ibm866',
'866',
'cp1251',
'windows-1251',
'win-1251',
'1251',
'cp1252',
'windows-1252',
'1252',
'koi8-r',
'koi8-ru',
'koi8r',
'big5',
'950',
'gb2312',
'936',
'big5-hkscs',
'shift_jis',
'sjis',
'sjis-win',
'cp932',
'932',
'euc-jp',
'eucjp',
'eucjp-win',
'macroman',
];
/**
* Constructor: Single parameter allows setting of global encoding for use by
* the current object.
*
* @param non-empty-string|null $encoding
* @throws Exception\InvalidArgumentException
*/
public function __construct(?string $encoding = null)
{
if ($encoding !== null) {
if ($encoding === '') {
throw new Exception\InvalidArgumentException(
static::class . ' constructor parameter does not allow a blank value'
);
}
$encoding = strtolower($encoding);
if (! in_array($encoding, $this->supportedEncodings)) {
throw new Exception\InvalidArgumentException(
'Value of \'' . $encoding . '\' passed to ' . static::class
. ' constructor parameter is invalid. Provide an encoding supported by htmlspecialchars()'
);
}
$this->encoding = $encoding;
}
// We take advantage of ENT_SUBSTITUTE flag to correctly deal with invalid UTF-8 sequences.
$this->htmlSpecialCharsFlags = ENT_QUOTES | ENT_SUBSTITUTE;
// set matcher callbacks
$this->htmlAttrMatcher =
/** @param array<array-key, string> $matches */
fn(array $matches): string => $this->htmlAttrMatcher($matches);
$this->jsMatcher =
/** @param array<array-key, string> $matches */
fn(array $matches): string => $this->jsMatcher($matches);
$this->cssMatcher =
/** @param array<array-key, string> $matches */
fn(array $matches): string => $this->cssMatcher($matches);
}
/**
* Return the encoding that all output/input is expected to be encoded in.
*
* @return non-empty-string
*/
public function getEncoding()
{
return $this->encoding;
}
/** @inheritDoc */
public function escapeHtml(string $string)
{
return htmlspecialchars($string, $this->htmlSpecialCharsFlags, $this->encoding);
}
/** @inheritDoc */
public function escapeHtmlAttr(string $string)
{
$string = $this->toUtf8($string);
if ($string === '' || ctype_digit($string)) {
return $string;
}
$result = preg_replace_callback('/[^a-z0-9,\.\-_]/iSu', $this->htmlAttrMatcher, $string);
assert(is_string($result));
return $this->fromUtf8($result);
}
/** @inheritDoc */
public function escapeJs(string $string)
{
$string = $this->toUtf8($string);
if ($string === '' || ctype_digit($string)) {
return $string;
}
$result = preg_replace_callback('/[^a-z0-9,\._]/iSu', $this->jsMatcher, $string);
assert(is_string($result));
return $this->fromUtf8($result);
}
/** @inheritDoc */
public function escapeUrl(string $string)
{
return rawurlencode($string);
}
/** @inheritDoc */
public function escapeCss(string $string)
{
$string = $this->toUtf8($string);
if ($string === '' || ctype_digit($string)) {
return $string;
}
$result = preg_replace_callback('/[^a-z0-9]/iSu', $this->cssMatcher, $string);
assert(is_string($result));
return $this->fromUtf8($result);
}
/**
* Callback function for preg_replace_callback that applies HTML Attribute
* escaping to all matches.
*
* @param array<array-key, string> $matches
* @return string
*/
protected function htmlAttrMatcher($matches)
{
$chr = $matches[0];
$ord = ord($chr);
/**
* The following replaces characters undefined in HTML with the
* hex entity for the Unicode replacement character.
*/
if (
($ord <= 0x1f && $chr !== "\t" && $chr !== "\n" && $chr !== "\r")
|| ($ord >= 0x7f && $ord <= 0x9f)
) {
return '�';
}
/**
* Check if the current character to escape has a name entity we should
* replace it with while grabbing the integer value of the character.
*/
if (strlen($chr) > 1) {
$chr = $this->convertEncoding($chr, 'UTF-32BE', 'UTF-8');
}
$hex = bin2hex($chr);
$ord = hexdec($hex);
if (isset(static::$htmlNamedEntityMap[$ord])) {
return '&' . static::$htmlNamedEntityMap[$ord] . ';';
}
/**
* Per OWASP recommendations, we'll use upper hex entities
* for any other characters where a named entity does not exist.
*/
if ($ord > 255) {
return sprintf('&#x%04X;', $ord);
}
return sprintf('&#x%02X;', $ord);
}
/**
* Callback function for preg_replace_callback that applies Javascript
* escaping to all matches.
*
* @param array<array-key, string> $matches
* @return string
*/
protected function jsMatcher($matches)
{
$chr = $matches[0];
if (strlen($chr) === 1) {
return sprintf('\\x%02X', ord($chr));
}
$chr = $this->convertEncoding($chr, 'UTF-16BE', 'UTF-8');
$hex = strtoupper(bin2hex($chr));
if (strlen($hex) <= 4) {
return sprintf('\\u%04s', $hex);
}
$highSurrogate = substr($hex, 0, 4);
$lowSurrogate = substr($hex, 4, 4);
return sprintf('\\u%04s\\u%04s', $highSurrogate, $lowSurrogate);
}
/**
* Callback function for preg_replace_callback that applies CSS
* escaping to all matches.
*
* @param array<array-key, string> $matches
* @return string
*/
protected function cssMatcher($matches)
{
$chr = $matches[0];
if (strlen($chr) === 1) {
$ord = ord($chr);
} else {
$chr = $this->convertEncoding($chr, 'UTF-32BE', 'UTF-8');
$ord = hexdec(bin2hex($chr));
}
return sprintf('\\%X ', $ord);
}
/**
* Converts a string to UTF-8 from the base encoding. The base encoding is set via this
*
* @param string $string
* @throws Exception\RuntimeException
* @return string
*/
protected function toUtf8($string)
{
if ($this->getEncoding() === 'utf-8') {
$result = $string;
} else {
$result = $this->convertEncoding($string, 'UTF-8', $this->getEncoding());
}
if (! $this->isUtf8($result)) {
throw new Exception\RuntimeException(
sprintf('String to be escaped was not valid UTF-8 or could not be converted: %s', $result)
);
}
return $result;
}
/**
* Converts a string from UTF-8 to the base encoding. The base encoding is set via this
*
* @param string $string
* @return string
*/
protected function fromUtf8($string)
{
if ($this->getEncoding() === 'utf-8') {
return $string;
}
return $this->convertEncoding($string, $this->getEncoding(), 'UTF-8');
}
/**
* Checks if a given string appears to be valid UTF-8 or not.
*
* @param string $string
* @return bool
*/
protected function isUtf8($string)
{
return $string === '' || preg_match('/^./su', $string);
}
/**
* Encoding conversion helper which wraps mb_convert_encoding
*
* @param string $string
* @param string $to
* @param array|string $from
* @return string
*/
protected function convertEncoding($string, $to, $from)
{
$result = mb_convert_encoding($string, $to, $from);
if ($result === false) {
return ''; // return non-fatal blank string on encoding errors from users
}
return $result;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Escaper/EscaperInterface.php | system/ThirdParty/Escaper/EscaperInterface.php | <?php
declare(strict_types=1);
namespace Laminas\Escaper;
/**
* Interface for context specific methods for use in secure output escaping
*/
interface EscaperInterface
{
/**
* Escape a string for the HTML Body context where there are very few characters
* of special meaning. Internally this will use htmlspecialchars().
*
* @return ($string is non-empty-string ? non-empty-string : string)
*/
public function escapeHtml(string $string);
/**
* Escape a string for the HTML Attribute context. We use an extended set of characters
* to escape that are not covered by htmlspecialchars() to cover cases where an attribute
* might be unquoted or quoted illegally (e.g. backticks are valid quotes for IE).
*
* @return ($string is non-empty-string ? non-empty-string : string)
*/
public function escapeHtmlAttr(string $string);
/**
* Escape a string for the Javascript context. This does not use json_encode(). An extended
* set of characters are escaped beyond ECMAScript's rules for Javascript literal string
* escaping in order to prevent misinterpretation of Javascript as HTML leading to the
* injection of special characters and entities. The escaping used should be tolerant
* of cases where HTML escaping was not applied on top of Javascript escaping correctly.
* Backslash escaping is not used as it still leaves the escaped character as-is and so
* is not useful in a HTML context.
*
* @return ($string is non-empty-string ? non-empty-string : string)
*/
public function escapeJs(string $string);
/**
* Escape a string for the URI or Parameter contexts. This should not be used to escape
* an entire URI - only a subcomponent being inserted. The function is a simple proxy
* to rawurlencode() which now implements RFC 3986 since PHP 5.3 completely.
*
* @return ($string is non-empty-string ? non-empty-string : string)
*/
public function escapeUrl(string $string);
/**
* Escape a string for the CSS context. CSS escaping can be applied to any string being
* inserted into CSS and escapes everything except alphanumerics.
*
* @return ($string is non-empty-string ? non-empty-string : string)
*/
public function escapeCss(string $string);
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Escaper/Exception/ExceptionInterface.php | system/ThirdParty/Escaper/Exception/ExceptionInterface.php | <?php
declare(strict_types=1);
namespace Laminas\Escaper\Exception;
use Throwable;
interface ExceptionInterface extends Throwable
{
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Escaper/Exception/RuntimeException.php | system/ThirdParty/Escaper/Exception/RuntimeException.php | <?php
declare(strict_types=1);
namespace Laminas\Escaper\Exception;
/**
* Invalid argument exception
*/
class RuntimeException extends \RuntimeException implements
ExceptionInterface
{
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Escaper/Exception/InvalidArgumentException.php | system/ThirdParty/Escaper/Exception/InvalidArgumentException.php | <?php
declare(strict_types=1);
namespace Laminas\Escaper\Exception;
/**
* Invalid argument exception
*/
class InvalidArgumentException extends \InvalidArgumentException implements
ExceptionInterface
{
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Kint.php | system/ThirdParty/Kint/Kint.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint;
use InvalidArgumentException;
use Kint\Parser\ConstructablePluginInterface;
use Kint\Parser\Parser;
use Kint\Parser\PluginInterface;
use Kint\Renderer\ConstructableRendererInterface;
use Kint\Renderer\RendererInterface;
use Kint\Renderer\TextRenderer;
use Kint\Value\Context\BaseContext;
use Kint\Value\Context\ContextInterface;
use Kint\Value\UninitializedValue;
/**
* @psalm-consistent-constructor
* Psalm bug #8523
*
* @psalm-import-type CallParameter from CallFinder
*
* @psalm-type KintMode = Kint::MODE_*|bool
*
* @psalm-api
*/
class Kint implements FacadeInterface
{
public const MODE_RICH = 'r';
public const MODE_TEXT = 't';
public const MODE_CLI = 'c';
public const MODE_PLAIN = 'p';
/**
* @var mixed Kint mode
*
* false: Disabled
* true: Enabled, default mode selection
* other: Manual mode selection
*
* @psalm-var KintMode
*/
public static $enabled_mode = true;
/**
* Default mode.
*
* @psalm-var KintMode
*/
public static $mode_default = self::MODE_RICH;
/**
* Default mode in CLI with cli_detection on.
*
* @psalm-var KintMode
*/
public static $mode_default_cli = self::MODE_CLI;
/**
* @var bool enable detection when Kint is command line.
*
* Formats output with whitespace only; does not HTML-escape it
*/
public static bool $cli_detection = true;
/**
* @var bool Return output instead of echoing
*/
public static bool $return = false;
/**
* @var int depth limit for array/object traversal. 0 for no limit
*/
public static int $depth_limit = 7;
/**
* @var bool expand all trees by default for rich view
*/
public static bool $expanded = false;
/**
* @var bool whether to display where kint was called from
*/
public static bool $display_called_from = true;
/**
* @var array Kint aliases. Add debug functions in Kint wrappers here to fix modifiers and backtraces
*/
public static array $aliases = [
[self::class, 'dump'],
[self::class, 'trace'],
[self::class, 'dumpAll'],
];
/**
* @psalm-var array<RendererInterface|class-string<ConstructableRendererInterface>>
*
* Array of modes to renderer class names
*/
public static array $renderers = [
self::MODE_RICH => Renderer\RichRenderer::class,
self::MODE_PLAIN => Renderer\PlainRenderer::class,
self::MODE_TEXT => TextRenderer::class,
self::MODE_CLI => Renderer\CliRenderer::class,
];
/**
* @psalm-var array<PluginInterface|class-string<ConstructablePluginInterface>>
*/
public static array $plugins = [
\Kint\Parser\ArrayLimitPlugin::class,
\Kint\Parser\ArrayObjectPlugin::class,
\Kint\Parser\Base64Plugin::class,
\Kint\Parser\BinaryPlugin::class,
\Kint\Parser\BlacklistPlugin::class,
\Kint\Parser\ClassHooksPlugin::class,
\Kint\Parser\ClassMethodsPlugin::class,
\Kint\Parser\ClassStaticsPlugin::class,
\Kint\Parser\ClassStringsPlugin::class,
\Kint\Parser\ClosurePlugin::class,
\Kint\Parser\ColorPlugin::class,
\Kint\Parser\DateTimePlugin::class,
\Kint\Parser\DomPlugin::class,
\Kint\Parser\EnumPlugin::class,
\Kint\Parser\FsPathPlugin::class,
\Kint\Parser\HtmlPlugin::class,
\Kint\Parser\IteratorPlugin::class,
\Kint\Parser\JsonPlugin::class,
\Kint\Parser\MicrotimePlugin::class,
\Kint\Parser\MysqliPlugin::class,
// \Kint\Parser\SerializePlugin::class,
\Kint\Parser\SimpleXMLElementPlugin::class,
\Kint\Parser\SplFileInfoPlugin::class,
\Kint\Parser\StreamPlugin::class,
\Kint\Parser\TablePlugin::class,
\Kint\Parser\ThrowablePlugin::class,
\Kint\Parser\TimestampPlugin::class,
\Kint\Parser\ToStringPlugin::class,
\Kint\Parser\TracePlugin::class,
\Kint\Parser\XmlPlugin::class,
];
protected Parser $parser;
protected RendererInterface $renderer;
public function __construct(Parser $p, RendererInterface $r)
{
$this->parser = $p;
$this->renderer = $r;
}
public function setParser(Parser $p): void
{
$this->parser = $p;
}
public function getParser(): Parser
{
return $this->parser;
}
public function setRenderer(RendererInterface $r): void
{
$this->renderer = $r;
}
public function getRenderer(): RendererInterface
{
return $this->renderer;
}
public function setStatesFromStatics(array $statics): void
{
$this->renderer->setStatics($statics);
$this->parser->setDepthLimit($statics['depth_limit'] ?? 0);
$this->parser->clearPlugins();
if (!isset($statics['plugins'])) {
return;
}
$plugins = [];
foreach ($statics['plugins'] as $plugin) {
if ($plugin instanceof PluginInterface) {
$plugins[] = $plugin;
} elseif (\is_string($plugin) && \is_a($plugin, ConstructablePluginInterface::class, true)) {
$plugins[] = new $plugin($this->parser);
}
}
$plugins = $this->renderer->filterParserPlugins($plugins);
foreach ($plugins as $plugin) {
try {
$this->parser->addPlugin($plugin);
} catch (InvalidArgumentException $e) {
\trigger_error(
'Plugin '.Utils::errorSanitizeString(\get_class($plugin)).' could not be added to a Kint parser: '.Utils::errorSanitizeString($e->getMessage()),
E_USER_WARNING
);
}
}
}
public function setStatesFromCallInfo(array $info): void
{
$this->renderer->setCallInfo($info);
if (isset($info['modifiers']) && \is_array($info['modifiers']) && \in_array('+', $info['modifiers'], true)) {
$this->parser->setDepthLimit(0);
}
$this->parser->setCallerClass($info['caller']['class'] ?? null);
}
public function dumpAll(array $vars, array $base): string
{
if (\array_keys($vars) !== \array_keys($base)) {
throw new InvalidArgumentException('Kint::dumpAll requires arrays of identical size and keys as arguments');
}
if ([] === $vars) {
return $this->dumpNothing();
}
$output = $this->renderer->preRender();
foreach ($vars as $key => $_) {
if (!$base[$key] instanceof ContextInterface) {
throw new InvalidArgumentException('Kint::dumpAll requires all elements of the second argument to be ContextInterface instances');
}
$output .= $this->dumpVar($vars[$key], $base[$key]);
}
$output .= $this->renderer->postRender();
return $output;
}
protected function dumpNothing(): string
{
$output = $this->renderer->preRender();
$output .= $this->renderer->render(new UninitializedValue(new BaseContext('No argument')));
$output .= $this->renderer->postRender();
return $output;
}
/**
* Dumps and renders a var.
*
* @param mixed &$var Data to dump
*/
protected function dumpVar(&$var, ContextInterface $c): string
{
return $this->renderer->render(
$this->parser->parse($var, $c)
);
}
/**
* Gets all static settings at once.
*
* @return array Current static settings
*/
public static function getStatics(): array
{
return [
'aliases' => static::$aliases,
'cli_detection' => static::$cli_detection,
'depth_limit' => static::$depth_limit,
'display_called_from' => static::$display_called_from,
'enabled_mode' => static::$enabled_mode,
'expanded' => static::$expanded,
'mode_default' => static::$mode_default,
'mode_default_cli' => static::$mode_default_cli,
'plugins' => static::$plugins,
'renderers' => static::$renderers,
'return' => static::$return,
];
}
/**
* Creates a Kint instance based on static settings.
*
* @param array $statics array of statics as returned by getStatics
*/
public static function createFromStatics(array $statics): ?FacadeInterface
{
$mode = false;
if (isset($statics['enabled_mode'])) {
$mode = $statics['enabled_mode'];
if (true === $mode && isset($statics['mode_default'])) {
$mode = $statics['mode_default'];
if (PHP_SAPI === 'cli' && !empty($statics['cli_detection']) && isset($statics['mode_default_cli'])) {
$mode = $statics['mode_default_cli'];
}
}
}
if (false === $mode) {
return null;
}
$renderer = null;
if (isset($statics['renderers'][$mode])) {
if ($statics['renderers'][$mode] instanceof RendererInterface) {
$renderer = $statics['renderers'][$mode];
}
if (\is_a($statics['renderers'][$mode], ConstructableRendererInterface::class, true)) {
$renderer = new $statics['renderers'][$mode]();
}
}
$renderer ??= new TextRenderer();
return new static(new Parser(), $renderer);
}
/**
* Creates base contexts given parameter info.
*
* @psalm-param list<CallParameter> $params
*
* @return BaseContext[] Base contexts for the arguments
*/
public static function getBasesFromParamInfo(array $params, int $argc): array
{
$bases = [];
for ($i = 0; $i < $argc; ++$i) {
$param = $params[$i] ?? null;
if (!empty($param['literal'])) {
$name = 'literal';
} else {
$name = $param['name'] ?? '$'.$i;
}
if (isset($param['path'])) {
$access_path = $param['path'];
if ($param['expression']) {
$access_path = '('.$access_path.')';
} elseif ($param['new_without_parens']) {
$access_path .= '()';
}
} else {
$access_path = '$'.$i;
}
$base = new BaseContext($name);
$base->access_path = $access_path;
$bases[] = $base;
}
return $bases;
}
/**
* Gets call info from the backtrace, alias, and argument count.
*
* Aliases must be normalized beforehand (Utils::normalizeAliases)
*
* @param array $aliases Call aliases as found in Kint::$aliases
* @param array[] $trace Backtrace
* @param array $args Arguments
*
* @return array Call info
*
* @psalm-param list<non-empty-array> $trace
*/
public static function getCallInfo(array $aliases, array $trace, array $args): array
{
$found = false;
$callee = null;
$caller = null;
$miniTrace = [];
foreach ($trace as $frame) {
if (Utils::traceFrameIsListed($frame, $aliases)) {
$found = true;
$miniTrace = [];
}
if (!Utils::traceFrameIsListed($frame, ['spl_autoload_call'])) {
$miniTrace[] = $frame;
}
}
if ($found) {
$callee = \reset($miniTrace) ?: null;
$caller = \next($miniTrace) ?: null;
}
foreach ($miniTrace as $index => $frame) {
if ((0 === $index && $callee === $frame) || isset($frame['file'], $frame['line'])) {
unset($frame['object'], $frame['args']);
$miniTrace[$index] = $frame;
} else {
unset($miniTrace[$index]);
}
}
$miniTrace = \array_values($miniTrace);
$call = static::getSingleCall($callee ?: [], $args);
$ret = [
'params' => null,
'modifiers' => [],
'callee' => $callee,
'caller' => $caller,
'trace' => $miniTrace,
];
if (null !== $call) {
$ret['params'] = $call['parameters'];
$ret['modifiers'] = $call['modifiers'];
}
return $ret;
}
/**
* Dumps a backtrace.
*
* Functionally equivalent to Kint::dump(1) or Kint::dump(debug_backtrace(true))
*
* @return int|string
*/
public static function trace()
{
if (false === static::$enabled_mode) {
return 0;
}
static::$aliases = Utils::normalizeAliases(static::$aliases);
$call_info = static::getCallInfo(static::$aliases, \debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), []);
$statics = static::getStatics();
if (\in_array('~', $call_info['modifiers'], true)) {
$statics['enabled_mode'] = static::MODE_TEXT;
}
$kintstance = static::createFromStatics($statics);
if (!$kintstance) {
return 0;
}
if (\in_array('-', $call_info['modifiers'], true)) {
while (\ob_get_level()) {
\ob_end_clean();
}
}
$kintstance->setStatesFromStatics($statics);
$kintstance->setStatesFromCallInfo($call_info);
$trimmed_trace = [];
$trace = \debug_backtrace();
foreach ($trace as $frame) {
if (Utils::traceFrameIsListed($frame, static::$aliases)) {
$trimmed_trace = [];
}
$trimmed_trace[] = $frame;
}
\array_shift($trimmed_trace);
$base = new BaseContext('Kint\\Kint::trace()');
$base->access_path = 'debug_backtrace()';
$output = $kintstance->dumpAll([$trimmed_trace], [$base]);
if (static::$return || \in_array('@', $call_info['modifiers'], true)) {
return $output;
}
echo $output;
if (\in_array('-', $call_info['modifiers'], true)) {
\flush(); // @codeCoverageIgnore
}
return 0;
}
/**
* Dumps some data.
*
* Functionally equivalent to Kint::dump(1) or Kint::dump(debug_backtrace())
*
* @psalm-param mixed ...$args
*
* @return int|string
*/
public static function dump(...$args)
{
if (false === static::$enabled_mode) {
return 0;
}
static::$aliases = Utils::normalizeAliases(static::$aliases);
$call_info = static::getCallInfo(static::$aliases, \debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), $args);
$statics = static::getStatics();
if (\in_array('~', $call_info['modifiers'], true)) {
$statics['enabled_mode'] = static::MODE_TEXT;
}
$kintstance = static::createFromStatics($statics);
if (!$kintstance) {
return 0;
}
if (\in_array('-', $call_info['modifiers'], true)) {
while (\ob_get_level()) {
\ob_end_clean();
}
}
$kintstance->setStatesFromStatics($statics);
$kintstance->setStatesFromCallInfo($call_info);
$bases = static::getBasesFromParamInfo($call_info['params'] ?? [], \count($args));
$output = $kintstance->dumpAll(\array_values($args), $bases);
if (static::$return || \in_array('@', $call_info['modifiers'], true)) {
return $output;
}
echo $output;
if (\in_array('-', $call_info['modifiers'], true)) {
\flush(); // @codeCoverageIgnore
}
return 0;
}
/**
* Returns specific function call info from a stack trace frame, or null if no match could be found.
*
* @param array $frame The stack trace frame in question
* @param array $args The arguments
*
* @return ?array params and modifiers, or null if a specific call could not be determined
*/
protected static function getSingleCall(array $frame, array $args): ?array
{
if (
!isset($frame['file'], $frame['line'], $frame['function']) ||
!\is_readable($frame['file']) ||
false === ($source = \file_get_contents($frame['file']))
) {
return null;
}
if (empty($frame['class'])) {
$callfunc = $frame['function'];
} else {
$callfunc = [$frame['class'], $frame['function']];
}
$calls = CallFinder::getFunctionCalls($source, $frame['line'], $callfunc);
$argc = \count($args);
$return = null;
foreach ($calls as $call) {
$is_unpack = false;
// Handle argument unpacking as a last resort
foreach ($call['parameters'] as $i => &$param) {
if (0 === \strpos($param['name'], '...')) {
$is_unpack = true;
// If we're on the last param
if ($i < $argc && $i === \count($call['parameters']) - 1) {
unset($call['parameters'][$i]);
if (Utils::isAssoc($args)) {
// Associated unpacked arrays can be accessed by key
$keys = \array_slice(\array_keys($args), $i);
foreach ($keys as $key) {
$call['parameters'][] = [
'name' => \substr($param['name'], 3).'['.\var_export($key, true).']',
'path' => \substr($param['path'], 3).'['.\var_export($key, true).']',
'expression' => false,
'literal' => false,
'new_without_parens' => false,
];
}
} else {
// Numeric unpacked arrays have their order blown away like a pass
// through array_values so we can't access them directly at all
for ($j = 0; $j + $i < $argc; ++$j) {
$call['parameters'][] = [
'name' => 'array_values('.\substr($param['name'], 3).')['.$j.']',
'path' => 'array_values('.\substr($param['path'], 3).')['.$j.']',
'expression' => false,
'literal' => false,
'new_without_parens' => false,
];
}
}
$call['parameters'] = \array_values($call['parameters']);
} else {
$call['parameters'] = \array_slice($call['parameters'], 0, $i);
}
break;
}
if ($i >= $argc) {
continue 2;
}
}
if ($is_unpack || \count($call['parameters']) === $argc) {
if (null === $return) {
$return = $call;
} else {
// If we have multiple calls on the same line with the same amount of arguments,
// we can't be sure which it is so just return null and let them figure it out
return null;
}
}
}
return $return;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/init_helpers.php | system/ThirdParty/Kint/init_helpers.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use Kint\Kint;
use Kint\Renderer\CliRenderer;
if (!\function_exists('d')) {
/**
* Alias of Kint::dump().
*
* @psalm-param mixed ...$args
*
* @return int|string
*/
function d(...$args)
{
return Kint::dump(...$args);
}
Kint::$aliases[] = 'd';
}
if (!\function_exists('s')) {
/**
* Alias of Kint::dump(), however the output is in plain text.
*
* Alias of Kint::dump(), however the output is in plain htmlescaped text
* with some minor visibility enhancements added.
*
* If run in CLI colors are disabled
*
* @psalm-param mixed ...$args
*
* @return int|string
*/
function s(...$args)
{
if (false === Kint::$enabled_mode) {
return 0;
}
$kstash = Kint::$enabled_mode;
$cstash = CliRenderer::$cli_colors;
if (Kint::MODE_TEXT !== Kint::$enabled_mode) {
Kint::$enabled_mode = Kint::MODE_PLAIN;
if (PHP_SAPI === 'cli' && true === Kint::$cli_detection) {
Kint::$enabled_mode = Kint::$mode_default_cli;
}
}
CliRenderer::$cli_colors = false;
$out = Kint::dump(...$args);
Kint::$enabled_mode = $kstash;
CliRenderer::$cli_colors = $cstash;
return $out;
}
Kint::$aliases[] = 's';
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/CallFinder.php | system/ThirdParty/Kint/CallFinder.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint;
/**
* @psalm-type PhpTokenArray = array{int, string, int}
* @psalm-type PhpToken = string|PhpTokenArray
* @psalm-type CallParameter = array{
* name: string,
* path: string,
* expression: bool,
* literal: bool,
* new_without_parens: bool,
* }
*/
class CallFinder
{
private static array $ignore = [
T_CLOSE_TAG => true,
T_COMMENT => true,
T_DOC_COMMENT => true,
T_INLINE_HTML => true,
T_OPEN_TAG => true,
T_OPEN_TAG_WITH_ECHO => true,
T_WHITESPACE => true,
];
/**
* Things we need to do specially for operator tokens:
* - Refuse to strip spaces around them
* - Wrap the access path in parentheses if there
* are any of these in the final short parameter.
*/
private static array $operator = [
T_AND_EQUAL => true,
T_BOOLEAN_AND => true,
T_BOOLEAN_OR => true,
T_ARRAY_CAST => true,
T_BOOL_CAST => true,
T_CLONE => true,
T_CONCAT_EQUAL => true,
T_DEC => true,
T_DIV_EQUAL => true,
T_DOUBLE_CAST => true,
T_FUNCTION => true,
T_INC => true,
T_INCLUDE => true,
T_INCLUDE_ONCE => true,
T_INSTANCEOF => true,
T_INT_CAST => true,
T_IS_EQUAL => true,
T_IS_GREATER_OR_EQUAL => true,
T_IS_IDENTICAL => true,
T_IS_NOT_EQUAL => true,
T_IS_NOT_IDENTICAL => true,
T_IS_SMALLER_OR_EQUAL => true,
T_LOGICAL_AND => true,
T_LOGICAL_OR => true,
T_LOGICAL_XOR => true,
T_MINUS_EQUAL => true,
T_MOD_EQUAL => true,
T_MUL_EQUAL => true,
T_OBJECT_CAST => true,
T_OR_EQUAL => true,
T_PLUS_EQUAL => true,
T_REQUIRE => true,
T_REQUIRE_ONCE => true,
T_SL => true,
T_SL_EQUAL => true,
T_SR => true,
T_SR_EQUAL => true,
T_STRING_CAST => true,
T_UNSET_CAST => true,
T_XOR_EQUAL => true,
T_POW => true,
T_POW_EQUAL => true,
T_SPACESHIP => true,
T_DOUBLE_ARROW => true,
T_FN => true,
T_COALESCE_EQUAL => true,
'!' => true,
'%' => true,
'&' => true,
'*' => true,
'+' => true,
'-' => true,
'.' => true,
'/' => true,
':' => true,
'<' => true,
'=' => true,
'>' => true,
'?' => true,
'^' => true,
'|' => true,
'~' => true,
];
private static array $preserve_spaces = [
T_CLASS => true,
T_NEW => true,
];
private static array $strip = [
'(' => true,
')' => true,
'[' => true,
']' => true,
'{' => true,
'}' => true,
T_OBJECT_OPERATOR => true,
T_DOUBLE_COLON => true,
T_NS_SEPARATOR => true,
];
private static array $classcalls = [
T_DOUBLE_COLON => true,
T_OBJECT_OPERATOR => true,
];
private static array $namespace = [
T_STRING => true,
];
/**
* @psalm-param callable-array|callable-string $function
*
* @psalm-return list<array{parameters: list<CallParameter>, modifiers: list<PhpToken>}>
*
* @return array List of matching calls on the relevant line
*/
public static function getFunctionCalls(string $source, int $line, $function): array
{
static $up = [
'(' => true,
'[' => true,
'{' => true,
T_CURLY_OPEN => true,
T_DOLLAR_OPEN_CURLY_BRACES => true,
];
static $down = [
')' => true,
']' => true,
'}' => true,
];
static $modifiers = [
'!' => true,
'@' => true,
'~' => true,
'+' => true,
'-' => true,
];
static $identifier = [
T_DOUBLE_COLON => true,
T_STRING => true,
T_NS_SEPARATOR => true,
];
if (KINT_PHP80) {
$up[T_ATTRIBUTE] = true;
self::$operator[T_MATCH] = true;
self::$strip[T_NULLSAFE_OBJECT_OPERATOR] = true;
self::$classcalls[T_NULLSAFE_OBJECT_OPERATOR] = true;
self::$namespace[T_NAME_FULLY_QUALIFIED] = true;
self::$namespace[T_NAME_QUALIFIED] = true;
self::$namespace[T_NAME_RELATIVE] = true;
$identifier[T_NAME_FULLY_QUALIFIED] = true;
$identifier[T_NAME_QUALIFIED] = true;
$identifier[T_NAME_RELATIVE] = true;
}
if (!KINT_PHP84) {
self::$operator[T_NEW] = true; // @codeCoverageIgnore
}
/** @psalm-var list<PhpToken> */
$tokens = \token_get_all($source);
$function_calls = [];
// Performance optimization preventing backwards loops
/** @psalm-var array<PhpToken|null> */
$prev_tokens = [null, null, null];
if (\is_array($function)) {
$class = \explode('\\', $function[0]);
$class = \strtolower(\end($class));
$function = \strtolower($function[1]);
} else {
$class = null;
/**
* @psalm-suppress RedundantFunctionCallGivenDocblockType
* Psalm bug #11075
*/
$function = \strtolower($function);
}
// Loop through tokens
foreach ($tokens as $index => $token) {
if (!\is_array($token)) {
continue;
}
if ($token[2] > $line) {
break;
}
// Store the last real tokens for later
if (isset(self::$ignore[$token[0]])) {
continue;
}
$prev_tokens = [$prev_tokens[1], $prev_tokens[2], $token];
// The logic for 7.3 through 8.1 is far more complicated.
// This should speed things up without making a lot more work for us
if (KINT_PHP82 && $line !== $token[2]) {
continue;
}
// Check if it's the right type to be the function we're looking for
if (!isset(self::$namespace[$token[0]])) {
continue;
}
$ns = \explode('\\', \strtolower($token[1]));
if (\end($ns) !== $function) {
continue;
}
// Check if it's a function call
$nextReal = self::realTokenIndex($tokens, $index);
if ('(' !== ($tokens[$nextReal] ?? null)) {
continue;
}
// Check if it matches the signature
if (null === $class) {
if (null !== $prev_tokens[1] && isset(self::$classcalls[$prev_tokens[1][0]])) {
continue;
}
} else {
if (null === $prev_tokens[1] || T_DOUBLE_COLON !== $prev_tokens[1][0]) {
continue;
}
if (null === $prev_tokens[0] || !isset(self::$namespace[$prev_tokens[0][0]])) {
continue;
}
// All self::$namespace tokens are T_ constants
/**
* @psalm-var PhpTokenArray $prev_tokens[0]
* Psalm bug #746 (wontfix)
*/
$ns = \explode('\\', \strtolower($prev_tokens[0][1]));
if (\end($ns) !== $class) {
continue;
}
}
$last_line = $token[2];
$depth = 1; // The depth respective to the function call
$offset = $nextReal + 1; // The start of the function call
$instring = false; // Whether we're in a string or not
$realtokens = false; // Whether the current scope contains anything meaningful or not
$paramrealtokens = false; // Whether the current parameter contains anything meaningful
$params = []; // All our collected parameters
$shortparam = []; // The short version of the parameter
$param_start = $offset; // The distance to the start of the parameter
// Loop through the following tokens until the function call ends
while (isset($tokens[$offset])) {
$token = $tokens[$offset];
if (\is_array($token)) {
$last_line = $token[2];
}
if (!isset(self::$ignore[$token[0]]) && !isset($down[$token[0]])) {
$paramrealtokens = $realtokens = true;
}
// If it's a token that makes us to up a level, increase the depth
if (isset($up[$token[0]])) {
if (1 === $depth) {
$shortparam[] = $token;
$realtokens = false;
}
++$depth;
} elseif (isset($down[$token[0]])) {
--$depth;
// If this brings us down to the parameter level, and we've had
// real tokens since going up, fill the $shortparam with an ellipsis
if (1 === $depth) {
if ($realtokens) {
$shortparam[] = '...';
}
$shortparam[] = $token;
}
} elseif ('"' === $token || 'b"' === $token) {
// Strings use the same symbol for up and down, but we can
// only ever be inside one string, so just use a bool for that
if ($instring) {
--$depth;
if (1 === $depth) {
$shortparam[] = '...';
}
} else {
++$depth;
}
$instring = !$instring;
$shortparam[] = $token;
} elseif (1 === $depth) {
if (',' === $token[0]) {
$params[] = [
'full' => \array_slice($tokens, $param_start, $offset - $param_start),
'short' => $shortparam,
];
$shortparam = [];
$paramrealtokens = false;
$param_start = $offset + 1;
} elseif (T_CONSTANT_ENCAPSED_STRING === $token[0]) {
$quote = $token[1][0];
if ('b' === $quote) {
$quote = $token[1][1];
if (\strlen($token[1]) > 3) {
$token[1] = 'b'.$quote.'...'.$quote;
}
} else {
if (\strlen($token[1]) > 2) {
$token[1] = $quote.'...'.$quote;
}
}
$shortparam[] = $token;
} else {
$shortparam[] = $token;
}
}
// Depth has dropped to 0 (So we've hit the closing paren)
if ($depth <= 0) {
if ($paramrealtokens) {
$params[] = [
'full' => \array_slice($tokens, $param_start, $offset - $param_start),
'short' => $shortparam,
];
}
break;
}
++$offset;
}
// If we're not passed (or at) the line at the end
// of the function call, we're too early so skip it
// Only applies to < 8.2 since we check line explicitly above that
if (!KINT_PHP82 && $last_line < $line) {
continue; // @codeCoverageIgnore
}
$formatted_parameters = [];
// Format the final output parameters
foreach ($params as $param) {
$name = self::tokensFormatted($param['short']);
$path = self::tokensToString(self::tokensTrim($param['full']));
$expression = false;
$literal = false;
$new_without_parens = false;
foreach ($name as $token) {
if (self::tokenIsOperator($token)) {
$expression = true;
break;
}
}
// As of 8.4 new is only an expression when parentheses are
// omitted. In that case we can cheat and add them ourselves.
//
// > PHP interprets the first expression after new as a class name
// per https://wiki.php.net/rfc/new_without_parentheses
if (KINT_PHP84 && !$expression && T_NEW === $name[0][0]) {
$had_name_token = false;
$new_without_parens = true;
foreach ($name as $token) {
if (T_NEW === $token[0]) {
continue;
}
if (isset(self::$ignore[$token[0]])) {
continue;
}
if (T_CLASS === $token[0]) {
$new_without_parens = false;
break;
}
if ('(' === $token && $had_name_token) {
$new_without_parens = false;
break;
}
$had_name_token = true;
}
}
if (!$expression && 1 === \count($name)) {
switch ($name[0][0]) {
case T_CONSTANT_ENCAPSED_STRING:
case T_LNUMBER:
case T_DNUMBER:
$literal = true;
break;
case T_STRING:
switch (\strtolower($name[0][1])) {
case 'null':
case 'true':
case 'false':
$literal = true;
}
}
$name = self::tokensToString($name);
} else {
$name = self::tokensToString($name);
if (!$expression) {
switch (\strtolower($name)) {
case 'array()':
case '[]':
$literal = true;
break;
}
}
}
$formatted_parameters[] = [
'name' => $name,
'path' => $path,
'expression' => $expression,
'literal' => $literal,
'new_without_parens' => $new_without_parens,
];
}
// Skip first-class callables
if (KINT_PHP81 && 1 === \count($formatted_parameters) && '...' === \reset($formatted_parameters)['path']) {
continue;
}
// Get the modifiers
--$index;
while (isset($tokens[$index])) {
if (!isset(self::$ignore[$tokens[$index][0]]) && !isset($identifier[$tokens[$index][0]])) {
break;
}
--$index;
}
$mods = [];
while (isset($tokens[$index])) {
if (isset(self::$ignore[$tokens[$index][0]])) {
--$index;
continue;
}
if (isset($modifiers[$tokens[$index][0]])) {
$mods[] = $tokens[$index];
--$index;
continue;
}
break;
}
$function_calls[] = [
'parameters' => $formatted_parameters,
'modifiers' => $mods,
];
}
return $function_calls;
}
private static function realTokenIndex(array $tokens, int $index): ?int
{
++$index;
while (isset($tokens[$index])) {
if (!isset(self::$ignore[$tokens[$index][0]])) {
return $index;
}
++$index;
}
return null;
}
/**
* We need a separate method to check if tokens are operators because we
* occasionally add "..." to short parameter versions. If we simply check
* for `$token[0]` then "..." will incorrectly match the "." operator.
*
* @psalm-param PhpToken $token The token to check
*/
private static function tokenIsOperator($token): bool
{
return '...' !== $token && isset(self::$operator[$token[0]]);
}
/**
* @psalm-param PhpToken $token The token to check
*/
private static function tokenPreserveWhitespace($token): bool
{
return self::tokenIsOperator($token) || isset(self::$preserve_spaces[$token[0]]);
}
private static function tokensToString(array $tokens): string
{
$out = '';
foreach ($tokens as $token) {
if (\is_string($token)) {
$out .= $token;
} else {
$out .= $token[1];
}
}
return $out;
}
private static function tokensTrim(array $tokens): array
{
foreach ($tokens as $index => $token) {
if (isset(self::$ignore[$token[0]])) {
unset($tokens[$index]);
} else {
break;
}
}
$tokens = \array_reverse($tokens);
foreach ($tokens as $index => $token) {
if (isset(self::$ignore[$token[0]])) {
unset($tokens[$index]);
} else {
break;
}
}
return \array_reverse($tokens);
}
private static function tokensFormatted(array $tokens): array
{
$tokens = self::tokensTrim($tokens);
$space = false;
$attribute = false;
// Keep space between "strip" symbols for different behavior for matches or closures
// Normally we want to strip spaces between strip tokens: $x{...}[...]
// However with closures and matches we don't: function (...) {...}
$ignorestrip = false;
$output = [];
$last = null;
if (T_FUNCTION === $tokens[0][0] ||
T_FN === $tokens[0][0] ||
(KINT_PHP80 && T_MATCH === $tokens[0][0])
) {
$ignorestrip = true;
}
foreach ($tokens as $index => $token) {
if (isset(self::$ignore[$token[0]])) {
if ($space) {
continue;
}
$next = self::realTokenIndex($tokens, $index);
if (null === $next) {
// This should be impossible, since we always call tokensTrim first
break; // @codeCoverageIgnore
}
$next = $tokens[$next];
/**
* @psalm-var PhpToken $last
* Since we call tokensTrim we know we can't be here without a $last
*/
if ($attribute && ']' === $last[0]) {
$attribute = false;
} elseif (!$ignorestrip && isset(self::$strip[$last[0]]) && !self::tokenPreserveWhitespace($next)) {
continue;
}
if (!$ignorestrip && isset(self::$strip[$next[0]]) && !self::tokenPreserveWhitespace($last)) {
continue;
}
$token[1] = ' ';
$space = true;
} else {
if (KINT_PHP80 && null !== $last && T_ATTRIBUTE === $last[0]) {
$attribute = true;
}
$space = false;
$last = $token;
}
$output[] = $token;
}
return $output;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Utils.php | system/ThirdParty/Kint/Utils.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint;
use Kint\Value\StringValue;
use Kint\Value\TraceFrameValue;
use ReflectionNamedType;
use ReflectionType;
use UnexpectedValueException;
/**
* A collection of utility methods. Should all be static methods with no dependencies.
*
* @psalm-import-type Encoding from StringValue
* @psalm-import-type TraceFrame from TraceFrameValue
*/
final class Utils
{
public const BT_STRUCTURE = [
'function' => 'string',
'line' => 'integer',
'file' => 'string',
'class' => 'string',
'object' => 'object',
'type' => 'string',
'args' => 'array',
];
public const BYTE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB'];
/**
* @var array Character encodings to detect
*
* @see https://secure.php.net/function.mb-detect-order
*
* In practice, mb_detect_encoding can only successfully determine the
* difference between the following common charsets at once without
* breaking things for one of the other charsets:
* - ASCII
* - UTF-8
* - SJIS
* - EUC-JP
*
* The order of the charsets is significant. If you put UTF-8 before ASCII
* it will never match ASCII, because UTF-8 is a superset of ASCII.
* Similarly, SJIS and EUC-JP frequently match UTF-8 strings, so you should
* check UTF-8 first. SJIS and EUC-JP seem to work either way, but SJIS is
* more common so it should probably be first.
*
* While you're free to experiment with other charsets, remember to keep
* this behavior in mind when setting up your char_encodings array.
*
* This depends on the mbstring extension
*/
public static array $char_encodings = [
'ASCII',
'UTF-8',
];
/**
* @var array Legacy character encodings to detect
*
* @see https://secure.php.net/function.iconv
*
* Assuming the other encoding checks fail, this will perform a
* simple iconv conversion to check for invalid bytes. If any are
* found it will not match.
*
* This can be useful for ambiguous single byte encodings like
* windows-125x and iso-8859-x which have practically undetectable
* differences because they use every single byte available.
*
* This is *NOT* reliable and should not be trusted implicitly. Since it
* works by triggering and suppressing conversion warnings, your error
* handler may complain.
*
* As with char_encodings, the order of the charsets is significant.
*
* This depends on the iconv extension
*/
public static array $legacy_encodings = [];
/**
* @var array Path aliases that will be displayed instead of the full path.
*
* Keys are paths, values are replacement strings
*
* Example for laravel:
*
* Utils::$path_aliases = [
* base_path() => '<BASE>',
* app_path() => '<APP>',
* base_path().'/vendor' => '<VENDOR>',
* ];
*
* Defaults to [$_SERVER['DOCUMENT_ROOT'] => '<ROOT>']
*
* @psalm-var array<non-empty-string, string>
*/
public static array $path_aliases = [];
/**
* @codeCoverageIgnore
*
* @psalm-suppress UnusedConstructor
*/
private function __construct()
{
}
/**
* Turns a byte value into a human-readable representation.
*
* @param int $value Amount of bytes
*
* @return array Human readable value and unit
*
* @psalm-return array{value: float, unit: 'B'|'KB'|'MB'|'GB'|'TB'}
*
* @psalm-pure
*/
public static function getHumanReadableBytes(int $value): array
{
$negative = $value < 0;
$value = \abs($value);
if ($value < 1024) {
$i = 0;
$value = \floor($value);
} elseif ($value < 0xFFFCCCCCCCCCCCC >> 40) {
$i = 1;
} elseif ($value < 0xFFFCCCCCCCCCCCC >> 30) {
$i = 2;
} elseif ($value < 0xFFFCCCCCCCCCCCC >> 20) {
$i = 3;
} else {
$i = 4;
}
if ($i) {
$value = $value / \pow(1024, $i);
}
if ($negative) {
$value *= -1;
}
return [
'value' => \round($value, 1),
'unit' => self::BYTE_UNITS[$i],
];
}
/** @psalm-pure */
public static function isSequential(array $array): bool
{
return \array_keys($array) === \range(0, \count($array) - 1);
}
/** @psalm-pure */
public static function isAssoc(array $array): bool
{
return (bool) \count(\array_filter(\array_keys($array), 'is_string'));
}
/**
* @psalm-assert-if-true list<TraceFrame> $trace
*/
public static function isTrace(array $trace): bool
{
if (!self::isSequential($trace)) {
return false;
}
$file_found = false;
foreach ($trace as $frame) {
if (!\is_array($frame) || !isset($frame['function'])) {
return false;
}
if (isset($frame['class']) && !\class_exists($frame['class'], false)) {
return false;
}
foreach ($frame as $key => $val) {
if (!isset(self::BT_STRUCTURE[$key])) {
return false;
}
if (\gettype($val) !== self::BT_STRUCTURE[$key]) {
return false;
}
if ('file' === $key) {
$file_found = true;
}
}
}
return $file_found;
}
/**
* @psalm-param TraceFrame $frame
*
* @psalm-pure
*/
public static function traceFrameIsListed(array $frame, array $matches): bool
{
if (isset($frame['class'])) {
$called = [\strtolower($frame['class']), \strtolower($frame['function'])];
} else {
$called = \strtolower($frame['function']);
}
return \in_array($called, $matches, true);
}
/** @psalm-pure */
public static function normalizeAliases(array $aliases): array
{
foreach ($aliases as $index => $alias) {
if (\is_array($alias) && 2 === \count($alias)) {
$alias = \array_values(\array_filter($alias, 'is_string'));
if (2 === \count($alias) && self::isValidPhpName($alias[1]) && self::isValidPhpNamespace($alias[0])) {
$aliases[$index] = [
\strtolower(\ltrim($alias[0], '\\')),
\strtolower($alias[1]),
];
} else {
unset($aliases[$index]);
continue;
}
} elseif (\is_string($alias)) {
if (self::isValidPhpNamespace($alias)) {
$alias = \explode('\\', \strtolower($alias));
$aliases[$index] = \end($alias);
} else {
unset($aliases[$index]);
continue;
}
} else {
unset($aliases[$index]);
}
}
return \array_values($aliases);
}
/** @psalm-pure */
public static function isValidPhpName(string $name): bool
{
return (bool) \preg_match('/^[a-zA-Z_\\x80-\\xff][a-zA-Z0-9_\\x80-\\xff]*$/', $name);
}
/** @psalm-pure */
public static function isValidPhpNamespace(string $ns): bool
{
$parts = \explode('\\', $ns);
if ('' === \reset($parts)) {
\array_shift($parts);
}
if (!\count($parts)) {
return false;
}
foreach ($parts as $part) {
if (!self::isValidPhpName($part)) {
return false;
}
}
return true;
}
/**
* trigger_error before PHP 8.1 truncates the error message at nul
* so we have to sanitize variable strings before using them.
*
* @psalm-pure
*/
public static function errorSanitizeString(string $input): string
{
if (KINT_PHP82 || '' === $input) {
return $input;
}
return \strtok($input, "\0"); // @codeCoverageIgnore
}
/** @psalm-pure */
public static function getTypeString(ReflectionType $type): string
{
// @codeCoverageIgnoreStart
// ReflectionType::__toString was deprecated in 7.4 and undeprecated in 8
// and toString doesn't correctly show the nullable ? in the type before 8
if (!KINT_PHP80) {
if (!$type instanceof ReflectionNamedType) {
throw new UnexpectedValueException('ReflectionType on PHP 7 must be ReflectionNamedType');
}
$name = $type->getName();
if ($type->allowsNull() && 'mixed' !== $name && false === \strpos($name, '|')) {
$name = '?'.$name;
}
return $name;
}
// @codeCoverageIgnoreEnd
return (string) $type;
}
/**
* @psalm-param Encoding $encoding
*/
public static function truncateString(string $input, int $length = PHP_INT_MAX, string $end = '...', $encoding = false): string
{
$endlength = self::strlen($end);
if ($endlength >= $length) {
$endlength = 0;
$end = '';
}
if (self::strlen($input, $encoding) > $length) {
return self::substr($input, 0, $length - $endlength, $encoding).$end;
}
return $input;
}
/**
* @psalm-return Encoding
*/
public static function detectEncoding(string $string)
{
if (\function_exists('mb_detect_encoding')) {
$ret = \mb_detect_encoding($string, self::$char_encodings, true);
if (false !== $ret) {
return $ret;
}
}
// Pretty much every character encoding uses first 32 bytes as control
// characters. If it's not a multi-byte format it's safe to say matching
// any control character besides tab, nl, and cr means it's binary.
if (\preg_match('/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]/', $string)) {
return false;
}
if (\function_exists('iconv')) {
foreach (self::$legacy_encodings as $encoding) {
// Iconv detection works by triggering
// "Detected an illegal character in input string" notices
// This notice does not become a TypeError with strict_types
// so we don't have to wrap this in a try catch
if (@\iconv($encoding, $encoding, $string) === $string) {
return $encoding;
}
}
} elseif (!\function_exists('mb_detect_encoding')) { // @codeCoverageIgnore
// If a user has neither mb_detect_encoding, nor iconv, nor the
// polyfills, there's not much we can do about it...
// Pretend it's ASCII and pray the browser renders it properly.
return 'ASCII'; // @codeCoverageIgnore
}
return false;
}
/**
* @psalm-param Encoding $encoding
*/
public static function strlen(string $string, $encoding = false): int
{
if (\function_exists('mb_strlen')) {
if (false === $encoding) {
$encoding = self::detectEncoding($string);
}
if (false !== $encoding && 'ASCII' !== $encoding) {
return \mb_strlen($string, $encoding);
}
}
return \strlen($string);
}
/**
* @psalm-param Encoding $encoding
*/
public static function substr(string $string, int $start, ?int $length = null, $encoding = false): string
{
if (\function_exists('mb_substr')) {
if (false === $encoding) {
$encoding = self::detectEncoding($string);
}
if (false !== $encoding && 'ASCII' !== $encoding) {
return \mb_substr($string, $start, $length, $encoding);
}
}
// Special case for substr/mb_substr discrepancy
if ('' === $string) {
return '';
}
return \substr($string, $start, $length ?? PHP_INT_MAX);
}
public static function shortenPath(string $file): string
{
$split = \explode('/', \str_replace('\\', '/', $file));
$longest_match = 0;
$match = '';
foreach (self::$path_aliases as $path => $alias) {
$path = \explode('/', \str_replace('\\', '/', $path));
if (\count($path) < 2) {
continue;
}
if (\array_slice($split, 0, \count($path)) === $path && \count($path) > $longest_match) {
$longest_match = \count($path);
$match = $alias;
}
}
if ($longest_match) {
$suffix = \implode('/', \array_slice($split, $longest_match));
if (\preg_match('%^/*$%', $suffix)) {
return $match;
}
return $match.'/'.$suffix;
}
// fallback to find common path with Kint dir
$kint = \explode('/', \str_replace('\\', '/', KINT_DIR));
$had_real_path_part = false;
foreach ($split as $i => $part) {
if (!isset($kint[$i]) || $kint[$i] !== $part) {
if (!$had_real_path_part) {
break;
}
$suffix = \implode('/', \array_slice($split, $i));
if (\preg_match('%^/*$%', $suffix)) {
break;
}
$prefix = $i > 1 ? '.../' : '/';
return $prefix.$suffix;
}
if ($i > 0 && \strlen($kint[$i])) {
$had_real_path_part = true;
}
}
return $file;
}
public static function composerGetExtras(string $key = 'kint'): array
{
if (0 === \strpos(KINT_DIR, 'phar://')) {
// Only run inside phar file, so skip for code coverage
return []; // @codeCoverageIgnore
}
$extras = [];
$folder = KINT_DIR.'/vendor';
for ($i = 0; $i < 4; ++$i) {
$installed = $folder.'/composer/installed.json';
if (\file_exists($installed) && \is_readable($installed)) {
$packages = \json_decode(\file_get_contents($installed), true);
if (!\is_array($packages)) {
continue;
}
// Composer 2.0 Compatibility: packages are now wrapped into a "packages" top level key instead of the whole file being the package array
// @see https://getcomposer.org/upgrade/UPGRADE-2.0.md
foreach ($packages['packages'] ?? $packages as $package) {
if (\is_array($package['extra'][$key] ?? null)) {
$extras = \array_replace($extras, $package['extra'][$key]);
}
}
$folder = \dirname($folder);
if (\file_exists($folder.'/composer.json') && \is_readable($folder.'/composer.json')) {
$composer = \json_decode(\file_get_contents($folder.'/composer.json'), true);
if (\is_array($composer['extra'][$key] ?? null)) {
$extras = \array_replace($extras, $composer['extra'][$key]);
}
}
break;
}
$folder = \dirname($folder);
}
return $extras;
}
/**
* @codeCoverageIgnore
*/
public static function composerSkipFlags(): void
{
if (\defined('KINT_SKIP_FACADE') && \defined('KINT_SKIP_HELPERS')) {
return;
}
$extras = self::composerGetExtras();
if (!empty($extras['disable-facade']) && !\defined('KINT_SKIP_FACADE')) {
\define('KINT_SKIP_FACADE', true);
}
if (!empty($extras['disable-helpers']) && !\defined('KINT_SKIP_HELPERS')) {
\define('KINT_SKIP_HELPERS', true);
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/init.php | system/ThirdParty/Kint/init.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use Kint\Kint;
use Kint\Renderer\AbstractRenderer;
use Kint\Utils;
if (\defined('KINT_DIR')) {
return;
}
if (\version_compare(PHP_VERSION, '7.4') < 0) {
throw new Exception('Kint 6 requires PHP 7.4 or higher');
}
\define('KINT_DIR', __DIR__);
\define('KINT_WIN', DIRECTORY_SEPARATOR !== '/');
\define('KINT_PHP80', \version_compare(PHP_VERSION, '8.0') >= 0);
\define('KINT_PHP81', \version_compare(PHP_VERSION, '8.1') >= 0);
\define('KINT_PHP82', \version_compare(PHP_VERSION, '8.2') >= 0);
\define('KINT_PHP83', \version_compare(PHP_VERSION, '8.3') >= 0);
\define('KINT_PHP84', \version_compare(PHP_VERSION, '8.4') >= 0);
\define('KINT_PHP85', \version_compare(PHP_VERSION, '8.5') >= 0);
// Dynamic default settings
if (\strlen((string) \ini_get('xdebug.file_link_format')) > 0) {
/** @psalm-var non-empty-string ini_get('xdebug.file_link_format') */
AbstractRenderer::$file_link_format = \ini_get('xdebug.file_link_format');
}
if (isset($_SERVER['DOCUMENT_ROOT']) && false === \strpos($_SERVER['DOCUMENT_ROOT'], "\0")) {
Utils::$path_aliases = [
$_SERVER['DOCUMENT_ROOT'] => '<ROOT>',
];
// Suppressed for unreadable document roots (related to open_basedir)
if (false !== @\realpath($_SERVER['DOCUMENT_ROOT'])) {
/** @psalm-suppress PropertyTypeCoercion */
Utils::$path_aliases[\realpath($_SERVER['DOCUMENT_ROOT'])] = '<ROOT>';
}
}
Utils::composerSkipFlags();
if ((!\defined('KINT_SKIP_FACADE') || !KINT_SKIP_FACADE) && !\class_exists('Kint')) {
\class_alias(Kint::class, 'Kint');
}
if (!\defined('KINT_SKIP_HELPERS') || !KINT_SKIP_HELPERS) {
require_once __DIR__.'/init_helpers.php';
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/FacadeInterface.php | system/ThirdParty/Kint/FacadeInterface.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint;
use Kint\Parser\Parser;
use Kint\Renderer\RendererInterface;
use Kint\Value\Context\ContextInterface;
interface FacadeInterface
{
public function __construct(Parser $p, RendererInterface $r);
public function setStatesFromStatics(array $statics): void;
public function setStatesFromCallInfo(array $info): void;
/**
* Renders a list of vars including the pre and post renders.
*
* @param array $vars Data to dump
* @param ContextInterface[] $base The base contexts
*/
public function dumpAll(array $vars, array $base): string;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/PlainRenderer.php | system/ThirdParty/Kint/Renderer/PlainRenderer.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer;
use Kint\Utils;
use Kint\Value\AbstractValue;
class PlainRenderer extends TextRenderer
{
use AssetRendererTrait;
public static array $pre_render_sources = [
'script' => [
[self::class, 'renderJs'],
],
'style' => [
[self::class, 'renderCss'],
],
'raw' => [],
];
/**
* Output htmlentities instead of utf8.
*/
public static bool $disable_utf8 = false;
public static bool $needs_pre_render = true;
public static bool $always_pre_render = false;
protected bool $force_pre_render = false;
public function __construct()
{
parent::__construct();
self::$theme ??= 'plain.css';
$this->setForcePreRender(self::$always_pre_render);
}
public function setCallInfo(array $info): void
{
parent::setCallInfo($info);
if (\in_array('@', $info['modifiers'], true)) {
$this->setForcePreRender(true);
}
}
public function setStatics(array $statics): void
{
parent::setStatics($statics);
if (!empty($statics['return'])) {
$this->setForcePreRender(true);
}
}
public function setForcePreRender(bool $force_pre_render): void
{
$this->force_pre_render = $force_pre_render;
}
public function getForcePreRender(): bool
{
return $this->force_pre_render;
}
public function shouldPreRender(): bool
{
return $this->getForcePreRender() || self::$needs_pre_render;
}
public function colorValue(string $string): string
{
return '<i>'.$string.'</i>';
}
public function colorType(string $string): string
{
return '<b>'.$string.'</b>';
}
public function colorTitle(string $string): string
{
return '<u>'.$string.'</u>';
}
public function renderTitle(AbstractValue $v): string
{
if (self::$disable_utf8) {
return $this->utf8ToHtmlentity(parent::renderTitle($v));
}
return parent::renderTitle($v);
}
public function preRender(): string
{
$output = '';
if ($this->shouldPreRender()) {
foreach (self::$pre_render_sources as $type => $values) {
$contents = '';
foreach ($values as $v) {
$contents .= \call_user_func($v, $this);
}
if (!\strlen($contents)) {
continue;
}
switch ($type) {
case 'script':
$output .= '<script class="kint-plain-script"';
if (null !== self::$js_nonce) {
$output .= ' nonce="'.\htmlspecialchars(self::$js_nonce).'"';
}
$output .= '>'.$contents.'</script>';
break;
case 'style':
$output .= '<style class="kint-plain-style"';
if (null !== self::$css_nonce) {
$output .= ' nonce="'.\htmlspecialchars(self::$css_nonce).'"';
}
$output .= '>'.$contents.'</style>';
break;
default:
$output .= $contents;
}
}
// Don't pre-render on every dump
if (!$this->getForcePreRender()) {
self::$needs_pre_render = false;
}
}
return $output.'<div class="kint-plain">';
}
public function postRender(): string
{
if (self::$disable_utf8) {
return $this->utf8ToHtmlentity(parent::postRender()).'</div>';
}
return parent::postRender().'</div>';
}
public function ideLink(string $file, int $line): string
{
$path = $this->escape(Utils::shortenPath($file)).':'.$line;
$ideLink = self::getFileLink($file, $line);
if (null === $ideLink) {
return $path;
}
return '<a href="'.$this->escape($ideLink).'">'.$path.'</a>';
}
public function escape(string $string, $encoding = false): string
{
if (false === $encoding) {
$encoding = Utils::detectEncoding($string);
}
$original_encoding = $encoding;
if (false === $encoding || 'ASCII' === $encoding) {
$encoding = 'UTF-8';
}
$string = \htmlspecialchars($string, ENT_NOQUOTES, $encoding);
// this call converts all non-ASCII characters into numeirc htmlentities
if (\function_exists('mb_encode_numericentity') && 'ASCII' !== $original_encoding) {
$string = \mb_encode_numericentity($string, [0x80, 0xFFFF, 0, 0xFFFF], $encoding);
}
return $string;
}
protected function utf8ToHtmlentity(string $string): string
{
return \str_replace(
['┌', '═', '┐', '│', '└', '─', '┘'],
['┌', '═', '┐', '│', '└', '─', '┘'],
$string
);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/CliRenderer.php | system/ThirdParty/Kint/Renderer/CliRenderer.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer;
use Kint\Value\AbstractValue;
use Throwable;
class CliRenderer extends TextRenderer
{
/**
* @var bool enable colors
*/
public static bool $cli_colors = true;
/**
* Detects the terminal width on startup.
*/
public static bool $detect_width = true;
/**
* The minimum width to detect terminal size as.
*
* Less than this is ignored and falls back to default width.
*/
public static int $min_terminal_width = 40;
/**
* Forces utf8 output on windows.
*/
public static bool $force_utf8 = false;
/**
* Which stream to check for VT100 support on windows.
*
* uses STDOUT by default if it's defined
*
* @psalm-var ?resource
*/
public static $windows_stream = null;
protected static ?int $terminal_width = null;
protected bool $windows_output = false;
protected bool $colors = false;
public function __construct()
{
parent::__construct();
if (!self::$force_utf8 && KINT_WIN) {
if (!\function_exists('sapi_windows_vt100_support')) {
$this->windows_output = true;
} else {
$stream = self::$windows_stream;
if (!$stream && \defined('STDOUT')) {
$stream = STDOUT;
}
if (!$stream) {
$this->windows_output = true;
} else {
$this->windows_output = !\sapi_windows_vt100_support($stream);
}
}
}
if (null === self::$terminal_width) {
if (self::$detect_width) {
try {
$tput = KINT_WIN ? \exec('tput cols 2>nul') : \exec('tput cols 2>/dev/null');
if ((bool) $tput) {
/**
* @psalm-suppress InvalidCast
* Psalm bug #11080
*/
self::$terminal_width = (int) $tput;
}
} catch (Throwable $t) {
self::$terminal_width = self::$default_width;
}
}
if (!isset(self::$terminal_width) || self::$terminal_width < self::$min_terminal_width) {
self::$terminal_width = self::$default_width;
}
}
$this->colors = $this->windows_output ? false : self::$cli_colors;
$this->header_width = self::$terminal_width;
}
public function colorValue(string $string): string
{
if (!$this->colors) {
return $string;
}
return "\x1b[32m".\str_replace("\n", "\x1b[0m\n\x1b[32m", $string)."\x1b[0m";
}
public function colorType(string $string): string
{
if (!$this->colors) {
return $string;
}
return "\x1b[35;1m".\str_replace("\n", "\x1b[0m\n\x1b[35;1m", $string)."\x1b[0m";
}
public function colorTitle(string $string): string
{
if (!$this->colors) {
return $string;
}
return "\x1b[36m".\str_replace("\n", "\x1b[0m\n\x1b[36m", $string)."\x1b[0m";
}
public function renderTitle(AbstractValue $v): string
{
if ($this->windows_output) {
return $this->utf8ToWindows(parent::renderTitle($v));
}
return parent::renderTitle($v);
}
public function preRender(): string
{
return PHP_EOL;
}
public function postRender(): string
{
if ($this->windows_output) {
return $this->utf8ToWindows(parent::postRender());
}
return parent::postRender();
}
public function escape(string $string, $encoding = false): string
{
return \str_replace("\x1b", '\\x1b', $string);
}
protected function utf8ToWindows(string $string): string
{
return \str_replace(
['┌', '═', '┐', '│', '└', '─', '┘'],
[' ', '=', ' ', '|', ' ', '-', ' '],
$string
);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/AbstractRenderer.php | system/ThirdParty/Kint/Renderer/AbstractRenderer.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer;
abstract class AbstractRenderer implements ConstructableRendererInterface
{
public static ?string $js_nonce = null;
public static ?string $css_nonce = null;
/** @psalm-var ?non-empty-string */
public static ?string $file_link_format = null;
protected bool $show_trace = true;
protected ?array $callee = null;
protected array $trace = [];
protected bool $render_spl_ids = true;
public function __construct()
{
}
public function shouldRenderObjectIds(): bool
{
return $this->render_spl_ids;
}
public function setCallInfo(array $info): void
{
$this->callee = $info['callee'] ?? null;
$this->trace = $info['trace'] ?? [];
}
public function setStatics(array $statics): void
{
$this->show_trace = !empty($statics['display_called_from']);
}
public function filterParserPlugins(array $plugins): array
{
return $plugins;
}
public function preRender(): string
{
return '';
}
public function postRender(): string
{
return '';
}
public static function getFileLink(string $file, int $line): ?string
{
if (null === self::$file_link_format) {
return null;
}
return \str_replace(['%f', '%l'], [$file, $line], self::$file_link_format);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/RichRenderer.php | system/ThirdParty/Kint/Renderer/RichRenderer.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer;
use Kint\Renderer\Rich\TabPluginInterface;
use Kint\Renderer\Rich\ValuePluginInterface;
use Kint\Utils;
use Kint\Value\AbstractValue;
use Kint\Value\Context\ClassDeclaredContext;
use Kint\Value\Context\ContextInterface;
use Kint\Value\Context\PropertyContext;
use Kint\Value\InstanceValue;
use Kint\Value\Representation;
use Kint\Value\Representation\ContainerRepresentation;
use Kint\Value\Representation\RepresentationInterface;
use Kint\Value\Representation\StringRepresentation;
use Kint\Value\Representation\ValueRepresentation;
use Kint\Value\StringValue;
/**
* @psalm-import-type Encoding from StringValue
*/
class RichRenderer extends AbstractRenderer
{
use AssetRendererTrait;
/**
* RichRenderer value plugins should implement ValuePluginInterface.
*
* @psalm-var class-string<ValuePluginInterface>[]
*/
public static array $value_plugins = [
'array_limit' => Rich\LockPlugin::class,
'blacklist' => Rich\LockPlugin::class,
'callable' => Rich\CallablePlugin::class,
'color' => Rich\ColorPlugin::class,
'depth_limit' => Rich\LockPlugin::class,
'recursion' => Rich\LockPlugin::class,
'trace_frame' => Rich\TraceFramePlugin::class,
];
/**
* RichRenderer tab plugins should implement TabPluginInterface.
*
* @psalm-var array<string, class-string<TabPluginInterface>>
*/
public static array $tab_plugins = [
'binary' => Rich\BinaryPlugin::class,
'callable' => Rich\CallableDefinitionPlugin::class,
'color' => Rich\ColorPlugin::class,
'microtime' => Rich\MicrotimePlugin::class,
'profiling' => Rich\ProfilePlugin::class,
'source' => Rich\SourcePlugin::class,
'table' => Rich\TablePlugin::class,
];
public static array $pre_render_sources = [
'script' => [
[self::class, 'renderJs'],
],
'style' => [
[self::class, 'renderCss'],
],
'raw' => [],
];
/**
* The maximum length of a string before it is truncated.
*
* Falsey to disable
*/
public static int $strlen_max = 80;
/**
* Timestamp to print in footer in date() format.
*/
public static ?string $timestamp = null;
/**
* Whether or not to render access paths.
*
* Access paths can become incredibly heavy with very deep and wide
* structures. Given mostly public variables it will typically make
* up one quarter of the output HTML size.
*
* If this is an unacceptably large amount and your browser is groaning
* under the weight of the access paths - your first order of buisiness
* should be to get a new browser. Failing that, use this to turn them off.
*/
public static bool $access_paths = true;
/**
* Assume types and sizes don't need to be escaped.
*
* Turn this off if you use anything but ascii in your class names,
* but it'll cause a slowdown of around 10%
*/
public static bool $escape_types = false;
/**
* Move all dumps to a folder at the bottom of the body.
*/
public static bool $folder = false;
public static bool $needs_pre_render = true;
public static bool $always_pre_render = false;
protected array $plugin_objs = [];
protected bool $expand = false;
protected bool $force_pre_render = false;
protected bool $use_folder = false;
public function __construct()
{
parent::__construct();
self::$theme ??= 'original.css';
$this->use_folder = self::$folder;
$this->force_pre_render = self::$always_pre_render;
}
public function setCallInfo(array $info): void
{
parent::setCallInfo($info);
if (\in_array('!', $info['modifiers'], true)) {
$this->expand = true;
$this->use_folder = false;
}
if (\in_array('@', $info['modifiers'], true)) {
$this->force_pre_render = true;
}
}
public function setStatics(array $statics): void
{
parent::setStatics($statics);
if (!empty($statics['expanded'])) {
$this->expand = true;
}
if (!empty($statics['return'])) {
$this->force_pre_render = true;
}
}
public function shouldPreRender(): bool
{
return $this->force_pre_render || self::$needs_pre_render;
}
public function render(AbstractValue $v): string
{
$render_spl_ids_stash = $this->render_spl_ids;
if ($this->render_spl_ids && $v->flags & AbstractValue::FLAG_GENERATED) {
$this->render_spl_ids = false;
}
if ($plugin = $this->getValuePlugin($v)) {
$output = $plugin->renderValue($v);
if (null !== $output && \strlen($output)) {
if (!$this->render_spl_ids && $render_spl_ids_stash) {
$this->render_spl_ids = true;
}
return $output;
}
}
$children = $this->renderChildren($v);
$header = $this->renderHeaderWrapper($v->getContext(), (bool) \strlen($children), $this->renderHeader($v));
if (!$this->render_spl_ids && $render_spl_ids_stash) {
$this->render_spl_ids = true;
}
return '<dl>'.$header.$children.'</dl>';
}
public function renderHeaderWrapper(ContextInterface $c, bool $has_children, string $contents): string
{
$out = '<dt';
if ($has_children) {
$out .= ' class="kint-parent';
if ($this->expand) {
$out .= ' kint-show';
}
$out .= '"';
}
$out .= '>';
if (self::$access_paths && $c->getDepth() > 0 && null !== ($ap = $c->getAccessPath())) {
$out .= '<span class="kint-access-path-trigger" title="Show access path"></span>';
}
if ($has_children) {
if (0 === $c->getDepth()) {
if (!$this->use_folder) {
$out .= '<span class="kint-folder-trigger" title="Move to folder"></span>';
}
$out .= '<span class="kint-search-trigger" title="Show search box"></span>';
$out .= '<input type="text" class="kint-search" value="">';
}
$out .= '<nav></nav>';
}
$out .= $contents;
if (!empty($ap)) {
$out .= '<div class="access-path">'.$this->escape($ap).'</div>';
}
return $out.'</dt>';
}
public function renderHeader(AbstractValue $v): string
{
$c = $v->getContext();
$output = '';
if ($c instanceof ClassDeclaredContext) {
$output .= '<var>'.$c->getModifiers().'</var> ';
}
$output .= '<dfn>'.$this->escape($v->getDisplayName()).'</dfn> ';
if ($c instanceof PropertyContext && null !== ($s = $c->getHooks())) {
$output .= '<var>'.$this->escape($s).'</var> ';
}
if (null !== ($s = $c->getOperator())) {
$output .= $this->escape($s, 'ASCII').' ';
}
$s = $v->getDisplayType();
if (self::$escape_types) {
$s = $this->escape($s);
}
if ($c->isRef()) {
$s = '&'.$s;
}
$output .= '<var>'.$s.'</var>';
if ($v instanceof InstanceValue && $this->shouldRenderObjectIds()) {
$output .= '#'.$v->getSplObjectId();
}
$output .= ' ';
if (null !== ($s = $v->getDisplaySize())) {
if (self::$escape_types) {
$s = $this->escape($s);
}
$output .= '('.$s.') ';
}
if (null !== ($s = $v->getDisplayValue())) {
$s = \preg_replace('/\\s+/', ' ', $s);
if (self::$strlen_max) {
$s = Utils::truncateString($s, self::$strlen_max);
}
$output .= $this->escape($s);
}
return \trim($output);
}
public function renderChildren(AbstractValue $v): string
{
$contents = [];
$tabs = [];
foreach ($v->getRepresentations() as $rep) {
$result = $this->renderTab($v, $rep);
if (\strlen($result)) {
$contents[] = $result;
$tabs[] = $rep;
}
}
if (empty($tabs)) {
return '';
}
$output = '<dd>';
if (1 === \count($tabs) && $tabs[0]->labelIsImplicit()) {
$output .= \reset($contents);
} else {
$output .= '<ul class="kint-tabs">';
foreach ($tabs as $i => $tab) {
if (0 === $i) {
$output .= '<li class="kint-active-tab">';
} else {
$output .= '<li>';
}
$output .= $this->escape($tab->getLabel()).'</li>';
}
$output .= '</ul><ul class="kint-tab-contents">';
foreach ($contents as $i => $tab) {
if (0 === $i) {
$output .= '<li class="kint-show">';
} else {
$output .= '<li>';
}
$output .= $tab.'</li>';
}
$output .= '</ul>';
}
return $output.'</dd>';
}
public function preRender(): string
{
$output = '';
if ($this->shouldPreRender()) {
foreach (self::$pre_render_sources as $type => $values) {
$contents = '';
foreach ($values as $v) {
$contents .= \call_user_func($v, $this);
}
if (!\strlen($contents)) {
continue;
}
switch ($type) {
case 'script':
$output .= '<script class="kint-rich-script"';
if (null !== self::$js_nonce) {
$output .= ' nonce="'.\htmlspecialchars(self::$js_nonce).'"';
}
$output .= '>'.$contents.'</script>';
break;
case 'style':
$output .= '<style class="kint-rich-style"';
if (null !== self::$css_nonce) {
$output .= ' nonce="'.\htmlspecialchars(self::$css_nonce).'"';
}
$output .= '>'.$contents.'</style>';
break;
default:
$output .= $contents;
}
}
// Don't pre-render on every dump
if (!$this->force_pre_render) {
self::$needs_pre_render = false;
}
}
$output .= '<div class="kint-rich';
if ($this->use_folder) {
$output .= ' kint-file';
}
$output .= '">';
return $output;
}
public function postRender(): string
{
if (!$this->show_trace) {
return '</div>';
}
$output = '<footer';
if ($this->expand) {
$output .= ' class="kint-show"';
}
$output .= '>';
if (!$this->use_folder) {
$output .= '<span class="kint-folder-trigger" title="Move to folder">↧</span>';
}
if (!empty($this->trace) && \count($this->trace) > 1) {
$output .= '<nav></nav>';
}
$output .= $this->calledFrom();
if (!empty($this->trace) && \count($this->trace) > 1) {
$output .= '<ol>';
foreach ($this->trace as $index => $step) {
if (!$index) {
continue;
}
$output .= '<li>'.$this->ideLink($step['file'], $step['line']); // closing tag not required
if (isset($step['function']) &&
!\in_array($step['function'], ['include', 'include_once', 'require', 'require_once'], true)
) {
$output .= ' [';
$output .= $step['class'] ?? '';
$output .= $step['type'] ?? '';
$output .= $step['function'].'()]';
}
}
$output .= '</ol>';
}
$output .= '</footer></div>';
return $output;
}
/**
* @psalm-param Encoding $encoding
*/
public function escape(string $string, $encoding = false): string
{
if (false === $encoding) {
$encoding = Utils::detectEncoding($string);
}
$original_encoding = $encoding;
if (false === $encoding || 'ASCII' === $encoding) {
$encoding = 'UTF-8';
}
$string = \htmlspecialchars($string, ENT_NOQUOTES, $encoding);
// this call converts all non-ASCII characters into numeirc htmlentities
if (\function_exists('mb_encode_numericentity') && 'ASCII' !== $original_encoding) {
$string = \mb_encode_numericentity($string, [0x80, 0xFFFF, 0, 0xFFFF], $encoding);
}
return $string;
}
public function ideLink(string $file, int $line): string
{
$path = $this->escape(Utils::shortenPath($file)).':'.$line;
$ideLink = self::getFileLink($file, $line);
if (null === $ideLink) {
return $path;
}
return '<a href="'.$this->escape($ideLink).'">'.$path.'</a>';
}
protected function calledFrom(): string
{
$output = '';
if (isset($this->callee['file'])) {
$output .= ' '.$this->ideLink(
$this->callee['file'],
$this->callee['line']
);
}
if (
isset($this->callee['function']) &&
(
!empty($this->callee['class']) ||
!\in_array(
$this->callee['function'],
['include', 'include_once', 'require', 'require_once'],
true
)
)
) {
$output .= ' [';
$output .= $this->callee['class'] ?? '';
$output .= $this->callee['type'] ?? '';
$output .= $this->callee['function'].'()]';
}
if ('' !== $output) {
$output = 'Called from'.$output;
}
if (null !== self::$timestamp) {
$output .= ' '.\date(self::$timestamp);
}
return $output;
}
protected function renderTab(AbstractValue $v, RepresentationInterface $rep): string
{
if ($plugin = $this->getTabPlugin($rep)) {
$output = $plugin->renderTab($rep, $v);
if (null !== $output) {
return $output;
}
}
if ($rep instanceof ValueRepresentation) {
return $this->render($rep->getValue());
}
if ($rep instanceof ContainerRepresentation) {
$output = '';
foreach ($rep->getContents() as $obj) {
$output .= $this->render($obj);
}
return $output;
}
if ($rep instanceof StringRepresentation) {
// If we're dealing with the content representation
if ($v instanceof StringValue && $rep->getValue() === $v->getValue()) {
// Only show the contents if:
if (\preg_match('/(:?[\\r\\n\\t\\f\\v]| {2})/', $rep->getValue())) {
// We have unrepresentable whitespace (Without whitespace preservation)
$show_contents = true;
} elseif (self::$strlen_max && Utils::strlen($v->getDisplayValue()) > self::$strlen_max) {
// We had to truncate getDisplayValue
$show_contents = true;
} else {
$show_contents = false;
}
} else {
$show_contents = true;
}
if ($show_contents) {
return '<pre>'.$this->escape($rep->getValue())."\n</pre>";
}
}
return '';
}
protected function getValuePlugin(AbstractValue $v): ?ValuePluginInterface
{
$hint = $v->getHint();
if (null === $hint || !isset(self::$value_plugins[$hint])) {
return null;
}
$plugin = self::$value_plugins[$hint];
if (!\is_a($plugin, ValuePluginInterface::class, true)) {
return null;
}
if (!isset($this->plugin_objs[$plugin])) {
$this->plugin_objs[$plugin] = new $plugin($this);
}
return $this->plugin_objs[$plugin];
}
protected function getTabPlugin(RepresentationInterface $r): ?TabPluginInterface
{
$hint = $r->getHint();
if (null === $hint || !isset(self::$tab_plugins[$hint])) {
return null;
}
$plugin = self::$tab_plugins[$hint];
if (!\is_a($plugin, TabPluginInterface::class, true)) {
return null;
}
if (!isset($this->plugin_objs[$plugin])) {
$this->plugin_objs[$plugin] = new $plugin($this);
}
return $this->plugin_objs[$plugin];
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/AssetRendererTrait.php | system/ThirdParty/Kint/Renderer/AssetRendererTrait.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer;
trait AssetRendererTrait
{
public static ?string $theme = null;
/** @psalm-var array{js?:string, css?:array<path, string|false>} */
private static array $assetCache = [];
/** @psalm-api */
public static function renderJs(): string
{
if (!isset(self::$assetCache['js'])) {
self::$assetCache['js'] = \file_get_contents(KINT_DIR.'/resources/compiled/main.js');
}
return self::$assetCache['js'];
}
/** @psalm-api */
public static function renderCss(): ?string
{
if (!isset(self::$theme)) {
return null;
}
if (!isset(self::$assetCache['css'][self::$theme])) {
if (\file_exists(KINT_DIR.'/resources/compiled/'.self::$theme)) {
self::$assetCache['css'][self::$theme] = \file_get_contents(KINT_DIR.'/resources/compiled/'.self::$theme);
} elseif (\file_exists(self::$theme)) {
self::$assetCache['css'][self::$theme] = \file_get_contents(self::$theme);
} else {
self::$assetCache['css'][self::$theme] = false;
}
}
if (false === self::$assetCache['css'][self::$theme]) {
return null;
}
return self::$assetCache['css'][self::$theme];
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/TextRenderer.php | system/ThirdParty/Kint/Renderer/TextRenderer.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer;
use Kint\Parser;
use Kint\Parser\PluginInterface as ParserPluginInterface;
use Kint\Renderer\Text\PluginInterface;
use Kint\Utils;
use Kint\Value\AbstractValue;
use Kint\Value\ArrayValue;
use Kint\Value\Context\ArrayContext;
use Kint\Value\Context\ClassDeclaredContext;
use Kint\Value\Context\PropertyContext;
use Kint\Value\InstanceValue;
use Kint\Value\StringValue;
/**
* @psalm-import-type Encoding from StringValue
*/
class TextRenderer extends AbstractRenderer
{
/**
* TextRenderer plugins should implement PluginInterface.
*
* @psalm-var class-string<PluginInterface>[]
*/
public static array $plugins = [
'array_limit' => Text\LockPlugin::class,
'blacklist' => Text\LockPlugin::class,
'depth_limit' => Text\LockPlugin::class,
'splfileinfo' => Text\SplFileInfoPlugin::class,
'microtime' => Text\MicrotimePlugin::class,
'recursion' => Text\LockPlugin::class,
'trace' => Text\TracePlugin::class,
];
/**
* Parser plugins must be instanceof one of these or
* it will be removed for performance reasons.
*
* @psalm-var class-string<ParserPluginInterface>[]
*/
public static array $parser_plugin_whitelist = [
Parser\ArrayLimitPlugin::class,
Parser\ArrayObjectPlugin::class,
Parser\BlacklistPlugin::class,
Parser\ClosurePlugin::class,
Parser\DateTimePlugin::class,
Parser\DomPlugin::class,
Parser\EnumPlugin::class,
Parser\IteratorPlugin::class,
Parser\MicrotimePlugin::class,
Parser\MysqliPlugin::class,
Parser\SimpleXMLElementPlugin::class,
Parser\SplFileInfoPlugin::class,
Parser\StreamPlugin::class,
Parser\TracePlugin::class,
];
/**
* The maximum length of a string before it is truncated.
*
* Falsey to disable
*/
public static int $strlen_max = 0;
/**
* Timestamp to print in footer in date() format.
*/
public static ?string $timestamp = null;
/**
* The default width of the terminal for headers.
*/
public static int $default_width = 80;
/**
* Indentation width.
*/
public static int $default_indent = 4;
/**
* Decorate the header and footer.
*/
public static bool $decorations = true;
public int $header_width = 80;
public int $indent_width = 4;
protected array $plugin_objs = [];
public function __construct()
{
parent::__construct();
$this->header_width = self::$default_width;
$this->indent_width = self::$default_indent;
}
public function render(AbstractValue $v): string
{
$render_spl_ids_stash = $this->render_spl_ids;
if ($this->render_spl_ids && ($v->flags & AbstractValue::FLAG_GENERATED)) {
$this->render_spl_ids = false;
}
if ($plugin = $this->getPlugin($v)) {
$output = $plugin->render($v);
if (null !== $output && \strlen($output)) {
if (!$this->render_spl_ids && $render_spl_ids_stash) {
$this->render_spl_ids = true;
}
return $output;
}
}
$out = '';
$c = $v->getContext();
if (0 === $c->getDepth()) {
$out .= $this->colorTitle($this->renderTitle($v)).PHP_EOL;
}
$out .= $header = $this->renderHeader($v);
$out .= $this->renderChildren($v);
if (\strlen($header)) {
$out .= PHP_EOL;
}
if (!$this->render_spl_ids && $render_spl_ids_stash) {
$this->render_spl_ids = true;
}
return $out;
}
public function boxText(string $text, int $width): string
{
$out = '┌'.\str_repeat('─', $width - 2).'┐'.PHP_EOL;
if (\strlen($text)) {
$text = Utils::truncateString($text, $width - 4);
$text = \str_pad($text, $width - 4);
$out .= '│ '.$this->escape($text).' │'.PHP_EOL;
}
$out .= '└'.\str_repeat('─', $width - 2).'┘';
return $out;
}
public function renderTitle(AbstractValue $v): string
{
if (self::$decorations) {
return $this->boxText($v->getDisplayName(), $this->header_width);
}
return Utils::truncateString($v->getDisplayName(), $this->header_width);
}
public function renderHeader(AbstractValue $v): string
{
$output = [];
$c = $v->getContext();
if ($c->getDepth() > 0) {
if ($c instanceof ClassDeclaredContext) {
$output[] = $this->colorType($c->getModifiers());
}
if ($c instanceof ArrayContext) {
$output[] = $this->escape(\var_export($c->getName(), true));
} else {
$output[] = $this->escape((string) $c->getName());
}
if ($c instanceof PropertyContext && null !== ($s = $c->getHooks())) {
$output[] = $this->colorType($this->escape($s));
}
if (null !== ($s = $c->getOperator())) {
$output[] = $this->escape($s);
}
}
$s = $v->getDisplayType();
if ($c->isRef()) {
$s = '&'.$s;
}
$s = $this->colorType($this->escape($s));
if ($v instanceof InstanceValue && $this->shouldRenderObjectIds()) {
$s .= '#'.$v->getSplObjectId();
}
$output[] = $s;
if (null !== ($s = $v->getDisplaySize())) {
$output[] = '('.$this->escape($s).')';
}
if (null !== ($s = $v->getDisplayValue())) {
if (self::$strlen_max) {
$s = Utils::truncateString($s, self::$strlen_max);
}
$output[] = $this->colorValue($this->escape($s));
}
return \str_repeat(' ', $c->getDepth() * $this->indent_width).\implode(' ', $output);
}
public function renderChildren(AbstractValue $v): string
{
$children = $v->getDisplayChildren();
if (!$children) {
if ($v instanceof ArrayValue) {
return ' []';
}
return '';
}
if ($v instanceof ArrayValue) {
$output = ' [';
} elseif ($v instanceof InstanceValue) {
$output = ' (';
} else {
$output = '';
}
$output .= PHP_EOL;
foreach ($children as $child) {
$output .= $this->render($child);
}
$indent = \str_repeat(' ', $v->getContext()->getDepth() * $this->indent_width);
if ($v instanceof ArrayValue) {
$output .= $indent.']';
} elseif ($v instanceof InstanceValue) {
$output .= $indent.')';
}
return $output;
}
public function colorValue(string $string): string
{
return $string;
}
public function colorType(string $string): string
{
return $string;
}
public function colorTitle(string $string): string
{
return $string;
}
public function postRender(): string
{
if (self::$decorations) {
$output = \str_repeat('═', $this->header_width);
} else {
$output = '';
}
if (!$this->show_trace) {
return $this->colorTitle($output);
}
if ($output) {
$output .= PHP_EOL;
}
return $this->colorTitle($output.$this->calledFrom().PHP_EOL);
}
public function filterParserPlugins(array $plugins): array
{
$return = [];
foreach ($plugins as $plugin) {
foreach (self::$parser_plugin_whitelist as $whitelist) {
if ($plugin instanceof $whitelist) {
$return[] = $plugin;
continue 2;
}
}
}
return $return;
}
public function ideLink(string $file, int $line): string
{
return $this->escape(Utils::shortenPath($file)).':'.$line;
}
/**
* @psalm-param Encoding $encoding
*/
public function escape(string $string, $encoding = false): string
{
return $string;
}
protected function calledFrom(): string
{
$output = '';
if (isset($this->callee['file'])) {
$output .= 'Called from '.$this->ideLink(
$this->callee['file'],
$this->callee['line']
);
}
if (
isset($this->callee['function']) &&
(
!empty($this->callee['class']) ||
!\in_array(
$this->callee['function'],
['include', 'include_once', 'require', 'require_once'],
true
)
)
) {
$output .= ' [';
$output .= $this->callee['class'] ?? '';
$output .= $this->callee['type'] ?? '';
$output .= $this->callee['function'].'()]';
}
if (null !== self::$timestamp) {
if (\strlen($output)) {
$output .= ' ';
}
$output .= \date(self::$timestamp);
}
return $output;
}
protected function getPlugin(AbstractValue $v): ?PluginInterface
{
$hint = $v->getHint();
if (null === $hint || !isset(self::$plugins[$hint])) {
return null;
}
$plugin = self::$plugins[$hint];
if (!\is_a($plugin, PluginInterface::class, true)) {
return null;
}
if (!isset($this->plugin_objs[$plugin])) {
$this->plugin_objs[$plugin] = new $plugin($this);
}
return $this->plugin_objs[$plugin];
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/RendererInterface.php | system/ThirdParty/Kint/Renderer/RendererInterface.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer;
use Kint\Value\AbstractValue;
interface RendererInterface
{
public function render(AbstractValue $v): string;
public function shouldRenderObjectIds(): bool;
public function setCallInfo(array $info): void;
public function setStatics(array $statics): void;
public function filterParserPlugins(array $plugins): array;
public function preRender(): string;
public function postRender(): string;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/ConstructableRendererInterface.php | system/ThirdParty/Kint/Renderer/ConstructableRendererInterface.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer;
interface ConstructableRendererInterface extends RendererInterface
{
public function __construct();
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/Text/PluginInterface.php | system/ThirdParty/Kint/Renderer/Text/PluginInterface.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer\Text;
use Kint\Renderer\TextRenderer;
use Kint\Value\AbstractValue;
interface PluginInterface
{
public function __construct(TextRenderer $r);
public function render(AbstractValue $v): ?string;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/Text/SplFileInfoPlugin.php | system/ThirdParty/Kint/Renderer/Text/SplFileInfoPlugin.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer\Text;
use Kint\Value\AbstractValue;
use Kint\Value\Representation\SplFileInfoRepresentation;
class SplFileInfoPlugin extends AbstractPlugin
{
public function render(AbstractValue $v): ?string
{
$r = $v->getRepresentation('splfileinfo');
if (!$r instanceof SplFileInfoRepresentation) {
return null;
}
$out = '';
$c = $v->getContext();
if (0 === $c->getDepth()) {
$out .= $this->renderer->colorTitle($this->renderer->renderTitle($v)).PHP_EOL;
}
$out .= $this->renderer->renderHeader($v);
if (null !== $v->getDisplayValue()) {
$out .= ' =>';
}
$out .= ' '.$this->renderer->colorValue($this->renderer->escape($r->getValue())).PHP_EOL;
return $out;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/Text/LockPlugin.php | system/ThirdParty/Kint/Renderer/Text/LockPlugin.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer\Text;
use Kint\Value\AbstractValue;
class LockPlugin extends AbstractPlugin
{
public function render(AbstractValue $v): ?string
{
switch ($v->getHint()) {
case 'blacklist':
return $this->renderLockedHeader($v, 'BLACKLISTED');
case 'recursion':
return $this->renderLockedHeader($v, 'RECURSION');
case 'depth_limit':
return $this->renderLockedHeader($v, 'DEPTH LIMIT');
case 'array_limit':
return $this->renderLockedHeader($v, 'ARRAY LIMIT');
}
return null;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/Text/TracePlugin.php | system/ThirdParty/Kint/Renderer/Text/TracePlugin.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer\Text;
use Kint\Value\AbstractValue;
use Kint\Value\MethodValue;
use Kint\Value\Representation\SourceRepresentation;
use Kint\Value\TraceFrameValue;
use Kint\Value\TraceValue;
class TracePlugin extends AbstractPlugin
{
public function render(AbstractValue $v): ?string
{
if (!$v instanceof TraceValue) {
return null;
}
$c = $v->getContext();
$out = '';
if (0 === $c->getDepth()) {
$out .= $this->renderer->colorTitle($this->renderer->renderTitle($v)).PHP_EOL;
}
$out .= $this->renderer->renderHeader($v).':'.PHP_EOL;
$indent = \str_repeat(' ', ($c->getDepth() + 1) * $this->renderer->indent_width);
$i = 1;
foreach ($v->getContents() as $frame) {
if (!$frame instanceof TraceFrameValue) {
continue;
}
$framedesc = $indent.\str_pad($i.': ', 4, ' ');
if (null !== ($file = $frame->getFile()) && null !== ($line = $frame->getLine())) {
$framedesc .= $this->renderer->ideLink($file, $line).PHP_EOL;
} else {
$framedesc .= 'PHP internal call'.PHP_EOL;
}
if ($callable = $frame->getCallable()) {
$framedesc .= $indent.' ';
if ($callable instanceof MethodValue) {
$framedesc .= $this->renderer->escape($callable->getContext()->owner_class.$callable->getContext()->getOperator());
}
$framedesc .= $this->renderer->escape($callable->getDisplayName());
}
$out .= $this->renderer->colorType($framedesc).PHP_EOL.PHP_EOL;
$source = $frame->getRepresentation('source');
if ($source instanceof SourceRepresentation) {
$line_wanted = $source->getLine();
$source = $source->getSourceLines();
// Trim empty lines from the start and end of the source
foreach ($source as $linenum => $line) {
if (\trim($line) || $linenum === $line_wanted) {
break;
}
unset($source[$linenum]);
}
foreach (\array_reverse($source, true) as $linenum => $line) {
if (\trim($line) || $linenum === $line_wanted) {
break;
}
unset($source[$linenum]);
}
foreach ($source as $lineno => $line) {
if ($lineno === $line_wanted) {
$out .= $indent.$this->renderer->colorValue($this->renderer->escape($line)).PHP_EOL;
} else {
$out .= $indent.$this->renderer->escape($line).PHP_EOL;
}
}
}
++$i;
}
return $out;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/Text/MicrotimePlugin.php | system/ThirdParty/Kint/Renderer/Text/MicrotimePlugin.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer\Text;
use Kint\Renderer\PlainRenderer;
use Kint\Renderer\TextRenderer;
use Kint\Utils;
use Kint\Value\AbstractValue;
use Kint\Value\Representation\MicrotimeRepresentation;
class MicrotimePlugin extends AbstractPlugin
{
protected bool $useJs = false;
public function __construct(TextRenderer $r)
{
parent::__construct($r);
if ($this->renderer instanceof PlainRenderer) {
$this->useJs = true;
}
}
public function render(AbstractValue $v): ?string
{
$r = $v->getRepresentation('microtime');
if (!$r instanceof MicrotimeRepresentation || !($dt = $r->getDateTime())) {
return null;
}
$c = $v->getContext();
$out = '';
if (0 === $c->getDepth()) {
$out .= $this->renderer->colorTitle($this->renderer->renderTitle($v)).PHP_EOL;
}
$out .= $this->renderer->renderHeader($v);
$out .= $this->renderer->renderChildren($v).PHP_EOL;
$indent = \str_repeat(' ', ($c->getDepth() + 1) * $this->renderer->indent_width);
if ($this->useJs) {
$out .= '<span data-kint-microtime-group="'.$r->getGroup().'">';
}
$out .= $indent.$this->renderer->colorType('TIME:').' ';
$out .= $this->renderer->colorValue($dt->format('Y-m-d H:i:s.u')).PHP_EOL;
if (null !== ($lap = $r->getLapTime())) {
$out .= $indent.$this->renderer->colorType('SINCE LAST CALL:').' ';
$lap = \round($lap, 4);
if ($this->useJs) {
$lap = '<span class="kint-microtime-lap">'.$lap.'</span>';
}
$out .= $this->renderer->colorValue($lap.'s').'.'.PHP_EOL;
}
if (null !== ($total = $r->getTotalTime())) {
$out .= $indent.$this->renderer->colorType('SINCE START:').' ';
$out .= $this->renderer->colorValue(\round($total, 4).'s').'.'.PHP_EOL;
}
if (null !== ($avg = $r->getAverageTime())) {
$out .= $indent.$this->renderer->colorType('AVERAGE DURATION:').' ';
$avg = \round($avg, 4);
if ($this->useJs) {
$avg = '<span class="kint-microtime-avg">'.$avg.'</span>';
}
$out .= $this->renderer->colorValue($avg.'s').'.'.PHP_EOL;
}
$bytes = Utils::getHumanReadableBytes($r->getMemoryUsage());
$mem = $r->getMemoryUsage().' bytes ('.\round($bytes['value'], 3).' '.$bytes['unit'].')';
$bytes = Utils::getHumanReadableBytes($r->getMemoryUsageReal());
$mem .= ' (real '.\round($bytes['value'], 3).' '.$bytes['unit'].')';
$out .= $indent.$this->renderer->colorType('MEMORY USAGE:').' ';
$out .= $this->renderer->colorValue($mem).'.'.PHP_EOL;
$bytes = Utils::getHumanReadableBytes($r->getMemoryPeakUsage());
$mem = $r->getMemoryPeakUsage().' bytes ('.\round($bytes['value'], 3).' '.$bytes['unit'].')';
$bytes = Utils::getHumanReadableBytes($r->getMemoryPeakUsageReal());
$mem .= ' (real '.\round($bytes['value'], 3).' '.$bytes['unit'].')';
$out .= $indent.$this->renderer->colorType('PEAK MEMORY USAGE:').' ';
$out .= $this->renderer->colorValue($mem).'.'.PHP_EOL;
if ($this->useJs) {
$out .= '</span>';
}
return $out;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/Text/AbstractPlugin.php | system/ThirdParty/Kint/Renderer/Text/AbstractPlugin.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer\Text;
use Kint\Renderer\TextRenderer;
use Kint\Value\AbstractValue;
abstract class AbstractPlugin implements PluginInterface
{
protected TextRenderer $renderer;
public function __construct(TextRenderer $r)
{
$this->renderer = $r;
}
public function renderLockedHeader(AbstractValue $v, ?string $content = null): string
{
$out = '';
if (0 === $v->getContext()->getDepth()) {
$out .= $this->renderer->colorTitle($this->renderer->renderTitle($v)).PHP_EOL;
}
$out .= $this->renderer->renderHeader($v);
if (null !== $content) {
$out .= ' '.$this->renderer->colorValue($content);
}
$out .= PHP_EOL;
return $out;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/Rich/SourcePlugin.php | system/ThirdParty/Kint/Renderer/Rich/SourcePlugin.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer\Rich;
use Kint\Value\AbstractValue;
use Kint\Value\Representation\RepresentationInterface;
use Kint\Value\Representation\SourceRepresentation;
class SourcePlugin extends AbstractPlugin implements TabPluginInterface
{
public function renderTab(RepresentationInterface $r, AbstractValue $v): ?string
{
if (!$r instanceof SourceRepresentation) {
return null;
}
$source = $r->getSourceLines();
// Trim empty lines from the start and end of the source
foreach ($source as $linenum => $line) {
if (\strlen(\trim($line)) || $linenum === $r->getLine()) {
break;
}
unset($source[$linenum]);
}
foreach (\array_reverse($source, true) as $linenum => $line) {
if (\strlen(\trim($line)) || $linenum === $r->getLine()) {
break;
}
unset($source[$linenum]);
}
$output = '';
foreach ($source as $linenum => $line) {
if ($linenum === $r->getLine()) {
$output .= '<div class="kint-highlight">'.$this->renderer->escape($line)."\n".'</div>';
} else {
$output .= '<div>'.$this->renderer->escape($line)."\n".'</div>';
}
}
if ($output) {
$data = '';
if ($r->showFileName()) {
$data = ' data-kint-filename="'.$this->renderer->escape($r->getFileName()).'"';
}
return '<div><pre class="kint-source"'.$data.' style="counter-reset: kint-l '.((int) \array_key_first($source) - 1).';">'.$output.'</pre></div><div></div>';
}
return null;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/Rich/PluginInterface.php | system/ThirdParty/Kint/Renderer/Rich/PluginInterface.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer\Rich;
use Kint\Renderer\RichRenderer;
interface PluginInterface
{
public function __construct(RichRenderer $r);
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/Rich/TablePlugin.php | system/ThirdParty/Kint/Renderer/Rich/TablePlugin.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer\Rich;
use Kint\Renderer\RichRenderer;
use Kint\Utils;
use Kint\Value\AbstractValue;
use Kint\Value\ArrayValue;
use Kint\Value\FixedWidthValue;
use Kint\Value\Representation\RepresentationInterface;
use Kint\Value\Representation\TableRepresentation;
use Kint\Value\StringValue;
class TablePlugin extends AbstractPlugin implements TabPluginInterface
{
public static bool $respect_str_length = true;
public function renderTab(RepresentationInterface $r, AbstractValue $v): ?string
{
if (!$r instanceof TableRepresentation) {
return null;
}
$contents = $r->getContents();
$firstrow = \reset($contents);
if (!$firstrow instanceof ArrayValue) {
return null;
}
$out = '<pre><table><thead><tr><th></th>';
foreach ($firstrow->getContents() as $field) {
$out .= '<th>'.$this->renderer->escape($field->getDisplayName()).'</th>';
}
$out .= '</tr></thead><tbody>';
foreach ($contents as $row) {
if (!$row instanceof ArrayValue) {
return null;
}
$out .= '<tr><th>'.$this->renderer->escape($row->getDisplayName()).'</th>';
foreach ($row->getContents() as $field) {
$ref = $field->getContext()->isRef() ? '&' : '';
$type = $this->renderer->escape($field->getDisplayType());
$out .= '<td title="'.$ref.$type;
if (null !== ($size = $field->getDisplaySize())) {
$size = $this->renderer->escape($size);
$out .= ' ('.$size.')';
}
$out .= '">';
if ($field instanceof FixedWidthValue) {
if (null === ($dv = $field->getDisplayValue())) {
$out .= '<var>'.$ref.'null</var>';
} elseif ('boolean' === $field->getType()) {
$out .= '<var>'.$ref.$dv.'</var>';
} else {
$out .= $dv;
}
} elseif ($field instanceof StringValue) {
if (false !== $field->getEncoding()) {
$val = $field->getValueUtf8();
if (RichRenderer::$strlen_max && self::$respect_str_length) {
$val = Utils::truncateString($val, RichRenderer::$strlen_max, 'UTF-8');
}
$out .= $this->renderer->escape($val);
} else {
$out .= '<var>'.$ref.$type.'</var>';
}
} elseif ($field instanceof ArrayValue) {
$out .= '<var>'.$ref.'array</var> ('.$field->getSize().')';
} else {
$out .= '<var>'.$ref.$type.'</var>';
if (null !== $size) {
$out .= ' ('.$size.')';
}
}
if ($field->flags & AbstractValue::FLAG_BLACKLIST) {
$out .= ' <var>Blacklisted</var>';
} elseif ($field->flags & AbstractValue::FLAG_RECURSION) {
$out .= ' <var>Recursion</var>';
} elseif ($field->flags & AbstractValue::FLAG_DEPTH_LIMIT) {
$out .= ' <var>Depth Limit</var>';
}
$out .= '</td>';
}
$out .= '</tr>';
}
$out .= '</tbody></table></pre>';
return $out;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/Rich/ColorPlugin.php | system/ThirdParty/Kint/Renderer/Rich/ColorPlugin.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer\Rich;
use Kint\Value\AbstractValue;
use Kint\Value\Representation\ColorRepresentation;
use Kint\Value\Representation\RepresentationInterface;
class ColorPlugin extends AbstractPlugin implements TabPluginInterface, ValuePluginInterface
{
public function renderValue(AbstractValue $v): ?string
{
$r = $v->getRepresentation('color');
if (!$r instanceof ColorRepresentation) {
return null;
}
$children = $this->renderer->renderChildren($v);
$header = $this->renderer->renderHeader($v);
$header .= '<div class="kint-color-preview"><div style="background:';
$header .= $r->getColor(ColorRepresentation::COLOR_RGBA);
$header .= '"></div></div>';
$header = $this->renderer->renderHeaderWrapper($v->getContext(), (bool) \strlen($children), $header);
return '<dl>'.$header.$children.'</dl>';
}
public function renderTab(RepresentationInterface $r, AbstractValue $v): ?string
{
if (!$r instanceof ColorRepresentation) {
return null;
}
$out = '';
if ($color = $r->getColor(ColorRepresentation::COLOR_NAME)) {
$out .= '<dfn>'.$color."</dfn>\n";
}
if ($color = $r->getColor(ColorRepresentation::COLOR_HEX_3)) {
$out .= '<dfn>'.$color."</dfn>\n";
}
if ($color = $r->getColor(ColorRepresentation::COLOR_HEX_6)) {
$out .= '<dfn>'.$color."</dfn>\n";
}
if ($r->hasAlpha()) {
if ($color = $r->getColor(ColorRepresentation::COLOR_HEX_4)) {
$out .= '<dfn>'.$color."</dfn>\n";
}
if ($color = $r->getColor(ColorRepresentation::COLOR_HEX_8)) {
$out .= '<dfn>'.$color."</dfn>\n";
}
if ($color = $r->getColor(ColorRepresentation::COLOR_RGBA)) {
$out .= '<dfn>'.$color."</dfn>\n";
}
if ($color = $r->getColor(ColorRepresentation::COLOR_HSLA)) {
$out .= '<dfn>'.$color."</dfn>\n";
}
} else {
if ($color = $r->getColor(ColorRepresentation::COLOR_RGB)) {
$out .= '<dfn>'.$color."</dfn>\n";
}
if ($color = $r->getColor(ColorRepresentation::COLOR_HSL)) {
$out .= '<dfn>'.$color."</dfn>\n";
}
}
if (!\strlen($out)) {
return null;
}
return '<pre>'.$out.'</pre>';
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/Rich/CallableDefinitionPlugin.php | system/ThirdParty/Kint/Renderer/Rich/CallableDefinitionPlugin.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer\Rich;
use Kint\Utils;
use Kint\Value\AbstractValue;
use Kint\Value\MethodValue;
use Kint\Value\Representation\CallableDefinitionRepresentation;
use Kint\Value\Representation\RepresentationInterface;
class CallableDefinitionPlugin extends AbstractPlugin implements TabPluginInterface
{
public function renderTab(RepresentationInterface $r, AbstractValue $v): ?string
{
if (!$r instanceof CallableDefinitionRepresentation) {
return null;
}
$docstring = [];
if ($v instanceof MethodValue) {
$c = $v->getContext();
if ($c->inherited) {
$docstring[] = 'Inherited from '.$this->renderer->escape($c->owner_class);
}
}
$docstring[] = 'Defined in '.$this->renderer->escape(Utils::shortenPath($r->getFileName())).':'.$r->getLine();
$docstring = '<small>'.\implode("\n", $docstring).'</small>';
if (null !== ($trimmed = $r->getDocstringTrimmed())) {
$docstring = $this->renderer->escape($trimmed)."\n\n".$docstring;
}
return '<pre>'.$docstring.'</pre>';
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/Rich/TraceFramePlugin.php | system/ThirdParty/Kint/Renderer/Rich/TraceFramePlugin.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer\Rich;
use Kint\Value\AbstractValue;
use Kint\Value\MethodValue;
use Kint\Value\TraceFrameValue;
class TraceFramePlugin extends AbstractPlugin implements ValuePluginInterface
{
public function renderValue(AbstractValue $v): ?string
{
if (!$v instanceof TraceFrameValue) {
return null;
}
if (null !== ($file = $v->getFile()) && null !== ($line = $v->getLine())) {
$header = '<var>'.$this->renderer->ideLink($file, $line).'</var> ';
} else {
$header = '<var>PHP internal call</var> ';
}
if ($callable = $v->getCallable()) {
if ($callable instanceof MethodValue) {
$function = $callable->getFullyQualifiedDisplayName();
} else {
$function = $callable->getDisplayName();
}
$function = $this->renderer->escape($function);
if (null !== ($url = $callable->getPhpDocUrl())) {
$function = '<a href="'.$url.'" target=_blank>'.$function.'</a>';
}
$header .= $function;
}
$children = $this->renderer->renderChildren($v);
$header = $this->renderer->renderHeaderWrapper($v->getContext(), (bool) \strlen($children), $header);
return '<dl>'.$header.$children.'</dl>';
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/Rich/ProfilePlugin.php | system/ThirdParty/Kint/Renderer/Rich/ProfilePlugin.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer\Rich;
use Kint\Value\AbstractValue;
use Kint\Value\Representation\ProfileRepresentation;
use Kint\Value\Representation\RepresentationInterface;
class ProfilePlugin extends AbstractPlugin implements TabPluginInterface
{
public function renderTab(RepresentationInterface $r, AbstractValue $v): ?string
{
if (!$r instanceof ProfileRepresentation) {
return null;
}
$out = '<pre>';
$out .= 'Complexity: '.$r->complexity.PHP_EOL;
if (isset($r->instance_counts)) {
$out .= 'Instance repetitions: '.\var_export($r->instance_counts, true).PHP_EOL;
}
if (isset($r->instance_complexity)) {
$out .= 'Instance complexity: '.\var_export($r->instance_complexity, true).PHP_EOL;
}
$out .= '</pre>';
return $out;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/Rich/LockPlugin.php | system/ThirdParty/Kint/Renderer/Rich/LockPlugin.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer\Rich;
use Kint\Value\AbstractValue;
class LockPlugin extends AbstractPlugin implements ValuePluginInterface
{
public function renderValue(AbstractValue $v): ?string
{
switch ($v->getHint()) {
case 'blacklist':
return '<dl>'.$this->renderLockedHeader($v, '<var>Blacklisted</var>').'</dl>';
case 'recursion':
return '<dl>'.$this->renderLockedHeader($v, '<var>Recursion</var>').'</dl>';
case 'depth_limit':
return '<dl>'.$this->renderLockedHeader($v, '<var>Depth Limit</var>').'</dl>';
case 'array_limit':
return '<dl>'.$this->renderLockedHeader($v, '<var>Array Limit</var>').'</dl>';
}
return null;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/Rich/TabPluginInterface.php | system/ThirdParty/Kint/Renderer/Rich/TabPluginInterface.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer\Rich;
use Kint\Value\AbstractValue;
use Kint\Value\Representation\RepresentationInterface;
interface TabPluginInterface extends PluginInterface
{
public function renderTab(RepresentationInterface $r, AbstractValue $v): ?string;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/Rich/ValuePluginInterface.php | system/ThirdParty/Kint/Renderer/Rich/ValuePluginInterface.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer\Rich;
use Kint\Value\AbstractValue;
interface ValuePluginInterface extends PluginInterface
{
public function renderValue(AbstractValue $v): ?string;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/Rich/CallablePlugin.php | system/ThirdParty/Kint/Renderer/Rich/CallablePlugin.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer\Rich;
use Kint\Renderer\RichRenderer;
use Kint\Utils;
use Kint\Value\AbstractValue;
use Kint\Value\Context\MethodContext;
use Kint\Value\MethodValue;
class CallablePlugin extends AbstractPlugin implements ValuePluginInterface
{
protected static array $method_cache = [];
public function renderValue(AbstractValue $v): ?string
{
if (!$v instanceof MethodValue) {
return null;
}
$c = $v->getContext();
if (!$c instanceof MethodContext) {
return null;
}
if (!isset(self::$method_cache[$c->owner_class][$c->name])) {
$children = $this->renderer->renderChildren($v);
$header = '<var>'.$c->getModifiers();
if ($v->getCallableBag()->return_reference) {
$header .= ' &';
}
$header .= '</var> ';
$function = $this->renderer->escape($v->getDisplayName());
if (null !== ($url = $v->getPhpDocUrl())) {
$function = '<a href="'.$url.'" target=_blank>'.$function.'</a>';
}
$header .= '<dfn>'.$function.'</dfn>';
if (null !== ($rt = $v->getCallableBag()->returntype)) {
$header .= ': <var>';
$header .= $this->renderer->escape($rt).'</var>';
} elseif (null !== ($ds = $v->getCallableBag()->docstring)) {
if (\preg_match('/@return\\s+(.*)\\r?\\n/m', $ds, $matches)) {
if (\trim($matches[1])) {
$header .= ': <var>'.$this->renderer->escape(\trim($matches[1])).'</var>';
}
}
}
if (null !== ($s = $v->getDisplayValue())) {
if (RichRenderer::$strlen_max) {
$s = Utils::truncateString($s, RichRenderer::$strlen_max);
}
$header .= ' '.$this->renderer->escape($s);
}
self::$method_cache[$c->owner_class][$c->name] = [
'header' => $header,
'children' => $children,
];
}
$children = self::$method_cache[$c->owner_class][$c->name]['children'];
$header = $this->renderer->renderHeaderWrapper(
$c,
(bool) \strlen($children),
self::$method_cache[$c->owner_class][$c->name]['header']
);
return '<dl>'.$header.$children.'</dl>';
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/Rich/MicrotimePlugin.php | system/ThirdParty/Kint/Renderer/Rich/MicrotimePlugin.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer\Rich;
use Kint\Utils;
use Kint\Value\AbstractValue;
use Kint\Value\Representation\MicrotimeRepresentation;
use Kint\Value\Representation\RepresentationInterface;
class MicrotimePlugin extends AbstractPlugin implements TabPluginInterface
{
public function renderTab(RepresentationInterface $r, AbstractValue $v): ?string
{
if (!$r instanceof MicrotimeRepresentation || !($dt = $r->getDateTime())) {
return null;
}
$out = $dt->format('Y-m-d H:i:s.u');
if (null !== ($lap = $r->getLapTime())) {
$out .= '<br><b>SINCE LAST CALL:</b> <span class="kint-microtime-lap">'.\round($lap, 4).'</span>s.';
}
if (null !== ($total = $r->getTotalTime())) {
$out .= '<br><b>SINCE START:</b> '.\round($total, 4).'s.';
}
if (null !== ($avg = $r->getAverageTime())) {
$out .= '<br><b>AVERAGE DURATION:</b> <span class="kint-microtime-avg">'.\round($avg, 4).'</span>s.';
}
$bytes = Utils::getHumanReadableBytes($r->getMemoryUsage());
$out .= '<br><b>MEMORY USAGE:</b> '.$r->getMemoryUsage().' bytes ('.\round($bytes['value'], 3).' '.$bytes['unit'].')';
$bytes = Utils::getHumanReadableBytes($r->getMemoryUsageReal());
$out .= ' (real '.\round($bytes['value'], 3).' '.$bytes['unit'].')';
$bytes = Utils::getHumanReadableBytes($r->getMemoryPeakUsage());
$out .= '<br><b>PEAK MEMORY USAGE:</b> '.$r->getMemoryPeakUsage().' bytes ('.\round($bytes['value'], 3).' '.$bytes['unit'].')';
$bytes = Utils::getHumanReadableBytes($r->getMemoryPeakUsageReal());
$out .= ' (real '.\round($bytes['value'], 3).' '.$bytes['unit'].')';
return '<pre data-kint-microtime-group="'.$r->getGroup().'">'.$out.'</pre>';
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/Rich/BinaryPlugin.php | system/ThirdParty/Kint/Renderer/Rich/BinaryPlugin.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer\Rich;
use Kint\Value\AbstractValue;
use Kint\Value\Representation\BinaryRepresentation;
use Kint\Value\Representation\RepresentationInterface;
class BinaryPlugin extends AbstractPlugin implements TabPluginInterface
{
/** @psalm-var positive-int */
public static int $line_length = 0x10;
/** @psalm-var positive-int */
public static int $chunk_length = 0x2;
public function renderTab(RepresentationInterface $r, AbstractValue $v): ?string
{
if (!$r instanceof BinaryRepresentation) {
return null;
}
$out = '<pre>';
$lines = \str_split($r->getValue(), self::$line_length);
foreach ($lines as $index => $line) {
$out .= \sprintf('%08X', $index * self::$line_length).":\t";
$chunks = \str_split(\str_pad(\bin2hex($line), 2 * self::$line_length, ' '), 2 * self::$chunk_length);
$out .= \implode(' ', $chunks);
$out .= "\t".\preg_replace('/[^\\x20-\\x7E]/', '.', $line)."\n";
}
$out .= '</pre>';
return $out;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Renderer/Rich/AbstractPlugin.php | system/ThirdParty/Kint/Renderer/Rich/AbstractPlugin.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Renderer\Rich;
use Kint\Renderer\RichRenderer;
use Kint\Value\AbstractValue;
use Kint\Value\Context\ClassDeclaredContext;
use Kint\Value\Context\PropertyContext;
use Kint\Value\InstanceValue;
abstract class AbstractPlugin implements PluginInterface
{
protected RichRenderer $renderer;
public function __construct(RichRenderer $r)
{
$this->renderer = $r;
}
/**
* @param string $content The replacement for the getValueShort contents
*/
public function renderLockedHeader(AbstractValue $v, string $content): string
{
$header = '<dt class="kint-parent kint-locked">';
$c = $v->getContext();
if (RichRenderer::$access_paths && $c->getDepth() > 0 && null !== ($ap = $c->getAccessPath())) {
$header .= '<span class="kint-access-path-trigger" title="Show access path">⇄</span>';
}
$header .= '<nav></nav>';
if ($c instanceof ClassDeclaredContext) {
$header .= '<var>'.$c->getModifiers().'</var> ';
}
$header .= '<dfn>'.$this->renderer->escape($v->getDisplayName()).'</dfn> ';
if ($c instanceof PropertyContext && null !== ($s = $c->getHooks())) {
$header .= '<var>'.$this->renderer->escape($s).'</var> ';
}
if (null !== ($s = $c->getOperator())) {
$header .= $this->renderer->escape($s, 'ASCII').' ';
}
$s = $v->getDisplayType();
if (RichRenderer::$escape_types) {
$s = $this->renderer->escape($s);
}
if ($c->isRef()) {
$s = '&'.$s;
}
$header .= '<var>'.$s.'</var>';
if ($v instanceof InstanceValue && $this->renderer->shouldRenderObjectIds()) {
$header .= '#'.$v->getSplObjectId();
}
$header .= ' ';
if (null !== ($s = $v->getDisplaySize())) {
if (RichRenderer::$escape_types) {
$s = $this->renderer->escape($s);
}
$header .= '('.$s.') ';
}
$header .= $content;
if (!empty($ap)) {
$header .= '<div class="access-path">'.$this->renderer->escape($ap).'</div>';
}
return $header.'</dt>';
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Parser/PluginInterface.php | system/ThirdParty/Kint/Parser/PluginInterface.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
/**
* @psalm-import-type ParserTrigger from Parser
*/
interface PluginInterface
{
public function setParser(Parser $p): void;
public function getTypes(): array;
/**
* @psalm-return ParserTrigger
*/
public function getTriggers(): int;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Parser/TablePlugin.php | system/ThirdParty/Kint/Parser/TablePlugin.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\ArrayValue;
use Kint\Value\Representation\TableRepresentation;
// Note: Interaction with ArrayLimitPlugin:
// Any array limited children will be shown in tables identically to
// non-array-limited children since the table only shows that it is an array
// and it's size anyway. Because ArrayLimitPlugin halts the parse on finding
// a limit all other plugins including this one are stopped, so you cannot get
// a tabular representation of an array that is longer than the limit.
class TablePlugin extends AbstractPlugin implements PluginCompleteInterface
{
public static int $max_width = 300;
public static int $min_width = 2;
public function getTypes(): array
{
return ['array'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if (!$v instanceof ArrayValue) {
return $v;
}
if (\count($var) < 2) {
return $v;
}
// Ensure this is an array of arrays and that all child arrays have the
// same keys. We don't care about their children - if there's another
// "table" inside we'll just make another one down the value tab
$keys = null;
foreach ($var as $elem) {
if (!\is_array($elem)) {
return $v;
}
if (null === $keys) {
if (\count($elem) < self::$min_width || \count($elem) > self::$max_width) {
return $v;
}
$keys = \array_keys($elem);
} elseif (\array_keys($elem) !== $keys) {
return $v;
}
}
$children = $v->getContents();
if (!$children) {
return $v;
}
// Ensure none of the child arrays are recursion or depth limit. We
// don't care if their children are since they are the table cells
foreach ($children as $childarray) {
if (!$childarray instanceof ArrayValue || empty($childarray->getContents())) {
return $v;
}
}
$v->addRepresentation(new TableRepresentation($children), 0);
return $v;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ThirdParty/Kint/Parser/ColorPlugin.php | system/ThirdParty/Kint/Parser/ColorPlugin.php | <?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use InvalidArgumentException;
use Kint\Value\AbstractValue;
use Kint\Value\ColorValue;
use Kint\Value\Representation\ColorRepresentation;
use Kint\Value\StringValue;
class ColorPlugin extends AbstractPlugin implements PluginCompleteInterface
{
public function getTypes(): array
{
return ['string'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if (\strlen($var) > 32) {
return $v;
}
if (!$v instanceof StringValue) {
return $v;
}
$trimmed = \strtolower(\trim($var));
if (!isset(ColorRepresentation::$color_map[$trimmed]) && !\preg_match('/^(?:(?:rgb|hsl)[^\\)]{6,}\\)|#[0-9a-fA-F]{3,8})$/', $trimmed)) {
return $v;
}
try {
$rep = new ColorRepresentation($var);
} catch (InvalidArgumentException $e) {
return $v;
}
$out = new ColorValue($v->getContext(), $v->getValue(), $v->getEncoding());
$out->flags = $v->flags;
$out->appendRepresentations($v->getRepresentations());
$out->removeRepresentation('contents');
$out->addRepresentation($rep, 0);
return $out;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.