1<?php
2
3/**
4 * Label handler is responsible for keeping all header labels unique.
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 * Class representing the LabelHandlers
12 */
13class LabelHandler {
14
15    /**
16     * Instance of a LabelHandler
17     * @var LabelHandler
18     */
19    protected static $instance;
20    /**
21     * All used labels.
22     * @var array
23     */
24    protected $labels;
25    /**
26     * Usage count of each label.
27     * @var array
28     */
29    protected $count;
30
31    /**
32     * The handler is singleton, so you can access it only by this function.
33     * @return LabelHandler
34     */
35    public static function getInstance() {
36        if(!isset(LabelHandler::$instance)) {
37            LabelHandler::$instance = new LabelHandler();
38        }
39        return LabelHandler::$instance;
40    }
41
42    /**
43     * Private constructor can be called only by getInstance method.
44     */
45    protected function __construct() {
46        $this->labels = array();
47        $this->count = array();
48    }
49
50    /**
51     * Inserts new label to array and returns its unique version.
52     * @param string $label
53     * @return string
54     */
55    public function newLabel($label) {
56        $search = array_search($label, $this->labels);
57        //if the occurence is first, just insert
58        if($search === FALSE) {
59            $this->labels[] = $label;
60            $this->count[] = 1;
61        }
62        //else increase count and return unique version with count in the end
63        else {
64            $this->count[$search]++;
65            $label .= $this->count[$search];
66        }
67        return $label;
68    }
69}
70