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