Passed
Push — master ( bb9802...b428f1 )
by Julito
09:11
created

Message::setSendDate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Entity;
8
9
use ApiPlatform\Core\Annotation\ApiFilter;
10
use ApiPlatform\Core\Annotation\ApiProperty;
11
use ApiPlatform\Core\Annotation\ApiResource;
12
use ApiPlatform\Core\Annotation\ApiSubresource;
13
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\OrderFilter;
14
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter;
15
use Chamilo\CourseBundle\Entity\CGroup;
16
use DateTime;
17
use Doctrine\Common\Collections\ArrayCollection;
18
use Doctrine\Common\Collections\Collection;
19
use Doctrine\Common\Collections\Criteria;
20
use Doctrine\ORM\Mapping as ORM;
21
use Gedmo\Mapping\Annotation as Gedmo;
22
use Symfony\Component\Serializer\Annotation\Groups;
23
use Symfony\Component\Validator\Constraints as Assert;
24
25
/**
26
 * Message.
27
 *
28
 * @ORM\Table(name="message", indexes={
29
 *     @ORM\Index(name="idx_message_user_sender", columns={"user_sender_id"}),
30
 *     @ORM\Index(name="idx_message_group", columns={"group_id"}),
31
 *     @ORM\Index(name="idx_message_type", columns={"msg_type"})
32
 * })
33
 * @ORM\Entity(repositoryClass="Chamilo\CoreBundle\Repository\MessageRepository")
34
 * @ORM\EntityListeners({"Chamilo\CoreBundle\Entity\Listener\MessageListener"})
35
 */
36
#[ApiResource(
37
    collectionOperations: [
38
        'get' => [
39
            'security' => "is_granted('ROLE_USER')",  // the get collection is also filtered by MessageExtension.php
40
        ],
41
        'post' => [
42
            //'security' => "is_granted('ROLE_USER')",
43
            /*'messenger' => true,
44
            'output' => false,
45
            'status' => 202,*/
46
            'security_post_denormalize' => "is_granted('CREATE', object)",
47
            //            'deserialize' => false,
48
            //            'controller' => Create::class,
49
            //            'openapi_context' => [
50
            //                'requestBody' => [
51
            //                    'content' => [
52
            //                        'multipart/form-data' => [
53
            //                            'schema' => [
54
            //                                'type' => 'object',
55
            //                                'properties' => [
56
            //                                    'title' => [
57
            //                                        'type' => 'string',
58
            //                                    ],
59
            //                                    'content' => [
60
            //                                        'type' => 'string',
61
            //                                    ],
62
            //                                ],
63
            //                            ],
64
            //                        ],
65
            //                    ],
66
            //                ],
67
            //            ],
68
        ],
69
    ],
70
    itemOperations: [
71
        'get' => [
72
            'security' => "is_granted('VIEW', object)",
73
        ],
74
        'put' => [
75
            'security' => "is_granted('EDIT', object)",
76
        ],
77
        'delete' => [
78
            'security' => "is_granted('DELETE', object)",
79
        ],
80
    ],
81
    attributes: [
82
        'security' => "is_granted('ROLE_USER')",
83
    ],
84
    denormalizationContext: [
85
        'groups' => ['message:write'],
86
    ],
87
    normalizationContext: [
88
        'groups' => ['message:read'],
89
    ],
90
)]
91
#[ApiFilter(OrderFilter::class, properties: ['title', 'sendDate'])]
92
#[ApiFilter(SearchFilter::class, properties: [
93
    'msgType' => 'exact',
94
    'status' => 'exact',
95
    'sender' => 'exact',
96
    //'receivers' => 'exact',
97
    'receivers.receiver' => 'exact',
98
    'receivers.tags.tag' => 'exact',
