Skip to content

Commit

Permalink
fix: Use multi-byte string methods
Browse files Browse the repository at this point in the history
  • Loading branch information
ambroisemaupate committed Sep 28, 2023
1 parent 324aa7a commit a9a5b84
Show file tree
Hide file tree
Showing 52 changed files with 87 additions and 87 deletions.
2 changes: 1 addition & 1 deletion lib/Documents/src/AbstractDocumentFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ public function updateDocument(DocumentInterface $document): DocumentInterface
}
}

$document->setFolder(substr(hash("crc32b", date('YmdHi')), 0, 12));
$document->setFolder(\mb_substr(hash("crc32b", date('YmdHi')), 0, 12));
}

$document->setFilename($this->getFileName());
Expand Down
2 changes: 1 addition & 1 deletion lib/Documents/src/Models/DocumentTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ public function isEmbed(): bool

protected function initDocumentTrait(): void
{
$this->setFolder(substr(hash("crc32b", date('YmdHi')), 0, 12));
$this->setFolder(\mb_substr(hash("crc32b", date('YmdHi')), 0, 12));
}

#[
Expand Down
2 changes: 1 addition & 1 deletion lib/Documents/src/TwigExtension/DocumentExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public function getFilters(): array
public function formatBytes($bytes, int $precision = 2): string
{
$size = ['B','kB','MB','GB','TB','PB','EB','ZB','YB'];
$factor = floor((strlen((string) $bytes) - 1) / 3);
$factor = floor((\mb_strlen((string) $bytes) - 1) / 3);
return sprintf("%.{$precision}f", (int) $bytes / pow(1024, $factor)) . @$size[$factor];
}

Expand Down
2 changes: 1 addition & 1 deletion lib/EntityGenerator/src/Field/NonVirtualFieldGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ protected function getMaxDefaultValuesLength(): int
$max = 0;
foreach (explode(',', $this->field->getDefaultValues()) as $value) {
$value = trim($value);
$max = max($max, strlen($value));
$max = max($max, \mb_strlen($value));
}

