Image::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Knp\MegaMAN\Markdown\Processor;
4
5
use Knp\MegaMAN\Extractor;
6
use Knp\MegaMAN\Markdown\Processor;
7
8
class Image implements Processor
9
{
10
    /**
11
     * @var Extractor
12
     */
13
    private $extractor;
14
15
    /**
16
     * @param Extractor $extractor
17
     */
18
    public function __construct(Extractor $extractor)
19
    {
20
        $this->extractor = $extractor;
21
    }
22
23
    /**
24
     * {@inheritdoc}
25
     */
26
    public function process($html)
27
    {
28
        $matches = [];
29
30
        if (false === preg_match_all('/<img([^>]*) src="(?!http)([^"]*)"/', $html, $matches)) {
31
            return $html;
32
        }
33
34
        if (null === $current = $this->extractor->getCurrent()) {
35
            return $html;
36
        }
37
38
        list($strings, $attributes, $files) = $matches;
39
40
        foreach ($strings as $index => $string) {
41
            $file = $files[$index];
42
43
            $path = sprintf('%s%s%s', dirname($current['readme']), DIRECTORY_SEPARATOR, $file);
44
45
            if (false === file_exists($path)) {
46
                continue;
47
            }
48
49
            if (false === $info = getimagesize($path)) {
50
                continue;
51
            }
52
53
            $data = sprintf('data:%s;base64,%s', $info['mime'], base64_encode(file_get_contents($path)));
54
55
            $html = str_replace(
56
                $string,
57
                sprintf('<img%s style="max-width: 100%%" src="%s"', $attributes[$index], $data),
58
                $html
59
            );
60
        }
61
62
        return $html;
63
    }
64
}
65