<commit_before><?php
use \Terminus\Endpoint;
use \Terminus\Request;
use \Terminus\Fixtures;
use \Terminus\Session;
use \Terminus\Auth;
use \Terminus\Loggers\Regular as Logger;

/**
 * Base class for Terminus commands
 *
 * @package terminus
 */
abstract class Terminus_Command {

  public $cache;
  public $session;
  public $sites;
  static $instance = false;

  protected $_func;
  protected $_siteInfo;
  protected $_bindings;

  public function __construct() {
    # Load commonly used data from cache.
    $this->cache = Terminus::get_cache();
    $this->session = Session::instance();
    $this->sites = $this->cache->get_data('sites');
    self::$instance = $this;
  }

  public static function instance() {
    if (!self::$instance) {
      Terminus::error("No valid instance available");
    }
    return self::$instance;
  }

  /**
   * Helper code to grab sites and manage local cache.
   */
  protected function fetch_sites( $nocache = false ) {
    if (!$this->sites || $nocache) {
      $this->_fetch_sites();
    }
    return $this->sites;
  }

  /**
   * Actually go out and get the sites.
   */
  protected function _fetch_sites() {
    Terminus::log('Fetching site list from Pantheon');

    $request = self::request( 'user', Session::getValue('user_uuid'), 'sites', 'GET', Array('hydrated' => true));

    # TODO: handle errors well.
    $sites = $request['data'];
    $this->cache->put_data( 'sites', $sites );
    $this->sites = $sites;
    return $sites;
  }

  /**
   * Helper function to grab a single site's data from cache if possible.
   */
  protected function fetch_site( $site_name, $nocache = false ) {
    if ( $this->_fetch_site($site_name) !== false && !$nocache ) {
      return $this->_fetch_site($site_name);
    }
    # No? Refresh that list.
    $this->_fetch_sites();
    if ( $this->_fetch_site($site_name) !== false ) {
      return $this->_fetch_site($site_name);
    }
    Terminus::error("The site named '%s' does not exist. Run `terminus sites show` for a list of sites.", array($site_name));
  }

  /**
   * Private function to deal with our data object for sites and return one
   * by name that includes its uuid.
   */
  private function _fetch_site( $site_name ) {
    foreach ($this->sites as $site_uuid => $data) {
      if ( $data->information->name == $site_name ) {
        $data->information->site_uuid = $site_uuid;
        return $data->information;
      }
    }
    return false;
  }

