diff --git a/app/Lib/Helpers/ToolboxHelper.php b/app/Lib/Helpers/ToolboxHelper.php index 85a3a1f1..d17ff34c 100644 --- a/app/Lib/Helpers/ToolboxHelper.php +++ b/app/Lib/Helpers/ToolboxHelper.php @@ -4,22 +4,12 @@ declare(strict_types=1); namespace App\Lib\Helpers; -use Illuminate\Contracts\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; -use Illuminate\Http\Request; -use Illuminate\Support\Arr; -use Illuminate\Support\Collection; -use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\File; -use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Str; use Illuminate\Validation\Rule; -use Illuminate\Validation\ValidationException; -use Propaganistas\LaravelPhone\PhoneNumber; -use Symfony\Component\Finder\SplFileInfo; -use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class ToolboxHelper extends ToolboxHelperCore { @@ -92,87 +82,6 @@ class ToolboxHelper extends ToolboxHelperCore ])->validate(); } - /** - * Assert That no Back Office url is present on txt - * - * @throws \Illuminate\Validation\ValidationException If url is a bo url. - */ - public static function assertNoInternalBoUrls(string $field, string $text): string - { - $routes = Route::getRoutes(); - - return self::replaceUrlsInText($text, function (string $url) use ($routes, $field): void { - $request = Request::create($url); - if (! self::isInternalHost($url)) { - return; - } - - if (trim($routes->match($request)->getPrefix() ?? '', '/') === 'bo') { - throw ValidationException::withMessages([ - $field => trans( - 'crud.libs.toolbox.assertNoInternalBoUrls', - ['attribute' => $field] - ), - ]); - } - }); - } - - /** - * Assert That only external url is present on txt - * - * @throws \Illuminate\Validation\ValidationException If url is a bo url. - */ - public static function assertNoInternalUrls(string $field, string $text): string - { - self::assertNoInternalBoUrls($field, $text); - $routes = Route::getRoutes(); - - return self::replaceUrlsInText($text, function (string $url) use ($routes, $field): void { - $request = Request::create($url); - $routes->match($request); - - if (! self::isInternalHost($url)) { - return; - } - - throw ValidationException::withMessages([ - $field => trans( - 'crud.libs.toolbox.assertNoInternalUrls', - ['attribute' => $field, 'appname' => Config::string('app.name')] - ), - ]); - }); - } - - private static function isInternalHost(string $url): bool - { - return \parse_url((string) Config::string('app.url'), \PHP_URL_HOST) === \parse_url($url, \PHP_URL_HOST); - } - - private static function replaceUrlsInText(string $text, callable $onMatchedUrl): string - { - $result = preg_replace_callback( - // phpcs:ignore Generic.Files.LineLength.TooLong - '/(?P(?:https?:\/\/)?(?:www\.)?[-a-zA-Z0-9@%._+~#=]{2,256}\.[a-z]{2,6}\b[-a-zA-Z0-9@:%_.+~#?&\/=]*)/', - function (array $matches) use ($onMatchedUrl): string { - $match = collect($matches)->first() ?? ''; - $url = (string) $match; - - try { - $onMatchedUrl($url); - } catch (NotFoundHttpException) { - return (string) $match; - } - - return (string) $match; - }, - $text - ); - - return is_string($result) ? $result : $text; - } - /** * Get original polyfill with autotranslate behavior */ @@ -194,78 +103,6 @@ class ToolboxHelper extends ToolboxHelperCore return $model->getOriginal($attribute); } - /** - * Dynamic model query - */ - public static function queryColumnWithLocales( - string $defaultLocale, - Builder $q, - string $column, - string $value - ): Builder { - $columnRegex = '/^[A-Za-z0-9_.]+$/'; - $localeRegex = '/^[A-Za-z0-9_-]+$/'; - - throw_unless(preg_match($columnRegex, $column), \InvalidArgumentException::class, 'Invalid column identifier.'); - - throw_unless(preg_match($localeRegex, $defaultLocale), \InvalidArgumentException::class, 'Invalid locale identifier.'); - - $currentLocale = app()->currentLocale(); - throw_unless(preg_match($localeRegex, $currentLocale), \InvalidArgumentException::class, 'Invalid locale identifier.'); - - /** @var array $locales */ - $locales = Config::array('app.locales', []); - $locales = Collection::make($locales) - ->filter(fn (string $locale) => (bool) preg_match($localeRegex, $locale)) - ->mapWithKeys(fn (string $locale) => [$locale => $locale]); - - if (! $locales->has($defaultLocale)) { - // * Remove default locale. - $locales->pull($defaultLocale); - } - if (! $locales->has($currentLocale)) { - // * Remove current locale. - $locales->pull($currentLocale); - } - - return $q->where(function (Builder $q) use ($defaultLocale, $currentLocale, $locales, $column, $value): void { - // * Query default locale - $q->where("{$column}->{$defaultLocale}", $value); - if ($defaultLocale !== $currentLocale) { - // * Query current locale - $q->orWhere("{$column}->{$currentLocale}", $value); - } - // * Query any other locale - $locales->each(fn (string $locale) => $q->orWhere( - "{$column}->{$locale}", - $value - )); - }); - } - - /** - * Generates an array from a dot separated string - * - * @param string $path The dot separated string to convert to an array. - * @param mixed $value The value to set at the end of the array. - * @param string $separator The separator used in the path (default is '.'). - * @return array The generated array. - */ - public static function dotStringToNestedArray(string $path, mixed $value, string $separator = '.'): array - { - throw_if($separator === '', \InvalidArgumentException::class, 'Separator cannot be an empty string.'); - - $arr = $value; - $keys = explode($separator, $path); - $keys = array_reverse($keys); - - foreach ($keys as $key) { - $arr = [$key => $arr]; - } - - return $arr; - } - /** * Validate picture * @@ -347,101 +184,4 @@ class ToolboxHelper extends ToolboxHelperCore $fail($yMessage); } } - - /** - * Fetch class list from a specific namespace - * - * @return array An array of classe namespaces - */ - public static function getClassesUsingNamespace(string $namespace): array - { - return collect(File::files(\app_path((string) Str::of($namespace)->replaceFirst('\App', '')))) - ->filter(fn (SplFileInfo $splFileInfo) => $splFileInfo->getExtension() === 'php') - ->map(fn (SplFileInfo $splFileInfo) => (string) Str::of($splFileInfo->getBasename()) - ->replace('.' . $splFileInfo->getExtension(), '')->prepend("{$namespace}\\"))->all(); - } - - /** - * Get all classes from a specific namespace that implement a specific interface - * - * @return array An array of classe namespaces - */ - public static function getClassesUsingInterface(string $namespace, string $interface): array - { - return Arr::where( - static::getClassesUsingNamespace($namespace), - fn (string $class_namespace) => \collect(class_implements($class_namespace, true) ?: [])->filter() - ->contains(fn (string $class_interface) => $class_interface === $interface) - ); - } - - /** - * Convert Hex color to RGB - * - * @return int[] - */ - public static function hexToRgb(string $hexcolor): array - { - $hexcolor = (string) str($hexcolor)->replaceStart('#', ''); - $r = (int) hexdec(substr($hexcolor, 0, 2)); - $g = (int) hexdec(substr($hexcolor, 2, 2)); - $b = (int) hexdec(substr($hexcolor, 4, 2)); - - return [$r, $g, $b]; - } - - /** - * Get text color contrast for a hex background color - * - * @return string "black" or "white" - */ - public static function getContrastYiq(string $hexcolor): string - { - [$r, $g, $b] = self::hexToRgb($hexcolor); - $yiq = (($r * 299) + ($g * 587) + ($b * 114)) / 1000; - - return ($yiq >= 128) ? 'black' : 'white'; - } - - /** - * Parse a phone number and return a PhoneNumber instance - * - * @param string $phoneNumber The phone number to parse - * @param string $countryCode The country code (default is 'FR' for France) - * @return \Propaganistas\LaravelPhone\PhoneNumber|null Returns the formatted phone number or null if invalid - */ - public static function parsePhoneNumber(string $phoneNumber, string $countryCode = 'FR'): ?PhoneNumber - { - $phoneNumber = new PhoneNumber($phoneNumber, $countryCode); - if (! $phoneNumber->isValid()) { - return null; - } - - return $phoneNumber; - } - - /** - * Convert an HTML string to plain text with proper word spacing. - * - * Replaces HTML tags with spaces, strips remaining tags, - * normalises whitespace and trims the result. - * - * @param string|null $html The HTML content to convert. - * @param int|null $limit Optional character limit (uses Str::limit). - */ - public static function htmlToText(?string $html, ?int $limit = null): string - { - if ($html === null || $html === '') { - return ''; - } - - $text = strip_tags((string) preg_replace('/<[^>]*>/', ' ', $html)); - $text = trim((string) preg_replace('/\s+/', ' ', $text)); - - if ($limit !== null) { - return Str::limit($text, $limit); - } - - return $text; - } } diff --git a/app/Lib/Helpers/ToolboxHelperCore.php b/app/Lib/Helpers/ToolboxHelperCore.php index 3e3e3d65..61463bde 100644 --- a/app/Lib/Helpers/ToolboxHelperCore.php +++ b/app/Lib/Helpers/ToolboxHelperCore.php @@ -4,7 +4,6 @@ declare(strict_types=1); namespace App\Lib\Helpers; -use App\Exceptions\Helpers\UnsupportedStructureConversionException; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Storage; @@ -118,48 +117,6 @@ abstract class ToolboxHelperCore return implode($replace, $parts); } - /** - * Convert deeply an object to array - * - * @return array - * - * @throws \App\Exceptions\Helpers\UnsupportedStructureConversionException If $input var is a scalar value. - */ - public static function objectToArray(mixed $input): array - { - if (! (is_object($input) || is_array($input))) { - throw UnsupportedStructureConversionException::fromType($input); - } - - $ret = (array) $input; - foreach ($ret as &$item) { - $item = (is_object($item) || is_array($item)) ? self::objectToArray($item) : $item; - } - - return $ret; - } - - /** - * Convert deeply an array to object - * - * @throws \App\Exceptions\Helpers\UnsupportedStructureConversionException If $input var is a scalar value. - */ - public static function arrayToObject(mixed $input): object - { - if (! (is_object($input) || is_array($input))) { - throw UnsupportedStructureConversionException::fromType($input); - } - - $ret = (object) $input; - $retArray = (array) $ret; - foreach ($retArray as &$item) { - $item = (is_object($item) || is_array($item)) ? self::arrayToObject($item) : $item; - } - unset($item); - - return (object) $retArray; - } - /** * Get the file full path */ diff --git a/lang/en/crud.php b/lang/en/crud.php index 45c028ba..25ee6472 100644 --- a/lang/en/crud.php +++ b/lang/en/crud.php @@ -55,8 +55,6 @@ return [ 'libs' => [ 'toolbox' => [ 'assertFieldIsUnique' => 'The :valeur of the field :attribut is already used', - 'assertNoInternalBoUrls' => ':attribute: It is forbidden to paste back-office uri in this field', - 'assertNoInternalUrls' => ':attribute: It is forbidden to paste a :appname url in this field.', ], ], diff --git a/lang/fr/crud.php b/lang/fr/crud.php index ef835118..64581205 100644 --- a/lang/fr/crud.php +++ b/lang/fr/crud.php @@ -57,8 +57,6 @@ return [ 'libs' => [ 'toolbox' => [ 'assertFieldIsUnique' => 'La :valeur du champ :attribut est déjà utilisée', - 'assertNoInternalBoUrls' => ':attribute : Il est interdit de coller l\'uri de back-office dans ce champ', - 'assertNoInternalUrls' => ':attribute : Il est interdit de coller une url de :appname dans ce champ.', ], ], diff --git a/tests/Integration/WithApp/Helpers/ToolboxHelpercoreTest.php b/tests/Integration/WithApp/Helpers/ToolboxHelpercoreTest.php index f069ca88..f2213ee1 100644 --- a/tests/Integration/WithApp/Helpers/ToolboxHelpercoreTest.php +++ b/tests/Integration/WithApp/Helpers/ToolboxHelpercoreTest.php @@ -2,7 +2,6 @@ declare(strict_types=1); -use App\Exceptions\Helpers\UnsupportedStructureConversionException; use Illuminate\Support\Facades\Storage; use Tests\Integration\WithApp\Helpers\ToolboxHelperCoreHarness; @@ -52,37 +51,6 @@ it('replaces with paired search and replace arrays', function (): void { expect($result)->toBe('X-Y'); }); -it('converts nested object to array and array to object', function (): void { - // GIVEN - $object = (object) [ - 'name' => 'demo', - 'nested' => (object) [ - 'value' => 10, - ], - ]; - - // WHEN - $asArray = ToolboxHelperCoreHarness::objectToArray($object); - $asObject = ToolboxHelperCoreHarness::arrayToObject($asArray); - - // THEN - expect($asArray)->toBe([ - 'name' => 'demo', - 'nested' => ['value' => 10], - ]) - ->and($asObject)->toBeObject() - ->and($asObject->nested)->toBeObject() - ->and($asObject->nested->value)->toBe(10); -}); - -it('throws for unsupported scalar structure conversion', function (): void { - // WHEN / THEN - expect(fn () => ToolboxHelperCoreHarness::objectToArray('x')) - ->toThrow(UnsupportedStructureConversionException::class) - ->and(fn () => ToolboxHelperCoreHarness::arrayToObject(12)) - ->toThrow(UnsupportedStructureConversionException::class); -}); - it('resolves full path and mime type without storage disk', function (): void { // GIVEN $tmpFile = tempnam(sys_get_temp_dir(), 'tbx-');