TypeAhead   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 82
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 6
dl 0
loc 82
ccs 33
cts 33
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A run() 0 9 2
B registerClientScript() 0 37 9
1
<?php
2
/**
3
 * @link https://github.com/2amigos/yii2-type-ahead-widget
4
 * @copyright Copyright (c) 2013-2015 2amigOS! Consulting Group LLC
5
 * @license http://opensource.org/licenses/BSD-3-Clause
6
 */
7
8
namespace dosamigos\typeahead;
9
10
use yii\helpers\Html;
11
use yii\helpers\Json;
12
use yii\widgets\InputWidget;
13
use Yii;
14
15
/**
16
 * TypeAhead renders a Twitter typeahead Bootstrap plugin.
17
 * @see http://twitter.github.io/typeahead.js/examples/
18
 * @author Antonio Ramirez <[email protected]>
19
 * @link http://www.ramirezcobos.com/
20
 * @link http://www.2amigos.us/
21
 * @package dosamigos\typeahead
22
 */
23
class TypeAhead extends InputWidget
24
{
25
    /**
26
     * @var array the options for the Bootstrap TypeAhead JS plugin.
27
     * Please refer to the Bootstrap TypeAhead plugin Web page for possible options.
28
     * @see https://github.com/twitter/typeahead.js#usage
29
     */
30
    public $clientOptions = [];
31
    /**
32
     * @var array the event handlers for the Bootstrap TypeAhead JS plugin.
33
     * Please refer to the Bootstrap TypeAhead plugin Web page for possible events.
34
     * @see https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md#custom-events
35
    */
36
    public $clientEvents = [];
37
    /**
38
     * @var array the datasets object arrays of the Bootstrap TypeAhead Js plugin.
39
     * @see https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md#datasets
40
     */
41
    public $dataSets = [];
42
    /**
43
     * @var array of [[Bloodhound]] instances. Please note, that the widget is just calling the object to return its
44
     * client script. In order to use its adapter, you will have to set it on the widget [[dataSets]] source option
45
     * and using the object instance as [[Bloodhound::getAdapter()]] method. This is required to be able to use multiple
46
     * datasets with bloodhound engine.
47
     * @see https://gist.github.com/jharding/9458772#file-remote-js
48
     */
49
    public $engines = [];
50
51
    /**
52
     * @inheritdoc
53
     */
54 3
    public function run()
55
    {
56 3
        if ($this->hasModel()) {
57 3
            echo Html::activeTextInput($this->model, $this->attribute, $this->options);
58 1
        } else {
59 3
            echo Html::textInput($this->name, $this->value, $this->options);
60
        }
61 3
        $this->registerClientScript();
62 3
    }
63
64
    /**
65
     * Registers Twitter TypeAhead Bootstrap plugin and the related events
66
     */
67 3
    protected function registerClientScript()
68
    {
69 3
        $view = $this->getView();
70
71 3
        TypeAheadPluginAsset::register($view);
72
73 3
        $id = $this->options['id'];
74
75 3
        $options = $this->clientOptions !== false && !empty($this->clientOptions)
76 1
            ? Json::encode($this->clientOptions)
77 3
            : 'null';
78
79 3
        foreach($this->dataSets as $dataSet) {
80 3
            if(empty($dataSet)) {
81 3
                continue;
82
            }
83 3
            $dataSets[] = Json::encode($dataSet);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$dataSets was never initialized. Although not strictly required by PHP, it is generally a good practice to add $dataSets = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
84 1
        }
85
86 3
        $dataSets = !empty($dataSets)
87 3
            ? implode(", ", $dataSets)
88 3
            : '{}';
89
90 3
        foreach ($this->engines as $bloodhound) {
91 3
            if ($bloodhound instanceof Bloodhound) {
92 3
                $js[] = $bloodhound->getClientScript();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$js was never initialized. Although not strictly required by PHP, it is generally a good practice to add $js = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
93 1
            }
94 1
        }
95
96 3
        $js[] = "jQuery('#$id').typeahead($options, $dataSets);";
0 ignored issues
show
Bug introduced by
The variable $js does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
97
98 3
        foreach ($this->clientEvents as $eventName => $handler) {
99 3
            $js[] = "jQuery('#$id').on('$eventName', $handler);";
100 1
        }
101
102 3
        $view->registerJs(implode("\n", $js));
103 3
    }
104
}
105