summaryrefslogtreecommitdiffstats
path: root/vendor/iio/libmergepdf/src/Pages.php
blob: 7675315acca77c731cc320bc84d3920fc6f64c09 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php

declare(strict_types = 1);

namespace iio\libmergepdf;

/**
 * Parse page numbers from string
 */
final class Pages implements PagesInterface
{
    /**
     * @var int[] Added integer page numbers
     */
    private $pages = [];

    /**
     * Parse page numbers from expression string
     *
     * Pages should be formatted as 1,3,6 or 12-16 or combined. Note that pages
     * are merged in the order that you provide them. If you put pages 12-14
     * before 1-5 then 12-14 will be placed first.
     */
    public function __construct(string $expressionString = '')
    {
        $expressions = explode(
            ',',
            str_replace(' ', '', $expressionString)
        );

        foreach ($expressions as $expr) {
            if (empty($expr)) {
                continue;
            }
            if (ctype_digit($expr)) {
                $this->addPage((int)$expr);
                continue;
            }
            if (preg_match("/^(\d+)-(\d+)/", $expr, $matches)) {
                $this->addRange((int)$matches[1], (int)$matches[2]);
                continue;
            }
            throw new Exception("Invalid page number(s) for expression '$expr'");
        }
    }

    /**
     * Add a single page
     */
    public function addPage(int $page): void
    {
        $this->pages[] = $page;
    }

    /**
     * Add a range of pages
     */
    public function addRange(int $start, int $end): void
    {
        $this->pages = array_merge($this->pages, range($start, $end));
    }

    public function getPageNumbers(): array
    {
        return $this->pages;
    }
}