summaryrefslogtreecommitdiffstats
path: root/library/Icingadb/Widget/IconImage.php
blob: fcf25c8e030a67fd28406992100e3198214ada16 (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
<?php

/* Icinga DB Web | (c) 2022 Icinga GmbH | GPLv2 */

namespace Icinga\Module\Icingadb\Widget;

use ipl\Html\BaseHtmlElement;
use ipl\Html\HtmlDocument;
use ipl\Web\Url;
use ipl\Web\Widget\Icon;

class IconImage extends BaseHtmlElement
{
    /** @var string */
    protected $source;

    /** @var ?string */
    protected $alt;

    protected $tag = 'img';

    /**
     * Create a new icon image
     *
     * @param string $source
     * @param ?string $alt The alternative text
     */
    public function __construct(string $source, ?string $alt)
    {
        $this->source = $source;
        $this->alt = $alt;
    }

    public function renderUnwrapped()
    {
        if (! $this->getAttributes()->has('src')) {
            // If it's an icon we don't need the <img> tag
            return '';
        }

        return parent::renderUnwrapped();
    }

    protected function assemble()
    {
        $src = $this->source;

        if (strpos($src, '.') === false) {
            $this->setWrapper((new HtmlDocument())->addHtml(new Icon($src)));
            return;
        }

        if (strpos($src, '/') === false) {
            $src = 'img/icons/' . $src;
        }

        if (getenv('ICINGAWEB_EXPORT_FORMAT') === 'pdf') {
            $srcUrl = Url::fromPath($src);
            $srcPath = $srcUrl->getRelativeUrl();
            if (! $srcUrl->isExternal() && file_exists($srcPath) && is_file($srcPath)) {
                $mimeType = @mime_content_type($srcPath);
                $content = @file_get_contents($srcPath);
                if ($mimeType !== false && $content !== false) {
                    $src = "data:$mimeType;base64," . base64_encode($content);
                }
            }
        }

        $this->addAttributes([
            'src' => $src,
            'alt' => $this->alt
        ]);
    }
}