ImageHelper::image()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 9
cts 9
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 9
nc 4
nop 6
crap 3
1
<?php
2
3
namespace AnkitPokhrel\LaravelImage;
4
5
class ImageHelper
6
{
7
    /** @var array $attributes Default attributes */
8
    protected $attributes = [
9
        'alt'   => null,
10
        'class' => null,
11
    ];
12
13
    protected $options = [
14
        'fit' => 'crop-center',
15
    ];
16
17
    /**
18
     * @param $dir string Directory to search
19
     * @param string $image   Image name
20
     * @param null   $width
21
     * @param null   $height
22
     * @param array  $options
23
     *
24
     * @return string
25
     */
26 3
    public function image($dir, $image, $width = null, $height = null, array $options = [], array $attributes = [])
27
    {
28 3
        $attributes = array_replace_recursive($this->attributes, $attributes);
29 3
        $options    = array_replace_recursive($this->options, $options);
30
31 3
        $path = config('laravelimage.routePath') . '/' . $dir . $image . '?' . http_build_query($options, '', '&');
32
33 3
        if ( ! empty((int) $width)) {
34 3
            $path .= '&w=' . (int) $width;
35
        }
36
37 3
        if ( ! empty((int) $height)) {
38 3
            $path .= '&h=' . (int) $height;
39
        }
40
41 3
        return '<img src="' . asset($path) . '" ' . $this->buildAttributes($attributes) . ' />';
42
    }
43
44
    /**
45
     * @param $attributes
46
     *
47
     * @codeCoverageIgnore
48
     *
49
     * @return null|string
50
     */
51
    protected function buildAttributes($attributes)
52
    {
53
        if ( ! $attributes) {
54
            return;
55
        }
56
57
        $attributeMap = [];
58
        foreach ($attributes as $attribute => $value) {
59
            $attributeMap[] = $attribute . '="' . $value . '"';
60
        }
61
62
        return implode($attributeMap, ' ');
63
    }
64
}
65