Keyword.php 2.66 KB
<?php

namespace App\Models;

use App\Models\Pivots\GoalKeyword;
use Carbon\Carbon;
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',
        'campaign_external_id',
        'ad_group_id',
        'campaign_id',
        'keyword',
        'user_param_1',
        'user_param_2',
        'bid',
        'context_bid',
        'state',
        'status',
        'serving_status',
    ];

    protected $casts = [
    ];

    /**
     * @return Collection
     */
    static public function getPropertiesWatch()
    {
        return collect([
            'keyword',
            'user_param_1',
            'user_param_2',
        ]);
    }

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


        static::created(function (Keyword $keyword) {
            if ($keyword->campaign) {
                $keyword->campaign->copyGroupInGoalKeyword();
            }
        });

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

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

                if (!is_null($keyword->campaign_id) && is_null($keyword->getOriginal('campaign_id'))) {
                    $keyword->campaign->copyGroupInGoalKeyword();
                } else {
                    $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');
    }

    public function campaign()
    {
        return $this->belongsTo(Campaigns::class, 'campaign_id');
    }

}