Completed
Push — develop ( 1d039a...ce10f4 )
by John
05:22 queued 01:32
created

DEnumView   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 128
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 16
c 1
b 0
f 0
lcom 1
cbo 11
dl 0
loc 128
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
C listView() 0 64 13
B editView() 0 46 3
1
<?php
2
3
namespace Alpha\View;
4
5
use Alpha\Util\Config\ConfigProvider;
6
use Alpha\Util\Security\SecurityUtils;
7
use Alpha\Util\Http\Session\SessionProviderFactory;
8
use Alpha\Controller\Front\FrontController;
9
use Alpha\View\Widget\SmallTextBox;
10
use Alpha\View\Widget\Button;
11
use Alpha\Model\Type\DEnumItem;
12
use Alpha\Model\Type\SmallText;
13
14
/**
15
 * The rendering class for the DEnum class.
16
 *
17
 * @since 1.0
18
 *
19
 * @author John Collins <[email protected]>
20
 * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
21
 * @copyright Copyright (c) 2017, John Collins (founder of Alpha Framework).
22
 * All rights reserved.
23
 *
24
 * <pre>
25
 * Redistribution and use in source and binary forms, with or
26
 * without modification, are permitted provided that the
27
 * following conditions are met:
28
 *
29
 * * Redistributions of source code must retain the above
30
 *   copyright notice, this list of conditions and the
31
 *   following disclaimer.
32
 * * Redistributions in binary form must reproduce the above
33
 *   copyright notice, this list of conditions and the
34
 *   following disclaimer in the documentation and/or other
35
 *   materials provided with the distribution.
36
 * * Neither the name of the Alpha Framework nor the names
37
 *   of its contributors may be used to endorse or promote
38
 *   products derived from this software without specific
39
 *   prior written permission.
40
 *
41
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
42
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
43
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
44
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
45
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
46
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
47
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
48
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
49
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
51
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
52
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
53
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
54
 * </pre>
55
 */
56
class DEnumView extends View
57
{
58
    /**
59
     * Custom list view.
60
     *
61
     * @return string
62
     *
63
     * @since 1.0
64
     */
65
    public function listView($fields = array())
66
    {
67
        $config = ConfigProvider::getInstance();
68
        $sessionProvider = $config->get('session.provider.name');
69
        $session = SessionProviderFactory::getInstance($sessionProvider);
70
71
        $reflection = new \ReflectionClass(get_class($this->record));
72
        $properties = $reflection->getProperties();
73
        $labels = $this->record->getDataLabels();
74
        $colCount = 1;
75
76
        $html = '<form action="'.$fields['URI'].'" method="POST">';
77
        $html .= '<table class="table">';
78
        // first render all of the table headers
79
        $html .= '<tr>';
80
        foreach ($properties as $propObj) {
81
            $prop = $propObj->name;
82
            if (!in_array($prop, $this->record->getDefaultAttributes()) && !in_array($prop, $this->record->getTransientAttributes())) {
83
                if (get_class($this->record->getPropObject($prop)) != 'Alpha\Model\Type\Text') {
84
                    ++$colCount;
85
                    $html .= '  <th>'.$labels[$prop].'</th>';
86
                }
87
            }
88
            if ($prop == 'ID') {
89
                $html .= '  <th>'.$labels[$prop].'</th>';
90
            }
91
        }
92
        // render the count
93
        $html .= '  <th>Item count</th>';
94
95
        $html .= '</tr><tr>';
96
97
        // and now the values
98
        foreach ($properties as $propObj) {
99
            $prop = $propObj->name;
100
            if (!in_array($prop, $this->record->getDefaultAttributes()) && !in_array($prop, $this->record->getTransientAttributes())) {
101
                if (get_class($this->record->getPropObject($prop)) != 'Alpha\Model\Type\Text') {
102
                    $html .= '  <td>&nbsp;'.$this->record->get($prop).'</td>';
103
                }
104
            }
105
            if ($prop == 'ID') {
106
                $html .= '  <td>&nbsp;'.$this->record->getID().'</td>';
107
            }
108
        }
109
        // render the count
110
        $html .= '  <td>&nbsp;'.$this->record->getItemCount().'</td>';
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Alpha\Model\ActiveRecord as the method getItemCount() does only exist in the following sub-classes of Alpha\Model\ActiveRecord: Alpha\Model\Type\DEnum. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
111
112
        $html .= '</tr>';
113
114
        $html .= '<tr><td colspan="'.($colCount+1).'" style="text-align:center;">';
115
        // render edit buttons for admins only
116
        if ($session->get('currentUser') != null && $session->get('currentUser')->inGroup('Admin')) {
117
            $html .= '&nbsp;&nbsp;';
118
            $button = new Button("document.location = '".FrontController::generateSecureURL('act=Alpha\Controller\DEnumController&denumID='.$this->record->getID())."'", 'Edit', 'edit'.$this->record->getID().'But');
119
            $html .= $button->render();
120
        }
121
        $html .= '</td></tr>';
122
123
        $html .= '</table>';
124
125
        $html .= '</form>';
126
127
        return $html;
128
    }
129
130
    /**
131
     * Custom edit view.
132
     *
133
     * @return string
134
     *
135
     * @since 1.0
136
     */
137
    public function editView($fields = array())
138
    {
139
        $config = ConfigProvider::getInstance();
140
141
        $labels = $this->record->getDataLabels();
142
143
        $html = '<form action="'.$fields['URI'].'" method="POST" accept-charset="UTF-8">';
144
145
        $temp = new SmallTextBox($this->record->getPropObject('name'), $labels['name'], 'name', '', 0, true, true);
0 ignored issues
show
Documentation introduced by
$this->record->getPropObject('name') is of type object<Alpha\Model\Type\Type>|boolean, but the function expects a object<Alpha\Model\Type\SmallText>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Unused Code introduced by
The call to SmallTextBox::__construct() has too many arguments starting with 0.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
146
        $html .= $temp->render();
147
148
        $html .= '<h3>DEnum display values:</h3>';
149
150
        // now get all of the options for the enum and render
151
        $denum = $this->record;
152
        $tmp = new DEnumItem();
153
        $denumItems = $tmp->loadItems($denum->getID());
154
155
        foreach ($denumItems as $item) {
156
            $labels = $item->getDataLabels();
157
            $temp = new SmallTextBox($item->getPropObject('value'), $labels['value'], 'value_'.$item->getID(), '');
158
            $html .= $temp->render();
159
        }
160
161
        $fieldname = ($config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('version_num')) : 'version_num');
162
163
        $html .= '<input type="hidden" name="'.$fieldname.'" value="'.$this->record->getVersion().'"/>';
164
165
        $html .= '<h3>Add a new value to the DEnum dropdown list:</h3>';
166
167
        $temp = new SmallTextBox(new SmallText(), 'Dropdown value', 'new_value', '');
168
        $html .= $temp->render();
169
170
        $temp = new Button('submit', 'Save', 'saveBut');
171
        $html .= $temp->render();
172
        $html .= '&nbsp;&nbsp;';
173
        $temp = new Button("document.location = '".FrontController::generateSecureURL('act=Alpha\Controller\DEnumController')."'", 'Back to List', 'cancelBut');
174
        $html .= $temp->render();
175
        $html .= '';
176
177
        $html .= View::renderSecurityFields();
178
179
        $html .= '</form>';
180
181
        return $html;
182
    }
183
}
184