Completed
Push — dev ( a70858...5b49da )
by nonanerz
06:08 queued 06:04
created

UserController::resetPasswordAction()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 28
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 6.2488

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 17
cts 21
cp 0.8095
rs 8.439
c 0
b 0
f 0
cc 6
eloc 21
nc 5
nop 1
crap 6.2488
1
<?php
2
3
namespace AppBundle\Controller\Api;
4
5
use AppBundle\Entity\S3\Image;
6
use AppBundle\Entity\User;
7
use AppBundle\Exception\JsonHttpException;
8
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
9
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
10
use Symfony\Component\HttpFoundation\JsonResponse;
11
use Symfony\Component\HttpFoundation\Request;
12
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
13
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
14
use Symfony\Component\Validator\ConstraintViolation;
15
use Symfony\Component\Validator\ConstraintViolationList;
16
17
class UserController extends Controller
18
{
19
    /**
20
     * @Route("/avatar", name="api_avatar")
21
     * @Method({"PUT"})
22
     */
23
    public function avatarAction(Request $request)
24
    {
25
        $headers = $request->headers;
26
        /** @var User $user */
27
        $user = $this->getUser();
28
29
        $image = new Image(sprintf('user/%d/avatar', $user->getId()));
30
        $image
31
            ->setContentType($headers->get('Content-Type'))
32
            ->setContent($request->getContent());
33
        /** @var ConstraintViolationList $errors */
34
        $errors = $this->get('validator')->validate($image, null, ['Api']);
35
36 View Code Duplication
        if ($errors->count()) {
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...
37
            $outErrors = [];
38
39
            /** @var ConstraintViolation $error */
40
            foreach ($errors as $error) {
41
                $outErrors['headers'][$error->getPropertyPath()] = $error->getMessage();
42
            }
43
44
            throw new JsonHttpException(400, 'Bad Request', $outErrors);
45
        }
46
        $user->setImage($image);
0 ignored issues
show
Documentation introduced by
$image is of type object<AppBundle\Entity\S3\Image>, but the function expects a string.

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...
47
        $this->getDoctrine()->getManager()->flush();
48
49
        return $this->json(['user' => $user], 201, [], [AbstractNormalizer::GROUPS => ['Short']]);
50
    }
51
52
    /**
53
     * @Route("/user")
54
     * @Method({"GET"})
55
     */
56 1
    public function userAction()
57
    {
58 1
        return $this->json(['user' => $this->getUser()], 200, [], [AbstractNormalizer::GROUPS => ['Detail']]);
59
    }
60
61
    /**
62
     * @Route("/password_reset", name="password_reset")
63
     * @Method({"POST"})
64
     *
65
     * @return JsonResponse
66
     */
67 1
    public function resetPasswordAction(Request $request)
68
    {
69 1
        $data = $request->getContent();
70 1
        if (!$data) {
71
            throw new JsonHttpException(400, 'Bad Request.');
72
        }
73 1
        $serializer = $this->get('serializer');
74 1
        $data = $serializer->decode($data, 'json');
75 1
        if (!isset($data['email']) || $data['email'] == null) {
76
            throw new JsonHttpException(400, 'Bad Request');
77
        }
78 1
        $user = $this->getDoctrine()->getRepository(User::class)->loadUserByEmail($data['email']);
79 1
        if (!$user) {
80 1
            throw new JsonHttpException(404, 'There is no user with this email');
81
        }
82 1
        $token = $user->getApiToken();
83 1
        if ($token == null) {
84
            $token = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
85
            $user->setApiToken($token);
86
        }
87 1
        $tomorrow = (new \DateTime())->modify('+24 hours');
88 1
        $user->setLinkExpiredAt($tomorrow);
89 1
        $this->getDoctrine()->getManager()->flush();
90 1
        $title = 'Hello '.$user->getFirstName();
91 1
        $this->get('app.email_notification')->sendNotification($user->getEmail(), $title, 'reset', $user);
92
93 1
        return $this->json(['message' => "You've got an update link on you email. Check your email"], 201);
94
    }
95
96
    /**
97
     * @Route("/email")
98
     * @Method({"PUT"})
99
     */
100
    public function emailAction(Request $request)
101
    {
102
        /** @var User $user */
103
        $user = $this->getUser();
104
105
        $this->get('serializer')
106
            ->deserialize($request->getContent(), User::class, 'json', [
107
                AbstractNormalizer::OBJECT_TO_POPULATE => $user
108
            ]);
109
        $errors = $this->get('validator')->validate($user);
110 View Code Duplication
        if ($errors->count()) {
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...
111
            $outErrors = [];
112
113
            /** @var ConstraintViolation $error */
114
            foreach ($errors as $error) {
115
                $outErrors[$error->getPropertyPath()] = $error->getMessage();
116
            }
117
118
            throw new JsonHttpException(400, 'Bad Request', $outErrors);
119
        }
120
        $this->getDoctrine()->getManager()->flush();
121
122
        return $this->json(['user' => $this->getUser()], 200, [], [AbstractNormalizer::GROUPS => ['Short']]);
123
    }
124
}
125