getChoices()   C
last analyzed

Complexity

Conditions 13
Paths 216

Size

Total Lines 53
Code Lines 26

Duplication

Lines 8
Ratio 15.09 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 8
loc 53
rs 5.4006
cc 13
eloc 26
nc 216
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
require_once(dirname(__FILE__) . '/../select2/Select2.class.php');
3
4
/**
5
 * This widget is designed to generate more user friendly autocomplete widgets.
6
 *
7
 * @package     symfony
8
 * @subpackage  widget
9
 * @link        https://github.com/19Gerhard85/sfSelect2WidgetsPlugin
10
 * @author      Ing. Gerhard Schranz <[email protected]>
11
 * @version     0.1 2013-03-11
12
 */
13
class sfWidgetFormSelect2PropelChoiceSortable extends sfWidgetFormInput
14
{
15
    /**
16
     * Configures the current widget.
17
     *
18
     * Available options:
19
     *
20
     *  * url:            The URL to call to get the choices to use (required)
21
     *  * config:         A JavaScript array that configures the JQuery autocompleter widget
22
     *  * value_callback: A callback that converts the value before it is displayed
23
     *
24
     * @param array $options     An array of options
25
     * @param array $attributes  An array of default HTML attributes
26
     *
27
     * @see sfWidgetForm
28
     */
29
    protected function configure($options = array(), $attributes = array())
30
    {
31
        $this->addOption('culture', sfContext::getInstance()->getUser()->getCulture());
32
        $this->addOption('width', sfConfig::get('sf_sfSelect2Widgets_width'));
33
        $this->addRequiredOption('model');
34
        $this->addOption('add_empty', false);
35
        $this->addOption('method', '__toString');
36
        $this->addOption('key_method', 'getPrimaryKey');
37
        $this->addOption('order_by', null);
38
        $this->addOption('query_methods', array());
39
        $this->addOption('criteria', null);
40
        $this->addOption('connection', null);
41
        $this->addOption('multiple', false);
42
        // not used anymore
43
        $this->addOption('peer_method', 'doSelect');
44
45
        parent::configure($options, $attributes);
46
        $this->setOption('type', 'hidden');
47
    }
48
49
    public function getChoices()
50
    {
51
        $choices = array();
52
        if (false !== $this->getOption('add_empty'))
53
        {
54
            $choices[''] = true === $this->getOption('add_empty') ? '' : $this->getOption('add_empty');
55
        }
56
57
        $criteria = PropelQuery::from($this->getOption('model'));
58
        if ($this->getOption('criteria'))
59
        {
60
            $criteria->mergeWith($this->getOption('criteria'));
61
        }
62
        foreach ((array)$this->getOption('query_methods') as $methodName => $methodParams)
63
        {
64
            if(is_array($methodParams))
65
            {
66
                $criteria = call_user_func_array(array($criteria, $methodName), $methodParams);
67
            }
68
            else
69
            {
70
                $criteria = $criteria->$methodParams();
71
            }
72
        }
73
        if ($order = $this->getOption('order_by'))
74
        {
75
            $criteria->orderBy($order[0], $order[1]);
76
        }
77
        $objects = $criteria->find($this->getOption('connection'));
78
79
        $methodKey = $this->getOption('key_method');
80 View Code Duplication
        if (!method_exists($this->getOption('model'), $methodKey))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
81
        {
82
            throw new RuntimeException(sprintf('Class "%s" must implement a "%s" method to be rendered in a "%s" widget', $this->getOption('model'), $methodKey, __CLASS__));
83
        }
84
85
        $methodValue = $this->getOption('method');
86 View Code Duplication
        if (!method_exists($this->getOption('model'), $methodValue))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
87
        {
88
            throw new RuntimeException(sprintf('Class "%s" must implement a "%s" method to be rendered in a "%s" widget', $this->getOption('model'), $methodValue, __CLASS__));
89
        }
90
91
        foreach ($objects as $object)
92
        {
93
            $choices[$object->$methodKey()] = $object->$methodValue();
94
        }
95
96
        if (count($choices) > 0 && isset($choices['']) && $choices[''] == '') {
97
            $choices[''] = '&nbsp;';
98
        }
99
100
        return $choices;
101
    }
102
103
    /**
104
     * @param  string $name        The element name
105
     * @param  string $value       The date displayed in this widget
106
     * @param  array  $attributes  An array of HTML attributes to be merged with the default HTML attributes
107
     * @param  array  $errors      An array of errors for the field
108
     *
109
     * @return string An HTML tag string
110
     *
111
     * @see sfWidgetForm
112
     */
113
    public function render($name, $value = null, $attributes = array(), $errors = array())
114
    {
115
        $id = $this->generateId($name);
116
117
        $choices = $this->getChoices();
118
        $choices_render = array();
119
120
        foreach($choices as $key => $choice)
121
        {
122
            $choices_render[] = array(
123
                'id' => $key,
124
                'text' => $choice
125
            );
126
        }
127
128
        $choices_render = json_encode($choices_render);
129
        $value_render = json_encode($value);
130
131
        $return = parent::render($name, null, $attributes, $errors);
132
133
        $return .= sprintf(<<<EOF
134
<script type="text/javascript">
135
function formatResult(item)
136
{
137
    return item.text;
138
}
139
140
jQuery("#%s").select2(
141
{
142
    tags: $choices_render,
143
    width:              '%s',
144
    allowClear:         %s
145
});
146
147
jQuery("#$id").select2("val", $value_render);
148
149
jQuery("#$id").select2("container").find("ul.select2-choices").sortable({
150
    containment: 'parent',
151
    start: function() { $("#$id").select2("onSortStart"); },
152
    update: function() { $("#$id").select2("onSortEnd"); }
153
});
154
155
</script>
156
EOF
157
            ,
158
            $id,
159
            $this->getOption('width'),
160
            $this->getOption('add_empty') == true ? 'true' : 'false'
161
        );
162
163
        return $return;
164
    }
165
166
    /**
167
     * Gets the stylesheet paths associated with the widget.
168
     *
169
     * @return array An array of stylesheet paths
170
     */
171
    public function getStylesheets()
172
    {
173
        return Select2::addStylesheets();
174
    }
175
176
    /**
177
     * Gets the JavaScript paths associated with the widget.
178
     *
179
     * @return array An array of JavaScript paths
180
     */
181
    public function getJavascripts()
182
    {
183
        return Select2::addJavascripts($this->getOption('culture'));
184
    }
185
}
186