Keyword.php 2.73 KB
<?php

namespace App\Models;

use App\Models\Pivots\GoalAdGroup;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;

class Keyword extends Model
{
    const STATE_OFF = 'OFF';
    const STATE_ON = 'ON';
    const STATE_SUSPENDED = 'SUSPENDED';

    const STATUS_ACCEPTED = 'ACCEPTED';
    const STATUS_DRAFT = 'DRAFT';
    const STATUS_REJECTED = 'REJECTED';
    const STATUS_UNKNOWN = 'UNKNOWN';

    const SERVING_STATUS_ELIGIBLE = 'ELIGIBLE';
    const SERVING_STATUS_RARELY_SERVED = 'RARELY_SERVED';

    protected $fillable = [
        'external_id',
        'ad_group_external_id',
        'ad_group_id',
        'keyword',
        'user_param_1',
        'user_param_2',
        'bid',
        'context_bid',
        'state',
        'status',
        'serving_status',
        'statistics_search',
        'statistics_network',
    ];

    protected $casts = [
        'external_id' => 'int',
        'ad_group_external_id' => 'int',
        'ad_group_id' => 'int',
        'bid' => 'int',
        'context_bid' => 'int',
        'statistics_search' => 'json',
        'statistics_network' => 'json',
    ];

    /**
     * @return Collection
     */
    static public function getPropertiesWatch()
    {
        return collect([
            'ad_group_external_id',
            'keyword',
            'user_param_1',
            'user_param_2',
            'bid',
            'context_bid',
            'state',
            'status',
            'serving_status',
            'statistics_search',
            'statistics_network',
        ]);
    }

    public static function boot()
    {
        parent::boot();

        static::created(function (Keyword $keyword) {
            //
        });

        static::updated(function (Keyword $keyword) {

            if (GoalKeyword::getPropertiesCopyWithPivot()->first(function ($property_name) use ($keyword) {
                return $keyword->{$property_name} !== $keyword->getOriginal($property_name);
            })) {
                $keyword->goalKeywords()->update(
                    GoalKeyword::copyPropertyFromMain($keyword)
                );
            }

            if (self::getPropertiesWatch()->first(function ($property_name) use ($keyword) {
                return $keyword->{$property_name} !== $keyword->getOriginal($property_name);
            })) {
                $keyword->goalKeywords()->update([
                    'updated_need' => Carbon::now(),
                ]);
            }

        });
    }

    public function goalKeywords()
    {
        return $this->hasMany(GoalKeyword::class, 'keyword_id');
    }

    public function group()
    {
        return $this->belongsTo(AdGroup::class, 'ad_group_id');
    }

}