Completed
Branch develop (7f369c)
by Nicolas
04:28
created

ArticlesPostController::__invoke()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.009

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 2
nop 2
dl 0
loc 17
ccs 9
cts 10
cp 0.9
crap 3.009
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\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