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

MessageController::getMessageManager()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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