  /**
   * Make a request to the Dashbord's internal API.
   *
   * @param $realm
   *    Permissions realm for data request: currently "user" or "site" but in the
   *    future this could also be "organization" or another high-level business
   *    object (e.g. "product" for managing your app). Can also be "public" to
   *    simply pull read-only data that is not privileged.
   *
   * @param $uuid
   *    The UUID of the item in the realm you want to access.
   *
   * @param $method
   *    HTTP method (verb) to use.
   *
   * @param $data
   *    A native PHP data structure (int, string, arary or simple object) to be
   *    sent along with the request. Will be encoded as JSON for you.
   */
  public static function request($realm, $uuid, $path = FALSE, $method = 'GET', $options = NULL) {
    if (!in_array($realm,array('login','public')) AND !Terminus::is_test()) {
      Auth::loggedIn();
    }

    try {
      $cache = Terminus::get_cache();

      // combine session realm uuid and path to get a unique key
      // @todo need cache "groups"
      $cachekey = md5( Session::getValue('user_uuid').$realm.$path );
      $data = $cache->get_data($cachekey);

      // check the request cache
      if ("GET" == $method AND !Terminus::get_config('nocache') AND !getenv('CLI_TEST_MODE') AND !empty($data)) {
        if (Terminus::get_config('debug')) {
          Logger::coloredOutput('<Y>Cached Request. Key: '.$cachekey.'</Y>');
        }
        return (array) $data;
      }

      // for some methods we'll assume the cache should be invalidated
      if ( in_array($method, array("POST","PUT","DELETE")) ) {
        $cache->flush(null, 'session');
      }

      if ($realm != 'login') {
        $options['cookies'] = array('X-Pantheon-Session' => Session::getValue('session'));
        $options['verify'] = false;
      }

      $url = Endpoint::get(array('realm'=>$realm, 'uuid'=>$uuid, 'path'=>$path));
      $resp = Request::send($url, $method, $options);
      $json = $resp->getBody(TRUE);

      $data = array(
        'info' => $resp->getInfo(),
        'headers' => $resp->getRawHeaders(),
        'json' => $json,
        'data' => json_decode($json)
      );
      $cache->put_data($cachekey, $data);
      return $data;
    } catch( Guzzle\Http\Exception\BadResponseException $e ) {
      $response = $e->getResponse();
      \Terminus::error("%s", $response->getBody(TRUE) );
    } catch( Guzzle\Http\Exception\BadResponseException $e ) {
      $request = $e->getRequest();
      \Terminus::error("Request %s had failed: %s", (string)$request, $e->getMessage() );
    } catch( Exception $e ) {
      \Terminus::error("Unrecognised request failure: %s", $e->getMessage() );
    }
<commit_msg>Typo: same exception was used in two catch lines. Changed to use HttpException interface.<commit_after><?php
use \Terminus\Endpoint;
use \Terminus\Request;
use \Terminus\Fixtures;
use \Terminus\Session;
use \Terminus\Auth;
use \Terminus\Loggers\Regular as Logger;

/**
 * Base class for Terminus commands
 *
 * @package terminus
 */
abstract class Terminus_Command {

  public $cache;
  public $session;
  public $sites;
  static $instance = false;

  protected $_func;
  protected $_siteInfo;
  protected $_bindings;

  public function __construct() {
    # Load commonly used data from cache.
    $this->cache = Terminus::get_cache();
    $this->session = Session::instance();
    $this->sites = $this->cache->get_data('sites');
    self::$instance = $this;
  }

  public static function instance() {
    if (!self::$instance) {
      Terminus::error("No valid instance available");
    }
    return self::$instance;
  }

  /**
   * Helper code to grab sites and manage local cache.
   */
  protected function fetch_sites( $nocache = false ) {
    if (!$this->sites || $nocache) {
      $this->_fetch_sites();
    }
    return $this->sites;
  }

  /**
   * Actually go out and get the sites.
   */
  protected function _fetch_sites() {
    Terminus::log('Fetching site list from Pantheon');

    $request = self::request( 'user', Session::getValue('user_uuid'), 'sites', 'GET', Array('hydrated' => true));

    # TODO: handle errors well.
    $sites = $request['data'];
    $this->cache->put_data( 'sites', $sites );
    $this->sites = $sites;
    return $sites;
  }

  /**
   * Helper function to grab a single site's data from cache if possible.
   */
  protected function fetch_site( $site_name, $nocache = false ) {
    if ( $this->_fetch_site($site_name) !== false && !$nocache ) {
      return $this->_fetch_site($site_name);
    }
    # No? Refresh that list.
    $this->_fetch_sites();
    if ( $this->_fetch_site($site_name) !== false ) {
      return $this->_fetch_site($site_name);
    }
    Terminus::error("The site named '%s' does not exist. Run `terminus sites show` for a list of sites.", array($site_name));
  }

  /**
   * Private function to deal with our data object for sites and return one
   * by name that includes its uuid.
   */
  private function _fetch_site( $site_name ) {
    foreach ($this->sites as $site_uuid => $data) {
      if ( $data->information->name == $site_name ) {
        $data->information->site_uuid = $site_uuid;
        return $data->information;
      }
    }
    return false;
  }

  /**
   * Make a request to the Dashbord's internal API.
   *
   * @param $realm
   *    Permissions realm for data request: currently "user" or "site" but in the
   *    future this could also be "organization" or another high-level business
   *    object (e.g. "product" for managing your app). Can also be "public" to
   *    simply pull read-only data that is not privileged.
   *
   * @param $uuid
   *    The UUID of the item in the realm you want to access.
   *
   * @param $method
   *    HTTP method (verb) to use.
   *
   * @param $data
   *    A native PHP data structure (int, string, arary or simple object) to be
   *    sent along with the request. Will be encoded as JSON for you.
   */
  public static function request($realm, $uuid, $path = FALSE, $method = 'GET', $options = NULL) {
    if (!in_array($realm,array('login','public')) AND !Terminus::is_test()) {
      Auth::loggedIn();
    }

    try {
      $cache = Terminus::get_cache();

      // combine session realm uuid and path to get a unique key
      // @todo need cache "groups"
      $cachekey = md5( Session::getValue('user_uuid').$realm.$path );
      $data = $cache->get_data($cachekey);

      // check the request cache
      if ("GET" == $method AND !Terminus::get_config('nocache') AND !getenv('CLI_TEST_MODE') AND !empty($data)) {
        if (Terminus::get_config('debug')) {
          Logger::coloredOutput('<Y>Cached Request. Key: '.$cachekey.'</Y>');
        }
        return (array) $data;
      }

      // for some methods we'll assume the cache should be invalidated
      if ( in_array($method, array("POST","PUT","DELETE")) ) {
        $cache->flush(null, 'session');
      }

      if ($realm != 'login') {
        $options['cookies'] = array('X-Pantheon-Session' => Session::getValue('session'));
        $options['verify'] = false;
      }

      $url = Endpoint::get(array('realm'=>$realm, 'uuid'=>$uuid, 'path'=>$path));
      $resp = Request::send($url, $method, $options);
      $json = $resp->getBody(TRUE);

      $data = array(
        'info' => $resp->getInfo(),
        'headers' => $resp->getRawHeaders(),
        'json' => $json,
        'data' => json_decode($json)
      );
      $cache->put_data($cachekey, $data);
      return $data;
    } catch( Guzzle\Http\Exception\BadResponseException $e ) {
      $response = $e->getResponse();
      \Terminus::error("%s", $response->getBody(TRUE) );
    } catch( Guzzle\Http\Exception\HttpException $e ) {
      $request = $e->getRequest();
      \Terminus::error("Request %s had failed: %s", (string)$request, $e->getMessage() );
    } catch( Exception $e ) {
      \Terminus::error("Unrecognised request failure: %s", $e->getMessage() );
    }

{'fraction_non_alphanumeric': 0.15759147219821376, 'fraction_numerical': 0.00019206760779794487, 'mean_word_length': 2.9387291981845687, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 93, 'https://': 0, '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': '752770', 'n_tokens_mistral': 3302, 'n_tokens_neox': 3237, 'n_words': 909}