Completed
Push — master ( ae2ef6...079feb )
by Filipe
03:03
created

EntityEditMethods::redirectFromEdit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
ccs 0
cts 4
cp 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 2
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
        $form->setData($entity->asArray());
45
        
46
        if (!$form->wasSubmitted()) {
47
            return;
48
        }
49
50
        try {
51
            $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...
52
                ->setEntity($entity)
53
                ->setForm($form)
54
                ->update();
55
            ;
56
        } catch (InvalidFormDataException $caught) {
57
            Log::logger()->addNotice($caught->getMessage(), $form->getData());
58
            $this->addErrorMessage($this->getInvalidFormDataMessage());
59
            return;
60
        } catch (\Exception $caught) {
61
            Log::logger()->addCritical(
62
                $caught->getMessage(),
63
                $form->getData()
64
            );
65
            $this->addErrorMessage($this->getGeneralErrorMessage($caught));
66
            return;
67
        }
68
69
        $this->addSuccessMessage(
70
            $this->getEditSuccessMessage($this->getUpdateService()->getEntity())
71
        );
72
        $this->redirectFromEdit($entity);
73
    }
74
75
    /**
76
     * Redirect after successful entity change
77
     *
78
     * @param EntityInterface $entity
79
     *
80
     * @return $this|ControllerInterface|static
81
     */
82
    protected function redirectFromEdit(EntityInterface $entity)
83
    {
84
        return $this->redirect(
85
            $this->getBasePath().'/show/'.$entity->getId()
0 ignored issues
show
Bug introduced by
It seems like getBasePath() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
86
        );
87
    }
88
89
    /**
90
     * Get the update successful entity message
91
     *
92
     * @param EntityInterface $entity
93
     *
94
     * @return string
95
     */
96
    protected function getEditSuccessMessage(EntityInterface $entity)
97
    {
98
        $singleName = $this->getEntityNameSingular();
99
        $message = "The {$singleName} '%s' was successfully updated.";
100
        return sprintf($this->translate($message), $entity);
101
    }
102
    
103
    /**
104
     * Get update service
105
     *
106
     * @return EntityUpdateService
107
     */
108
    abstract public function getUpdateService();
109
110
    /**
111
     * @return FormInterface|EntityForm
112
     */
113
    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...
114
115
    /**
116
     * Get invalid form data message
117
     *
118
     * @param \Exception $caught
119
     *
120
     * @return string
121
     */
122
    abstract protected function getGeneralErrorMessage(\Exception $caught);
123
124
    /**
125
     * Get invalid form data message
126
     *
127
     * @return string
128
     */
129
    abstract protected function getInvalidFormDataMessage();
130
131
    /**
132
     * Sets a value to be used by render
133
     *
134
     * The key argument can be an associative array with values to be set
135
     * or a string naming the passed value. If an array is given then the
136
     * value will be ignored.
137
     *
138
     * Those values must be set in the request attributes so they can be used
139
     * latter by any other middle ware in the stack.
140
     *
141
     * @param string|array $key
142
     * @param mixed        $value
143
     *
144
     * @return ControllerInterface
145
     */
146
    abstract public function set($key, $value = null);
147
148
    /**
149
     * Redirects the flow to another route/path
150
     *
151
     * @param string $path the route or path to redirect to
152
     *
153
     * @return ControllerInterface|self|$this
154
     */
155
    abstract public function redirect($path);
156
157
    /**
158
     * Add an error flash message
159
     *
160
     * @param string $message
161
     * @return self
162
     */
163
    abstract public function addErrorMessage($message);
164
165
    /**
166
     * Add a success flash message
167
     *
168
     * @param string $message
169
     * @return self
170
     */
171
    abstract public function addSuccessMessage($message);
172
173
    /**
174
     * Handles the request to view an entity
175
     *
176
     * @param int $entityId
177
     *
178
     * @return null|EntityInterface
179
     */
180
    abstract public function show($entityId = 0);
181
182
    /**
183
     * Returns the translation for the provided message
184
     *
185
     * @param string $message
186
     * @param string $domain
187
     * @param string $locale
188
     *
189
     * @return string
190
     */
191
    abstract public function translate(
192
        $message, $domain = null, $locale = null
193
    );
194
195
    /**
196
     * Get entity singular name used on controller actions
197
     *
198
     * @return string
199
     */
200
    abstract protected function getEntityNameSingular();
201
}