summaryrefslogtreecommitdiffstats
path: root/library/Icinga/Chart/Primitive/Line.php
blob: d83cbeabe3340d58aff3b6ba3edf335c00568a4e (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
/* Icinga Web 2 | (c) 2013 Icinga Development Team | GPLv2+ */

namespace Icinga\Chart\Primitive;

use DOMDocument;
use DOMElement;
use Icinga\Chart\Render\RenderContext;
use Icinga\Chart\Format;

/**
 * Drawable for the svg line element
 */
class Line extends Styleable implements Drawable
{

    /**
     * The default stroke width
     *
     * @var int
     */
    public $strokeWidth = 1;

    /**
     * The line's start x coordinate
     *
     * @var int
     */
    private $xStart = 0;

    /**
     * The line's end x coordinate
     *
     * @var int
     */
    private $xEnd = 0;

    /**
     * The line's start y coordinate
     *
     * @var int
     */
    private $yStart = 0;

    /**
     * The line's end y coordinate
     *
     * @var int
     */
    private $yEnd = 0;

    /**
     * Create a line object starting at the first coordinate and ending at the second one
     *
     * @param int $x1   The line's start x coordinate
     * @param int $y1   The line's start y coordinate
     * @param int $x2   The line's end x coordinate
     * @param int $y2   The line's end y coordinate
     */
    public function __construct($x1, $y1, $x2, $y2)
    {
        $this->xStart = $x1;
        $this->xEnd = $x2;
        $this->yStart = $y1;
        $this->yEnd = $y2;
    }

    /**
     * Create the SVG representation from this Drawable
     *
     * @param   RenderContext $ctx The context to use for rendering
     * @return  DOMElement         The SVG Element
     */
    public function toSvg(RenderContext $ctx)
    {
        $doc = $ctx->getDocument();
        list($x1, $y1) = $ctx->toAbsolute($this->xStart, $this->yStart);
        list($x2, $y2) = $ctx->toAbsolute($this->xEnd, $this->yEnd);
        $line = $doc->createElement('line');
        $line->setAttribute('x1', Format::formatSVGNumber($x1));
        $line->setAttribute('x2', Format::formatSVGNumber($x2));
        $line->setAttribute('y1', Format::formatSVGNumber($y1));
        $line->setAttribute('y2', Format::formatSVGNumber($y2));

        $id = $this->id ?? uniqid('line-');
        $line->setAttribute('id', $id);
        $this->setId($id);

        $this->applyAttributes($line);

        $style = new DOMDocument();
        $style->loadHTML($this->getStyle());

        $line->appendChild(
            $line->ownerDocument->importNode(
                $style->getElementsByTagName('style')->item(0),
                true
            )
        );

        return $line;
    }
}