1<?php
2
3/**
4 * Rowspan handler is responsible for handling rowspan in tables.
5 *
6 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
7 * @author  Adam Kučera <adam.kucera@wrent.cz>
8 */
9
10/**
11 * includes data object representing Rowspan
12 */
13require_once DOKU_INC . 'lib/plugins/latexit/classes/Rowspan.php';
14
15class RowspanHandler {
16
17    /**
18     * All rowspans in table are saved here.
19     * @var array of Rowspan
20     */
21    protected $rowspans;
22
23    /**
24     * Init handler.
25     */
26    public function __construct() {
27        $this->rowspans = array();
28    }
29
30    /**
31     * Insert new Rowspan with a given params.
32     * @param int $rowspan Rowspan value itself.
33     * @param int $cell_id Cell order in a row.
34     */
35    public function insertRowspan($rowspan, $cell_id) {
36        $rs = new Rowspan($rowspan, $cell_id);
37        $this->rowspans[] = $rs;
38    }
39
40    /**
41     * Decreases a rowspan for given cell order by one.
42     * @param int $cell_id Cell order.
43     * @return void
44     */
45    public function decreaseRowspan($cell_id) {
46        $i = $this->findRowspan($cell_id);
47        if ($i == -1) {
48            return;
49        }
50        $rs = $this->rowspans[$i]->getRowspan() - 1;
51        $this->rowspans[$i]->setRowspan($rs);
52
53        //remove from array
54        if ($rs == 0) {
55            unset($this->rowspans[$i]);
56            $this->rowspans = array_values($this->rowspans);
57        }
58    }
59
60    /**
61     * Return the rowspan for a give cell order.
62     * @param int $cell_id Cell order
63     * @return int Rowspan value.
64     */
65    public function getRowspan($cell_id) {
66        $i = $this->findRowspan($cell_id);
67        if ($i == -1) {
68            return 0;
69        }
70        return $this->rowspans[$i]->getRowspan();
71    }
72
73    /**
74     * Function used for finding rowspan for a give cell order.
75     * @param int $cell_id Cell order
76     * @return int Rowspan position in array.
77     */
78    protected function findRowspan($cell_id) {
79        $i = 0;
80        while ($i < count($this->rowspans) && $cell_id != $this->rowspans[$i]->getCellId()) {
81            $i++;
82        }
83        if ($i >= count($this->rowspans)) {
84            //no rowspan with this cell id has been found
85            return -1;
86        } else {
87            return $i;
88        }
89    }
90
91}
92