<commit_before><?php
/**
 * Created by PhpStorm.
 * User: joeldg
 * Date: 5/16/17
 * Time: 6:53 PM
 */

namespace Bowhead\Util;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use DateTimeZone;
use DateTime;

/**
 * Class OneBroker
 * @package Bowhead\Util
 *          One Broker API wrapper..
 *          https://1broker.com/?c=en/content/api-documentation
 */
class OneBroker {
    /**
     * @var mixed
     */
    protected $token;
    /**
     * @var string
     */
    protected $baseurl = 'https://1broker.com/api/v2/';

    /**
     * @var array
     */
    public $symbols = array();

    /**
     * @var string
     */
    public $symbolslist = '';

    /**
     * OneBroker constructor.
     */
    public function __construct()
    {
        $this->token = env('ONEBROKER_TOKEN');
        if (\Cache::has('ONEBROKER::symbols')) {
            $this->symbols = \Cache::get('ONEBROKER::symbols');
        } else {
            $toCache = array();
            $categories = $this->getCategories();
            $categories = $categories['body']['response'];
            foreach($categories as $category) {
               $lists              = $this->getCategories($category);
               $toCache[$category] = $lists['body']['response'];
            }
            \Cache::put('ONEBROKER::symbols', $toCache, 60*24*7);
            $this->symbols = \Cache::get('ONEBROKER::symbols');
        }
        /**
         *  we want to keep this fresh, but not be crazy about it.
         */
        $update = (rand(1,100) == 85 ? 1 : 0);
        if (!\Cache::has('ONEBROKER::symbols::detail::BTCUSD') ) {
            $update = 1; /** this is the first run kind of thing */
        }
        if ($update) {
            foreach ($this->symbols as $cat => $symbols) {
                foreach ($symbols as $arr) {
                    $this->getMarketDetails($arr['symbol']);
                }
            }
        }

    }

