Completed
Pull Request — master (#110)
by
unknown
07:23
created

DoctrineProvider::findBy()   C

Complexity

Conditions 8
Paths 16

Size

Total Lines 26
Code Lines 16

Duplication

Lines 8
Ratio 30.77 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 0
Metric Value
dl 8
loc 26
ccs 0
cts 21
cp 0
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 16
nc 16
nop 1
crap 72
1
<?php
2
3
/**
4
 * Copyright Talisman Innovations Ltd. (2016). All rights reserved
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 *
18
 * @package     qpush-bundle
19
 * @copyright   Talisman Innovations Ltd. (2016)
20
 * @license     Apache License, Version 2.0
21
 */
22
23
namespace Uecode\Bundle\QPushBundle\Provider;
24
25
use Doctrine\Common\Cache\Cache;
26
use Monolog\Logger;
27
use Uecode\Bundle\QPushBundle\Message\Message;
28
use Uecode\Bundle\QPushBundle\Entity\DoctrineMessage;
29
30
class DoctrineProvider extends AbstractProvider
31
{
32
33
    protected $em;
34
    protected $repository;
35
    protected static $entityName = 'Uecode\Bundle\QPushBundle\Entity\DoctrineMessage';
36
37
    /**
38
     * Constructor for Provider classes
39
     *
40
     * @param string $name    Name of the Queue the provider is for
41
     * @param array  $options An array of configuration options for the Queue
42
     * @param mixed  $client  A Queue Client for the provider
43
     * @param Cache  $cache   An instance of Doctrine\Common\Cache\Cache
44
     * @param Logger $logger  An instance of Symfony\Bridge\Mongolog\Logger
45
     */
46
    public function __construct($name, array $options, $client, Cache $cache, Logger $logger)
47
    {
48
        $this->name = $name;
49
        $this->options = $options;
50
        $this->cache = $cache;
51
        $this->logger = $logger;
52
        $this->em = $client;
53
        $this->repository = $this->em->getRepository(self::$entityName);
54
    }
55
56
    /**
57
     * Returns the name of the Queue that this Provider is for
58
     *
59
     * @return string
60
     */
61
    public function getName()
62
    {
63
        return $this->name;
64
    }
65
66
    /**
67
     * Returns the Queue Provider name
68
     *
69
     * @return string
70
     */
71
    public function getProvider()
72
    {
73
        return 'Doctrine';
74
    }
75
76
    /**
77
     * Returns the Provider's Configuration Options
78
     *
79
     * @return array
80
     */
81
    public function getOptions()
82
    {
83
        return $this->options;
84
    }
85
86
    /**
87
     * Returns the Cache service
88
     *
89
     * @return Cache
90
     */
91
    public function getCache()
92
    {
93
        return $this->cache;
94
    }
95
96
    /**
97
     * Returns the Logger service
98
     *
99
     * @return Logger
100
     */
101
    public function getLogger()
102
    {
103
        return $this->logger;
104
    }
105
106
    /**
107
     * Get repository
108
     * 
109
     * @return array
110
     */
111
    public function getRepository()
112
    {
113
        if (!$this->repository) {
114
            return;
115
        }
116
        
117
        return $this->repository;
118
    }
119
120
    /**
121
     * Creates the Queue
122
     * Checks to see if the underlying table has been created or not
123
     * 
124
     * @return bool
125
     */
126
    public function create()
127
    {
128
        $sm = $this->em->getConnection()->getSchemaManager();
129
        $table = $this->em->getClassMetadata(self::$entityName)->getTableName();
130
        
131
        return $sm->tablesExist(array($table));
132
    }
133
134
    /**
135
     * Publishes a message to the Queue
136
     *
137
     * This method should return a string MessageId or Response
138
     *
139
     * @param array $message The message to queue
140
     * @param array $options An array of options that override the queue defaults
141
     *
142
     * @return string
143
     */
144
    public function publish(array $message, array $options = [])
145
    {
146
        if (!$this->em) {
147
            return '';
148
        }
149
150
        $doctrineMessage = new DoctrineMessage();
151
        $doctrineMessage->setQueue($this->name)
152
                ->setDelivered(false)
153
                ->setMessage($message)
154
                ->setLength(strlen(serialize($message)));
155
156
        $this->em->persist($doctrineMessage);
157
        $this->em->flush();
158
159
        return (string) $doctrineMessage->getId();
160
    }
161
162
    /**
163
     * Polls the Queue for Messages
164
     *
165
     * Depending on the Provider, this method may keep the connection open for
166
     * a configurable amount of time, to allow for long polling.  In most cases,
167
     * this method is not meant to be used to long poll indefinitely, but should
168
     * return in reasonable amount of time
169
     *
170
     * @param  array $options An array of options that override the queue defaults
171
     *
172
     * @return array
173
     */
174
    public function receive(array $options = [])
175
    {
176
        if (!$this->em) {
177
            return [];
178
        }
179
180
        $doctrineMessages = $this->repository->findBy(
181
                array('delivered' => false, 'queue' => $this->name),
182
                array('id' => 'ASC')
183
        );
184
185
        $messages = [];
186
        foreach ($doctrineMessages as $doctrineMessage) {
187
            $messages[] = new Message($doctrineMessage->getId(), $doctrineMessage->getMessage(), []);
188
            $doctrineMessage->setDelivered(true);
189
        }
190
        $this->em->flush();
191
192
        return $messages;
193
    }
194
195
    /**
196
     * Deletes the Queue Message
197
     *
198
     * @param mixed $id A message identifier or resource
199
     */
200
    public function delete($id)
201
    {
202
        $doctrineMessage = $this->repository->findById($id);
203
        $doctrineMessage->setDelivered(true);
204
        $this->em->flush();
205
        
206
        return true;
207
    }
208
209
    /**
210
     * Destroys a Queue and clears any Queue related Cache
211
     *
212
     * @return bool
213
     */
214
    public function destroy()
215
    {
216
        $qb = $this->repository->createQueryBuilder('dm');
217
        $qb->delete();
218
        $qb->where('dm.queue = :queue');
219
        $qb->setParameter('queue', $this->name);
220
        $qb->getQuery()->execute();
221
        
222
        return true;
223
    }
224
225
    /**
226
     * Returns a specific message
227
     * 
228
     * @param integer $id
229
     * 
230
     * @return Message
231
     */
232
    public function getById($id)
233
    {
234
        return $this->repository->find($id);
235
    }
236
237
    /**
238
     * Returns a query of the message queue
239
     * 
240
     * @param array $data ['field'=>'id', 'search'=>'text', 'to'=>date, from=>date]
241
     * @return Query
242
     * 
243
     */
244
    public function findBy($data)
245
    {
246
        $qb = $this->repository->createQueryBuilder('p');
247
        $qb->select('p');
248
        $qb->where('p.queue = :queue');
249
        $qb->setParameter('queue', $this->name);
250
251
        $field = (isset($data['field']))?$data['field']:'message';
252
        
253
        if (isset($data['search']) && $data['search'] !== null) {
254
            $qb->andWhere('p.'.$field.' LIKE :contains');
255
            $qb->setParameter('contains', '%' . $data['search'] . '%');
256
        }
257
258 View Code Duplication
        if (isset($data['from']) && $data['from'] !== null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
259
            $qb->andWhere('p.created >= :from');
260
            $qb->setParameter('from', $data['from']);
261
        }
262
263 View Code Duplication
        if (isset($data['to']) && $data['to'] !== null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
264
            $qb->andWhere('p.created <= :to');
265
            $qb->setParameter('to', $data['to']);
266
        }
267
268
        return $qb->getQuery();
269
    }
270
}
271