Commits

Anonymous committed 11d89a8

Added initial version of PHP API wrapper.

Comments (0)

Files changed (2)

php/Repustate.php

+<?php
+//
+//  Repustate PHP API client.
+//
+//  Requirements:
+//  - PHP >= 5.3, with cURL, JSON and SimpleXML
+//
+//  Want to change it / improve it / share it? Go for it.
+//
+//  Feedback is appreciated at info@repustate.com
+//
+//  More documentation available at http://www.repustate.com/docs
+//
+
+function subst($str, $dict){
+    return preg_replace(array_map(create_function('$a', 'return "/%\\($a\\)s/";'), array_keys($dict)), array_values($dict), $str);
+}
+
+class Repustate
+{
+    const urlTemplate = 'http://api.repustate.com/%(version)s/%(key)s/%(function)s.%(responseType)s';
+
+    const pptUrl = 'http://api.repustate.com/%(version)s/%(key)s/powerpoint/';
+
+    protected $validResponseTypes = array('json', 'xml');
+
+    public $apiKey;
+    public $version;
+
+    public function __construct($apiKey, $version='v1')
+    {
+        $this->apiKey = $apiKey;
+        $this->version = $version;
+    }
+
+    //
+    // Construct a query string from an array of arguments.
+    //
+    protected function getQueryString($args)
+    {
+        $data = array();
+        foreach ($args as $k => $v)
+        {
+            // Skip empty values
+            if ($v == '')
+            {
+                continue;
+            }
+            $data[] = $k . '=' . rawurlencode($v);
+        }
+        return join('&', $data);
+    }
+
+    //
+    // Retrieve the url for the given api function and response type.
+    //
+    protected function getUrlForCall($apiFunction, $responseType)
+    {
+        if ($apiFunction == 'powerpoint')
+        {
+            $urlTemplate = self::pptUrl;
+        }
+        else
+        {
+            $urlTemplate = self::urlTemplate;
+        }
+
+        $urlArgs = array(
+            'responseType' => $responseType,
+            'function' => $apiFunction,
+            'key' => $this->apiKey,
+            'version' => $this->version,
+        );
+
+        return subst($urlTemplate, $urlArgs);
+    }
+
+    /**
+     * Make an HTTP request via cURL for the given url and data.
+     */
+    protected function getHttpResult($url, $data, $useHttpGet)
+    {
+        $ch = curl_init();
+
+        if ($useHttpGet)
+        {
+            $url .= '?' . $data;
+        }
+        else
+        {
+            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
+        }
+
+        curl_setopt($ch, CURLOPT_URL, $url);
+        curl_setopt($ch, CURLOPT_POST, ! $useHttpGet);
+        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
+        curl_setopt($ch, CURLOPT_HEADER, FALSE);
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
+
+        $result = curl_exec($ch);
+
+        if (curl_errno($ch))
+        {
+            throw new Exception('Curl Error: ' . curl_error($ch));
+        }
+
+        $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+        if ($httpStatus != 200)
+        {
+            throw new Exception('HTTP Error: ' . $httpStatus . ' ' . $result);
+        }
+
+        curl_close($ch);
+
+        return $result;
+    }
+
+    protected function parseResult($result, $apiFunction, $responseType)
+    {
+        if ($apiFunction == 'powerpoint')
+        {
+            return $result;
+        }
+        else if ($responseType == 'json')
+        {
+            return json_decode($result);
+        }
+        else
+        {
+            // Default is XML
+            return new SimpleXMLElement($result);
+        }
+    }
+
+    protected function callApi($apiFunction, $args=null,
+                               $responseType='json', $useHttpGet=FALSE)
+    {
+        if (! in_array($responseType, $this->validResponseTypes))
+        {
+            throw new Exception($responseType .
+                                ' is not a valid response type.');
+        }
+
+        $data = $this->getQueryString($args);
+        $url = $this->getUrlForCall($apiFunction, $responseType);
+        $result = $this->getHttpResult($url, $data, $useHttpGet);
+        return $this->parseResult($result, $apiFunction, $responseType);
+    }
+
+    //
+    // Helper function for the NLP calls.
+    //
+    protected function callNaturalLanguage($apiFunction, $cloud=null,
+                                           $text=null, $url=null,
+                                           $responseType='json')
+    {
+        $args = array(
+            'cloud' => $cloud,
+            'text' => $text,
+            'url' => $url,
+        );
+        $useHttpGet = ($text == null);
+        return $this->callApi($apiFunction, $args, $responseType, $useHttpGet);
+    }
+
+    //
+    // Retreive the sentiment for a single URL or block of text.
+    //
+    public function sentiment($text=null, $url=null, $responseType='json')
+    {
+        if (is_array($text))
+        {
+            extract($text, EXTR_IF_EXISTS);
+            if (is_array($text))
+            {
+                $text = null;
+            }
+        }
+        return $this->callApi('score', array('text' => $text, 'url' => $url),
+                              $responseType);
+    }
+
+    //
+    // Bulk score multiple pieces of text (not urls!).
+    //
+    public function bulkSentiment($items, $responseType='json')
+    {
+        $itemsToScore = array();
+        foreach (array_values($items) as $k => $v)
+        {
+            $itemsToScore['text' . $k] = $v;
+        }
+        return $this->callApi('bulk-score', $itemsToScore, $responseType);
+    }
+
+    //
+    // Clean up a web page. It doesn't work well on home pages - it's
+    // designed for content pages.
+    //
+    public function clean_html($url=null, $responseType='json')
+    {
+        if (is_array($url)) extract($url, EXTR_IF_EXISTS);
+        return $this->callApi('clean-html', array('url' => $url),
+                              $responseType, $useHttpGet=TRUE);
+    }
+
+    public function adjectives($cloud=null, $text=null, $url=null,
+                               $responseType='json')
+    {
+        if (is_array($cloud))
+        {
+            extract($cloud, EXTR_IF_EXISTS);
+            if (is_array($cloud))
+            {
+                $cloud = null;
+            }
+        }
+        return $this->callNaturalLanguage('adj', $cloud, $text, $url,
+                                          $responseType);
+    }
+
+    public function verbs($cloud=null, $text=null, $url=null,
+                          $responseType='json')
+    {
+        if (is_array($cloud))
+        {
+            extract($cloud, EXTR_IF_EXISTS);
+            if (is_array($cloud))
+            {
+                $cloud = null;
+            }
+        }
+        return $this->callNaturalLanguage('verb', $cloud, $text, $url,
+                                          $responseType);
+    }
+
+    public function ngrams($url=null, $text=null, $max=null, $min=null,
+                           $freq=null, $stopwords=null, $responseType='json')
+    {
+        if (is_array($url))
+        {
+            extract($url, EXTR_IF_EXISTS);
+            if (is_array($url))
+            {
+                $url = null;
+            }
+        }
+        $args = array(
+            'url' => $url,
+            'text' => $text,
+            'max' => $max,
+            'min' => $min,
+            'freq' => $freq,
+            'stopwords' => $stopwords,
+        );
+        $useHttpGet = ($url != null);
+        return $this->callApi('ngrams', $args, $responseType, $useHttpGet);
+    }
+
+    //
+    // Given a list of images and titles, generate a simple powerpoint
+    // presentation.
+    //
+    public function powerpoint($reportTitle=null, $author=null, $images=null,
+                               $titles=null)
+    {
+        if (is_array($reportTitle))
+        {
+            extract($reportTitle, EXTR_IF_EXISTS);
+            if (is_array($reportTitle))
+            {
+                $reportTitle = null;
+            }
+        }
+        $args = array(
+            'title' => $reportTitle,
+            'author' => $author,
+        );
+        $zippedArrays = array_map(null, $images, $titles);
+        foreach (array_values($zippedArrays) as $k => $v)
+        {
+            $filename = $v[0];
+            $title = $v[1];
+            $fileHandle = fopen($filename, 'rb');
+            $fileData = fread($fileHandle, filesize($filename));
+            fclose($fileHandle);
+            $args['slide_' . $k . '_image'] = base64_encode($fileData);
+            $args['slide_' . $k . '_title'] = $title;
+        }
+        return $this->callApi('powerpoint', $args);
+    }
+}
+
+?>

