Skip to content

Commit

Permalink
update file
Browse files Browse the repository at this point in the history
  • Loading branch information
juancristobalgd1 authored Jun 9, 2024
1 parent d555d4c commit c857d24
Show file tree
Hide file tree
Showing 7 changed files with 225 additions and 407 deletions.
30 changes: 21 additions & 9 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ function partials(string $partial_name, array $data = [])
$partialsPath = config('paths.partialsPath'); // Make sure we have our paths set up!
$partial_file = $partialsPath . DIRECTORY_SEPARATOR . $partial_name . '.php';
$partials = app()->view->file($partial_file, $data);

return $partials;
}
}
Expand All @@ -136,16 +136,16 @@ function partials(string $partial_name, array $data = [])
function cleanInput(mixed $data): mixed
{
return match (true) {
is_array($data) => array_map('cleanInput', $data),
is_array($data) => array_map('cleanInput', $data),
is_object($data) => cleanInput((array) $data),
is_email($data) => filter_var($data, FILTER_SANITIZE_EMAIL),
is_url($data) => filter_var($data, FILTER_SANITIZE_URL),
is_ip($data) => filter_var($data, FILTER_VALIDATE_IP),
is_email($data) => filter_var($data, FILTER_SANITIZE_EMAIL),
is_url($data) => filter_var($data, FILTER_SANITIZE_URL),
is_ip($data) => filter_var($data, FILTER_VALIDATE_IP),
is_string($data) => preg_replace('/[\x00-\x1F\x7F]/u', '', filter_var(trim($data), FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_NO_ENCODE_QUOTES)),
is_int($data) => filter_var($data, FILTER_SANITIZE_NUMBER_INT),
is_float($data) => filter_var($data, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION),
is_bool($data) => filter_var($data, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE),
is_null($data) => settype($data, 'NULL'),
is_int($data) => filter_var($data, FILTER_SANITIZE_NUMBER_INT),
is_float($data) => filter_var($data, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION),
is_bool($data) => filter_var($data, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE),
is_null($data) => settype($data, 'NULL'),

default => filter_var($data, FILTER_SANITIZE_SPECIAL_CHARS),
};
Expand Down Expand Up @@ -630,4 +630,16 @@ function esc(string $text): string
$brText = nl2br($encodedText);
return $brText;
}

}

