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/Helpers/cookie_helper.php
system/Helpers/cookie_helper.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. */ use CodeIgniter\Cookie\Cookie; use Config\Cookie as CookieConfig; // ============================================================================= // CodeIgniter Cookie Helpers // ============================================================================= if (! function_exists('set_cookie')) { /** * Set cookie * * Accepts seven parameters, or you can submit 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 The value of the cookie * @param int $expire The number of seconds until expiration * @param string $domain For site-wide cookie. Usually: .yourdomain.com * @param string $path The cookie path * @param string $prefix The cookie prefix ('': the default prefix) * @param bool|null $secure True makes the cookie secure * @param bool|null $httpOnly True makes the cookie accessible via http(s) only (no javascript) * @param string|null $sameSite The cookie SameSite value * * @see \CodeIgniter\HTTP\Response::setCookie() */ function set_cookie( $name, string $value = '', int $expire = 0, string $domain = '', string $path = '/', string $prefix = '', ?bool $secure = null, ?bool $httpOnly = null, ?string $sameSite = null, ): void { $response = service('response'); $response->setCookie($name, $value, $expire, $domain, $path, $prefix, $secure, $httpOnly, $sameSite); } } if (! function_exists('get_cookie')) { /** * Fetch an item from the $_COOKIE array * * @param string $index * @param string|null $prefix Cookie name prefix. * '': the prefix in Config\Cookie * null: no prefix * * @return array|string|null * * @see \CodeIgniter\HTTP\IncomingRequest::getCookie() */ function get_cookie($index, bool $xssClean = false, ?string $prefix = '') { if ($prefix === '') { $cookie = config(CookieConfig::class); $prefix = $cookie->prefix; } $request = service('request'); $filter = $xssClean ? FILTER_SANITIZE_FULL_SPECIAL_CHARS : FILTER_DEFAULT; return $request->getCookie($prefix . $index, $filter); } } if (! function_exists('delete_cookie')) { /** * Delete a cookie * * @param string $name * @param string $domain the cookie domain. Usually: .yourdomain.com * @param string $path the cookie path * @param string $prefix the cookie prefix * * @see \CodeIgniter\HTTP\Response::deleteCookie() */ function delete_cookie($name, string $domain = '', string $path = '/', string $prefix = ''): void { service('response')->deleteCookie($name, $domain, $path, $prefix); } } if (! function_exists('has_cookie')) { /** * Checks if a cookie exists by name. */ function has_cookie(string $name, ?string $value = null, string $prefix = ''): bool { return service('response')->hasCookie($name, $value, $prefix); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Helpers/filesystem_helper.php
system/Helpers/filesystem_helper.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. */ use CodeIgniter\Exceptions\InvalidArgumentException; // CodeIgniter File System Helpers if (! function_exists('directory_map')) { /** * Create a Directory Map * * Reads the specified directory and builds an array * representation of it. Sub-folders contained with the * directory will be mapped as well. * * @param string $sourceDir Path to source * @param int $directoryDepth Depth of directories to traverse * (0 = fully recursive, 1 = current dir, etc) * @param bool $hidden Whether to show hidden files */ function directory_map(string $sourceDir, int $directoryDepth = 0, bool $hidden = false): array { try { $fp = opendir($sourceDir); $fileData = []; $newDepth = $directoryDepth - 1; $sourceDir = rtrim($sourceDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; while (false !== ($file = readdir($fp))) { // Remove '.', '..', and hidden files [optional] if ($file === '.' || $file === '..' || ($hidden === false && $file[0] === '.')) { continue; } if (is_dir($sourceDir . $file)) { $file .= DIRECTORY_SEPARATOR; } if (($directoryDepth < 1 || $newDepth > 0) && is_dir($sourceDir . $file)) { $fileData[$file] = directory_map($sourceDir . $file, $newDepth, $hidden); } else { $fileData[] = $file; } } closedir($fp); return $fileData; } catch (Throwable) { return []; } } } if (! function_exists('directory_mirror')) { /** * Recursively copies the files and directories of the origin directory * into the target directory, i.e. "mirror" its contents. * * @param bool $overwrite Whether individual files overwrite on collision * * @throws InvalidArgumentException */ function directory_mirror(string $originDir, string $targetDir, bool $overwrite = true): void { if (! is_dir($originDir = rtrim($originDir, '\\/'))) { throw new InvalidArgumentException(sprintf('The origin directory "%s" was not found.', $originDir)); } if (! is_dir($targetDir = rtrim($targetDir, '\\/'))) { @mkdir($targetDir, 0755, true); } $dirLen = strlen($originDir); /** * @var SplFileInfo $file */ foreach (new RecursiveIteratorIterator( new RecursiveDirectoryIterator($originDir, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST, ) as $file) { $origin = $file->getPathname(); $target = $targetDir . substr($origin, $dirLen); if ($file->isDir()) { if (! is_dir($target)) { mkdir($target, 0755); } } elseif ($overwrite || ! is_file($target)) { copy($origin, $target); } } } } if (! function_exists('write_file')) { /** * Write File * * Writes data to the file specified in the path. * Creates a new file if non-existent. * * @param string $path File path * @param string $data Data to write * @param string $mode fopen() mode (default: 'wb') */ function write_file(string $path, string $data, string $mode = 'wb'): bool { try { $fp = fopen($path, $mode); flock($fp, LOCK_EX); $result = 0; for ($written = 0, $length = strlen($data); $written < $length; $written += $result) { if (($result = fwrite($fp, substr($data, $written))) === false) { break; } } flock($fp, LOCK_UN); fclose($fp); return is_int($result); } catch (Throwable) { return false; } } } if (! function_exists('delete_files')) { /** * Delete Files * * Deletes all files contained in the supplied directory path. * Files must be writable or owned by the system in order to be deleted. * If the second parameter is set to true, any directories contained * within the supplied base directory will be nuked as well. * * @param string $path File path * @param bool $delDir Whether to delete any directories found in the path * @param bool $htdocs Whether to skip deleting .htaccess and index page files * @param bool $hidden Whether to include hidden files (files beginning with a period) */ function delete_files(string $path, bool $delDir = false, bool $htdocs = false, bool $hidden = false): bool { $path = realpath($path) ?: $path; $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; try { foreach (new RecursiveIteratorIterator( new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST, ) as $object) { $filename = $object->getFilename(); if (! $hidden && $filename[0] === '.') { continue; } if (! $htdocs || preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename) !== 1) { $isDir = $object->isDir(); if ($isDir && $delDir) { rmdir($object->getPathname()); continue; } if (! $isDir) { unlink($object->getPathname()); } } } return true; } catch (Throwable) { return false; } } } if (! function_exists('get_filenames')) { /** * Get Filenames * * Reads the specified directory and builds an array containing the filenames. * Any sub-folders contained within the specified path are read as well. * * @param string $sourceDir Path to source * @param bool|null $includePath Whether to include the path as part of the filename; false for no path, null for a relative path, true for full path * @param bool $hidden Whether to include hidden files (files beginning with a period) * @param bool $includeDir Whether to include directories */ function get_filenames( string $sourceDir, ?bool $includePath = false, bool $hidden = false, bool $includeDir = true, ): array { $files = []; $sourceDir = realpath($sourceDir) ?: $sourceDir; $sourceDir = rtrim($sourceDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; try { foreach (new RecursiveIteratorIterator( new RecursiveDirectoryIterator($sourceDir, RecursiveDirectoryIterator::SKIP_DOTS | FilesystemIterator::FOLLOW_SYMLINKS), RecursiveIteratorIterator::SELF_FIRST, ) as $name => $object) { $basename = pathinfo($name, PATHINFO_BASENAME); if (! $hidden && $basename[0] === '.') { continue; } if ($includeDir || ! $object->isDir()) { if ($includePath === false) { $files[] = $basename; } elseif ($includePath === null) { $files[] = str_replace($sourceDir, '', $name); } else { $files[] = $name; } } } } catch (Throwable) { return []; } sort($files); return $files; } } if (! function_exists('get_dir_file_info')) { /** * Get Directory File Information * * Reads the specified directory and builds an array containing the filenames, * filesize, dates, and permissions * * Any sub-folders contained within the specified path are read as well. * * @param string $sourceDir Path to source * @param bool $topLevelOnly Look only at the top level directory specified? * @param bool $recursion Internal variable to determine recursion status - do not use in calls * * @return array<string, array{ * name: string, * server_path: string, * size: int, * date: int, * relative_path: string, * }> */ function get_dir_file_info(string $sourceDir, bool $topLevelOnly = true, bool $recursion = false): array { static $fileData = []; $relativePath = $sourceDir; try { $fp = opendir($sourceDir); // reset the array and make sure $sourceDir has a trailing slash on the initial call if ($recursion === false) { $fileData = []; $sourceDir = rtrim(realpath($sourceDir), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } // Used to be foreach (scandir($sourceDir, 1) as $file), but scandir() is simply not as fast while (false !== ($file = readdir($fp))) { if (is_dir($sourceDir . $file) && $file[0] !== '.' && $topLevelOnly === false) { get_dir_file_info($sourceDir . $file . DIRECTORY_SEPARATOR, $topLevelOnly, true); } elseif ($file[0] !== '.') { $fileData[$file] = get_file_info($sourceDir . $file); $fileData[$file]['relative_path'] = $relativePath; } } closedir($fp); return $fileData; } catch (Throwable) { return []; } } } if (! function_exists('get_file_info')) { /** * Get File Info * * Given a file and path, returns the name, path, size, date modified * Second parameter allows you to explicitly declare what information you want returned * Options are: name, server_path, size, date, readable, writable, executable, fileperms * Returns false if the file cannot be found. * * @param string $file Path to file * @param list<string>|string $returnedValues Array or comma separated string of information returned * * @return array{ * name?: string, * server_path?: string, * size?: int, * date?: int, * readable?: bool, * writable?: bool, * executable?: bool, * fileperms?: int * }|null */ function get_file_info(string $file, $returnedValues = ['name', 'server_path', 'size', 'date']) { if (! is_file($file)) { return null; } $fileInfo = []; if (is_string($returnedValues)) { $returnedValues = explode(',', $returnedValues); } foreach ($returnedValues as $key) { switch ($key) { case 'name': $fileInfo['name'] = basename($file); break; case 'server_path': $fileInfo['server_path'] = $file; break; case 'size': $fileInfo['size'] = filesize($file); break; case 'date': $fileInfo['date'] = filemtime($file); break; case 'readable': $fileInfo['readable'] = is_readable($file); break; case 'writable': $fileInfo['writable'] = is_really_writable($file); break; case 'executable': $fileInfo['executable'] = is_executable($file); break; case 'fileperms': $fileInfo['fileperms'] = fileperms($file); break; } } return $fileInfo; } } if (! function_exists('symbolic_permissions')) { /** * Symbolic Permissions * * Takes a numeric value representing a file's permissions and returns * standard symbolic notation representing that value * * @param int $perms Permissions */ function symbolic_permissions(int $perms): string { if (($perms & 0xC000) === 0xC000) { $symbolic = 's'; // Socket } elseif (($perms & 0xA000) === 0xA000) { $symbolic = 'l'; // Symbolic Link } elseif (($perms & 0x8000) === 0x8000) { $symbolic = '-'; // Regular } elseif (($perms & 0x6000) === 0x6000) { $symbolic = 'b'; // Block special } elseif (($perms & 0x4000) === 0x4000) { $symbolic = 'd'; // Directory } elseif (($perms & 0x2000) === 0x2000) { $symbolic = 'c'; // Character special } elseif (($perms & 0x1000) === 0x1000) { $symbolic = 'p'; // FIFO pipe } else { $symbolic = 'u'; // Unknown } // Owner $symbolic .= ((($perms & 0x0100) !== 0) ? 'r' : '-') . ((($perms & 0x0080) !== 0) ? 'w' : '-') . ((($perms & 0x0040) !== 0) ? ((($perms & 0x0800) !== 0) ? 's' : 'x') : ((($perms & 0x0800) !== 0) ? 'S' : '-')); // Group $symbolic .= ((($perms & 0x0020) !== 0) ? 'r' : '-') . ((($perms & 0x0010) !== 0) ? 'w' : '-') . ((($perms & 0x0008) !== 0) ? ((($perms & 0x0400) !== 0) ? 's' : 'x') : ((($perms & 0x0400) !== 0) ? 'S' : '-')); // World $symbolic .= ((($perms & 0x0004) !== 0) ? 'r' : '-') . ((($perms & 0x0002) !== 0) ? 'w' : '-') . ((($perms & 0x0001) !== 0) ? ((($perms & 0x0200) !== 0) ? 't' : 'x') : ((($perms & 0x0200) !== 0) ? 'T' : '-')); return $symbolic; } } if (! function_exists('octal_permissions')) { /** * Octal Permissions * * Takes a numeric value representing a file's permissions and returns * a three character string representing the file's octal permissions * * @param int $perms Permissions */ function octal_permissions(int $perms): string { return substr(sprintf('%o', $perms), -3); } } if (! function_exists('same_file')) { /** * Checks if two files both exist and have identical hashes * * @return bool Same or not */ function same_file(string $file1, string $file2): bool { return is_file($file1) && is_file($file2) && md5_file($file1) === md5_file($file2); } } if (! function_exists('set_realpath')) { /** * Set Realpath * * @param bool $checkExistence Checks to see if the path exists */ function set_realpath(string $path, bool $checkExistence = false): string { // Security check to make sure the path is NOT a URL. No remote file inclusion! if (preg_match('#^(http:\/\/|https:\/\/|www\.|ftp)#i', $path) || filter_var($path, FILTER_VALIDATE_IP) === $path) { throw new InvalidArgumentException('The path you submitted must be a local server path, not a URL'); } // Resolve the path if (realpath($path) !== false) { $path = realpath($path); } elseif ($checkExistence && ! is_dir($path) && ! is_file($path)) { throw new InvalidArgumentException('Not a valid path: ' . $path); } // Add a trailing slash, if this is a directory return is_dir($path) ? rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR : $path; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Helpers/number_helper.php
system/Helpers/number_helper.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. */ use CodeIgniter\Exceptions\BadFunctionCallException; // CodeIgniter Number Helpers if (! function_exists('number_to_size')) { /** * Formats a numbers as bytes, based on size, and adds the appropriate suffix * * @param int|string $num Will be cast as int * @param non-empty-string|null $locale [optional] * * @return bool|string */ function number_to_size($num, int $precision = 1, ?string $locale = null) { // Strip any formatting & ensure numeric input try { // @phpstan-ignore-next-line $num = 0 + str_replace(',', '', (string) $num); } catch (ErrorException) { // Catch "Warning: A non-numeric value encountered" return false; } // ignore sub part $generalLocale = $locale; if ($locale !== null && $locale !== '' && ($underscorePos = strpos($locale, '_'))) { $generalLocale = substr($locale, 0, $underscorePos); } if ($num >= 1_000_000_000_000) { $num = round($num / 1_099_511_627_776, $precision); $unit = lang('Number.terabyteAbbr', [], $generalLocale); } elseif ($num >= 1_000_000_000) { $num = round($num / 1_073_741_824, $precision); $unit = lang('Number.gigabyteAbbr', [], $generalLocale); } elseif ($num >= 1_000_000) { $num = round($num / 1_048_576, $precision); $unit = lang('Number.megabyteAbbr', [], $generalLocale); } elseif ($num >= 1000) { $num = round($num / 1024, $precision); $unit = lang('Number.kilobyteAbbr', [], $generalLocale); } else { $unit = lang('Number.bytes', [], $generalLocale); } return format_number($num, $precision, $locale, ['after' => ' ' . $unit]); } } if (! function_exists('number_to_amount')) { /** * Converts numbers to a more readable representation * when dealing with very large numbers (in the thousands or above), * up to the quadrillions, because you won't often deal with numbers * larger than that. * * It uses the "short form" numbering system as this is most commonly * used within most English-speaking countries today. * * @see https://simple.wikipedia.org/wiki/Names_for_large_numbers * * @param int|string $num Will be cast as int * @param int $precision [optional] The optional number of decimal digits to round to. * @param non-empty-string|null $locale [optional] * * @return bool|string */ function number_to_amount($num, int $precision = 0, ?string $locale = null) { // Strip any formatting & ensure numeric input try { // @phpstan-ignore-next-line $num = 0 + str_replace(',', '', (string) $num); } catch (ErrorException) { // Catch "Warning: A non-numeric value encountered" return false; } $suffix = ''; // ignore sub part $generalLocale = $locale; if ($locale !== null && $locale !== '' && ($underscorePos = strpos($locale, '_'))) { $generalLocale = substr($locale, 0, $underscorePos); } if ($num >= 1_000_000_000_000_000) { $suffix = lang('Number.quadrillion', [], $generalLocale); $num = round(($num / 1_000_000_000_000_000), $precision); } elseif ($num >= 1_000_000_000_000) { $suffix = lang('Number.trillion', [], $generalLocale); $num = round(($num / 1_000_000_000_000), $precision); } elseif ($num >= 1_000_000_000) { $suffix = lang('Number.billion', [], $generalLocale); $num = round(($num / 1_000_000_000), $precision); } elseif ($num >= 1_000_000) { $suffix = lang('Number.million', [], $generalLocale); $num = round(($num / 1_000_000), $precision); } elseif ($num >= 1000) { $suffix = lang('Number.thousand', [], $generalLocale); $num = round(($num / 1000), $precision); } return format_number($num, $precision, $locale, ['after' => $suffix]); } } if (! function_exists('number_to_currency')) { function number_to_currency(float $num, string $currency, ?string $locale = null, int $fraction = 0): string { return format_number($num, 1, $locale, [ 'type' => NumberFormatter::CURRENCY, 'currency' => $currency, 'fraction' => $fraction, ]); } } if (! function_exists('format_number')) { /** * A general purpose, locale-aware, number_format method. * Used by all of the functions of the number_helper. */ function format_number(float $num, int $precision = 1, ?string $locale = null, array $options = []): string { // If locale is not passed, get from the default locale that is set from our config file // or set by HTTP content negotiation. $locale ??= Locale::getDefault(); // Type can be any of the NumberFormatter options, but provide a default. $type = (int) ($options['type'] ?? NumberFormatter::DECIMAL); $formatter = new NumberFormatter($locale, $type); // Try to format it per the locale if ($type === NumberFormatter::CURRENCY) { $formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, (float) $options['fraction']); $output = $formatter->formatCurrency($num, $options['currency']); } else { // In order to specify a precision, we'll have to modify // the pattern used by NumberFormatter. $pattern = '#,##0.' . str_repeat('#', $precision); $formatter->setPattern($pattern); $output = $formatter->format($num); } // This might lead a trailing period if $precision == 0 $output = trim($output, '. '); if (intl_is_failure($formatter->getErrorCode())) { throw new BadFunctionCallException($formatter->getErrorMessage()); } // Add on any before/after text. if (isset($options['before']) && is_string($options['before'])) { $output = $options['before'] . $output; } if (isset($options['after']) && is_string($options['after'])) { $output .= $options['after']; } return $output; } } if (! function_exists('number_to_roman')) { /** * Convert a number to a roman numeral. * * @param int|string $num it will convert to int */ function number_to_roman($num): ?string { static $map = [ 'M' => 1000, 'CM' => 900, 'D' => 500, 'CD' => 400, 'C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40, 'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1, ]; $num = (int) $num; if ($num < 1 || $num > 3999) { return null; } $result = ''; foreach ($map as $roman => $arabic) { $repeat = (int) floor($num / $arabic); $result .= str_repeat($roman, $repeat); $num %= $arabic; } return $result; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Helpers/Array/ArrayHelper.php
system/Helpers/Array/ArrayHelper.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\Helpers\Array; use CodeIgniter\Exceptions\InvalidArgumentException; /** * @interal This is internal implementation for the framework. * * If there are any methods that should be provided, make them * public APIs via helper functions. * * @see \CodeIgniter\Helpers\Array\ArrayHelperDotKeyExistsTest * @see \CodeIgniter\Helpers\Array\ArrayHelperRecursiveDiffTest * @see \CodeIgniter\Helpers\Array\ArrayHelperSortValuesByNaturalTest */ final class ArrayHelper { /** * Searches an array through dot syntax. Supports wildcard searches, * like `foo.*.bar`. * * @used-by dot_array_search() * * @param string $index The index as dot array syntax. * * @return array|bool|int|object|string|null */ public static function dotSearch(string $index, array $array) { return self::arraySearchDot(self::convertToArray($index), $array); } /** * @param string $index The index as dot array syntax. * * @return list<string> The index as an array. */ private static function convertToArray(string $index): array { // See https://regex101.com/r/44Ipql/1 $segments = preg_split( '/(?<!\\\\)\./', rtrim($index, '* '), 0, PREG_SPLIT_NO_EMPTY, ); return array_map( static fn ($key): string => str_replace('\.', '.', $key), $segments, ); } /** * Recursively search the array with wildcards. * * @used-by dotSearch() * * @return array|bool|float|int|object|string|null */ private static function arraySearchDot(array $indexes, array $array) { // If index is empty, returns null. if ($indexes === []) { return null; } // Grab the current index $currentIndex = array_shift($indexes); if (! isset($array[$currentIndex]) && $currentIndex !== '*') { return null; } // Handle Wildcard (*) if ($currentIndex === '*') { $answer = []; foreach ($array as $value) { if (! is_array($value)) { return null; } $answer[] = self::arraySearchDot($indexes, $value); } $answer = array_filter($answer, static fn ($value): bool => $value !== null); if ($answer !== []) { // If array only has one element, we return that element for BC. return count($answer) === 1 ? current($answer) : $answer; } return null; } // If this is the last index, make sure to return it now, // and not try to recurse through things. if ($indexes === []) { return $array[$currentIndex]; } // Do we need to recursively search this value? if (is_array($array[$currentIndex]) && $array[$currentIndex] !== []) { return self::arraySearchDot($indexes, $array[$currentIndex]); } // Otherwise, not found. return null; } /** * array_key_exists() with dot array syntax. * * If wildcard `*` is used, all items for the key after it must have the key. */ public static function dotKeyExists(string $index, array $array): bool { if (str_ends_with($index, '*') || str_contains($index, '*.*')) { throw new InvalidArgumentException( 'You must set key right after "*". Invalid index: "' . $index . '"', ); } $indexes = self::convertToArray($index); // If indexes is empty, returns false. if ($indexes === []) { return false; } $currentArray = $array; // Grab the current index while ($currentIndex = array_shift($indexes)) { if ($currentIndex === '*') { $currentIndex = array_shift($indexes); foreach ($currentArray as $item) { if (! array_key_exists($currentIndex, $item)) { return false; } } // If indexes is empty, all elements are checked. if ($indexes === []) { return true; } $currentArray = self::dotSearch('*.' . $currentIndex, $currentArray); continue; } if (! array_key_exists($currentIndex, $currentArray)) { return false; } $currentArray = $currentArray[$currentIndex]; } return true; } /** * Groups all rows by their index values. Result's depth equals number of indexes * * @used-by array_group_by() * * @param array $array Data array (i.e. from query result) * @param array $indexes Indexes to group by. Dot syntax used. Returns $array if empty * @param bool $includeEmpty If true, null and '' are also added as valid keys to group * * @return array Result array where rows are grouped together by indexes values. */ public static function groupBy(array $array, array $indexes, bool $includeEmpty = false): array { if ($indexes === []) { return $array; } $result = []; foreach ($array as $row) { $result = self::arrayAttachIndexedValue($result, $row, $indexes, $includeEmpty); } return $result; } /** * Recursively attach $row to the $indexes path of values found by * `dot_array_search()`. * * @used-by groupBy() */ private static function arrayAttachIndexedValue( array $result, array $row, array $indexes, bool $includeEmpty, ): array { if (($index = array_shift($indexes)) === null) { $result[] = $row; return $result; } $value = dot_array_search($index, $row); if (! is_scalar($value)) { $value = ''; } if (is_bool($value)) { $value = (int) $value; } if (! $includeEmpty && $value === '') { return $result; } if (! array_key_exists($value, $result)) { $result[$value] = []; } $result[$value] = self::arrayAttachIndexedValue($result[$value], $row, $indexes, $includeEmpty); return $result; } /** * Compare recursively two associative arrays and return difference as new array. * Returns keys that exist in `$original` but not in `$compareWith`. */ public static function recursiveDiff(array $original, array $compareWith): array { $difference = []; if ($original === []) { return []; } if ($compareWith === []) { return $original; } foreach ($original as $originalKey => $originalValue) { if ($originalValue === []) { continue; } if (is_array($originalValue)) { $diffArrays = []; if (isset($compareWith[$originalKey]) && is_array($compareWith[$originalKey])) { $diffArrays = self::recursiveDiff($originalValue, $compareWith[$originalKey]); } else { $difference[$originalKey] = $originalValue; } if ($diffArrays !== []) { $difference[$originalKey] = $diffArrays; } } elseif (is_string($originalValue) && ! array_key_exists($originalKey, $compareWith)) { $difference[$originalKey] = $originalValue; } } return $difference; } /** * Recursively count all keys. */ public static function recursiveCount(array $array, int $counter = 0): int { foreach ($array as $value) { if (is_array($value)) { $counter = self::recursiveCount($value, $counter); } $counter++; } return $counter; } /** * Sorts array values in natural order * If the value is an array, you need to specify the $sortByIndex of the key to sort * * @param list<int|list<int|string>|string> $array * @param int|string|null $sortByIndex */ public static function sortValuesByNatural(array &$array, $sortByIndex = null): bool { return usort($array, static function ($currentValue, $nextValue) use ($sortByIndex): int { if ($sortByIndex !== null) { return strnatcmp((string) $currentValue[$sortByIndex], (string) $nextValue[$sortByIndex]); } return strnatcmp((string) $currentValue, (string) $nextValue); }); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Publisher/ContentReplacer.php
system/Publisher/ContentReplacer.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\Publisher; use CodeIgniter\Exceptions\RuntimeException; /** * Replace Text Content * * @see \CodeIgniter\Publisher\ContentReplacerTest */ class ContentReplacer { /** * Replace content * * @param array $replaces [search => replace] */ public function replace(string $content, array $replaces): string { return strtr($content, $replaces); } /** * Add text * * @param string $text Text to add. * @param string $pattern Regexp search pattern. * @param string $replace Regexp replacement including text to add. * * @return string|null Updated content, or null if not updated. */ private function add(string $content, string $text, string $pattern, string $replace): ?string { $return = preg_match('/' . preg_quote($text, '/') . '/u', $content); if ($return === false) { // Regexp error. throw new RuntimeException('Regex error. PCRE error code: ' . preg_last_error()); } if ($return === 1) { // It has already been updated. return null; } $return = preg_replace($pattern, $replace, $content); if ($return === null) { // Regexp error. throw new RuntimeException('Regex error. PCRE error code: ' . preg_last_error()); } return $return; } /** * Add line after the line with the string * * @param string $content Whole content. * @param string $line Line to add. * @param string $after String to search. * * @return string|null Updated content, or null if not updated. */ public function addAfter(string $content, string $line, string $after): ?string { $pattern = '/(.*)(\n[^\n]*?' . preg_quote($after, '/') . '[^\n]*?\n)/su'; $replace = '$1$2' . $line . "\n"; return $this->add($content, $line, $pattern, $replace); } /** * Add line before the line with the string * * @param string $content Whole content. * @param string $line Line to add. * @param string $before String to search. * * @return string|null Updated content, or null if not updated. */ public function addBefore(string $content, string $line, string $before): ?string { $pattern = '/(\n)([^\n]*?' . preg_quote($before, '/') . ')(.*)/su'; $replace = '$1' . $line . "\n" . '$2$3'; return $this->add($content, $line, $pattern, $replace); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Publisher/Publisher.php
system/Publisher/Publisher.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\Publisher; use CodeIgniter\Autoloader\FileLocatorInterface; use CodeIgniter\Exceptions\RuntimeException; use CodeIgniter\Files\FileCollection; use CodeIgniter\HTTP\URI; use CodeIgniter\Publisher\Exceptions\PublisherException; use Config\Publisher as PublisherConfig; use Throwable; /** * Publishers read in file paths from a variety of sources and copy * the files out to different destinations. This class acts both as * a base for individual publication directives as well as the mode * of discovery for said instances. In this class a "file" is a full * path to a verified file while a "path" is relative to its source * or destination and may indicate either a file or directory of * unconfirmed existence. * * Class failures throw the PublisherException, but some underlying * methods may percolate different exceptions, like FileException, * FileNotFoundException or InvalidArgumentException. * * Write operations will catch all errors in the file-specific * $errors property to minimize impact of partial batch operations. */ class Publisher extends FileCollection { /** * Array of discovered Publishers. * * @var array<string, list<self>|null> */ private static array $discovered = []; /** * Directory to use for methods that need temporary storage. * Created on-the-fly as needed. */ private ?string $scratch = null; /** * Exceptions for specific files from the last write operation. * * @var array<string, Throwable> */ private array $errors = []; /** * List of file published curing the last write operation. * * @var list<string> */ private array $published = []; /** * List of allowed directories and their allowed files regex. * Restrictions are intentionally private to prevent overriding. * * @var array<string,string> */ private readonly array $restrictions; private readonly ContentReplacer $replacer; /** * Base path to use for the source. * * @var string */ protected $source = ROOTPATH; /** * Base path to use for the destination. * * @var string */ protected $destination = FCPATH; // -------------------------------------------------------------------- // Support Methods // -------------------------------------------------------------------- /** * Discovers and returns all Publishers in the specified namespace directory. * * @return list<self> */ final public static function discover(string $directory = 'Publishers', string $namespace = ''): array { $key = implode('.', [$namespace, $directory]); if (isset(self::$discovered[$key])) { return self::$discovered[$key]; } self::$discovered[$key] = []; /** @var FileLocatorInterface */ $locator = service('locator'); $files = $namespace === '' ? $locator->listFiles($directory) : $locator->listNamespaceFiles($namespace, $directory); if ([] === $files) { return []; } // Loop over each file checking to see if it is a Publisher foreach (array_unique($files) as $file) { $className = $locator->findQualifiedNameFromPath($file); if ($className !== false && class_exists($className) && is_a($className, self::class, true)) { /** @var class-string<self> $className */ self::$discovered[$key][] = new $className(); } } sort(self::$discovered[$key]); return self::$discovered[$key]; } /** * Removes a directory and all its files and subdirectories. */ private static function wipeDirectory(string $directory): void { if (is_dir($directory)) { // Try a few times in case of lingering locks $attempts = 10; while ((bool) $attempts && ! delete_files($directory, true, false, true)) { // @codeCoverageIgnoreStart $attempts--; usleep(100000); // .1s // @codeCoverageIgnoreEnd } @rmdir($directory); } } // -------------------------------------------------------------------- // Class Core // -------------------------------------------------------------------- /** * Loads the helper and verifies the source and destination directories. */ public function __construct(?string $source = null, ?string $destination = null) { helper(['filesystem']); $this->source = self::resolveDirectory($source ?? $this->source); $this->destination = self::resolveDirectory($destination ?? $this->destination); $this->replacer = new ContentReplacer(); // Restrictions are intentionally not injected to prevent overriding $this->restrictions = config(PublisherConfig::class)->restrictions; // Make sure the destination is allowed foreach (array_keys($this->restrictions) as $directory) { if (str_starts_with($this->destination, $directory)) { return; } } throw PublisherException::forDestinationNotAllowed($this->destination); } /** * Cleans up any temporary files in the scratch space. */ public function __destruct() { if (isset($this->scratch)) { self::wipeDirectory($this->scratch); $this->scratch = null; } } /** * Reads files from the sources and copies them out to their destinations. * This method should be reimplemented by child classes intended for * discovery. * * @throws RuntimeException */ public function publish(): bool { // Safeguard against accidental misuse if ($this->source === ROOTPATH && $this->destination === FCPATH) { throw new RuntimeException('Child classes of Publisher should provide their own publish method or a source and destination.'); } return $this->addPath('/')->merge(true); } // -------------------------------------------------------------------- // Property Accessors // -------------------------------------------------------------------- /** * Returns the source directory. */ final public function getSource(): string { return $this->source; } /** * Returns the destination directory. */ final public function getDestination(): string { return $this->destination; } /** * Returns the temporary workspace, creating it if necessary. */ final public function getScratch(): string { if ($this->scratch === null) { $this->scratch = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . bin2hex(random_bytes(6)) . DIRECTORY_SEPARATOR; mkdir($this->scratch, 0700); $this->scratch = realpath($this->scratch) ? realpath($this->scratch) . DIRECTORY_SEPARATOR : $this->scratch; } return $this->scratch; } /** * Returns errors from the last write operation if any. * * @return array<string,Throwable> */ final public function getErrors(): array { return $this->errors; } /** * Returns the files published by the last write operation. * * @return list<string> */ final public function getPublished(): array { return $this->published; } // -------------------------------------------------------------------- // Additional Handlers // -------------------------------------------------------------------- /** * Verifies and adds paths to the list. * * @param list<string> $paths * * @return $this */ final public function addPaths(array $paths, bool $recursive = true) { foreach ($paths as $path) { $this->addPath($path, $recursive); } return $this; } /** * Adds a single path to the file list. * * @return $this */ final public function addPath(string $path, bool $recursive = true) { $this->add($this->source . $path, $recursive); return $this; } /** * Downloads and stages files from an array of URIs. * * @param list<string> $uris * * @return $this */ final public function addUris(array $uris) { foreach ($uris as $uri) { $this->addUri($uri); } return $this; } /** * Downloads a file from the URI, and adds it to the file list. * * @param string $uri Because HTTP\URI is stringable it will still be accepted * * @return $this */ final public function addUri(string $uri) { // Figure out a good filename (using URI strips queries and fragments) $file = $this->getScratch() . basename((new URI($uri))->getPath()); // Get the content and write it to the scratch space write_file($file, service('curlrequest')->get($uri)->getBody()); return $this->addFile($file); } // -------------------------------------------------------------------- // Write Methods // -------------------------------------------------------------------- /** * Removes the destination and all its files and folders. * * @return $this */ final public function wipe() { self::wipeDirectory($this->destination); return $this; } /** * Copies all files into the destination, does not create directory structure. * * @param bool $replace Whether to overwrite existing files. * * @return bool Whether all files were copied successfully */ final public function copy(bool $replace = true): bool { $this->errors = $this->published = []; foreach ($this->get() as $file) { $to = $this->destination . basename($file); try { $this->safeCopyFile($file, $to, $replace); $this->published[] = $to; } catch (Throwable $e) { $this->errors[$file] = $e; } } return $this->errors === []; } /** * Merges all files into the destination. * Creates a mirrored directory structure only for files from source. * * @param bool $replace Whether to overwrite existing files. * * @return bool Whether all files were copied successfully */ final public function merge(bool $replace = true): bool { $this->errors = $this->published = []; // Get the files from source for special handling $sourced = self::filterFiles($this->get(), $this->source); // Handle everything else with a flat copy $this->files = array_diff($this->files, $sourced); $this->copy($replace); // Copy each sourced file to its relative destination foreach ($sourced as $file) { // Resolve the destination path $to = $this->destination . substr($file, strlen($this->source)); try { $this->safeCopyFile($file, $to, $replace); $this->published[] = $to; } catch (Throwable $e) { $this->errors[$file] = $e; } } return $this->errors === []; } /** * Replace content * * @param array $replaces [search => replace] */ public function replace(string $file, array $replaces): bool { $this->verifyAllowed($file, $file); $content = file_get_contents($file); $newContent = $this->replacer->replace($content, $replaces); $return = file_put_contents($file, $newContent); return $return !== false; } /** * Add line after the line with the string * * @param string $after String to search. */ public function addLineAfter(string $file, string $line, string $after): bool { $this->verifyAllowed($file, $file); $content = file_get_contents($file); $result = $this->replacer->addAfter($content, $line, $after); if ($result !== null) { $return = file_put_contents($file, $result); return $return !== false; } return false; } /** * Add line before the line with the string * * @param string $before String to search. */ public function addLineBefore(string $file, string $line, string $before): bool { $this->verifyAllowed($file, $file); $content = file_get_contents($file); $result = $this->replacer->addBefore($content, $line, $before); if ($result !== null) { $return = file_put_contents($file, $result); return $return !== false; } return false; } /** * Verify this is an allowed file for its destination. */ private function verifyAllowed(string $from, string $to): void { // Verify this is an allowed file for its destination foreach ($this->restrictions as $directory => $pattern) { if (str_starts_with($to, $directory) && self::matchFiles([$to], $pattern) === []) { throw PublisherException::forFileNotAllowed($from, $directory, $pattern); } } } /** * Copies a file with directory creation and identical file awareness. * Intentionally allows errors. * * @throws PublisherException For collisions and restriction violations */ private function safeCopyFile(string $from, string $to, bool $replace): void { // Verify this is an allowed file for its destination $this->verifyAllowed($from, $to); // Check for an existing file if (file_exists($to)) { // If not replacing or if files are identical then consider successful if (! $replace || same_file($from, $to)) { return; } // If it is a directory then do not try to remove it if (is_dir($to)) { throw PublisherException::forCollision($from, $to); } // Try to remove anything else unlink($to); } // Make sure the directory exists if (! is_dir($directory = pathinfo($to, PATHINFO_DIRNAME))) { mkdir($directory, 0775, true); } // Allow copy() to throw errors copy($from, $to); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Publisher/Exceptions/PublisherException.php
system/Publisher/Exceptions/PublisherException.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\Publisher\Exceptions; use CodeIgniter\Exceptions\FrameworkException; /** * Publisher Exception Class * * Handles exceptions related to actions taken by a Publisher. */ class PublisherException extends FrameworkException { /** * Throws when a file should be overwritten yet cannot. * * @param string $from The source file * @param string $to The destination file * * @return static */ public static function forCollision(string $from, string $to) { return new static(lang('Publisher.collision', [filetype($to), $from, $to])); } /** * Throws when given a destination that is not in the list of allowed directories. * * @return static */ public static function forDestinationNotAllowed(string $destination) { return new static(lang('Publisher.destinationNotAllowed', [$destination])); } /** * Throws when a file fails to match the allowed pattern for its destination. * * @return static */ public static function forFileNotAllowed(string $file, string $directory, string $pattern) { return new static(lang('Publisher.fileNotAllowed', [$file, $directory, $pattern])); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Entity/Entity.php
system/Entity/Entity.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\Entity; use CodeIgniter\DataCaster\DataCaster; use CodeIgniter\Entity\Cast\ArrayCast; use CodeIgniter\Entity\Cast\BooleanCast; use CodeIgniter\Entity\Cast\CSVCast; use CodeIgniter\Entity\Cast\DatetimeCast; use CodeIgniter\Entity\Cast\FloatCast; use CodeIgniter\Entity\Cast\IntBoolCast; use CodeIgniter\Entity\Cast\IntegerCast; use CodeIgniter\Entity\Cast\JsonCast; use CodeIgniter\Entity\Cast\ObjectCast; use CodeIgniter\Entity\Cast\StringCast; use CodeIgniter\Entity\Cast\TimestampCast; use CodeIgniter\Entity\Cast\URICast; use CodeIgniter\Entity\Exceptions\CastException; use CodeIgniter\I18n\Time; use DateTime; use Exception; use JsonSerializable; use ReturnTypeWillChange; /** * Entity encapsulation, for use with CodeIgniter\Model * * @see \CodeIgniter\Entity\EntityTest */ class Entity implements JsonSerializable { /** * Maps names used in sets and gets against unique * names within the class, allowing independence from * database column names. * * Example: * $datamap = [ * 'class_property_name' => 'db_column_name' * ]; * * @var array<string, string> */ protected $datamap = []; /** * The date fields. * * @var list<string> */ protected $dates = [ 'created_at', 'updated_at', 'deleted_at', ]; /** * Array of field names and the type of value to cast them as when * they are accessed. * * @var array<string, string> */ protected $casts = []; /** * Custom convert handlers * * @var array<string, string> */ protected $castHandlers = []; /** * Default convert handlers * * @var array<string, string> */ private array $defaultCastHandlers = [ 'array' => ArrayCast::class, 'bool' => BooleanCast::class, 'boolean' => BooleanCast::class, 'csv' => CSVCast::class, 'datetime' => DatetimeCast::class, 'double' => FloatCast::class, 'float' => FloatCast::class, 'int' => IntegerCast::class, 'integer' => IntegerCast::class, 'int-bool' => IntBoolCast::class, 'json' => JsonCast::class, 'object' => ObjectCast::class, 'string' => StringCast::class, 'timestamp' => TimestampCast::class, 'uri' => URICast::class, ]; /** * Holds the current values of all class vars. * * @var array<string, mixed> */ protected $attributes = []; /** * Holds original copies of all class vars so we can determine * what's actually been changed and not accidentally write * nulls where we shouldn't. * * @var array<string, mixed> */ protected $original = []; /** * The data caster. */ protected DataCaster $dataCaster; /** * Holds info whenever properties have to be casted */ private bool $_cast = true; /** * Allows filling in Entity parameters during construction. */ public function __construct(?array $data = null) { $this->dataCaster = new DataCaster( array_merge($this->defaultCastHandlers, $this->castHandlers), null, null, false, ); $this->syncOriginal(); $this->fill($data); } /** * Takes an array of key/value pairs and sets them as class * properties, using any `setCamelCasedProperty()` methods * that may or may not exist. * * @param array<string, array|bool|float|int|object|string|null> $data * * @return $this */ public function fill(?array $data = null) { if (! is_array($data)) { return $this; } foreach ($data as $key => $value) { $this->__set($key, $value); } return $this; } /** * General method that will return all public and protected values * of this entity as an array. All values are accessed through the * __get() magic method so will have any casts, etc applied to them. * * @param bool $onlyChanged If true, only return values that have changed since object creation * @param bool $cast If true, properties will be cast. * @param bool $recursive If true, inner entities will be cast as array as well. */ public function toArray(bool $onlyChanged = false, bool $cast = true, bool $recursive = false): array { $this->_cast = $cast; $keys = array_filter(array_keys($this->attributes), static fn ($key): bool => ! str_starts_with($key, '_')); if (is_array($this->datamap)) { $keys = array_unique( [...array_diff($keys, $this->datamap), ...array_keys($this->datamap)], ); } $return = []; // Loop over the properties, to allow magic methods to do their thing. foreach ($keys as $key) { if ($onlyChanged && ! $this->hasChanged($key)) { continue; } $return[$key] = $this->__get($key); if ($recursive) { if ($return[$key] instanceof self) { $return[$key] = $return[$key]->toArray($onlyChanged, $cast, $recursive); } elseif (is_callable([$return[$key], 'toArray'])) { $return[$key] = $return[$key]->toArray(); } } } $this->_cast = true; return $return; } /** * Returns the raw values of the current attributes. * * @param bool $onlyChanged If true, only return values that have changed since object creation * @param bool $recursive If true, inner entities will be cast as array as well. */ public function toRawArray(bool $onlyChanged = false, bool $recursive = false): array { $return = []; if (! $onlyChanged) { if ($recursive) { return array_map(static function ($value) use ($onlyChanged, $recursive) { if ($value instanceof self) { $value = $value->toRawArray($onlyChanged, $recursive); } elseif (is_callable([$value, 'toRawArray'])) { $value = $value->toRawArray(); } return $value; }, $this->attributes); } return $this->attributes; } foreach ($this->attributes as $key => $value) { if (! $this->hasChanged($key)) { continue; } if ($recursive) { if ($value instanceof self) { $value = $value->toRawArray($onlyChanged, $recursive); } elseif (is_callable([$value, 'toRawArray'])) { $value = $value->toRawArray(); } } $return[$key] = $value; } return $return; } /** * Ensures our "original" values match the current values. * * @return $this */ public function syncOriginal() { $this->original = $this->attributes; return $this; } /** * Checks a property to see if it has changed since the entity * was created. Or, without a parameter, checks if any * properties have changed. * * @param string|null $key class property */ public function hasChanged(?string $key = null): bool { // If no parameter was given then check all attributes if ($key === null) { return $this->original !== $this->attributes; } $dbColumn = $this->mapProperty($key); // Key doesn't exist in either if (! array_key_exists($dbColumn, $this->original) && ! array_key_exists($dbColumn, $this->attributes)) { return false; } // It's a new element if (! array_key_exists($dbColumn, $this->original) && array_key_exists($dbColumn, $this->attributes)) { return true; } return $this->original[$dbColumn] !== $this->attributes[$dbColumn]; } /** * Set raw data array without any mutations * * @return $this */ public function injectRawData(array $data) { $this->attributes = $data; $this->syncOriginal(); return $this; } /** * Set raw data array without any mutations * * @return $this * * @deprecated Use injectRawData() instead. */ public function setAttributes(array $data) { return $this->injectRawData($data); } /** * Checks the datamap to see if this property name is being mapped, * and returns the db column name, if any, or the original property name. * * @return string db column name */ protected function mapProperty(string $key) { if ($this->datamap === []) { return $key; } if (! empty($this->datamap[$key])) { return $this->datamap[$key]; } return $key; } /** * Converts the given string|timestamp|DateTime|Time instance * into the "CodeIgniter\I18n\Time" object. * * @param DateTime|float|int|string|Time $value * * @return Time * * @throws Exception */ protected function mutateDate($value) { return DatetimeCast::get($value); } /** * Provides the ability to cast an item as a specific data type. * Add ? at the beginning of the type (i.e. ?string) to get `null` * instead of casting $value when $value is null. * * @param bool|float|int|string|null $value Attribute value * @param string $attribute Attribute name * @param string $method Allowed to "get" and "set" * * @return array|bool|float|int|object|string|null * * @throws CastException */ protected function castAs($value, string $attribute, string $method = 'get') { return $this->dataCaster // @TODO if $casts is readonly, we don't need the setTypes() method. ->setTypes($this->casts) ->castAs($value, $attribute, $method); } /** * Support for json_encode() * * @return array */ #[ReturnTypeWillChange] public function jsonSerialize() { return $this->toArray(); } /** * Change the value of the private $_cast property * * @return bool|Entity */ public function cast(?bool $cast = null) { if ($cast === null) { return $this->_cast; } $this->_cast = $cast; return $this; } /** * Magic method to all protected/private class properties to be * easily set, either through a direct access or a * `setCamelCasedProperty()` method. * * Examples: * $this->my_property = $p; * $this->setMyProperty() = $p; * * @param array|bool|float|int|object|string|null $value * * @return void * * @throws Exception */ public function __set(string $key, $value = null) { $dbColumn = $this->mapProperty($key); // Check if the field should be mutated into a date if (in_array($dbColumn, $this->dates, true)) { $value = $this->mutateDate($value); } $value = $this->castAs($value, $dbColumn, 'set'); // if a setter method exists for this key, use that method to // insert this value. should be outside $isNullable check, // so maybe wants to do sth with null value automatically $method = 'set' . str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $dbColumn))); // If a "`_set` + $key" method exists, it is a setter. if (method_exists($this, '_' . $method)) { $this->{'_' . $method}($value); return; } // If a "`set` + $key" method exists, it is also a setter. if (method_exists($this, $method) && $method !== 'setAttributes') { $this->{$method}($value); return; } // Otherwise, just the value. This allows for creation of new // class properties that are undefined, though they cannot be // saved. Useful for grabbing values through joins, assigning // relationships, etc. $this->attributes[$dbColumn] = $value; } /** * Magic method to allow retrieval of protected and private class properties * either by their name, or through a `getCamelCasedProperty()` method. * * Examples: * $p = $this->my_property * $p = $this->getMyProperty() * * @return array|bool|float|int|object|string|null * * @throws Exception * * @params string $key class property */ public function __get(string $key) { $dbColumn = $this->mapProperty($key); $result = null; // Convert to CamelCase for the method $method = 'get' . str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $dbColumn))); // if a getter method exists for this key, // use that method to insert this value. if (method_exists($this, '_' . $method)) { // If a "`_get` + $key" method exists, it is a getter. $result = $this->{'_' . $method}(); } elseif (method_exists($this, $method)) { // If a "`get` + $key" method exists, it is also a getter. $result = $this->{$method}(); } // Otherwise return the protected property // if it exists. elseif (array_key_exists($dbColumn, $this->attributes)) { $result = $this->attributes[$dbColumn]; } // Do we need to mutate this into a date? if (in_array($dbColumn, $this->dates, true)) { $result = $this->mutateDate($result); } // Or cast it as something? elseif ($this->_cast) { $result = $this->castAs($result, $dbColumn); } return $result; } /** * Returns true if a property exists names $key, or a getter method * exists named like for __get(). */ public function __isset(string $key): bool { if ($this->isMappedDbColumn($key)) { return false; } $dbColumn = $this->mapProperty($key); $method = 'get' . str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $dbColumn))); if (method_exists($this, $method)) { return true; } return isset($this->attributes[$dbColumn]); } /** * Unsets an attribute property. */ public function __unset(string $key): void { if ($this->isMappedDbColumn($key)) { return; } $dbColumn = $this->mapProperty($key); unset($this->attributes[$dbColumn]); } /** * Whether this key is mapped db column name? */ protected function isMappedDbColumn(string $key): bool { $dbColumn = $this->mapProperty($key); // The $key is a property name which has mapped db column name if ($key !== $dbColumn) { return false; } return $this->hasMappedProperty($key); } /** * Whether this key has mapped property? */ protected function hasMappedProperty(string $key): bool { $property = array_search($key, $this->datamap, true); return $property !== false; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Entity/Cast/JsonCast.php
system/Entity/Cast/JsonCast.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\Entity\Cast; use CodeIgniter\Entity\Exceptions\CastException; use JsonException; use stdClass; /** * Class JsonCast */ class JsonCast extends BaseCast { /** * {@inheritDoc} */ public static function get($value, array $params = []) { $associative = in_array('array', $params, true); $tmp = $value !== null ? ($associative ? [] : new stdClass()) : null; if (function_exists('json_decode') && ( (is_string($value) && strlen($value) > 1 && in_array($value[0], ['[', '{', '"'], true)) || is_numeric($value) ) ) { try { $tmp = json_decode($value, $associative, 512, JSON_THROW_ON_ERROR); } catch (JsonException $e) { throw CastException::forInvalidJsonFormat($e->getCode()); } } return $tmp; } /** * {@inheritDoc} */ public static function set($value, array $params = []): string { if (function_exists('json_encode')) { try { $value = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR); } catch (JsonException $e) { throw CastException::forInvalidJsonFormat($e->getCode()); } } return $value; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Entity/Cast/TimestampCast.php
system/Entity/Cast/TimestampCast.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\Entity\Cast; use CodeIgniter\Entity\Exceptions\CastException; /** * Class TimestampCast */ class TimestampCast extends BaseCast { /** * {@inheritDoc} */ public static function get($value, array $params = []) { $value = strtotime($value); if ($value === false) { throw CastException::forInvalidTimestamp(); } return $value; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Entity/Cast/BaseCast.php
system/Entity/Cast/BaseCast.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\Entity\Cast; /** * Class BaseCast */ abstract class BaseCast implements CastInterface { /** * Get * * @param array|bool|float|int|object|string|null $value Data * @param array $params Additional param * * @return array|bool|float|int|object|string|null */ public static function get($value, array $params = []) { return $value; } /** * Set * * @param array|bool|float|int|object|string|null $value Data * @param array $params Additional param * * @return array|bool|float|int|object|string|null */ public static function set($value, array $params = []) { return $value; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Entity/Cast/ArrayCast.php
system/Entity/Cast/ArrayCast.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\Entity\Cast; /** * Class ArrayCast */ class ArrayCast extends BaseCast { /** * {@inheritDoc} */ public static function get($value, array $params = []): array { if (is_string($value) && (str_starts_with($value, 'a:') || str_starts_with($value, 's:'))) { $value = unserialize($value); } return (array) $value; } /** * {@inheritDoc} */ public static function set($value, array $params = []): string { return serialize($value); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Entity/Cast/FloatCast.php
system/Entity/Cast/FloatCast.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\Entity\Cast; /** * Class FloatCast */ class FloatCast extends BaseCast { /** * {@inheritDoc} */ public static function get($value, array $params = []): float { return (float) $value; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Entity/Cast/DatetimeCast.php
system/Entity/Cast/DatetimeCast.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\Entity\Cast; use CodeIgniter\I18n\Time; use DateTime; use Exception; /** * Class DatetimeCast */ class DatetimeCast extends BaseCast { /** * {@inheritDoc} * * @return Time * * @throws Exception */ public static function get($value, array $params = []) { if ($value instanceof Time) { return $value; } if ($value instanceof DateTime) { return Time::createFromInstance($value); } if (is_numeric($value)) { return Time::createFromTimestamp((int) $value, date_default_timezone_get()); } if (is_string($value)) { return Time::parse($value); } return $value; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Entity/Cast/StringCast.php
system/Entity/Cast/StringCast.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\Entity\Cast; /** * Class StringCast */ class StringCast extends BaseCast { /** * {@inheritDoc} */ public static function get($value, array $params = []): string { return (string) $value; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Entity/Cast/IntegerCast.php
system/Entity/Cast/IntegerCast.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\Entity\Cast; /** * Class IntegerCast */ class IntegerCast extends BaseCast { /** * {@inheritDoc} */ public static function get($value, array $params = []): int { return (int) $value; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Entity/Cast/IntBoolCast.php
system/Entity/Cast/IntBoolCast.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\Entity\Cast; /** * Int Bool Cast * * DB column: int (0/1) <--> Class property: bool */ final class IntBoolCast extends BaseCast { /** * @param int $value */ public static function get($value, array $params = []): bool { return (bool) $value; } /** * @param bool|int|string $value */ public static function set($value, array $params = []): int { return (int) $value; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Entity/Cast/URICast.php
system/Entity/Cast/URICast.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\Entity\Cast; use CodeIgniter\HTTP\URI; /** * Class URICast */ class URICast extends BaseCast { /** * {@inheritDoc} */ public static function get($value, array $params = []): URI { return $value instanceof URI ? $value : new URI($value); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Entity/Cast/CastInterface.php
system/Entity/Cast/CastInterface.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\Entity\Cast; /** * Interface CastInterface * * The methods work at (1)(4) only. * [App Code] --- (1) --> [Entity] --- (2) --> [Database] * [App Code] <-- (4) --- [Entity] <-- (3) --- [Database] */ interface CastInterface { /** * Takes a raw value from Entity, returns its value for PHP. * * @param array|bool|float|int|object|string|null $value Data * @param array $params Additional param * * @return array|bool|float|int|object|string|null */ public static function get($value, array $params = []); /** * Takes a PHP value, returns its raw value for Entity. * * @param array|bool|float|int|object|string|null $value Data * @param array $params Additional param * * @return array|bool|float|int|object|string|null */ public static function set($value, array $params = []); }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Entity/Cast/ObjectCast.php
system/Entity/Cast/ObjectCast.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\Entity\Cast; /** * Class ObjectCast */ class ObjectCast extends BaseCast { /** * {@inheritDoc} */ public static function get($value, array $params = []): object { return (object) $value; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Entity/Cast/BooleanCast.php
system/Entity/Cast/BooleanCast.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\Entity\Cast; /** * Class BooleanCast */ class BooleanCast extends BaseCast { /** * {@inheritDoc} */ public static function get($value, array $params = []): bool { return (bool) $value; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Entity/Cast/CSVCast.php
system/Entity/Cast/CSVCast.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\Entity\Cast; /** * Class CSVCast */ class CSVCast extends BaseCast { /** * {@inheritDoc} */ public static function get($value, array $params = []): array { return explode(',', $value); } /** * {@inheritDoc} */ public static function set($value, array $params = []): string { return implode(',', $value); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Entity/Exceptions/CastException.php
system/Entity/Exceptions/CastException.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\Entity\Exceptions; use CodeIgniter\Exceptions\FrameworkException; use CodeIgniter\Exceptions\HasExitCodeInterface; /** * CastException is thrown for invalid cast initialization and management. */ class CastException extends FrameworkException implements HasExitCodeInterface { public function getExitCode(): int { return EXIT_CONFIG; } /** * Thrown when the cast class does not extends BaseCast. * * @return static */ public static function forInvalidInterface(string $class) { return new static(lang('Cast.baseCastMissing', [$class])); } /** * Thrown when the Json format is invalid. * * @return static */ public static function forInvalidJsonFormat(int $error) { return match ($error) { JSON_ERROR_DEPTH => new static(lang('Cast.jsonErrorDepth')), JSON_ERROR_STATE_MISMATCH => new static(lang('Cast.jsonErrorStateMismatch')), JSON_ERROR_CTRL_CHAR => new static(lang('Cast.jsonErrorCtrlChar')), JSON_ERROR_SYNTAX => new static(lang('Cast.jsonErrorSyntax')), JSON_ERROR_UTF8 => new static(lang('Cast.jsonErrorUtf8')), default => new static(lang('Cast.jsonErrorUnknown')), }; } /** * Thrown when the cast method is not `get` or `set`. * * @return static */ public static function forInvalidMethod(string $method) { return new static(lang('Cast.invalidCastMethod', [$method])); } /** * Thrown when the casting timestamp is not correct timestamp. * * @return static */ public static function forInvalidTimestamp() { return new static(lang('Cast.invalidTimestamp')); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Traits/PropertiesTrait.php
system/Traits/PropertiesTrait.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\Traits; use ReflectionClass; use ReflectionProperty; /** * Trait PropertiesTrait * * Provides utilities for reading and writing * class properties, primarily for limiting access * to public properties. */ trait PropertiesTrait { /** * Attempts to set the values of public class properties. * * @return $this */ final public function fill(array $params): self { foreach ($params as $key => $value) { if (property_exists($this, $key)) { $this->{$key} = $value; } } return $this; } /** * Get the public properties of the class and return as an array. */ final public function getPublicProperties(): array { $worker = new class () { public function getProperties(object $obj): array { return get_object_vars($obj); } }; return $worker->getProperties($this); } /** * Get the protected and private properties of the class and return as an array. */ final public function getNonPublicProperties(): array { $exclude = ['view']; $properties = []; $reflection = new ReflectionClass($this); foreach ($reflection->getProperties(ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED) as $property) { if ($property->isStatic() || in_array($property->getName(), $exclude, true)) { continue; } $properties[] = $property; } return $properties; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Traits/ConditionalTrait.php
system/Traits/ConditionalTrait.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\Traits; trait ConditionalTrait { /** * Only runs the query when $condition evaluates to true * * @template TWhen of mixed * * @param TWhen $condition * @param callable(self, TWhen): mixed $callback * @param (callable(self): mixed)|null $defaultCallback * @param mixed $condition * * @return $this */ public function when($condition, callable $callback, ?callable $defaultCallback = null): self { if ((bool) $condition) { $callback($this, $condition); } elseif ($defaultCallback !== null) { $defaultCallback($this); } return $this; } /** * Only runs the query when $condition evaluates to false * * @template TWhenNot of mixed * * @param TWhenNot $condition * @param callable(self, TWhenNot): mixed $callback * @param (callable(self): mixed)|null $defaultCallback * @param mixed $condition * * @return $this */ public function whenNot($condition, callable $callback, ?callable $defaultCallback = null): self { if (! (bool) $condition) { $callback($this, $condition); } elseif ($defaultCallback !== null) { $defaultCallback($this); } return $this; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/ReflectionHelper.php
system/Test/ReflectionHelper.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\Test; use Closure; use ReflectionClass; use ReflectionException; use ReflectionMethod; use ReflectionObject; use ReflectionProperty; /** * Testing helper. */ trait ReflectionHelper { /** * Find a private method invoker. * * @param object|string $obj object or class name * @param string $method method name * * @return Closure(mixed ...$args): mixed * * @throws ReflectionException */ public static function getPrivateMethodInvoker($obj, $method) { $refMethod = new ReflectionMethod($obj, $method); $obj = (gettype($obj) === 'object') ? $obj : null; return static fn (...$args): mixed => $refMethod->invokeArgs($obj, $args); } /** * Find an accessible property. * * @param object|string $obj * @param string $property * * @return ReflectionProperty * * @throws ReflectionException */ private static function getAccessibleRefProperty($obj, $property) { $refClass = is_object($obj) ? new ReflectionObject($obj) : new ReflectionClass($obj); return $refClass->getProperty($property); } /** * Set a private property. * * @param object|string $obj object or class name * @param string $property property name * @param mixed $value value * * @throws ReflectionException */ public static function setPrivateProperty($obj, $property, $value): void { $refProperty = self::getAccessibleRefProperty($obj, $property); if (is_object($obj)) { $refProperty->setValue($obj, $value); } else { $refProperty->setValue(null, $value); } } /** * Retrieve a private property. * * @param object|string $obj object or class name * @param string $property property name * * @return mixed * * @throws ReflectionException */ public static function getPrivateProperty($obj, $property) { $refProperty = self::getAccessibleRefProperty($obj, $property); return is_string($obj) ? $refProperty->getValue() : $refProperty->getValue($obj); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/PhpStreamWrapper.php
system/Test/PhpStreamWrapper.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\Test; /** * StreamWrapper for php protocol * * This class is used for mocking `php://stdin`. * * See https://www.php.net/manual/en/class.streamwrapper.php */ final class PhpStreamWrapper { /** * @var resource|null */ public $context; private static string $content = ''; private int $position = 0; /** * @return void */ public static function setContent(string $content) { self::$content = $content; } /** * @return void */ public static function register() { stream_wrapper_unregister('php'); stream_wrapper_register('php', self::class); } /** * @return void */ public static function restore() { stream_wrapper_restore('php'); } public function stream_open(): bool { return true; } /** * @return string */ public function stream_read(int $count) { $return = substr(self::$content, $this->position, $count); $this->position += strlen($return); return $return; } /** * @return array{} */ public function stream_stat() { return []; } public function stream_eof(): bool { return $this->position >= strlen(self::$content); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/ConfigFromArrayTrait.php
system/Test/ConfigFromArrayTrait.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\Test; use CodeIgniter\Exceptions\LogicException; trait ConfigFromArrayTrait { /** * Creates a Config instance from an array. * * @template T of \CodeIgniter\Config\BaseConfig * * @param class-string<T> $classname Config classname * @param array<string, mixed> $config * * @return T */ private function createConfigFromArray(string $classname, array $config) { $configObj = new $classname(); foreach ($config as $key => $value) { if (property_exists($configObj, $key)) { $configObj->{$key} = $value; continue; } throw new LogicException( 'No such property: ' . $classname . '::$' . $key, ); } return $configObj; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/FilterTestTrait.php
system/Test/FilterTestTrait.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\Test; use Closure; use CodeIgniter\Exceptions\InvalidArgumentException; use CodeIgniter\Exceptions\RuntimeException; use CodeIgniter\Filters\Exceptions\FilterException; use CodeIgniter\Filters\FilterInterface; use CodeIgniter\Filters\Filters; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\Router\RouteCollection; use Config\Filters as FiltersConfig; /** * Filter Test Trait * * Provides functionality for testing * filters and their route associations. * * @mixin CIUnitTestCase */ trait FilterTestTrait { /** * Have the one-time classes been instantiated? * * @var bool */ private $doneFilterSetUp = false; /** * The active IncomingRequest or CLIRequest * * @var RequestInterface */ protected $request; /** * The active Response instance * * @var ResponseInterface */ protected $response; /** * The Filters configuration to use. * Extracted for access to aliases * during Filters::discoverFilters(). * * @var FiltersConfig|null */ protected $filtersConfig; /** * The prepared Filters library. * * @var Filters|null */ protected $filters; /** * The default App and discovered * routes to check for filters. * * @var RouteCollection|null */ protected $collection; // -------------------------------------------------------------------- // Staging // -------------------------------------------------------------------- /** * Initializes dependencies once. */ protected function setUpFilterTestTrait(): void { if ($this->doneFilterSetUp === true) { return; } // Create our own Request and Response so we can // use the same ones for Filters and FilterInterface // yet isolate them from outside influence $this->request ??= clone service('request'); $this->response ??= clone service('response'); // Create our config and Filters instance to reuse for performance $this->filtersConfig ??= config(FiltersConfig::class); $this->filters ??= new Filters($this->filtersConfig, $this->request, $this->response); if ($this->collection === null) { $this->collection = service('routes')->loadRoutes(); } $this->doneFilterSetUp = true; } // -------------------------------------------------------------------- // Utility // -------------------------------------------------------------------- /** * Returns a callable method for a filter position * using the local HTTP instances. * * @param FilterInterface|string $filter The filter instance, class, or alias * @param string $position "before" or "after" * * @return Closure(list<string>|null=): mixed */ protected function getFilterCaller($filter, string $position): Closure { if (! in_array($position, ['before', 'after'], true)) { throw new InvalidArgumentException('Invalid filter position passed: ' . $position); } if ($filter instanceof FilterInterface) { $filterInstances = [$filter]; } if (is_string($filter)) { // Check for an alias (no namespace) if (! str_contains($filter, '\\')) { if (! isset($this->filtersConfig->aliases[$filter])) { throw new RuntimeException("No filter found with alias '{$filter}'"); } $filterClasses = (array) $this->filtersConfig->aliases[$filter]; } else { // FQCN $filterClasses = [$filter]; } $filterInstances = []; foreach ($filterClasses as $class) { // Get an instance $filter = new $class(); if (! $filter instanceof FilterInterface) { throw FilterException::forIncorrectInterface($filter::class); } $filterInstances[] = $filter; } } $request = clone $this->request; if ($position === 'before') { return static function (?array $params = null) use ($filterInstances, $request) { $result = null; foreach ($filterInstances as $filter) { $result = $filter->before($request, $params); // @TODO The following logic is in Filters class. // Should use Filters class. if ($result instanceof RequestInterface) { $request = $result; continue; } if ($result instanceof ResponseInterface) { return $result; } if (empty($result)) { continue; } } return $result; }; } $response = clone $this->response; return static function (?array $params = null) use ($filterInstances, $request, $response) { $result = null; foreach ($filterInstances as $filter) { $result = $filter->after($request, $response, $params); // @TODO The following logic is in Filters class. // Should use Filters class. if ($result instanceof ResponseInterface) { $response = $result; continue; } } return $result; }; } /** * Gets an array of filter aliases enabled * for the given route at position. * * @param string $route The route to test * @param string $position "before" or "after" * * @return list<string> The filter aliases */ protected function getFiltersForRoute(string $route, string $position): array { if (! in_array($position, ['before', 'after'], true)) { throw new InvalidArgumentException('Invalid filter position passed:' . $position); } $this->filters->reset(); $routeFilters = $this->collection->getFiltersForRoute($route); if ($routeFilters !== []) { $this->filters->enableFilters($routeFilters, $position); } $aliases = $this->filters->initialize($route)->getFilters(); $this->filters->reset(); return $aliases[$position]; } // -------------------------------------------------------------------- // Assertions // -------------------------------------------------------------------- /** * Asserts that the given route at position uses * the filter (by its alias). * * @param string $route The route to test * @param string $position "before" or "after" * @param string $alias Alias for the anticipated filter */ protected function assertFilter(string $route, string $position, string $alias): void { $filters = $this->getFiltersForRoute($route, $position); $this->assertContains( $alias, $filters, "Filter '{$alias}' does not apply to '{$route}'.", ); } /** * Asserts that the given route at position does not * use the filter (by its alias). * * @param string $route The route to test * @param string $position "before" or "after" * @param string $alias Alias for the anticipated filter * * @return void */ protected function assertNotFilter(string $route, string $position, string $alias) { $filters = $this->getFiltersForRoute($route, $position); $this->assertNotContains( $alias, $filters, "Filter '{$alias}' applies to '{$route}' when it should not.", ); } /** * Asserts that the given route at position has * at least one filter set. * * @param string $route The route to test * @param string $position "before" or "after" * * @return void */ protected function assertHasFilters(string $route, string $position) { $filters = $this->getFiltersForRoute($route, $position); $this->assertNotEmpty( $filters, "No filters found for '{$route}' when at least one was expected.", ); } /** * Asserts that the given route at position has * no filters set. * * @param string $route The route to test * @param string $position "before" or "after" * * @return void */ protected function assertNotHasFilters(string $route, string $position) { $filters = $this->getFiltersForRoute($route, $position); $this->assertSame( [], $filters, "Found filters for '{$route}' when none were expected: " . implode(', ', $filters) . '.', ); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/TestLogger.php
system/Test/TestLogger.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\Test; use CodeIgniter\Log\Logger; use Stringable; /** * @see \CodeIgniter\Test\TestLoggerTest */ class TestLogger extends Logger { /** * @var list<array{level: mixed, message: string, file: string|null}> */ protected static $op_logs = []; /** * The log method is overridden so that we can store log history during * the tests to allow us to check ->assertLogged() methods. * * @param mixed $level * @param string $message */ public function log($level, string|Stringable $message, array $context = []): void { // While this requires duplicate work, we want to ensure // we have the final message to test against. $logMessage = $this->interpolate($message, $context); // Determine the file and line by finding the first // backtrace that is not part of our logging system. $trace = debug_backtrace(); $file = null; foreach ($trace as $row) { if (! in_array($row['function'], ['log', 'log_message'], true)) { $file = basename($row['file'] ?? ''); break; } } self::$op_logs[] = [ 'level' => $level, 'message' => $logMessage, 'file' => $file, ]; // Let the parent do it's thing. parent::log($level, $message, $context); } /** * Used by CIUnitTestCase class to provide ->assertLogged() methods. * * @param string $message * * @return bool */ public static function didLog(string $level, $message, bool $useExactComparison = true) { $lowerLevel = strtolower($level); foreach (self::$op_logs as $log) { if (strtolower($log['level']) !== $lowerLevel) { continue; } if ($useExactComparison) { if ($log['message'] === $message) { return true; } continue; } if (str_contains($log['message'], $message)) { return true; } } return false; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/StreamFilterTrait.php
system/Test/StreamFilterTrait.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\Test; use CodeIgniter\Test\Filters\CITestStreamFilter; trait StreamFilterTrait { protected function setUpStreamFilterTrait(): void { CITestStreamFilter::registration(); CITestStreamFilter::addOutputFilter(); CITestStreamFilter::addErrorFilter(); } protected function tearDownStreamFilterTrait(): void { CITestStreamFilter::removeOutputFilter(); CITestStreamFilter::removeErrorFilter(); } protected function getStreamFilterBuffer(): string { return CITestStreamFilter::$buffer; } protected function resetStreamFilterBuffer(): void { CITestStreamFilter::$buffer = ''; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Fabricator.php
system/Test/Fabricator.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\Test; use Closure; use CodeIgniter\Exceptions\FrameworkException; use CodeIgniter\Exceptions\InvalidArgumentException; use CodeIgniter\Exceptions\RuntimeException; use CodeIgniter\I18n\Time; use CodeIgniter\Model; use Config\App; use Faker\Factory; use Faker\Generator; use InvalidArgumentException as BaseInvalidArgumentException; /** * Fabricator * * Bridge class for using Faker to create example data based on * model specifications. * * @see \CodeIgniter\Test\FabricatorTest */ class Fabricator { /** * Array of counts for fabricated items * * @var array */ protected static $tableCounts = []; /** * Locale-specific Faker instance * * @var Generator */ protected $faker; /** * Model instance (can be non-framework if it follows framework design) * * @var Model|object */ protected $model; /** * Locale used to initialize Faker * * @var string */ protected $locale; /** * Map of properties and their formatter to use * * @var array|null */ protected $formatters; /** * Date fields present in the model * * @var array */ protected $dateFields = []; /** * Array of data to add or override faked versions * * @var array */ protected $overrides = []; /** * Array of single-use data to override faked versions * * @var array|null */ protected $tempOverrides; /** * Fields to be modified before applying any formatter. * * @var array{ * unique: array<non-empty-string, array{reset: bool, maxRetries: int}>, * optional: array<non-empty-string, array{weight: float, default: mixed}>, * valid: array<non-empty-string, array{validator: Closure(mixed): bool|null, maxRetries: int}> * } */ private array $modifiedFields = ['unique' => [], 'optional' => [], 'valid' => []]; /** * Default formatter to use when nothing is detected * * @var string */ public $defaultFormatter = 'word'; /** * Store the model instance and initialize Faker to the locale. * * @param object|string $model Instance or classname of the model to use * @param array|null $formatters Array of property => formatter * @param string|null $locale Locale for Faker provider * * @throws InvalidArgumentException */ public function __construct($model, ?array $formatters = null, ?string $locale = null) { if (is_string($model) && class_exists($model)) { $model = model($model, false); } if (! is_object($model)) { throw new InvalidArgumentException(lang('Fabricator.invalidModel')); } $this->model = $model; // If no locale was specified then use the App default if ($locale === null) { $locale = config(App::class)->defaultLocale; } // There is no easy way to retrieve the locale from Faker so we will store it $this->locale = $locale; // Create the locale-specific Generator $this->faker = Factory::create($this->locale); // Determine eligible date fields foreach (['createdField', 'updatedField', 'deletedField'] as $field) { if (isset($this->model->{$field})) { $this->dateFields[] = $this->model->{$field}; } } // Set the formatters $this->setFormatters($formatters); } /** * Reset internal counts * * @return void */ public static function resetCounts() { self::$tableCounts = []; } /** * Get the count for a specific table * * @param string $table Name of the target table */ public static function getCount(string $table): int { return ! isset(self::$tableCounts[$table]) ? 0 : self::$tableCounts[$table]; } /** * Set the count for a specific table * * @param string $table Name of the target table * @param int $count Count value * * @return int The new count value */ public static function setCount(string $table, int $count): int { self::$tableCounts[$table] = $count; return $count; } /** * Increment the count for a table * * @param string $table Name of the target table * * @return int The new count value */ public static function upCount(string $table): int { return self::setCount($table, self::getCount($table) + 1); } /** * Decrement the count for a table * * @param string $table Name of the target table * * @return int The new count value */ public static function downCount(string $table): int { return self::setCount($table, self::getCount($table) - 1); } /** * Returns the model instance * * @return object Framework or compatible model */ public function getModel() { return $this->model; } /** * Returns the locale */ public function getLocale(): string { return $this->locale; } /** * Returns the Faker generator */ public function getFaker(): Generator { return $this->faker; } /** * Return and reset tempOverrides */ public function getOverrides(): array { $overrides = $this->tempOverrides ?? $this->overrides; $this->tempOverrides = $this->overrides; return $overrides; } /** * Set the overrides, once or persistent * * @param array $overrides Array of [field => value] * @param bool $persist Whether these overrides should persist through the next operation */ public function setOverrides(array $overrides = [], $persist = true): self { if ($persist) { $this->overrides = $overrides; } $this->tempOverrides = $overrides; return $this; } /** * Set a field to be unique. * * @param bool $reset If set to true, resets the list of existing values * @param int $maxRetries Maximum number of retries to find a unique value, * After which an OverflowException is thrown. */ public function setUnique(string $field, bool $reset = false, int $maxRetries = 10000): static { $this->modifiedFields['unique'][$field] = compact('reset', 'maxRetries'); return $this; } /** * Set a field to be optional. * * @param float $weight A probability between 0 and 1, 0 means that we always get the default value. */ public function setOptional(string $field, float $weight = 0.5, mixed $default = null): static { $this->modifiedFields['optional'][$field] = compact('weight', 'default'); return $this; } /** * Set a field to be valid using a callback. * * @param Closure(mixed): bool|null $validator A function returning true for valid values * @param int $maxRetries Maximum number of retries to find a valid value, * After which an OverflowException is thrown. */ public function setValid(string $field, ?Closure $validator = null, int $maxRetries = 10000): static { $this->modifiedFields['valid'][$field] = compact('validator', 'maxRetries'); return $this; } /** * Returns the current formatters */ public function getFormatters(): ?array { return $this->formatters; } /** * Set the formatters to use. Will attempt to autodetect if none are available. * * @param array|null $formatters Array of [field => formatter], or null to detect */ public function setFormatters(?array $formatters = null): self { if ($formatters !== null) { $this->formatters = $formatters; } elseif (method_exists($this->model, 'fake')) { $this->formatters = null; } else { $this->detectFormatters(); } return $this; } /** * Try to identify the appropriate Faker formatter for each field. */ protected function detectFormatters(): self { $this->formatters = []; if (isset($this->model->allowedFields)) { foreach ($this->model->allowedFields as $field) { $this->formatters[$field] = $this->guessFormatter($field); } } return $this; } /** * Guess at the correct formatter to match a field name. * * @param string $field Name of the field * * @return string Name of the formatter */ protected function guessFormatter($field): string { // First check for a Faker formatter of the same name - covers things like "email" try { $this->faker->getFormatter($field); return $field; } catch (BaseInvalidArgumentException) { // No match, keep going } // Next look for known model fields if (in_array($field, $this->dateFields, true)) { switch ($this->model->dateFormat) { case 'datetime': case 'date': return 'date'; case 'int': return 'unixTime'; } } elseif ($field === $this->model->primaryKey) { return 'numberBetween'; } // Check some common partials foreach (['email', 'name', 'title', 'text', 'date', 'url'] as $term) { if (str_contains(strtolower($field), strtolower($term))) { return $term; } } if (str_contains(strtolower($field), 'phone')) { return 'phoneNumber'; } // Nothing left, use the default return $this->defaultFormatter; } /** * Generate new entities with faked data * * @param int|null $count Optional number to create a collection * * @return array|object An array or object (based on returnType), or an array of returnTypes */ public function make(?int $count = null) { // If a singleton was requested then go straight to it if ($count === null) { return $this->model->returnType === 'array' ? $this->makeArray() : $this->makeObject(); } $return = []; for ($i = 0; $i < $count; $i++) { $return[] = $this->model->returnType === 'array' ? $this->makeArray() : $this->makeObject(); } return $return; } /** * Generate an array of faked data * * @return array An array of faked data * * @throws RuntimeException */ public function makeArray() { if ($this->formatters !== null) { $result = []; foreach ($this->formatters as $field => $formatter) { $faker = $this->faker; if (isset($this->modifiedFields['unique'][$field])) { $faker = $faker->unique( $this->modifiedFields['unique'][$field]['reset'], $this->modifiedFields['unique'][$field]['maxRetries'], ); } if (isset($this->modifiedFields['optional'][$field])) { $faker = $faker->optional( $this->modifiedFields['optional'][$field]['weight'], $this->modifiedFields['optional'][$field]['default'], ); } if (isset($this->modifiedFields['valid'][$field])) { $faker = $faker->valid( $this->modifiedFields['valid'][$field]['validator'], $this->modifiedFields['valid'][$field]['maxRetries'], ); } $result[$field] = $faker->format($formatter); } } // If no formatters were defined then look for a model fake() method elseif (method_exists($this->model, 'fake')) { $result = $this->model->fake($this->faker); $result = is_object($result) && method_exists($result, 'toArray') // This should cover entities ? $result->toArray() // Try to cast it : (array) $result; } // Nothing left to do but give up else { throw new RuntimeException(lang('Fabricator.missingFormatters')); } // Replace overridden fields return array_merge($result, $this->getOverrides()); } /** * Generate an object of faked data * * @param string|null $className Class name of the object to create; null to use model default * * @return object An instance of the class with faked data * * @throws RuntimeException */ public function makeObject(?string $className = null): object { if ($className === null) { if ($this->model->returnType === 'object' || $this->model->returnType === 'array') { $className = 'stdClass'; } else { $className = $this->model->returnType; } } // If using the model's fake() method then check it for the correct return type if ($this->formatters === null && method_exists($this->model, 'fake')) { $result = $this->model->fake($this->faker); if ($result instanceof $className) { // Set overrides manually foreach ($this->getOverrides() as $key => $value) { $result->{$key} = $value; } return $result; } } // Get the array values and apply them to the object $array = $this->makeArray(); $object = new $className(); // Check for the entity method if (method_exists($object, 'fill')) { $object->fill($array); } else { foreach ($array as $key => $value) { $object->{$key} = $value; } } return $object; } /** * Generate new entities from the database * * @param int|null $count Optional number to create a collection * @param bool $mock Whether to execute or mock the insertion * * @return array|object An array or object (based on returnType), or an array of returnTypes * * @throws FrameworkException */ public function create(?int $count = null, bool $mock = false) { // Intercept mock requests if ($mock) { return $this->createMock($count); } $ids = []; // Iterate over new entities and insert each one, storing insert IDs foreach ($this->make($count ?? 1) as $result) { if ($id = $this->model->insert($result, true)) { $ids[] = $id; self::upCount($this->model->table); continue; } throw FrameworkException::forFabricatorCreateFailed($this->model->table, implode(' ', $this->model->errors() ?? [])); } // If the model defines a "withDeleted" method for handling soft deletes then use it if (method_exists($this->model, 'withDeleted')) { $this->model->withDeleted(); } return $this->model->find($count === null ? reset($ids) : $ids); } /** * Generate new database entities without actually inserting them * * @param int|null $count Optional number to create a collection * * @return array|object An array or object (based on returnType), or an array of returnTypes */ protected function createMock(?int $count = null) { $datetime = match ($this->model->dateFormat) { 'datetime' => date('Y-m-d H:i:s'), 'date' => date('Y-m-d'), default => Time::now()->getTimestamp(), }; // Determine which fields we will need $fields = []; if ($this->model->useTimestamps) { $fields[$this->model->createdField] = $datetime; $fields[$this->model->updatedField] = $datetime; } if ($this->model->useSoftDeletes) { $fields[$this->model->deletedField] = null; } // Iterate over new entities and add the necessary fields $return = []; foreach ($this->make($count ?? 1) as $i => $result) { // Set the ID $fields[$this->model->primaryKey] = $i; // Merge fields if (is_array($result)) { $result = array_merge($result, $fields); } else { foreach ($fields as $key => $value) { $result->{$key} = $value; } } $return[] = $result; } return $count === null ? reset($return) : $return; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/IniTestTrait.php
system/Test/IniTestTrait.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\Test; trait IniTestTrait { private array $iniSettings = []; private function backupIniValues(array $keys): void { foreach ($keys as $key) { $this->iniSettings[$key] = ini_get($key); } } private function restoreIniValues(): void { foreach ($this->iniSettings as $key => $value) { ini_set($key, $value); } $this->iniSettings = []; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/ControllerTestTrait.php
system/Test/ControllerTestTrait.php
<?php /** * 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\Test; use CodeIgniter\Controller; use CodeIgniter\Exceptions\InvalidArgumentException; use CodeIgniter\HTTP\Exceptions\HTTPException; use CodeIgniter\HTTP\IncomingRequest; use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\HTTP\URI; use Config\App; use Config\Services; use Psr\Log\LoggerInterface; use Throwable; /** * Controller Test Trait * * Provides features that make testing controllers simple and fluent. * * Example: * * $this->withRequest($request) * ->withResponse($response) * ->withUri($uri) * ->withBody($body) * ->controller('App\Controllers\Home') * ->execute('methodName'); */ trait ControllerTestTrait { /** * Controller configuration. * * @var App */ protected $appConfig; /** * Request. * * @var IncomingRequest */ protected $request; /** * Response. * * @var ResponseInterface */ protected $response; /** * Message logger. * * @var LoggerInterface */ protected $logger; /** * Initialized controller. * * @var Controller */ protected $controller; /** * URI of this request. * * @var string */ protected $uri = 'http://example.com'; /** * Request body. * * @var string|null */ protected $body; /** * Initializes required components. */ protected function setUpControllerTestTrait(): void { // The URL helper is always loaded by the system so ensure it is available. helper('url'); if (! $this->appConfig instanceof App) { $this->appConfig = config(App::class); } if (! $this->uri instanceof URI) { $factory = Services::siteurifactory($this->appConfig, service('superglobals'), false); $this->uri = $factory->createFromGlobals(); } if (! $this->request instanceof IncomingRequest) { // Do some acrobatics, so we can use the Request service with our own URI $tempUri = service('uri'); Services::injectMock('uri', $this->uri); $this->withRequest(service('incomingrequest', $this->appConfig, false)); // Restore the URI service Services::injectMock('uri', $tempUri); } if (! $this->response instanceof ResponseInterface) { $this->response = service('response', $this->appConfig, false); } if (! $this->logger instanceof LoggerInterface) { $this->logger = service('logger'); } } /** * Loads the specified controller, and generates any needed dependencies. * * @return $this */ public function controller(string $name) { if (! class_exists($name)) { throw new InvalidArgumentException('Invalid Controller: ' . $name); } $this->controller = new $name(); $this->controller->initController($this->request, $this->response, $this->logger); return $this; } /** * Runs the specified method on the controller and returns the results. * * @param array $params * * @return TestResponse * * @throws InvalidArgumentException */ public function execute(string $method, ...$params) { if (! method_exists($this->controller, $method) || ! is_callable([$this->controller, $method])) { throw new InvalidArgumentException('Method does not exist or is not callable in controller: ' . $method); } $response = null; $this->request->setBody($this->body); try { ob_start(); // The controller method param types may not be string. // So cannot set `declare(strict_types=1)` in this file. $response = $this->controller->{$method}(...$params); } catch (Throwable $e) { $code = $e->getCode(); // If code is not a valid HTTP status then assume there is an error if ($code < 100 || $code >= 600) { throw $e; } } finally { $output = ob_get_clean(); } // If the controller returned a view then add it to the output if (is_string($response)) { $output = is_string($output) ? $output . $response : $response; } // If the controller did not return a response then start one if (! $response instanceof ResponseInterface) { $response = $this->response; } // Check for output to set or prepend // @see \CodeIgniter\CodeIgniter::gatherOutput() if (is_string($output)) { if (is_string($response->getBody())) { $response->setBody($output . $response->getBody()); } else { $response->setBody($output); } } // Check for an overriding code from exceptions if (isset($code)) { $response->setStatusCode($code); } // Otherwise ensure there is a status code else { // getStatusCode() throws for empty codes try { $response->getStatusCode(); } catch (HTTPException) { // If no code has been set then assume success $response->setStatusCode(200); } } // Create the result and add the Request for reference return (new TestResponse($response))->setRequest($this->request); } /** * Set controller's config, with method chaining. * * @param App $appConfig * * @return $this */ public function withConfig($appConfig) { $this->appConfig = $appConfig; return $this; } /** * Set controller's request, with method chaining. * * @param IncomingRequest $request * * @return $this */ public function withRequest($request) { $this->request = $request; // Make sure it's available for other classes Services::injectMock('request', $request); return $this; } /** * Set controller's response, with method chaining. * * @param ResponseInterface $response * * @return $this */ public function withResponse($response) { $this->response = $response; return $this; } /** * Set controller's logger, with method chaining. * * @param LoggerInterface $logger * * @return $this */ public function withLogger($logger) { $this->logger = $logger; return $this; } /** * Set the controller's URI, with method chaining. * * @return $this */ public function withUri(string $uri) { $factory = service('siteurifactory'); $this->uri = $factory->createFromString($uri); Services::injectMock('uri', $this->uri); // Update the Request instance, because Request has the SiteURI instance. $this->request = service('incomingrequest', null, false); Services::injectMock('request', $this->request); return $this; } /** * Set the method's body, with method chaining. * * @param string|null $body * * @return $this */ public function withBody($body) { $this->body = $body; return $this; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/bootstrap.php
system/Test/bootstrap.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. */ use CodeIgniter\Boot; use Config\Paths; error_reporting(E_ALL); ini_set('display_errors', '1'); ini_set('display_startup_errors', '1'); /* * --------------------------------------------------------------- * DEFINE ENVIRONMENT * --------------------------------------------------------------- */ // Make sure it recognizes that we're testing. $_SERVER['CI_ENVIRONMENT'] = 'testing'; define('ENVIRONMENT', 'testing'); defined('CI_DEBUG') || define('CI_DEBUG', true); /* * --------------------------------------------------------------- * SET UP OUR PATH CONSTANTS * --------------------------------------------------------------- * * The path constants provide convenient access to the folders * throughout the application. We have to set them up here * so they are available in the config files that are loaded. */ // Often these constants are pre-defined, but query the current directory structure as a fallback defined('HOMEPATH') || define('HOMEPATH', realpath(rtrim(getcwd(), '\\/ ')) . DIRECTORY_SEPARATOR); $source = is_dir(HOMEPATH . 'app') ? HOMEPATH : (is_dir('vendor/codeigniter4/framework/') ? 'vendor/codeigniter4/framework/' : 'vendor/codeigniter4/codeigniter4/'); defined('CONFIGPATH') || define('CONFIGPATH', realpath($source . 'app/Config') . DIRECTORY_SEPARATOR); defined('PUBLICPATH') || define('PUBLICPATH', realpath($source . 'public') . DIRECTORY_SEPARATOR); unset($source); // LOAD OUR PATHS CONFIG FILE // Load framework paths from their config file require CONFIGPATH . 'Paths.php'; $paths = new Paths(); // Define necessary framework path constants defined('APPPATH') || define('APPPATH', realpath(rtrim($paths->appDirectory, '\\/ ')) . DIRECTORY_SEPARATOR); defined('ROOTPATH') || define('ROOTPATH', realpath(APPPATH . '../') . DIRECTORY_SEPARATOR); defined('SYSTEMPATH') || define('SYSTEMPATH', realpath(rtrim($paths->systemDirectory, '\\/')) . DIRECTORY_SEPARATOR); defined('WRITEPATH') || define('WRITEPATH', realpath(rtrim($paths->writableDirectory, '\\/ ')) . DIRECTORY_SEPARATOR); defined('TESTPATH') || define('TESTPATH', realpath(HOMEPATH . 'tests/') . DIRECTORY_SEPARATOR); defined('CIPATH') || define('CIPATH', realpath(SYSTEMPATH . '../') . DIRECTORY_SEPARATOR); defined('FCPATH') || define('FCPATH', realpath(PUBLICPATH) . DIRECTORY_SEPARATOR); defined('SUPPORTPATH') || define('SUPPORTPATH', realpath(TESTPATH . '_support/') . DIRECTORY_SEPARATOR); defined('COMPOSER_PATH') || define('COMPOSER_PATH', (string) realpath(HOMEPATH . 'vendor/autoload.php')); defined('VENDORPATH') || define('VENDORPATH', realpath(HOMEPATH . 'vendor') . DIRECTORY_SEPARATOR); /* *--------------------------------------------------------------- * BOOTSTRAP THE APPLICATION *--------------------------------------------------------------- * This process sets up the path constants, loads and registers * our autoloader, along with Composer's, loads our constants * and fires up an environment-specific bootstrapping. */ // LOAD THE FRAMEWORK BOOTSTRAP FILE require $paths->systemDirectory . '/Boot.php'; Boot::bootTest($paths); /* * --------------------------------------------------------------- * LOAD ROUTES * --------------------------------------------------------------- */ service('routes')->loadRoutes();
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/DatabaseTestTrait.php
system/Test/DatabaseTestTrait.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\Test; use CodeIgniter\Database\BaseBuilder; use CodeIgniter\Database\Exceptions\DatabaseException; use CodeIgniter\Test\Constraints\SeeInDatabase; use Config\Database; use Config\Migrations; use Config\Services; use PHPUnit\Framework\Attributes\AfterClass; /** * DatabaseTestTrait * * Provides functionality for refreshing/seeding * the database during testing. * * @mixin CIUnitTestCase */ trait DatabaseTestTrait { /** * Is db migration done once or more than once? * * @var bool */ private static $doneMigration = false; /** * Is seeding done once or more than once? * * @var bool */ private static $doneSeed = false; // -------------------------------------------------------------------- // Staging // -------------------------------------------------------------------- /** * Runs the trait set up methods. * * @return void */ protected function setUpDatabase() { $this->loadDependencies(); $this->setUpMigrate(); $this->setUpSeed(); } /** * Runs the trait set up methods. * * @return void */ protected function tearDownDatabase() { $this->clearInsertCache(); } /** * Load any database test dependencies. * * @return void */ public function loadDependencies() { if ($this->db === null) { $this->db = Database::connect($this->DBGroup); $this->db->initialize(); } if ($this->migrations === null) { // Ensure that we can run migrations $config = new Migrations(); $config->enabled = true; $this->migrations = Services::migrations($config, $this->db, false); $this->migrations->setSilent(false); } if ($this->seeder === null) { $this->seeder = Database::seeder($this->DBGroup); $this->seeder->setSilent(true); } } // -------------------------------------------------------------------- // Migrations // -------------------------------------------------------------------- /** * Migrate on setUp * * @return void */ protected function setUpMigrate() { if ($this->migrateOnce === false || self::$doneMigration === false) { if ($this->refresh === true) { $this->regressDatabase(); // Reset counts on faked items Fabricator::resetCounts(); } $this->migrateDatabase(); } } /** * Regress migrations as defined by the class * * @return void */ protected function regressDatabase() { if ($this->migrate === false) { return; } // If no namespace was specified then rollback all if ($this->namespace === null) { $this->migrations->setNamespace(null); $this->migrations->regress(0, 'tests'); } // Regress each specified namespace else { $namespaces = is_array($this->namespace) ? $this->namespace : [$this->namespace]; foreach ($namespaces as $namespace) { $this->migrations->setNamespace($namespace); $this->migrations->regress(0, 'tests'); } } } /** * Run migrations as defined by the class * * @return void */ protected function migrateDatabase() { if ($this->migrate === false) { return; } // If no namespace was specified then migrate all if ($this->namespace === null) { $this->migrations->setNamespace(null); $this->migrations->latest('tests'); self::$doneMigration = true; } // Run migrations for each specified namespace else { $namespaces = is_array($this->namespace) ? $this->namespace : [$this->namespace]; foreach ($namespaces as $namespace) { $this->migrations->setNamespace($namespace); $this->migrations->latest('tests'); self::$doneMigration = true; } } } // -------------------------------------------------------------------- // Seeds // -------------------------------------------------------------------- /** * Seed on setUp * * @return void */ protected function setUpSeed() { if ($this->seedOnce === false || self::$doneSeed === false) { $this->runSeeds(); } } /** * Run seeds as defined by the class * * @return void */ protected function runSeeds() { if ($this->seed !== '') { if ($this->basePath !== '') { $this->seeder->setPath(rtrim($this->basePath, '/') . '/Seeds'); } $seeds = is_array($this->seed) ? $this->seed : [$this->seed]; foreach ($seeds as $seed) { $this->seed($seed); } } self::$doneSeed = true; } /** * Seeds that database with a specific seeder. * * @return void */ public function seed(string $name) { $this->seeder->call($name); } // -------------------------------------------------------------------- // Utility // -------------------------------------------------------------------- /** * Reset $doneMigration and $doneSeed * * @return void */ #[AfterClass] public static function resetMigrationSeedCount() { self::$doneMigration = false; self::$doneSeed = false; } /** * Removes any rows inserted via $this->hasInDatabase() * * @return void */ protected function clearInsertCache() { foreach ($this->insertCache as $row) { $this->db->table($row[0]) ->where($row[1]) ->delete(); } } /** * Loads the Builder class appropriate for the current database. * * @return BaseBuilder */ public function loadBuilder(string $tableName) { $builderClass = str_replace('Connection', 'Builder', $this->db::class); return new $builderClass($tableName, $this->db); } /** * Fetches a single column from a database row with criteria * matching $where. * * @param array<string, mixed> $where * * @return bool * * @throws DatabaseException */ public function grabFromDatabase(string $table, string $column, array $where) { $query = $this->db->table($table) ->select($column) ->where($where) ->get(); $query = $query->getRow(); return $query->{$column} ?? false; } // -------------------------------------------------------------------- // Assertions // -------------------------------------------------------------------- /** * Asserts that records that match the conditions in $where DO * exist in the database. * * @param array<string, mixed> $where * * @return void * * @throws DatabaseException */ public function seeInDatabase(string $table, array $where) { $constraint = new SeeInDatabase($this->db, $where); static::assertThat($table, $constraint); } /** * Asserts that records that match the conditions in $where do * not exist in the database. * * @param array<string, mixed> $where * * @return void */ public function dontSeeInDatabase(string $table, array $where) { $count = $this->db->table($table) ->where($where) ->countAllResults(); $this->assertTrue($count === 0, 'Row was found in database'); } /** * Inserts a row into to the database. This row will be removed * after the test has run. * * @param array<string, mixed> $data * * @return bool */ public function hasInDatabase(string $table, array $data) { $this->insertCache[] = [ $table, $data, ]; return $this->db->table($table)->insert($data); } /** * Asserts that the number of rows in the database that match $where * is equal to $expected. * * @param array<string, mixed> $where * * @return void * * @throws DatabaseException */ public function seeNumRecords(int $expected, string $table, array $where) { $count = $this->db->table($table) ->where($where) ->countAllResults(); $this->assertEquals($expected, $count, 'Wrong number of matching rows in database.'); } /** * Sets $DBDebug to false. * * WARNING: this value will persist! take care to roll it back. */ protected function disableDBDebug(): void { $this->setPrivateProperty($this->db, 'DBDebug', false); } /** * Sets $DBDebug to true. */ protected function enableDBDebug(): void { $this->setPrivateProperty($this->db, 'DBDebug', true); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/FeatureTestTrait.php
system/Test/FeatureTestTrait.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\Test; use CodeIgniter\Events\Events; use CodeIgniter\HTTP\Exceptions\RedirectException; use CodeIgniter\HTTP\IncomingRequest; use CodeIgniter\HTTP\Method; use CodeIgniter\HTTP\Request; use CodeIgniter\HTTP\SiteURI; use CodeIgniter\HTTP\URI; use Config\App; use Config\Services; use Exception; use ReflectionException; /** * Trait FeatureTestTrait * * Provides additional utilities for doing full HTTP testing * against your application in trait format. */ trait FeatureTestTrait { /** * Sets a RouteCollection that will override * the application's route collection. * * Example routes: * [ * ['GET', 'home', 'Home::index'], * ] * * @param array|null $routes Array to set routes * * @return $this */ protected function withRoutes(?array $routes = null) { $collection = service('routes'); if ($routes !== null) { $collection->resetRoutes(); foreach ($routes as $route) { if ($route[0] === strtolower($route[0])) { @trigger_error( 'Passing lowercase HTTP method "' . $route[0] . '" is deprecated.' . ' Use uppercase HTTP method like "' . strtoupper($route[0]) . '".', E_USER_DEPRECATED, ); } /** * @TODO For backward compatibility. Remove strtolower() in the future. * @deprecated 4.5.0 */ $method = strtolower($route[0]); if (isset($route[3])) { $collection->{$method}($route[1], $route[2], $route[3]); } else { $collection->{$method}($route[1], $route[2]); } } } $this->routes = $collection; return $this; } /** * Sets any values that should exist during this session. * * @param array|null $values Array of values, or null to use the current $_SESSION * * @return $this */ public function withSession(?array $values = null) { $this->session = $values ?? $_SESSION; return $this; } /** * Set request's headers * * Example of use * withHeaders([ * 'Authorization' => 'Token' * ]) * * @param array $headers Array of headers * * @return $this */ public function withHeaders(array $headers = []) { $this->headers = $headers; return $this; } /** * Set the format the request's body should have. * * @param string $format The desired format. Currently supported formats: xml, json * * @return $this */ public function withBodyFormat(string $format) { $this->bodyFormat = $format; return $this; } /** * Set the raw body for the request * * @param string $body * * @return $this */ public function withBody($body) { $this->requestBody = $body; return $this; } /** * Don't run any events while running this test. * * @return $this */ public function skipEvents() { Events::simulate(true); return $this; } /** * Calls a single URI, executes it, and returns a TestResponse * instance that can be used to run many assertions against. * * @param string $method HTTP verb * * @return TestResponse */ public function call(string $method, string $path, ?array $params = null) { if ($method === strtolower($method)) { @trigger_error( 'Passing lowercase HTTP method "' . $method . '" is deprecated.' . ' Use uppercase HTTP method like "' . strtoupper($method) . '".', E_USER_DEPRECATED, ); } /** * @deprecated 4.5.0 * @TODO remove this in the future. */ $method = strtoupper($method); // Simulate having a blank session $_SESSION = []; service('superglobals')->setServer('REQUEST_METHOD', $method); $request = $this->setupRequest($method, $path); $request = $this->setupHeaders($request); $name = strtolower($method); $request = $this->populateGlobals($name, $request, $params); $request = $this->setRequestBody($request, $params); // Initialize the RouteCollection $routes = $this->routes; if ($routes !== []) { $routes = service('routes')->loadRoutes(); } $routes->setHTTPVerb($method); // Make sure any other classes that might call the request // instance get the right one. Services::injectMock('request', $request); // Make sure filters are reset between tests Services::injectMock('filters', service('filters', null, false)); // Make sure validation is reset between tests Services::injectMock('validation', service('validation', null, false)); $response = $this->app ->setContext('web') ->setRequest($request) ->run($routes, true); // Reset directory if it has been set service('router')->setDirectory(null); return new TestResponse($response); } /** * Performs a GET request. * * @param string $path URI path relative to baseURL. May include query. * * @return TestResponse * * @throws RedirectException * @throws Exception */ public function get(string $path, ?array $params = null) { return $this->call(Method::GET, $path, $params); } /** * Performs a POST request. * * @return TestResponse * * @throws RedirectException * @throws Exception */ public function post(string $path, ?array $params = null) { return $this->call(Method::POST, $path, $params); } /** * Performs a PUT request * * @return TestResponse * * @throws RedirectException * @throws Exception */ public function put(string $path, ?array $params = null) { return $this->call(Method::PUT, $path, $params); } /** * Performss a PATCH request * * @return TestResponse * * @throws RedirectException * @throws Exception */ public function patch(string $path, ?array $params = null) { return $this->call(Method::PATCH, $path, $params); } /** * Performs a DELETE request. * * @return TestResponse * * @throws RedirectException * @throws Exception */ public function delete(string $path, ?array $params = null) { return $this->call(Method::DELETE, $path, $params); } /** * Performs an OPTIONS request. * * @return TestResponse * * @throws RedirectException * @throws Exception */ public function options(string $path, ?array $params = null) { return $this->call(Method::OPTIONS, $path, $params); } /** * Setup a Request object to use so that CodeIgniter * won't try to auto-populate some of the items. * * @param string $method HTTP verb */ protected function setupRequest(string $method, ?string $path = null): IncomingRequest { $config = config(App::class); $uri = new SiteURI($config); // $path may have a query in it $path = URI::removeDotSegments($path); $parts = explode('?', $path); $path = $parts[0]; $query = $parts[1] ?? ''; $superglobals = service('superglobals'); $superglobals->setServer('QUERY_STRING', $query); $uri->setPath($path); $uri->setQuery($query); Services::injectMock('uri', $uri); $request = service('incomingrequest', $config, false); $request->setMethod($method); $request->setProtocolVersion('1.1'); if ($config->forceGlobalSecureRequests) { $_SERVER['HTTPS'] = 'test'; $server = $request->getServer(); $server['HTTPS'] = 'test'; $request->setGlobal('server', $server); } return $request; } /** * Setup the custom request's headers * * @return IncomingRequest */ protected function setupHeaders(IncomingRequest $request) { if (! empty($this->headers)) { foreach ($this->headers as $name => $value) { $request->setHeader($name, $value); } } return $request; } /** * Populates the data of our Request with "global" data * relevant to the request, like $_POST data. * * Always populate the GET vars based on the URI. * * @param string $name Superglobal name (lowercase) * @param non-empty-array|null $params * * @return Request * * @throws ReflectionException */ protected function populateGlobals(string $name, Request $request, ?array $params = null) { // $params should set the query vars if present, // otherwise set it from the URL. $get = ($params !== null && $params !== [] && $name === 'get') ? $params : $this->getPrivateProperty($request->getUri(), 'query'); $request->setGlobal('get', $get); if ($name === 'get') { $request->setGlobal('request', $request->fetchGlobal('get')); } if ($name === 'post') { $request->setGlobal($name, $params); $request->setGlobal( 'request', $request->fetchGlobal('post') + $request->fetchGlobal('get'), ); } $_SESSION = $this->session ?? []; return $request; } /** * Set the request's body formatted according to the value in $this->bodyFormat. * This allows the body to be formatted in a way that the controller is going to * expect as in the case of testing a JSON or XML API. * * @param array|null $params The parameters to be formatted and put in the body. */ protected function setRequestBody(Request $request, ?array $params = null): Request { if ($this->requestBody !== '') { $request->setBody($this->requestBody); } if ($this->bodyFormat !== '') { $formatMime = ''; if ($this->bodyFormat === 'json') { $formatMime = 'application/json'; } elseif ($this->bodyFormat === 'xml') { $formatMime = 'application/xml'; } if ($formatMime !== '') { $request->setHeader('Content-Type', $formatMime); } if ($params !== null && $formatMime !== '') { $formatted = service('format')->getFormatter($formatMime)->format($params); // "withBodyFormat() and $params of call()" has higher priority than withBody(). $request->setBody($formatted); } } return $request; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/DOMParser.php
system/Test/DOMParser.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\Test; use CodeIgniter\Exceptions\BadMethodCallException; use CodeIgniter\Exceptions\InvalidArgumentException; use DOMDocument; use DOMNodeList; use DOMXPath; /** * Load a response into a DOMDocument for testing assertions based on that * * @see \CodeIgniter\Test\DOMParserTest */ class DOMParser { /** * DOM for the body, * * @var DOMDocument */ protected $dom; /** * Constructor. * * @throws BadMethodCallException */ public function __construct() { if (! extension_loaded('DOM')) { throw new BadMethodCallException('DOM extension is required, but not currently loaded.'); // @codeCoverageIgnore } $this->dom = new DOMDocument('1.0', 'utf-8'); } /** * Returns the body of the current document. */ public function getBody(): string { return $this->dom->saveHTML(); } /** * Sets a string as the body that we want to work with. * * @return $this */ public function withString(string $content) { // DOMDocument::loadHTML() will treat your string as being in ISO-8859-1 // (the HTTP/1.1 default character set) unless you tell it otherwise. // https://stackoverflow.com/a/8218649 // So encode characters to HTML numeric string references. $content = mb_encode_numericentity($content, [0x80, 0x10FFFF, 0, 0x1FFFFF], 'UTF-8'); // turning off some errors libxml_use_internal_errors(true); if (! $this->dom->loadHTML($content)) { // unclear how we would get here, given that we are trapping libxml errors // @codeCoverageIgnoreStart libxml_clear_errors(); throw new BadMethodCallException('Invalid HTML'); // @codeCoverageIgnoreEnd } // ignore the whitespace. $this->dom->preserveWhiteSpace = false; return $this; } /** * Loads the contents of a file as a string * so that we can work with it. * * @return $this */ public function withFile(string $path) { if (! is_file($path)) { throw new InvalidArgumentException(basename($path) . ' is not a valid file.'); } $content = file_get_contents($path); return $this->withString($content); } /** * Checks to see if the text is found within the result. */ public function see(?string $search = null, ?string $element = null): bool { // If Element is null, we're just scanning for text if ($element === null) { $content = $this->dom->saveHTML($this->dom->documentElement); return mb_strpos($content, $search) !== false; } $result = $this->doXPath($search, $element); return (bool) $result->length; } /** * Checks to see if the text is NOT found within the result. */ public function dontSee(?string $search = null, ?string $element = null): bool { return ! $this->see($search, $element); } /** * Checks to see if an element with the matching CSS specifier * is found within the current DOM. */ public function seeElement(string $element): bool { return $this->see(null, $element); } /** * Checks to see if the element is available within the result. */ public function dontSeeElement(string $element): bool { return $this->dontSee(null, $element); } /** * Determines if a link with the specified text is found * within the results. */ public function seeLink(string $text, ?string $details = null): bool { return $this->see($text, 'a' . $details); } /** * Checks for an input named $field with a value of $value. */ public function seeInField(string $field, string $value): bool { $result = $this->doXPath(null, 'input', ["[@value=\"{$value}\"][@name=\"{$field}\"]"]); return (bool) $result->length; } /** * Checks for checkboxes that are currently checked. */ public function seeCheckboxIsChecked(string $element): bool { $result = $this->doXPath(null, 'input' . $element, [ '[@type="checkbox"]', '[@checked="checked"]', ]); return (bool) $result->length; } /** * Checks to see if the XPath can be found. */ public function seeXPath(string $path): bool { $xpath = new DOMXPath($this->dom); return (bool) $xpath->query($path)->length; } /** * Checks to see if the XPath can't be found. */ public function dontSeeXPath(string $path): bool { return ! $this->seeXPath($path); } /** * Search the DOM using an XPath expression. * * @return DOMNodeList|false */ protected function doXPath(?string $search, string $element, array $paths = []) { // Otherwise, grab any elements that match // the selector $selector = $this->parseSelector($element); $path = ''; // By ID if (isset($selector['id'])) { $path = ($selector['tag'] === '') ? "id(\"{$selector['id']}\")" : "//{$selector['tag']}[@id=\"{$selector['id']}\"]"; } // By Class elseif (isset($selector['class'])) { $path = ($selector['tag'] === '') ? "//*[@class=\"{$selector['class']}\"]" : "//{$selector['tag']}[@class=\"{$selector['class']}\"]"; } // By tag only elseif ($selector['tag'] !== '') { $path = "//{$selector['tag']}"; } if (isset($selector['attr'])) { foreach ($selector['attr'] as $key => $value) { $path .= "[@{$key}=\"{$value}\"]"; } } // $paths might contain a number of different // ready to go xpath portions to tack on. foreach ($paths as $extra) { $path .= $extra; } if ($search !== null) { $path .= "[contains(., \"{$search}\")]"; } $xpath = new DOMXPath($this->dom); return $xpath->query($path); } /** * Look for the a selector in the passed text. * * @return array{tag: string, id: string|null, class: string|null, attr: array<string, string>|null} */ public function parseSelector(string $selector) { $id = null; $class = null; $attr = null; // ID? if (str_contains($selector, '#')) { [$tag, $id] = explode('#', $selector); } // Attribute elseif (str_contains($selector, '[') && str_contains($selector, ']')) { $open = strpos($selector, '['); $close = strpos($selector, ']'); $tag = substr($selector, 0, $open); $text = substr($selector, $open + 1, $close - 2); // We only support a single attribute currently $text = explode(',', $text); $text = trim(array_shift($text)); [$name, $value] = explode('=', $text); $name = trim($name); $value = trim($value); $attr = [$name => trim($value, '] ')]; } // Class? elseif (str_contains($selector, '.')) { [$tag, $class] = explode('.', $selector); } // Otherwise, assume the entire string is our tag else { $tag = $selector; } return [ 'tag' => $tag, 'id' => $id, 'class' => $class, 'attr' => $attr, ]; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/CIUnitTestCase.php
system/Test/CIUnitTestCase.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\Test; use CodeIgniter\CodeIgniter; use CodeIgniter\Config\Factories; use CodeIgniter\Database\BaseConnection; use CodeIgniter\Database\MigrationRunner; use CodeIgniter\Database\Seeder; use CodeIgniter\Events\Events; use CodeIgniter\Router\RouteCollection; use CodeIgniter\Session\Handlers\ArrayHandler; use CodeIgniter\Test\Mock\MockCache; use CodeIgniter\Test\Mock\MockCodeIgniter; use CodeIgniter\Test\Mock\MockEmail; use CodeIgniter\Test\Mock\MockSession; use Config\App; use Config\Autoload; use Config\Email; use Config\Modules; use Config\Services; use Config\Session; use Exception; use PHPUnit\Framework\TestCase; /** * Framework test case for PHPUnit. */ abstract class CIUnitTestCase extends TestCase { use ReflectionHelper; /** * @var CodeIgniter */ protected $app; /** * Methods to run during setUp. * * WARNING: Do not override unless you know exactly what you are doing. * This property may be deprecated in the future. * * @var list<string> array of methods */ protected $setUpMethods = [ 'resetFactories', 'mockCache', 'mockEmail', 'mockSession', ]; /** * Methods to run during tearDown. * * WARNING: This property may be deprecated in the future. * * @var list<string> array of methods */ protected $tearDownMethods = []; /** * Store of identified traits. */ private ?array $traits = null; // -------------------------------------------------------------------- // Database Properties // -------------------------------------------------------------------- /** * Should run db migration? * * @var bool */ protected $migrate = true; /** * Should run db migration only once? * * @var bool */ protected $migrateOnce = false; /** * Should run seeding only once? * * @var bool */ protected $seedOnce = false; /** * Should the db be refreshed before test? * * @var bool */ protected $refresh = true; /** * The seed file(s) used for all tests within this test case. * Should be fully-namespaced or relative to $basePath * * @var class-string<Seeder>|list<class-string<Seeder>> */ protected $seed = ''; /** * The path to the seeds directory. * Allows overriding the default application directories. * * @var string */ protected $basePath = SUPPORTPATH . 'Database'; /** * The namespace(s) to help us find the migration classes. * `null` is equivalent to running `spark migrate --all`. * Note that running "all" runs migrations in date order, * but specifying namespaces runs them in namespace order (then date) * * @var array|string|null */ protected $namespace = 'Tests\Support'; /** * The name of the database group to connect to. * If not present, will use the defaultGroup. * * @var non-empty-string */ protected $DBGroup = 'tests'; /** * Our database connection. * * @var BaseConnection */ protected $db; /** * Migration Runner instance. * * @var MigrationRunner|null */ protected $migrations; /** * Seeder instance * * @var Seeder */ protected $seeder; /** * Stores information needed to remove any * rows inserted via $this->hasInDatabase(); * * @var array */ protected $insertCache = []; // -------------------------------------------------------------------- // Feature Properties // -------------------------------------------------------------------- /** * If present, will override application * routes when using call(). * * @var RouteCollection|null */ protected $routes; /** * Values to be set in the SESSION global * before running the test. * * @var array */ protected $session = []; /** * Enabled auto clean op buffer after request call * * @var bool */ protected $clean = true; /** * Custom request's headers * * @var array */ protected $headers = []; /** * Allows for formatting the request body to what * the controller is going to expect * * @var string */ protected $bodyFormat = ''; /** * Allows for directly setting the body to what * it needs to be. * * @var mixed */ protected $requestBody = ''; // -------------------------------------------------------------------- // Staging // -------------------------------------------------------------------- /** * Load the helpers. */ public static function setUpBeforeClass(): void { parent::setUpBeforeClass(); helper(['url', 'test']); } protected function setUp(): void { parent::setUp(); if (! $this->app instanceof CodeIgniter) { $this->app = $this->createApplication(); } foreach ($this->setUpMethods as $method) { $this->{$method}(); } // Check for the database trait if (method_exists($this, 'setUpDatabase')) { $this->setUpDatabase(); } // Check for other trait methods $this->callTraitMethods('setUp'); } protected function tearDown(): void { parent::tearDown(); foreach ($this->tearDownMethods as $method) { $this->{$method}(); } // Check for the database trait if (method_exists($this, 'tearDownDatabase')) { $this->tearDownDatabase(); } // Check for other trait methods $this->callTraitMethods('tearDown'); } /** * Checks for traits with corresponding * methods for setUp or tearDown. * * @param string $stage 'setUp' or 'tearDown' */ private function callTraitMethods(string $stage): void { if ($this->traits === null) { $this->traits = class_uses_recursive($this); } foreach ($this->traits as $trait) { $method = $stage . class_basename($trait); if (method_exists($this, $method)) { $this->{$method}(); } } } // -------------------------------------------------------------------- // Mocking // -------------------------------------------------------------------- /** * Resets shared instanced for all Factories components * * @return void */ protected function resetFactories() { Factories::reset(); } /** * Resets shared instanced for all Services * * @return void */ protected function resetServices(bool $initAutoloader = true) { Services::reset($initAutoloader); } /** * Injects the mock Cache driver to prevent filesystem collisions * * @return void */ protected function mockCache() { Services::injectMock('cache', new MockCache()); } /** * Injects the mock email driver so no emails really send * * @return void */ protected function mockEmail() { Services::injectMock('email', new MockEmail(config(Email::class))); } /** * Injects the mock session driver into Services * * @return void */ protected function mockSession() { $_SESSION = []; $config = config(Session::class); $session = new MockSession(new ArrayHandler($config, '0.0.0.0'), $config); Services::injectMock('session', $session); } // -------------------------------------------------------------------- // Assertions // -------------------------------------------------------------------- /** * Custom function to hook into CodeIgniter's Logging mechanism * to check if certain messages were logged during code execution. * * @param string|null $expectedMessage * * @return bool */ public function assertLogged(string $level, $expectedMessage = null) { $result = TestLogger::didLog($level, $expectedMessage); $this->assertTrue($result, sprintf( 'Failed asserting that expected message "%s" with level "%s" was logged.', $expectedMessage ?? '', $level, )); return $result; } /** * Asserts that there is a log record that contains `$logMessage` in the message. */ public function assertLogContains(string $level, string $logMessage, string $message = ''): void { $this->assertTrue( TestLogger::didLog($level, $logMessage, false), $message !== '' ? $message : sprintf( 'Failed asserting that logs have a record of message containing "%s" with level "%s".', $logMessage, $level, ), ); } /** * Hooks into CodeIgniter's Events system to check if a specific * event was triggered or not. * * @throws Exception */ public function assertEventTriggered(string $eventName): bool { $found = false; $eventName = strtolower($eventName); foreach (Events::getPerformanceLogs() as $log) { if ($log['event'] !== $eventName) { continue; } $found = true; break; } $this->assertTrue($found); return $found; } /** * Hooks into xdebug's headers capture, looking for presence of * a specific header emitted. * * @param string $header The leading portion of the header we are looking for */ public function assertHeaderEmitted(string $header, bool $ignoreCase = false): void { $this->assertNotNull( $this->getHeaderEmitted($header, $ignoreCase, __METHOD__), "Didn't find header for {$header}", ); } /** * Hooks into xdebug's headers capture, looking for absence of * a specific header emitted. * * @param string $header The leading portion of the header we don't want to find */ public function assertHeaderNotEmitted(string $header, bool $ignoreCase = false): void { $this->assertNull( $this->getHeaderEmitted($header, $ignoreCase, __METHOD__), "Found header for {$header}", ); } /** * Custom function to test that two values are "close enough". * This is intended for extended execution time testing, * where the result is close but not exactly equal to the * expected time, for reasons beyond our control. * * @param float|int $actual * * @return void * * @throws Exception */ public function assertCloseEnough(int $expected, $actual, string $message = '', int $tolerance = 1) { $difference = abs($expected - (int) floor($actual)); $this->assertLessThanOrEqual($tolerance, $difference, $message); } /** * Custom function to test that two values are "close enough". * This is intended for extended execution time testing, * where the result is close but not exactly equal to the * expected time, for reasons beyond our control. * * @param mixed $expected * @param mixed $actual * * @return bool|null * * @throws Exception */ public function assertCloseEnoughString($expected, $actual, string $message = '', int $tolerance = 1) { $expected = (string) $expected; $actual = (string) $actual; if (strlen($expected) !== strlen($actual)) { return false; } try { $expected = (int) substr($expected, -2); $actual = (int) substr($actual, -2); $difference = abs($expected - $actual); $this->assertLessThanOrEqual($tolerance, $difference, $message); } catch (Exception) { return false; } return null; } // -------------------------------------------------------------------- // Utility // -------------------------------------------------------------------- /** * Loads up an instance of CodeIgniter * and gets the environment setup. * * @return CodeIgniter */ protected function createApplication() { // Initialize the autoloader. service('autoloader')->initialize(new Autoload(), new Modules()); $app = new MockCodeIgniter(new App()); $app->initialize(); return $app; } /** * Return first matching emitted header. */ protected function getHeaderEmitted(string $header, bool $ignoreCase = false, string $method = __METHOD__): ?string { if (! function_exists('xdebug_get_headers')) { $this->markTestSkipped($method . '() requires xdebug.'); } foreach (xdebug_get_headers() as $emittedHeader) { $found = $ignoreCase ? (str_starts_with(strtolower($emittedHeader), strtolower($header))) : (str_starts_with($emittedHeader, $header)); if ($found) { return $emittedHeader; } } return null; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/TestResponse.php
system/Test/TestResponse.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\Test; use CodeIgniter\HTTP\RedirectResponse; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\I18n\Time; use PHPUnit\Framework\Assert; use PHPUnit\Framework\Constraint\IsEqual; /** * Consolidated response processing * for test results. * * @mixin DOMParser * * @see \CodeIgniter\Test\TestResponseTest */ class TestResponse { /** * The request. * * @var RequestInterface|null */ protected $request; /** * The response. * * @var ResponseInterface */ protected $response; /** * DOM for the body. * * @var DOMParser */ protected $domParser; /** * Stores or the Response and parses the body in the DOM. */ public function __construct(ResponseInterface $response) { $this->setResponse($response); } // -------------------------------------------------------------------- // Getters / Setters // -------------------------------------------------------------------- /** * Sets the request. * * @return $this */ public function setRequest(RequestInterface $request) { $this->request = $request; return $this; } /** * Sets the Response and updates the DOM. * * @return $this */ public function setResponse(ResponseInterface $response) { $this->response = $response; $this->domParser = new DOMParser(); $body = $response->getBody(); if (is_string($body) && $body !== '') { $this->domParser->withString($body); } return $this; } /** * Request accessor. * * @return RequestInterface|null */ public function request() { return $this->request; } /** * Response accessor. * * @return ResponseInterface */ public function response() { return $this->response; } // -------------------------------------------------------------------- // Status Checks // -------------------------------------------------------------------- /** * Boils down the possible responses into a boolean valid/not-valid * response type. */ public function isOK(): bool { $status = $this->response->getStatusCode(); // Only 200 and 300 range status codes // are considered valid. if ($status >= 400 || $status < 200) { return false; } $body = (string) $this->response->getBody(); // Empty bodies are not considered valid, unless in redirects return ! ($status < 300 && $body === ''); } /** * Asserts that the status is a specific value. */ public function assertStatus(int $code): void { Assert::assertSame($code, $this->response->getStatusCode()); } /** * Asserts that the Response is considered OK. */ public function assertOK(): void { Assert::assertTrue( $this->isOK(), "{$this->response->getStatusCode()} is not a successful status code, or Response has an empty body.", ); } /** * Asserts that the Response is considered not OK. */ public function assertNotOK(): void { Assert::assertFalse( $this->isOK(), "{$this->response->getStatusCode()} is an unexpected successful status code, or Response body has content.", ); } // -------------------------------------------------------------------- // Redirection // -------------------------------------------------------------------- /** * Returns whether or not the Response was a redirect or RedirectResponse */ public function isRedirect(): bool { return $this->response instanceof RedirectResponse || $this->response->hasHeader('Location') || $this->response->hasHeader('Refresh'); } /** * Assert that the given response was a redirect. */ public function assertRedirect(): void { Assert::assertTrue($this->isRedirect(), 'Response is not a redirect or instance of RedirectResponse.'); } /** * Assert that a given response was a redirect * and it was redirect to a specific URI. */ public function assertRedirectTo(string $uri): void { $this->assertRedirect(); $uri = trim(strtolower($uri)); $redirectUri = strtolower($this->getRedirectUrl()); $matches = $uri === $redirectUri || strtolower(site_url($uri)) === $redirectUri || $uri === site_url($redirectUri); Assert::assertTrue($matches, "Redirect URL '{$uri}' does not match '{$redirectUri}'."); } /** * Assert that the given response was not a redirect. */ public function assertNotRedirect(): void { Assert::assertFalse($this->isRedirect(), 'Response is an unexpected redirect or instance of RedirectResponse.'); } /** * Returns the URL set for redirection. */ public function getRedirectUrl(): ?string { if (! $this->isRedirect()) { return null; } if ($this->response->hasHeader('Location')) { return $this->response->getHeaderLine('Location'); } if ($this->response->hasHeader('Refresh')) { return str_replace('0;url=', '', $this->response->getHeaderLine('Refresh')); } return null; } // -------------------------------------------------------------------- // Session // -------------------------------------------------------------------- /** * Asserts that an SESSION key has been set and, optionally, test its value. * * @param mixed $value */ public function assertSessionHas(string $key, $value = null): void { Assert::assertArrayHasKey($key, $_SESSION, "Key '{$key}' is not in the current \$_SESSION"); if ($value === null) { return; } if (is_scalar($value)) { Assert::assertSame($value, $_SESSION[$key], "The value of key '{$key}' ({$value}) does not match expected value."); return; } Assert::assertSame($value, $_SESSION[$key], "The value of key '{$key}' does not match expected value."); } /** * Asserts the session is missing $key. */ public function assertSessionMissing(string $key): void { Assert::assertArrayNotHasKey($key, $_SESSION, "Key '{$key}' should not be present in \$_SESSION."); } // -------------------------------------------------------------------- // Headers // -------------------------------------------------------------------- /** * Asserts that the Response contains a specific header. * * @param string|null $value */ public function assertHeader(string $key, $value = null): void { Assert::assertTrue($this->response->hasHeader($key), "Header '{$key}' is not a valid Response header."); if ($value !== null) { Assert::assertSame( $value, $this->response->getHeaderLine($key), "The value of '{$key}' header ({$this->response->getHeaderLine($key)}) does not match expected value.", ); } } /** * Asserts the Response headers does not contain the specified header. */ public function assertHeaderMissing(string $key): void { Assert::assertFalse($this->response->hasHeader($key), "Header '{$key}' should not be in the Response headers."); } // -------------------------------------------------------------------- // Cookies // -------------------------------------------------------------------- /** * Asserts that the response has the specified cookie. * * @param string|null $value */ public function assertCookie(string $key, $value = null, string $prefix = ''): void { Assert::assertTrue($this->response->hasCookie($key, $value, $prefix), "Cookie named '{$key}' is not found."); } /** * Assert the Response does not have the specified cookie set. */ public function assertCookieMissing(string $key): void { Assert::assertFalse($this->response->hasCookie($key), "Cookie named '{$key}' should not be set."); } /** * Asserts that a cookie exists and has an expired time. */ public function assertCookieExpired(string $key, string $prefix = ''): void { Assert::assertTrue($this->response->hasCookie($key, null, $prefix)); Assert::assertGreaterThan( Time::now()->getTimestamp(), $this->response->getCookie($key, $prefix)->getExpiresTimestamp(), ); } // -------------------------------------------------------------------- // JSON // -------------------------------------------------------------------- /** * Returns the response's body as JSON * * @return false|string */ public function getJSON() { $response = $this->response->getJSON(); if ($response === null) { return false; } return $response; } /** * Test that the response contains a matching JSON fragment. */ public function assertJSONFragment(array $fragment, bool $strict = false): void { $json = json_decode($this->getJSON(), true); Assert::assertIsArray($json, 'Response is not a valid JSON.'); $patched = array_replace_recursive($json, $fragment); if ($strict) { Assert::assertSame($json, $patched, 'Response does not contain a matching JSON fragment.'); return; } Assert::assertThat($patched, new IsEqual($json), 'Response does not contain a matching JSON fragment.'); } /** * Asserts that the JSON exactly matches the passed in data. * If the value being passed in is a string, it must be a json_encoded string. * * @param array|object|string $test */ public function assertJSONExact($test): void { $json = $this->getJSON(); if (is_object($test)) { $test = method_exists($test, 'toArray') ? $test->toArray() : (array) $test; } if (is_array($test)) { $test = service('format')->getFormatter('application/json')->format($test); } Assert::assertJsonStringEqualsJsonString($test, $json, 'Response does not contain matching JSON.'); } // -------------------------------------------------------------------- // XML Methods // -------------------------------------------------------------------- /** * Returns the response' body as XML * * @return bool|string|null */ public function getXML() { return $this->response->getXML(); } // -------------------------------------------------------------------- // DomParser // -------------------------------------------------------------------- /** * Assert that the desired text can be found in the result body. */ public function assertSee(?string $search = null, ?string $element = null): void { Assert::assertTrue( $this->domParser->see($search, $element), "Text '{$search}' is not seen in response.", ); } /** * Asserts that we do not see the specified text. */ public function assertDontSee(?string $search = null, ?string $element = null): void { Assert::assertTrue( $this->domParser->dontSee($search, $element), "Text '{$search}' is unexpectedly seen in response.", ); } /** * Assert that we see an element selected via a CSS selector. */ public function assertSeeElement(string $search): void { Assert::assertTrue( $this->domParser->seeElement($search), "Element with selector '{$search}' is not seen in response.", ); } /** * Assert that we do not see an element selected via a CSS selector. */ public function assertDontSeeElement(string $search): void { Assert::assertTrue( $this->domParser->dontSeeElement($search), "Element with selector '{$search}' is unexpectedly seen in response.'", ); } /** * Assert that we see a link with the matching text and/or class. */ public function assertSeeLink(string $text, ?string $details = null): void { Assert::assertTrue( $this->domParser->seeLink($text, $details), "Anchor tag with text '{$text}' is not seen in response.", ); } /** * Assert that we see an input with name/value. */ public function assertSeeInField(string $field, ?string $value = null): void { Assert::assertTrue( $this->domParser->seeInField($field, $value), "Input named '{$field}' with value '{$value}' is not seen in response.", ); } /** * Forward any unrecognized method calls to our DOMParser instance. * * @param list<mixed> $params */ public function __call(string $function, array $params): mixed { if (method_exists($this->domParser, $function)) { return $this->domParser->{$function}(...$params); } return null; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Interfaces/FabricatorModel.php
system/Test/Interfaces/FabricatorModel.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\Test\Interfaces; use CodeIgniter\BaseModel; use Faker\Generator; use ReflectionException; /** * FabricatorModel * * An interface defining the required methods and properties * needed for a model to qualify for use with the Fabricator class. * While interfaces cannot enforce properties, the following * are required for use with Fabricator: * * @property string $returnType * @property string $primaryKey * @property string $dateFormat * * @phpstan-import-type row_array from BaseModel */ interface FabricatorModel { /** * Fetches the row of database from $this->table with a primary key * matching $id. * * @param int|list<int|string>|string|null $id One primary key or an array of primary keys * * @return ($id is int|string ? object|row_array|null : list<object|row_array>) */ public function find($id = null); /** * Inserts data into the current table. If an object is provided, * it will attempt to convert it to an array. * * @param object|row_array|null $row * @param bool $returnID Whether insert ID should be returned or not. * * @return bool|int|string * * @throws ReflectionException */ public function insert($row = null, bool $returnID = true); /** * The following properties and methods are optional, but if present should * adhere to their definitions. * * @property array $allowedFields * @property string $useSoftDeletes * @property string $useTimestamps * @property string $createdField * @property string $updatedField * @property string $deletedField */ /* * Sets $useSoftDeletes value so that we can temporarily override * the softdeletes settings. Can be used for all find* methods. * * @param bool $val * * @return Model */ // public function withDeleted($val = true); /** * Faked data for Fabricator. * * @param Generator $faker * * @return array|object */ // public function fake(Generator &$faker); }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Constraints/SeeInDatabase.php
system/Test/Constraints/SeeInDatabase.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\Test\Constraints; use CodeIgniter\Database\ConnectionInterface; use PHPUnit\Framework\Constraint\Constraint; class SeeInDatabase extends Constraint { /** * The number of results that will show in the database * in case of failure. * * @var int */ protected $show = 3; /** * @var ConnectionInterface */ protected $db; /** * Data used to compare results against. * * @var array */ protected $data; /** * SeeInDatabase constructor. */ public function __construct(ConnectionInterface $db, array $data) { $this->db = $db; $this->data = $data; } /** * Check if data is found in the table * * @param mixed $table */ protected function matches($table): bool { return $this->db->table($table)->where($this->data)->countAllResults() > 0; } /** * Get the description of the failure * * @param mixed $table */ protected function failureDescription($table): string { return sprintf( "a row in the table [%s] matches the attributes \n%s\n\n%s", $table, $this->toString(false, JSON_PRETTY_PRINT), $this->getAdditionalInfo($table), ); } /** * Gets additional records similar to $data. */ protected function getAdditionalInfo(string $table): string { $builder = $this->db->table($table); $similar = $builder->where( array_key_first($this->data), $this->data[array_key_first($this->data)], )->limit($this->show)->get()->getResultArray(); if ($similar !== []) { $description = 'Found similar results: ' . json_encode($similar, JSON_PRETTY_PRINT); } else { // Does the table have any results at all? $results = $this->db->table($table) ->limit($this->show) ->get() ->getResultArray(); if ($results !== []) { return 'The table is empty.'; } $description = 'Found: ' . json_encode($results, JSON_PRETTY_PRINT); } $total = $this->db->table($table)->countAll(); if ($total > $this->show) { $description .= sprintf(' and %s others', $total - $this->show); } return $description; } /** * Gets a string representation of the constraint * * @param int $options */ public function toString(bool $exportObjects = false, $options = 0): string { return json_encode($this->data, $options); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockIncomingRequest.php
system/Test/Mock/MockIncomingRequest.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\Test\Mock; use CodeIgniter\HTTP\IncomingRequest; class MockIncomingRequest extends IncomingRequest { }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockLogger.php
system/Test/Mock/MockLogger.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\Test\Mock; use CodeIgniter\Log\Handlers\HandlerInterface; use Config\Logger; use Tests\Support\Log\Handlers\TestHandler; class MockLogger extends Logger { /** *-------------------------------------------------------------------------- * Error Logging Threshold *-------------------------------------------------------------------------- * * You can enable error logging by setting a threshold over zero. The * threshold determines what gets logged. Any values below or equal to the * threshold will be logged. Threshold options are: * * 0 = Disables logging, Error logging TURNED OFF * 1 = Emergency Messages - System is unusable * 2 = Alert Messages - Action Must Be Taken Immediately * 3 = Critical Messages - Application component unavailable, unexpected exception. * 4 = Runtime Errors - Don't need immediate action, but should be monitored. * 5 = Warnings - Exceptional occurrences that are not errors. * 6 = Notices - Normal but significant events. * 7 = Info - Interesting events, like user logging in, etc. * 8 = Debug - Detailed debug information. * 9 = All Messages * * You can also pass an array with threshold levels to show individual error types * * array(1, 2, 3, 8) = Emergency, Alert, Critical, and Debug messages * * For a live site you'll usually enable Critical or higher (3) to be logged otherwise * your log files will fill up very fast. * * @var int|list<int> */ public $threshold = 9; /** *-------------------------------------------------------------------------- * Date Format for Logs *-------------------------------------------------------------------------- * * Each item that is logged has an associated date. You can use PHP date * codes to set your own date formatting */ public string $dateFormat = 'Y-m-d'; /** *-------------------------------------------------------------------------- * Log Handlers *-------------------------------------------------------------------------- * * The logging system supports multiple actions to be taken when something * is logged. This is done by allowing for multiple Handlers, special classes * designed to write the log to their chosen destinations, whether that is * a file on the server, a cloud-based service, or even taking actions such * as emailing the dev team. * * Each handler is defined by the class name used for that handler, and it * MUST implement the CodeIgniter\Log\Handlers\HandlerInterface interface. * * The value of each key is an array of configuration items that are sent * to the constructor of each handler. The only required configuration item * is the 'handles' element, which must be an array of integer log levels. * This is most easily handled by using the constants defined in the * Psr\Log\LogLevel class. * * Handlers are executed in the order defined in this array, starting with * the handler on top and continuing down. * * @var array<class-string<HandlerInterface>, array<string, int|list<string>|string>> */ public array $handlers = [ // File Handler TestHandler::class => [ // The log levels that this handler will handle. 'handles' => [ 'critical', 'alert', 'emergency', 'debug', 'error', 'info', 'notice', 'warning', ], // Logging Directory Path 'path' => '', ], ]; }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockResourcePresenter.php
system/Test/Mock/MockResourcePresenter.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\Test\Mock; use CodeIgniter\API\ResponseTrait; use CodeIgniter\RESTful\ResourcePresenter; class MockResourcePresenter extends ResourcePresenter { use ResponseTrait; /** * @return object|null */ public function getModel() { return $this->model; } /** * @return class-string|null */ public function getModelName() { return $this->modelName; } /** * @return 'json'|'xml'|null */ public function getFormat() { return $this->format; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockQuery.php
system/Test/Mock/MockQuery.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\Test\Mock; use CodeIgniter\Database\Query; class MockQuery extends Query { }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockServices.php
system/Test/Mock/MockServices.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\Test\Mock; use CodeIgniter\Autoloader\FileLocator; use CodeIgniter\Config\BaseService; class MockServices extends BaseService { /** * @var array<non-empty-string, non-empty-string> */ public $psr4 = [ 'Tests/Support' => TESTPATH . '_support/', ]; /** * @var array<class-string, string> */ public $classmap = []; public function __construct() { // Don't call the parent since we don't want the default mappings. // parent::__construct(); } public static function locator(bool $getShared = true) { return new FileLocator(static::autoloader()); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockCLIConfig.php
system/Test/Mock/MockCLIConfig.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\Test\Mock; use Config\App; class MockCLIConfig extends App { public string $baseURL = 'http://example.com/'; public string $uriProtocol = 'REQUEST_URI'; public array $proxyIPs = []; public string $CSRFTokenName = 'csrf_test_name'; public string $CSRFCookieName = 'csrf_cookie_name'; public int $CSRFExpire = 7200; public bool $CSRFRegenerate = true; /** * @var list<string> */ public array $CSRFExcludeURIs = ['http://example.com']; public string $CSRFSameSite = 'Lax'; public bool $CSPEnabled = false; public string $defaultLocale = 'en'; public bool $negotiateLocale = false; public array $supportedLocales = [ 'en', 'es', ]; }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockAppConfig.php
system/Test/Mock/MockAppConfig.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\Test\Mock; use Config\App; class MockAppConfig extends App { public string $baseURL = 'http://example.com/'; public string $uriProtocol = 'REQUEST_URI'; public array $proxyIPs = []; public bool $CSPEnabled = false; public string $defaultLocale = 'en'; public bool $negotiateLocale = false; public array $supportedLocales = [ 'en', 'es', ]; }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockAutoload.php
system/Test/Mock/MockAutoload.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\Test\Mock; use Config\Autoload; class MockAutoload extends Autoload { public $psr4 = []; public $classmap = []; public function __construct() { // Don't call the parent since we don't want the default mappings. // parent::__construct(); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockTable.php
system/Test/Mock/MockTable.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\Test\Mock; use CodeIgniter\Exceptions\BadMethodCallException; use CodeIgniter\View\Table; class MockTable extends Table { /** * Override inaccessible protected method * * @param string $method * @param list<mixed> $params * * @return mixed */ public function __call($method, $params) { if (is_callable([$this, '_' . $method])) { return call_user_func_array([$this, '_' . $method], $params); } throw new BadMethodCallException('Method ' . $method . ' was not found'); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockCodeIgniter.php
system/Test/Mock/MockCodeIgniter.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\Test\Mock; use CodeIgniter\CodeIgniter; class MockCodeIgniter extends CodeIgniter { protected ?string $context = 'web'; /** * @param int $code * * @deprecated 4.4.0 No longer Used. Moved to index.php. */ protected function callExit($code) { // Do not call exit() in testing. } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockResourceController.php
system/Test/Mock/MockResourceController.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\Test\Mock; use CodeIgniter\RESTful\ResourceController; class MockResourceController extends ResourceController { /** * @return object|null */ public function getModel() { return $this->model; } /** * @return class-string|null */ public function getModelName() { return $this->modelName; } /** * @return 'json'|'xml'|null */ public function getFormat() { return $this->format; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockConnection.php
system/Test/Mock/MockConnection.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\Test\Mock; use CodeIgniter\CodeIgniter; use CodeIgniter\Database\BaseConnection; use CodeIgniter\Database\BaseResult; use CodeIgniter\Database\Query; use CodeIgniter\Database\TableName; use stdClass; /** * @extends BaseConnection<object|resource, object|resource> */ class MockConnection extends BaseConnection { /** * @var array{ * connect?: false|list<false|object|resource>|object|resource, * execute?: false|object|resource, * } */ protected $returnValues = []; /** * Database schema for Postgre and SQLSRV * * @var string */ protected $schema; /** * @var string */ public $database; /** * @var Query */ public $lastQuery; /** * @param false|list<false|object|resource>|object|resource $return * * @return $this */ public function shouldReturn(string $method, $return) { $this->returnValues[$method] = $return; return $this; } /** * Orchestrates a query against the database. Queries must use * Database\Statement objects to store the query and build it. * This method works with the cache. * * Should automatically handle different connections for read/write * queries if needed. * * @param mixed $binds * * @return BaseResult<object|resource, object|resource>|bool|Query * * @todo BC set $queryClass default as null in 4.1 */ public function query(string $sql, $binds = null, bool $setEscapeFlags = true, string $queryClass = '') { /** @var class-string<Query> $queryClass */ $queryClass = str_replace('Connection', 'Query', static::class); $query = new $queryClass($this); $query->setQuery($sql, $binds, $setEscapeFlags); if ($this->swapPre !== '' && $this->DBPrefix !== '') { $query->swapPrefix($this->DBPrefix, $this->swapPre); } $startTime = microtime(true); $this->lastQuery = $query; $this->resultID = $this->simpleQuery($query->getQuery()); if ($this->resultID === false) { $query->setDuration($startTime, $startTime); // @todo deal with errors return false; } $query->setDuration($startTime); // resultID is not false, so it must be successful if ($query->isWriteType()) { return true; } // query is not write-type, so it must be read-type query; return QueryResult /** @var class-string<BaseResult> $resultClass */ $resultClass = str_replace('Connection', 'Result', static::class); return new $resultClass($this->connID, $this->resultID); } /** * Connect to the database. * * @return false|object|resource */ public function connect(bool $persistent = false) { $return = $this->returnValues['connect'] ?? true; if (is_array($return)) { // By removing the top item here, we can // get a different value for, say, testing failover connections. $return = array_shift($this->returnValues['connect']); } return $return; } /** * Keep or establish the connection if no queries have been sent for * a length of time exceeding the server's idle timeout. */ public function reconnect(): bool { return true; } /** * Select a specific database table to use. * * @return bool */ public function setDatabase(string $databaseName) { $this->database = $databaseName; return true; } /** * Returns a string containing the version of the database being used. */ public function getVersion(): string { return CodeIgniter::CI_VERSION; } /** * Executes the query against the database. * * @return false|object|resource */ protected function execute(string $sql) { return $this->returnValues['execute']; } /** * Returns the total number of rows affected by this query. */ public function affectedRows(): int { return 1; } /** * Returns the last error code and message. * * @return array{code: int, message: string} */ public function error(): array { return [ 'code' => 0, 'message' => '', ]; } public function insertID(): int { return $this->connID->insert_id; } /** * Generates the SQL for listing tables in a platform-dependent manner. * * @param string|null $tableName If $tableName is provided will return only this table if exists. */ protected function _listTables(bool $constrainByPrefix = false, ?string $tableName = null): string { return ''; } /** * Generates a platform-specific query string so that the column names can be fetched. * * @param string|TableName $table */ protected function _listColumns($table = ''): string { return ''; } /** * @return list<stdClass> */ protected function _fieldData(string $table): array { return []; } /** * @return array<string, stdClass> */ protected function _indexData(string $table): array { return []; } /** * @return array<string, stdClass> */ protected function _foreignKeyData(string $table): array { return []; } /** * Close the connection. * * @return void */ protected function _close() { } /** * Begin Transaction */ protected function _transBegin(): bool { return true; } /** * Commit Transaction */ protected function _transCommit(): bool { return true; } /** * Rollback Transaction */ protected function _transRollback(): bool { return true; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockEmail.php
system/Test/Mock/MockEmail.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\Test\Mock; use CodeIgniter\Email\Email; use CodeIgniter\Events\Events; class MockEmail extends Email { /** * Value to return from mocked send(). * * @var bool */ public $returnValue = true; public function send($autoClear = true) { if ($this->returnValue) { $this->setArchiveValues(); if ($autoClear) { $this->clear(); } Events::trigger('email', $this->archive); } return $this->returnValue; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockSession.php
system/Test/Mock/MockSession.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\Test\Mock; use CodeIgniter\Cookie\Cookie; use CodeIgniter\I18n\Time; use CodeIgniter\Session\Session; /** * Class MockSession * * Provides a safe way to test the Session class itself, * that doesn't interact with the session or cookies at all. */ class MockSession extends Session { /** * Holds our "cookie" data. * * @var list<Cookie> */ public array $cookies = []; public bool $didRegenerate = false; /** * Sets the driver as the session handler in PHP. * Extracted for easier testing. * * @return void */ protected function setSaveHandler() { // session_set_save_handler($this->driver, true); } /** * Starts the session. * Extracted for testing reasons. * * @return void */ protected function startSession() { // session_start(); $this->setCookie(); } /** * Takes care of setting the cookie on the client side. * Extracted for testing reasons. * * @return void */ protected function setCookie() { $expiration = $this->config->expiration === 0 ? 0 : Time::now()->getTimestamp() + $this->config->expiration; $this->cookie = $this->cookie->withValue(session_id())->withExpires($expiration); $this->cookies[] = $this->cookie; } /** * Regenerates the session ID. * * @return void */ public function regenerate(bool $destroy = false) { $this->didRegenerate = true; $_SESSION['__ci_last_regenerate'] = Time::now()->getTimestamp(); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockResult.php
system/Test/Mock/MockResult.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\Test\Mock; use CodeIgniter\Database\BaseResult; use stdClass; /** * @extends BaseResult<object|resource, object|resource> */ class MockResult extends BaseResult { /** * Gets the number of fields in the result set. */ public function getFieldCount(): int { return 0; } /** * Generates an array of column names in the result set. * * @return array{} */ public function getFieldNames(): array { return []; } /** * Generates an array of objects representing field meta-data. * * @return array{} */ public function getFieldData(): array { return []; } /** * Frees the current result. * * @return void */ public function freeResult() { } /** * Moves the internal pointer to the desired offset. This is called * internally before fetching results to make sure the result set * starts at zero. * * @param int $n * * @return bool */ public function dataSeek($n = 0) { return true; } /** * Returns the result set as an array. * * Overridden by driver classes. * * @return array{} */ protected function fetchAssoc() { return []; } /** * Returns the result set as an object. * * @param class-string $className * * @return object */ protected function fetchObject($className = stdClass::class) { return new $className(); } /** * Gets the number of fields in the result set. */ public function getNumRows(): int { return 0; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockCache.php
system/Test/Mock/MockCache.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\Test\Mock; use Closure; use CodeIgniter\Cache\CacheInterface; use CodeIgniter\Cache\Handlers\BaseHandler; use CodeIgniter\I18n\Time; use PHPUnit\Framework\Assert; class MockCache extends BaseHandler implements CacheInterface { /** * Mock cache storage. * * @var array<string, mixed> */ protected $cache = []; /** * Expiration times. * * @var array<string, int|null> */ protected $expirations = []; /** * If true, will not cache any data. * * @var bool */ protected $bypass = false; /** * Takes care of any handler-specific setup that must be done. * * @return void */ public function initialize() { } /** * Attempts to fetch an item from the cache store. * * @param string $key Cache item name * * @return bool|null */ public function get(string $key) { $key = static::validateKey($key, $this->prefix); return array_key_exists($key, $this->cache) ? $this->cache[$key] : null; } /** * Get an item from the cache, or execute the given Closure and store the result. * * @return bool|null */ public function remember(string $key, int $ttl, Closure $callback) { $value = $this->get($key); if ($value !== null) { return $value; } $this->save($key, $value = $callback(), $ttl); return $value; } /** * Saves an item to the cache store. * * The $raw parameter is only utilized by Mamcache in order to * allow usage of increment() and decrement(). * * @param string $key Cache item name * @param mixed $value the data to save * @param int $ttl Time To Live, in seconds (default 60) * * @return bool */ public function save(string $key, $value, int $ttl = 60) { if ($this->bypass) { return false; } $key = static::validateKey($key, $this->prefix); $this->cache[$key] = $value; $this->expirations[$key] = $ttl > 0 ? Time::now()->getTimestamp() + $ttl : null; return true; } /** * Deletes a specific item from the cache store. * * @return bool */ public function delete(string $key) { $key = static::validateKey($key, $this->prefix); if (! isset($this->cache[$key])) { return false; } unset($this->cache[$key], $this->expirations[$key]); return true; } /** * Deletes items from the cache store matching a given pattern. * * @return int */ public function deleteMatching(string $pattern) { $count = 0; foreach (array_keys($this->cache) as $key) { if (fnmatch($pattern, $key)) { $count++; unset($this->cache[$key], $this->expirations[$key]); } } return $count; } /** * Performs atomic incrementation of a raw stored value. * * @return bool */ public function increment(string $key, int $offset = 1) { $key = static::validateKey($key, $this->prefix); $data = $this->cache[$key] ?: null; if ($data === null) { $data = 0; } elseif (! is_int($data)) { return false; } return $this->save($key, $data + $offset); } /** * Performs atomic decrementation of a raw stored value. * * @return bool */ public function decrement(string $key, int $offset = 1) { $key = static::validateKey($key, $this->prefix); $data = $this->cache[$key] ?: null; if ($data === null) { $data = 0; } elseif (! is_int($data)) { return false; } return $this->save($key, $data - $offset); } /** * Will delete all items in the entire cache. * * @return bool */ public function clean() { $this->cache = []; $this->expirations = []; return true; } /** * Returns information on the entire cache. * * The information returned and the structure of the data * varies depending on the handler. * * @return list<string> Keys currently present in the store */ public function getCacheInfo() { return array_keys($this->cache); } /** * Returns detailed information about the specific item in the cache. * * @return array{expire: int|null}|null Returns null if the item does not exist, * otherwise, array with the 'expire' key for * absolute epoch expiry (or null). */ public function getMetaData(string $key) { // Misses return null if (! array_key_exists($key, $this->expirations)) { return null; } // Count expired items as a miss if (is_int($this->expirations[$key]) && $this->expirations[$key] > Time::now()->getTimestamp()) { return null; } return ['expire' => $this->expirations[$key]]; } /** * Determine if the driver is supported on this system. */ public function isSupported(): bool { return true; } // -------------------------------------------------------------------- // Test Helpers // -------------------------------------------------------------------- /** * Instructs the class to ignore all * requests to cache an item, and always "miss" * when checked for existing data. * * @return $this */ public function bypass(bool $bypass = true) { $this->clean(); $this->bypass = $bypass; return $this; } // -------------------------------------------------------------------- // Additional Assertions // -------------------------------------------------------------------- /** * Asserts that the cache has an item named $key. * The value is not checked since storing false or null * values is valid. * * @return void */ public function assertHas(string $key) { Assert::assertNotNull($this->get($key), "The cache does not have an item named: `{$key}`"); } /** * Asserts that the cache has an item named $key with a value matching $value. * * @param mixed $value * * @return void */ public function assertHasValue(string $key, $value = null) { $item = $this->get($key); // Let assertHas() handle throwing the error for consistency // if the key is not found if ($item === null) { $this->assertHas($key); } Assert::assertSame($value, $this->get($key), "The cached item `{$key}` does not equal match expectation. Found: " . print_r($value, true)); } /** * Asserts that the cache does NOT have an item named $key. * * @return void */ public function assertMissing(string $key) { Assert::assertArrayNotHasKey($key, $this->cache, "The cached item named `{$key}` exists."); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockCommon.php
system/Test/Mock/MockCommon.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. */ if (! function_exists('is_cli')) { /** * Is CLI? * * Test to see if a request was made from the command line. * You can set the return value for testing. * * @param bool $newReturn return value to set */ function is_cli(?bool $newReturn = null): bool { // PHPUnit always runs via CLI. static $returnValue = true; if ($newReturn !== null) { $returnValue = $newReturn; } return $returnValue; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockInputOutput.php
system/Test/Mock/MockInputOutput.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\Test\Mock; use CodeIgniter\CLI\InputOutput; use CodeIgniter\Exceptions\InvalidArgumentException; use CodeIgniter\Exceptions\LogicException; use CodeIgniter\Test\Filters\CITestStreamFilter; use CodeIgniter\Test\PhpStreamWrapper; final class MockInputOutput extends InputOutput { /** * String to be entered by the user. * * @var list<string> */ private array $inputs = []; /** * Output lines. * * @var list<string> */ private array $outputs = []; /** * Sets user inputs. * * @param list<string> $inputs */ public function setInputs(array $inputs): void { $this->inputs = $inputs; } /** * Gets the item from the output array. * * @param int|null $index The output array index. If null, returns all output * string. If negative int, returns the last $index-th * item. */ public function getOutput(?int $index = null): string { if ($index === null) { return implode('', $this->outputs); } if (array_key_exists($index, $this->outputs)) { return $this->outputs[$index]; } if ($index < 0) { $i = count($this->outputs) + $index; if (array_key_exists($i, $this->outputs)) { return $this->outputs[$i]; } } throw new InvalidArgumentException( 'No such index in output: ' . $index . ', the last index is: ' . (count($this->outputs) - 1), ); } /** * Returns the outputs array. * * @return list<string> */ public function getOutputs(): array { return $this->outputs; } private function addStreamFilters(): void { CITestStreamFilter::registration(); CITestStreamFilter::addOutputFilter(); CITestStreamFilter::addErrorFilter(); } private function removeStreamFilters(): void { CITestStreamFilter::removeOutputFilter(); CITestStreamFilter::removeErrorFilter(); } public function input(?string $prefix = null): string { if ($this->inputs === []) { throw new LogicException( 'No input data. Specifiy input data with `MockInputOutput::setInputs()`.', ); } $input = array_shift($this->inputs); $this->addStreamFilters(); PhpStreamWrapper::register(); PhpStreamWrapper::setContent($input); $userInput = parent::input($prefix); $this->outputs[] = CITestStreamFilter::$buffer . $input . PHP_EOL; PhpStreamWrapper::restore(); $this->removeStreamFilters(); if ($input !== $userInput) { throw new LogicException($input . '!==' . $userInput); } return $input; } public function fwrite($handle, string $string): void { $this->addStreamFilters(); parent::fwrite($handle, $string); $this->outputs[] = CITestStreamFilter::$buffer; $this->removeStreamFilters(); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockResponse.php
system/Test/Mock/MockResponse.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\Test\Mock; use CodeIgniter\HTTP\Response; class MockResponse extends Response { /** * If true, will not write output. Useful during testing. * * @var bool */ protected $pretend = true; /** * For testing. * * @return bool */ public function getPretend() { return $this->pretend; } /** * Artificial error for testing * * @return void */ public function misbehave() { $this->statusCode = 0; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockLanguage.php
system/Test/Mock/MockLanguage.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\Test\Mock; use CodeIgniter\Language\Language; class MockLanguage extends Language { /** * Stores the data that should be * returned by the 'requireFile()' method. * * @var mixed */ protected $data; /** * Sets the data that should be returned by the * 'requireFile()' method to allow easy overrides * during testing. * * @return $this */ public function setData(string $file, array $data, ?string $locale = null) { $this->language[$locale ?? $this->locale][$file] = $data; return $this; } /** * Provides an override that allows us to set custom * data to be returned easily during testing. */ protected function requireFile(string $path): array { return $this->data ?? []; } /** * Arbitrarily turnoff internationalization support for testing * * @return void */ public function disableIntlSupport() { $this->intlSupport = false; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockCURLRequest.php
system/Test/Mock/MockCURLRequest.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\Test\Mock; use CodeIgniter\HTTP\CURLRequest; use CodeIgniter\HTTP\URI; /** * Simply allows us to not actually call cURL during the * test runs. Instead, we can set the desired output * and get back the set options. */ class MockCURLRequest extends CURLRequest { /** * @var array<int, mixed> */ public $curl_options; /** * @var string */ protected $output = ''; /** * @param string $output * * @return $this */ public function setOutput($output) { $this->output = $output; return $this; } /** * @param array<int, mixed> $curlOptions */ protected function sendRequest(array $curlOptions = []): string { $this->response = clone $this->responseOrig; $this->curl_options = $curlOptions; return $this->output; } /** * for testing purposes only * * @return URI */ public function getBaseURI() { return $this->baseURI; } /** * for testing purposes only * * @return float */ public function getDelay() { return $this->delay; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockFileLogger.php
system/Test/Mock/MockFileLogger.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\Test\Mock; use CodeIgniter\Log\Handlers\FileHandler; /** * Extends FileHandler, exposing some inner workings */ class MockFileLogger extends FileHandler { /** * Where would the log be written? * * @var string */ public $destination; /** * @param array{handles?: list<string>, path?: string, fileExtension?: string, filePermissions?: int} $config */ public function __construct(array $config) { parent::__construct($config); $this->destination = $this->path . 'log-' . date('Y-m-d') . '.' . $this->fileExtension; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockBuilder.php
system/Test/Mock/MockBuilder.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\Test\Mock; use CodeIgniter\Database\BaseBuilder; class MockBuilder extends BaseBuilder { /** * @var array<string, string> */ protected $supportedIgnoreStatements = [ 'update' => 'IGNORE', 'insert' => 'IGNORE', 'delete' => 'IGNORE', ]; }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockSecurity.php
system/Test/Mock/MockSecurity.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\Test\Mock; use CodeIgniter\Security\Security; class MockSecurity extends Security { protected function doSendCookie(): void { $_COOKIE['csrf_cookie_name'] = $this->hash; } protected function randomize(string $hash): string { $keyBinary = hex2bin('005513c290126d34d41bf41c5265e0f1'); $hashBinary = hex2bin($hash); return bin2hex(($hashBinary ^ $keyBinary) . $keyBinary); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Mock/MockEvents.php
system/Test/Mock/MockEvents.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\Test\Mock; use CodeIgniter\Events\Events; class MockEvents extends Events { /** * @return array<string, array{0: bool, 1: list<int>, 2: list<callable(mixed): mixed>}> */ public function getListeners() { return self::$listeners; } /** * @return list<string> */ public function getEventsFile() { return self::$files; } /** * @return bool */ public function getSimulate() { return self::$simulate; } /** * @return void */ public function unInitialize() { static::$initialized = false; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Test/Filters/CITestStreamFilter.php
system/Test/Filters/CITestStreamFilter.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\Test\Filters; use php_user_filter; /** * Used to capture output during unit testing, so that it can * be used in assertions. */ class CITestStreamFilter extends php_user_filter { /** * Buffer to capture stream content. * * @var string */ public static $buffer = ''; protected static bool $registered = false; /** * @var resource|null */ private static $err; /** * @var resource|null */ private static $out; /** * This method is called whenever data is read from or written to the * attached stream (such as with fread() or fwrite()). * * @param resource $in * @param resource $out * @param int $consumed * @param bool $closing * * @param-out int $consumed */ public function filter($in, $out, &$consumed, $closing): int { while ($bucket = stream_bucket_make_writeable($in)) { static::$buffer .= $bucket->data; $consumed += (int) $bucket->datalen; } return PSFS_PASS_ON; } public static function registration(): void { if (! static::$registered) { static::$registered = stream_filter_register('CITestStreamFilter', self::class); // @codeCoverageIgnore } static::$buffer = ''; } public static function addErrorFilter(): void { self::removeFilter(self::$err); self::$err = stream_filter_append(STDERR, 'CITestStreamFilter'); } public static function addOutputFilter(): void { self::removeFilter(self::$out); self::$out = stream_filter_append(STDOUT, 'CITestStreamFilter'); } public static function removeErrorFilter(): void { self::removeFilter(self::$err); } public static function removeOutputFilter(): void { self::removeFilter(self::$out); } /** * @param resource|null $stream * * @param-out null $stream */ protected static function removeFilter(&$stream): void { if ($stream !== null) { stream_filter_remove($stream); $stream = null; } } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Encryption/Encryption.php
system/Encryption/Encryption.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\Encryption; use CodeIgniter\Encryption\Exceptions\EncryptionException; use Config\Encryption as EncryptionConfig; /** * CodeIgniter Encryption Manager * * Provides two-way keyed encryption via PHP's Sodium and/or OpenSSL extensions. * This class determines the driver, cipher, and mode to use, and then * initializes the appropriate encryption handler. * * @property-read string $digest * @property-read string $driver * @property-read list<string> $drivers * @property-read string $key * * @see \CodeIgniter\Encryption\EncryptionTest */ class Encryption { /** * The encrypter we create * * @var EncrypterInterface */ protected $encrypter; /** * The driver being used * * @var string */ protected $driver; /** * The key/seed being used * * @var string */ protected $key; /** * The derived HMAC key * * @var string */ protected $hmacKey; /** * HMAC digest to use * * @var string */ protected $digest = 'SHA512'; /** * Map of drivers to handler classes, in preference order * * @var array */ protected $drivers = [ 'OpenSSL', 'Sodium', ]; /** * Handlers that are to be installed * * @var array<string, bool> */ protected $handlers = []; /** * @throws EncryptionException */ public function __construct(?EncryptionConfig $config = null) { $config ??= new EncryptionConfig(); $this->key = $config->key; $this->driver = $config->driver; $this->digest = $config->digest ?? 'SHA512'; $this->handlers = [ 'OpenSSL' => extension_loaded('openssl'), // the SodiumHandler uses some API (like sodium_pad) that is available only on v1.0.14+ 'Sodium' => extension_loaded('sodium') && version_compare(SODIUM_LIBRARY_VERSION, '1.0.14', '>='), ]; if (! in_array($this->driver, $this->drivers, true) || (array_key_exists($this->driver, $this->handlers) && ! $this->handlers[$this->driver])) { throw EncryptionException::forNoHandlerAvailable($this->driver); } } /** * Initialize or re-initialize an encrypter * * @return EncrypterInterface * * @throws EncryptionException */ public function initialize(?EncryptionConfig $config = null) { if ($config instanceof EncryptionConfig) { $this->key = $config->key; $this->driver = $config->driver; $this->digest = $config->digest ?? 'SHA512'; } if (empty($this->driver)) { throw EncryptionException::forNoDriverRequested(); } if (! in_array($this->driver, $this->drivers, true)) { throw EncryptionException::forUnKnownHandler($this->driver); } if (empty($this->key)) { throw EncryptionException::forNeedsStarterKey(); } $this->hmacKey = bin2hex(\hash_hkdf($this->digest, $this->key)); $handlerName = 'CodeIgniter\\Encryption\\Handlers\\' . $this->driver . 'Handler'; $this->encrypter = new $handlerName($config); return $this->encrypter; } /** * Create a random key * * @param int $length Output length * * @return string */ public static function createKey($length = 32) { return random_bytes($length); } /** * __get() magic, providing readonly access to some of our protected properties * * @param string $key Property name * * @return array|string|null */ public function __get($key) { if ($this->__isset($key)) { return $this->{$key}; } return null; } /** * __isset() magic, providing checking for some of our protected properties * * @param string $key Property name */ public function __isset($key): bool { return in_array($key, ['key', 'digest', 'driver', 'drivers'], true); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Encryption/EncrypterInterface.php
system/Encryption/EncrypterInterface.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\Encryption; use CodeIgniter\Encryption\Exceptions\EncryptionException; /** * CodeIgniter Encryption Handler * * Provides two-way keyed encryption */ interface EncrypterInterface { /** * Encrypt - convert plaintext into ciphertext * * @param string $data Input data * @param array|string|null $params Overridden parameters, specifically the key * * @return string * * @throws EncryptionException */ public function encrypt($data, $params = null); /** * Decrypt - convert ciphertext into plaintext * * @param string $data Encrypted data * @param array|string|null $params Overridden parameters, specifically the key * * @return string * * @throws EncryptionException */ public function decrypt($data, $params = null); }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Encryption/Exceptions/EncryptionException.php
system/Encryption/Exceptions/EncryptionException.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\Encryption\Exceptions; use CodeIgniter\Exceptions\DebugTraceableTrait; use CodeIgniter\Exceptions\RuntimeException; /** * Encryption exception */ class EncryptionException extends RuntimeException { use DebugTraceableTrait; /** * Thrown when no driver is present in the active encryption session. * * @return static */ public static function forNoDriverRequested() { return new static(lang('Encryption.noDriverRequested')); } /** * Thrown when the handler requested is not available. * * @return static */ public static function forNoHandlerAvailable(string $handler) { return new static(lang('Encryption.noHandlerAvailable', [$handler])); } /** * Thrown when the handler requested is unknown. * * @return static */ public static function forUnKnownHandler(?string $driver = null) { return new static(lang('Encryption.unKnownHandler', [$driver])); } /** * Thrown when no starter key is provided for the current encryption session. * * @return static */ public static function forNeedsStarterKey() { return new static(lang('Encryption.starterKeyNeeded')); } /** * Thrown during data decryption when a problem or error occurred. * * @return static */ public static function forAuthenticationFailed() { return new static(lang('Encryption.authenticationFailed')); } /** * Thrown during data encryption when a problem or error occurred. * * @return static */ public static function forEncryptionFailed() { return new static(lang('Encryption.encryptionFailed')); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Encryption/Handlers/OpenSSLHandler.php
system/Encryption/Handlers/OpenSSLHandler.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\Encryption\Handlers; use CodeIgniter\Encryption\Exceptions\EncryptionException; /** * Encryption handling for OpenSSL library * * @see \CodeIgniter\Encryption\Handlers\OpenSSLHandlerTest */ class OpenSSLHandler extends BaseHandler { /** * HMAC digest to use * * @var string */ protected $digest = 'SHA512'; /** * List of supported HMAC algorithms * * @var array [name => digest size] */ protected array $digestSize = [ 'SHA224' => 28, 'SHA256' => 32, 'SHA384' => 48, 'SHA512' => 64, ]; /** * Cipher to use * * @var string */ protected $cipher = 'AES-256-CTR'; /** * Starter key * * @var string */ protected $key = ''; /** * Whether the cipher-text should be raw. If set to false, then it will be base64 encoded. */ protected bool $rawData = true; /** * Encryption key info. * This setting is only used by OpenSSLHandler. * * Set to 'encryption' for CI3 Encryption compatibility. */ public string $encryptKeyInfo = ''; /** * Authentication key info. * This setting is only used by OpenSSLHandler. * * Set to 'authentication' for CI3 Encryption compatibility. */ public string $authKeyInfo = ''; /** * {@inheritDoc} */ public function encrypt($data, $params = null) { // Allow key override if ($params !== null) { $this->key = is_array($params) && isset($params['key']) ? $params['key'] : $params; } if (empty($this->key)) { throw EncryptionException::forNeedsStarterKey(); } // derive a secret key $encryptKey = \hash_hkdf($this->digest, $this->key, 0, $this->encryptKeyInfo); // basic encryption $iv = ($ivSize = \openssl_cipher_iv_length($this->cipher)) ? \openssl_random_pseudo_bytes($ivSize) : null; $data = \openssl_encrypt($data, $this->cipher, $encryptKey, OPENSSL_RAW_DATA, $iv); if ($data === false) { throw EncryptionException::forEncryptionFailed(); } $result = $this->rawData ? $iv . $data : base64_encode($iv . $data); // derive a secret key $authKey = \hash_hkdf($this->digest, $this->key, 0, $this->authKeyInfo); $hmacKey = \hash_hmac($this->digest, $result, $authKey, $this->rawData); return $hmacKey . $result; } /** * {@inheritDoc} */ public function decrypt($data, $params = null) { // Allow key override if ($params !== null) { $this->key = is_array($params) && isset($params['key']) ? $params['key'] : $params; } if (empty($this->key)) { throw EncryptionException::forNeedsStarterKey(); } // derive a secret key $authKey = \hash_hkdf($this->digest, $this->key, 0, $this->authKeyInfo); $hmacLength = $this->rawData ? $this->digestSize[$this->digest] : $this->digestSize[$this->digest] * 2; $hmacKey = self::substr($data, 0, $hmacLength); $data = self::substr($data, $hmacLength); $hmacCalc = \hash_hmac($this->digest, $data, $authKey, $this->rawData); if (! hash_equals($hmacKey, $hmacCalc)) { throw EncryptionException::forAuthenticationFailed(); } $data = $this->rawData ? $data : base64_decode($data, true); if ($ivSize = \openssl_cipher_iv_length($this->cipher)) { $iv = self::substr($data, 0, $ivSize); $data = self::substr($data, $ivSize); } else { $iv = null; } // derive a secret key $encryptKey = \hash_hkdf($this->digest, $this->key, 0, $this->encryptKeyInfo); return \openssl_decrypt($data, $this->cipher, $encryptKey, OPENSSL_RAW_DATA, $iv); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Encryption/Handlers/SodiumHandler.php
system/Encryption/Handlers/SodiumHandler.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\Encryption\Handlers; use CodeIgniter\Encryption\Exceptions\EncryptionException; /** * SodiumHandler uses libsodium in encryption. * * @see https://github.com/jedisct1/libsodium/issues/392 * @see \CodeIgniter\Encryption\Handlers\SodiumHandlerTest */ class SodiumHandler extends BaseHandler { /** * Starter key * * @var string|null Null is used for buffer cleanup. */ protected $key = ''; /** * Block size for padding message. * * @var int */ protected $blockSize = 16; /** * {@inheritDoc} */ public function encrypt($data, $params = null) { $this->parseParams($params); if (empty($this->key)) { throw EncryptionException::forNeedsStarterKey(); } // create a nonce for this operation $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); // 24 bytes // add padding before we encrypt the data if ($this->blockSize <= 0) { throw EncryptionException::forEncryptionFailed(); } $data = sodium_pad($data, $this->blockSize); // encrypt message and combine with nonce $ciphertext = $nonce . sodium_crypto_secretbox($data, $nonce, $this->key); // cleanup buffers sodium_memzero($data); sodium_memzero($this->key); return $ciphertext; } /** * {@inheritDoc} */ public function decrypt($data, $params = null) { $this->parseParams($params); if (empty($this->key)) { throw EncryptionException::forNeedsStarterKey(); } if (mb_strlen($data, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES)) { // message was truncated throw EncryptionException::forAuthenticationFailed(); } // Extract info from encrypted data $nonce = self::substr($data, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); $ciphertext = self::substr($data, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); // decrypt data $data = sodium_crypto_secretbox_open($ciphertext, $nonce, $this->key); if ($data === false) { // message was tampered in transit throw EncryptionException::forAuthenticationFailed(); // @codeCoverageIgnore } // remove extra padding during encryption if ($this->blockSize <= 0) { throw EncryptionException::forAuthenticationFailed(); } $data = sodium_unpad($data, $this->blockSize); // cleanup buffers sodium_memzero($ciphertext); sodium_memzero($this->key); return $data; } /** * Parse the $params before doing assignment. * * @param array|string|null $params * * @return void * * @throws EncryptionException If key is empty */ protected function parseParams($params) { if ($params === null) { return; } if (is_array($params)) { if (isset($params['key'])) { $this->key = $params['key']; } if (isset($params['blockSize'])) { $this->blockSize = $params['blockSize']; } return; } $this->key = (string) $params; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Encryption/Handlers/BaseHandler.php
system/Encryption/Handlers/BaseHandler.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\Encryption\Handlers; use CodeIgniter\Encryption\EncrypterInterface; use Config\Encryption; /** * Base class for encryption handling */ abstract class BaseHandler implements EncrypterInterface { /** * Constructor */ public function __construct(?Encryption $config = null) { $config ??= config(Encryption::class); // make the parameters conveniently accessible foreach (get_object_vars($config) as $key => $value) { if (property_exists($this, $key)) { $this->{$key} = $value; } } } /** * Byte-safe substr() * * @param string $str * @param int $start * @param int $length * * @return string */ protected static function substr($str, $start, $length = null) { return mb_substr($str, $start, $length, '8bit'); } /** * __get() magic, providing readonly access to some of our properties * * @param string $key Property name * * @return array|bool|int|string|null */ public function __get($key) { if ($this->__isset($key)) { return $this->{$key}; } return null; } /** * __isset() magic, providing checking for some of our properties * * @param string $key Property name */ public function __isset($key): bool { return property_exists($this, $key); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Format/XMLFormatter.php
system/Format/XMLFormatter.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\Format; use CodeIgniter\Format\Exceptions\FormatException; use Config\Format; use SimpleXMLElement; /** * XML data formatter * * @see \CodeIgniter\Format\XMLFormatterTest */ class XMLFormatter implements FormatterInterface { /** * Takes the given data and formats it. * * @param array<array-key, mixed>|object|string $data * * @return false|non-empty-string */ public function format($data) { $config = new Format(); // SimpleXML is installed but default // but best to check, and then provide a fallback. if (! extension_loaded('simplexml')) { throw FormatException::forMissingExtension(); // @codeCoverageIgnore } $options = $config->formatterOptions['application/xml'] ?? 0; $output = new SimpleXMLElement('<?xml version="1.0"?><response></response>', $options); $this->arrayToXML((array) $data, $output); return $output->asXML(); } /** * A recursive method to convert an array into a valid XML string. * * Written by CodexWorld. Received permission by email on Nov 24, 2016 to use this code. * * @see http://www.codexworld.com/convert-array-to-xml-in-php/ * * @param array<array-key, mixed> $data * @param SimpleXMLElement $output * * @return void */ protected function arrayToXML(array $data, &$output) { foreach ($data as $key => $value) { $key = $this->normalizeXMLTag($key); if (is_array($value)) { $subnode = $output->addChild("{$key}"); $this->arrayToXML($value, $subnode); } else { $output->addChild("{$key}", htmlspecialchars("{$value}")); } } } /** * Normalizes tags into the allowed by W3C. * Regex adopted from this StackOverflow answer. * * @param int|string $key * * @return string * * @see https://stackoverflow.com/questions/60001029/invalid-characters-in-xml-tag-name */ protected function normalizeXMLTag($key) { $startChar = 'A-Z_a-z' . '\\x{C0}-\\x{D6}\\x{D8}-\\x{F6}\\x{F8}-\\x{2FF}\\x{370}-\\x{37D}' . '\\x{37F}-\\x{1FFF}\\x{200C}-\\x{200D}\\x{2070}-\\x{218F}' . '\\x{2C00}-\\x{2FEF}\\x{3001}-\\x{D7FF}\\x{F900}-\\x{FDCF}' . '\\x{FDF0}-\\x{FFFD}\\x{10000}-\\x{EFFFF}'; $validName = $startChar . '\\.\\d\\x{B7}\\x{300}-\\x{36F}\\x{203F}-\\x{2040}'; $key = (string) $key; $key = trim($key); $key = preg_replace("/[^{$validName}-]+/u", '', $key); $key = preg_replace("/^[^{$startChar}]+/u", 'item$0', $key); return preg_replace('/^(xml).*/iu', 'item$0', $key); // XML is a reserved starting word } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Format/Format.php
system/Format/Format.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\Format; use CodeIgniter\Format\Exceptions\FormatException; use Config\Format as FormatConfig; /** * The Format class is a convenient place to create Formatters. * * @see \CodeIgniter\Format\FormatTest */ class Format { public function __construct(protected FormatConfig $config) { } /** * Returns the current configuration instance. * * @return FormatConfig */ public function getConfig() { return $this->config; } /** * A Factory method to return the appropriate formatter for the given mime type. * * @throws FormatException */ public function getFormatter(string $mime): FormatterInterface { if (! array_key_exists($mime, $this->config->formatters)) { throw FormatException::forInvalidMime($mime); } $className = $this->config->formatters[$mime]; if (! class_exists($className)) { throw FormatException::forInvalidFormatter($className); } $class = new $className(); if (! $class instanceof FormatterInterface) { throw FormatException::forInvalidFormatter($className); } return $class; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Format/JSONFormatter.php
system/Format/JSONFormatter.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\Format; use CodeIgniter\Format\Exceptions\FormatException; use Config\Format; /** * JSON data formatter * * @see \CodeIgniter\Format\JSONFormatterTest */ class JSONFormatter implements FormatterInterface { /** * Takes the given data and formats it. * * @param array<array-key, mixed>|object|string $data * * @return false|non-empty-string */ public function format($data) { $config = new Format(); $options = $config->formatterOptions['application/json'] ?? JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES; $options |= JSON_PARTIAL_OUTPUT_ON_ERROR; if (ENVIRONMENT !== 'production') { $options |= JSON_PRETTY_PRINT; } $result = json_encode($data, $options, 512); if (! in_array(json_last_error(), [JSON_ERROR_NONE, JSON_ERROR_RECURSION], true)) { throw FormatException::forInvalidJSON(json_last_error_msg()); } return $result; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Format/FormatterInterface.php
system/Format/FormatterInterface.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\Format; /** * Formatter interface */ interface FormatterInterface { /** * Takes the given data and formats it. * * @param array<array-key, mixed>|object|string $data * * @return false|non-empty-string */ public function format($data); }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Format/Exceptions/FormatException.php
system/Format/Exceptions/FormatException.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\Format\Exceptions; use CodeIgniter\Exceptions\DebugTraceableTrait; use CodeIgniter\Exceptions\RuntimeException; /** * FormatException */ class FormatException extends RuntimeException { use DebugTraceableTrait; /** * Thrown when the instantiated class does not exist. * * @return static */ public static function forInvalidFormatter(string $class) { return new static(lang('Format.invalidFormatter', [$class])); } /** * Thrown in JSONFormatter when the json_encode produces * an error code other than JSON_ERROR_NONE and JSON_ERROR_RECURSION. * * @param string|null $error The error message * * @return static */ public static function forInvalidJSON(?string $error = null) { return new static(lang('Format.invalidJSON', [$error])); } /** * Thrown when the supplied MIME type has no * defined Formatter class. * * @return static */ public static function forInvalidMime(string $mime) { return new static(lang('Format.invalidMime', [$mime])); } /** * Thrown on XMLFormatter when the `simplexml` extension * is not installed. * * @return static * * @codeCoverageIgnore */ public static function forMissingExtension() { return new static(lang('Format.missingExtension')); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HotReloader/IteratorFilter.php
system/HotReloader/IteratorFilter.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\HotReloader; use Config\Toolbar; use RecursiveFilterIterator; use RecursiveIterator; /** * @internal * * @psalm-suppress MissingTemplateParam */ final class IteratorFilter extends RecursiveFilterIterator implements RecursiveIterator { private array $watchedExtensions = []; public function __construct(RecursiveIterator $iterator) { parent::__construct($iterator); $this->watchedExtensions = config(Toolbar::class)->watchedExtensions; } /** * Apply filters to the files in the iterator. */ public function accept(): bool { if (! $this->current()->isFile()) { return true; } $filename = $this->current()->getFilename(); // Skip hidden files and directories. if ($filename[0] === '.') { return false; } // Only consume files of interest. $ext = trim(strtolower($this->current()->getExtension()), '. '); return in_array($ext, $this->watchedExtensions, true); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HotReloader/HotReloader.php
system/HotReloader/HotReloader.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\HotReloader; /** * @internal */ final class HotReloader { public function run(): void { if (session_status() === PHP_SESSION_ACTIVE) { session_write_close(); } ini_set('zlib.output_compression', 'Off'); header('Cache-Control: no-store'); header('Content-Type: text/event-stream'); header('Access-Control-Allow-Methods: GET'); ob_end_clean(); set_time_limit(0); $hasher = new DirectoryHasher(); $appHash = $hasher->hash(); while (true) { if (connection_status() !== CONNECTION_NORMAL || connection_aborted() === 1) { break; } $currentHash = $hasher->hash(); // If hash has changed, tell the browser to reload. if ($currentHash !== $appHash) { $appHash = $currentHash; $this->sendEvent('reload', ['time' => date('Y-m-d H:i:s')]); break; } if (mt_rand(1, 10) > 8) { $this->sendEvent('ping', ['time' => date('Y-m-d H:i:s')]); } sleep(1); } } /** * Send an event to the browser. */ private function sendEvent(string $event, array $data): void { echo "event: {$event}\n"; echo 'data: ' . json_encode($data) . "\n\n"; ob_flush(); flush(); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HotReloader/DirectoryHasher.php
system/HotReloader/DirectoryHasher.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\HotReloader; use CodeIgniter\Exceptions\FrameworkException; use Config\Toolbar; use FilesystemIterator; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; /** * @internal * @see \CodeIgniter\HotReloader\DirectoryHasherTest */ final class DirectoryHasher { /** * Generates an md5 value of all directories that are watched by the * Hot Reloader, as defined in the Config\Toolbar. * * This is the current app fingerprint. */ public function hash(): string { return md5(implode('', $this->hashApp())); } /** * Generates an array of md5 hashes for all directories that are * watched by the Hot Reloader, as defined in the Config\Toolbar. */ public function hashApp(): array { $hashes = []; $watchedDirectories = config(Toolbar::class)->watchedDirectories; foreach ($watchedDirectories as $directory) { if (is_dir(ROOTPATH . $directory)) { $hashes[$directory] = $this->hashDirectory(ROOTPATH . $directory); } } return array_unique(array_filter($hashes)); } /** * Generates an md5 hash of a given directory and all of its files * that match the watched extensions defined in Config\Toolbar. */ public function hashDirectory(string $path): string { if (! is_dir($path)) { throw FrameworkException::forInvalidDirectory($path); } $directory = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS); $filter = new IteratorFilter($directory); $iterator = new RecursiveIteratorIterator($filter); $hashes = []; foreach ($iterator as $file) { if ($file->isFile()) { $hashes[] = md5_file($file->getRealPath()); } } return md5(implode('', $hashes)); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Images/ImageHandlerInterface.php
system/Images/ImageHandlerInterface.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\Images; /** * Expected behavior of an Image handler */ interface ImageHandlerInterface { /** * Resize the image * * @param bool $maintainRatio If true, will get the closest match possible while keeping aspect ratio true. * * @return $this */ public function resize(int $width, int $height, bool $maintainRatio = false, string $masterDim = 'auto'); /** * Crops the image to the desired height and width. If one of the height/width values * is not provided, that value will be set the appropriate value based on offsets and * image dimensions. * * @param int|null $x X-axis coord to start cropping from the left of image * @param int|null $y Y-axis coord to start cropping from the top of image * * @return $this */ public function crop(?int $width = null, ?int $height = null, ?int $x = null, ?int $y = null, bool $maintainRatio = false, string $masterDim = 'auto'); /** * Changes the stored image type to indicate the new file format to use when saving. * Does not touch the actual resource. * * @param int $imageType A PHP imagetype constant, e.g. https://www.php.net/manual/en/function.image-type-to-mime-type.php * * @return $this */ public function convert(int $imageType); /** * Rotates the image on the current canvas. * * @return $this */ public function rotate(float $angle); /** * Flattens transparencies, default white background * * @return $this */ public function flatten(int $red = 255, int $green = 255, int $blue = 255); /** * Reads the EXIF information from the image and modifies the orientation * so that displays correctly in the browser. * * @return ImageHandlerInterface */ public function reorient(); /** * Retrieve the EXIF information from the image, if possible. Returns * an array of the information, or null if nothing can be found. * * @param string|null $key If specified, will only return this piece of EXIF data. * * @return mixed */ public function getEXIF(?string $key = null); /** * Flip an image horizontally or vertically * * @param string $dir Direction to flip, either 'vertical' or 'horizontal' * * @return $this */ public function flip(string $dir = 'vertical'); /** * Combine cropping and resizing into a single command. * * Supported positions: * - top-left * - top * - top-right * - left * - center * - right * - bottom-left * - bottom * - bottom-right * * @return $this */ public function fit(int $width, int $height, string $position); /** * Overlays a string of text over the image. * * Valid options: * * - color Text Color (hex number) * - shadowColor Color of the shadow (hex number) * - hAlign Horizontal alignment: left, center, right * - vAlign Vertical alignment: top, middle, bottom * * @param array{ * color?: string, * shadowColor?: string, * hAlign?: string, * vAlign?: string, * hOffset?: int, * vOffset?: int, * fontPath?: string, * fontSize?: int, * shadowOffset?: int, * opacity?: float, * padding?: int, * withShadow?: bool|string * } $options * * @return $this */ public function text(string $text, array $options = []); /** * Saves any changes that have been made to file. * * Example: * $image->resize(100, 200, true) * ->save($target); * * @param non-empty-string|null $target The path to save the file to. * * @return bool */ public function save(?string $target = null, int $quality = 90); }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Images/Image.php
system/Images/Image.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\Images; use CodeIgniter\Files\File; use CodeIgniter\Images\Exceptions\ImageException; /** * Encapsulation of an Image file * * @see \CodeIgniter\Images\ImageTest */ class Image extends File { /** * The original image width in pixels. * * @var float|int */ public $origWidth; /** * The original image height in pixels. * * @var float|int */ public $origHeight; /** * The image type constant. * * @see http://php.net/manual/en/image.constants.php * * @var int */ public $imageType; /** * attributes string with size info: * 'height="100" width="200"' * * @var string */ public $sizeStr; /** * The image's mime type, i.e. image/jpeg * * @var string */ public $mime; /** * Makes a copy of itself to the new location. If no filename is provided * it will use the existing filename. * * @param string $targetPath The directory to store the file in * @param string|null $targetName The new name of the copied file. * @param int $perms File permissions to be applied after copy. */ public function copy(string $targetPath, ?string $targetName = null, int $perms = 0644): bool { $targetPath = rtrim($targetPath, '/ ') . '/'; $targetName ??= $this->getFilename(); if (empty($targetName)) { throw ImageException::forInvalidFile($targetName); } if (! is_dir($targetPath)) { mkdir($targetPath, 0755, true); } if (! copy($this->getPathname(), "{$targetPath}{$targetName}")) { throw ImageException::forCopyError($targetPath); } chmod("{$targetPath}/{$targetName}", $perms); return true; } /** * Get image properties * * A helper function that gets info about the file * * @return array|bool */ public function getProperties(bool $return = false) { $path = $this->getPathname(); $vals = getimagesize($path); if ($vals === false) { throw ImageException::forFileNotSupported(); } $types = [ IMAGETYPE_GIF => 'gif', IMAGETYPE_JPEG => 'jpeg', IMAGETYPE_PNG => 'png', IMAGETYPE_WEBP => 'webp', ]; $mime = 'image/' . ($types[$vals[2]] ?? 'jpg'); if ($return) { return [ 'width' => $vals[0], 'height' => $vals[1], 'image_type' => $vals[2], 'size_str' => $vals[3], 'mime_type' => $mime, ]; } $this->origWidth = $vals[0]; $this->origHeight = $vals[1]; $this->imageType = $vals[2]; $this->sizeStr = $vals[3]; $this->mime = $mime; return true; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Images/Exceptions/ImageException.php
system/Images/Exceptions/ImageException.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\Images\Exceptions; use CodeIgniter\Exceptions\FrameworkException; class ImageException extends FrameworkException { /** * Thrown when the image is not found. * * @return static */ public static function forMissingImage() { return new static(lang('Images.sourceImageRequired')); } /** * Thrown when the file specific is not following the role. * * @return static */ public static function forFileNotSupported() { return new static(lang('Images.fileNotSupported')); } /** * Thrown when the angle is undefined. * * @return static */ public static function forMissingAngle() { return new static(lang('Images.rotationAngleRequired')); } /** * Thrown when the direction property is invalid. * * @return static */ public static function forInvalidDirection(?string $dir = null) { return new static(lang('Images.invalidDirection', [$dir])); } /** * Thrown when the path property is invalid. * * @return static */ public static function forInvalidPath() { return new static(lang('Images.invalidPath')); } /** * Thrown when the EXIF function is not supported. * * @return static */ public static function forEXIFUnsupported() { return new static(lang('Images.exifNotSupported')); } /** * Thrown when the image specific is invalid. * * @return static */ public static function forInvalidImageCreate(?string $extra = null) { return new static(lang('Images.unsupportedImageCreate') . ' ' . $extra); } /** * Thrown when the image save failed. * * @return static */ public static function forSaveFailed() { return new static(lang('Images.saveFailed')); } /** * Thrown when the image library path is invalid. * * @return static */ public static function forInvalidImageLibraryPath(?string $path = null) { return new static(lang('Images.libPathInvalid', [$path])); } /** * Thrown when the image process failed. * * @return static */ public static function forImageProcessFailed() { return new static(lang('Images.imageProcessFailed')); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Images/Handlers/ImageMagickHandler.php
system/Images/Handlers/ImageMagickHandler.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\Images\Handlers; use CodeIgniter\I18n\Time; use CodeIgniter\Images\Exceptions\ImageException; use Config\Images; use Exception; use Imagick; /** * Class ImageMagickHandler * * FIXME - This needs conversion & unit testing, to use the imagick extension */ class ImageMagickHandler extends BaseHandler { /** * Stores image resource in memory. * * @var string|null */ protected $resource; /** * @param Images $config * * @throws ImageException */ public function __construct($config = null) { parent::__construct($config); if (! extension_loaded('imagick') && ! class_exists(Imagick::class)) { throw ImageException::forMissingExtension('IMAGICK'); // @codeCoverageIgnore } $cmd = $this->config->libraryPath; if ($cmd === '') { throw ImageException::forInvalidImageLibraryPath($cmd); } if (preg_match('/convert$/i', $cmd) !== 1) { $cmd = rtrim($cmd, '\/') . '/convert'; $this->config->libraryPath = $cmd; } if (! is_file($cmd)) { throw ImageException::forInvalidImageLibraryPath($cmd); } } /** * Handles the actual resizing of the image. * * @return ImageMagickHandler * * @throws Exception */ public function _resize(bool $maintainRatio = false) { $source = ! empty($this->resource) ? $this->resource : $this->image()->getPathname(); $destination = $this->getResourcePath(); $escape = '\\'; if (PHP_OS_FAMILY === 'Windows') { $escape = ''; } $action = $maintainRatio ? ' -resize ' . ($this->width ?? 0) . 'x' . ($this->height ?? 0) . ' ' . escapeshellarg($source) . ' ' . escapeshellarg($destination) : ' -resize ' . ($this->width ?? 0) . 'x' . ($this->height ?? 0) . "{$escape}! " . escapeshellarg($source) . ' ' . escapeshellarg($destination); $this->process($action); return $this; } /** * Crops the image. * * @return bool|ImageMagickHandler * * @throws Exception */ public function _crop() { $source = ! empty($this->resource) ? $this->resource : $this->image()->getPathname(); $destination = $this->getResourcePath(); $extent = ' '; if ($this->xAxis >= $this->width || $this->yAxis > $this->height) { $extent = ' -background transparent -extent ' . ($this->width ?? 0) . 'x' . ($this->height ?? 0) . ' '; } $action = ' -crop ' . ($this->width ?? 0) . 'x' . ($this->height ?? 0) . '+' . ($this->xAxis ?? 0) . '+' . ($this->yAxis ?? 0) . $extent . escapeshellarg($source) . ' ' . escapeshellarg($destination); $this->process($action); return $this; } /** * Handles the rotation of an image resource. * Doesn't save the image, but replaces the current resource. * * @return $this * * @throws Exception */ protected function _rotate(int $angle) { $angle = '-rotate ' . $angle; $source = ! empty($this->resource) ? $this->resource : $this->image()->getPathname(); $destination = $this->getResourcePath(); $action = ' ' . $angle . ' ' . escapeshellarg($source) . ' ' . escapeshellarg($destination); $this->process($action); return $this; } /** * Flattens transparencies, default white background * * @return $this * * @throws Exception */ protected function _flatten(int $red = 255, int $green = 255, int $blue = 255) { $flatten = "-background 'rgb({$red},{$green},{$blue})' -flatten"; $source = ! empty($this->resource) ? $this->resource : $this->image()->getPathname(); $destination = $this->getResourcePath(); $action = ' ' . $flatten . ' ' . escapeshellarg($source) . ' ' . escapeshellarg($destination); $this->process($action); return $this; } /** * Flips an image along it's vertical or horizontal axis. * * @return $this * * @throws Exception */ protected function _flip(string $direction) { $angle = $direction === 'horizontal' ? '-flop' : '-flip'; $source = ! empty($this->resource) ? $this->resource : $this->image()->getPathname(); $destination = $this->getResourcePath(); $action = ' ' . $angle . ' ' . escapeshellarg($source) . ' ' . escapeshellarg($destination); $this->process($action); return $this; } /** * Get driver version */ public function getVersion(): string { $versionString = $this->process('-version')[0]; preg_match('/ImageMagick\s(?P<version>[\S]+)/', $versionString, $matches); return $matches['version']; } /** * Handles all of the grunt work of resizing, etc. * * @return array Lines of output from shell command * * @throws Exception */ protected function process(string $action, int $quality = 100): array { if ($action !== '-version') { $this->supportedFormatCheck(); } $cmd = $this->config->libraryPath; $cmd .= $action === '-version' ? ' ' . $action : ' -quality ' . $quality . ' ' . $action; $retval = 1; $output = []; // exec() might be disabled if (function_usable('exec')) { @exec($cmd, $output, $retval); } // Did it work? if ($retval > 0) { throw ImageException::forImageProcessFailed(); } return $output; } /** * Saves any changes that have been made to file. If no new filename is * provided, the existing image is overwritten, otherwise a copy of the * file is made at $target. * * Example: * $image->resize(100, 200, true) * ->save(); * * @param non-empty-string|null $target */ public function save(?string $target = null, int $quality = 90): bool { $original = $target; $target = ($target === null || $target === '') ? $this->image()->getPathname() : $target; // If no new resource has been created, then we're // simply copy the existing one. if (empty($this->resource) && $quality === 100) { if ($original === null) { return true; } $name = basename($target); $path = pathinfo($target, PATHINFO_DIRNAME); return $this->image()->copy($path, $name); } $this->ensureResource(); // Copy the file through ImageMagick so that it has // a chance to convert file format. $action = escapeshellarg($this->resource) . ' ' . escapeshellarg($target); $this->process($action, $quality); unlink($this->resource); return true; } /** * Get Image Resource * * This simply creates an image resource handle * based on the type of image being processed. * Since ImageMagick is used on the cli, we need to * ensure we have a temporary file on the server * that we can use. * * To ensure we can use all features, like transparency, * during the process, we'll use a PNG as the temp file type. * * @return string * * @throws Exception */ protected function getResourcePath() { if ($this->resource !== null) { return $this->resource; } $this->resource = WRITEPATH . 'cache/' . Time::now()->getTimestamp() . '_' . bin2hex(random_bytes(10)) . '.png'; $name = basename($this->resource); $path = pathinfo($this->resource, PATHINFO_DIRNAME); $this->image()->copy($path, $name); return $this->resource; } /** * Make the image resource object if needed * * @return void * * @throws Exception */ protected function ensureResource() { $this->getResourcePath(); $this->supportedFormatCheck(); } /** * Check if given image format is supported * * @return void * * @throws ImageException */ protected function supportedFormatCheck() { switch ($this->image()->imageType) { case IMAGETYPE_WEBP: if (! in_array('WEBP', Imagick::queryFormats(), true)) { throw ImageException::forInvalidImageCreate(lang('images.webpNotSupported')); } break; } } /** * Handler-specific method for overlaying text on an image. * * @throws Exception */ protected function _text(string $text, array $options = []) { $xAxis = 0; $yAxis = 0; $gravity = ''; $cmd = ''; // Reverse the vertical offset // When the image is positioned at the bottom // we don't want the vertical offset to push it // further down. We want the reverse, so we'll // invert the offset. Note: The horizontal // offset flips itself automatically if ($options['vAlign'] === 'bottom') { $options['vOffset'] *= -1; } if ($options['hAlign'] === 'right') { $options['hOffset'] *= -1; } // Font if (! empty($options['fontPath'])) { $cmd .= ' -font ' . escapeshellarg($options['fontPath']); } if (isset($options['hAlign'], $options['vAlign'])) { switch ($options['hAlign']) { case 'left': $xAxis = $options['hOffset'] + $options['padding']; $yAxis = $options['vOffset'] + $options['padding']; $gravity = $options['vAlign'] === 'top' ? 'NorthWest' : 'West'; if ($options['vAlign'] === 'bottom') { $gravity = 'SouthWest'; $yAxis = $options['vOffset'] - $options['padding']; } break; case 'center': $xAxis = $options['hOffset'] + $options['padding']; $yAxis = $options['vOffset'] + $options['padding']; $gravity = $options['vAlign'] === 'top' ? 'North' : 'Center'; if ($options['vAlign'] === 'bottom') { $yAxis = $options['vOffset'] - $options['padding']; $gravity = 'South'; } break; case 'right': $xAxis = $options['hOffset'] - $options['padding']; $yAxis = $options['vOffset'] + $options['padding']; $gravity = $options['vAlign'] === 'top' ? 'NorthEast' : 'East'; if ($options['vAlign'] === 'bottom') { $gravity = 'SouthEast'; $yAxis = $options['vOffset'] - $options['padding']; } break; } $xAxis = $xAxis >= 0 ? '+' . $xAxis : $xAxis; $yAxis = $yAxis >= 0 ? '+' . $yAxis : $yAxis; $cmd .= ' -gravity ' . escapeshellarg($gravity) . ' -geometry ' . escapeshellarg("{$xAxis}{$yAxis}"); } // Color if (isset($options['color'])) { [$r, $g, $b] = sscanf("#{$options['color']}", '#%02x%02x%02x'); $cmd .= ' -fill ' . escapeshellarg("rgba({$r},{$g},{$b},{$options['opacity']})"); } // Font Size - use points.... if (isset($options['fontSize'])) { $cmd .= ' -pointsize ' . escapeshellarg((string) $options['fontSize']); } // Text $cmd .= ' -annotate 0 ' . escapeshellarg($text); $source = ! empty($this->resource) ? $this->resource : $this->image()->getPathname(); $destination = $this->getResourcePath(); $cmd = ' ' . escapeshellarg($source) . ' ' . $cmd . ' ' . escapeshellarg($destination); $this->process($cmd); } /** * Return the width of an image. * * @return int */ public function _getWidth() { return imagesx(imagecreatefromstring(file_get_contents($this->resource))); } /** * Return the height of an image. * * @return int */ public function _getHeight() { return imagesy(imagecreatefromstring(file_get_contents($this->resource))); } /** * Reads the EXIF information from the image and modifies the orientation * so that displays correctly in the browser. This is especially an issue * with images taken by smartphones who always store the image up-right, * but set the orientation flag to display it correctly. * * @param bool $silent If true, will ignore exceptions when PHP doesn't support EXIF. * * @return $this */ public function reorient(bool $silent = false) { $orientation = $this->getEXIF('Orientation', $silent); return match ($orientation) { 2 => $this->flip('horizontal'), 3 => $this->rotate(180), 4 => $this->rotate(180)->flip('horizontal'), 5 => $this->rotate(90)->flip('horizontal'), 6 => $this->rotate(90), 7 => $this->rotate(270)->flip('horizontal'), 8 => $this->rotate(270), default => $this, }; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Images/Handlers/GDHandler.php
system/Images/Handlers/GDHandler.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\Images\Handlers; use CodeIgniter\Images\Exceptions\ImageException; use Config\Images; /** * Image handler for GD package */ class GDHandler extends BaseHandler { /** * Constructor. * * @param Images|null $config * * @throws ImageException */ public function __construct($config = null) { parent::__construct($config); if (! extension_loaded('gd')) { throw ImageException::forMissingExtension('GD'); // @codeCoverageIgnore } } /** * Handles the rotation of an image resource. * Doesn't save the image, but replaces the current resource. */ protected function _rotate(int $angle): bool { // Create the image handle $srcImg = $this->createImage(); // Set the background color // This won't work with transparent PNG files so we are // going to have to figure out how to determine the color // of the alpha channel in a future release. $white = imagecolorallocate($srcImg, 255, 255, 255); // Rotate it! $destImg = imagerotate($srcImg, $angle, $white); // Kill the file handles imagedestroy($srcImg); $this->resource = $destImg; return true; } /** * Flattens transparencies * * @return $this */ protected function _flatten(int $red = 255, int $green = 255, int $blue = 255) { $srcImg = $this->createImage(); if (function_exists('imagecreatetruecolor')) { $create = 'imagecreatetruecolor'; $copy = 'imagecopyresampled'; } else { $create = 'imagecreate'; $copy = 'imagecopyresized'; } $dest = $create($this->width, $this->height); $matte = imagecolorallocate($dest, $red, $green, $blue); imagefilledrectangle($dest, 0, 0, $this->width, $this->height, $matte); imagecopy($dest, $srcImg, 0, 0, 0, 0, $this->width, $this->height); // Kill the file handles imagedestroy($srcImg); $this->resource = $dest; return $this; } /** * Flips an image along it's vertical or horizontal axis. * * @return $this */ protected function _flip(string $direction) { $srcImg = $this->createImage(); $angle = $direction === 'horizontal' ? IMG_FLIP_HORIZONTAL : IMG_FLIP_VERTICAL; imageflip($srcImg, $angle); $this->resource = $srcImg; return $this; } /** * Get GD version * * @return mixed */ public function getVersion() { if (function_exists('gd_info')) { $gdVersion = @gd_info(); return preg_replace('/\D/', '', $gdVersion['GD Version']); } return false; } /** * Resizes the image. * * @return GDHandler */ public function _resize(bool $maintainRatio = false) { return $this->process('resize'); } /** * Crops the image. * * @return GDHandler */ public function _crop() { return $this->process('crop'); } /** * Handles all of the grunt work of resizing, etc. * * @return $this */ protected function process(string $action) { $origWidth = $this->image()->origWidth; $origHeight = $this->image()->origHeight; if ($action === 'crop') { // Reassign the source width/height if cropping $origWidth = $this->width; $origHeight = $this->height; // Modify the "original" width/height to the new // values so that methods that come after have the // correct size to work with. $this->image()->origHeight = $this->height; $this->image()->origWidth = $this->width; } // Create the image handle $src = $this->createImage(); if (function_exists('imagecreatetruecolor')) { $create = 'imagecreatetruecolor'; $copy = 'imagecopyresampled'; } else { $create = 'imagecreate'; $copy = 'imagecopyresized'; } $dest = $create($this->width, $this->height); // for png and webp we can actually preserve transparency if (in_array($this->image()->imageType, $this->supportTransparency, true)) { imagealphablending($dest, false); imagesavealpha($dest, true); } $copy($dest, $src, 0, 0, (int) $this->xAxis, (int) $this->yAxis, $this->width, $this->height, $origWidth, $origHeight); imagedestroy($src); $this->resource = $dest; return $this; } /** * Saves any changes that have been made to file. If no new filename is * provided, the existing image is overwritten, otherwise a copy of the * file is made at $target. * * Example: * $image->resize(100, 200, true) * ->save(); * * @param non-empty-string|null $target */ public function save(?string $target = null, int $quality = 90): bool { $original = $target; $target = ($target === null || $target === '') ? $this->image()->getPathname() : $target; // If no new resource has been created, then we're // simply copy the existing one. if (empty($this->resource) && $quality === 100) { if ($original === null) { return true; } $name = basename($target); $path = pathinfo($target, PATHINFO_DIRNAME); return $this->image()->copy($path, $name); } $this->ensureResource(); // for png and webp we can actually preserve transparency if (in_array($this->image()->imageType, $this->supportTransparency, true)) { imagepalettetotruecolor($this->resource); imagealphablending($this->resource, false); imagesavealpha($this->resource, true); } switch ($this->image()->imageType) { case IMAGETYPE_GIF: if (! function_exists('imagegif')) { throw ImageException::forInvalidImageCreate(lang('Images.gifNotSupported')); } if (! @imagegif($this->resource, $target)) { throw ImageException::forSaveFailed(); } break; case IMAGETYPE_JPEG: if (! function_exists('imagejpeg')) { throw ImageException::forInvalidImageCreate(lang('Images.jpgNotSupported')); } if (! @imagejpeg($this->resource, $target, $quality)) { throw ImageException::forSaveFailed(); } break; case IMAGETYPE_PNG: if (! function_exists('imagepng')) { throw ImageException::forInvalidImageCreate(lang('Images.pngNotSupported')); } if (! @imagepng($this->resource, $target)) { throw ImageException::forSaveFailed(); } break; case IMAGETYPE_WEBP: if (! function_exists('imagewebp')) { throw ImageException::forInvalidImageCreate(lang('Images.webpNotSupported')); } if (! @imagewebp($this->resource, $target, $quality)) { throw ImageException::forSaveFailed(); } break; default: throw ImageException::forInvalidImageCreate(); } imagedestroy($this->resource); chmod($target, $this->filePermissions); return true; } /** * Create Image Resource * * This simply creates an image resource handle * based on the type of image being processed * * @return bool|resource */ protected function createImage(string $path = '', string $imageType = '') { if ($this->resource !== null) { return $this->resource; } if ($path === '') { $path = $this->image()->getPathname(); } if ($imageType === '') { $imageType = $this->image()->imageType; } return $this->getImageResource($path, $imageType); } /** * Make the image resource object if needed */ protected function ensureResource() { if ($this->resource === null) { // if valid image type, make corresponding image resource $this->resource = $this->getImageResource( $this->image()->getPathname(), $this->image()->imageType, ); } } /** * Check if image type is supported and return image resource * * @param string $path Image path * @param int $imageType Image type * * @return bool|resource * * @throws ImageException */ protected function getImageResource(string $path, int $imageType) { switch ($imageType) { case IMAGETYPE_GIF: if (! function_exists('imagecreatefromgif')) { throw ImageException::forInvalidImageCreate(lang('Images.gifNotSupported')); } return imagecreatefromgif($path); case IMAGETYPE_JPEG: if (! function_exists('imagecreatefromjpeg')) { throw ImageException::forInvalidImageCreate(lang('Images.jpgNotSupported')); } return imagecreatefromjpeg($path); case IMAGETYPE_PNG: if (! function_exists('imagecreatefrompng')) { throw ImageException::forInvalidImageCreate(lang('Images.pngNotSupported')); } return @imagecreatefrompng($path); case IMAGETYPE_WEBP: if (! function_exists('imagecreatefromwebp')) { throw ImageException::forInvalidImageCreate(lang('Images.webpNotSupported')); } return imagecreatefromwebp($path); default: throw ImageException::forInvalidImageCreate('Ima'); } } /** * Add text overlay to an image. */ protected function _text(string $text, array $options = []) { // Reverse the vertical offset // When the image is positioned at the bottom // we don't want the vertical offset to push it // further down. We want the reverse, so we'll // invert the offset. Note: The horizontal // offset flips itself automatically if ($options['vAlign'] === 'bottom') { $options['vOffset'] *= -1; } if ($options['hAlign'] === 'right') { $options['hOffset'] *= -1; } // Set font width and height // These are calculated differently depending on // whether we are using the true type font or not if (! empty($options['fontPath'])) { if (function_exists('imagettfbbox')) { $temp = imagettfbbox($options['fontSize'], 0, $options['fontPath'], $text); $temp = $temp[2] - $temp[0]; $fontwidth = $temp / strlen($text); } else { $fontwidth = $options['fontSize'] - ($options['fontSize'] / 4); } $fontheight = $options['fontSize']; } else { $fontwidth = imagefontwidth($options['fontSize']); $fontheight = imagefontheight($options['fontSize']); } $options['fontheight'] = $fontheight; $options['fontwidth'] = $fontwidth; // Set base X and Y axis values $xAxis = $options['hOffset'] + $options['padding']; $yAxis = $options['vOffset'] + $options['padding']; // Set vertical alignment if ($options['vAlign'] === 'middle') { // Don't apply padding when you're in the middle of the image. $yAxis += ($this->image()->origHeight / 2) + ($fontheight / 2) - $options['padding'] - $fontheight - $options['shadowOffset']; } elseif ($options['vAlign'] === 'bottom') { $yAxis = ($this->image()->origHeight - $fontheight - $options['shadowOffset'] - ($fontheight / 2)) - $yAxis; } // Set horizontal alignment if ($options['hAlign'] === 'right') { $xAxis += ($this->image()->origWidth - ($fontwidth * strlen($text)) - $options['shadowOffset']) - (2 * $options['padding']); } elseif ($options['hAlign'] === 'center') { $xAxis += floor(($this->image()->origWidth - ($fontwidth * strlen($text))) / 2); } $options['xAxis'] = $xAxis; $options['yAxis'] = $yAxis; if ($options['withShadow']) { // Offset from text $options['xShadow'] = $xAxis + $options['shadowOffset']; $options['yShadow'] = $yAxis + $options['shadowOffset']; $this->textOverlay($text, $options, true); } $this->textOverlay($text, $options); } /** * Handler-specific method for overlaying text on an image. * * @param bool $isShadow Whether we are drawing the dropshadow or actual text */ protected function textOverlay(string $text, array $options = [], bool $isShadow = false) { $src = $this->createImage(); /* Set RGB values for shadow * * Get the rest of the string and split it into 2-length * hex values: */ $opacity = (int) ($options['opacity'] * 127); // Allow opacity to be applied to the text imagealphablending($src, true); $color = $isShadow ? $options['shadowColor'] : $options['color']; // shorthand hex, #f00 if (strlen($color) === 3) { $color = implode('', array_map(str_repeat(...), str_split($color), [2, 2, 2])); } $color = str_split(substr($color, 0, 6), 2); $color = imagecolorclosestalpha($src, hexdec($color[0]), hexdec($color[1]), hexdec($color[2]), $opacity); $xAxis = $isShadow ? $options['xShadow'] : $options['xAxis']; $yAxis = $isShadow ? $options['yShadow'] : $options['yAxis']; // Add the shadow to the source image if (! empty($options['fontPath'])) { // We have to add fontheight because imagettftext locates the bottom left corner, not top-left corner. imagettftext($src, $options['fontSize'], 0, (int) $xAxis, (int) ($yAxis + $options['fontheight']), $color, $options['fontPath'], $text); } else { imagestring($src, (int) $options['fontSize'], (int) $xAxis, (int) $yAxis, $text, $color); } $this->resource = $src; } /** * Return image width. * * @return int */ public function _getWidth() { return imagesx($this->resource); } /** * Return image height. * * @return int */ public function _getHeight() { return imagesy($this->resource); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Images/Handlers/BaseHandler.php
system/Images/Handlers/BaseHandler.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\Images\Handlers; use CodeIgniter\Exceptions\InvalidArgumentException; use CodeIgniter\Images\Exceptions\ImageException; use CodeIgniter\Images\Image; use CodeIgniter\Images\ImageHandlerInterface; use Config\Images; /** * Base image handling implementation */ abstract class BaseHandler implements ImageHandlerInterface { /** * Configuration settings. * * @var Images */ protected $config; /** * The image/file instance * * @var Image|null */ protected $image; /** * Whether the image file has been confirmed. * * @var bool */ protected $verified = false; /** * Image width. * * @var int */ protected $width = 0; /** * Image height. * * @var int */ protected $height = 0; /** * File permission mask. * * @var int */ protected $filePermissions = 0644; /** * X-axis. * * @var int|null */ protected $xAxis = 0; /** * Y-axis. * * @var int|null */ protected $yAxis = 0; /** * Master dimensioning. * * @var string */ protected $masterDim = 'auto'; /** * Default options for text watermarking. * * @var array */ protected $textDefaults = [ 'fontPath' => null, 'fontSize' => 16, 'color' => 'ffffff', 'opacity' => 1.0, 'vAlign' => 'bottom', 'hAlign' => 'center', 'vOffset' => 0, 'hOffset' => 0, 'padding' => 0, 'withShadow' => false, 'shadowColor' => '000000', 'shadowOffset' => 3, ]; /** * Image types with support for transparency. * * @var array */ protected $supportTransparency = [ IMAGETYPE_PNG, IMAGETYPE_WEBP, ]; /** * Temporary image used by the different engines. * * @var resource|null */ protected $resource; /** * Constructor. * * @param Images|null $config */ public function __construct($config = null) { $this->config = $config ?? new Images(); } /** * Sets another image for this handler to work on. * Keeps us from needing to continually instantiate the handler. * * @phpstan-assert Image $this->image * * @return $this */ public function withFile(string $path) { // Clear out the old resource so that // it doesn't try to use a previous image $this->resource = null; $this->verified = false; $this->image = new Image($path, true); $this->image->getProperties(false); $this->width = $this->image->origWidth; $this->height = $this->image->origHeight; return $this; } /** * Make the image resource object if needed * * @return void */ abstract protected function ensureResource(); /** * Returns the image instance. * * @return Image */ public function getFile() { return $this->image; } /** * Verifies that a file has been supplied and it is an image. * * @phpstan-assert Image $this->image * * @throws ImageException */ protected function image(): Image { if ($this->verified) { return $this->image; } // Verify withFile has been called if ($this->image === null) { throw ImageException::forMissingImage(); } // Verify the loaded image is an Image instance if (! $this->image instanceof Image) { throw ImageException::forInvalidPath(); } // File::__construct has verified the file exists - make sure it is an image if (! is_int($this->image->imageType)) { throw ImageException::forFileNotSupported(); } // Note that the image has been verified $this->verified = true; return $this->image; } /** * Returns the temporary image used during the image processing. * Good for extending the system or doing things this library * is not intended to do. * * @return resource */ public function getResource() { $this->ensureResource(); return $this->resource; } /** * Load the temporary image used during the image processing. * Some functions e.g. save() will only copy and not compress * your image otherwise. * * @return $this */ public function withResource() { $this->ensureResource(); return $this; } /** * Resize the image * * @param bool $maintainRatio If true, will get the closest match possible while keeping aspect ratio true. * * @return BaseHandler */ public function resize(int $width, int $height, bool $maintainRatio = false, string $masterDim = 'auto') { // If the target width/height match the source, then we have nothing to do here. if ($this->image()->origWidth === $width && $this->image()->origHeight === $height) { return $this; } $this->width = $width; $this->height = $height; if ($maintainRatio) { $this->masterDim = $masterDim; $this->reproportion(); } return $this->_resize($maintainRatio); } /** * Crops the image to the desired height and width. If one of the height/width values * is not provided, that value will be set the appropriate value based on offsets and * image dimensions. * * @param int|null $x X-axis coord to start cropping from the left of image * @param int|null $y Y-axis coord to start cropping from the top of image * * @return $this */ public function crop(?int $width = null, ?int $height = null, ?int $x = null, ?int $y = null, bool $maintainRatio = false, string $masterDim = 'auto') { $this->width = $width; $this->height = $height; $this->xAxis = $x; $this->yAxis = $y; if ($maintainRatio) { $this->masterDim = $masterDim; $this->reproportion(); } $result = $this->_crop(); $this->xAxis = null; $this->yAxis = null; return $result; } /** * Changes the stored image type to indicate the new file format to use when saving. * Does not touch the actual resource. * * @param int $imageType A PHP imageType constant, e.g. https://www.php.net/manual/en/function.image-type-to-mime-type.php * * @return $this */ public function convert(int $imageType) { $this->ensureResource(); $this->image()->imageType = $imageType; return $this; } /** * Rotates the image on the current canvas. * * @return $this */ public function rotate(float $angle) { // Allowed rotation values $degs = [ 90.0, 180.0, 270.0, ]; if (! in_array($angle, $degs, true)) { throw ImageException::forMissingAngle(); } // cast angle as an int, for our use $angle = (int) $angle; // Reassign the width and height if ($angle === 90 || $angle === 270) { $temp = $this->height; $this->width = $this->height; $this->height = $temp; } // Call the Handler-specific version. $this->_rotate($angle); return $this; } /** * Flattens transparencies, default white background * * @return $this */ public function flatten(int $red = 255, int $green = 255, int $blue = 255) { $this->width = $this->image()->origWidth; $this->height = $this->image()->origHeight; return $this->_flatten($red, $green, $blue); } /** * Handler-specific method to flattening an image's transparencies. * * @return $this * * @internal */ abstract protected function _flatten(int $red = 255, int $green = 255, int $blue = 255); /** * Handler-specific method to handle rotating an image in 90 degree increments. * * @return mixed */ abstract protected function _rotate(int $angle); /** * Flips an image either horizontally or vertically. * * @param string $dir Either 'vertical' or 'horizontal' * * @return $this */ public function flip(string $dir = 'vertical') { $dir = strtolower($dir); if ($dir !== 'vertical' && $dir !== 'horizontal') { throw ImageException::forInvalidDirection($dir); } return $this->_flip($dir); } /** * Handler-specific method to handle flipping an image along its * horizontal or vertical axis. * * @return $this */ abstract protected function _flip(string $direction); public function text(string $text, array $options = []) { $options = array_merge($this->textDefaults, $options); $options['color'] = trim($options['color'], '# '); $options['shadowColor'] = trim($options['shadowColor'], '# '); $this->_text($text, $options); return $this; } /** * Handler-specific method for overlaying text on an image. * * @param array{ * color?: string, * shadowColor?: string, * hAlign?: string, * vAlign?: string, * hOffset?: int, * vOffset?: int, * fontPath?: string, * fontSize?: int, * shadowOffset?: int, * opacity?: float, * padding?: int, * withShadow?: bool|string * } $options * * @return void */ abstract protected function _text(string $text, array $options = []); /** * Handles the actual resizing of the image. * * @return $this */ abstract public function _resize(bool $maintainRatio = false); /** * Crops the image. * * @return $this */ abstract public function _crop(); /** * Return image width. * * @return int */ abstract public function _getWidth(); /** * Return the height of an image. * * @return int */ abstract public function _getHeight(); /** * Reads the EXIF information from the image and modifies the orientation * so that displays correctly in the browser. This is especially an issue * with images taken by smartphones who always store the image up-right, * but set the orientation flag to display it correctly. * * @param bool $silent If true, will ignore exceptions when PHP doesn't support EXIF. * * @return $this */ public function reorient(bool $silent = false) { $orientation = $this->getEXIF('Orientation', $silent); return match ($orientation) { 2 => $this->flip('horizontal'), 3 => $this->rotate(180), 4 => $this->rotate(180)->flip('horizontal'), 5 => $this->rotate(270)->flip('horizontal'), 6 => $this->rotate(270), 7 => $this->rotate(90)->flip('horizontal'), 8 => $this->rotate(90), default => $this, }; } /** * Retrieve the EXIF information from the image, if possible. Returns * an array of the information, or null if nothing can be found. * * EXIF data is only supported fr JPEG & TIFF formats. * * @param string|null $key If specified, will only return this piece of EXIF data. * @param bool $silent If true, will not throw our own exceptions. * * @return mixed * * @throws ImageException */ public function getEXIF(?string $key = null, bool $silent = false) { if (! function_exists('exif_read_data')) { if ($silent) { return null; } throw ImageException::forEXIFUnsupported(); // @codeCoverageIgnore } $exif = null; // default switch ($this->image()->imageType) { case IMAGETYPE_JPEG: case IMAGETYPE_TIFF_II: $exif = @exif_read_data($this->image()->getPathname()); if ($key !== null && is_array($exif)) { $exif = $exif[$key] ?? false; } } return $exif; } /** * Combine cropping and resizing into a single command. * * Supported positions: * - top-left * - top * - top-right * - left * - center * - right * - bottom-left * - bottom * - bottom-right * * @return BaseHandler */ public function fit(int $width, ?int $height = null, string $position = 'center') { $origWidth = $this->image()->origWidth; $origHeight = $this->image()->origHeight; [$cropWidth, $cropHeight] = $this->calcAspectRatio($width, $height, $origWidth, $origHeight); if ($height === null) { $height = (int) ceil(($width / $cropWidth) * $cropHeight); } [$x, $y] = $this->calcCropCoords($cropWidth, $cropHeight, $origWidth, $origHeight, $position); return $this->crop($cropWidth, $cropHeight, (int) $x, (int) $y)->resize($width, $height); } /** * Calculate image aspect ratio. * * @param float|int $width * @param float|int|null $height * @param float|int $origWidth * @param float|int $origHeight */ protected function calcAspectRatio($width, $height = null, $origWidth = 0, $origHeight = 0): array { if (empty($origWidth) || empty($origHeight)) { throw new InvalidArgumentException('You must supply the parameters: origWidth, origHeight.'); } // If $height is null, then we have it easy. // Calc based on full image size and be done. if ($height === null) { $height = ($width / $origWidth) * $origHeight; return [ $width, (int) $height, ]; } $xRatio = $width / $origWidth; $yRatio = $height / $origHeight; if ($xRatio > $yRatio) { return [ $origWidth, (int) ($origWidth * $height / $width), ]; } return [ (int) ($origHeight * $width / $height), $origHeight, ]; } /** * Based on the position, will determine the correct x/y coords to * crop the desired portion from the image. * * @param float|int $width * @param float|int $height * @param float|int $origWidth * @param float|int $origHeight * @param string $position */ protected function calcCropCoords($width, $height, $origWidth, $origHeight, $position): array { $position = strtolower($position); $x = $y = 0; switch ($position) { case 'top-left': $x = 0; $y = 0; break; case 'top': $x = floor(($origWidth - $width) / 2); $y = 0; break; case 'top-right': $x = $origWidth - $width; $y = 0; break; case 'left': $x = 0; $y = floor(($origHeight - $height) / 2); break; case 'center': $x = floor(($origWidth - $width) / 2); $y = floor(($origHeight - $height) / 2); break; case 'right': $x = ($origWidth - $width); $y = floor(($origHeight - $height) / 2); break; case 'bottom-left': $x = 0; $y = $origHeight - $height; break; case 'bottom': $x = floor(($origWidth - $width) / 2); $y = $origHeight - $height; break; case 'bottom-right': $x = ($origWidth - $width); $y = $origHeight - $height; break; } return [ $x, $y, ]; } /** * Get the version of the image library in use. * * @return string */ abstract public function getVersion(); /** * Saves any changes that have been made to file. * * Example: * $image->resize(100, 200, true) * ->save($target); * * @param non-empty-string|null $target * * @return bool */ abstract public function save(?string $target = null, int $quality = 90); /** * Does the driver-specific processing of the image. * * @return mixed */ abstract protected function process(string $action); /** * Provide access to the Image class' methods if they don't exist * on the handler itself. * * @return mixed */ public function __call(string $name, array $args = []) { if (method_exists($this->image(), $name)) { return $this->image()->{$name}(...$args); } return null; } /** * Re-proportion Image Width/Height * * When creating thumbs, the desired width/height * can end up warping the image due to an incorrect * ratio between the full-sized image and the thumb. * * This function lets us re-proportion the width/height * if users choose to maintain the aspect ratio when resizing. * * @return void */ protected function reproportion() { if (($this->width === 0 && $this->height === 0) || $this->image()->origWidth === 0 || $this->image()->origHeight === 0 || (! ctype_digit((string) $this->width) && ! ctype_digit((string) $this->height)) || ! ctype_digit((string) $this->image()->origWidth) || ! ctype_digit((string) $this->image()->origHeight)) { return; } // Sanitize $this->width = (int) $this->width; $this->height = (int) $this->height; if ($this->masterDim !== 'width' && $this->masterDim !== 'height') { if ($this->width > 0 && $this->height > 0) { $this->masterDim = ((($this->image()->origHeight / $this->image()->origWidth) - ($this->height / $this->width)) < 0) ? 'width' : 'height'; } else { $this->masterDim = ($this->height === 0) ? 'width' : 'height'; } } elseif (($this->masterDim === 'width' && $this->width === 0) || ($this->masterDim === 'height' && $this->height === 0) ) { return; } if ($this->masterDim === 'width') { $this->height = (int) ceil($this->width * $this->image()->origHeight / $this->image()->origWidth); } else { $this->width = (int) ceil($this->image()->origWidth * $this->height / $this->image()->origHeight); } } /** * Return image width. * * accessor for testing; not part of interface * * @return int */ public function getWidth() { return ($this->resource !== null) ? $this->_getWidth() : $this->width; } /** * Return image height. * * accessor for testing; not part of interface * * @return int */ public function getHeight() { return ($this->resource !== null) ? $this->_getHeight() : $this->height; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Modules/Modules.php
system/Modules/Modules.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\Modules; /** * Modules Class * * @see https://codeigniter.com/user_guide/general/modules.html * * @phpstan-consistent-constructor */ class Modules { /** * Auto-Discover * * @var bool */ public $enabled = true; /** * Auto-Discovery Within Composer Packages * * @var bool */ public $discoverInComposer = true; /** * Auto-Discover Rules Handler * * @var list<string> */ public $aliases = []; public function __construct() { // For @phpstan-consistent-constructor } /** * Should the application auto-discover the requested resource. */ public function shouldDiscover(string $alias): bool { if (! $this->enabled) { return false; } return in_array(strtolower($alias), $this->aliases, true); } public static function __set_state(array $array) { $obj = new static(); $properties = array_keys(get_object_vars($obj)); foreach ($properties as $property) { $obj->{$property} = $array[$property]; } return $obj; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/Cors.php
system/HTTP/Cors.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 Config\Cors as CorsConfig; /** * Cross-Origin Resource Sharing (CORS) * * @see \CodeIgniter\HTTP\CorsTest */ class Cors { /** * @var array{ * allowedOrigins: list<string>, * allowedOriginsPatterns: list<string>, * supportsCredentials: bool, * allowedHeaders: list<string>, * exposedHeaders: list<string>, * allowedMethods: list<string>, * maxAge: int, * } */ private array $config = [ 'allowedOrigins' => [], 'allowedOriginsPatterns' => [], 'supportsCredentials' => false, 'allowedHeaders' => [], 'exposedHeaders' => [], 'allowedMethods' => [], 'maxAge' => 7200, ]; /** * @param array{ * allowedOrigins?: list<string>, * allowedOriginsPatterns?: list<string>, * supportsCredentials?: bool, * allowedHeaders?: list<string>, * exposedHeaders?: list<string>, * allowedMethods?: list<string>, * maxAge?: int, * }|CorsConfig|null $config */ public function __construct($config = null) { $config ??= config(CorsConfig::class); if ($config instanceof CorsConfig) { $config = $config->default; } $this->config = array_merge($this->config, $config); } /** * Creates a new instance by config name. */ public static function factory(string $configName = 'default'): self { $config = config(CorsConfig::class)->{$configName}; return new self($config); } /** * Whether if the request is a preflight request. */ public function isPreflightRequest(IncomingRequest $request): bool { return $request->is('OPTIONS') && $request->hasHeader('Access-Control-Request-Method'); } /** * Handles the preflight request, and returns the response. */ public function handlePreflightRequest(RequestInterface $request, ResponseInterface $response): ResponseInterface { $response->setStatusCode(204); $this->setAllowOrigin($request, $response); if ($response->hasHeader('Access-Control-Allow-Origin')) { $this->setAllowHeaders($response); $this->setAllowMethods($response); $this->setAllowMaxAge($response); $this->setAllowCredentials($response); } return $response; } private function checkWildcard(string $name, int $count): void { if (in_array('*', $this->config[$name], true) && $count > 1) { throw new ConfigException( "If wildcard is specified, you must set `'{$name}' => ['*']`." . ' But using wildcard is not recommended.', ); } } private function checkWildcardAndCredentials(string $name, string $header): void { if ( $this->config[$name] === ['*'] && $this->config['supportsCredentials'] ) { throw new ConfigException( 'When responding to a credentialed request, ' . 'the server must not specify the "*" wildcard for the ' . $header . ' response-header value.', ); } } private function setAllowOrigin(RequestInterface $request, ResponseInterface $response): void { $originCount = count($this->config['allowedOrigins']); $originPatternCount = count($this->config['allowedOriginsPatterns']); $this->checkWildcard('allowedOrigins', $originCount); $this->checkWildcardAndCredentials('allowedOrigins', 'Access-Control-Allow-Origin'); // Single Origin. if ($originCount === 1 && $originPatternCount === 0) { $response->setHeader('Access-Control-Allow-Origin', $this->config['allowedOrigins'][0]); return; } // Multiple Origins. if (! $request->hasHeader('Origin')) { return; } $origin = $request->getHeaderLine('Origin'); if ($originCount > 1 && in_array($origin, $this->config['allowedOrigins'], true)) { $response->setHeader('Access-Control-Allow-Origin', $origin); $response->appendHeader('Vary', 'Origin'); return; } if ($originPatternCount > 0) { foreach ($this->config['allowedOriginsPatterns'] as $pattern) { $regex = '#\A' . $pattern . '\z#'; if (preg_match($regex, $origin)) { $response->setHeader('Access-Control-Allow-Origin', $origin); $response->appendHeader('Vary', 'Origin'); return; } } } } private function setAllowHeaders(ResponseInterface $response): void { $this->checkWildcard('allowedHeaders', count($this->config['allowedHeaders'])); $this->checkWildcardAndCredentials('allowedHeaders', 'Access-Control-Allow-Headers'); $response->setHeader( 'Access-Control-Allow-Headers', implode(', ', $this->config['allowedHeaders']), ); } private function setAllowMethods(ResponseInterface $response): void { $this->checkWildcard('allowedMethods', count($this->config['allowedMethods'])); $this->checkWildcardAndCredentials('allowedMethods', 'Access-Control-Allow-Methods'); $response->setHeader( 'Access-Control-Allow-Methods', implode(', ', $this->config['allowedMethods']), ); } private function setAllowMaxAge(ResponseInterface $response): void { $response->setHeader('Access-Control-Max-Age', (string) $this->config['maxAge']); } private function setAllowCredentials(ResponseInterface $response): void { if ($this->config['supportsCredentials']) { $response->setHeader('Access-Control-Allow-Credentials', 'true'); } } /** * Adds CORS headers to the Response. */ public function addResponseHeaders(RequestInterface $request, ResponseInterface $response): ResponseInterface { $this->setAllowOrigin($request, $response); if ($response->hasHeader('Access-Control-Allow-Origin')) { $this->setAllowCredentials($response); $this->setExposeHeaders($response); } return $response; } private function setExposeHeaders(ResponseInterface $response): void { if ($this->config['exposedHeaders'] !== []) { $response->setHeader( 'Access-Control-Expose-Headers', implode(', ', $this->config['exposedHeaders']), ); } } /** * Check if response headers were set */ public function hasResponseHeaders(RequestInterface $request, ResponseInterface $response): bool { if (! $response->hasHeader('Access-Control-Allow-Origin')) { return false; } if ($this->config['supportsCredentials'] && ! $response->hasHeader('Access-Control-Allow-Credentials')) { return false; } return ! ($this->config['exposedHeaders'] !== [] && (! $response->hasHeader('Access-Control-Expose-Headers') || ! str_contains( $response->getHeaderLine('Access-Control-Expose-Headers'), implode(', ', $this->config['exposedHeaders']), ))); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/DownloadResponse.php
system/HTTP/DownloadResponse.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\DownloadException; use CodeIgniter\Files\File; use Config\App; use Config\Mimes; /** * HTTP response when a download is requested. * * @see \CodeIgniter\HTTP\DownloadResponseTest */ class DownloadResponse extends Response { /** * Download file name */ private string $filename; /** * Download for file */ private ?File $file = null; /** * mime set flag */ private readonly bool $setMime; /** * Download for binary */ private ?string $binary = null; /** * Download charset */ private string $charset = 'UTF-8'; /** * Download reason * * @var string */ protected $reason = 'OK'; /** * The current status code for this response. * * @var int */ protected $statusCode = 200; /** * Constructor. */ public function __construct(string $filename, bool $setMime) { parent::__construct(config(App::class)); $this->filename = $filename; $this->setMime = $setMime; // Make sure the content type is either specified or detected $this->removeHeader('Content-Type'); } /** * set download for binary string. * * @return void */ public function setBinary(string $binary) { if ($this->file instanceof File) { throw DownloadException::forCannotSetBinary(); } $this->binary = $binary; } /** * set download for file. * * @return void */ public function setFilePath(string $filepath) { if ($this->binary !== null) { throw DownloadException::forCannotSetFilePath($filepath); } $this->file = new File($filepath, true); } /** * set name for the download. * * @return $this */ public function setFileName(string $filename) { $this->filename = $filename; return $this; } /** * get content length. */ public function getContentLength(): int { if (is_string($this->binary)) { return strlen($this->binary); } if ($this->file instanceof File) { return $this->file->getSize(); } return 0; } /** * Set content type by guessing mime type from file extension */ private function setContentTypeByMimeType(): void { $mime = null; $charset = ''; if ($this->setMime && ($lastDotPosition = strrpos($this->filename, '.')) !== false) { $mime = Mimes::guessTypeFromExtension(substr($this->filename, $lastDotPosition + 1)); $charset = $this->charset; } if (! is_string($mime)) { // Set the default MIME type to send $mime = 'application/octet-stream'; $charset = ''; } $this->setContentType($mime, $charset); } /** * get download filename. */ private function getDownloadFileName(): string { $filename = $this->filename; $x = explode('.', $this->filename); $extension = end($x); /* It was reported that browsers on Android 2.1 (and possibly older as well) * need to have the filename extension upper-cased in order to be able to * download it. * * Reference: http://digiblog.de/2011/04/19/android-and-the-download-file-headers/ */ // @todo: depend super global if (count($x) !== 1 && isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/Android\s(1|2\.[01])/', $_SERVER['HTTP_USER_AGENT'])) { $x[count($x) - 1] = strtoupper($extension); $filename = implode('.', $x); } return $filename; } /** * Get Content-Disposition Header string. */ private function getContentDisposition(bool $inline = false): string { $downloadFilename = $utf8Filename = $this->getDownloadFileName(); $disposition = $inline ? 'inline' : 'attachment'; if (strtoupper($this->charset) !== 'UTF-8') { $utf8Filename = mb_convert_encoding($downloadFilename, 'UTF-8', $this->charset); } $result = sprintf('%s; filename="%s"', $disposition, addslashes($downloadFilename)); if ($utf8Filename !== '') { $result .= sprintf('; filename*=UTF-8\'\'%s', rawurlencode($utf8Filename)); } return $result; } /** * Disallows status changing. * * @throws DownloadException */ public function setStatusCode(int $code, string $reason = '') { throw DownloadException::forCannotSetStatusCode($code, $reason); } /** * Sets the Content Type header for this response with the mime type * and, optionally, the charset. * * @return ResponseInterface */ public function setContentType(string $mime, string $charset = 'UTF-8') { parent::setContentType($mime, $charset); if ($charset !== '') { $this->charset = $charset; } return $this; } /** * Sets the appropriate headers to ensure this response * is not cached by the browsers. */ public function noCache(): self { $this->removeHeader('Cache-Control'); $this->setHeader('Cache-Control', ['private', 'no-transform', 'no-store', 'must-revalidate']); return $this; } /** * {@inheritDoc} * * @return $this * * @todo Do downloads need CSP or Cookies? Compare with ResponseTrait::send() */ public function send() { // Turn off output buffering completely, even if php.ini output_buffering is not off if (ENVIRONMENT !== 'testing') { while (ob_get_level() > 0) { ob_end_clean(); } } $this->buildHeaders(); $this->sendHeaders(); $this->sendBody(); return $this; } /** * set header for file download. * * @return void */ public function buildHeaders() { if (! $this->hasHeader('Content-Type')) { $this->setContentTypeByMimeType(); } if (! $this->hasHeader('Content-Disposition')) { $this->setHeader('Content-Disposition', $this->getContentDisposition()); } $this->setHeader('Content-Transfer-Encoding', 'binary'); $this->setHeader('Content-Length', (string) $this->getContentLength()); } /** * output download file text. * * @return DownloadResponse * * @throws DownloadException */ public function sendBody() { if ($this->binary !== null) { return $this->sendBodyByBinary(); } if ($this->file instanceof File) { return $this->sendBodyByFilePath(); } throw DownloadException::forNotFoundDownloadSource(); } /** * output download text by file. * * @return DownloadResponse */ private function sendBodyByFilePath() { $splFileObject = $this->file->openFile('rb'); // Flush 1MB chunks of data while (! $splFileObject->eof() && ($data = $splFileObject->fread(1_048_576)) !== false) { echo $data; unset($data); } return $this; } /** * output download text by binary * * @return DownloadResponse */ private function sendBodyByBinary() { echo $this->binary; return $this; } /** * Sets the response header to display the file in the browser. * * @return DownloadResponse */ public function inline() { $this->setHeader('Content-Disposition', $this->getContentDisposition(true)); return $this; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/MessageTrait.php
system/HTTP/MessageTrait.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; /** * Message Trait * Additional methods to make a PSR-7 Message class * compliant with the framework's own MessageInterface. * * @see https://github.com/php-fig/http-message/blob/master/src/MessageInterface.php */ trait MessageTrait { /** * List of all HTTP request headers. * * [name => Header] * or * [name => [Header1, Header2]] * * @var array<string, Header|list<Header>> */ protected $headers = []; /** * Holds a map of lower-case header names * and their normal-case key as it is in $headers. * Used for case-insensitive header access. * * @var array */ protected $headerMap = []; // -------------------------------------------------------------------- // Body // -------------------------------------------------------------------- /** * Sets the body of the current message. * * @param string $data * * @return $this */ public function setBody($data): self { $this->body = $data; return $this; } /** * Appends data to the body of the current message. * * @param string $data * * @return $this */ public function appendBody($data): self { $this->body .= (string) $data; return $this; } // -------------------------------------------------------------------- // Headers // -------------------------------------------------------------------- /** * Populates the $headers array with any headers the server knows about. */ public function populateHeaders(): void { $contentType = $_SERVER['CONTENT_TYPE'] ?? getenv('CONTENT_TYPE'); if (! empty($contentType)) { $this->setHeader('Content-Type', $contentType); } unset($contentType); foreach (array_keys($_SERVER) as $key) { if (sscanf($key, 'HTTP_%s', $header) === 1) { // take SOME_HEADER and turn it into Some-Header $header = str_replace('_', ' ', strtolower($header)); $header = str_replace(' ', '-', ucwords($header)); $this->setHeader($header, $_SERVER[$key]); // Add us to the header map, so we can find them case-insensitively $this->headerMap[strtolower($header)] = $header; } } } /** * Returns an array containing all Headers. * * @return array<string, Header|list<Header>> An array of the Header objects */ public function headers(): array { // If no headers are defined, but the user is // requesting it, then it's likely they want // it to be populated so do that... if (empty($this->headers)) { $this->populateHeaders(); } return $this->headers; } /** * Returns a single Header object. If multiple headers with the same * name exist, then will return an array of header objects. * * @param string $name * * @return Header|list<Header>|null */ public function header($name) { $origName = $this->getHeaderName($name); return $this->headers[$origName] ?? null; } /** * Sets a header and it's value. * * @param array|string|null $value * * @return $this */ public function setHeader(string $name, $value): self { $this->checkMultipleHeaders($name); $origName = $this->getHeaderName($name); if ( isset($this->headers[$origName]) && is_array($this->headers[$origName]->getValue()) ) { if (! is_array($value)) { $value = [$value]; } foreach ($value as $v) { $this->appendHeader($origName, $v); } } else { $this->headers[$origName] = new Header($origName, $value); $this->headerMap[strtolower($origName)] = $origName; } return $this; } private function hasMultipleHeaders(string $name): bool { $origName = $this->getHeaderName($name); return isset($this->headers[$origName]) && is_array($this->headers[$origName]); } private function checkMultipleHeaders(string $name): void { if ($this->hasMultipleHeaders($name)) { throw new InvalidArgumentException( 'The header "' . $name . '" already has multiple headers.' . ' You cannot change them. If you really need to change, remove the header first.', ); } } /** * Removes a header from the list of headers we track. * * @return $this */ public function removeHeader(string $name): self { $origName = $this->getHeaderName($name); unset($this->headers[$origName], $this->headerMap[strtolower($name)]); return $this; } /** * Adds an additional header value to any headers that accept * multiple values (i.e. are an array or implement ArrayAccess) * * @return $this */ public function appendHeader(string $name, ?string $value): self { $this->checkMultipleHeaders($name); $origName = $this->getHeaderName($name); array_key_exists($origName, $this->headers) ? $this->headers[$origName]->appendValue($value) : $this->setHeader($name, $value); return $this; } /** * Adds a header (not a header value) with the same name. * Use this only when you set multiple headers with the same name, * typically, for `Set-Cookie`. * * @return $this */ public function addHeader(string $name, string $value): static { $origName = $this->getHeaderName($name); if (! isset($this->headers[$origName])) { $this->setHeader($name, $value); return $this; } if (! $this->hasMultipleHeaders($name) && isset($this->headers[$origName])) { $this->headers[$origName] = [$this->headers[$origName]]; } // Add the header. $this->headers[$origName][] = new Header($origName, $value); return $this; } /** * Adds an additional header value to any headers that accept * multiple values (i.e. are an array or implement ArrayAccess) * * @return $this */ public function prependHeader(string $name, string $value): self { $this->checkMultipleHeaders($name); $origName = $this->getHeaderName($name); $this->headers[$origName]->prependValue($value); return $this; } /** * Takes a header name in any case, and returns the * normal-case version of the header. */ protected function getHeaderName(string $name): string { return $this->headerMap[strtolower($name)] ?? $name; } /** * Sets the HTTP protocol version. * * @return $this * * @throws HTTPException For invalid protocols */ public function setProtocolVersion(string $version): self { if (! is_numeric($version)) { $version = substr($version, strpos($version, '/') + 1); } // Make sure that version is in the correct format $version = number_format((float) $version, 1); if (! in_array($version, $this->validProtocolVersions, true)) { throw HTTPException::forInvalidHTTPProtocol($version); } $this->protocolVersion = $version; return $this; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/Method.php
system/HTTP/Method.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; /** * HTTP Method List */ class Method { /** * Safe: No * Idempotent: No * Cacheable: No * * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT */ public const CONNECT = 'CONNECT'; /** * Safe: No * Idempotent: Yes * Cacheable: No * * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE */ public const DELETE = 'DELETE'; /** * Safe: Yes * Idempotent: Yes * Cacheable: Yes * * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET */ public const GET = 'GET'; /** * Safe: Yes * Idempotent: Yes * Cacheable: Yes * * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD */ public const HEAD = 'HEAD'; /** * Safe: Yes * Idempotent: Yes * Cacheable: No * * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS */ public const OPTIONS = 'OPTIONS'; /** * Safe: No * Idempotent: No * Cacheable: Only if freshness information is included * * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH */ public const PATCH = 'PATCH'; /** * Safe: No * Idempotent: No * Cacheable: Only if freshness information is included * * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST */ public const POST = 'POST'; /** * Safe: No * Idempotent: Yes * Cacheable: No * * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT */ public const PUT = 'PUT'; /** * Safe: Yes * Idempotent: Yes * Cacheable: No * * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/TRACE */ public const TRACE = 'TRACE'; /** * Returns all HTTP methods. * * @return list<string> */ public static function all(): array { return [ self::CONNECT, self::DELETE, self::GET, self::HEAD, self::OPTIONS, self::PATCH, self::POST, self::PUT, self::TRACE, ]; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/ResponsableInterface.php
system/HTTP/ResponsableInterface.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; interface ResponsableInterface { public function getResponse(): ResponseInterface; }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/MessageInterface.php
system/HTTP/MessageInterface.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; /** * Expected behavior of an HTTP message */ interface MessageInterface { /** * Retrieves the HTTP protocol version as a string. * * The string MUST contain only the HTTP version number (e.g., "1.1", "1.0"). * * @return string HTTP protocol version. */ public function getProtocolVersion(): string; /** * Sets the body of the current message. * * @param string $data * * @return $this */ public function setBody($data); /** * Gets the body of the message. * * @return string|null * * @TODO Incompatible return type with PSR-7 */ public function getBody(); /** * Appends data to the body of the current message. * * @param string $data * * @return $this */ public function appendBody($data); /** * Populates the $headers array with any headers the server knows about. */ public function populateHeaders(): void; /** * Returns an array containing all Headers. * * @return array<string, Header|list<Header>> An array of the Header objects */ public function headers(): array; /** * Checks if a header exists by the given case-insensitive name. * * @param string $name Case-insensitive header field name. * * @return bool Returns true if any header names match the given header * name using a case-insensitive string comparison. Returns false if * no matching header name is found in the message. */ public function hasHeader(string $name): bool; /** * Returns a single Header object. If multiple headers with the same * name exist, then will return an array of header objects. * * @param string $name * * @return Header|list<Header>|null */ public function header($name); /** * 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; /** * Sets a header and it's value. * * @param array|string|null $value * * @return $this */ public function setHeader(string $name, $value); /** * Removes a header from the list of headers we track. * * @return $this */ public function removeHeader(string $name); /** * Adds an additional header value to any headers that accept * multiple values (i.e. are an array or implement ArrayAccess) * * @return $this */ public function appendHeader(string $name, ?string $value); /** * Adds an additional header value to any headers that accept * multiple values (i.e. are an array or implement ArrayAccess) * * @return $this */ public function prependHeader(string $name, string $value); /** * Sets the HTTP protocol version. * * @return $this * * @throws HTTPException For invalid protocols */ public function setProtocolVersion(string $version); }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/RequestInterface.php
system/HTTP/RequestInterface.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 incoming, server-side HTTP request. * * Corresponds to Psr7\ServerRequestInterface. */ interface RequestInterface extends OutgoingRequestInterface { /** * Gets the user's IP address. * Supplied by RequestTrait. * * @return string IP address */ public function getIPAddress(): string; /** * Fetch an item from the $_SERVER array. * Supplied by RequestTrait. * * @param array|string|null $index Index for item to be fetched from $_SERVER * @param int|null $filter A filter name to be applied * * @return mixed */ public function getServer($index = null, $filter = null); }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/ContentSecurityPolicy.php
system/HTTP/ContentSecurityPolicy.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\App; use Config\ContentSecurityPolicy as ContentSecurityPolicyConfig; /** * Provides tools for working with the Content-Security-Policy header * to help defeat XSS attacks. * * @see http://www.w3.org/TR/CSP/ * @see http://www.html5rocks.com/en/tutorials/security/content-security-policy/ * @see http://content-security-policy.com/ * @see https://www.owasp.org/index.php/Content_Security_Policy * @see \CodeIgniter\HTTP\ContentSecurityPolicyTest */ class ContentSecurityPolicy { /** * CSP directives * * @var array<string, string> [name => property] */ protected array $directives = [ 'base-uri' => 'baseURI', 'child-src' => 'childSrc', 'connect-src' => 'connectSrc', 'default-src' => 'defaultSrc', 'font-src' => 'fontSrc', 'form-action' => 'formAction', 'frame-ancestors' => 'frameAncestors', 'frame-src' => 'frameSrc', 'img-src' => 'imageSrc', 'media-src' => 'mediaSrc', 'object-src' => 'objectSrc', 'plugin-types' => 'pluginTypes', 'script-src' => 'scriptSrc', 'style-src' => 'styleSrc', 'manifest-src' => 'manifestSrc', 'sandbox' => 'sandbox', 'report-uri' => 'reportURI', ]; /** * Used for security enforcement * * @var array|string */ protected $baseURI = []; /** * Used for security enforcement * * @var array|string */ protected $childSrc = []; /** * Used for security enforcement * * @var array */ protected $connectSrc = []; /** * Used for security enforcement * * @var array|string */ protected $defaultSrc = []; /** * Used for security enforcement * * @var array|string */ protected $fontSrc = []; /** * Used for security enforcement * * @var array|string */ protected $formAction = []; /** * Used for security enforcement * * @var array|string */ protected $frameAncestors = []; /** * Used for security enforcement * * @var array|string */ protected $frameSrc = []; /** * Used for security enforcement * * @var array|string */ protected $imageSrc = []; /** * Used for security enforcement * * @var array|string */ protected $mediaSrc = []; /** * Used for security enforcement * * @var array|string */ protected $objectSrc = []; /** * Used for security enforcement * * @var array|string */ protected $pluginTypes = []; /** * Used for security enforcement * * @var array|string */ protected $scriptSrc = []; /** * Used for security enforcement * * @var array|string */ protected $styleSrc = []; /** * Used for security enforcement * * @var array|string */ protected $manifestSrc = []; /** * Used for security enforcement * * @var array|string */ protected $sandbox = []; /** * A set of endpoints to which csp violation reports will be sent when * particular behaviors are prevented. * * @var string|null */ protected $reportURI; /** * Used for security enforcement * * @var bool */ protected $upgradeInsecureRequests = false; /** * Used for security enforcement * * @var bool */ protected $reportOnly = false; /** * Used for security enforcement * * @var list<string> */ protected $validSources = [ 'self', 'none', 'unsafe-inline', 'unsafe-eval', ]; /** * Used for security enforcement * * @var array */ protected $nonces = []; /** * Nonce for style * * @var string */ protected $styleNonce; /** * Nonce for script * * @var string */ protected $scriptNonce; /** * Nonce tag for style * * @var string */ protected $styleNonceTag = '{csp-style-nonce}'; /** * Nonce tag for script * * @var string */ protected $scriptNonceTag = '{csp-script-nonce}'; /** * Replace nonce tag automatically * * @var bool */ protected $autoNonce = true; /** * An array of header info since we have * to build ourselves before passing to Response. * * @var array */ protected $tempHeaders = []; /** * An array of header info to build * that should only be reported. * * @var array */ protected $reportOnlyHeaders = []; /** * Whether Content Security Policy is being enforced. * * @var bool */ protected $CSPEnabled = false; /** * Constructor. * * Stores our default values from the Config file. */ public function __construct(ContentSecurityPolicyConfig $config) { $appConfig = config(App::class); $this->CSPEnabled = $appConfig->CSPEnabled; foreach (get_object_vars($config) as $setting => $value) { if (property_exists($this, $setting)) { $this->{$setting} = $value; } } if (! is_array($this->styleSrc)) { $this->styleSrc = [$this->styleSrc]; } if (! is_array($this->scriptSrc)) { $this->scriptSrc = [$this->scriptSrc]; } } /** * Whether Content Security Policy is being enforced. */ public function enabled(): bool { return $this->CSPEnabled; } /** * Get the nonce for the style tag. */ public function getStyleNonce(): string { if ($this->styleNonce === null) { $this->styleNonce = bin2hex(random_bytes(12)); $this->styleSrc[] = 'nonce-' . $this->styleNonce; } return $this->styleNonce; } /** * Get the nonce for the script tag. */ public function getScriptNonce(): string { if ($this->scriptNonce === null) { $this->scriptNonce = bin2hex(random_bytes(12)); $this->scriptSrc[] = 'nonce-' . $this->scriptNonce; } return $this->scriptNonce; } /** * Compiles and sets the appropriate headers in the request. * * Should be called just prior to sending the response to the user agent. * * @return void */ public function finalize(ResponseInterface $response) { if ($this->autoNonce) { $this->generateNonces($response); } $this->buildHeaders($response); } /** * If TRUE, nothing will be restricted. Instead all violations will * be reported to the reportURI for monitoring. This is useful when * you are just starting to implement the policy, and will help * determine what errors need to be addressed before you turn on * all filtering. * * @return $this */ public function reportOnly(bool $value = true) { $this->reportOnly = $value; return $this; } /** * Adds a new baseURI value. Can be either a URI class or a simple string. * * baseURI restricts the URLs that can appear in a page's <base> element. * * @see http://www.w3.org/TR/CSP/#directive-base-uri * * @param array|string $uri * * @return $this */ public function addBaseURI($uri, ?bool $explicitReporting = null) { $this->addOption($uri, 'baseURI', $explicitReporting ?? $this->reportOnly); return $this; } /** * Adds a new valid endpoint for a form's action. Can be either * a URI class or a simple string. * * child-src lists the URLs for workers and embedded frame contents. * For example: child-src https://youtube.com would enable embedding * videos from YouTube but not from other origins. * * @see http://www.w3.org/TR/CSP/#directive-child-src * * @param array|string $uri * * @return $this */ public function addChildSrc($uri, ?bool $explicitReporting = null) { $this->addOption($uri, 'childSrc', $explicitReporting ?? $this->reportOnly); return $this; } /** * Adds a new valid endpoint for a form's action. Can be either * a URI class or a simple string. * * connect-src limits the origins to which you can connect * (via XHR, WebSockets, and EventSource). * * @see http://www.w3.org/TR/CSP/#directive-connect-src * * @param array|string $uri * * @return $this */ public function addConnectSrc($uri, ?bool $explicitReporting = null) { $this->addOption($uri, 'connectSrc', $explicitReporting ?? $this->reportOnly); return $this; } /** * Adds a new valid endpoint for a form's action. Can be either * a URI class or a simple string. * * default_src is the URI that is used for many of the settings when * no other source has been set. * * @see http://www.w3.org/TR/CSP/#directive-default-src * * @param array|string $uri * * @return $this */ public function setDefaultSrc($uri, ?bool $explicitReporting = null) { $this->defaultSrc = [(string) $uri => $explicitReporting ?? $this->reportOnly]; return $this; } /** * Adds a new valid endpoint for a form's action. Can be either * a URI class or a simple string. * * font-src specifies the origins that can serve web fonts. * * @see http://www.w3.org/TR/CSP/#directive-font-src * * @param array|string $uri * * @return $this */ public function addFontSrc($uri, ?bool $explicitReporting = null) { $this->addOption($uri, 'fontSrc', $explicitReporting ?? $this->reportOnly); return $this; } /** * Adds a new valid endpoint for a form's action. Can be either * a URI class or a simple string. * * @see http://www.w3.org/TR/CSP/#directive-form-action * * @param array|string $uri * * @return $this */ public function addFormAction($uri, ?bool $explicitReporting = null) { $this->addOption($uri, 'formAction', $explicitReporting ?? $this->reportOnly); return $this; } /** * Adds a new resource that should allow embedding the resource using * <frame>, <iframe>, <object>, <embed>, or <applet> * * @see http://www.w3.org/TR/CSP/#directive-frame-ancestors * * @param array|string $uri * * @return $this */ public function addFrameAncestor($uri, ?bool $explicitReporting = null) { $this->addOption($uri, 'frameAncestors', $explicitReporting ?? $this->reportOnly); return $this; } /** * Adds a new valid endpoint for valid frame sources. Can be either * a URI class or a simple string. * * @see http://www.w3.org/TR/CSP/#directive-frame-src * * @param array|string $uri * * @return $this */ public function addFrameSrc($uri, ?bool $explicitReporting = null) { $this->addOption($uri, 'frameSrc', $explicitReporting ?? $this->reportOnly); return $this; } /** * Adds a new valid endpoint for valid image sources. Can be either * a URI class or a simple string. * * @see http://www.w3.org/TR/CSP/#directive-img-src * * @param array|string $uri * * @return $this */ public function addImageSrc($uri, ?bool $explicitReporting = null) { $this->addOption($uri, 'imageSrc', $explicitReporting ?? $this->reportOnly); return $this; } /** * Adds a new valid endpoint for valid video and audio. Can be either * a URI class or a simple string. * * @see http://www.w3.org/TR/CSP/#directive-media-src * * @param array|string $uri * * @return $this */ public function addMediaSrc($uri, ?bool $explicitReporting = null) { $this->addOption($uri, 'mediaSrc', $explicitReporting ?? $this->reportOnly); return $this; } /** * Adds a new valid endpoint for manifest sources. Can be either * a URI class or simple string. * * @see https://www.w3.org/TR/CSP/#directive-manifest-src * * @param array|string $uri * * @return $this */ public function addManifestSrc($uri, ?bool $explicitReporting = null) { $this->addOption($uri, 'manifestSrc', $explicitReporting ?? $this->reportOnly); return $this; } /** * Adds a new valid endpoint for Flash and other plugin sources. Can be either * a URI class or a simple string. * * @see http://www.w3.org/TR/CSP/#directive-object-src * * @param array|string $uri * * @return $this */ public function addObjectSrc($uri, ?bool $explicitReporting = null) { $this->addOption($uri, 'objectSrc', $explicitReporting ?? $this->reportOnly); return $this; } /** * Limits the types of plugins that can be used. Can be either * a URI class or a simple string. * * @see http://www.w3.org/TR/CSP/#directive-plugin-types * * @param array|string $mime One or more plugin mime types, separate by spaces * * @return $this */ public function addPluginType($mime, ?bool $explicitReporting = null) { $this->addOption($mime, 'pluginTypes', $explicitReporting ?? $this->reportOnly); return $this; } /** * Specifies a URL where a browser will send reports when a content * security policy is violated. Can be either a URI class or a simple string. * * @see http://www.w3.org/TR/CSP/#directive-report-uri * * @param string $uri URL to send reports. Set `''` if you want to remove * this directive at runtime. * * @return $this */ public function setReportURI(string $uri) { $this->reportURI = $uri; return $this; } /** * specifies an HTML sandbox policy that the user agent applies to * the protected resource. * * @see http://www.w3.org/TR/CSP/#directive-sandbox * * @param array|string $flags An array of sandbox flags that can be added to the directive. * * @return $this */ public function addSandbox($flags, ?bool $explicitReporting = null) { $this->addOption($flags, 'sandbox', $explicitReporting ?? $this->reportOnly); return $this; } /** * Adds a new valid endpoint for javascript file sources. Can be either * a URI class or a simple string. * * @see http://www.w3.org/TR/CSP/#directive-connect-src * * @param array|string $uri * * @return $this */ public function addScriptSrc($uri, ?bool $explicitReporting = null) { $this->addOption($uri, 'scriptSrc', $explicitReporting ?? $this->reportOnly); return $this; } /** * Adds a new valid endpoint for CSS file sources. Can be either * a URI class or a simple string. * * @see http://www.w3.org/TR/CSP/#directive-connect-src * * @param array|string $uri * * @return $this */ public function addStyleSrc($uri, ?bool $explicitReporting = null) { $this->addOption($uri, 'styleSrc', $explicitReporting ?? $this->reportOnly); return $this; } /** * Sets whether the user agents should rewrite URL schemes, changing * HTTP to HTTPS. * * @return $this */ public function upgradeInsecureRequests(bool $value = true) { $this->upgradeInsecureRequests = $value; return $this; } /** * DRY method to add an string or array to a class property. * * @param list<string>|string $options * * @return void */ protected function addOption($options, string $target, ?bool $explicitReporting = null) { // Ensure we have an array to work with... if (is_string($this->{$target})) { $this->{$target} = [$this->{$target}]; } if (is_array($options)) { foreach ($options as $opt) { $this->{$target}[$opt] = $explicitReporting ?? $this->reportOnly; } } else { $this->{$target}[$options] = $explicitReporting ?? $this->reportOnly; } } /** * Scans the body of the request message and replaces any nonce * placeholders with actual nonces, that we'll then add to our * headers. * * @return void */ protected function generateNonces(ResponseInterface $response) { $body = $response->getBody(); if (empty($body)) { return; } // Replace style and script placeholders with nonces $pattern = '/(' . preg_quote($this->styleNonceTag, '/') . '|' . preg_quote($this->scriptNonceTag, '/') . ')/'; $body = preg_replace_callback($pattern, function ($match): string { $nonce = $match[0] === $this->styleNonceTag ? $this->getStyleNonce() : $this->getScriptNonce(); return "nonce=\"{$nonce}\""; }, $body); $response->setBody($body); } /** * Based on the current state of the elements, will add the appropriate * Content-Security-Policy and Content-Security-Policy-Report-Only headers * with their values to the response object. * * @return void */ protected function buildHeaders(ResponseInterface $response) { // Ensure both headers are available and arrays... $response->setHeader('Content-Security-Policy', []); $response->setHeader('Content-Security-Policy-Report-Only', []); // inject default base & default URIs if needed if (empty($this->baseURI)) { $this->baseURI = 'self'; } if (empty($this->defaultSrc)) { $this->defaultSrc = 'self'; } foreach ($this->directives as $name => $property) { if (! empty($this->{$property})) { $this->addToHeader($name, $this->{$property}); } } // Compile our own header strings here since if we just // append it to the response, it will be joined with // commas, not semi-colons as we need. if (! empty($this->tempHeaders)) { $header = ''; foreach ($this->tempHeaders as $name => $value) { $header .= " {$name} {$value};"; } // add token only if needed if ($this->upgradeInsecureRequests) { $header .= ' upgrade-insecure-requests;'; } $response->appendHeader('Content-Security-Policy', $header); } if (! empty($this->reportOnlyHeaders)) { $header = ''; foreach ($this->reportOnlyHeaders as $name => $value) { $header .= " {$name} {$value};"; } $response->appendHeader('Content-Security-Policy-Report-Only', $header); } $this->tempHeaders = []; $this->reportOnlyHeaders = []; } /** * Adds a directive and it's options to the appropriate header. The $values * array might have options that are geared toward either the regular or the * reportOnly header, since it's viable to have both simultaneously. * * @param array|string|null $values * * @return void */ protected function addToHeader(string $name, $values = null) { if (is_string($values)) { $values = [$values => $this->reportOnly]; } $sources = []; $reportSources = []; foreach ($values as $value => $reportOnly) { if (is_numeric($value) && is_string($reportOnly) && ($reportOnly !== '')) { $value = $reportOnly; $reportOnly = $this->reportOnly; } if (str_starts_with($value, 'nonce-')) { $value = "'{$value}'"; } if ($reportOnly === true) { $reportSources[] = in_array($value, $this->validSources, true) ? "'{$value}'" : $value; } else { $sources[] = in_array($value, $this->validSources, true) ? "'{$value}'" : $value; } } if ($sources !== []) { $this->tempHeaders[$name] = implode(' ', $sources); } if ($reportSources !== []) { $this->reportOnlyHeaders[$name] = implode(' ', $reportSources); } } /** * Clear the directive. * * @param string $directive CSP directive */ public function clearDirective(string $directive): void { if ($directive === 'report-uris') { $this->{$this->directives[$directive]} = null; return; } $this->{$this->directives[$directive]} = []; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/URI.php
system/HTTP/URI.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\InvalidArgumentException; use CodeIgniter\HTTP\Exceptions\HTTPException; use Config\App; use Stringable; /** * Abstraction for a uniform resource identifier (URI). * * @see \CodeIgniter\HTTP\URITest */ class URI implements Stringable { /** * Sub-delimiters used in query strings and fragments. */ public const CHAR_SUB_DELIMS = '!\$&\'\(\)\*\+,;='; /** * Unreserved characters used in paths, query strings, and fragments. */ public const CHAR_UNRESERVED = 'a-zA-Z0-9_\-\.~'; /** * Current URI string * * @var string * * @deprecated 4.4.0 Not used. */ protected $uriString; /** * The Current baseURL. * * @deprecated 4.4.0 Use SiteURI instead. */ private ?string $baseURL = null; /** * List of URI segments. * * Starts at 1 instead of 0 * * @var array<int, string> */ protected $segments = []; /** * The URI Scheme. * * @var string */ protected $scheme = 'http'; /** * URI User Info * * @var string|null */ protected $user; /** * URI User Password * * @var string|null */ protected $password; /** * URI Host * * @var string|null */ protected $host; /** * URI Port * * @var int|null */ protected $port; /** * URI path. * * @var string|null */ protected $path; /** * The name of any fragment. * * @var string */ protected $fragment = ''; /** * The query string. * * @var array<string, string> */ protected $query = []; /** * Default schemes/ports. * * @var array{ * http: int, * https: int, * ftp: int, * sftp: int, * } */ protected $defaultPorts = [ 'http' => 80, 'https' => 443, 'ftp' => 21, 'sftp' => 22, ]; /** * Whether passwords should be shown in userInfo/authority calls. * Default to false because URIs often show up in logs * * @var bool */ protected $showPassword = false; /** * If true, will continue instead of throwing exceptions. * * @var bool */ protected $silent = false; /** * If true, will use raw query string. * * @var bool */ protected $rawQueryString = false; /** * Builds a representation of the string from the component parts. * * @param string|null $scheme URI scheme. E.g., http, ftp * * @return string URI string with only passed parts. Maybe incomplete as a URI. */ public static function createURIString( ?string $scheme = null, ?string $authority = null, ?string $path = null, ?string $query = null, ?string $fragment = null, ): string { $uri = ''; if ((string) $scheme !== '') { $uri .= $scheme . '://'; } if ((string) $authority !== '') { $uri .= $authority; } if ((string) $path !== '') { $uri .= ! str_ends_with($uri, '/') ? '/' . ltrim($path, '/') : ltrim($path, '/'); } if ((string) $query !== '') { $uri .= '?' . $query; } if ((string) $fragment !== '') { $uri .= '#' . $fragment; } return $uri; } /** * Used when resolving and merging paths to correctly interpret and * remove single and double dot segments from the path per * RFC 3986 Section 5.2.4 * * @see http://tools.ietf.org/html/rfc3986#section-5.2.4 * * @internal */ public static function removeDotSegments(string $path): string { if ($path === '' || $path === '/') { return $path; } $output = []; $input = explode('/', $path); if ($input[0] === '') { unset($input[0]); $input = array_values($input); } // This is not a perfect representation of the // RFC, but matches most cases and is pretty // much what Guzzle uses. Should be good enough // for almost every real use case. foreach ($input as $segment) { if ($segment === '..') { array_pop($output); } elseif ($segment !== '.' && $segment !== '') { $output[] = $segment; } } $output = implode('/', $output); $output = trim($output, '/ '); // Add leading slash if necessary if (str_starts_with($path, '/')) { $output = '/' . $output; } // Add trailing slash if necessary if ($output !== '/' && str_ends_with($path, '/')) { $output .= '/'; } return $output; } /** * Constructor. * * @param string|null $uri The URI to parse. * * @throws HTTPException * * @TODO null for param $uri should be removed. * See https://www.php-fig.org/psr/psr-17/#26-urifactoryinterface */ public function __construct(?string $uri = null) { $this->setURI($uri); } /** * If $silent == true, then will not throw exceptions and will * attempt to continue gracefully. * * @deprecated 4.4.0 Method not in PSR-7 * * @return URI */ public function setSilent(bool $silent = true) { $this->silent = $silent; return $this; } /** * If $raw == true, then will use parseStr() method * instead of native parse_str() function. * * Note: Method not in PSR-7 * * @return URI */ public function useRawQueryString(bool $raw = true) { $this->rawQueryString = $raw; return $this; } /** * Sets and overwrites any current URI information. * * @return URI * * @throws HTTPException * * @deprecated 4.4.0 This method will be private. */ public function setURI(?string $uri = null) { if ($uri === null) { return $this; } $parts = parse_url($uri); if (is_array($parts)) { $this->applyParts($parts); return $this; } if ($this->silent) { return $this; } throw HTTPException::forUnableToParseURI($uri); } /** * Retrieve the scheme component of the URI. * * If no scheme is present, this method MUST return an empty string. * * The value returned MUST be normalized to lowercase, per RFC 3986 * Section 3.1. * * The trailing ":" character is not part of the scheme and MUST NOT be * added. * * @see https://tools.ietf.org/html/rfc3986#section-3.1 * * @return string The URI scheme. */ public function getScheme(): string { return $this->scheme; } /** * Retrieve the authority component of the URI. * * If no authority information is present, this method MUST return an empty * string. * * The authority syntax of the URI is: * * <pre> * [user-info@]host[:port] * </pre> * * If the port component is not set or is the standard port for the current * scheme, it SHOULD NOT be included. * * @see https://tools.ietf.org/html/rfc3986#section-3.2 * * @return string The URI authority, in "[user-info@]host[:port]" format. */ public function getAuthority(bool $ignorePort = false): string { if ((string) $this->host === '') { return ''; } $authority = $this->host; if ((string) $this->getUserInfo() !== '') { $authority = $this->getUserInfo() . '@' . $authority; } // Don't add port if it's a standard port for this scheme if ((int) $this->port !== 0 && ! $ignorePort && $this->port !== ($this->defaultPorts[$this->scheme] ?? null)) { $authority .= ':' . $this->port; } $this->showPassword = false; return $authority; } /** * Retrieve the user information component of the URI. * * If no user information is present, this method MUST return an empty * string. * * If a user is present in the URI, this will return that value; * additionally, if the password is also present, it will be appended to the * user value, with a colon (":") separating the values. * * NOTE that be default, the password, if available, will NOT be shown * as a security measure as discussed in RFC 3986, Section 7.5. If you know * the password is not a security issue, you can force it to be shown * with $this->showPassword(); * * The trailing "@" character is not part of the user information and MUST * NOT be added. * * @return string|null The URI user information, in "username[:password]" format. */ public function getUserInfo() { $userInfo = $this->user; if ($this->showPassword === true && (string) $this->password !== '') { $userInfo .= ':' . $this->password; } return $userInfo; } /** * Temporarily sets the URI to show a password in userInfo. Will * reset itself after the first call to authority(). * * Note: Method not in PSR-7 * * @return URI */ public function showPassword(bool $val = true) { $this->showPassword = $val; return $this; } /** * Retrieve the host component of the URI. * * If no host is present, this method MUST return an empty string. * * The value returned MUST be normalized to lowercase, per RFC 3986 * Section 3.2.2. * * @see http://tools.ietf.org/html/rfc3986#section-3.2.2 * * @return string The URI host. */ public function getHost(): string { return $this->host ?? ''; } /** * Retrieve the port component of the URI. * * If a port is present, and it is non-standard for the current scheme, * this method MUST return it as an integer. If the port is the standard port * used with the current scheme, this method SHOULD return null. * * If no port is present, and no scheme is present, this method MUST return * a null value. * * If no port is present, but a scheme is present, this method MAY return * the standard port for that scheme, but SHOULD return null. * * @return int|null The URI port. */ public function getPort() { return $this->port; } /** * Retrieve the path component of the URI. * * The path can either be empty or absolute (starting with a slash) or * rootless (not starting with a slash). Implementations MUST support all * three syntaxes. * * Normally, the empty path "" and absolute path "/" are considered equal as * defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically * do this normalization because in contexts with a trimmed base path, e.g. * the front controller, this difference becomes significant. It's the task * of the user to handle both "" and "/". * * The value returned MUST be percent-encoded, but MUST NOT double-encode * any characters. To determine what characters to encode, please refer to * RFC 3986, Sections 2 and 3.3. * * As an example, if the value should include a slash ("/") not intended as * delimiter between path segments, that value MUST be passed in encoded * form (e.g., "%2F") to the instance. * * @see https://tools.ietf.org/html/rfc3986#section-2 * @see https://tools.ietf.org/html/rfc3986#section-3.3 * * @return string The URI path. */ public function getPath(): string { return $this->path ?? ''; } /** * Retrieve the query string * * @param array{except?: list<string>|string, only?: list<string>|string} $options */ public function getQuery(array $options = []): string { $vars = $this->query; if (array_key_exists('except', $options)) { if (! is_array($options['except'])) { $options['except'] = [$options['except']]; } foreach ($options['except'] as $var) { unset($vars[$var]); } } elseif (array_key_exists('only', $options)) { $temp = []; if (! is_array($options['only'])) { $options['only'] = [$options['only']]; } foreach ($options['only'] as $var) { if (array_key_exists($var, $vars)) { $temp[$var] = $vars[$var]; } } $vars = $temp; } return $vars === [] ? '' : http_build_query($vars); } /** * Retrieve a URI fragment */ public function getFragment(): string { return $this->fragment ?? ''; } /** * Returns the segments of the path as an array. * * @return array<int, string> */ public function getSegments(): array { return $this->segments; } /** * Returns the value of a specific segment of the URI path. * Allows to get only existing segments or the next one. * * @param int $number Segment number starting at 1 * @param string $default Default value * * @return string The value of the segment. If you specify the last +1 * segment, the $default value. If you specify the last +2 * or more throws HTTPException. */ public function getSegment(int $number, string $default = ''): string { if ($number < 1) { throw HTTPException::forURISegmentOutOfRange($number); } if ($number > count($this->segments) + 1 && ! $this->silent) { throw HTTPException::forURISegmentOutOfRange($number); } // The segment should treat the array as 1-based for the user // but we still have to deal with a zero-based array. $number--; return $this->segments[$number] ?? $default; } /** * Set the value of a specific segment of the URI path. * Allows to set only existing segments or add new one. * * Note: Method not in PSR-7 * * @param int $number Segment number starting at 1 * @param int|string $value * * @return $this */ public function setSegment(int $number, $value) { if ($number < 1) { throw HTTPException::forURISegmentOutOfRange($number); } if ($number > count($this->segments) + 1) { if ($this->silent) { return $this; } throw HTTPException::forURISegmentOutOfRange($number); } // The segment should treat the array as 1-based for the user // but we still have to deal with a zero-based array. $number--; $this->segments[$number] = $value; return $this->refreshPath(); } /** * Returns the total number of segments. * * Note: Method not in PSR-7 */ public function getTotalSegments(): int { return count($this->segments); } /** * Formats the URI as a string. * * Warning: For backwards-compatability this method * assumes URIs with the same host as baseURL should * be relative to the project's configuration. * This aspect of __toString() is deprecated and should be avoided. */ public function __toString(): string { $path = $this->getPath(); $scheme = $this->getScheme(); // If the hosts matches then assume this should be relative to baseURL [$scheme, $path] = $this->changeSchemeAndPath($scheme, $path); return static::createURIString( $scheme, $this->getAuthority(), $path, // Absolute URIs should use a "/" for an empty path $this->getQuery(), $this->getFragment(), ); } /** * Change the path (and scheme) assuming URIs with the same host as baseURL * should be relative to the project's configuration. * * @return array{string, string} * * @deprecated This method will be deleted. */ private function changeSchemeAndPath(string $scheme, string $path): array { // Check if this is an internal URI $config = config(App::class); $baseUri = new self($config->baseURL); if ( str_starts_with($this->getScheme(), 'http') && $this->getHost() === $baseUri->getHost() ) { // Check for additional segments $basePath = trim($baseUri->getPath(), '/') . '/'; $trimPath = ltrim($path, '/'); if ($basePath !== '/' && ! str_starts_with($trimPath, $basePath)) { $path = $basePath . $trimPath; } // Check for forced HTTPS if ($config->forceGlobalSecureRequests) { $scheme = 'https'; } } return [$scheme, $path]; } /** * Parses the given string and saves the appropriate authority pieces. * * Note: Method not in PSR-7 * * @return $this */ public function setAuthority(string $str) { $parts = parse_url($str); if (! isset($parts['path'])) { $parts['path'] = $this->getPath(); } if (! isset($parts['host']) && $parts['path'] !== '') { $parts['host'] = $parts['path']; unset($parts['path']); } $this->applyParts($parts); return $this; } /** * Sets the scheme for this URI. * * Because of the large number of valid schemes we cannot limit this * to only http or https. * * @see https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml * * @return $this * * @deprecated 4.4.0 Use `withScheme()` instead. */ public function setScheme(string $str) { $str = strtolower($str); $this->scheme = preg_replace('#:(//)?$#', '', $str); return $this; } /** * Return an instance with the specified scheme. * * This method MUST retain the state of the current instance, and return * an instance that contains the specified scheme. * * Implementations MUST support the schemes "http" and "https" case * insensitively, and MAY accommodate other schemes if required. * * An empty scheme is equivalent to removing the scheme. * * @param string $scheme The scheme to use with the new instance. * * @return static A new instance with the specified scheme. * * @throws InvalidArgumentException for invalid or unsupported schemes. */ public function withScheme(string $scheme) { $uri = clone $this; $scheme = strtolower($scheme); $uri->scheme = preg_replace('#:(//)?$#', '', $scheme); return $uri; } /** * Sets the userInfo/Authority portion of the URI. * * @param string $user The user's username * @param string $pass The user's password * * @return $this * * @TODO PSR-7: Should be `withUserInfo($user, $password = null)`. */ public function setUserInfo(string $user, string $pass) { $this->user = trim($user); $this->password = trim($pass); return $this; } /** * Sets the host name to use. * * @return $this * * @TODO PSR-7: Should be `withHost($host)`. */ public function setHost(string $str) { $this->host = trim($str); return $this; } /** * Sets the port portion of the URI. * * @return $this * * @TODO PSR-7: Should be `withPort($port)`. */ public function setPort(?int $port = null) { if ($port === null) { return $this; } if ($port > 0 && $port <= 65535) { $this->port = $port; return $this; } if ($this->silent) { return $this; } throw HTTPException::forInvalidPort($port); } /** * Sets the path portion of the URI. * * @return $this * * @TODO PSR-7: Should be `withPath($port)`. */ public function setPath(string $path) { $this->path = $this->filterPath($path); $tempPath = trim($this->path, '/'); $this->segments = ($tempPath === '') ? [] : explode('/', $tempPath); return $this; } /** * Sets the current baseURL. * * @interal * * @deprecated Use SiteURI instead. */ public function setBaseURL(string $baseURL): void { $this->baseURL = $baseURL; } /** * Returns the current baseURL. * * @interal * * @deprecated Use SiteURI instead. */ public function getBaseURL(): string { if ($this->baseURL === null) { throw new BadMethodCallException('The $baseURL is not set.'); } return $this->baseURL; } /** * Sets the path portion of the URI based on segments. * * @return $this * * @deprecated This method will be private. */ public function refreshPath() { $this->path = $this->filterPath(implode('/', $this->segments)); $tempPath = trim($this->path, '/'); $this->segments = $tempPath === '' ? [] : explode('/', $tempPath); return $this; } /** * Sets the query portion of the URI, while attempting * to clean the various parts of the query keys and values. * * @return $this * * @TODO PSR-7: Should be `withQuery($query)`. */ public function setQuery(string $query) { if (str_contains($query, '#')) { if ($this->silent) { return $this; } throw HTTPException::forMalformedQueryString(); } // Can't have leading ? if ($query !== '' && str_starts_with($query, '?')) { $query = substr($query, 1); } if ($this->rawQueryString) { $this->query = $this->parseStr($query); } else { parse_str($query, $this->query); } return $this; } /** * A convenience method to pass an array of items in as the Query * portion of the URI. * * @return URI * * @TODO: PSR-7: Should be `withQueryParams(array $query)` */ public function setQueryArray(array $query) { $query = http_build_query($query); return $this->setQuery($query); } /** * Adds a single new element to the query vars. * * Note: Method not in PSR-7 * * @param int|string|null $value * * @return $this */ public function addQuery(string $key, $value = null) { $this->query[$key] = $value; return $this; } /** * Removes one or more query vars from the URI. * * Note: Method not in PSR-7 * * @param string ...$params * * @return $this */ public function stripQuery(...$params) { foreach ($params as $param) { unset($this->query[$param]); } return $this; } /** * Filters the query variables so that only the keys passed in * are kept. The rest are removed from the object. * * Note: Method not in PSR-7 * * @param string ...$params * * @return $this */ public function keepQuery(...$params) { $temp = []; foreach ($this->query as $key => $value) { if (! in_array($key, $params, true)) { continue; } $temp[$key] = $value; } $this->query = $temp; return $this; } /** * Sets the fragment portion of the URI. * * @see https://tools.ietf.org/html/rfc3986#section-3.5 * * @return $this * * @TODO PSR-7: Should be `withFragment($fragment)`. */ public function setFragment(string $string) { $this->fragment = trim($string, '# '); return $this; } /** * Encodes any dangerous characters, and removes dot segments. * While dot segments have valid uses according to the spec, * this URI class does not allow them. */ protected function filterPath(?string $path = null): string { $orig = $path; // Decode/normalize percent-encoded chars so // we can always have matching for Routes, etc. $path = urldecode($path); // Remove dot segments $path = self::removeDotSegments($path); // Fix up some leading slash edge cases... if (str_starts_with($orig, './')) { $path = '/' . $path; } if (str_starts_with($orig, '../')) { $path = '/' . $path; } // Encode characters $path = preg_replace_callback( '/(?:[^' . static::CHAR_UNRESERVED . ':@&=\+\$,\/;%]+|%(?![A-Fa-f0-9]{2}))/', static fn (array $matches): string => rawurlencode($matches[0]), $path, ); return $path; } /** * 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 * * @return void */ protected function applyParts(array $parts) { 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']; } if (isset($parts['path']) && $parts['path'] !== '') { $tempPath = trim($parts['path'], '/'); $this->segments = $tempPath === '' ? [] : explode('/', $tempPath); } } /** * Combines one URI string with this one based on the rules set out in * RFC 3986 Section 2 * * @see http://tools.ietf.org/html/rfc3986#section-5.2 * * @return URI */ public function resolveRelativeURI(string $uri) { /* * NOTE: We don't use removeDotSegments in this * algorithm since it's already done by this line! */ $relative = new self(); $relative->setURI($uri); if ($relative->getScheme() === $this->getScheme()) { $relative->setScheme(''); } $transformed = clone $relative; // 5.2.2 Transform References in a non-strict method (no scheme) if ($relative->getAuthority() !== '') { $transformed ->setAuthority($relative->getAuthority()) ->setPath($relative->getPath()) ->setQuery($relative->getQuery()); } else { if ($relative->getPath() === '') { $transformed->setPath($this->getPath()); if ($relative->getQuery() !== '') { $transformed->setQuery($relative->getQuery()); } else { $transformed->setQuery($this->getQuery()); } } else { if (str_starts_with($relative->getPath(), '/')) { $transformed->setPath($relative->getPath()); } else { $transformed->setPath($this->mergePaths($this, $relative)); } $transformed->setQuery($relative->getQuery()); } $transformed->setAuthority($this->getAuthority()); } $transformed->setScheme($this->getScheme()); $transformed->setFragment($relative->getFragment()); return $transformed; } /** * Given 2 paths, will merge them according to rules set out in RFC 2986, * Section 5.2 * * @see http://tools.ietf.org/html/rfc3986#section-5.2.3 */ protected function mergePaths(self $base, self $reference): string { if ($base->getAuthority() !== '' && $base->getPath() === '') { return '/' . ltrim($reference->getPath(), '/ '); } $path = explode('/', $base->getPath()); if ($path[0] === '') { unset($path[0]); } array_pop($path); $path[] = $reference->getPath(); return implode('/', $path); } /** * This is equivalent to the native PHP parse_str() function. * This version allows the dot to be used as a key of the query string. * * @return array<string, string> */ protected function parseStr(string $query): array { $return = []; $query = explode('&', $query); $params = array_map(static fn (string $chunk): ?string => preg_replace_callback( '/^(?<key>[^&=]+?)(?:\[[^&=]*\])?=(?<value>[^&=]+)/', static fn (array $match): string => str_replace($match['key'], bin2hex($match['key']), $match[0]), urldecode($chunk), ), $query); $params = implode('&', $params); parse_str($params, $result); foreach ($result as $key => $value) { // Array key might be int $return[hex2bin((string) $key)] = $value; } return $return; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/CURLRequest.php
system/HTTP/CURLRequest.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 Config\App; use Config\CURLRequest as ConfigCURLRequest; /** * A lightweight HTTP client for sending synchronous HTTP requests via cURL. * * @see \CodeIgniter\HTTP\CURLRequestTest */ class CURLRequest extends OutgoingRequest { /** * The response object associated with this request * * @var ResponseInterface|null */ protected $response; /** * The original response object associated with this request * * @var ResponseInterface|null */ protected $responseOrig; /** * The URI associated with this request * * @var URI */ protected $baseURI; /** * The setting values * * @var array */ protected $config; /** * The default setting values * * @var array */ protected $defaultConfig = [ 'timeout' => 0.0, 'connect_timeout' => 150, 'debug' => false, 'verify' => true, ]; /** * Default values for when 'allow_redirects' * option is true. * * @var array */ protected $redirectDefaults = [ 'max' => 5, 'strict' => true, 'protocols' => [ 'http', 'https', ], ]; /** * The number of milliseconds to delay before * sending the request. * * @var float */ protected $delay = 0.0; /** * The default options from the constructor. Applied to all requests. */ private readonly array $defaultOptions; /** * Whether share options between requests or not. * * If true, all the options won't be reset between requests. * It may cause an error request with unnecessary headers. */ private readonly bool $shareOptions; /** * Takes an array of options to set the following possible class properties: * * - baseURI * - timeout * - any other request options to use as defaults. * * @param array<string, mixed> $options */ public function __construct(App $config, URI $uri, ?ResponseInterface $response = null, array $options = []) { if (! function_exists('curl_version')) { throw HTTPException::forMissingCurl(); // @codeCoverageIgnore } parent::__construct(Method::GET, $uri); $this->responseOrig = $response ?? new Response($config); // Remove the default Content-Type header. $this->responseOrig->removeHeader('Content-Type'); $this->baseURI = $uri->useRawQueryString(); $this->defaultOptions = $options; $this->shareOptions = config(ConfigCURLRequest::class)->shareOptions ?? true; $this->config = $this->defaultConfig; $this->parseOptions($options); } /** * Sends an HTTP request to the specified $url. If this is a relative * URL, it will be merged with $this->baseURI to form a complete URL. * * @param string $method HTTP method */ public function request($method, string $url, array $options = []): ResponseInterface { $this->response = clone $this->responseOrig; $this->parseOptions($options); $url = $this->prepareURL($url); $method = esc(strip_tags($method)); $this->send($method, $url); if ($this->shareOptions === false) { $this->resetOptions(); } return $this->response; } /** * Reset all options to default. * * @return void */ protected function resetOptions() { // Reset headers $this->headers = []; $this->headerMap = []; // Reset body $this->body = null; // Reset configs $this->config = $this->defaultConfig; // Set the default options for next request $this->parseOptions($this->defaultOptions); } /** * Convenience method for sending a GET request. */ public function get(string $url, array $options = []): ResponseInterface { return $this->request(Method::GET, $url, $options); } /** * Convenience method for sending a DELETE request. */ public function delete(string $url, array $options = []): ResponseInterface { return $this->request('DELETE', $url, $options); } /** * Convenience method for sending a HEAD request. */ public function head(string $url, array $options = []): ResponseInterface { return $this->request('HEAD', $url, $options); } /** * Convenience method for sending an OPTIONS request. */ public function options(string $url, array $options = []): ResponseInterface { return $this->request('OPTIONS', $url, $options); } /** * Convenience method for sending a PATCH request. */ public function patch(string $url, array $options = []): ResponseInterface { return $this->request('PATCH', $url, $options); } /** * Convenience method for sending a POST request. */ public function post(string $url, array $options = []): ResponseInterface { return $this->request(Method::POST, $url, $options); } /** * Convenience method for sending a PUT request. */ public function put(string $url, array $options = []): ResponseInterface { return $this->request(Method::PUT, $url, $options); } /** * Set the HTTP Authentication. * * @param string $type basic or digest * * @return $this */ public function setAuth(string $username, string $password, string $type = 'basic') { $this->config['auth'] = [ $username, $password, $type, ]; return $this; } /** * Set form data to be sent. * * @param bool $multipart Set TRUE if you are sending CURLFiles * * @return $this */ public function setForm(array $params, bool $multipart = false) { if ($multipart) { $this->config['multipart'] = $params; } else { $this->config['form_params'] = $params; } return $this; } /** * Set JSON data to be sent. * * @param array|bool|float|int|object|string|null $data * * @return $this */ public function setJSON($data) { $this->config['json'] = $data; return $this; } /** * Sets the correct settings based on the options array * passed in. * * @return void */ protected function parseOptions(array $options) { if (array_key_exists('baseURI', $options)) { $this->baseURI = $this->baseURI->setURI($options['baseURI']); unset($options['baseURI']); } if (array_key_exists('headers', $options) && is_array($options['headers'])) { foreach ($options['headers'] as $name => $value) { $this->setHeader($name, $value); } unset($options['headers']); } if (array_key_exists('delay', $options)) { // Convert from the milliseconds passed in // to the seconds that sleep requires. $this->delay = (float) $options['delay'] / 1000; unset($options['delay']); } if (array_key_exists('body', $options)) { $this->setBody($options['body']); unset($options['body']); } foreach ($options as $key => $value) { $this->config[$key] = $value; } } /** * If the $url is a relative URL, will attempt to create * a full URL by prepending $this->baseURI to it. */ protected function prepareURL(string $url): string { // If it's a full URI, then we have nothing to do here... if (str_contains($url, '://')) { return $url; } $uri = $this->baseURI->resolveRelativeURI($url); // Create the string instead of casting to prevent baseURL muddling return URI::createURIString( $uri->getScheme(), $uri->getAuthority(), $uri->getPath(), $uri->getQuery(), $uri->getFragment(), ); } /** * Fires the actual cURL request. * * @return ResponseInterface */ public function send(string $method, string $url) { // Reset our curl options so we're on a fresh slate. $curlOptions = []; if (! empty($this->config['query']) && is_array($this->config['query'])) { // This is likely too naive a solution. // Should look into handling when $url already // has query vars on it. $url .= '?' . http_build_query($this->config['query']); unset($this->config['query']); } $curlOptions[CURLOPT_URL] = $url; $curlOptions[CURLOPT_RETURNTRANSFER] = true; $curlOptions[CURLOPT_HEADER] = true; $curlOptions[CURLOPT_FRESH_CONNECT] = true; // Disable @file uploads in post data. $curlOptions[CURLOPT_SAFE_UPLOAD] = true; $curlOptions = $this->setCURLOptions($curlOptions, $this->config); $curlOptions = $this->applyMethod($method, $curlOptions); $curlOptions = $this->applyRequestHeaders($curlOptions); // Do we need to delay this request? if ($this->delay > 0) { usleep((int) $this->delay * 1_000_000); } $output = $this->sendRequest($curlOptions); // Set the string we want to break our response from $breakString = "\r\n\r\n"; // Remove all intermediate responses $output = $this->removeIntermediateResponses($output, $breakString); // Split out our headers and body $break = strpos($output, $breakString); if ($break !== false) { // Our headers $headers = explode("\n", substr($output, 0, $break)); $this->setResponseHeaders($headers); // Our body $body = substr($output, $break + 4); $this->response->setBody($body); } else { $this->response->setBody($output); } return $this->response; } /** * Adds $this->headers to the cURL request. */ protected function applyRequestHeaders(array $curlOptions = []): array { if (empty($this->headers)) { return $curlOptions; } $set = []; foreach (array_keys($this->headers) as $name) { $set[] = $name . ': ' . $this->getHeaderLine($name); } $curlOptions[CURLOPT_HTTPHEADER] = $set; return $curlOptions; } /** * Apply method */ protected function applyMethod(string $method, array $curlOptions): array { $this->method = $method; $curlOptions[CURLOPT_CUSTOMREQUEST] = $method; $size = strlen($this->body ?? ''); // Have content? if ($size > 0) { return $this->applyBody($curlOptions); } if ($method === Method::PUT || $method === Method::POST) { // See http://tools.ietf.org/html/rfc7230#section-3.3.2 if ($this->header('content-length') === null && ! isset($this->config['multipart'])) { $this->setHeader('Content-Length', '0'); } } elseif ($method === 'HEAD') { $curlOptions[CURLOPT_NOBODY] = 1; } return $curlOptions; } /** * Apply body */ protected function applyBody(array $curlOptions = []): array { if (! empty($this->body)) { $curlOptions[CURLOPT_POSTFIELDS] = (string) $this->getBody(); } return $curlOptions; } /** * Parses the header retrieved from the cURL response into * our Response object. * * @return void */ protected function setResponseHeaders(array $headers = []) { foreach ($headers as $header) { if (($pos = strpos($header, ':')) !== false) { $title = trim(substr($header, 0, $pos)); $value = trim(substr($header, $pos + 1)); if ($this->response instanceof Response) { $this->response->addHeader($title, $value); } else { $this->response->setHeader($title, $value); } } elseif (str_starts_with($header, 'HTTP')) { preg_match('#^HTTP\/([12](?:\.[01])?) (\d+) (.+)#', $header, $matches); if (isset($matches[1])) { $this->response->setProtocolVersion($matches[1]); } if (isset($matches[2])) { $this->response->setStatusCode((int) $matches[2], $matches[3] ?? null); } } } } /** * Set CURL options * * @return array * * @throws InvalidArgumentException */ protected function setCURLOptions(array $curlOptions = [], array $config = []) { // Auth Headers if (! empty($config['auth'])) { $curlOptions[CURLOPT_USERPWD] = $config['auth'][0] . ':' . $config['auth'][1]; if (! empty($config['auth'][2]) && strtolower($config['auth'][2]) === 'digest') { $curlOptions[CURLOPT_HTTPAUTH] = CURLAUTH_DIGEST; } else { $curlOptions[CURLOPT_HTTPAUTH] = CURLAUTH_BASIC; } } // Certificate if (! empty($config['cert'])) { $cert = $config['cert']; if (is_array($cert)) { $curlOptions[CURLOPT_SSLCERTPASSWD] = $cert[1]; $cert = $cert[0]; } if (! is_file($cert)) { throw HTTPException::forSSLCertNotFound($cert); } $curlOptions[CURLOPT_SSLCERT] = $cert; } // SSL Verification if (isset($config['verify'])) { if (is_string($config['verify'])) { $file = realpath($config['verify']) ?: $config['verify']; if (! is_file($file)) { throw HTTPException::forInvalidSSLKey($config['verify']); } $curlOptions[CURLOPT_CAINFO] = $file; $curlOptions[CURLOPT_SSL_VERIFYPEER] = true; $curlOptions[CURLOPT_SSL_VERIFYHOST] = 2; } elseif (is_bool($config['verify'])) { $curlOptions[CURLOPT_SSL_VERIFYPEER] = $config['verify']; $curlOptions[CURLOPT_SSL_VERIFYHOST] = $config['verify'] ? 2 : 0; } } // Proxy if (isset($config['proxy'])) { $curlOptions[CURLOPT_HTTPPROXYTUNNEL] = true; $curlOptions[CURLOPT_PROXY] = $config['proxy']; } // Debug if ($config['debug']) { $curlOptions[CURLOPT_VERBOSE] = 1; $curlOptions[CURLOPT_STDERR] = is_string($config['debug']) ? fopen($config['debug'], 'a+b') : fopen('php://stderr', 'wb'); } // Decode Content if (! empty($config['decode_content'])) { $accept = $this->getHeaderLine('Accept-Encoding'); if ($accept !== '') { $curlOptions[CURLOPT_ENCODING] = $accept; } else { $curlOptions[CURLOPT_ENCODING] = ''; $curlOptions[CURLOPT_HTTPHEADER] = 'Accept-Encoding'; } } // Allow Redirects if (array_key_exists('allow_redirects', $config)) { $settings = $this->redirectDefaults; if (is_array($config['allow_redirects'])) { $settings = array_merge($settings, $config['allow_redirects']); } if ($config['allow_redirects'] === false) { $curlOptions[CURLOPT_FOLLOWLOCATION] = 0; } else { $curlOptions[CURLOPT_FOLLOWLOCATION] = 1; $curlOptions[CURLOPT_MAXREDIRS] = $settings['max']; if ($settings['strict'] === true) { $curlOptions[CURLOPT_POSTREDIR] = 1 | 2 | 4; } $protocols = 0; foreach ($settings['protocols'] as $proto) { $protocols += constant('CURLPROTO_' . strtoupper($proto)); } $curlOptions[CURLOPT_REDIR_PROTOCOLS] = $protocols; } } // Timeout $curlOptions[CURLOPT_TIMEOUT_MS] = (float) $config['timeout'] * 1000; // Connection Timeout $curlOptions[CURLOPT_CONNECTTIMEOUT_MS] = (float) $config['connect_timeout'] * 1000; // Post Data - application/x-www-form-urlencoded if (! empty($config['form_params']) && is_array($config['form_params'])) { $postFields = http_build_query($config['form_params']); $curlOptions[CURLOPT_POSTFIELDS] = $postFields; // Ensure content-length is set, since CURL doesn't seem to // calculate it when HTTPHEADER is set. $this->setHeader('Content-Length', (string) strlen($postFields)); $this->setHeader('Content-Type', 'application/x-www-form-urlencoded'); } // Post Data - multipart/form-data if (! empty($config['multipart']) && is_array($config['multipart'])) { // setting the POSTFIELDS option automatically sets multipart $curlOptions[CURLOPT_POSTFIELDS] = $config['multipart']; } // HTTP Errors $curlOptions[CURLOPT_FAILONERROR] = array_key_exists('http_errors', $config) ? (bool) $config['http_errors'] : true; // JSON if (isset($config['json'])) { // Will be set as the body in `applyBody()` $json = json_encode($config['json']); $this->setBody($json); $this->setHeader('Content-Type', 'application/json'); $this->setHeader('Content-Length', (string) strlen($json)); } // Resolve IP if (array_key_exists('force_ip_resolve', $config)) { $curlOptions[CURLOPT_IPRESOLVE] = match ($config['force_ip_resolve']) { 'v4' => CURL_IPRESOLVE_V4, 'v6' => CURL_IPRESOLVE_V6, default => CURL_IPRESOLVE_WHATEVER, }; } // version if (! empty($config['version'])) { $version = sprintf('%.1F', $config['version']); if ($version === '1.0') { $curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0; } elseif ($version === '1.1') { $curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1; } elseif ($version === '2.0') { $curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_2_0; } elseif ($version === '3.0') { if (! defined('CURL_HTTP_VERSION_3')) { define('CURL_HTTP_VERSION_3', 30); } $curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_3; } } // Cookie if (isset($config['cookie'])) { $curlOptions[CURLOPT_COOKIEJAR] = $config['cookie']; $curlOptions[CURLOPT_COOKIEFILE] = $config['cookie']; } // User Agent if (isset($config['user_agent'])) { $curlOptions[CURLOPT_USERAGENT] = $config['user_agent']; } return $curlOptions; } /** * Does the actual work of initializing cURL, setting the options, * and grabbing the output. * * @param array<int, mixed> $curlOptions * * @codeCoverageIgnore */ protected function sendRequest(array $curlOptions = []): string { $ch = curl_init(); curl_setopt_array($ch, $curlOptions); // Send the request and wait for a response. $output = curl_exec($ch); if ($output === false) { throw HTTPException::forCurlError((string) curl_errno($ch), curl_error($ch)); } curl_close($ch); return $output; } private function removeIntermediateResponses(string $output, string $breakString): string { while (true) { // Check if we should remove the current response if ($this->shouldRemoveCurrentResponse($output, $breakString)) { $breakStringPos = strpos($output, $breakString); if ($breakStringPos !== false) { $output = substr($output, $breakStringPos + 4); continue; } } // No more intermediate responses to remove break; } return $output; } /** * Check if the current response (at the beginning of output) should be removed. */ private function shouldRemoveCurrentResponse(string $output, string $breakString): bool { // HTTP/x.x 1xx responses (Continue, Processing, etc.) if (preg_match('/^HTTP\/\d+(?:\.\d+)?\s+1\d\d\s/', $output)) { return true; } // HTTP/x.x 200 Connection established (proxy responses) if (preg_match('/^HTTP\/\d+(?:\.\d+)?\s+200\s+Connection\s+established/i', $output)) { return true; } // HTTP/x.x 3xx responses (redirects) - only if redirects are allowed $allowRedirects = isset($this->config['allow_redirects']) && $this->config['allow_redirects'] !== false; if ($allowRedirects && preg_match('/^HTTP\/\d+(?:\.\d+)?\s+3\d\d\s/', $output)) { // Check if there's a Location header $breakStringPos = strpos($output, $breakString); if ($breakStringPos !== false) { $headerSection = substr($output, 0, $breakStringPos); $headers = explode("\n", $headerSection); foreach ($headers as $header) { if (str_starts_with(strtolower($header), 'location:')) { return true; // Found location header, this is a redirect to remove } } } } // Digest auth challenges - only remove if there's another response after if (isset($this->config['auth'][2]) && $this->config['auth'][2] === 'digest') { $breakStringPos = strpos($output, $breakString); if ($breakStringPos !== false) { $headerSection = substr($output, 0, $breakStringPos); if (str_contains($headerSection, 'WWW-Authenticate: Digest')) { $nextBreakPos = strpos($output, $breakString, $breakStringPos + 4); return $nextBreakPos !== false; // Only remove if there's another response } } } return false; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/HTTP/Request.php
system/HTTP/Request.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\App; /** * Representation of an incoming, server-side HTTP request. * * @see \CodeIgniter\HTTP\RequestTest */ class Request extends OutgoingRequest implements RequestInterface { use RequestTrait; /** * Constructor. * * @param App $config */ public function __construct($config = null) { $this->config = $config ?? config(App::class); if (empty($this->method)) { $this->method = $this->getServer('REQUEST_METHOD') ?? Method::GET; } if (empty($this->uri)) { $this->uri = new URI(); } } /** * Sets the request method. Used when spoofing the request. * * @return $this * * @deprecated 4.0.5 Use withMethod() instead for immutability * * @codeCoverageIgnore */ 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 */ public function getUri() { return $this->uri; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false