Test Failed
Branch develop (7f369c)
by Nicolas
04:26
created

UsersPostController::__invoke()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 2
nop 1
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace App\Controller\Api;
4
5
use App\Entity\User;
6
use App\Form\UserType;
7
use Doctrine\ORM\EntityManagerInterface;
8
use FOS\RestBundle\Controller\Annotations\View;
9
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
10
use Symfony\Component\Form\FormFactoryInterface;
11
use Symfony\Component\Form\FormInterface;
12
use Symfony\Component\HttpFoundation\Request;
13
use Symfony\Component\Routing\Annotation\Route;
14
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
15
16
/**
17
 * UsersPostController.
18
 *
19
 * @Route("/api/users", name="api_users_post")
20
 * @Method("POST")
21
 * @View(statusCode=201, serializerGroups={"me"})
22
 */
23
class UsersPostController
24
{
25
    /**
26
     * @var FormFactoryInterface
27
     */
28
    protected $factory;
29
30
    /**
31
     * @var UserPasswordEncoderInterface
32
     */
33
    protected $encoder;
34
35
    /**
36
     * @var EntityManagerInterface
37
     */
38
    protected $manager;
39
40
    /**
41
     * @param FormFactoryInterface         $factory
42
     * @param UserPasswordEncoderInterface $encoder
43
     * @param EntityManagerInterface       $manager
44
     */
45
    public function __construct(
46
        FormFactoryInterface $factory,
47
        UserPasswordEncoderInterface $encoder,
48
        EntityManagerInterface $manager
49
    ) {
50
        $this->factory = $factory;
51
        $this->encoder = $encoder;
52
        $this->manager = $manager;
53
    }
54
55
    /**
56
     * @param Request $request
57
     *
58
     * @return array|FormInterface
59
     */
60
    public function __invoke(Request $request)
61
    {
62
        $user = new User();
63
64
        $form = $this->factory->createNamed('user', UserType::class, $user);
65
        $form->handleRequest($request);
66
67
        if ($form->isSubmitted() && $form->isValid()) {
68
            $user->setPassword($this->encoder->encodePassword($user, $user->getPassword()));
69
            $this->manager->persist($user);
70
            $this->manager->flush();
71
72
            return ['user' => $user];
73
        }
74
75
        return $form;
76
    }
77
}
78