Passed
Branch develop (f6de6e)
by Nicolas
04:27
created

ArticlesPostController::__invoke()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3.0067

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 2
nop 1
dl 0
loc 18
ccs 10
cts 11
cp 0.9091
crap 3.0067
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace App\Controller\Api;
4
5
use App\Entity\Article;
6
use App\Form\ArticleType;
7
use App\Security\UserResolver;
8
use Doctrine\ORM\EntityManagerInterface;
9
use FOS\RestBundle\Controller\Annotations\View;
10
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
11
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
12
use Symfony\Component\Form\FormFactoryInterface;
13
use Symfony\Component\Form\FormInterface;
14
use Symfony\Component\HttpFoundation\Request;
15
use Symfony\Component\Routing\Annotation\Route;
16
17
/**
18
 * @Route("/api/articles", name="api_articles_post")
19
 * @Method("POST")
20
 *
21
 * @View(statusCode=201)
22
 *
23
 * @Security("is_granted('ROLE_USER')")
24
 */
25
final class ArticlesPostController
26
{
27
    /**
28
     * @var FormFactoryInterface
29
     */
30
    private $formFactory;
31
32
    /**
33
     * @var EntityManagerInterface
34
     */
35
    private $entityManager;
36
37
    /**
38
     * @var UserResolver
39
     */
40
    private $userResolver;
41
42
    /**
43
     * @param FormFactoryInterface   $formFactory
44
     * @param EntityManagerInterface $entityManager
45
     * @param UserResolver           $userResolver
46
     */
47 2
    public function __construct(
48
        FormFactoryInterface $formFactory,
49
        EntityManagerInterface $entityManager,
50
        UserResolver $userResolver
51
    ) {
52 2
        $this->formFactory = $formFactory;
53 2
        $this->entityManager = $entityManager;
54 2
        $this->userResolver = $userResolver;
55 2
    }
56
57
    /**
58
     * @param Request $request
59
     *
60
     * @throws \Exception
61
     *
62
     * @return array|FormInterface
63
     */
64 1
    public function __invoke(Request $request)
65
    {
66 1
        $user = $this->userResolver->getCurrentUser();
67
68 1
        $article = new Article();
69 1
        $article->setAuthor($user);
70
71 1
        $form = $this->formFactory->createNamed('article', ArticleType::class, $article);
72 1
        $form->handleRequest($request);
73
74 1
        if ($form->isSubmitted() && $form->isValid()) {
75 1
            $this->entityManager->persist($article);
76 1
            $this->entityManager->flush();
77
78 1
            return ['article' => $article];
79
        }
80
81
        return $form;
82
    }
83
}
84