123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140 |
- <?php
- namespace OC;
- use Psr\Log\LoggerInterface;
- class NaturalSort {
- private static $instance;
- private $collator;
- private $cache = [];
-
- public function __construct($injectedCollator = null) {
-
-
- if (isset($injectedCollator)) {
- $this->collator = $injectedCollator;
- \OC::$server->get(LoggerInterface::class)->debug('forced use of '.get_class($injectedCollator));
- }
- }
-
- private function naturalSortChunkify($t) {
-
-
- if (isset($this->cache[$t])) {
- return $this->cache[$t];
- }
- $tz = [];
- $x = 0;
- $y = -1;
- $n = null;
- while (isset($t[$x])) {
- $c = $t[$x];
-
- $m = ((!$n && $c === '.') || ($c >= '0' && $c <= '9'));
- if ($m !== $n) {
-
- $y++;
- $tz[$y] = '';
- $n = $m;
- }
- $tz[$y] .= $c;
- $x++;
- }
- $this->cache[$t] = $tz;
- return $tz;
- }
-
- private function getCollator() {
- if (!isset($this->collator)) {
-
-
- if (class_exists('Collator')) {
- $this->collator = new \Collator('en_US');
- } else {
- $this->collator = new \OC\NaturalSort_DefaultCollator();
- }
- }
- return $this->collator;
- }
-
- public function compare($a, $b) {
-
-
-
-
- $aa = self::naturalSortChunkify($a);
- $bb = self::naturalSortChunkify($b);
- for ($x = 0; isset($aa[$x]) && isset($bb[$x]); $x++) {
- $aChunk = $aa[$x];
- $bChunk = $bb[$x];
- if ($aChunk !== $bChunk) {
-
- if ($aChunk[0] >= '0' && $aChunk[0] <= '9' && $bChunk[0] >= '0' && $bChunk[0] <= '9') {
- $aNum = (int)$aChunk;
- $bNum = (int)$bChunk;
- return $aNum - $bNum;
- }
- return self::getCollator()->compare($aChunk, $bChunk);
- }
- }
- return count($aa) - count($bb);
- }
-
- public static function getInstance() {
- if (!isset(self::$instance)) {
- self::$instance = new \OC\NaturalSort();
- }
- return self::$instance;
- }
- }
|