Completed
Push — master ( a8612d...130145 )
by Jan
04:35
created

UserController::userSettings()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 71
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 34
c 1
b 0
f 0
nc 5
nop 3
dl 0
loc 71
rs 8.7537

How to fix   Long Method   

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
/**
3
 * part-db version 0.1
4
 * Copyright (C) 2005 Christoph Lechner
5
 * http://www.cl-projects.de/.
6
 *
7
 * part-db version 0.2+
8
 * Copyright (C) 2009 K. Jacobs and others (see authors.php)
9
 * http://code.google.com/p/part-db/
10
 *
11
 * Part-DB Version 0.4+
12
 * Copyright (C) 2016 - 2019 Jan Böhmer
13
 * https://github.com/jbtronics
14
 *
15
 * This program is free software; you can redistribute it and/or
16
 * modify it under the terms of the GNU General Public License
17
 * as published by the Free Software Foundation; either version 2
18
 * of the License, or (at your option) any later version.
19
 *
20
 * This program is distributed in the hope that it will be useful,
21
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 * GNU General Public License for more details.
24
 *
25
 * You should have received a copy of the GNU General Public License
26
 * along with this program; if not, write to the Free Software
27
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
28
 */
29
30
namespace App\Controller;
31
32
use App\Entity\Attachments\AttachmentType;
33
use App\Entity\UserSystem\User;
34
use App\Form\Permissions\PermissionsType;
35
use App\Form\UserAdminForm;
36
use App\Form\UserSettingsType;
37
use App\Services\EntityExporter;
38
use App\Services\EntityImporter;
39
use App\Services\StructuralElementRecursionHelper;
40
use Doctrine\ORM\EntityManagerInterface;
41
use Symfony\Component\Asset\Packages;
42
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
43
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
44
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
45
use Symfony\Component\HttpFoundation\Request;
46
use Symfony\Component\HttpFoundation\Response;
47
use Symfony\Component\Routing\Annotation\Route;
48
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
49
use Symfony\Component\Security\Core\Validator\Constraints\UserPassword;
50
use Symfony\Component\Serializer\SerializerInterface;
51
use Symfony\Component\Validator\Constraints\Length;
52
53
/**
54
 * @Route("/user")
55
 * Class UserController
56
 * @package App\Controller
57
 */
