291 lines
10 KiB
PHP
291 lines
10 KiB
PHP
<?php
|
|
|
|
namespace App\Lib\Helpers;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Route;
|
|
use Illuminate\Support\Facades\Session;
|
|
use Illuminate\Support\Facades\Validator;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Validation\Rule;
|
|
use Illuminate\Validation\ValidationException;
|
|
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
|
|
|
class ToolboxHelper
|
|
{
|
|
/**
|
|
* Cut string words
|
|
*
|
|
* @param string $string
|
|
* @param integer $max
|
|
* @param string $hyphen
|
|
* @return string
|
|
*/
|
|
public static function cutWords(string $string, int $max = 20, string $hyphen = '[.]')
|
|
{
|
|
$originalString = $string;
|
|
$tok = strtok($string, ' ');
|
|
$string = '';
|
|
while ($tok !== false && mb_strlen($string) < $max) {
|
|
if (
|
|
mb_strlen($string) + mb_strlen($tok) <= $max
|
|
) {
|
|
$string .= $tok . ' ';
|
|
} else {
|
|
break;
|
|
}
|
|
$tok = strtok(' ');
|
|
}
|
|
return trim($string) . (strlen(trim($string)) !== strlen(trim($originalString)) ? $hyphen : '');
|
|
}
|
|
|
|
/**
|
|
* Strip scheme (https) on oembed urls
|
|
* Only embed allowed are for MP4 self hosted videos right now
|
|
*
|
|
* https is force by ckeditor MediaElements which natively supports
|
|
* only cloud hosted medias (youtube, spotify etc..)
|
|
*
|
|
* @param string $input
|
|
* @return string
|
|
*/
|
|
public static function stripCkEditorSchemesOnMediaInputs(string $input): string
|
|
{
|
|
$input = \preg_replace('/(?<=<oembed url=")(https:\/\/)(?=.*?">)/m', '', $input);
|
|
return $input;
|
|
}
|
|
|
|
/**
|
|
* Assert That no Back Office url is present on txt
|
|
*
|
|
* @param string $field
|
|
* @param string $text
|
|
* @return string
|
|
* @throws \Illuminate\Validation\ValidationException If url is a bo url.
|
|
*/
|
|
public static function assertNoInternalBoUrls(string $field, string $text): string
|
|
{
|
|
$routes = Route::getRoutes();
|
|
// * Url replace and email replace.
|
|
$text = preg_replace_callback(
|
|
// phpcs:ignore Generic.Files.LineLength.TooLong
|
|
'/(?P<url>(?:http[s]?:\/\/.)?(?:www\.)?[-a-zA-Z0-9@%._\+~#=]{2,256}\.[a-z]{2,6}\b(?:[-a-zA-Z0-9@:%_\+.~#?&\/\/=]*))/',
|
|
function ($matches) use ($routes, $field) {
|
|
$match = collect($matches)->first() ?? '';
|
|
$url = $match;
|
|
try {
|
|
$request = Request::create($url);
|
|
// If a route is match then it do not throws exception.
|
|
if (
|
|
\parse_url(config('app.url'), \PHP_URL_HOST) === \parse_url($url, \PHP_URL_HOST) &&
|
|
trim($routes->match($request)->getPrefix() ?? '', '/') === 'bo'
|
|
) {
|
|
// Removes the matched url.
|
|
throw ValidationException::withMessages([
|
|
$field => ':attribute : Il est interdit de coller une url du back office dans ce champ'
|
|
]);
|
|
}
|
|
return $match;
|
|
} catch (NotFoundHttpException $e) {
|
|
return $match;
|
|
}
|
|
},
|
|
$text
|
|
);
|
|
return $text;
|
|
}
|
|
|
|
/**
|
|
* Assert That only external url is present on txt
|
|
*
|
|
* @param string $field
|
|
* @param string $text
|
|
* @return string
|
|
* @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();
|
|
// * Url replace and email replace.
|
|
$text = preg_replace_callback(
|
|
// phpcs:ignore Generic.Files.LineLength.TooLong
|
|
'/(?P<url>(?:http[s]?:\/\/.)?(?:www\.)?[-a-zA-Z0-9@%._\+~#=]{2,256}\.[a-z]{2,6}\b(?:[-a-zA-Z0-9@:%_\+.~#?&\/\/=]*))/',
|
|
function ($matches) use ($routes, $field) {
|
|
$match = collect($matches)->first() ?? '';
|
|
$url = $match;
|
|
try {
|
|
$request = Request::create($url);
|
|
// If a route is match then it do not throws exception.
|
|
if (
|
|
\parse_url(config('app.url'), \PHP_URL_HOST) === \parse_url($url, \PHP_URL_HOST) &&
|
|
$routes->match($request)
|
|
) {
|
|
// Removes the matched url.
|
|
throw ValidationException::withMessages([
|
|
$field => sprintf(
|
|
':attribute : Il est interdit de coller une url de %s dans ce champ',
|
|
config('app.name')
|
|
)
|
|
]);
|
|
}
|
|
return $match;
|
|
} catch (NotFoundHttpException $e) {
|
|
return $match;
|
|
}
|
|
},
|
|
$text
|
|
);
|
|
return $text;
|
|
}
|
|
|
|
/**
|
|
* Generates an array from a dot separated string
|
|
*
|
|
* @param string $path
|
|
* @param mixed $value
|
|
* @param string $separator
|
|
* @return array
|
|
*/
|
|
public static function dotStringToNestedArray(string $path, $value, string $separator = '.'): array
|
|
{
|
|
$arr = $value;
|
|
$keys = array_reverse(explode($separator, $path));
|
|
|
|
foreach ($keys as $key) {
|
|
$arr = [$key => $arr];
|
|
}
|
|
return $arr;
|
|
}
|
|
|
|
/**
|
|
* Generate url using laravel route passing our group query if present
|
|
* This is used to keep ou group tracking
|
|
* Curd-policies is only used for root users as it cannot keep track of our group
|
|
* and validate things
|
|
*
|
|
* @param array|string $name
|
|
* @param mixed $parameters
|
|
* @param boolean $absolute
|
|
* @return string
|
|
* @throws \ErrorException If an object given as parameter is not a Model.
|
|
*/
|
|
public static function routeWithGroup($name, $parameters = [], bool $absolute = true): string
|
|
{
|
|
// * Handle if parameter if is an object.
|
|
if (\is_object($parameters)) {
|
|
$parents = \class_parents($parameters);
|
|
if ($parents === false or !\in_array(Model::class, $parents)) {
|
|
throw new \ErrorException(\sprintf(
|
|
'%s only support object of type %s',
|
|
__FUNCTION__,
|
|
Model::class
|
|
));
|
|
}
|
|
/** @var \Illuminate\Database\Eloquent\Model $model */
|
|
$model = $parameters;
|
|
$parameters = [Str::singular($model->getTable()) => $model];
|
|
}
|
|
// * Handle if parameter isnt and array like slug or else.
|
|
if (!is_array($parameters)) {
|
|
// * Best effort, result is not garantee.
|
|
$parameters = [$parameters];
|
|
}
|
|
// * Pass our group.
|
|
if ($group = Session::get('activeGroup', request()->group)) {
|
|
$parameters = array_merge($parameters, ['group' => $group]);
|
|
}
|
|
// * Call laravel route helper.
|
|
return route($name, $parameters, $absolute);
|
|
}
|
|
|
|
/**
|
|
* Mutltibyte string replace
|
|
* @param mixed $search
|
|
* @param mixed $replace
|
|
* @param mixed $subject
|
|
* @param integer $count
|
|
* @return mixed
|
|
*/
|
|
public static function mbReplace($search, $replace, $subject, int &$count = 0)
|
|
{
|
|
if (!is_array($search) && is_array($replace)) {
|
|
return false;
|
|
}
|
|
if (is_array($subject)) {
|
|
// Call mb_replace for each single string in $subject .
|
|
foreach ($subject as &$string) {
|
|
$string = &self::mbReplace($search, $replace, $string, $count);
|
|
}
|
|
} elseif (is_array($search)) {
|
|
if (!is_array($replace)) {
|
|
foreach ($search as &$string) {
|
|
$subject = self::mbReplace($string, $replace, $subject, $count);
|
|
}
|
|
} else {
|
|
$n = max(count($search), count($replace));
|
|
while ($n--) {
|
|
$subject = self::mbReplace(current($search), current($replace), $subject, $count);
|
|
next($search);
|
|
next($replace);
|
|
}
|
|
}
|
|
} else {
|
|
$parts = mb_split(preg_quote($search), $subject);
|
|
$count = count($parts) - 1;
|
|
$subject = implode($replace, $parts);
|
|
} //end if
|
|
return $subject;
|
|
}
|
|
|
|
/**
|
|
* Asserts that the field is unique
|
|
*
|
|
* @param string $table
|
|
* @param string $field
|
|
* @param mixed $value
|
|
* @param integer|null $id
|
|
* @param callable|null $query
|
|
* @return void
|
|
* @throws \Illuminate\Validation\ValidationException If the field is not unique.
|
|
*/
|
|
public static function assertFieldIsUnique(
|
|
string $table,
|
|
string $field,
|
|
$value,
|
|
?int $id = null,
|
|
?callable $query = null
|
|
) {
|
|
if (!$query) {
|
|
Validator::make([$field => $value], [
|
|
$field => Rule::unique($table, $field)->ignore($id),
|
|
], [
|
|
$field . '.unique' => trans('La valeur :value pour le champ :attribute est déjà utilisé', [
|
|
'attribute' => $field,
|
|
'value' => $value
|
|
])
|
|
])->validate();
|
|
return;
|
|
}
|
|
Validator::make([$field => $value], [
|
|
$field => Rule::unique($table)->where($query)->ignore($id),
|
|
], [
|
|
$field . '.unique' => trans('La valeur pour le champ :attribute est déjà utilisé', [
|
|
'attribute' => $field
|
|
])
|
|
])->validate();
|
|
}
|
|
|
|
/**
|
|
* Check that two arrays have the same content (1 level only)
|
|
*
|
|
* @param array $array1
|
|
* @param array $array2
|
|
* @return boolean
|
|
*/
|
|
public static function arrayHaveSameContent(array $array1, array $array2): bool
|
|
{
|
|
return (array_diff($array1, $array2) == [] && array_diff($array2, $array1) == []);
|
|
}
|
|
}
|