return $max > 0 ? $max : 250;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public function getMaxDefaultValuesLengthAmongAllFields(NodeTypeFieldInterface $
// get max length of exploded default values
$max = 0;
foreach ($this->getDefaultValuesAmongAllFields($field) as $value) {
$max = max($max, strlen($value));
$max = max($max, \mb_strlen($value));
}

return $max > 0 ? $max : 250;
Expand Down
2 changes: 1 addition & 1 deletion lib/Models/src/Roadiz/Utils/StringHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ public static function replaceLast(string $search, string $replace, string $subj
$pos = strrpos($subject, $search);

if ($pos !== false) {
$subject = substr_replace($subject, $replace, $pos, strlen($search));
$subject = \substr_replace($subject, $replace, $pos, \mb_strlen($search));
}

return $subject;
Expand Down
4 changes: 2 additions & 2 deletions lib/Random/src/PasswordGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@ public function generatePassword(int $length = 12)
$all = '';
$password = '';
foreach ($sets as $set) {
$password .= $set[array_rand(str_split($set))];
$password .= $set[array_rand(\mb_str_split($set))];
$all .= $set;
}

$all = str_split($all);
$all = \mb_str_split($all);
for ($i = 0; $i < $length - count($sets); $i++) {
$password .= $all[array_rand($all)];
}
Expand Down
2 changes: 1 addition & 1 deletion lib/RoadizCompatBundle/src/Controller/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ protected function generateUrl($route, array $parameters = [], int $referenceTyp
public static function getCalledClass()
{
$className = get_called_class();
if (strpos($className, "\\") !== 0) {
if (\mb_strpos($className, "\\") !== 0) {
$className = "\\" . $className;
}
return $className;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ private function registerThemeTranslatorResources(ContainerBuilder $container):
->followLinks()
->files()
->filter(function (\SplFileInfo $file) {
return 2 <= substr_count($file->getBasename(), '.') &&
preg_match('/\.\w+$/', $file->getBasename());
return 2 <= \mb_substr_count($file->getBasename(), '.') &&
\preg_match('/\.\w+$/', $file->getBasename());
})
->in($translationFolder)
->sortByName()
Expand All @@ -70,7 +70,7 @@ private function registerThemeTranslatorResources(ContainerBuilder $container):
'scanned_directories' => $scannedDirectories = [$translationFolder],
'cache_vary' => [
'scanned_directories' => array_map(static function (string $dir) use ($projectDir): string {
return str_starts_with($dir, $projectDir . '/') ? substr($dir, 1 + \strlen($projectDir)) : $dir;
return str_starts_with($dir, $projectDir . '/') ? \mb_substr($dir, 1 + \mb_strlen($projectDir)) : $dir;
}, $scannedDirectories),
],
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public function handle(bool $disabled = false)
* Query must be longer than 3 chars or Solr might crash
* on highlighting fields.
*/
if (strlen($query) > 3) {
if (\mb_strlen($query) > 3) {
$this->searchResults = $this->searchHandler->searchWithHighlight(
$query, # Use ?q query parameter to search with
$this->criteria, # a simple criteria array to filter search results
Expand Down
2 changes: 1 addition & 1 deletion lib/RoadizCoreBundle/src/Console/FilesExportCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ protected function zipFolder(ZipArchive $zip, string $folder, string $prefix = "
if (!$file->isDir()) {
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($folder) + 1);
$relativePath = \mb_substr($filePath, \mb_strlen($folder) + 1);

// Add current file to archive
$zip->addFile($filePath, $prefix . '/' . $relativePath);
Expand Down
2 changes: 1 addition & 1 deletion lib/RoadizCoreBundle/src/Console/UsersCreationCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ private function executeUserCreation(
}

if ($input->getOption('password')) {
if (strlen($input->getOption('password')) < 5) {
if (\mb_strlen($input->getOption('password')) < 5) {
throw new \InvalidArgumentException('Password is too short.');
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public function redirectAction(Request $request, Redirection $redirection): Redi

if (
null !== $redirection->getRedirectUri() &&
strlen($redirection->getRedirectUri()) > 0
\mb_strlen($redirection->getRedirectUri()) > 0
) {
return new RedirectResponse($redirection->getRedirectUri(), $redirection->getType());
}
Expand Down
2 changes: 1 addition & 1 deletion lib/RoadizCoreBundle/src/CustomForm/CustomFormHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ protected function getDocumentFolderForCustomForm(): ?Folder
->findOrCreateByPath(
'custom_forms/' .
$this->customForm->getCreatedAt()->format('Ymd') . '_' .
substr($this->customForm->getDisplayName(), 0, 30)
\mb_substr($this->customForm->getDisplayName(), 0, 30)
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ private function checkIfBundleRelativePath(string $path, ContainerBuilder $conta
{
if (isset($path[0]) && $path[0] === '@') {
$pathParts = explode('/', $path);
$bundleName = substr($pathParts[0], 1);
$bundleName = \mb_substr($pathParts[0], 1);
$bundlePath = $this->getBundlePath($bundleName, $container);
return $bundlePath . substr($path, strlen('@' . $bundleName));
return $bundlePath . \mb_substr($path, \mb_strlen('@' . $bundleName));
}

return $path;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void
$nodeTypes = $this->nodeTypes->all();
$map = [];
foreach ($nodeTypes as $type) {
$map[strtolower($type->getName())] = $type->getSourceEntityFullQualifiedClassName();
$map[\mb_strtolower($type->getName())] = $type->getSourceEntityFullQualifiedClassName();
}
$metadata->setDiscriminatorMap($map);

Expand Down
6 changes: 3 additions & 3 deletions lib/RoadizCoreBundle/src/Doctrine/ORM/SimpleQueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public function __construct(QueryBuilder $queryBuilder)
*/
public function getParameterKey(string $key): string
{
return strtolower(str_replace('.', '_', $key));
return \mb_strtolower(str_replace('.', '_', $key));
}

/**
Expand All @@ -57,7 +57,7 @@ public function buildExpressionWithBinding($value, string $prefix, string $key):
*/
public function buildExpressionWithoutBinding($value, string $prefix, string $key, string $baseKey = null)
{
if (strlen($prefix) > 0 && substr($prefix, -strlen('.')) !== '.') {
if (\mb_strlen($prefix) > 0 && \mb_substr($prefix, -\mb_strlen('.')) !== '.') {
$prefix .= '.';
}

Expand Down Expand Up @@ -111,7 +111,7 @@ public function buildExpressionWithoutBinding($value, string $prefix, string $ke
$fullKey = sprintf('LOWER(%s)', $prefix . $key);
return $this->queryBuilder->expr()->like(
$fullKey,
$this->queryBuilder->expr()->literal(strtolower($value[1] ?? ''))
$this->queryBuilder->expr()->literal(\mb_strtolower($value[1] ?? ''))
);
case 'NOT IN':
return $this->queryBuilder->expr()->notIn($prefix . $key, ':' . $baseKey);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ private function getCopyright(array $exif): ?string
foreach ($exif as $key => $section) {
if (is_array($section)) {
foreach ($section as $skey => $value) {
if (strtolower($skey) === 'copyright') {
if (\mb_strtolower($skey) === 'copyright') {
return $value;
}
}
Expand All @@ -99,18 +99,18 @@ private function getCopyright(array $exif): ?string
private function getDescription(array $exif): ?string
{
foreach ($exif as $key => $section) {
if (is_string($section) && strtolower($key) === 'imagedescription') {
if (is_string($section) && \mb_strtolower($key) === 'imagedescription') {
return $section;
} elseif (is_array($section)) {
if (strtolower($key) == 'comment') {
if (\mb_strtolower($key) == 'comment') {
$comment = '';
foreach ($section as $value) {
$comment .= $value . PHP_EOL;
}
return $comment;
} else {
foreach ($section as $skey => $value) {
if (strtolower($skey) == 'comment') {
if (\mb_strtolower($skey) == 'comment') {
return $value;
}
}
Expand Down
2 changes: 1 addition & 1 deletion lib/RoadizCoreBundle/src/Entity/NodeType.php
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,7 @@ public function getSourceEntityClassName(): string
#[SymfonySerializer\Ignore]
public function getSourceEntityTableName(): string
{
return 'ns_' . strtolower($this->getName());
return 'ns_' . \mb_strtolower($this->getName());
}

/**
Expand Down
2 changes: 1 addition & 1 deletion lib/RoadizCoreBundle/src/Entity/Role.php
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ public function removeGroup(Group $group): Role
#[SymfonySerializer\Groups(['role'])]
public function getClassName(): string
{
return str_replace('_', '-', strtolower($this->getRole()));
return str_replace('_', '-', \mb_strtolower($this->getRole()));
}

/**
Expand Down
2 changes: 1 addition & 1 deletion lib/RoadizCoreBundle/src/Entity/Setting.php
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ public function getName(): string
*/
public function setName(?string $name)
{
$this->name = trim(strtolower($name ?? ''));
$this->name = trim(\mb_strtolower($name ?? ''));
$this->name = (new UnicodeString($this->name))
->ascii()
->toString();
Expand Down
4 changes: 2 additions & 2 deletions lib/RoadizCoreBundle/src/Entity/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -741,7 +741,7 @@ public function setChroot(Node $chroot = null): User
public function getGravatarUrl(string $type = "identicon", string $size = "200"): string
{
if (null !== $this->getEmail()) {
return "https://www.gravatar.com/avatar/" . md5(strtolower(trim($this->getEmail()))) . "?d=" . $type . "&s=" . $size;
return "https://www.gravatar.com/avatar/" . md5(\mb_strtolower(trim($this->getEmail()))) . "?d=" . $type . "&s=" . $size;
}
return '';
}
Expand Down Expand Up @@ -932,7 +932,7 @@ public function hasGroup(string $name): bool
*/
public function hasRole(string $role): bool
{
return in_array(strtoupper((string) $role), $this->getRoles(), true);
return in_array(\mb_strtoupper((string) $role), $this->getRoles(), true);
}

/**
Expand Down
4 changes: 2 additions & 2 deletions lib/RoadizCoreBundle/src/Exception/ExceptionViewer.php
Original file line number Diff line number Diff line change
Expand Up @@ -266,8 +266,8 @@ public function isFormatJson(Request $request): bool
if (
$request->headers->get('Content-Type') &&
(
0 === strpos($request->headers->get('Content-Type'), 'application/json') ||
0 === strpos($request->headers->get('Content-Type'), 'application/ld+json')
0 === \mb_strpos($request->headers->get('Content-Type'), 'application/json') ||
0 === \mb_strpos($request->headers->get('Content-Type'), 'application/ld+json')
)
) {
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class HexadecimalColorValidator extends ConstraintValidator
public function validate(mixed $value, Constraint $constraint): void
{
if ($constraint instanceof HexadecimalColor) {
if (null !== $value && preg_match('#\#[0-9a-f]{6}#', strtolower($value)) === 0) {
if (null !== $value && preg_match('#\#[0-9a-f]{6}#', \mb_strtolower($value)) === 0) {
$this->context->addViolation($constraint->message);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public function validate(mixed $value, Constraint $constraint): void
{
if (null !== $value) {
$fieldName = StringHandler::variablize($value);
$lowerName = strtolower($value);
$lowerName = \mb_strtolower($value);
if (
in_array($value, NonSqlReservedWord::$forbiddenNames) ||
in_array($lowerName, NonSqlReservedWord::$forbiddenNames) ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class SimpleLatinStringValidator extends ConstraintValidator
public function validate(mixed $value, Constraint $constraint): void
{
if ($constraint instanceof SimpleLatinString) {
if (null !== $value && preg_match('#[^a-z_\s\-]#', strtolower($value)) === 1) {
if (null !== $value && preg_match('#[^a-z_\s\-]#', \mb_strtolower($value)) === 1) {
$this->context->addViolation($constraint->message);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,6 @@ protected function tagNameExists(string $name): bool
*/
protected function isMulti(?string $value): bool
{
return (bool) strpos($value ?? '', ',');
return (bool) \mb_strpos($value ?? '', ',');
}
}
2 changes: 1 addition & 1 deletion lib/RoadizCoreBundle/src/ListManager/Paginator.php
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ protected function getSearchQueryBuilder(string $alias): QueryBuilder
foreach ($this->getSearchableFields() as $field) {
$orX[] = $qb->expr()->like(
'LOWER(' . $alias . '.' . $field . ')',
$qb->expr()->literal('%' . mb_strtolower($this->searchPattern) . '%')
$qb->expr()->literal('%' . \mb_strtolower($this->searchPattern) . '%')
);
}
$qb->andWhere($qb->expr()->orX(...$orX));
Expand Down
2 changes: 1 addition & 1 deletion lib/RoadizCoreBundle/src/Mailer/ContactFormManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,7 @@ protected function isFieldPrivate(FormInterface $form): bool
];
return
is_string($key) &&
(substr($key, 0, 1) === '_' || \in_array($key, $privateFieldNames))
(\mb_substr($key, 0, 1) === '_' || \in_array($key, $privateFieldNames))
;
}

Expand Down
2 changes: 1 addition & 1 deletion lib/RoadizCoreBundle/src/Node/NodeFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public function create(
if (true === $repository->exists($nodeName)) {
$nodeName = $this->nodeNamePolicy->getSafeNodeName($source);
}
if (mb_strlen($nodeName) > 250) {
if (\mb_strlen($nodeName) > 250) {
throw new \InvalidArgumentException(sprintf('Node name "%s" is too long.', $nodeName));
}
$node->setNodeName($nodeName);
Expand Down
20 changes: 10 additions & 10 deletions lib/RoadizCoreBundle/src/Node/NodeNameChecker.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,14 @@ public function getCanonicalNodeName(NodesSources $nodeSource): string
$title = StringHandler::slugify($nodeSource->getTitle());
if ($nodeSource->isReachable() || !$this->useTypedSuffix) {
// truncate title to 250 chars if needed
if (strlen($title) > self::MAX_LENGTH) {
$title = substr($title, 0, self::MAX_LENGTH);
if (\mb_strlen($title) > self::MAX_LENGTH) {
$title = \mb_substr($title, 0, self::MAX_LENGTH);
}
return $title;
}
// truncate title if title + suffix + 1 exceed 250 chars
if ((strlen($title) + strlen($nodeTypeSuffix) + 1) > self::MAX_LENGTH) {
$title = substr($title, 0, self::MAX_LENGTH - (strlen($nodeTypeSuffix) + 1));
if ((\mb_strlen($title) + \mb_strlen($nodeTypeSuffix) + 1) > self::MAX_LENGTH) {
$title = \mb_substr($title, 0, self::MAX_LENGTH - (\mb_strlen($nodeTypeSuffix) + 1));
}
return sprintf(
'%s-%s',
Expand All @@ -63,11 +63,11 @@ public function getSafeNodeName(NodesSources $nodeSource): string
$uniqueId = uniqid();

// truncate canonicalNodeName if canonicalNodeName + uniqueId + 1 exceed 250 chars
if ((strlen($canonicalNodeName) + strlen($uniqueId) + 1) > self::MAX_LENGTH) {
$canonicalNodeName = substr(
if ((\mb_strlen($canonicalNodeName) + \mb_strlen($uniqueId) + 1) > self::MAX_LENGTH) {
$canonicalNodeName = \mb_substr(
$canonicalNodeName,
0,
self::MAX_LENGTH - (strlen($uniqueId) + 1)
self::MAX_LENGTH - (\mb_strlen($uniqueId) + 1)
);
}

Expand All @@ -84,11 +84,11 @@ public function getDatestampedNodeName(NodesSources $nodeSource): string
$timestamp = $nodeSource->getPublishedAt()->format('Y-m-d');

// truncate canonicalNodeName if canonicalNodeName + uniqueId + 1 exceed 250 chars
if ((strlen($canonicalNodeName) + strlen($timestamp) + 1) > self::MAX_LENGTH) {
$canonicalNodeName = substr(
if ((\mb_strlen($canonicalNodeName) + \mb_strlen($timestamp) + 1) > self::MAX_LENGTH) {
$canonicalNodeName = \mb_substr(
$canonicalNodeName,
0,
self::MAX_LENGTH - (strlen($timestamp) + 1)
self::MAX_LENGTH - (\mb_strlen($timestamp) + 1)
);
}

Expand Down
2 changes: 1 addition & 1 deletion lib/RoadizCoreBundle/src/Node/NodeTranstyper.php
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ protected function mockTranstype(NodeTypeInterface $nodeType): void

$translation = new Translation();
$translation->setAvailable(true);
$translation->setLocale(substr($uniqueId, 0, 10));
$translation->setLocale(\mb_substr($uniqueId, 0, 10));
$translation->setName('test' . $uniqueId);
$this->getManager()->persist($translation);

Expand Down
Loading

0 comments on commit a9a5b84

Please sign in to comment.