58
class UserController extends AdminPages\BaseAdminController
59
{
60
61
    protected $entity_class = User::class;
62
    protected $twig_template = 'AdminPages/UserAdmin.html.twig';
63
    protected $form_class = UserAdminForm::class;
64
    protected $route_base = 'user';
65
66
67
    /**
68
     * @Route("/{id}/edit", requirements={"id"="\d+"}, name="user_edit")
69
     * @Route("/{id}/", requirements={"id"="\d+"})
70
     */
71
    public function edit(User $entity, Request $request, EntityManagerInterface $em)
72
    {
73
        return $this->_edit($entity, $request, $em);
74
    }
75
76
    /**
77
     * @Route("/new", name="user_new")
78
     * @Route("/")
79
     *
80
     * @return Response
81
     */
82
    public function new(Request $request, EntityManagerInterface $em, EntityImporter $importer)
83
    {
84
        return $this->_new($request, $em, $importer);
85
    }
86
87
    /**
88
     * @Route("/{id}", name="user_delete", methods={"DELETE"})
89
     */
90
    public function delete(Request $request, User $entity, StructuralElementRecursionHelper $recursionHelper)
91
    {
92
        if ($entity->getID() == User::ID_ANONYMOUS) {
93
            throw new \InvalidArgumentException('You can not delete the anonymous user! It is needed for permission checking without a logged in user');
94
        }
95
        return $this->_delete($request, $entity, $recursionHelper);
96
    }
97
98
    /**
99
     * @Route("/export", name="user_export_all")
100
     * @param Request $request
101
     * @param SerializerInterface $serializer
102
     * @param EntityManagerInterface $em
103
     * @return Response
104
     */
105
    public function exportAll(EntityManagerInterface $em, EntityExporter $exporter, Request $request)
106
    {
107
        return $this->_exportAll($em, $exporter, $request);
108
    }
109
110
    /**
111
     * @Route("/{id}/export", name="user_export")
112
     * @param Request $request
113
     * @param AttachmentType $entity
114
     * @return Response
115
     */
116
    public function exportEntity(User $entity, EntityExporter $exporter, Request $request)
117
    {
118
        return $this->_exportEntity($entity, $exporter, $request);
119
    }
120
121
122
    /**
123
     * @Route("/info", name="user_info_self")
124
     * @Route("/{id}/info")
125
     */
126
    public function userInfo(?User $user, Packages $packages)
127
    {
128
        //If no user id was passed, then we show info about the current user
129
        if (null === $user) {
130
            $user = $this->getUser();
131
        } else {
132
            //Else we must check, if the current user is allowed to access $user
133
            $this->denyAccessUnlessGranted('read', $user);
134
        }
135
136
        if ($this->getParameter('use_gravatar')) {
137
            $avatar = $this->getGravatar($user->getEmail(), 200, 'identicon');
0 ignored issues
show
Bug introduced by
It seems like $user->getEmail() can also be of type null; however, parameter $email of App\Controller\UserController::getGravatar() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

137
            $avatar = $this->getGravatar(/** @scrutinizer ignore-type */ $user->getEmail(), 200, 'identicon');
Loading history...
138
        } else {
139
            $avatar = $packages->getUrl('/img/default_avatar.png');
140
        }
141
142
        //Show permissions to user
143
        $builder = $this->createFormBuilder()->add('permissions',PermissionsType::class, [
144
            'mapped' => false,
145
            'disabled' => true,
146
            'inherit' => true,
147
            'data' => $user
148
        ]);
149
150
        return $this->render('Users/user_info.html.twig', [
151
            'user' => $user,
152
            'avatar' => $avatar,
153
            'form' => $builder->getForm()->createView()
154
        ]);
155
    }
156
157
    /**
158
     * @Route("/settings", name="user_settings")
159
     */
160
    public function userSettings(Request $request, EntityManagerInterface $em, UserPasswordEncoderInterface $passwordEncoder)
161
    {
162
        /**
163
         * @var User
164
         */
165
        $user = $this->getUser();
166
167
        if(!$user instanceof User) {
168
            return new \RuntimeException("This controller only works only for Part-DB User objects!");
169
        }
170
171
        //When user change its settings, he should be logged  in fully.
172
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
173
174
        /***************************
175
         * User settings form
176
         ***************************/
177
178
        $form = $this->createForm(UserSettingsType::class, $user);
179
180
        $form->handleRequest($request);
181
182
        if ($form->isSubmitted() && $form->isValid()) {
183
            //$em->persist($user);
184
            $em->flush();
185
            $this->addFlash('success', 'user.settings.saved_flash');
186
        }
187
188
        /*****************************
189
         * Password change form
190
         ****************************/
191
192
        $pw_form = $this->createFormBuilder()
193
            ->add('old_password', PasswordType::class, [
194
                'label' => 'user.settings.pw_old.label',
195
                'constraints' => [new UserPassword()], ]) //This constraint checks, if the current user pw was inputted.
196
            ->add('new_password', RepeatedType::class, [
197
                'type' => PasswordType::class,
198
                'first_options' => ['label' => 'user.settings.pw_new.label'],
199
                'second_options' => ['label' => 'user.settings.pw_confirm.label'],
200
                'invalid_message' => 'password_must_match',
201
                'constraints' => [new Length([
202
                    'min' => 6,
203
                    'max' => 128,
204
                ])],
205
            ])
206
            ->add('submit', SubmitType::class, ['label' => 'save'])
207
            ->getForm();
208
209
        $pw_form->handleRequest($request);
210
211
        //Check if password if everything was correct, then save it to User and DB
212
        if ($pw_form->isSubmitted() && $pw_form->isValid()) {
213
            $password = $passwordEncoder->encodePassword($user, $pw_form['new_password']->getData());
214
            $user->setPassword($password);
215
216
            //After the change reset the password change needed setting
217
            $user->setNeedPwChange(false);
218
219
            $em->persist($user);
220
            $em->flush();
221
            $this->addFlash('success', 'user.settings.pw_changed_flash');
222
        }
223
224
        /******************************
225
         * Output both forms
226
         *****************************/
227
228
        return $this->render('Users/user_settings.html.twig', [
229
            'settings_form' => $form->createView(),
230
            'pw_form' => $pw_form->createView(),
231
        ]);
232
    }
233
234
    /**
235
     * Get either a Gravatar URL or complete image tag for a specified email address.
236
     *
237
     * @param string $email The email address
238
     * @param string $s     Size in pixels, defaults to 80px [ 1 - 2048 ]
239
     * @param string $d     Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
240
     * @param string $r     Maximum rating (inclusive) [ g | pg | r | x ]
241
     * @param bool   $img   True to return a complete IMG tag False for just the URL
242
     * @param array  $atts  Optional, additional key/value attributes to include in the IMG tag
243
     *
244
     * @return string containing either just a URL or a complete image tag
245
     * @source https://gravatar.com/site/implement/images/php/
246
     */
247
    public function getGravatar(string $email, int $s = 80, string $d = 'mm', string $r = 'g', bool $img = false, array $atts = array())
248
    {
249
        $url = 'https://www.gravatar.com/avatar/';
250
        $url .= md5(strtolower(trim($email)));
251
        $url .= "?s=$s&d=$d&r=$r";
252
        if ($img) {
253
            $url = '<img src="'.$url.'"';
254
            foreach ($atts as $key => $val) {
255
                $url .= ' '.$key.'="'.$val.'"';
256
            }
257
            $url .= ' />';
258
        }
259
260
        return $url;
261
    }
262
}
263