ThumbProjectImage.php 2.3 KB
<?php

namespace App\Console\Commands\Project;

use App\Helper\Arr;
use App\Models\Product\Product;
use App\Services\ProjectServer;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class ThumbProjectImage extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'thumb_project_image';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '处理项目产品缩略图';

    public function handle()
    {
        while (true) {
            $this->start_thumb();
        }
    }

    public function start_thumb()
    {
        $key = 'thumb_project_image';
        $project_id = Redis::rpop($key);
        if (empty($project_id)) {
            sleep(60);
            return true;
        }

        $this->output('project_id:' . $project_id . ' | start');

        $project_info = ProjectServer::useProject($project_id);

        if ($project_info) {
            $thumb_w = $project_info->deploy_build->thumb_w ?? 0;
            Product::select(['id', 'project_id', 'gallery'])->chunk(100, function ($products) use ($thumb_w) {
                foreach ($products as $product) {
                    $thumb = $product['gallery'][0] ?? [];
                    if (isset($thumb['url']) && $thumb['url']) {
                        $thumb['url'] = thumbImageByUrl($thumb['url'], $thumb_w);
                        $json_thumb = Arr::a2s($thumb);
                        if (strlen($json_thumb) <= 500) {
                            $product->timestamps = false;
                            $product->thumb = $json_thumb;
                            $product->save();

                            $this->output('project_id:' . $product->project_id . ',product_id:' . $product->id . ',thumb:' . $thumb_w . ' | success');
                        }
                    }
                }
            });

            DB::disconnect('custom_mysql');
        }

        $this->output('project_id:' . $project_id . ' | end');

        return true;
    }


    /**
     * 输出处理日志
     * @param $message
     * @return bool
     */
    public function output($message)
    {
        echo date('Y-m-d H:i:s') . ' | ' . $message . PHP_EOL;
        return true;
    }
}