News::setAttribute()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 8

Duplication

Lines 7
Ratio 87.5 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 7
loc 8
ccs 0
cts 7
cp 0
rs 10
c 0
b 0
f 0
cc 3
nc 2
nop 2
crap 12
1
<?php
2
3
namespace SET;
4
5
use Carbon\Carbon;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Support\Facades\Mail;
8
use SET\Handlers\DateFormat;
9
use SET\Mail\SendNewsEmail;
10
11
class News extends Model
12
{
13
    use DateFormat;
14
15
    protected $table = 'news';
16
    public $timestamps = true;
17
18
    protected $fillable = ['title', 'description', 'publish_date', 'expire_date', 'author_id', 'send_email'];
19
20
    public function attachments()
21
    {
22
        return $this->morphMany('SET\Attachment', 'imageable');
23
    }
24
25
    public function author()
26
    {
27
        return $this->belongsTo('SET\User', 'author_id');
28
    }
29
30
    /**
31
     * @param $query
32
     */
33
    public function scopePublishedNews($query)
34
    {
35
        return $query->where('publish_date', '<=', Carbon::today())
36
                ->where(function ($q) {
37
                    $q->where('expire_date', '>=', Carbon::today())
38
                    ->orWhere('expire_date', null);
39
                });
40
    }
41
42
    /**
43
     * Store empty values as null in the DB.
44
     *
45
     * @param string $key
46
     * @param mixed  $value
47
     *
48
     * @return $this
49
     */
50 View Code Duplication
    public function setAttribute($key, $value)
51
    {
52
        if (is_scalar($value) && $value === '') {
53
            $value = null;
54
        }
55
56
        return parent::setAttribute($key, $value);
57
    }
58
59
    public function getPublishDateAttribute()
60
    {
61
        return $this->dateFormat($this->attributes['publish_date']);
62
    }
63
64
    public function getExpirationDateAttribute()
65
    {
66
        return $this->dateFormat($this->attributes['expire_date']);
67
    }
68
69
    /**
70
     * Email the news on the publish_date when a news article is created or updated.
71
     */
72
    public function emailNews()
73
    {
74
        $publishDate = Carbon::createFromFormat('Y-m-d', $this->publish_date);
75
76
        if ($this->send_email && $publishDate->eq(Carbon::now())) {
77
            $users = User::skipSystem()->active()->get();
78
            Mail::bcc($users)->send(new SendNewsEmail($this));
79
        }
80
    }
81
}
82