Skip to content

Commit

Permalink
Refactor exception handling and update comments in code (#159)
Browse files Browse the repository at this point in the history
This commit refactors exception handling across the code by replacing
generic exception throwing with specific Exception subclasses. It also
includes updates to comments to improve clarity and readability.
  • Loading branch information
SmetDenis committed Apr 10, 2024
1 parent c6602fa commit 6a74e3f
Show file tree
Hide file tree
Showing 30 changed files with 161 additions and 58 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -433,12 +433,12 @@ columns:
# Format: https://www.php.net/manual/en/datetime.format.php
# Parsing: https://www.php.net/manual/en/function.strtotime.php
# Timezones: https://www.php.net/manual/en/timezones.php
date_min: -100 years # Example of relative formats
date_min: -100 years # Example of relative past date
date_greater: -99 days # Example of relative formats
date_not: 2006-01-02 15:04:05 -0700 Europe/Rome
date: 01 Jan 2000 # You can use any string that can be parsed by the strtotime function
date_less: now # Example of current date and time
date_max: +1 day # Example of relative formats
date_max: +1 day # Example of relative future date
date_format: Y-m-d # Check strict format of the date.
is_date: true # Accepts arbitrary date format. Is shows error if failed to convert to timestamp.
is_timezone: true # Allow only timezone identifiers. Case-insensitive. Example: "Europe/London", "utc".
Expand Down
3 changes: 1 addition & 2 deletions docker/build-preloader.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@

declare(strict_types=1);

$require = __DIR__ . '/../vendor/composer/autoload_classmap.php';
$classes = require $require;
$classes = include_once __DIR__ . '/../vendor/composer/autoload_classmap.php';

$header = <<<'TEXT'
<?php
Expand Down
4 changes: 2 additions & 2 deletions schema-examples/full.yml
Original file line number Diff line number Diff line change
Expand Up @@ -144,12 +144,12 @@ columns:
# Format: https://www.php.net/manual/en/datetime.format.php
# Parsing: https://www.php.net/manual/en/function.strtotime.php
# Timezones: https://www.php.net/manual/en/timezones.php
date_min: -100 years # Example of relative formats
date_min: -100 years # Example of relative past date
date_greater: -99 days # Example of relative formats
date_not: 2006-01-02 15:04:05 -0700 Europe/Rome
date: 01 Jan 2000 # You can use any string that can be parsed by the strtotime function
date_less: now # Example of current date and time
date_max: +1 day # Example of relative formats
date_max: +1 day # Example of relative future date
date_format: Y-m-d # Check strict format of the date.
is_date: true # Accepts arbitrary date format. Is shows error if failed to convert to timestamp.
is_timezone: true # Allow only timezone identifiers. Case-insensitive. Example: "Europe/London", "utc".
Expand Down
1 change: 0 additions & 1 deletion src/Commands/AbstractValidate.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
namespace JBZoo\CsvBlueprint\Commands;

use JBZoo\Cli\CliCommand;
use JBZoo\CsvBlueprint\Exception;
use JBZoo\CsvBlueprint\Schema;
use JBZoo\CsvBlueprint\Utils;
use JBZoo\CsvBlueprint\Validators\ErrorSuite;
Expand Down
21 changes: 21 additions & 0 deletions src/Commands/Exception.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

/**
* JBZoo Toolbox - Csv-Blueprint.
*
* This file is part of the JBZoo Toolbox project.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT
* @copyright Copyright (C) JBZoo.com, All rights reserved.
* @see https://github.com/JBZoo/Csv-Blueprint
*/

declare(strict_types=1);

namespace JBZoo\CsvBlueprint\Commands;

class Exception extends \JBZoo\CsvBlueprint\Exception
{
}
1 change: 0 additions & 1 deletion src/Commands/ValidateCsv.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
namespace JBZoo\CsvBlueprint\Commands;

use JBZoo\CsvBlueprint\Csv\CsvFile;
use JBZoo\CsvBlueprint\Exception;
use JBZoo\CsvBlueprint\Schema;
use JBZoo\CsvBlueprint\Utils;
use JBZoo\CsvBlueprint\Validators\ErrorSuite;
Expand Down
2 changes: 1 addition & 1 deletion src/Csv/CsvFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ final class CsvFile
public function __construct(string $csvFilename, null|array|string $csvSchemaFilenameOrArray = null)
{
if (\realpath($csvFilename) !== false && \file_exists($csvFilename) === false) {
throw new \InvalidArgumentException('File not found: ' . $csvFilename);
throw new Exception('File not found: ' . $csvFilename);
}

$this->csvFilename = $csvFilename;
Expand Down
2 changes: 1 addition & 1 deletion src/Rules/AbstarctRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public function validate(array|string $cellValue, int $line = ValidatorColumn::F
);
}
} else {
throw new \RuntimeException('Method "validateRule" not found in ' . static::class);
throw new Exception('Method "validateRule" not found in ' . static::class);
}