php/RepustateTest.php

+<?php
+//
+//  Unit tests for the Repustate PHP API client.
+//
+//  Requirements:
+//  - phpunit - http://www.phpunit.de/manual/3.6/en/phpunit-book.html
+//
+
+require 'Repustate.php';
+
+class RepustateTest extends PHPUnit_Framework_TestCase
+{
+    const key = '0c9cf39718d8ce33e5310047617f8020984d8f18';
+
+    function getAccessor()
+    {
+        return new Repustate(self::key);
+    }
+
+    function makeCall()
+    {
+
+    }
+
+    function checkCall()
+    {
+        $accessor = $this->getAccessor();
+        $args = func_get_args();
+        $method = $args[0];
+        $methodArgs = $args[1];
+        $result = $accessor->{$method}($methodArgs);
+        $this->assertInternalType('object', $result, 'Invalid result');
+        $this->assertEquals($result->status, 'OK', $result->status);
+    }
+
+    public function textUrlProvider()
+    {
+        return array(
+            array(array('text' => 'iPad')),
+            array(array('url' => 'http://tcrn.ch/aav9Ty')),
+        );
+    }
+
+    /**
+     * @dataProvider textUrlProvider
+     */
+    public function testSentiment($args)
+    {
+        $this->checkCall('sentiment', $args);
+    }
+
+    public function testBulkSentiment()
+    {
+        $this->checkCall('bulkSentiment', array('I love candy'));
+    }
+
+    /**
+     * @dataProvider textUrlProvider
+     */
+    public function testAdjectives($args)
+    {
+        $this->checkCall('adjectives', $args);
+    }
+
+    /**
+     * @dataProvider textUrlProvider
+     */
+    public function testVerbs($args)
+    {
+        $this->checkCall('verbs', $args);
+    }
+
+    public function testCleanHtml()
+    {
+        $this->checkCall('clean_html', array('url' => 'http://tcrn.ch/aav9Ty'));
+    }
+
+    /**
+     * @dataProvider textUrlProvider
+     */
+    public function testNgrams($args)
+    {
+        $this->checkCall('ngrams', $args);
+    }
+
+    /* public function testPowerpoint() */
+    /* { */
+    /*     $args = array( */
+    /*         'reportTitle' => 'Test Report', */
+    /*         'author' => 'Martin Ostrovsky', */
+    /*         'images' => array('test.gif'), */
+    /*         'titles' => array('A test title'), */
+    /*     ); */
+    /*     $accessor = $this->getAccessor(); */
+    /*     $result = $accessor->powerpoint($args); */
+    /* } */
+}
+
+?>
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.