Completed
Push — 2.x-dev-kit ( 8d77e1 )
by
unknown
28:22 queued 25:50
created

MessageManagerBackend::getStatus()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 26
rs 8.439
cc 6
eloc 14
nc 6
nop 0
1
<?php
2
3
/*
4
 * This file is part of the Sonata project.
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\Backend;
13
14
use Sonata\NotificationBundle\Consumer\ConsumerEvent;
15
use Sonata\NotificationBundle\Exception\HandlingException;
16
use Sonata\NotificationBundle\Iterator\MessageManagerMessageIterator;
17
use Sonata\NotificationBundle\Model\MessageInterface;
18
use Sonata\NotificationBundle\Model\MessageManagerInterface;
19
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
20
use ZendDiagnostics\Result\Failure;
21
use ZendDiagnostics\Result\Success;
22
use ZendDiagnostics\Result\Warning;
23
24
class MessageManagerBackend implements BackendInterface
25
{
26
    /**
27
     * @var MessageManagerInterface
28
     */
29
    protected $messageManager;
30
31
    /**
32
     * @var array
33
     */
34
    protected $checkLevel;
35
36
    /**
37
     * @var int
38
     */
39
    protected $pause;
40
41
    /**
42
     * @var int
43
     */
44
    protected $maxAge;
45
46
    /**
47
     * @var MessageManagerBackendDispatcher|null
48
     */
49
    protected $dispatcher = null;
50
51
    /**
52
     * @var array
53
     */
54
    protected $types;
55
56
    /**
57
     * @var int
58
     */
59
    protected $batchSize;
60
61
    /**
62
     * @param MessageManagerInterface $messageManager
63
     * @param array                   $checkLevel
64
     * @param int                     $pause
65
     * @param int                     $maxAge
66
     * @param int                     $batchSize
67
     * @param array                   $types
68
     */
69
    public function __construct(MessageManagerInterface $messageManager, array $checkLevel, $pause = 500000, $maxAge = 86400, $batchSize = 10, array $types = array())
70
    {
71
        $this->messageManager = $messageManager;
72
        $this->checkLevel     = $checkLevel;
73
        $this->pause          = $pause;
74
        $this->maxAge         = $maxAge;
75
        $this->batchSize      = $batchSize;
76
        $this->types          = $types;
77
    }
78
79
    /**
80
     * @param array $types
81
     */
82
    public function setTypes($types)
83
    {
84
        $this->types = $types;
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90
    public function publish(MessageInterface $message)
91
    {
92
        $this->messageManager->save($message);
93
94
        return $message;
95
    }
96
97
    /**
98
     * {@inheritdoc}
99
     */
100
    public function create($type, array $body)
101
    {
102
        $message = $this->messageManager->create();
103
        $message->setType($type);
104
        $message->setBody($body);
105
        $message->setState(MessageInterface::STATE_OPEN);
106
107
        return $message;
108
    }
109
110
    /**
111
     * {@inheritdoc}
112
     */
113
    public function createAndPublish($type, array $body)
114
    {
115
        return $this->publish($this->create($type, $body));
116
    }
117
118
    /**
119
     * {@inheritdoc}
120
     */
121
    public function getIterator()
122
    {
123
        return new MessageManagerMessageIterator($this->messageManager, $this->types, $this->pause, $this->batchSize);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Sonata\Notif...use, $this->batchSize); (Sonata\NotificationBundl...eManagerMessageIterator) is incompatible with the return type declared by the interface Sonata\NotificationBundl...dInterface::getIterator of type Sonata\NotificationBundl...essageIteratorInterface.

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...
124
    }
125
126
    /**
127
     * {@inheritdoc}
128
     */
129
    public function initialize()
130
    {
131
    }
132
133
    /**
134
     * @param MessageManagerBackendDispatcher $dispatcher
135
     */
136
    public function setDispatcher(MessageManagerBackendDispatcher $dispatcher)
137
    {
138
        $this->dispatcher = $dispatcher;
139
    }
140
141
    /**
142
     * {@inheritdoc}
143
     */
144
    public function handle(MessageInterface $message, EventDispatcherInterface $dispatcher)
145
    {
146
        $event = new ConsumerEvent($message);
147
148
        try {
149
            $message->setStartedAt(new \DateTime());
150
            $message->setState(MessageInterface::STATE_IN_PROGRESS);
151
            $this->messageManager->save($message);
152
153
            $dispatcher->dispatch($message->getType(), $event);
154
155
            $message->setCompletedAt(new \DateTime());
156
            $message->setState(MessageInterface::STATE_DONE);
157
            $this->messageManager->save($message);
158
159
            return $event->getReturnInfo();
160
        } catch (\Exception $e) {
161
            $message->setCompletedAt(new \DateTime());
162
            $message->setState(MessageInterface::STATE_ERROR);
163
164
            $this->messageManager->save($message);
165
166
            throw new HandlingException('Error while handling a message', 0, $e);
167
        }
168
    }
169
170
    /**
171
     * {@inheritdoc}
172
     */
173
    public function getStatus()
174
    {
175
        try {
176
            $states = $this->messageManager->countStates();
177
        } catch (\Exception $e) {
178
            return new Failure(sprintf('Unable to retrieve message information - %s (Database)', $e->getMessage()));
179
        }
180
181
        if ($states[MessageInterface::STATE_IN_PROGRESS] > $this->checkLevel[MessageInterface::STATE_IN_PROGRESS]) {
182
            return new Failure('Too many messages processed at the same time (Database)');
183
        }
184
185
        if ($states[MessageInterface::STATE_ERROR] > $this->checkLevel[MessageInterface::STATE_ERROR]) {
186
            return new Failure('Too many errors (Database)');
187
        }
188
189
        if ($states[MessageInterface::STATE_OPEN] > $this->checkLevel[MessageInterface::STATE_OPEN]) {
190
            return new Warning('Too many messages waiting to be processed (Database)');
191
        }
192
193
        if ($states[MessageInterface::STATE_DONE] > $this->checkLevel[MessageInterface::STATE_DONE]) {
194
            return new Warning('Too many processed messages, please clean the database (Database)');
195
        }
196
197
        return new Success('Ok (Database)');
198
    }
199
200
    /**
201
     * {@inheritdoc}
202
     */
203
    public function cleanup()
204
    {
205
        $this->messageManager->cleanup($this->maxAge);
206
    }
207
}
208