Passed
Branch develop (7f369c)
by Nicolas
04:17
created

ArticlesPostController   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 92.86%

Importance

Changes 0
Metric Value
dl 0
loc 45
ccs 13
cts 14
cp 0.9286
rs 10
c 0
b 0
f 0
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 17 3
A __construct() 0 4 1
1
<?php
2
3
namespace App\Controller\Api;
4
5
use App\Entity\Article;
6
use App\Entity\User;
7
use App\Form\ArticleType;
8
use Doctrine\ORM\EntityManagerInterface;
9
use FOS\RestBundle\Controller\Annotations\View;
10
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
11
use Symfony\Component\Form\FormFactoryInterface;
12
use Symfony\Component\Form\FormInterface;
13
use Symfony\Component\HttpFoundation\Request;
14
use Symfony\Component\Routing\Annotation\Route;
15
use Symfony\Component\Security\Core\User\UserInterface;
16
17
/**
18
 * UsersPostController.
19
 *
20
 * @Route("/api/articles", name="api_articles_post")
21
 * @Method("POST")
22
 * @View(statusCode=201)
23
 */
24
class ArticlesPostController
25
{
26
    /**
27
     * @var FormFactoryInterface
28
     */
29
    protected $factory;
30
31
    /**
32
     * @var EntityManagerInterface
33
     */
34
    protected $manager;
35
36
    /**
37
     * @param FormFactoryInterface   $factory
38
     * @param EntityManagerInterface $manager
39
     */
40 1
    public function __construct(FormFactoryInterface $factory, EntityManagerInterface $manager)
41
    {
42 1
        $this->factory = $factory;
43 1
        $this->manager = $manager;
44 1
    }
45
46
    /**
47
     * @param UserInterface $user
48
     * @param Request       $request
49
     *
50
     * @return array|FormInterface
51
     */
52 1
    public function __invoke(UserInterface $user, Request $request)
53
    {
54
        /** @var User $user */
55 1
        $article = new Article();
56 1
        $article->setAuthor($user);
57
58 1
        $form = $this->factory->createNamed('article', ArticleType::class, $article);
59 1
        $form->handleRequest($request);
60
61 1
        if ($form->isSubmitted() && $form->isValid()) {
62 1
            $this->manager->persist($article);
63 1
            $this->manager->flush();
64
65 1
            return ['article' => $article];
66
        }
67
68
        return $form;
69
    }
70
}
71