PageHelper::renderMinimal()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
c 1
b 0
f 0
nc 4
nop 3
dl 0
loc 15
rs 9.9666
1
<?php
2
/*
3
 * citeproc-php
4
 *
5
 * @link        http://github.com/seboettg/citeproc-php for the source repository
6
 * @copyright   Copyright (c) 2017 Sebastian Böttger.
7
 * @license     https://opensource.org/licenses/MIT
8
 */
9
10
namespace Seboettg\CiteProc\Util;
11
12
use Seboettg\CiteProc\Style\Options\PageRangeFormats;
13
14
/**
15
 * Class PageHelper
16
 * @package Seboettg\CiteProc\Util
17
 * @author Sebastian Böttger <[email protected]>
18
 */
19
class PageHelper
20
{
21
    /**
22
     * @param array $ranges
23
     * @param string $pageRangeFormat
24
     * @return string
25
     */
26
    public static function processPageRangeFormats($ranges, $pageRangeFormat)
27
    {
28
        list($from, $to) = $ranges;
29
30
        if (!empty($pageRangeFormat)) {
31
            switch ($pageRangeFormat) {
32
                case PageRangeFormats::MINIMAL:
33
                    $resTo = self::renderMinimal($from, $to, 0);
34
                    break;
35
                case PageRangeFormats::MINIMAL_TWO:
36
                    if (strlen($to) > 2) {
37
                        $resTo = self::renderMinimal($from, $to, strlen($to) - 2);
38
                    } else {
39
                        $resTo = $to;
40
                    }
41
                    break;
42
                case PageRangeFormats::CHICAGO:
43
                    $resTo = self::renderChicago($from, $to);
44
                    break;
45
                case PageRangeFormats::EXPANDED:
46
                default:
47
                    $resTo = $to;
48
            }
49
            return "$from-$resTo";
50
        }
51
        return "$from-$to";
52
    }
53
54
    /**
55
     *
56
     * @param $from
57
     * @param $to
58
     * @param int $limit
59
     * @return string
60
     */
61
    private static function renderMinimal($from, $to, $limit = 1)
62
    {
63
        $resTo = "";
64
        if (strlen($from) == strlen($to)) {
65
            for ($i = strlen($to) - 1; $i >= $limit; --$i) {
66
                $digitTo = $to[$i];
67
68
                $digitFrom = $from[$i];
69
                if ($digitTo !== $digitFrom) {
70
                    $resTo = $digitTo.$resTo;
71
                }
72
            }
73
            return $resTo;
74
        }
75
        return $to;
76
    }
77
78
    private static function renderChicago($from, $to)
79
    {
80
        if ($from > 100 && ($from % 100 > 0) && intval(($from / 100), 10) === intval(($to / 100), 10)) {
81
            return "".($to % 100);
82
        } elseif ($from >= 10000) {
83
            return "".($to % 1000);
84
        }
85
        return $to;
86
    }
87
}
88