Просмотр исходного кода

Core\Func: Optimize the friendly() method

Removed the transliterator_transliterate() function since it initializes a new Transliterator every time.
Currently, Transliterator is initialized once with the rules set, and then only the transliterate() method is used.
Visman 1 год назад
Родитель
Сommit
2ddd7796b0
1 измененных файлов с 24 добавлено и 7 удалено
  1. 24 7
      app/Core/Func.php

+ 24 - 7
app/Core/Func.php

@@ -13,6 +13,7 @@ namespace ForkBB\Core;
 use ForkBB\Core\Container;
 use ForkBB\Core\Container;
 use DateTime;
 use DateTime;
 use DateTimeZone;
 use DateTimeZone;
+use Transliterator;
 use function \ForkBB\__;
 use function \ForkBB\__;
 
 
 class Func
 class Func
@@ -37,8 +38,14 @@ class Func
      */
      */
     protected ?int $offset = null;
     protected ?int $offset = null;
 
 
+    /**
+     * Копия $this->c->FRIENDLY_URL
+     */
+    protected array $fUrl;
+
     public function __construct(protected Container $c)
     public function __construct(protected Container $c)
     {
     {
+        $this->fUrl = $this->c->FRIENDLY_URL;
     }
     }
 
 
     /**
     /**
@@ -303,23 +310,33 @@ class Func
         }
         }
     }
     }
 
 
+    /**
+     * Для кэширования транслитератора
+     */
+    protected Transliterator|false|null $transl = null;
+
     /**
     /**
      * Преобразует строку в соотвествии с правилами FRIENDLY_URL
      * Преобразует строку в соотвествии с правилами FRIENDLY_URL
      */
      */
     public function friendly(string $str): string
     public function friendly(string $str): string
     {
     {
-        $conf = $this->c->FRIENDLY_URL;
-        $rule = $conf['translit'];
+        if (null === $this->transl) {
+            if (empty($this->fUrl['translit'])) {
+                $this->transl = false;
+            } else {
+                $this->transl = Transliterator::create($this->fUrl['translit']) ?? false;
+            }
+        }
 
 
-        if (true === $conf['lowercase']) {
-            $rule .= 'Lower();';
+        if ($this->transl instanceof Transliterator) {
+            $str = $this->transl->transliterate($str);
         }
         }
 
 
-        if ('' !== $rule) {
-            $str = \transliterator_transliterate($rule, $str);
+        if (true === $this->fUrl['lowercase']) {
+            $str = \mb_strtolower($str, 'UTF-8');
         }
         }
 
 
-        if (true === $conf['WtoHyphen']) {
+        if (true === $this->fUrl['WtoHyphen']) {
             $str = \trim(\preg_replace(['%[^\w]+%u', '%_+%'], ['-', '_'], $str), '-_');
             $str = \trim(\preg_replace(['%[^\w]+%u', '%_+%'], ['-', '_'], $str), '-_');
         }
         }