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

ArticlesPostController   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Test Coverage

Coverage 93.75%

Importance

Changes 0
Metric Value
dl 0
loc 57
ccs 15
cts 16
cp 0.9375
rs 10
c 0
b 0
f 0
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 18 3
A __construct() 0 8 1
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