Completed
Push — master ( 760d2d...04364f )
by Ankit
07:59
created

ImageHelper::image()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 17
rs 9.4285
cc 3
eloc 9
nc 4
nop 6
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
    public function image($dir, $image, $width = null, $height = null, array $options = [], array $attributes = [])
27
    {
28
        $attributes = array_replace_recursive($this->attributes, $attributes);
29
        $options    = array_replace_recursive($this->options, $options);
30
31
        $path = config('laravelimage.routePath') . '/' . $dir . $image . '?' . http_build_query($options, '', '&');
32
33
        if ( ! empty((int) $width)) {
34
            $path .= '&w=' . (int) $width;
35
        }
36
37
        if ( ! empty((int) $height)) {
38
            $path .= '&h=' . (int) $height;
39
        }
40
41
        return '<img src="' . asset($path) . '" ' . $this->buildAttributes($attributes) . ' />';
42
    }
43
44
    /**
45
     * @param $attributes
46
     *
47
     * @return null|string
48
     */
49
    protected function buildAttributes($attributes)
50
    {
51
        if ( ! $attributes) {
52
            return null;
53
        }
54
55
        $attributeMap = [];
56
        foreach ($attributes as $attribute => $value) {
57
            $attributeMap[] = $attribute . '="' . $value . '"';
58
        }
59
60
        return implode($attributeMap, ' ');
61
    }
62
}
63