    /**
     * @param      $remote_tz
     * @param null $origin_tz
     *
     * @return bool|int
     */
    public function get_timezone_offset($remote_tz, $origin_tz = null) {
        if($origin_tz === null) {
            if(!is_string($origin_tz = date_default_timezone_get())) {
                return false; // A UTC timestamp was returned -- bail out!
            }
        }
        $origin_dtz = new DateTimeZone($origin_tz);
        $remote_dtz = new DateTimeZone($remote_tz);
        $origin_dt = new DateTime("now", $origin_dtz);
        $remote_dt = new DateTime("now", $remote_dtz);
        $offset = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);
        return $offset;
    }

    /**
     * @param      $dateString
     * @param null $timeZoneSource
     * @param null $timeZoneTarget
     *
     * @return string
     */
    function changeTimeZone($dateString, $timeZoneSource = null, $timeZoneTarget = null)
    {
        // this formatting was causing issues
        $dateString = str_replace('T',' ', $dateString);
        $dateString = str_replace('Z','', $dateString);

        if (empty($timeZoneSource)) {
            $timeZoneSource = date_default_timezone_get();
        }
        if (empty($timeZoneTarget)) {
            $timeZoneTarget = date_default_timezone_get();
        }

        $dt = new DateTime($dateString, new DateTimeZone($timeZoneSource));
        $dt->setTimezone(new DateTimeZone($timeZoneTarget));

        return $dt->format('Y-m-d\TH:i:s\Z');
    }

    /**
     * @param $endpoint
     * @param $data
     *
     * @return array
     */
    private function getApiData($endpoint, $data)
    {
        $curl = curl_init();
        $data['token'] = $this->token;
        #$data['pretty'] = 1; /** comment out for live */
        $data['execution_time']=1;
        $options = array(
            CURLOPT_URL => $this->baseurl . $endpoint . '?' . http_build_query($data),
            CURLOPT_RETURNTRANSFER => true,
        );
        curl_setopt_array($curl, $options);
        $response = curl_exec($curl);

        if ($response === false) {
            $error   = curl_errno($curl);
            $message = curl_error($curl);
            curl_close($curl);
        }
        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);

        if($statusCode != 200) {
            error_log('STATUS CODE', $statusCode . ' ' . $response);
        }

        $body = json_decode($response,1);
        
        if ($body['error'] === true) {
            throw new \RuntimeException(
                sprintf('OneBroker API returned an error - %d: %s', $body['error_code'], $body['error_message'])
            );
        }
        
        return array( "statusCode" => $statusCode, "body" => json_decode($response,1));
    }

    /**
     * @param null $category
     *
     * @return array
     */
    public function getCategories($category=null)
    {
        # /market/categories.php (response[])
        # /market/list.php ? category=$category  (response[]->symbol)
        if (!empty($category)) {
            if (\Cache::has('ONEBROKER::category::detail::'.$category)) {
                \Cache::get('ONEBROKER::category::detail::'.$category);
            } else {
                $data = $this->getApiData('market/list.php', ['category' => $category]);
                \Cache::put('ONEBROKER::category::detail::'.$category, $data, 60*24);
            }
        } else {
            if (\Cache::has('ONEBROKER::categories')) {
                \Cache::get('ONEBROKER::categories');
            } else {
                $data = $this->getApiData('market/categories.php', ['category'=>$category]);
                \Cache::put('ONEBROKER::categories', $data, 60*24);
            }
        }<commit_msg>reusing decoded response<commit_after><?php
/**
 * Created by PhpStorm.
 * User: joeldg
 * Date: 5/16/17
 * Time: 6:53 PM
 */

namespace Bowhead\Util;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use DateTimeZone;
use DateTime;

/**
 * Class OneBroker
 * @package Bowhead\Util
 *          One Broker API wrapper..
 *          https://1broker.com/?c=en/content/api-documentation
 */
class OneBroker {
    /**
     * @var mixed
     */
    protected $token;
    /**
     * @var string
     */
    protected $baseurl = 'https://1broker.com/api/v2/';

    /**
     * @var array
     */
    public $symbols = array();

    /**
     * @var string
     */
    public $symbolslist = '';

    /**
     * OneBroker constructor.
     */
    public function __construct()
    {
        $this->token = env('ONEBROKER_TOKEN');
        if (\Cache::has('ONEBROKER::symbols')) {
            $this->symbols = \Cache::get('ONEBROKER::symbols');
        } else {
            $toCache = array();
            $categories = $this->getCategories();
            $categories = $categories['body']['response'];
            foreach($categories as $category) {
               $lists              = $this->getCategories($category);
               $toCache[$category] = $lists['body']['response'];
            }
            \Cache::put('ONEBROKER::symbols', $toCache, 60*24*7);
            $this->symbols = \Cache::get('ONEBROKER::symbols');
        }
        /**
         *  we want to keep this fresh, but not be crazy about it.
         */
        $update = (rand(1,100) == 85 ? 1 : 0);
        if (!\Cache::has('ONEBROKER::symbols::detail::BTCUSD') ) {
            $update = 1; /** this is the first run kind of thing */
        }
        if ($update) {
            foreach ($this->symbols as $cat => $symbols) {
                foreach ($symbols as $arr) {
                    $this->getMarketDetails($arr['symbol']);
                }
            }
        }

    }

    /**
     * @param      $remote_tz
     * @param null $origin_tz
     *
     * @return bool|int
     */
    public function get_timezone_offset($remote_tz, $origin_tz = null) {
        if($origin_tz === null) {
            if(!is_string($origin_tz = date_default_timezone_get())) {
                return false; // A UTC timestamp was returned -- bail out!
            }
        }
        $origin_dtz = new DateTimeZone($origin_tz);
        $remote_dtz = new DateTimeZone($remote_tz);
        $origin_dt = new DateTime("now", $origin_dtz);
        $remote_dt = new DateTime("now", $remote_dtz);
        $offset = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);
        return $offset;
    }

    /**
     * @param      $dateString
     * @param null $timeZoneSource
     * @param null $timeZoneTarget
     *
     * @return string
     */
    function changeTimeZone($dateString, $timeZoneSource = null, $timeZoneTarget = null)
    {
        // this formatting was causing issues
        $dateString = str_replace('T',' ', $dateString);
        $dateString = str_replace('Z','', $dateString);

        if (empty($timeZoneSource)) {
            $timeZoneSource = date_default_timezone_get();
        }
        if (empty($timeZoneTarget)) {
            $timeZoneTarget = date_default_timezone_get();
        }

        $dt = new DateTime($dateString, new DateTimeZone($timeZoneSource));
        $dt->setTimezone(new DateTimeZone($timeZoneTarget));

        return $dt->format('Y-m-d\TH:i:s\Z');
    }

    /**
     * @param $endpoint
     * @param $data
     *
     * @return array
     */
    private function getApiData($endpoint, $data)
    {
        $curl = curl_init();
        $data['token'] = $this->token;
        #$data['pretty'] = 1; /** comment out for live */
        $data['execution_time']=1;
        $options = array(
            CURLOPT_URL => $this->baseurl . $endpoint . '?' . http_build_query($data),
            CURLOPT_RETURNTRANSFER => true,
        );
        curl_setopt_array($curl, $options);
        $response = curl_exec($curl);

        if ($response === false) {
            $error   = curl_errno($curl);
            $message = curl_error($curl);
            curl_close($curl);
        }
        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);

        if($statusCode != 200) {
            error_log('STATUS CODE', $statusCode . ' ' . $response);
        }

        $body = json_decode($response, 1);
        
        if ($body['error'] === true) {
            throw new \RuntimeException(
                sprintf('OneBroker API returned an error - %d: %s', $body['error_code'], $body['error_message'])
            );
        }
        
        return array( "statusCode" => $statusCode, "body" => $body);
    }

    /**
     * @param null $category
     *
     * @return array
     */
    public function getCategories($category=null)
    {
        # /market/categories.php (response[])
        # /market/list.php ? category=$category  (response[]->symbol)
        if (!empty($category)) {
            if (\Cache::has('ONEBROKER::category::detail::'.$category)) {
                \Cache::get('ONEBROKER::category::detail::'.$category);
            } else {
                $data = $this->getApiData('market/list.php', ['category' => $category]);
                \Cache::put('ONEBROKER::category::detail::'.$category, $data, 60*24);
            }
        } else {
            if (\Cache::has('ONEBROKER::categories')) {
                \Cache::get('ONEBROKER::categories');
            } else {
                $data = $this->getApiData('market/categories.php', ['category'=>$category]);
                \Cache::put('ONEBROKER::categories', $data, 60*24);
            }
        }
{'fraction_non_alphanumeric': 0.15942533739660428, 'fraction_numerical': 0.006878537222464083, 'mean_word_length': 1.9557385486361296, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 49, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6776934', 'n_tokens_mistral': 3547, 'n_tokens_neox': 3401, 'n_words': 643}