Skip to content

Commit

Permalink
Refactoring and cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Echron committed Jul 29, 2024
1 parent 114bd94 commit a9f14e9
Show file tree
Hide file tree
Showing 7 changed files with 89 additions and 95 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
"ext-simplexml": "*",
"ext-libxml": "*",
"ext-dom": "*",
"ext-json": "*"
"ext-json": "*",
"ext-mbstring": "*"
},
"require-dev": {
"phpunit/phpunit": "^10.1.2",
Expand Down
6 changes: 3 additions & 3 deletions src/CsvHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

class CsvHelper
{
public static function toCSVFile(array $data, string $filePath, string $lineDelimiter = PHP_EOL, $delimiter = ';', $encapsulate = '"'): void
public static function toCSVFile(array $data, string $filePath, string $lineDelimiter = PHP_EOL, string $delimiter = ';', string $encapsulate = '"'): void
{
$rows = [];

Expand All @@ -27,7 +27,7 @@ public static function toCSVFile(array $data, string $filePath, string $lineDeli
}
}
}
$rows[] = CsvHelper::toCSVRow($headers, $delimiter, $encapsulate);
$rows[] = self::toCSVRow($headers, $delimiter, $encapsulate);
foreach ($data as $dat) {

$rowFields = [];
Expand All @@ -40,7 +40,7 @@ public static function toCSVFile(array $data, string $filePath, string $lineDeli
}
$rowFields[] = $rowFieldValue;
}
$rows[] = CsvHelper::toCSVRow($rowFields, $delimiter, $encapsulate);
$rows[] = self::toCSVRow($rowFields, $delimiter, $encapsulate);
}

file_put_contents($filePath, implode($lineDelimiter, $rows));
Expand Down
100 changes: 50 additions & 50 deletions src/FileSystem.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,45 +9,6 @@