return null;
Expand Down
8 changes: 4 additions & 4 deletions src/Rules/AbstarctRuleCombo.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,28 +92,28 @@ protected static function compare(float $expected, float $actual, string $mode):
self::EQ => $expected === $actual,
self::LESS => $expected > $actual,
self::MAX => $expected >= $actual,
default => throw new \InvalidArgumentException("Unknown mode: {$mode}"),
default => throw new Exception("Unknown mode: {$mode}"),
};
}

private function validateCombo(array|string $cellValue): ?string
{
if ($this instanceof AbstractCellRuleCombo) {
if (!\is_string($cellValue)) {
throw new \InvalidArgumentException('The value should be a string');
throw new Exception('The value should be a string');
}

return $this->validateComboCell($cellValue, $this->mode);
}

if ($this instanceof AbstractAggregateRuleCombo) {
if (!\is_array($cellValue)) {
throw new \InvalidArgumentException('The value should be an array of numbers/strings');
throw new Exception('The value should be an array of numbers/strings');
}

return $this->validateComboAggregate($cellValue, $this->mode);
}

throw new \LogicException('Unknown rule type: ' . static::class);
throw new Exception('Unknown rule type: ' . static::class);
}
}
2 changes: 1 addition & 1 deletion src/Rules/Aggregate/AbstractAggregateRuleCombo.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public function getRuleCode(?string $mode = null): string
protected function getActual(array|string $value): float
{
if (\is_string($value)) {
throw new \InvalidArgumentException('The value should be an array of numbers/strings');
throw new Exception('The value should be an array of numbers/strings');
}

$result = $this->getActualAggregate($value);
Expand Down
4 changes: 2 additions & 2 deletions src/Rules/Aggregate/ComboNthNum.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ protected function getActualAggregate(array $colValues): ?float
$actual = $colValues[$arrayInd] ?? null;

if ($actual === null) {
throw new \RuntimeException(
throw new Exception(
"The column does not have a line {$realLine}, so the value cannot be checked.",
);
}
Expand All @@ -79,7 +79,7 @@ private function getParams(): array
{
$params = $this->getOptionAsArray();
if (\count($params) !== self::ARGS) {
throw new \RuntimeException(
throw new Exception(
'The rule expects exactly two arguments: ' .
'the first is the line number (without header), the second is the expected value',
);
Expand Down
2 changes: 1 addition & 1 deletion src/Rules/Aggregate/ComboPercentile.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ private function getParams(): array
{
$params = $this->getOptionAsArray();
if (\count($params) !== self::ARGS) {
throw new \RuntimeException(
throw new Exception(
'The rule expects exactly two params: ' .
'the first is percentile (P is beet 0.0 and 100.0), the second is the expected value (float)',
);
Expand Down
6 changes: 3 additions & 3 deletions src/Rules/Aggregate/ComboQuartiles.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ private function getType(): string
$type = $this->getParams()[self::TYPE];

if (!\in_array($type, self::TYPES, true)) {
throw new \RuntimeException(
throw new Exception(
"Unknown quartile type: \"{$type}\". Allowed: " . Utils::printList(self::TYPES, 'green'),
);
}
Expand All @@ -98,7 +98,7 @@ private function getMethod(): string
$method = $this->getParams()[self::METHOD];

if (!\in_array($method, self::METHODS, true)) {
throw new \RuntimeException(
throw new Exception(
"Unknown quartile method: \"{$method}\". Allowed: " . Utils::printList(self::METHODS, 'green'),
);
}
Expand All @@ -110,7 +110,7 @@ private function getParams(): array
{
$params = $this->getOptionAsArray();
if (\count($params) !== self::ARGS) {
throw new \RuntimeException(
throw new Exception(
'The rule expects exactly three params: ' .
'method ' . Utils::printList(self::METHODS) . ', ' .
'type ' . Utils::printList(self::TYPES) . ', ' .
Expand Down
21 changes: 21 additions & 0 deletions src/Rules/Aggregate/Exception.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

/**
* JBZoo Toolbox - Csv-Blueprint.
*
* This file is part of the JBZoo Toolbox project.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT
* @copyright Copyright (C) JBZoo.com, All rights reserved.
* @see https://github.com/JBZoo/Csv-Blueprint
*/

declare(strict_types=1);

namespace JBZoo\CsvBlueprint\Rules\Aggregate;

class Exception extends \JBZoo\CsvBlueprint\Rules\Exception
{
}
8 changes: 4 additions & 4 deletions src/Rules/Aggregate/Sorted.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public function validateRule(array $columnValues): ?string
try {
$dir = $this->getDir();
$method = $this->getMethod();
} catch (\RuntimeException $e) {
} catch (\Throwable $e) {
return $e->getMessage();
}

Expand All @@ -84,7 +84,7 @@ private function getDir(): string
$dir = $this->getParams()[self::DIR];

if (!\in_array($dir, self::DIRS, true)) {
throw new \RuntimeException(
throw new Exception(
"Unknown sort direction: \"{$dir}\". Allowed: " . Utils::printList(self::DIRS, 'green'),
);
}
Expand All @@ -97,7 +97,7 @@ private function getMethod(): int
$method = $this->getParams()[self::METHOD];

if (!\in_array($method, \array_keys(self::METHODS), true)) {
throw new \RuntimeException(
throw new Exception(
"Unknown sort method: \"{$method}\". Allowed: " . Utils::printList(\array_keys(self::METHODS), 'green'),
);
}
Expand All @@ -109,7 +109,7 @@ private function getParams(): array
{
$params = $this->getOptionAsArray();
if (\count($params) !== self::ARGS) {
throw new \RuntimeException(
throw new Exception(
'The rule expects exactly two params: ' .
'direction ' . Utils::printList(self::DIRS) . ' and ' .
'method ' . Utils::printList(\array_keys(self::METHODS)),
Expand Down
2 changes: 1 addition & 1 deletion src/Rules/Cell/AbstractCellRuleCombo.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ abstract protected function getActualCell(string $cellValue): float;
protected function getActual(array|string $value): float
{
if (\is_array($value)) {
throw new \InvalidArgumentException('This method should not be called with an array');
throw new Exception('This method should not be called with an array');
}

return $this->getActualCell($value);
Expand Down
4 changes: 2 additions & 2 deletions src/Rules/Cell/ComboDate.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ public function getHelpMeta(): array
'Timezones: https://www.php.net/manual/en/timezones.php',
],
[
self::MIN => ['-100 years', 'Example of relative formats'],
self::MIN => ['-100 years', 'Example of relative past date'],
self::GREATER => ['-99 days', 'Example of relative formats'],
self::EQ => ['01 Jan 2000', 'You can use any string that can be parsed by the strtotime function'],
self::NOT => ['2006-01-02 15:04:05 -0700 Europe/Rome'],
self::LESS => ['now', 'Example of current date and time'],
self::MAX => ['+1 day', 'Example of relative formats'],
self::MAX => ['+1 day', 'Example of relative future date'],
],
];
}
Expand Down
4 changes: 2 additions & 2 deletions src/Rules/Cell/ComboDateInterval.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,12 +98,12 @@ private static function dateIntervalToSeconds(string $dateIntervalOrAsString): i
try {
$interval = \DateInterval::createFromDateString($dateIntervalOrAsString);
} catch (\Exception) {
throw new \RuntimeException("Can't parse date interval: {$dateIntervalOrAsString}");
throw new Exception("Can't parse date interval: {$dateIntervalOrAsString}");
}
}

if (!$interval instanceof \DateInterval) {
throw new \RuntimeException("Can't parse date interval: {$dateIntervalOrAsString}");
throw new Exception("Can't parse date interval: {$dateIntervalOrAsString}");
}

$daysPerYear = 365.25; // Average considering leap years
Expand Down
6 changes: 3 additions & 3 deletions src/Rules/Cell/ComboPasswordStrength.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public static function passwordScore(string $password): int
}

// Numbers: +1 point if at least one
if (\preg_match('/[0-9]/', $password) !== 0) {
if (\preg_match('/\d/', $password) !== 0) {
$score++;
}

Expand All @@ -82,8 +82,8 @@ public static function passwordScore(string $password): int
$deductions += \preg_match_all('/01|12|23|34|45|56|67|78|89|90/', $password);

$deductions += \preg_match_all(
'/ab|bc|cd|de|ef|fg|gh|hi|ij|jk|kl|lm|mn|no|op|pq|qr|rs|st|tu|uv|vw|wx|xy|yz/i',
$password,
'/abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz/',
\strtolower($password),
);

if (\preg_match('/qwerty|pass|password/i', $password) !== 0) {
Expand Down
21 changes: 21 additions & 0 deletions src/Rules/Cell/Exception.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

/**
* JBZoo Toolbox - Csv-Blueprint.
*
* This file is part of the JBZoo Toolbox project.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT
* @copyright Copyright (C) JBZoo.com, All rights reserved.
* @see https://github.com/JBZoo/Csv-Blueprint
*/

declare(strict_types=1);

namespace JBZoo\CsvBlueprint\Rules\Cell;

class Exception extends \JBZoo\CsvBlueprint\Rules\Exception
{
}
4 changes: 2 additions & 2 deletions src/Rules/Cell/IsHex.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ public function getHelpMeta(): array
public function validateRule(string $cellValue): ?string
{
if (
\preg_match('/^[0-9a-fA-F]+$/i', $cellValue) === 0
&& \preg_match('/^0x[0-9a-fA-F]+$/i', $cellValue) === 0
\preg_match('/^[0-9a-f]+$/i', $cellValue) === 0
&& \preg_match('/^0x[0-9a-f]+$/i', $cellValue) === 0
) {
return "Value \"<c>{$cellValue}</c>\" is not a valid hexadecimal number. Example: \"0x1A\" or \"1A\"";
}
Expand Down
12 changes: 6 additions & 6 deletions src/Rules/Cell/IsTime.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@ public function validateRule(string $cellValue): ?string
}

$regexs = [
'1:59' => '/^([1-9]|1[0-2]):[0-5][0-9]$/',
'23:59' => '/^(?:2[0-3]|[01][0-9]):[0-5][0-9]$/',
'23:59:59' => '/^(?:2[0-3]|[01]?[0-9]):[0-5][0-9]:[0-5][0-9]$/',
'1:59 am' => '/^([1-9]|1[0-2]):[0-5][0-9]\s?(am|pm)$/i',
'12:59 am' => '/^(1[0-2]|0?[1-9]):[0-5][0-9]\s?(am|pm)$/i',
'12:59:59 am' => '/^(1[0-2]|0?[1-9]):[0-5][0-9]:[0-5][0-9]\s?(am|pm)$/i',
'1:59' => '/^([1-9]|1[0-2]):[0-5]\d$/',
'23:59' => '/^(?:2[0-3]|[01]\d):[0-5]\d$/',
'23:59:59' => '/^(?:2[0-3]|[01]?\d):[0-5]\d:[0-5]\d$/',
'1:59 am' => '/^([1-9]|1[0-2]):[0-5]\d\s?(am|pm)$/i',
'12:59 am' => '/^(1[0-2]|0?[1-9]):[0-5]\d\s?(am|pm)$/i',
'12:59:59 am' => '/^(1[0-2]|0?[1-9]):[0-5]\d:[0-5]\d\s?(am|pm)$/i',
];

foreach ($regexs as $regex) {
Expand Down
2 changes: 1 addition & 1 deletion src/Rules/Cell/IsTimezoneOffset.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public function validateRule(string $cellValue): ?string
return null;
}

if (Utils::testRegex('/^[\+\-](0[0-9]|1[0-4]):([0-5][0-9])$/', $cellValue)) {
if (Utils::testRegex('/^[\+\-](0\d|1[0-4]):([0-5]\d)$/', $cellValue)) {
return "Value \"<c>{$cellValue}</c>\" is not a valid timezone offset. " .
'Example: "<green>+03:00</green>".';
}
Expand Down

0 comments on commit 6a74e3f

Please sign in to comment.