vannut / statamic-weather-addon

🎏 A Statamic-Addon for the OpenWeathermap API
5 stars 0 forks source link

Add fetch now widget/button #1

Closed vannut closed 2 years ago

Wibbmer commented 2 years ago

Quick and dirty solution:

in settings.blade.php to @section('content') add

<form
        title="Fetch current Weather"
        method="post"
        action="{{ cp_route('weather.settings.fetchWeather') }}"
    >
        <button class="btn-primary" type="submit">Fetch current Weather</button>
        @csrf
    </form>

in routes\cp.php add


        Route::post('/fetch-weather', 'ControlPanelController@fetchWeather')->name('.settings.fetchWeather');

and in ControlPanelController.phpadd


use Illuminate\Support\Facades\Storage;

    protected function fetch($config)
    {
        $endpoint = $config->get('api_url')
            . 'onecall?lat=' . $config->get('lat')
            . '&lon=' . $config->get('lon')
            . '&lang=' . $config->get('lang')
            . '&exclude=minutely,hourly,alerts'
            . '&units=' . $config->get('units', 'metric')
            . '&appid=' . $config->get('api_secret_key');

        $headers = [
            'Content-Type:application/json',
        ];
        $ch = curl_init($endpoint);

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $result = curl_exec($ch);
        curl_close($ch);

        return $result;

    }

    public function fetchWeather(Request $request)
    {
        $config = (new Settings())->get();
        $content = $this->fetch($config);

        // Do nothing when we don't get anything back
        if ($content === false)
        {
            return;
        }

        // Decode the json object, drop out when not a valid object
        $jsonObj = json_decode($content);
        if ($jsonObj === null && json_last_error() !== JSON_ERROR_NONE)
        {
            return;
        }

        // Store the JSON to be used by the tags and endpoints
        Storage::put('weather-forecast.json', json_encode($jsonObj));

        return redirect()->back();
    }

I tried to make it work using the existing command, but ended up copy/pasting it instead.

But it get's the job done 😬