/ Gists / Component - Instagram
On gists

Component - Instagram

Nette

instagram.php Raw #

<?php

namespace App\FrontModule\Components;

use App;
use Nette\Caching\Cache;
use Nette\Caching\IStorage;
use Nette\Utils\Json;

/**
 * Class Instagram
 */
class Instagram extends FrontControl
{
    public $presets;
    public $content;
    public $cacheStorage;

    public function __construct(App\Model\Presets $presets, IStorage $IStorage)
    {
        $this->presets = $presets;
        $this->cacheStorage = $IStorage;
    }

    private function fetchData()
    {

        $token = $this->presets->defaults['keys']['instagram']['token'];
        $user = $this->presets->defaults['keys']['instagram']['user'];
        $url = "https://api.instagram.com/v1/users/$user/media/recent/?access_token=$token";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 20);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    public function getData()
    {

        $cache = new Cache($this->cacheStorage, 'instagramPosts');

        try {
            $out = $cache->load("photos");
        } catch (\Exception $e) {
            $out = false;
        }

        if (empty($out)) {
            try {
                $data = self::fetchData();
                $out = Json::decode($data, true);
                $out = $out['data'];
                $cache->save("photos", $out, array(
                    Cache::EXPIRATION => '+30 minutes',
                    Cache::SLIDING => TRUE
                ));
            } catch (\Exception $e) {
                $out = false;
            }
        }
        return $out;

    }

	public function renderDefault(array $config = array())
	{	
        $config = $this->getCurrentConfig($config);
        $this->template->presets = $this->presets->getPresets();
        $this->template->instagramData = $this->getData();

		$this->render($config);
	}


}