OtaVersionRepository.php 2.34 KB
<?php

namespace App\Repositories\Backend\Ota;

use App\Exceptions\GeneralException;
use App\Modules\Models\Ota\OtaVersion;
use App\Modules\Repositories\Ota\BaseOtaVersionRepository;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

/**
 * Class BaseOtaVersionRepository
 * @package App\Modules\Repositories\Ota
 */
class OtaVersionRepository extends BaseOtaVersionRepository
{

    /**
     * @return mixed
     */
    public function getForDataTable()
    {
        return OtaVersion::query();
    }

    /**
     * @param $input
     * @return bool
     * @throws GeneralException
     */
    public function create($input)
    {
        $otaVersion = $this->createOtaVersionStub($input);

        if ($otaVersion->save()) {
            return true;
        }

        throw new GeneralException(trans('exceptions.backend.otaVersion.create_error'));
    }


    /**
     * @param OtaVersion $otaVersion
     * @param $input
     * @return bool
     * @throws GeneralException
     */
    public function update(OtaVersion $otaVersion, $input)
    {
        Log::info("update param:" . json_encode($input));

        if ($otaVersion->update($input)) {
            return true;
        }

        throw new GeneralException(trans('exceptions.backend.otaVersion.update_error'));
    }

    /**
     * @param $input
     * @return OtaVersion
     */
    private function createOtaVersionStub($input)
    {
        $otaVersion = new OtaVersion();
        $otaVersion->version_code = $input['version_code'];
        $otaVersion->update_info = $input['update_info'];
        $otaVersion->filename = $input['filename'];

        return $otaVersion;
    }

    /**
     * @param OtaVersion $otaVersion
     * @return mixed
     */
    public function delete(OtaVersion $otaVersion)
    {
        $latest_version = $this->getLatest();

        if ($latest_version == $otaVersion)
        {
            $otaVersion->delete();

            $latest_version = $this->getLatest();

            if ($latest_version == null)
            {
                Storage::disk('ota')->put('.env', '');
            }
            else
            {
                Storage::disk('ota')->put('.env', 'LATEST_VERSION='.$latest_version->version_code."\nFILENAME=".$latest_version->filename);
            }
        }
        else
        {
            $otaVersion->delete();
        }
    }
}