Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Continue review of Utility classes #354

Merged
merged 4 commits into from
Jan 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Toolkit/Core/ErrorHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ public function silencePath(string $path, int $levels = \E_DEPRECATED | \E_USER_

$path = File::realpath($path);
$this->silencePattern(
'@^' . preg_quote($path, '@') . (is_dir($path) ? '/' : '$') . '@',
'@^' . Regex::quote($path, '@') . (is_dir($path) ? '/' : '$') . '@',
$levels
);
return $this;
Expand Down
2 changes: 1 addition & 1 deletion src/Toolkit/Sli/Command/AnalyseClass.php
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ protected function run(string ...$args)
$block = $blockPrefix . str_replace("\n", $replace, $block);
}
if ($trimmed !== $blockPrefix) {
$regex = preg_quote($blockPrefix, '/');
$regex = Regex::quote($blockPrefix, '/');
$block = Regex::replace("/(?<=\n|^){$regex}(?=\n|\$)/D", $trimmed, $block);
}
if (!$continue) {
Expand Down
28 changes: 2 additions & 26 deletions src/Toolkit/Utility/Debug.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace Salient\Utility;

/**
* Get information about the call stack
* Get data from the call stack
*
* @api
*/
Expand All @@ -21,30 +21,6 @@ final class Debug extends AbstractUtility
* - `function`
* - `line`
*
* The return values below, for example, would implode to:
* - `Salient\Tests\Utility\Debug\GetCallerClass->getCallerViaMethod:23`
* - `/path/to/tests/fixtures/Toolkit/Utility/Debug/GetCallerFile1.php::{closure}:29`
*
* ```
* <?php
* [
* 'namespace' => 'Salient\\Tests\\Utility\\Debug\\',
* 'class' => 'GetCallerClass',
* '->',
* 'function' => 'getCallerViaMethod',
* ':',
* 'line' => 23,
* ];
*
* [
* 'file' => '/path/to/tests/fixtures/Toolkit/Utility/Debug/GetCallerFile1.php',
* '::',
* 'function' => '{closure}',
* ':',
* 'line' => 29,
* ];
* ```
*
* For an earlier frame in the call stack, set `$depth` to `1` or higher.
*
* @return array{namespace?:string,class?:string,file?:string,0?:string,function?:string,1?:string,line?:int}
Expand Down Expand Up @@ -76,7 +52,7 @@ public static function getCaller(int $depth = 0): array
$namespace = Get::namespace($closure ?? $frame['function']);
$class = '';
}
// NB: `function` and `class` are both namespaced for closures in
// `function` and `class` are both namespaced for closures in
// namespaced classes
$function = isset($closure)
? '{closure}'
Expand Down
22 changes: 13 additions & 9 deletions src/Toolkit/Utility/Env.php
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ public static function getInt(string $name, $default = false): ?int
if ($value === false) {
return self::_default($name, $default, false);
}
$value = trim($value);
if (!Regex::match('/^' . Regex::INTEGER_STRING . '$/', $value)) {
throw new InvalidEnvironmentException(
sprintf('Value is not an integer: %s', $name)
Expand All @@ -212,7 +213,8 @@ public static function getBool(string $name, $default = -1): ?bool
if ($value === false) {
return self::_default($name, $default, -1);
}
if (trim($value) === '') {
$value = trim($value);
if ($value === '') {
return false;
}
if (!Regex::match(
Expand Down Expand Up @@ -268,13 +270,13 @@ public static function getIntList(string $name, $default = false, string $delimi
if (trim($value) === '') {
return [];
}
$regex = sprintf('/^%s(?:%s%1$s)*+$/', Regex::INTEGER_STRING, preg_quote($delimiter, '/'));
if (!Regex::match($regex, $value)) {
throw new InvalidEnvironmentException(
sprintf('Value is not an integer list: %s', $name)
);
}
foreach (explode($delimiter, $value) as $value) {
$value = trim($value);
if (!Regex::match('/^' . Regex::INTEGER_STRING . '$/', $value)) {
throw new InvalidEnvironmentException(
sprintf('Value is not an integer list: %s', $name)
);
}
$list[] = (int) $value;
}
return $list;
Expand Down Expand Up @@ -309,7 +311,8 @@ public static function getNullableInt(string $name, $default = false): ?int
if ($value === false) {
return self::_default($name, $default, false);
}
if (trim($value) === '') {
$value = trim($value);
if ($value === '') {
return null;
}
if (!Regex::match('/^' . Regex::INTEGER_STRING . '$/', $value)) {
Expand All @@ -333,7 +336,8 @@ public static function getNullableBool(string $name, $default = -1): ?bool
if ($value === false) {
return self::_default($name, $default, -1);
}
if (trim($value) === '') {
$value = trim($value);
if ($value === '') {
return null;
}
if (!Regex::match(
Expand Down
2 changes: 2 additions & 0 deletions src/Toolkit/Utility/Exception/AbstractUtilityException.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
abstract class AbstractUtilityException extends RuntimeException
{
/**
* @api
*
* @codeCoverageIgnore
*/
public function __construct(string $message = '', ?Throwable $previous = null)
Expand Down
91 changes: 31 additions & 60 deletions src/Toolkit/Utility/Exception/PcreErrorException.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Salient\Utility\Exception;

use Salient\Utility\Arr;
use Salient\Utility\Format;
use Stringable;

/**
Expand All @@ -19,9 +21,6 @@ class PcreErrorException extends AbstractUtilityException
\PREG_JIT_STACKLIMIT_ERROR => 'JIT stack limit exhausted',
];

protected int $PcreError;
protected string $PcreErrorMessage;
protected string $Function;
/** @var array<string,callable>|string[]|string */
protected $Pattern;
/** @var array<int|float|string|bool|Stringable|null>|string */
Expand All @@ -30,6 +29,8 @@ class PcreErrorException extends AbstractUtilityException
private static array $ErrorNameMap;

/**
* @api
*
* @param array<string,callable>|string[]|string $pattern
* @param array<int|float|string|bool|Stringable|null>|string $subject
*/
Expand All @@ -40,87 +41,57 @@ public function __construct(?int $error, string $function, $pattern, $subject)
? self::ERROR_MESSAGE_MAP[$error] ?? 'Unknown error'
: preg_last_error_msg();

$this->PcreError = $error;
$this->PcreErrorMessage = $message;
$this->Function = $function;
$this->Pattern = $pattern;
$this->Subject = $subject;

parent::__construct(sprintf(
'Call to %s() failed with %s (%s)',
$function,
(self::$ErrorNameMap ??= $this->getErrorNameMap())[$error],
(self::$ErrorNameMap ??= self::getErrorNameMap())[$error] ?? "#$error",
$message,
));
}

/**
* Get the exception's PCRE error code
*/
public function getPcreError(): int
{
return $this->PcreError;
}

/**
* Get the name of the exception's PCRE error
*/
public function getPcreErrorName(): string
{
return self::$ErrorNameMap[$this->PcreError];
}

/**
* Get the exception's PCRE error message
*/
public function getPcreErrorMessage(): string
{
return $this->PcreErrorMessage;
}

/**
* Get the name of the PCRE function that failed
*/
public function getFunction(): string
{
return $this->Function;
}

/**
* Get the pattern passed to the PCRE function
*
* @return array<string,callable>|string[]|string
* @inheritDoc
*/
public function getPattern()
public function __toString(): string
{
return $this->Pattern;
}
$detail = '';
foreach ([
'Pattern' => is_array($this->Pattern)
? array_map(
fn($value) => is_string($value) ? $value : '<callable>',
$this->Pattern,
)
: $this->Pattern,
'Subject' => $this->Subject,
] as $key => $value) {
if (is_array($value)) {
$value = Arr::isList($value)
? Format::list($value)
: Format::array($value);
}
$detail .= sprintf("\n\n%s:\n%s", $key, rtrim($value, "\n"));
}

/**
* Get the subject passed to the PCRE function
*
* @return array<int|float|string|bool|Stringable|null>|string
*/
public function getSubject()
{
return $this->Subject;
return parent::__toString() . $detail;
}

/**
* @return array<int,string>
*/
private function getErrorNameMap(): array
private static function getErrorNameMap(): array
{
/** @var array<string,mixed> */
$constants = get_defined_constants(true)['pcre'];
$map = [];
foreach ($constants as $name => $value) {
if (substr($name, -6) !== '_ERROR') {
continue;
if (substr($name, -6) === '_ERROR') {
/** @var int $value */
$map[$value] = $name;
}
/** @var int $value */
$errors[$value] = $name;
}

return $errors ?? [];
return $map;
}
}
61 changes: 36 additions & 25 deletions src/Toolkit/Utility/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,22 @@
self::check(@chmod($filename, $permissions), 'chmod', $filename);
}

/**
* Rename a file or directory
*/
public static function rename(string $from, string $to): void

Check warning on line 109 in src/Toolkit/Utility/File.php

View check run for this annotation

Codecov / codecov/patch

src/Toolkit/Utility/File.php#L109

Added line #L109 was not covered by tests
{
self::check(@rename($from, $to), 'rename', null, null, $from, $to);

Check warning on line 111 in src/Toolkit/Utility/File.php

View check run for this annotation

Codecov / codecov/patch

src/Toolkit/Utility/File.php#L111

Added line #L111 was not covered by tests
}

/**
* Create a symbolic link to a target with a given name
*/
public static function symlink(string $target, string $link): void

Check warning on line 117 in src/Toolkit/Utility/File.php

View check run for this annotation

Codecov / codecov/patch

src/Toolkit/Utility/File.php#L117

Added line #L117 was not covered by tests
{
self::check(@symlink($target, $link), 'symlink', null, null, $target, $link);

Check warning on line 119 in src/Toolkit/Utility/File.php

View check run for this annotation

Codecov / codecov/patch

src/Toolkit/Utility/File.php#L119

Added line #L119 was not covered by tests
}

/**
* Set file access and modification times
*/
Expand Down Expand Up @@ -144,33 +160,30 @@
}

/**
* Create a file if it doesn't exist
*
* To prevent access by an attacker before `$permissions` are applied,
* `$filename` is created with umask `0077`.
*
* File mode defaults and behaviour are similar to `install` on *nix.
* Safely create a file if it doesn't exist
*
* @param int $permissions Applied if `$filename` is created.
* @param int $dirPermissions Applied if `$filename`'s directory is created.
* Parent directories, if any, are created with file mode `0755`, or `0777 &
* ~umask()` if `$applyUmask` is `true`.
* Parent directories, if any, are created with file mode `0777 & ~umask()`,
* or `0755` if `$umaskApplies` is `false`.
*/
public static function create(
string $filename,
int $permissions = 0755,
int $dirPermissions = 0755,
bool $applyUmask = false
int $permissions = 0777,
int $dirPermissions = 0777,
bool $umaskApplies = true
): void {
if (is_file($filename)) {
return;
}
self::createDir(dirname($filename), $dirPermissions, $applyUmask);
self::createDir(dirname($filename), $dirPermissions, $umaskApplies);
$umask = umask();
if ($applyUmask) {
if ($umaskApplies) {
$permissions &= ~$umask;
}
try {
// Create the file without group or other permissions to prevent
// access by a bad actor before permissions are set
umask(077);
$handle = self::open($filename, 'x');
self::chmod($filename, $permissions);
Expand All @@ -181,34 +194,32 @@
}

/**
* Create a directory if it doesn't exist
*
* To prevent access by an attacker before `$permissions` are applied,
* `$directory` is created with umask `0077`.
*
* File mode defaults and behaviour are similar to `install` on *nix.
* Safely create a directory if it doesn't exist
*
* @param int $permissions Applied if `$directory` is created. Parent
* directories, if any, are created with file mode `0755`, or `0777 &
* ~umask()` if `$applyUmask` is `true`.
* directories, if any, are created with file mode `0777 & ~umask()`, or
* `0755` if `$umaskApplies` is `false`.
*/
public static function createDir(
string $directory,
int $permissions = 0755,
bool $applyUmask = false
int $permissions = 0777,
bool $umaskApplies = true
): void {
if (is_dir($directory)) {
return;
}
$parent = dirname($directory);
$umask = umask();
if ($applyUmask) {
if ($umaskApplies) {
$permissions &= ~$umask;
}
try {
if (!is_dir($parent)) {
umask(0);
self::mkdir($parent, $applyUmask ? 0777 & ~$umask : 0755, true);
$parentPerms = $umaskApplies
? 0777 & ~$umask
: 0755;
self::mkdir($parent, $parentPerms, true);
}
umask(077);
self::mkdir($directory);
Expand Down
Loading