Completed
Pull Request — 3.x (#317)
by Jordi Sala
08:20
created

MessageController::postMessageAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 10
nc 2
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Sonata Project package.
5
 *
6
 * (c) Thomas Rabaix <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sonata\NotificationBundle\Controller\Api;
13
14
use FOS\RestBundle\Context\Context;
15
use FOS\RestBundle\Controller\Annotations\QueryParam;
16
use FOS\RestBundle\Controller\Annotations\Route;
17
use FOS\RestBundle\Controller\Annotations\View;
18
use FOS\RestBundle\Request\ParamFetcherInterface;
19
use FOS\RestBundle\View\View as FOSRestView;
20
use JMS\Serializer\SerializationContext;
21
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
22
use Sonata\DatagridBundle\Pager\PagerInterface;
23
use Sonata\NotificationBundle\Model\MessageInterface;
24
use Sonata\NotificationBundle\Model\MessageManagerInterface;
25
use Symfony\Component\Form\FormFactoryInterface;
26
use Symfony\Component\HttpFoundation\Request;
27
28
/**
29
 * @author Hugo Briand <[email protected]>
30
 */
31
class MessageController
32
{
33
    /**
34
     * @var MessageManagerInterface
35
     */
36
    protected $messageManager;
37
38
    /**
39
     * @var FormFactoryInterface
40
     */
41
    protected $formFactory;
42
43
    /**
44
     * @param MessageManagerInterface $messageManager
45
     * @param FormFactoryInterface    $formFactory
46
     */
47
    public function __construct(MessageManagerInterface $messageManager, FormFactoryInterface $formFactory)
48
    {
49
        $this->messageManager = $messageManager;
50
        $this->formFactory = $formFactory;
51
    }
52
53
    /**
54
     * Retrieves the list of messages (paginated).
55
     *
56
     * @ApiDoc(
57
     *  resource=true,
58
     *  output={"class"="Sonata\DatagridBundle\Pager\PagerInterface", "groups"={"sonata_api_read"}}
59
     * )
60
     *
61
     * @QueryParam(name="page", requirements="\d+", default="1", description="Page for message list pagination")
62
     * @QueryParam(name="count", requirements="\d+", default="10", description="Number of messages by page")
63
     * @QueryParam(name="type", nullable=true, description="Message type filter")
64
     * @QueryParam(name="state", requirements="\d+", strict=true, nullable=true, description="Message status filter")
65
     * @QueryParam(name="orderBy", map=true, requirements="ASC|DESC", nullable=true, strict=true, description="Query groups order by clause (key is field, value is direction)")
66
     *
67
     * @View(serializerGroups={"sonata_api_read"}, serializerEnableMaxDepthChecks=true)
68
     *
69
     * @param ParamFetcherInterface $paramFetcher
70
     *
71
     * @return PagerInterface
72
     */
73
    public function getMessagesAction(ParamFetcherInterface $paramFetcher)
74
    {
75
        $supportedCriteria = [
76
            'state' => '',
77
            'type' => '',
78
        ];
79
80
        $page = $paramFetcher->get('page');
81
        $limit = $paramFetcher->get('count');
82
        $sort = $paramFetcher->get('orderBy');
83
        $criteria = array_intersect_key($paramFetcher->all(), $supportedCriteria);
84
85
        foreach ($criteria as $key => $value) {
86
            if (null === $value) {
87
                unset($criteria[$key]);
88
            }
89
        }
90
91
        if (!$sort) {
92
            $sort = [];
93
        } elseif (!is_array($sort)) {
94
            $sort = [$sort => 'asc'];
95
        }
96
97
        return $this->getMessageManager()->getPager($criteria, $page, $limit, $sort);
98
    }
99
100
    /**
101
     * Adds a message.
102
     *
103
     * @ApiDoc(
104
     *  input={"class"="sonata_notification_api_form_message", "name"="", "groups"={"sonata_api_write"}},
105
     *  output={"class"="Sonata\NotificationBundle\Model\Message", "groups"={"sonata_api_read"}},
106
     *  statusCodes={
107
     *      200="Returned when successful",
108
     *      400="Returned when an error has occurred while message creation"
109
     *  }
110
     * )
111
     *
112
     * @View(serializerGroups={"sonata_api_read"}, serializerEnableMaxDepthChecks=true)
113
     *
114
     * @Route(requirements={"_format"="json|xml"})
115
     *
116
     * @param Request $request A Symfony request
117
     *
118
     * @return MessageInterface
119
     */
120
    public function postMessageAction(Request $request)
121
    {
122
        $message = null;
123
124
        $form = $this->formFactory->createNamed(null, 'sonata_notification_api_form_message', $message, [
125
            'csrf_protection' => false,
126
        ]);
127
128
        $form->handleRequest($request);
129
130
        if ($form->isValid()) {
131
            $message = $form->getData();
132
            $this->messageManager->save($message);
133
134
            return $message;
135
        }
136
137
        return $form;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $form; (Symfony\Component\Form\FormInterface) is incompatible with the return type documented by Sonata\NotificationBundl...ller::postMessageAction of type Sonata\NotificationBundle\Model\MessageInterface.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
138
    }
139
140
    /**
141
     * @return MessageManagerInterface
142
     */
143
    protected function getMessageManager()
144
    {
145
        return $this->messageManager;
146
    }
147
}
148