Completed
Push — master ( c8924f...ae2ef6 )
by Filipe
02:36
created

EntityEditMethods   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 159
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
c 1
b 0
f 0
lcom 1
cbo 5
dl 0
loc 159
ccs 0
cts 31
cp 0
rs 10

13 Methods

Rating   Name   Duplication   Size   Complexity  
B edit() 0 37 5
A getEditSuccessMessage() 0 6 1
getUpdateService() 0 1 ?
getForm() 0 1 ?
getGeneralErrorMessage() 0 1 ?
getInvalidFormDataMessage() 0 1 ?
set() 0 1 ?
redirect() 0 1 ?
addErrorMessage() 0 1 ?
addSuccessMessage() 0 1 ?
show() 0 1 ?
translate() 0 3 ?
getEntityNameSingular() 0 1 ?
1
<?php
2
3
/**
4
 * This file is part of slick/mvc package
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace Slick\Mvc\Controller;
11
12
use Slick\Common\Log;
13
use Slick\Form\FormInterface;
14
use Slick\Mvc\ControllerInterface;
15
use Slick\Mvc\Exception\Service\InvalidFormDataException;
16
use Slick\Mvc\Form\EntityForm;
17
use Slick\Mvc\Service\Entity\EntityUpdateService;
18
use Slick\Orm\EntityInterface;
19
20
/**
21
 * Entity Edit Methods
22
 * 
23
 * @package Slick\Mvc\Controller
24
 * @author  Filipe Silva <[email protected]>
25
 */
26
trait EntityEditMethods
27
{
28
29
    /**
30
     * Handle the request to edit an entity
31
     * 
32
     * @param mixed $entityId
33
     */
34
    public function edit($entityId)
35
    {
36
        $entity = $this->show($entityId);
37
        $form = $this->getForm();
38
        $this->set(compact('form'));
39
        
40
        if (!$entity instanceof EntityInterface) {
41
            return;
42
        }
43
        
44
        if (!$form->wasSubmitted()) {
45
            return;
46
        }
47
48
        try {
49
            $this->getUpdateService()
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Slick\Mvc\Service\Entity\AbstractEntityService as the method setForm() does only exist in the following sub-classes of Slick\Mvc\Service\Entity\AbstractEntityService: Slick\Mvc\Service\Entity\EntityUpdateService. 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...
50
                ->setEntity($entity)
51
                ->setForm($form)
52
                ->update();
53
            ;
54
        } catch (InvalidFormDataException $caught) {
55
            Log::logger()->addNotice($caught->getMessage(), $form->getData());
56
            $this->addErrorMessage($this->getInvalidFormDataMessage());
57
            return;
58
        } catch (\Exception $caught) {
59
            Log::logger()->addCritical(
60
                $caught->getMessage(),
61
                $form->getData()
62
            );
63
            $this->addErrorMessage($this->getGeneralErrorMessage($caught));
64
            return;
65
        }
66
67
        $this->addSuccessMessage(
68
            $this->getEditSuccessMessage($this->getUpdateService()->getEntity())
69
        );
70
    }
71
72
    /**
73
     * Get the update successful entity message
74
     *
75
     * @param EntityInterface $entity
76
     *
77
     * @return string
78
     */
79
    protected function getEditSuccessMessage(EntityInterface $entity)
80
    {
81
        $singleName = $this->getEntityNameSingular();
82
        $message = "The {$singleName} '%s' was successfully updated.";
83
        return sprintf($this->translate($message), $entity);
84
    }
85
    
86
    /**
87
     * Get update service
88
     *
89
     * @return EntityUpdateService
90
     */
91
    abstract public function getUpdateService();
92
93
    /**
94
     * @return FormInterface|EntityForm
95
     */
96
    abstract function getForm();
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
97
98
    /**
99
     * Get invalid form data message
100
     *
101
     * @param \Exception $caught
102
     *
103
     * @return string
104
     */
105
    abstract protected function getGeneralErrorMessage(\Exception $caught);
106
107
    /**
108
     * Get invalid form data message
109
     *
110
     * @return string
111
     */
112
    abstract protected function getInvalidFormDataMessage();
113
114
    /**
115
     * Sets a value to be used by render
116
     *
117
     * The key argument can be an associative array with values to be set
118
     * or a string naming the passed value. If an array is given then the
119
     * value will be ignored.
120
     *
121
     * Those values must be set in the request attributes so they can be used
122
     * latter by any other middle ware in the stack.
123
     *
124
     * @param string|array $key
125
     * @param mixed        $value
126
     *
127
     * @return ControllerInterface
128
     */
129
    abstract public function set($key, $value = null);
130
131
    /**
132
     * Redirects the flow to another route/path
133
     *
134
     * @param string $path the route or path to redirect to
135
     *
136
     * @return ControllerInterface|self|$this
137
     */
138
    abstract public function redirect($path);
139
140
    /**
141
     * Add an error flash message
142
     *
143
     * @param string $message
144
     * @return self
145
     */
146
    abstract public function addErrorMessage($message);
147
148
    /**
149
     * Add a success flash message
150
     *
151
     * @param string $message
152
     * @return self
153
     */
154
    abstract public function addSuccessMessage($message);
155
156
    /**
157
     * Handles the request to view an entity
158
     *
159
     * @param int $entityId
160
     *
161
     * @return null|EntityInterface
162
     */
163
    abstract public function show($entityId = 0);
164
165
    /**
166
     * Returns the translation for the provided message
167
     *
168
     * @param string $message
169
     * @param string $domain
170
     * @param string $locale
171
     *
172
     * @return string
173
     */
174
    abstract public function translate(
175
        $message, $domain = null, $locale = null
176
    );
177
178
    /**
179
     * Get entity singular name used on controller actions
180
     *
181
     * @return string
182
     */
183
    abstract protected function getEntityNameSingular();
184
}