class FileSystem
{
public static function createDir(string $path, bool $recursive = true, int $permissions = 0777, bool $ignoreIfExists = true): void
{
if (self::dirExists($path)) {
if ($ignoreIfExists) {
return;
}

throw new FileAlreadyExistsException('Unable to create directory "' . $path . '": directory already exists');
}
$exception = null;
$old = error_reporting(0);
try {
$created = mkdir($path, $permissions, $recursive);
if (!$created) {
if (ExceptionHelper::hasLastError()) {
$exception = ExceptionHelper::getLastError();
} else {
$exception = new \Exception('Unable to create directory');
}
}
} catch (\Throwable $ex) {
$exception = $ex;
}
error_reporting($old);

if ($exception !== null) {
switch ($exception->getMessage()) {
case 'mkdir(): Permissions denied':
throw new PermissionsDeniedException('Unable to create directory "' . $path . '": permissions denied');

case 'mkdir(): File exists':
throw new FileAlreadyExistsException('Unable to create directory "' . $path . '": directory already exists');

default:
throw $exception;
}
}
}

public static function isReadable(string $path, bool $clearStatCache = false): bool
{
if ($clearStatCache) {
Expand All @@ -66,15 +27,6 @@ public static function isWritable(string $path, bool $clearStatCache = false): b
return is_writable($path);
}

public static function dirExists(string $path, bool $clearStatCache = false): bool
{
if ($clearStatCache) {
clearstatcache(true, $path);
}

return file_exists($path) && is_dir($path);
}

public static function fileExists(string $path, bool $clearStatCache = false): bool
{
if ($clearStatCache) {
Expand Down Expand Up @@ -193,7 +145,7 @@ public static function joinPath(...$segments): string
}
}

return preg_replace('#/+#', \DIRECTORY_SEPARATOR, join(\DIRECTORY_SEPARATOR, $paths));
return preg_replace('#/+#', \DIRECTORY_SEPARATOR, implode(\DIRECTORY_SEPARATOR, $paths));
}

public static function copyDirectory(string $source, string $destination, bool $recursive = false): void
Expand All @@ -209,7 +161,7 @@ public static function copyDirectory(string $source, string $destination, bool $

// Loop through the files in source directory
while (false !== ($file = readdir($dir))) {
if (($file != '.') && ($file != '..')) {
if (($file !== '.') && ($file !== '..')) {
if (is_dir($source . \DIRECTORY_SEPARATOR . $file)) {
// Recursively calling custom copy function
// for sub directory
Expand All @@ -225,6 +177,54 @@ public static function copyDirectory(string $source, string $destination, bool $
closedir($dir);
}

public static function createDir(string $path, bool $recursive = true, int $permissions = 0777, bool $ignoreIfExists = true): void
{
if (self::dirExists($path)) {
if ($ignoreIfExists) {
return;
}

throw new FileAlreadyExistsException('Unable to create directory "' . $path . '": directory already exists');
}
$exception = null;
$old = error_reporting(0);
try {
$created = mkdir($path, $permissions, $recursive);
if (!$created) {
if (ExceptionHelper::hasLastError()) {
$exception = ExceptionHelper::getLastError();
} else {
$exception = new \Exception('Unable to create directory');
}
}
} catch (\Throwable $ex) {
$exception = $ex;
}
error_reporting($old);

if ($exception !== null) {
switch ($exception->getMessage()) {
case 'mkdir(): Permissions denied':
throw new PermissionsDeniedException('Unable to create directory "' . $path . '": permissions denied');

case 'mkdir(): File exists':
throw new FileAlreadyExistsException('Unable to create directory "' . $path . '": directory already exists');

default:
throw $exception;
}
}
}

public static function dirExists(string $path, bool $clearStatCache = false): bool
{
if ($clearStatCache) {
clearstatcache(true, $path);
}

return file_exists($path) && is_dir($path);
}

public static function getFileModificationTime(string $fileName): int
{
$exception = null;
Expand Down
30 changes: 15 additions & 15 deletions src/Normalize/Normalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,17 @@

class Normalizer
{
public static function normalizeCollection(array $codes, NormalizeConfig $keyFormatConfig = null): array
{
$result = [];

foreach ($codes as $code) {
$result[] = self::normalize($code, $keyFormatConfig);
}

return $result;
}

public static function normalize(string $code, NormalizeConfig $keyFormatConfig = null): string
{
// TODO: this is quite a slow function and called loads of times
Expand Down Expand Up @@ -41,7 +52,7 @@ public static function normalize(string $code, NormalizeConfig $keyFormatConfig
//'(\+{2,})',
];

if ($keyFormatConfig->isAllowSlash() && $keyFormatConfig->allowConsecutiveSlashes > 0) {
if ($keyFormatConfig->allowConsecutiveSlashes > 0 && $keyFormatConfig->isAllowSlash()) {
$allowedChars[] = '\/';
// $notAllowed[] = '(\/{2,})';
}
Expand Down Expand Up @@ -88,15 +99,15 @@ public static function normalize(string $code, NormalizeConfig $keyFormatConfig
$id = preg_replace($regex, '_', $id);


if ($keyFormatConfig->isAllowSlash() && $keyFormatConfig->allowConsecutiveSlashes > 0) {
if ($keyFormatConfig->allowConsecutiveSlashes > 0 && $keyFormatConfig->isAllowSlash()) {
$regex = '/(\/{' . ($keyFormatConfig->allowConsecutiveSlashes + 1) . ',})/mi';
$id = preg_replace($regex, \str_repeat('/', $keyFormatConfig->allowConsecutiveSlashes), $id);
}
if ($keyFormatConfig->isAllowDot() && $keyFormatConfig->allowConsecutiveDots > 0) {
if ($keyFormatConfig->allowConsecutiveDots > 0 && $keyFormatConfig->isAllowDot()) {
$regex = '/(\.{' . ($keyFormatConfig->allowConsecutiveDots + 1) . ',})/mi';
$id = preg_replace($regex, \str_repeat('.', $keyFormatConfig->allowConsecutiveDots), $id);
}
if ($keyFormatConfig->isAllowDash() && $keyFormatConfig->allowConsecutiveDashes > 0) {
if ($keyFormatConfig->allowConsecutiveDashes > 0 && $keyFormatConfig->isAllowDash()) {
$regex = '/(\-{' . ($keyFormatConfig->allowConsecutiveDashes + 1) . ',})/mi';
$id = preg_replace($regex, \str_repeat('-', $keyFormatConfig->allowConsecutiveDashes), $id);
}
Expand All @@ -115,15 +126,4 @@ public static function normalize(string $code, NormalizeConfig $keyFormatConfig
return $id;
// return new NormalizedCode($id);
}

public static function normalizeCollection(array $codes, NormalizeConfig $keyFormatConfig = null): array
{
$result = [];

foreach ($codes as $code) {
$result[] = self::normalize($code, $keyFormatConfig);
}

return $result;
}
}
4 changes: 1 addition & 3 deletions src/StringHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@

namespace Echron\Tools;

use Random\RandomException;

class StringHelper
{
/**
Expand Down Expand Up @@ -95,7 +93,7 @@ public static function mask(
/**
* Generate 128-bit GUID
* @return string
* @throws RandomException
* @throws \Random\RandomException
*/
public static function generateGuid(): string
{
Expand Down
34 changes: 15 additions & 19 deletions src/Time.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,25 +125,6 @@ public static function todayInRange(
return ($todayStartInSeconds >= $startTimeInSeconds && $todayEndInSeconds <= $endTimeInSeconds) || ($todayStartInSeconds >= $startTimeInSeconds && $endTimeInSeconds === null);
}

public static function isInPeriod(\DateTimeInterface $from, \DateTimeInterface $to = null, \DateTimeInterface $input = null): bool
{
if (\is_null($input)) {
$input = new \DateTime();
}
//Reverse 'to' & 'from' when 'to' is earlier than 'from''
if (!is_null($to) && $from > $to) {
$tmp = $from;
$from = $to;
$to = $tmp;
}

if (($input >= $from && $input <= $to) || ($input >= $from && is_null($to))) {
return true;
}

return false;
}

private static function getTime(int|string|\DateTimeInterface|null $input): int|null
{
if (is_numeric($input)) {
Expand All @@ -159,6 +140,21 @@ private static function getTime(int|string|\DateTimeInterface|null $input): int|
return null;
}

public static function isInPeriod(\DateTimeInterface $from, \DateTimeInterface $to = null, \DateTimeInterface $input = null): bool
{
if (\is_null($input)) {
$input = new \DateTime();
}
//Reverse 'to' & 'from' when 'to' is earlier than 'from''
if (!is_null($to) && $from > $to) {
$tmp = $from;
$from = $to;
$to = $tmp;
}

return ($input >= $from && $input <= $to) || ($input >= $from && null === $to);
}

/**
* createFromFormat("2022-10-23 15:49:06")
* @param string $time
Expand Down
7 changes: 3 additions & 4 deletions src/XmlHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@ public static function parseStringToSimpleXml(string $xmlString): \SimpleXMLElem
private static function cleanupMeta(string $xml): string
{
//Temp fix
$xml = str_replace("\x01", "", $xml);
return str_replace("\x02", "", $xml);
return str_replace(["\x01", "\x02"], "", $xml);

}

Expand Down Expand Up @@ -113,10 +112,10 @@ public static function saveFile(\SimpleXMLElement $xml, string $destination): bo
$message = $error['message'];

throw new \Exception('Unable to save XML file: ' . $message);
} else {
throw new \Exception('Unable to save XML file: unknown exception');
}

throw new \Exception('Unable to save XML file: unknown exception');

}
libxml_use_internal_errors(false);

Expand Down

0 comments on commit a9f14e9

Please sign in to comment.