99
])]
100
class Message
101
{
102
    public const MESSAGE_TYPE_INBOX = 1;
103
    public const MESSAGE_TYPE_OUTBOX = 2;
104
    public const MESSAGE_TYPE_PROMOTED = 3;
105
    public const MESSAGE_TYPE_WALL = 4;
106
    public const MESSAGE_TYPE_GROUP = 5;
107
    public const MESSAGE_TYPE_INVITATION = 6;
108
    public const MESSAGE_TYPE_CONVERSATION = 7;
109
110
    // status
111
    public const MESSAGE_STATUS_DELETED = 3;
112
    public const MESSAGE_STATUS_DRAFT = 4;
113
    public const MESSAGE_STATUS_INVITATION_PENDING = 5;
114
    public const MESSAGE_STATUS_INVITATION_ACCEPTED = 6;
115
    public const MESSAGE_STATUS_INVITATION_DENIED = 7;
116
    public const MESSAGE_STATUS_PROMOTED = 13;
117
118
    /**
119
     * @ORM\Column(name="id", type="bigint")
120
     * @ORM\Id
121
     * @ORM\GeneratedValue()
122
     */
123
    #[ApiProperty(identifier: true)]
124
    #[Groups(['message:read'])]
125
    protected ?int $id = null;
126
127
    /**
128
     * @ORM\ManyToOne(targetEntity="User", inversedBy="sentMessages")
129
     * @ORM\JoinColumn(name="user_sender_id", referencedColumnName="id", nullable=false)
130
     */
131
    #[Assert\NotBlank]
132
    #[Groups(['message:read', 'message:write'])]
133
    protected User $sender;
134
135
    /**
136
     * @var Collection|MessageRelUser[]
137
     *
138
     * @ORM\OneToMany(targetEntity="MessageRelUser", mappedBy="message", cascade={"persist", "remove"})
139
     */
140
    #[Assert\Valid]
141
    #[Groups(['message:read', 'message:write'])]
142
    #[ApiSubresource]
143
    protected array | null | Collection $receivers;
144
145
    /**
146
     * @ORM\Column(name="msg_type", type="smallint", nullable=false)
147
     */
148
    #[Assert\NotBlank]
149
    // @todo use enums with PHP 8.1
150
    /*#[Assert\Choice([
151
        self::MESSAGE_TYPE_INBOX,
152
        self::MESSAGE_TYPE_OUTBOX,
153
        self::MESSAGE_TYPE_PROMOTED,
154
    ])]*/
155
    /*#[ApiProperty(attributes: [
156
        'openapi_context' => [
157
            'type' => 'int',
158
            'enum' => [self::MESSAGE_TYPE_INBOX, self::MESSAGE_TYPE_OUTBOX],
159
        ],
160
    ])]*/
161
    #[Groups(['message:read', 'message:write'])]
162
    protected int $msgType;
163
164
    /**
165
     * @ORM\Column(name="status", type="smallint", nullable=false)
166
     */
167
    #[Assert\NotBlank]
168
    #[Groups(['message:read', 'message:write'])]
169
    protected int $status;
170
171
    /**
172
     * @ORM\Column(name="send_date", type="datetime", nullable=false)
173
     */
174
    #[Groups(['message:read'])]
175
    protected DateTime $sendDate;
176
177
    /**
178
     * @ORM\Column(name="title", type="string", length=255, nullable=false)
179
     */
180
    #[Assert\NotBlank]
181
    #[Groups(['message:read', 'message:write'])]
182
    protected string $title;
183
184
    /**
185
     * @ORM\Column(name="content", type="text", nullable=false)
186
     */
187
    #[Assert\NotBlank]
188
    #[Groups(['message:read', 'message:write'])]
189
    protected string $content;
190
191
    /**
192
     * @ORM\ManyToOne(targetEntity="Chamilo\CourseBundle\Entity\CGroup")
193
     * @ORM\JoinColumn(name="group_id", referencedColumnName="iid", nullable=true, onDelete="CASCADE")
194
     */
195
    protected ?CGroup $group = null;
196
197
    /**
198
     * @var Collection|Message[]
199
     * @ORM\OneToMany(targetEntity="Message", mappedBy="parent")
200
     */
201
    protected Collection $children;
202
203
    /**
204
     * @ORM\ManyToOne(targetEntity="Message", inversedBy="children")
205
     * @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
206
     */
207
    protected ?Message $parent = null;
208
209
    /**
210
     * @Gedmo\Timestampable(on="update")
211
     * @ORM\Column(name="update_date", type="datetime", nullable=true)
212
     */
213
    protected ?DateTime $updateDate;
214
215
    /**
216
     * @ORM\Column(name="votes", type="integer", nullable=true)
217
     */
218
    protected ?int $votes;
219
220
    /**
221
     * @var Collection|MessageAttachment[]
222
     *
223
     * @ORM\OneToMany(targetEntity="MessageAttachment", mappedBy="message")
224
     */
225
    protected Collection $attachments;
226
227
    /**
228
     * @var Collection|MessageFeedback[]
229
     *
230
     * @ORM\OneToMany(targetEntity="MessageFeedback", mappedBy="message", orphanRemoval=true)
231
     */
232
    protected Collection $likes;
233
234
    public function __construct()
235
    {
236
        $this->sendDate = new DateTime('now');
237
        $this->updateDate = $this->sendDate;
238
        $this->content = '';
239
        $this->attachments = new ArrayCollection();
240
        $this->children = new ArrayCollection();
241
        $this->likes = new ArrayCollection();
242
        $this->receivers = new ArrayCollection();
243
        $this->votes = 0;
244
        $this->status = 0;
245
    }
246
247
    /**
248
     * @return null|Collection|MessageRelUser[]
249
     */
250
    public function getReceivers()
251
    {
252
        return $this->receivers;
253
    }
254
255
    public function hasReceiver(User $receiver)
256
    {
257
        if ($this->receivers->count()) {
258
            $criteria = Criteria::create()->where(
259
                Criteria::expr()->eq('receiver', $receiver),
260
            )->andWhere(
261
                Criteria::expr()->eq('message', $this),
262
            );
263
264
            return $this->receivers->matching($criteria)->count() > 0;
265
        }
266
267
        return false;
268
    }
269
270
    public function addReceiver(User $receiver): self
271
    {
272
        $messageRelUser = (new MessageRelUser())
273
            ->setReceiver($receiver)
274
            ->setMessage($this)
275
        ;
276
        if (!$this->receivers->contains($messageRelUser)) {
277
            $this->receivers->add($messageRelUser);
278
        }
279
280
        return $this;
281
    }
282
283
    /**
284
     * @param Collection|MessageRelUser $receivers
285
     */
286
    public function setReceivers($receivers): self
287
    {
288
        /** @var MessageRelUser $receiver */
289
        foreach ($receivers as $receiver) {
290
            $receiver->setMessage($this);
291
        }
292
        $this->receivers = $receivers;
0 ignored issues
show
Documentation Bug introduced by
It seems like $receivers can also be of type Chamilo\CoreBundle\Entity\MessageRelUser. However, the property $receivers is declared as type Chamilo\CoreBundle\Entit...\Collections\Collection. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
293
294
        return $this;
295
    }
296
297
    public function setSender(User $sender): self
298
    {
299
        $this->sender = $sender;
300
301
        return $this;
302
    }
303
304
    public function getSender(): User
305
    {
306
        return $this->sender;
307
    }
308
309
    public function setMsgType(int $msgType): self
310
    {
311
        $this->msgType = $msgType;
312
313
        return $this;
314
    }
315
316
    public function getMsgType(): int
317
    {
318
        return $this->msgType;
319
    }
320
321
    public function setSendDate(DateTime $sendDate): self
322
    {
323
        $this->sendDate = $sendDate;
324
325
        return $this;
326
    }
327
328
    /**
329
     * Get sendDate.
330
     *
331
     * @return DateTime
332
     */
333
    public function getSendDate()
334
    {
335
        return $this->sendDate;
336
    }
337
338
    public function setTitle(string $title): self
339
    {
340
        $this->title = $title;
341
342
        return $this;
343
    }
344
345
    public function getTitle(): string
346
    {
347
        return $this->title;
348
    }
349
350
    public function setContent(string $content): self
351
    {
352
        $this->content = $content;
353
354
        return $this;
355
    }
356
357
    public function getContent(): string
358
    {
359
        return $this->content;
360
    }
361
362
    public function setUpdateDate(DateTime $updateDate): self
363
    {
364
        $this->updateDate = $updateDate;
365
366
        return $this;
367
    }
368
369
    /**
370
     * Get updateDate.
371
     *
372
     * @return DateTime
373
     */
374
    public function getUpdateDate()
375
    {
376
        return $this->updateDate;
377
    }
378
379
    /**
380
     * Get id.
381
     *
382
     * @return int
383
     */
384
    public function getId()
385
    {
386
        return $this->id;
387
    }
388
389
    public function setVotes(int $votes): self
390
    {
391
        $this->votes = $votes;
392
393
        return $this;
394
    }
395
396
    public function getVotes(): int
397
    {
398
        return $this->votes;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->votes could return the type null which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
399
    }
400
401
    /**
402
     * Get attachments.
403
     *
404
     * @return Collection|MessageAttachment[]
405
     */
406
    public function getAttachments()
407
    {
408
        return $this->attachments;
409
    }
410
411
    public function addAttachment(MessageAttachment $attachment): self
412
    {
413
        $this->attachments->add($attachment);
414
        $attachment->setMessage($this);
415
416
        return $this;
417
    }
418
419
    public function getParent(): ?self
420
    {
421
        return $this->parent;
422
    }
423
424
    /**
425
     * @return Collection|Message[]
426
     */
427
    public function getChildren()
428
    {
429
        return $this->children;
430
    }
431
432
    public function addChild(self $child): self
433
    {
434
        $this->children[] = $child;
435
        $child->setParent($this);
436
437
        return $this;
438
    }
439
440
    public function setParent(self $parent = null): self
441
    {
442
        $this->parent = $parent;
443
444
        return $this;
445
    }
446
447
    /**
448
     * @return MessageFeedback[]|Collection
449
     */
450
    public function getLikes()
451
    {
452
        return $this->likes;
453
    }
454
455
    public function getGroup(): ?CGroup
456
    {
457
        return $this->group;
458
    }
459
460
    public function setGroup(?CGroup $group): self
461
    {
462
        $this->msgType = self::MESSAGE_TYPE_GROUP;
463
        $this->group = $group;
464
465
        return $this;
466
    }
467
468
    public function getStatus(): int
469
    {
470
        return $this->status;
471
    }
472
473
    public function setStatus(int $status): self
474
    {
475
        $this->status = $status;
476
477
        return $this;
478
    }
479
}
480