diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bcc0b7a --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.idea +vendor/ \ No newline at end of file diff --git a/README.rst b/README.rst index bacf94d..357913b 100644 --- a/README.rst +++ b/README.rst @@ -1,6 +1,6 @@ php-votesmart ======================= -A PHP library for use with the Vote Smart API(http://votesmart.org/share/api). +A PHP library for use with the Vote Smart API (http://votesmart.org/share/api). ------------ Requirements @@ -11,43 +11,60 @@ The PHP libraries require PHP 5 with the SimpleXML extension and ``allow_url_fop ------------ Usage ------------ -Using the libraries is fairly simple. You initialize the object with the name one of the methods and any arguments needed in an array. Then a call go ``getXmlObj()`` can be made to retrieve a SimpleXML object to work with. Let's say you wanted to get information on a bill...:: +First, you need your API token. Once you get that from VoteSmart.org, store the API token in a file which is loaded +by your application. It should be defined as:: - // Initialize the VoteSmart object - $obj = new VoteSmart( - 'CandidateBio.getBio', - Array( - 'candidateId' => 9026 - )); + $_ENV['VOTESMART_API_KEY'] - // Get the SimpleXML object +Using the libraries is fairly simple. You initialize the object, and call ``query()`` to make the call parse the +response from VoteSmart. If there is no response, or the request fails, the output is boolean ``false``:: + + // Initialize the VoteSmart object. The default output type is XML. + $obj = new VoteSmart(); + + // You can also pass in optional to change the expected output type, and the location where the API token is located + // inside the $_ENV global variable. In this case, your VoteSmart API key would be stored in $_ENV['SOME_KEY']. + $obj = new VoteSmart('JSON', 'SOME_KEY'); + + // Make the query with required parameters, with the name of one of the methods, and any required or optional + // arguments in an array. Let's say you wanted to get information on a bill. For example: + $x = $obj->query( + 'CandidateBio.getBio', + Array( + 'candidateId' => 9026 + ) + ); + + // Once a query has been made, you can also get the stored decoded response. + // If your output type was XML, you could access the SimpleXMLElement object via $x = $obj->getXmlObj(); + // If your output type was JSON, you could access the array via + $x = $obj->getJsonObj(); + Now ``$xml_object`` is a SimpleXML object representative of the XML structure. Here's a small cut from the XML itself.:: - - Project Vote Smart - Bio - Rep. Stephen Scalise - http://votesmart.org/bio.php?can_id=9026 - - - 9026 - - - http://votesmart.org/canphoto/9026.JPG - Stephen - Steve - J. - Scalise - - - 10/06/1965 - - - Male - [...] - + + Project Vote Smart - Bio - Rep. Stephen Scalise + http://votesmart.org/bio.php?can_id=9026 + + + 9026 + + http://votesmart.org/canphoto/9026.JPG + Stephen + Steve + J. + Scalise + + 10/06/1965 + + + Male + [...] + Let's say you wanted to get the candidateId of the candidate. You could simply access it like this:: diff --git a/VoteSmart.php b/VoteSmart.php deleted file mode 100644 index 52b565b..0000000 --- a/VoteSmart.php +++ /dev/null @@ -1,124 +0,0 @@ - '54321') - */ - public function __construct($method = null, $args = null) { - - if ($method && $args) { - - $this->query($method, $args); - - } - - } - - /** - * function getXml - * - * Return raw XML string - * - * @return string - */ - public function getXml() { - - return $this->xml; - - } - - /** - * function getXmlObj - * - * Return SimpleXML object - * - * @return object SimpleXMLElement - */ - public function getXmlObj() { - - return $this->xmlObj; - - } - - /** - * function getIface - * - * Return string of URL queried - * - * @return string - */ - public function getIface() { - - return $this->iface; - - } - - /** - * function query - * - * Query API backend and return SimpleXML object. This - * function can be reused repeatedly - * - * @param string $method CandidateBio.getBio' - * @param array $args Array('candidateId' => '54321') - * @return object SimpleXMLElement - */ - public function query($method, $args = Array()) { - - $terms = ""; - - if(!empty($args)) { - - foreach($args as $n => $v) { - - $terms .= '&' . $n . '=' . $v; - - } - } - - $this->iface = _APISERVER_ . "/" . $method . "?key=" . _KEY_ . "&o=" . _OUTPUT_ . $terms; - - if (!$this->xml = file_get_contents($this->iface)) { - - return false; - - } else { - - // Let's use the SimpleXML to drop the whole XML - // output into an object we can later interact with easilly - $this->xmlObj = new SimpleXMLElement($this->xml, LIBXML_NOCDATA); - - return $this->xmlObj; - - } - - } - -} diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..98d2cad --- /dev/null +++ b/composer.json @@ -0,0 +1,12 @@ +{ + "name": "ozzyogkush/php-votesmart", + "description": "A PHP library for accessing VoteSmart.org via their API.", + "keywords": ["votesmart", "php", "api"], + "license": "BSD", + "require": { + "php": ">=5.3.0" + }, + "autoload": { + "psr-4": {"VoteSmart\\" : "src/"} + } +} \ No newline at end of file diff --git a/composer.lock b/composer.lock new file mode 100644 index 0000000..8a8b001 --- /dev/null +++ b/composer.lock @@ -0,0 +1,19 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", + "This file is @generated automatically" + ], + "hash": "189f86c01904cd88bec379f45fa94b3b", + "packages": [], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": { + "php": ">=5.3.0" + }, + "platform-dev": [] +} diff --git a/config.php b/config.php deleted file mode 100644 index 319733f..0000000 --- a/config.php +++ /dev/null @@ -1,19 +0,0 @@ -= 1) { - error_reporting(E_ALL ^ E_NOTICE); // All but notice errors -} else { - error_reporting(E_NONE); -} - -define("_APISERVER_", "http://api.votesmart.org"); // Without trailing slash and with protocol diff --git a/src/Api.php b/src/Api.php new file mode 100644 index 0000000..9f2bf1f --- /dev/null +++ b/src/Api.php @@ -0,0 +1,313 @@ + + * @class Api + * @name Api + */ +class Api +{ + //-------------------------------------------------------------------------- + // + // Static Variables + // + //-------------------------------------------------------------------------- + + /** + * The API endpoint where requests are sent. + * + * @static + * @var string + */ + public static $API_SERVER = "http://api.votesmart.org"; + + /** + * Possible return formats from API endpoint. + * + * @static + * @var array + */ + public static $OUTPUT_TYPES = [ + 'XML', + 'JSON' + ]; + + //-------------------------------------------------------------------------- + // + // Variables and get/set functions + // + //-------------------------------------------------------------------------- + + /** + * The full query URL. + * + * @var string + */ + protected $iface; + + /** + * function getIface + * + * Return string of URL queried + * + * @return string + */ + public function getIface() + { + return $this->iface; + } + + /** + * Raw XML + * + * @var string + */ + protected $xml; + + /** + * function getXml + * + * Return raw XML string + * + * @return string + */ + public function getXml() + { + return $this->xml; + } + + /** + * SimpleXML object + * + * @var \SimpleXMLElement + */ + protected $xmlObj; + + /** + * Return SimpleXMLElement object + * + * @return \SimpleXMLElement + */ + public function getXmlObj() + { + return $this->xmlObj; + } + + /** + * Raw JSON + * + * @var string + */ + protected $json; + + /** + * Return raw JSON string + * + * @return string + */ + public function getJson() + { + return $this->json; + } + + /** + * Decoded JSON data + * + * @var array + */ + protected $jsonObj; + + /** + * Return decoded JSON array. + * + * @return array + */ + public function getJsonObj() + { + return $this->jsonObj; + } + + /** + * The array key in $_ENV where you are storing your VoteSmart API token. + * + * @var string + */ + protected $envKey = null; + + /** + * Sets the array key in $_ENV where you are storing your VoteSmart API token, and updates + * the apiKey stored in this object to point to the new location in $_ENV. + * + * @throws \InvalidArgumentException iff the output type isn't a string + * @throws \Exception iff the API token can't be found in $_ENV + * + * @param string $envKey The array key in $_ENV where the VoteSmart token exists. + */ + public function setEnvKey($envKey) + { + if (! is_string($envKey)) { + throw new \InvalidArgumentException( + "The environment key '{$envKey}' is expecting a string" + ); + } + if (empty($_ENV[$envKey])) { + throw new \Exception( + "VoteSmart requires an API authentication token. Place it in your application's `\$_ENV['".$envKey."']` variable." + ); + } + $this->envKey = $envKey; + $apiToken = $_ENV[$this->envKey]; + $this->setApiToken($apiToken); + } + + /** + * Authentication token provided to you by VoteSmart. Place it in your application's + * `$_ENV['VOTESMART_API_KEY']` variable so that it is globally available. For example, + * in the Laravel framework, you would put this in your .env.php file. + * + * If you've stored your key in another $_ENV key already, you can pass in the key where + * the API token can be found in the constructor. + * + * @var string + */ + protected $apiToken = null; + + /** + * Sets the API token. + * + * @param string $apiToken Sets the API key. Required. + */ + public function setApiToken($apiToken) + { + $this->apiToken = $apiToken; + } + + /** + * The type of output to request from VoteSmart. + * + * @var string + */ + protected $outputType = null; + + /** + * Set the expected output type. + * + * @throws \InvalidArgumentException iff the output type isn't a string + * @throws \Exception iff the output type isn't supported + * + * @param string $outputType The expected output type from VoteSmart. + */ + public function setOutputType($outputType) + { + if (! is_string($outputType)) { + throw new \InvalidArgumentException( + "The output type '{$outputType}' is unsupported." + ); + } + if (! in_array($outputType, static::$OUTPUT_TYPES)) { + throw new \Exception( + "The output type '{$outputType}' is unsupported." + ); + } + $this->outputType = $outputType; + } + + //-------------------------------------------------------------------------- + // + // Methods + // + //-------------------------------------------------------------------------- + + /* Private Methods */ + + /* Protected Methods */ + + /** + * Use SimpleXML to drop the whole XML output into an object we can later interact with easily. + * Stores both the XML and the constructed SimpleXMLElement object. + * + * @param string $xml + */ + protected function parseXml($xml) + { + $this->xml = $xml; + $this->xmlObj = new \SimpleXMLElement($this->xml, LIBXML_NOCDATA); + } + + /** + * Take in a JSON string and decode it. Store both the JSON and the decoded array. + * + * @param string $json + */ + protected function parseJson($json) + { + $this->json = $json; + $this->jsonObj = json_decode($this->json); + } + + /* Public Methods */ + + /** + * Initialize the VoteSmart object and ready it to make queries. + * + * @param string $outputType optional The type of output to request from VoteSmart. Default is 'XML'. + * @param string $envKey optional Key of your Authentication key stored in $_ENV var. Default is 'VOTESMART_API_KEY'. + */ + public function __construct($outputType = 'XML', $envKey = 'VOTESMART_API_KEY') + { + $this->setOutputType($outputType); + $this->setEnvKey($envKey); + } + + /** + * Query API backend and parse the response, either as JSON or XML depending on the instance's outputType + * attribute. Returns false if it can't get the contents, a SimpleXMLElement if the output type is XML, + * or an array if the output type is JSON. + * + * @param string $method required 'CandidateBio.getBio' + * @param array $args optional Array('candidateId' => '54321') + * + * @return false|\SimpleXMLElement|array + */ + public function query($method, $args = Array()) + { + $terms = ""; + + if (! empty($args)) { + foreach ($args as $n => $v) { + $terms .= "&{$n}={$v}"; + } + } + $this->iface = static::$API_SERVER . "/" . $method . "?key=" . $this->apiToken . "&o=" . $this->outputType . $terms; + + $response = file_get_contents($this->iface); + if (! $response) { + return false; + } + + if ($this->outputType == 'JSON') { + $this->parseJson($response); + return $this->responseArr; + } + + // Parse as XML by default. + $this->parseXml($response); + return $this->xmlObj; + } +}