if (!function_exists('csrf')) {
/**
* Generates a hidden input field with the CSRF token.
*/
function csrf(): string
{
return '<input type="hidden" name="_token" value="' . app()->getCsrfToken() . '">';
}

}
34 changes: 15 additions & 19 deletions src/libraries/Console/CLI.php
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ public static function input(?string $prefix = null): string
* @param array|string $validation Validation rules
* @return string The user input
*/
public static function prompt(string $field, $options = null, $validation = null, string $color = 'yellow'): string
public static function prompt(string $field, array|string $options = null, string|array $validation = null, string $color = 'yellow'): string
{
$extraOutput = '';
$default = '';
Expand All @@ -209,7 +209,7 @@ public static function prompt(string $field, $options = null, $validation = null

unset($opts[0]);

if (empty ($opts)) {
if (empty($opts)) {
$extraOutput = $extraOutputDefault;
} else {
$extraOutput = '[' . $extraOutputDefault . ', ' . implode(', ', $opts) . ']';
Expand Down Expand Up @@ -271,21 +271,17 @@ public static function promptByKey($text, array $options, $validation = null): s
/**
* Validate one prompt "field" at a time
*
* @param string $field Prompt "field" output
* @param string $value Input value
* @param array|string $rules Validation rules
*
*/
protected static function validate(string $field, string $value, $rules): bool
protected static function validate(string $value, array|string $rules): bool
{
$rules = ['input' => $rules];
$data = ['input' => $value];
$validator = Validator::make($rules, $data);
$validator = Validator::make(['input' => $value], ['input' => $rules]);

if ($validator->fails()) {
$msg = $validator->getFirstError();
static::error($msg);
exit();
static::error($validator->getFirstError());
return false; // instead of exiting, return false to indicate failure
}

return true;
Expand Down Expand Up @@ -642,7 +638,7 @@ public static function streamSupports(string $function, $resource): bool
public static function hasColorSupport($resource): bool
{
// Follow https://no-color.org/
if (isset ($_SERVER['NO_COLOR']) || getenv('NO_COLOR') !== false) {
if (isset($_SERVER['NO_COLOR']) || getenv('NO_COLOR') !== false) {
return false;
}

Expand All @@ -652,7 +648,7 @@ public static function hasColorSupport($resource): bool

if (static::isWindows()) {
return static::streamSupports('sapi_windows_vt100_support', $resource)
|| isset ($_SERVER['ANSICON'])
|| isset($_SERVER['ANSICON'])
|| getenv('ANSICON') !== false
|| getenv('ConEmuANSI') === 'ON'
|| getenv('TERM') === 'xterm';
Expand Down Expand Up @@ -769,7 +765,7 @@ public static function showProgress($thisStep = 1, int $totalSteps = 10)
*/
public static function wrap(?string $string = null, int $max = 0, int $padLeft = 0): string
{
if (empty ($string)) {
if (empty($string)) {
return '';
}

Expand Down Expand Up @@ -837,7 +833,7 @@ protected static function parseCommandLine()
$arg = ltrim($arg, '-');
$value = null;

if (isset ($args[$i + 1]) && mb_strpos($args[$i + 1], '-') !== 0) {
if (isset($args[$i + 1]) && mb_strpos($args[$i + 1], '-') !== 0) {
$value = $args[$i + 1];
$optionValue = true;
}
Expand Down Expand Up @@ -918,7 +914,7 @@ public static function getOptions(): array
*/
public static function getOptionString(bool $useLongOpts = false, bool $trim = false): string
{
if (empty (static::$options)) {
if (empty(static::$options)) {
return '';
}

Expand Down Expand Up @@ -957,7 +953,7 @@ public static function table(array $tbody, array $thead = [])
$tableRows = [];

// We need only indexes and not keys
if (!empty ($thead)) {
if (!empty($thead)) {
$tableRows[] = array_values($thead);
}

Expand Down Expand Up @@ -987,7 +983,7 @@ public static function table(array $tbody, array $thead = [])
// If the current column does not have a value among the larger ones
// or the value of this is greater than the existing one
// then, now, this assumes the maximum length
if (!isset ($maxColsLengths[$column]) || $allColsLengths[$row][$column] > $maxColsLengths[$column]) {
if (!isset($maxColsLengths[$column]) || $allColsLengths[$row][$column] > $maxColsLengths[$column]) {
$maxColsLengths[$column] = $allColsLengths[$row][$column];
}

Expand Down Expand Up @@ -1030,7 +1026,7 @@ public static function table(array $tbody, array $thead = [])
$table .= '| ' . implode(' | ', $tableRows[$row]) . ' |' . PHP_EOL;

// Set the thead and table borders-bottom
if (isset ($cols) && (($row === 0 && !empty ($thead)) || ($row + 1 === $totalRows))) {
if (isset($cols) && (($row === 0 && !empty($thead)) || ($row + 1 === $totalRows))) {
$table .= $cols . PHP_EOL;
}
}
Expand Down Expand Up @@ -1067,7 +1063,7 @@ protected static function is_cli(): bool
return true;
}

return !isset ($_SERVER['REMOTE_ADDR']) && !isset ($_SERVER['REQUEST_METHOD']);
return !isset($_SERVER['REMOTE_ADDR']) && !isset($_SERVER['REQUEST_METHOD']);
}
}

Expand Down
80 changes: 57 additions & 23 deletions src/libraries/Http/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Http;

use Http\URI;
use Validation\Validator;
use RuntimeException;

/**
Expand Down Expand Up @@ -59,6 +60,7 @@ class Request extends URI
*/
protected $body;

protected ?string $key;

public function __construct()
{
Expand All @@ -82,69 +84,87 @@ public function getMethod(): ?string
return strtoupper($_SERVER['REQUEST_METHOD'] ?? '');
}


/**
* Gets the $_FILES array of uploaded files
* Gets the $_FILES array of uploaded files or a specific file.
*/
public function files(string $name = null): ?array
{
$this->files = isset($_FILES[$name]) ? $_FILES[$name] : $_FILES;
return $this->files ?: null;
if ($name !== null) {
return $_FILES[$name] ?? null;
}

return $_FILES;
}

/**
* Get an uploaded file by its name
* Get an uploaded file by its name.
*/
public function file(string $name): ?array
{
$file = $this->files[$name];
return isset($file[$name]) ? $file[$name] : null;
return $this->files($name);
}

/**
* Checks if a file with a specific name has been uploaded
* Checks if a file with a specific name has been uploaded.
*/
public function hasFile(string $name): bool
{
$files = $this->files;
return isset($files[$name]) && $files[$name]['error'] === UPLOAD_ERR_OK;
$file = $this->file($name);
return isset($file) && $file['error'] === UPLOAD_ERR_OK;
}

/**
* Moves an uploaded file to a destination location
* Moves an uploaded file to a destination location.
*/
public function move(string $destination): bool
public function move(string $name, string $destination = ''): bool
{
$sourcePath = $this->files('tmp_name')[0];
if (is_uploaded_file($sourcePath) && move_uploaded_file($sourcePath, $destination)) {
if (!$file = $this->file($name)) {
return false;
}

$uploadPath = config('paths.uploadPath');
$destinationPath = rtrim($uploadPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . trim($destination, DIRECTORY_SEPARATOR);

if (!is_dir($destinationPath) && !mkdir($destinationPath, 0777, true) && !is_dir($destinationPath)) {
throw new RuntimeException(sprintf('Directory "%s" was not created', $destinationPath));
}

$uniqueFilename = bin2hex(random_bytes(20)) . time() . '.' . $this->getClientOriginalExtension($name);
$destinationFile = $destinationPath . DIRECTORY_SEPARATOR . $uniqueFilename;

if (is_uploaded_file($file['tmp_name']) && move_uploaded_file($file['tmp_name'], $destinationFile)) {
return true;
}

return false;
}

/**
* Gets the uploaded files.
* Gets the original name of the uploaded file.
*/
public function getClientOriginalName(): ?string
public function getClientOriginalName(string $name): ?string
{
return $_FILES['name'] ?? null;
return $this->file($name)['name'] ?? null;
}

/**
* Gets the uploaded files.
* Gets the original extension of the uploaded file.
*/
public function getClientOriginalExtension()
public function getClientOriginalExtension(string $name): ?string
{
$file = data_get($this->files(), 'file');
$extension = pathinfo($file, PATHINFO_EXTENSION);
$file = $this->file($name);
if ($file) {
return pathinfo($file['name'], PATHINFO_EXTENSION);
}

return $extension;
return null;
}

/**
* Get extension of file
* Gets the extension of a given file array.
*/
public function get_file_extension(array $file): string
public function getFileExtension(array $file): string
{
return pathinfo($file['name'], PATHINFO_EXTENSION);
}
Expand Down Expand Up @@ -477,6 +497,20 @@ private function is_csrf_valid(): bool
return $_COOKIE['csrfToken'] === $requestToken;
}

/**
* Validate data against a set of rules.
*/
public function validate(array $rules, array $data): ?string
{
$validator = Validator::make($rules, $data);

if ($validator->fails()) {
return $validator->getFirstError();
}

return null;
}

/**
* A convenience method that grabs the raw input stream and decodes
* the JSON into an array.
Expand Down
29 changes: 11 additions & 18 deletions src/libraries/Validation/Rules/Compare.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,24 +32,17 @@ public function validate($input): bool
throw new InvalidArgumentException('Invalid operator');
}

switch ($operator) {
case '>':
return $left > $right;
case '<':
return $left < $right;
case '>=':
return $left >= $right;
case '<=':
return $left <= $right;
case '==':
return $left == $right;
case '===':
return $left === $right;
case '!=':
return $left != $right;
case '!==':
return $left !== $right;
}
return match ($operator) {

'>' => $left > $right,
'<' => $left < $right,
'>=' => $left >= $right,
'<=' => $left <= $right,
'==' => $left == $right,
'===' => $left === $right,
'!=' => $left != $right,
'!==', => $left !== $right,
};
}

public function message()
Expand Down
Loading

0 comments on commit c857d24

Please sign in to comment.