Skip to content

Commit

Permalink
Fix passing null to string|int only fields
Browse files Browse the repository at this point in the history
  • Loading branch information
paulbalandan committed Aug 31, 2021
1 parent 007d1e1 commit 8432f92
Show file tree
Hide file tree
Showing 17 changed files with 102 additions and 185 deletions.
4 changes: 1 addition & 3 deletions app/Config/Mimes.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
namespace Config;

/**
* Mimes
*
* This file contains an array of mime types. It is used by the
* Upload class to help identify allowed file types.
*
Expand Down Expand Up @@ -509,7 +507,7 @@ public static function guessExtensionFromType(string $type, ?string $proposedExt
{
$type = trim(strtolower($type), '. ');

$proposedExtension = trim(strtolower($proposedExtension));
$proposedExtension = trim(strtolower($proposedExtension ?? ''));

if ($proposedExtension !== '') {
if (array_key_exists($proposedExtension, static::$mimes) && in_array($type, is_string(static::$mimes[$proposedExtension]) ? [static::$mimes[$proposedExtension]] : static::$mimes[$proposedExtension], true)) {
Expand Down
10 changes: 5 additions & 5 deletions system/CLI/CLI.php
Original file line number Diff line number Diff line change
Expand Up @@ -826,11 +826,11 @@ public static function getOptionString(bool $useLongOpts = false, bool $trim = f
$out .= "-{$name} ";
}

// If there's a space, we need to group
// so it will pass correctly.
if (mb_strpos($value, ' ') !== false) {
$out .= '"' . $value . '" ';
} elseif ($value !== null) {
if ($value === null) {
$out .= '';
} elseif (mb_strpos($value, ' ') !== false) {
$out .= "\"{$value}\" ";
} else {
$out .= "{$value} ";
}
}
Expand Down
20 changes: 6 additions & 14 deletions system/Filters/Filters.php
Original file line number Diff line number Diff line change
Expand Up @@ -377,28 +377,20 @@ protected function processGlobals(?string $uri = null)
return;
}

$uri = strtolower(trim($uri, '/ '));
$uri = strtolower(trim($uri ?? '', '/ '));

// Add any global filters, unless they are excluded for this URI
$sets = [
'before',
'after',
];
$sets = ['before', 'after'];

foreach ($sets as $set) {
if (isset($this->config->globals[$set])) {

// look at each alias in the group
foreach ($this->config->globals[$set] as $alias => $rules) {
$keep = true;
if (is_array($rules)) {
// see if it should be excluded
if (isset($rules['except'])) {
// grab the exclusion rules
$check = $rules['except'];
if ($this->pathApplies($uri, $check)) {
$keep = false;
}
}

if (is_array($rules) && isset($rules['except']) && $this->pathApplies($uri, $rules['except'])) {
$keep = false;
} else {
$alias = $rules; // simple name of filter to apply
}
Expand Down
18 changes: 8 additions & 10 deletions system/HTTP/CLIRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
use RuntimeException;

/**
* Class CLIRequest
*
* Represents a request from the command-line. Provides additional
* tools to interact with that request since CLI requests are not
* static like HTTP requests might be.
Expand Down Expand Up @@ -141,11 +139,11 @@ public function getOptionString(bool $useLongOpts = false): string
$out .= "-{$name} ";
}

// If there's a space, we need to group
// so it will pass correctly.
if (mb_strpos($value, ' ') !== false) {
$out .= '"' . $value . '" ';
} elseif ($value !== null) {
if ($value === null) {
$out .= '';
} elseif (mb_strpos($value, ' ') !== false) {
$out .= "\"{$value}\" ";
} else {
$out .= "{$value} ";
}
}
Expand All @@ -172,17 +170,17 @@ protected function parseCommand()
if ($optionValue) {
$optionValue = false;
} else {
$this->segments[] = filter_var($arg, FILTER_SANITIZE_STRING);
$this->segments[] = esc(strip_tags($arg));
}

continue;
}

$arg = filter_var(ltrim($arg, '-'), FILTER_SANITIZE_STRING);
$arg = esc(strip_tags(ltrim($arg, '-')));
$value = null;

if (isset($args[$i + 1]) && mb_strpos($args[$i + 1], '-') !== 0) {
$value = filter_var($args[$i + 1], FILTER_SANITIZE_STRING);
$value = esc(strip_tags($args[$i + 1]));
$optionValue = true;
}

Expand Down
29 changes: 7 additions & 22 deletions system/HTTP/CURLRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,7 @@
use InvalidArgumentException;

/**
* Class OutgoingRequest
*
* A lightweight HTTP client for sending synchronous HTTP requests
* via cURL.
* A lightweight HTTP client for sending synchronous HTTP requests via cURL.
*/
class CURLRequest extends Request
{
Expand Down Expand Up @@ -84,10 +81,7 @@ class CURLRequest extends Request
public function __construct(App $config, URI $uri, ?ResponseInterface $response = null, array $options = [])
{
if (! function_exists('curl_version')) {
// we won't see this during travis-CI
// @codeCoverageIgnoreStart
throw HTTPException::forMissingCurl();
// @codeCoverageIgnoreEnd
throw HTTPException::forMissingCurl(); // @codeCoverageIgnore
}

parent::__construct($config);
Expand All @@ -110,9 +104,7 @@ public function request($method, string $url, array $options = []): ResponseInte

$url = $this->prepareURL($url);

$method = filter_var($method, FILTER_SANITIZE_STRING);

$this->send($method, $url);
$this->send(esc(strip_tags($method)), $url);

return $this->response;
}
Expand Down Expand Up @@ -182,11 +174,7 @@ public function put(string $url, array $options = []): ResponseInterface
*/
public function setAuth(string $username, string $password, string $type = 'basic')
{
$this->config['auth'] = [
$username,
$password,
$type,
];
$this->config['auth'] = [$username, $password, $type];

return $this;
}
Expand Down Expand Up @@ -260,14 +248,12 @@ protected function parseOptions(array $options)
*/
protected function prepareURL(string $url): string
{
// If it's a full URI, then we have nothing to do here...
if (strpos($url, '://') !== false) {
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());
}

Expand All @@ -279,7 +265,7 @@ protected function prepareURL(string $url): string
*/
public function getMethod(bool $upper = false): string
{
return ($upper) ? strtoupper($this->method) : strtolower($this->method);
return $upper ? strtoupper($this->method) : strtolower($this->method);
}

/**
Expand Down Expand Up @@ -386,10 +372,9 @@ protected function applyMethod(string $method, array $curlOptions): array
{
$method = strtoupper($method);

$this->method = $method;
$curlOptions[CURLOPT_CUSTOMREQUEST] = $method;
$this->method = $curlOptions[CURLOPT_CUSTOMREQUEST] = $method;

$size = strlen($this->body);
$size = strlen($this->body ?? '');

// Have content?
if ($size > 0) {
Expand Down
4 changes: 1 addition & 3 deletions system/HTTP/ResponseTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@
use InvalidArgumentException;

/**
* Request Trait
*
* Additional methods to make a PSR-7 Response class
* compliant with the framework's own ResponseInterface.
*
Expand Down Expand Up @@ -435,7 +433,7 @@ public function send()
if ($this->CSPEnabled === true) {
$this->CSP->finalize($this);
} else {
$this->body = str_replace(['{csp-style-nonce}', '{csp-script-nonce}'], '', $this->body);
$this->body = str_replace(['{csp-style-nonce}', '{csp-script-nonce}'], '', $this->body ?? '');
}

$this->sendHeaders();
Expand Down
6 changes: 3 additions & 3 deletions system/Helpers/number_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,14 @@
*/
function number_to_size($num, int $precision = 1, ?string $locale = null)
{
// Strip any formatting & ensure numeric input
try {
$num = 0 + str_replace(',', '', $num); // @phpstan-ignore-line
} catch (ErrorException $ee) {
} catch (ErrorException $e) {
return false;
}

// ignore sub part
$generalLocale = $locale;

if (! empty($locale) && ($underscorePos = strpos($locale, '_'))) {
$generalLocale = substr($locale, 0, $underscorePos);
}
Expand Down Expand Up @@ -248,6 +247,7 @@ function number_to_roman(string $num): ?string
$return = $keyF; // @phpstan-ignore-line
break;
}

if ($num > 10) {
$return = $_number_to_roman($num / 10, ++$th) . $return;
}
Expand Down
16 changes: 6 additions & 10 deletions system/I18n/Time.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,25 +75,21 @@ class Time extends DateTime
*/
public function __construct(?string $time = null, $timezone = null, ?string $locale = null)
{
// If no locale was provided, grab it from Locale (set by IncomingRequest for web requests)
$this->locale = ! empty($locale) ? $locale : Locale::getDefault();
$this->locale = $locale ?: Locale::getDefault();

// If a test instance has been provided, use it instead.
if ($time === null && static::$testNow instanceof self) {
if (empty($timezone)) {
$timezone = static::$testNow->getTimezone();
}

$time = static::$testNow->toDateTimeString();
$timezone = $timezone ?: static::$testNow->getTimezone();
$time = static::$testNow->toDateTimeString();
}

$timezone = ! empty($timezone) ? $timezone : date_default_timezone_get();
$timezone = $timezone ?: date_default_timezone_get();
$this->timezone = $timezone instanceof DateTimeZone ? $timezone : new DateTimeZone($timezone);

// If the time string was a relative string (i.e. 'next Tuesday')
// then we need to adjust the time going in so that we have a current
// timezone to work with.
if (! empty($time) && (is_string($time) && static::hasRelativeKeywords($time))) {
if (! empty($time) && is_string($time) && static::hasRelativeKeywords($time)) {
$instance = new DateTime('now', $this->timezone);
$instance->modify($time);
$time = $instance->format('Y-m-d H:i:s');
Expand All @@ -113,7 +109,7 @@ public function __construct(?string $time = null, $timezone = null, ?string $loc
*/
public static function now($timezone = null, ?string $locale = null)
{
return new self(null, $timezone, $locale);
return new self('now', $timezone, $locale);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion system/Images/Handlers/GDHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ protected function process(string $action)
imagesavealpha($dest, true);
}

$copy($dest, $src, 0, 0, $this->xAxis, $this->yAxis, $this->width, $this->height, $origWidth, $origHeight);
$copy($dest, $src, 0, 0, $this->xAxis ?? 0, $this->yAxis ?? 0, $this->width, $this->height, $origWidth, $origHeight);

imagedestroy($src);
$this->resource = $dest;
Expand Down
10 changes: 4 additions & 6 deletions system/Router/RouteCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@
use InvalidArgumentException;

/**
* Class RouteCollection
*
* @todo Implement nested resource routing (See CakePHP)
*/
class RouteCollection implements RouteCollectionInterface
Expand Down Expand Up @@ -663,17 +661,17 @@ public function resource(string $name, ?array $options = null): RouteCollectionI
// resources are sent to, we need to have a new name
// to store the values in.
$newName = implode('\\', array_map('ucfirst', explode('/', $name)));

// If a new controller is specified, then we replace the
// $name value with the name of the new controller.
if (isset($options['controller'])) {
$newName = ucfirst(filter_var($options['controller'], FILTER_SANITIZE_STRING));
$newName = ucfirst(esc(strip_tags($options['controller'])));
}

// In order to allow customization of allowed id values
// we need someplace to store them.
$id = $options['placeholder'] ?? $this->placeholders[$this->defaultPlaceholder] ?? '(:segment)';

// Make sure we capture back-references
$id = $options['placeholder'] ?? $this->placeholders[$this->defaultPlaceholder] ?? '(:segment)';
$id = '(' . trim($id, '()') . ')';

$methods = isset($options['only']) ? (is_string($options['only']) ? explode(',', $options['only']) : $options['only']) : ['index', 'show', 'create', 'update', 'delete', 'new', 'edit'];
Expand Down Expand Up @@ -759,7 +757,7 @@ public function presenter(string $name, ?array $options = null): RouteCollection
// If a new controller is specified, then we replace the
// $name value with the name of the new controller.
if (isset($options['controller'])) {
$newName = ucfirst(filter_var($options['controller'], FILTER_SANITIZE_STRING));
$newName = ucfirst(esc(strip_tags($options['controller'])));
}

// In order to allow customization of allowed id values
Expand Down
7 changes: 3 additions & 4 deletions system/Security/Security.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@
use Config\Security as SecurityConfig;

/**
* Class Security
*
* Provides methods that help protect your site against
* Cross-Site Request Forgery attacks.
*/
Expand Down Expand Up @@ -206,9 +204,10 @@ public function verify(RequestInterface $request)
if ($request->hasHeader($this->headerName) && ! empty($request->getHeader($this->headerName)->getValue())) {
$tokenName = $request->getHeader($this->headerName)->getValue();
} else {
$json = json_decode($request->getBody());
$body = $request->getBody() ?? '';
$json = json_decode($body);

if (! empty($request->getBody()) && ! empty($json) && json_last_error() === JSON_ERROR_NONE) {
if ($body !== '' && $json !== null && json_last_error() === JSON_ERROR_NONE) {
$tokenName = $json->{$this->tokenName} ?? null;
} else {
$tokenName = null;
Expand Down
4 changes: 1 addition & 3 deletions system/Validation/CreditCardRules.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@
namespace CodeIgniter\Validation;

/**
* Class CreditCardRules
*
* Provides validation methods for common credit-card inputs.
*
* @see http://en.wikipedia.org/wiki/Credit_card_number
Expand Down Expand Up @@ -189,7 +187,7 @@ public function valid_cc_number(?string $ccNumber, string $type): bool
}

// Make sure we have a valid length
if (strlen($ccNumber) === 0) {
if (strlen($ccNumber ?? '') === 0) {
return false;
}

Expand Down
Loading

0 comments on commit 8432f92

Please sign in to comment.