ImageColumn   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 3
dl 0
loc 58
ccs 0
cts 28
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 15 4
A renderDataCellContent() 0 19 4
1
<?php
2
3
/*
4
 * This file is part of the 2amigos/yii2-grid-view-library project.
5
 * (c) 2amigOS! <http://2amigos.us/>
6
 * For the full copyright and license information, please view
7
 * the LICENSE file that was distributed with this source code.
8
 */
9
10
namespace dosamigos\grid\columns;
11
12
use yii\helpers\ArrayHelper;
13
use yii\helpers\Html;
14
15
/**
16
 * ImageColumn displays an image tag. Assumes the attribute is a url to an image.
17
 */
18
class ImageColumn extends DataColumn
19
{
20
    /**
21
     * @var array the HTML options of the image tag
22
     */
23
    public $imgOptions = [];
24
    /**
25
     * @var string|callable $path if string will be prepended to the column's attribute. If a callable is provided, it
26
     *                      will call it passing the model's attribute value.
27
     */
28
    public $path;
29
    /**
30
     * @var string $emptyText renders if $attribute is null
31
     */
32
    public $emptyText = '';
33
34
    /**
35
     * @inheritdoc
36
     */
37
    public function init()
38
    {
39
        parent::init();
40
41
        if (!$this->format) {
42
            $this->format = 'html';
43
        }
44
45
        if (!empty($this->path)) {
46
            $this->path = mb_substr($this->path, -1) == '/'
47
                ? ''
48
                : '/';
49
        }
50
        return $this->path;
51
    }
52
53
    /**
54
     * @inheritdoc
55
     */
56
    protected function renderDataCellContent($model, $key, $index)
57
    {
58
        $content = $this->emptyText;
59
        $value = ArrayHelper::getValue($model, $this->attribute);
60
61
        if (!empty($value)) {
62
            $value = mb_substr($value, 0, 1) == '/'
63
                ? mb_substr($value, 1)
64
                : $value;
65
66
            $src = is_callable($this->path)
67
                ? call_user_func_array($this->path, [$value])
68
                : $this->path . $value;
69
70
            $content = Html::img($src, $this->imgOptions);
71
        }
72
73
        return $content;
74
    }
75
}
76