diff --git a/README.md b/README.md index 6f4c1e6..88bee01 100644 --- a/README.md +++ b/README.md @@ -3,17 +3,19 @@ The PHP GIS Wrapper is a PHP library to connect your PHP projects with AIESEC's It gives you the possibility to access every resource in the GIS as if it would be a native object in your php script. You don't need to take care about any requests, parsing or the token generation. Just instantiate an Authentication Provider with a user name and password. Then instantiate the GIS Wrapper and you are ready to go. -If you already used the PHP GIS Wrapper v0.1 please be aware that v0.2 is a complete rewrite. There are a lot of architectural changes whereby the update of your projects is most probably not that simple. The new version definitely gives you a performance boost and brings many new possibilities. Please check the changelog for further informations. If you need help do not hesitate to drop me a message. +Version 0.3 is a partial rewrite with breaking changes in the acccess of endpoints, please check the documentation and test your application, if you update. -- author: Karl Johann Schubert -- version: 0.2 +If you already used the PHP GIS Wrapper v0.1 please be aware that v0.2 is a complete rewrite. There are a lot of architectural changes whereby the update of your projects is most probably not that simple. The new version definitely gives you a performance boost and brings many new possibilities. Please check the changelog for further informations. + +- author: Lukas Ehnle +- author until v0.2: Karl Johann Schubert +- version: 0.3 # Documentation -Please check the examples folder for a quick start. The explanations below are more general. ## Installation 1. install composer (https://getcomposer.org/) -2. `composer require kjschubert/php-gis-wrapper` +2. `composer require aiesecgermany/php-gis-wrapper` 3. require the composer autoloader in your scripts ## AuthProviders @@ -61,37 +63,30 @@ Please make sure to call the function `setSession($path)` before you generate an - The `AuthProviderShadow` provides the function `getAuthProvider()`, which returns the underlaying AuthProvider or null ## Class GIS -The class GIS is the entry point to access AIESECs Global Information System from your project. The first argument must be an AuthProvider. The second parameter can either be empty, or the url of the API documentation, or an array containing the already parsed API documentation. +The class GIS is the entry point to access AIESECs Global Information System from your project. The first argument must be an AuthProvider. The second parameter can either be empty. For simple projects it is fine to leave the second argument empty. ``` $user = new \GISwrapper\AuthProviderEXPA($username, $password); $gis = new \GISwrapper\GIS($user); ``` -If you want to improve the performance of your project read more in the paragraph caching. ### Caching -The GIS API is documented in the swagger format. Normally the GIS wrapper downloads those files and parses them with every instantiation. If your project is using the GIS on a higher scale you can retrieve the parsing result and cache it by yourself. -- `\GISwrapper\GIS::generateSimpleCache()` returns an array with just the parsed root swagger file -- `\GISwrapper\GIS::generateFullCache()` returns an array with all endpoints parsed - -Both functions can take a alternative link to the API documentation as first argument. - -You can instantiate the GIS class with the returned array as second parameter. Please check the examples folder for an example script on how to cache the full cache in a file. +This new version does not need or support caching. As it does not parse a swagger file anymore. ## Data Access and Manipulation Please check the api documentation at http://apidocs.aies.ec/ to get to know which endpoints exists. (Attention: make sure to change the file to the docs.json from v1 to v2) -Starting from your instance of the GIS (e.g. $gis) every static part after /v2/ of the path is turned into an object. Every dynamic part turns the previous part into an array, whereby the array key represents the value for the dynamic part. +Starting from your instance of the GIS (e.g. $gis) every part after /v2/ of the path is turned into an object. ``` // /v2/opportunities.json $gis->opportunities; // /v2/opportunities/{opportunity_id}.json -$gis->opportunities[opportunity_id] +$gis->opportunities->{opportunity_id} // /v2/opportunities/{opportunity_id}/progress.json -$gis->opportunities[opportunity_id]->progress +$gis->opportunities->{opportunity_id}->progress ``` ### Getting data @@ -113,14 +108,14 @@ foreach($gis->opportunities as $o) { ``` ### Create a resource -Please check the paragraph Parameters to get to know how to access the parameters of an endpoint. After you set all parameters which are necessary to create a new object call the `update()` function on that endpoint. +Please check the paragraph Parameters to get to know how to access the parameters of an endpoint. After you set all parameters which are necessary to create a new object call the `post()` function on that endpoint. Please check the examples folder for an script on how to create, update and delete a new opportunity. Endpoints who support the creation of a new object are those who support the http method POST. Please check the respective endpoint documentation for the required parameters. ### Update an existing resource -After setting the necessary parameters on the endpoint you want to update, call the `update()` method on that endpoint. +After setting the necessary parameters on the endpoint you want to update, call the `patch()` method on that endpoint. Please check the examples folder for an script on how to create, update and delete a new opportunity. @@ -132,39 +127,24 @@ To delete an resource call the `delete()` method on that endpoint. Endpoint who support the delete methode are those which support the http method DELETE. Please check the api documentation to find those endpoints. ## Parameters -Every Endpoint on the GIS API has parameters. Some parameters are already part of the path. Like already described those parameters turn into array keys. +Every Endpoint on the GIS API has parameters. Some parameters are already part of the path. Like already described those parameters turn into objects. The GIS wrapper already takes care of the parameters access_token, page and per_page. Thereby you can not access or change them. -All other parameters of the parameter type query and form turn into subobjects of the endpoint. The Array notation in the documentation is translated into the object notation in php. So in general every key mentioned in the documentation becomes a subobject, whereby the array notation in php is used for the different elements of an parameter with the data type array. +All other parameters of the parameter type query and form turn into an associative array of the endpoint. Let's take a look at the endpoint `/v2/opportunities.json` ``` -$gis->opportunities->q = "some String"; // set parameter q -$gis->opportunities->filters->organisation = 10 // set parameter filters[organisation] -$gis->opportunities->filters->issues[0] = 10 // set element 0 of the array parameter filters[issues] -$gis->opportunities->filters->issues[1] = 20 // set element 1 of the array parameter filters[issues] -$gis->opportunities->filters->skills[0]->id = 10 // set the id of the first element of the array parameter filters[skills] -$gis->opportunities->filters->skills[1]->id = 20 // set the id of the second element of the array parameter filters[skills] +$gis->opportunities[q] = "some String"; // set parameter q +$gis->opportunities->[filters] = [ + "organisation" => 10, // set parameter filters[organisation] + "issues" => [10, 20], // set elements of the array parameter filters[issues] + "skills" => [ // set the ids of elements of the array parameter filters[skills] + ["id" => 10], + ["id" => 20] + ] +] ``` -Attention: Please take care of the fact that those parameters are saved until you unset them. Even a request will not unset them. - -You can call the php function unset on every element in this hierarchy. This will delete the specific instance and thereby all the parameters below. Please remember that when you unset your instance of the GIS class you have to reinitialize the GIS wrapper by yourself. Every object below the GIS class will be reinitialized automatically as soon as you access it. - -The easiest way is to unset the endpoint you worked on, after your request. In the example above this would mean `unset($gis->opportunities)`. - -### Hash and Array Parameters -When it comes to Hash and Array parameters you should take a closer look at the column data type in the API documentation. - -A parameter with the data type Hash does not have an accessable value. Rather you can think of it as the value is consisting in the value of the subparameters. - -Thereby an hash parameter is also not accessable as an array in php, rather every subparameter turns into a subobject in php. An example is the parameter filter, used in the example above. - -On the other side there are two different kind of array parameters. Those who have subparameters and those who do not have subparameters and thereby just take values. In PHP those parameters turn into arrays. - -On the first kind of array parameters you can access the subparameters on each array key, like the filter skills in the example above. - -On the second kind of array parameters you can access and set values on each array key. In the example above this would be the filer issues. ### setting many parameters at once When you want to set many parameters at once without using the long notation with subobjects you can set them as array. Please be aware that this method can be hard to debug. @@ -185,36 +165,10 @@ $gis->opportunities = [ ] ``` -## Helper functions -- On every object with subobjects you can call the function `exists($name)` to check if a subobject exists. This does not mean that there is already an instance of this object, rather only that it is accessable. -- On Endpoints with Dynamic Sub Endpoints, so those where you can access endpoints via array notation, the `exists($name)` function checks both for subobjects as well as array keys. - - To only check for subobjects use the function `existsSub($name)`. Subobjects are static path endpoints and parameters. - - To only check for elements of the dynamic sub endpoint use the function `existsDynamicSub($key)`. - - When checking for a dynamic sub endpoint the GIS wrapper actually send a request to the GIS to check if the resource is available. - - It's recommended to use the functions `existsSub($name)` and `existsDynamicSub($key)` on endpoints with dynamic Subs to avoid unnecessary requests - - Please be aware that the functions `existsSub($name)` and `existsDynamicSub($key)` are only available on objects with dynamic sub objects. On objects with static sub objects and parameters you can only use the function `exists($name)` -- The function `isset($object)`, returns true as soon as the the respective object is initialized. If the object is not initialized it will return false. - - if `isset($object)` returns false this does not mean that the object is not accessable. To check if an object is accessable use the function `exists($name)`, which is described above - - at the moment `isset($object)` also return true, when an parameter is initialized, but does not have a value. This might change in the future. For the moment you can use the function `valid($operation)` described below - - calling `isset($object)` on an array key, will return true when there is an instance at this key. This must not mean that there is a resource existing for this key. -- The function `unset($object)` will delete the instance of the given object. - - Afterwards `isset($object)` will return false, until you access the object again. - - Calling `exists($name)` on the parent object will still return true -- The function `count($object)` can be called on paged endpoints and array parameters, both are also iteratable (e.g. in a foreach loop) - - on paged endpoints this will relate in a request with the current set of parameters - - to get the number of elements in the last request call `lastCount()` on the endpoint - -## Testing -The PHP GIS Wrapper is tested with PHP unit. All the tests can be found in the folder tests. There you can also find the Code Coverage report. - -If you send a pull request, please make sure that your code is covered and run phpunit in the root folder before you commit. Normally phpunit will automatically recognize the file phpunit.xml in the root folder. - -## Providers -Providers have to purpose to include the functionality of the GIS wrapper in a different context (e.g. a framework). - -Currently we support the PHP Framework Lumen and thereby also Laravel. Please check the README in the providers folder, for more details. - # Changelog +## 0.3.0 +- rewrite that does not parse the swagger file, instead everything is allowed as an endpoint, so you have to take care to call the correct endpoints. + ## 0.2.5 - added AuthProviderShadow and AuthProviderNationalIdentity - added ServiceProvider for Lumen (should also work with Laravel) @@ -250,11 +204,8 @@ This was the initial version of the PHP-GIS-Wrapper. It only supported GET reque - Later the AuthProviderUser was replaced by AuthProviderEXPA, AuthProviderOP and AuthProviderCombined # FAQ -If you have any questions, feature wishes, problems or found a bug don't hesitate to send an email to karljohann@familieschubi.de - -If you found a bug you can also directly open an issue in the github repository. -If you integrated the PHP GIS Wrapper as Provider or Service in a framework or used it in one of your projects feel free to drop me a message to feature it here, or write a pull request to include your code in the providers folder. +If you found a bug please open an issue in the github repository. If you wrote another example just send a pull request diff --git a/composer.json b/composer.json index e938f17..483c35f 100644 --- a/composer.json +++ b/composer.json @@ -1,16 +1,21 @@ { - "name": "kjschubert/php-gis-wrapper", + "name": "aiesecgermany/php-gis-wrapper", "description": "PHP library to connect your projects with AIESEC's Global Information System", "authors": [ { "name": "Karl Johann Schubert", "email": "karljohann@familieschubi.de" + }, + { + "name": "Lukas Ehnke", + "email": "lukas.ehnle@aiesec.de" } ], "minimum-stability": "stable", "require": { "php": ">=5.4.0", - "lib-curl": "*" + "lib-curl": "*", + "tcdent/php-restclient": "^0.1.6" }, "autoload": { "psr-4": { diff --git a/examples/caching.php b/examples/caching.php deleted file mode 100644 index 04f9ea5..0000000 --- a/examples/caching.php +++ /dev/null @@ -1,43 +0,0 @@ -app->bind('GIS', function() { - return new LumenFactory(); - }); - } -} \ No newline at end of file diff --git a/providers/LumenFactory.php b/providers/LumenFactory.php deleted file mode 100644 index 7eda5cb..0000000 --- a/providers/LumenFactory.php +++ /dev/null @@ -1,99 +0,0 @@ - - * @package GISwrapper\Providers - * @version 0.1 - */ -class LumenFactory -{ - /** - * @var array - */ - private static $_cache; - - public static function getCache() { - if(self::$_cache == null) { - if(file_exists(dirname(__DIR__) . '/cache.dat')) { - self::$_cache = unserialize(file_get_contents(dirname(__DIR__) . '/cache.dat')); - } - if(self::$_cache == null || self::$_cache == false) { - self::$_cache = GIS::generateFullCache(); - file_put_contents(dirname(__DIR__) . '/cache.dat', serialize(self::$_cache)); - } - } - return self::$_cache; - } - - /** - * @param null|integer $userId - * @return GIS - */ - public static function getInstance($userId = null) { - if($userId === null) { - $token = Cache::get('gis_token'); - if($token != null) { - $user = new AuthProviderShadow($token, new AuthProviderEXPA(env('GIS_USER'), env('GIS_PASS'))); - } else { - $user = new AuthProviderEXPA(env('GIS_USER'), env('GIS_PASS')); - Cache::put('gis_token', $user->getToken(), $user->getExpiresAt()); - } - } else { - $token = Cache::get('gis_token:' . $userId); - $url = str_replace('%USER_ID%', $userId, env('NATIONAL_AUTH_URL')); - if($token != null) { - $user = new AuthProviderShadow($token, new AuthProviderNationalIdentity($url)); - } else { - $user = new AuthProviderNationalIdentity($url); - try { - $token = $user->getToken(); - Cache::put('gis_token:' . $userId, $token, $user->getExpiresAt()); - } catch (\Exception $e) {} - } - } - return new GIS($user, self::getCache()); - } - - /** - * @param string $username - * @param null|string $password - * @param string $type expa|op|combined - * @return GIS - */ - public static function getUserInstance($username, $password = null, $type = 'combined') { - switch($type) { - case 'expa': - $user = new AuthProviderEXPA($username, $password); - break; - - case 'op': - $user = new AuthProviderOP($username, $password); - break; - - default: - $type = 'combined'; - $user = new AuthProviderCombined($username, $password); - } - $token = Cache::get('gis_token_' . $type . ':' . $username); - if($token != null) { - $user = new AuthProviderShadow($token, $user); - } else { - try { - $token = $user->getToken(); - Cache::put('gis_token_' . $type . ':' . $username, $token, $user->getExpiresAt()); - } catch (\Exception $e) {} // just try if we get a token to put it in cache, but don't fire any exception - } - return new GIS($user, self::getCache()); - } -} \ No newline at end of file diff --git a/providers/README.md b/providers/README.md deleted file mode 100644 index 15026b0..0000000 --- a/providers/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# GIS Wrapper Providers -## Lumen -You should be able to use the Provider in Laravel in a similar way -### Installation -1. Include the GIS wrapper `composer require kjschubert/php-gis-wrapper` -2. Register the GIS wrapper in your `app/bootstrap.php` -``` -$app->register(\GISwrapper\Providers/Lumen::class); -``` - -### Configuration -The Lumen Provider uses the following Environment variables -- `GIS_USER` and `GIS_PASS` standard login credentials (must be an EXPA account) -- `NATIONAL_AUTH_URL` url for the AIESEC Identity custom token flow. Use '%USER_ID%' as placeholder for the user ID - -### Usage -- get an instance with the standard login credentials: `App::make('GIS')->getInstance()` -- get an instance for a specific user via the AIESEC Identity custom token flow `App::make('GIS')->getInstance($userId)` -- get an instance with specified login credentials `App::make('GIS')->getUserInstance($username, $password)` - - this uses the AuthProviderCombined - - you can pass 'expa' or 'op' as third parameter to use those AuthProviders - - you can also use sessions by providing the session path as first parameter leave the second parameter or set it to `null` -- get the currently used cache `App::make('GIS')->getCache()` - -The Lumen Provider automatically uses the caching functionality, by placing a `cache.dat` file in its root folder. \ No newline at end of file diff --git a/src/API.php b/src/API.php index 08e3259..7ac7064 100644 --- a/src/API.php +++ b/src/API.php @@ -3,89 +3,57 @@ /** * Class API - * represents a part of the path which is not an data endpoint + * make requests to API * - * @author Karl Johann Schubert + * @author Lukas Ehnle * @package GISwrapper - * @version 0.2 + * @version 0.3 */ class API { - /** - * @var array - */ - protected $_cache; + private static $instance; - /** - * @var array - */ - protected $_subs; + private $auth; - /** - * @var AuthProvider - */ - protected $_auth; + private $api; - /** - * @var array - */ - protected $_pathParams; - - /** - * API constructor. - * @param array $cache parsed swagger file for this api - * @param AuthProvider $auth - * @param array $pathParams array with values for dynamic parts of the path - */ - public function __construct($cache, $auth, $pathParams = array()) + private function __construct(AuthProvider $auth, String $baseUrl) { - $this->_cache = $cache; - $this->_subs = array(); - $this->_auth = $auth; - $this->_pathParams = $pathParams; + $this->auth = $auth; + $this->api = new \RestClient([ + 'base_url' => $baseUrl, + 'headers' => [ + 'Content-Type' => 'application/json' + ] + ]); } - /** - * @param mixed $name property name - * @return mixed|null value for the property - */ - public function __get($name) - { - if(array_key_exists($name, $this->_cache['subs']) && !$this->_cache['subs'][$name]['dynamic']) { - if(!isset($this->_subs[$name])) { - $this->_subs[$name] = APISubFactory::factory($this->_cache['subs'][$name], $this->_auth); - } - return $this->_subs[$name]; - } else { - trigger_error("Property " . $name . " does not exist.", E_USER_WARNING); - return null; - } + public function __call($name, $arguments){ + if( method_exists($this->api, $name) ){ + // add access token to requestUrl + $arguments[0] .= '?access_token=' . $this->auth->getToken(); + + $response = call_user_func_array([$this->api, $name], $arguments)->decode_response(); + if(isset($response->status) + && isset($response->status->code) + && $response->status->code == 401){ + //TODO: retry with new token on fail + } + return $response; + } } - /** - * @param mixed $name property name - * @return bool indicating if there is a active instance of this property - */ - public function __isset($name) - { - return isset($this->_subs[$name]); + public static function createInstance($auth = NULL, $baseUrl = 'https://gis-api.aiesec.org/v2'){ + if($auth instanceof AuthProvider){ + API::$instance = new API($auth, $baseUrl); + } } - /** - * @param mixed $name property name - * deletes the current instance of the property - */ - public function __unset($name) { - if(isset($this->_subs[$name])) { - unset($this->_subs[$name]); - } + public static function getInstance(){ + if(! API::$instance instanceof API){ + throw new \Error("API not instantiated yet."); + } + return API::$instance; } - /** - * @param mixed $name property name - * @return bool indicating if the property exists (this doesn't mean that there is a instance of the property). The existence of the instance is indicated by isset - */ - public function exists($name) { - return (isset($this->_cache['subs'][$name]) && !$this->_cache['subs'][$name]['dynamic']); - } -} \ No newline at end of file +} diff --git a/src/APIDynamicSub.php b/src/APIDynamicSub.php deleted file mode 100644 index 3ccc73d..0000000 --- a/src/APIDynamicSub.php +++ /dev/null @@ -1,97 +0,0 @@ - - * @package GISwrapper - * @version 0.2 - */ -class APIDynamicSub extends API implements \ArrayAccess -{ - /** - * @var DynamicSub - */ - private $_dynamicSub; - - /** - * APIDynamicSub constructor. - * @param array $cache parsed swagger file for this api - * @param AuthProvider $auth - * @param array $pathParams array with values for dynamic parts of the path - */ - public function __construct($cache, $auth, $pathParams = array()) - { - parent::__construct($cache, $auth, $pathParams); - - // create instance of DynamicSub class - $this->_dynamicSub = new DynamicSub($cache, $auth, $pathParams); - } - - /** - * @param mixed $name property name - * @return bool indicating if this property exists (Does not mean there is a instance. Use isset to check if the instance exists) - */ - public function exists($name) { - if(!$this->existsSub($name)) { - return $this->existsDynamicSub($name); - } else { - return true; - } - } - - /** - * @param mixed $name sub name - * @return bool indicating if a subpath with this name exists (Does not mean there is a instance. Use isset to check if the instance exists) - */ - public function existsSub($name) { - return parent::exists($name); - } - - /** - * @param mixed $name - * @return bool indicating if the offset exists for the dynamic subpath (Does not mean there is a instance. Use isset to check if the instance exists) - * @throws NoResponseException - */ - public function existsDynamicSub($name) { - return $this->_dynamicSub->exists($name); - } - - /** - * @param mixed $offset - * @return bool indicating if there is a instance for this offset - */ - public function offsetExists($offset) - { - return $this->_dynamicSub->offsetExists($offset); - } - - /** - * @param mixed $offset - * @return mixed instance for this offset - */ - public function offsetGet($offset) - { - return $this->_dynamicSub->offsetGet($offset); - } - - /** - * @param mixed $offset - * @param mixed $value - */ - public function offsetSet($offset, $value) - { - $this->_dynamicSub->offsetSet($offset, $value); - } - - /** - * @param mixed $offset - * deletes the instance at $offset - */ - public function offsetUnset($offset) - { - $this->_dynamicSub->offsetUnset($offset); - } -} \ No newline at end of file diff --git a/src/APIEndpoint.php b/src/APIEndpoint.php index 7b7790f..bb34fb1 100644 --- a/src/APIEndpoint.php +++ b/src/APIEndpoint.php @@ -1,401 +1,117 @@ + * @version 0.3 * @package GISwrapper - * @version 0.2 */ -class APIEndpoint extends API +class APIEndpoint implements \ArrayAccess { - /** - * @var array - */ - private $_params; + private $api; - /** - * @var int - * value for the current page of paged endpoints, declared here for use in the get method - */ - protected $_currentPage; + private $parts; - /** - * @var int - * value for parameter per_page of paged endpoint, declared here for use in the get method - */ - protected $_perPage; + private $subs; - /** - * APIEndpoint constructor. - * @param array $cache parsed swagger file for this api - * @param AuthProvider $auth - * @param array $pathParams array with values for dynamic parts of the path + private $params; + + /** + * BaseOperations constructor. */ - function __construct($cache, $auth, $pathParams = array()) + function __construct($parts = [], $newPart = NULL) { - parent::__construct($cache, $auth, $pathParams); - $this->_params = array(); + $this->parts = $parts; + if($newPart){ + $this->parts[] = $newPart; + } + + $this->api = API::getInstance(); + $this->subs = array(); + $this->params = array(); } - /** + public function get(){ + return $this->api->get(implode('/', $this->parts)); + } + + public function patch(){ + return $this->api->patch(implode('/', $this->parts), json_encode($this->params)); + } + + public function post(){ + return $this->api->post(implode('/', $this->parts), json_encode($this->params)); + } + + public function delete(){ + return $this->api->delete(implode('/', $this->parts), json_encode($this->params)); + } + + /** * @param mixed $name property name * @return mixed|null property value */ public function __get($name) { - if(isset($this->_cache['subs'][$name]) && !$this->_cache['subs'][$name]['dynamic']) { - if(!isset($this->_subs[$name])) { - $this->_subs[$name] = APISubFactory::factory($this->_cache['subs'][$name], $this->_auth, $this->_pathParams); - } - return $this->_subs[$name]; - } elseif(isset($this->_cache['params'][$name])) { - if(!isset($this->_params[$name])) { - $this->_params[$name] = ParameterFactory::factory($this->_cache['params'][$name]); - } - if($this->_params[$name]->hasChilds() || $this->_params[$name] instanceof ParameterArrayType) { - return $this->_params[$name]; - } else { - return $this->_params[$name]->get(); - } - } else { - trigger_error("Property " . $name . " does not exist", E_USER_ERROR); - return null; - } + if(!isset($this->subs[$name])){ + $this->subs[$name] = new APIEndpoint($this->parts, $name); + } + return $this->subs[$name]; } /** - * @param mixed $name name of the property to change - * @param mixed $value new value for the property + * @param string $name name of the property to change + * @param array $arr new values for the property * @return void */ - public function __set($name, $value) + public function __set($name, $arr) { - if(isset($this->_cache['subs'][$name]) && !$this->_cache['subs'][$name]['dynamic']) { - trigger_error('Property ' . $name . ' is not a parameter', E_USER_ERROR); - } elseif(isset($this->_cache['params'][$name])) { - if(is_scalar($value) || $value instanceof \DateTime) { - if(!isset($this->_params[$name])) { - $this->_params[$name] = ParameterFactory::factory($this->_cache['params'][$name]); - } - $this->_params[$name]->set($value); - } elseif(is_array($value)) { - // recreate param to reset other keys and keep scalar value if existent - $v = ((isset($this->_params[$name]) && is_scalar($this->_params[$name]->value())) ? $this->_params[$name]->value() : null); - $this->_params[$name] = ParameterFactory::factory($this->_cache['params'][$name]); - $this->_params[$name]->value($v); - - // proceed array - if($this->_params[$name] instanceof ParameterArrayType) { - foreach($value as $key => $v) { - $this->_params[$name][$key] = $v; - } - } else { - foreach($value as $key => $v) { - $this->_params[$name]->$key = $v; - } - } - } else { - trigger_error("Invalid value for property " . $name, E_USER_ERROR); - } - } else { - trigger_error("Property " . $name . " does not exist", E_USER_ERROR); - } + if(is_array($arr)){ + $sub = $this->__get($name); + foreach ($arr as $key => $value) { + $sub[$key] = $value; + } + } else { + trigger_error("Use array notation to assign parameters.", E_USER_ERROR); + } } /** - * @param mixed $name property name of the instance to delete + * @param mixed $offset + * @return bool indicating if this offset is instantiated */ - public function __unset($name) + public function offsetExists($offset) { - if(isset($this->_subs[$name])) { - unset($this->_subs[$name]); - } elseif(isset($this->_params[$name])) { - unset($this->_params[$name]); - } elseif(!array_key_exists($name, $this->_cache['subs']) && !array_key_exists($name, $this->_cache['params'])) { - trigger_error("Property " . $name . " does not exist", E_USER_WARNING); - } + return isset($this->params[$offset]); } /** - * @param mixed $name property name - * @return bool indicating if this property is instantiated + * @param mixed $offset + * @return mixed returns the instance at this offset */ - public function __isset($name) + public function offsetGet($offset) { - return isset($this->_subs[$name]) || isset($this->_params[$name]); + return $this->params[$offset]; } /** - * @param mixed $name property name - * @return bool indicating if this property exists (Does not mean it is instantiated. Use isset for this) + * @param mixed $offset + * @param mixed $value */ - public function exists($name) { - return ((isset($this->_cache['subs'][$name]) && !$this->_cache['subs'][$name]['dynamic']) || isset($this->_cache['params'][$name])); - } - - /** - * @return array containing the http Methods of this endpoint - */ - public function getOperations() { - return $this->_cache['operations']; - } - - /** - * @param string $operation http method to check - * @return bool indicating if all parameters are valid for the http method to check - */ - public function valid($operation) { - if(in_array($operation, $this->_cache['operations'])) { - foreach($this->_cache['params'] as $name => $param) { - if(isset($this->_params[$name])) { - if (!$this->_params[$name]->valid($operation)) return false; - } elseif(isset($param['operations'][$operation]) && $param['operations'][$operation]['required']) { - return false; - } - } - return true; - } - return false; - } - - /** - * @return object representing the resource returned by this endpoint - * @throws ActiveRoleRequiredException - * @throws InvalidAPIResponseException - * @throws NoResponseException - * @throws OperationNotAvailableException - * @throws ParameterRequiredException - * @throws UnauthorizedException - */ - public function get() { - if(in_array('GET', $this->_cache['operations'])) { - if($this->valid('GET')) { - $url = $this->getQueryUrl('GET'); - - // check if we need to add the page parameter - if(isset($this->_currentPage)) { - $url .= 'page=' . $this->_currentPage . '&'; - } - - // check if we need to add the per_page parameter - if(isset($this->_perPage)) { - $url .= 'per_page=' . $this->_perPage . '&'; - } - - // try to load - $res = GET::request($url, $this->_auth); - - // validate response - if(isset($res->status) && isset($res->status->code) && isset($res->status->message)) { - $this->proceedStatus($res->status); - } else { - return $res; - } - } else { - throw new ParameterRequiredException('There are one or more required parameters missing for a GET request'); - } - } else { - throw new OperationNotAvailableException("Operation GET is not available."); - } - } - - /** - * @return object representing the updated version of the resource - * @throws OperationNotAvailableException - * @throws ParameterRequiredException - */ - public function update() { - return $this->payloadRequest('PATCH'); - } - - /** - * @return object representing the created resource - * @throws OperationNotAvailableException - * @throws ParameterRequiredException - */ - public function create() { - return $this->payloadRequest('POST'); - } - - /** - * delete the resource at this endpoint - * @return bool|mixed indicating the success of the request or content of the request response - * @throws NoResponseException - * @throws OperationNotAvailableException - * @throws ParameterRequiredException - */ - public function delete() { - if(in_array('DELETE', $this->_cache['operations'])) { - if ($this->valid('DELETE')) { - $url = $this->getQueryUrl('DELETE') . 'access_token='; - - $req = curl_init(); - curl_setopt($req, CURLOPT_CUSTOMREQUEST, "DELETE"); - curl_setopt($req, CURLOPT_RETURNTRANSFER, true); - - $attempts = 0; - $res = false; - while($res === false && $attempts < 3) { - curl_setopt($req, CURLOPT_URL, $url . $this->_auth->getToken()); - $res = curl_exec($req); - if(curl_getinfo($req, CURLINFO_HTTP_CODE) == 401 && $attempts < 2) { - $this->_auth->getNewToken(); - $res = false; - } - $attempts++; - } - - return $this->proceedResponse($req, $res); - } else { - throw new ParameterRequiredException('There are one or more required parameters missing for a DELETE request'); - } - } else { - throw new OperationNotAvailableException("Operation DELETE is not available."); - } - } - - /** - * prepare and send a request with body - * @param string $operation - * @return object representing the resource - * @throws NoResponseException - * @throws OperationNotAvailableException - * @throws ParameterRequiredException - */ - private function payloadRequest($operation) { - if(in_array($operation, $this->_cache['operations'])) { - if ($this->valid($operation)) { - $url = $this->baseUrl() . '?access_token='; - $params = json_encode($this->gatherParams($operation), JSON_BIGINT_AS_STRING); - - $req = curl_init(); - curl_setopt($req, CURLOPT_RETURNTRANSFER, true); - - $res = false; - $attempts = 0; - while($res === false && $attempts < 3) { - curl_setopt($req, CURLOPT_URL, $url . $this->_auth->getToken()); - curl_setopt($req, CURLOPT_CUSTOMREQUEST, $operation); - curl_setopt($req, CURLOPT_POSTFIELDS, $params); - curl_setopt($req, CURLOPT_HTTPHEADER, array( - 'Content-Type: application/json', - 'Content-Length: ' . strlen($params)) - ); - - $res = curl_exec($req); - if(curl_getinfo($req, CURLINFO_HTTP_CODE) == 401 && $attempts < 2) { - $this->_auth->getNewToken(); - $res = false; - } - $attempts++; - } - - return $this->proceedResponse($req, $res); - } else { - throw new ParameterRequiredException("There are one or more required parameters missing for a $operation request"); - } - } else { - throw new OperationNotAvailableException("Operation $operation is not available."); - } - } - - /** - * @param $req the curl request - * @param $res the response of the curl request - * @return bool|object indicating success or representing the returned resource - * @throws ActiveRoleRequiredException - * @throws InvalidAPIResponseException - * @throws NoResponseException - * @throws UnauthorizedException - */ - private function proceedResponse($req, $res) { - if($res !== false) { - if(strlen($res) < 2 && (curl_getinfo($req, CURLINFO_HTTP_CODE) == 200 || curl_getinfo($req, CURLINFO_HTTP_CODE) == 201 || curl_getinfo($req, CURLINFO_HTTP_CODE) == 204)) { - return true; - } else { - $json = json_decode($res); - if($json === null) { - throw new NoResponseException("Invalid JSON"); - } elseif(isset($json->status) && isset($json->status->code) && isset($json->status->message)) { - $this->proceedStatus($json->status); - } else { - return $json; - } - } - } else { - throw new NoResponseException(curl_error($req)); - } - } - - /** - * proceeds a returned status object and throws exceptions accordingly - * @param object $status - * @throws ActiveRoleRequiredException - * @throws InvalidAPIResponseException - * @throws UnauthorizedException - */ - private function proceedStatus($status) { - if($status->code == "403" && $status->message == "Active role required to view this content.") { - throw new ActiveRoleRequiredException("Active role required to view this content. This mostly happens when an non-active person login through EXPA. URL: " . $url . "access_token=" . $token . ""); - } elseif($status->code == "403" && $status->message == "You are not authorized to perform the requested action") { - throw new UnauthorizedException("You are not authorized to perform the requested action"); - } else { - throw new InvalidAPIResponseException($status->message); - } - } - - /** - * prepares the url for requests with parameters in the url - * @param string $operation http method - * @return string url with all parameters - */ - private function getQueryUrl($operation) { - $url = $this->baseUrl(); - $params = $this->gatherParams($operation); - - // build url - if (count($params) > 0) { - $params = http_build_query($params); - - // gis hack (replace numerical array keys with appending array key - $params = preg_replace('/(%5B[0-9]*%5D)/', '%5B%5D', $params); - - $url .= '?' . $params . '&'; - } else { - $url .= '?'; - } - return $url; + public function offsetSet($offset, $value) + { + $this->params[$offset] = $value; } /** - * @return string endpoint path with proceeded dynamic parts + * @param mixed $offset offset of the instance to be destroyed */ - private function baseUrl() { - // start with endpoint path - $url = $this->_cache['path']; - - // replace all dynamic path parts - foreach($this->_pathParams as $name => $value) { - $url = str_replace($name, $value, $url); - } - - return $url; + public function offsetUnset($offset) + { + unset($this->params[$offset]); } - /** - * @param string $operation http method - * @return array containing the relevant parameter values - */ - private function gatherParams($operation) { - $data = array(); - foreach($this->_params as $name => $param) { - $v = $param->getRequestValue($operation); - if($v != null) $data[$name] = $v; - } - - return $data; - } -} \ No newline at end of file +} diff --git a/src/APIEndpointDynamicSub.php b/src/APIEndpointDynamicSub.php deleted file mode 100644 index 7ae8dd0..0000000 --- a/src/APIEndpointDynamicSub.php +++ /dev/null @@ -1,97 +0,0 @@ - - * @package GISwrapper - * @version 0.2 - */ -class APIEndpointDynamicSub extends APIEndpoint implements \ArrayAccess -{ - /** - * @var DynamicSub - */ - private $_dynamicSub; - - /** - * APIEndpointDynamicSub constructor. - * @param array $cache parsed swagger file for this api - * @param AuthProvider $auth - * @param array $pathParams array with values for dynamic parts of the path - */ - public function __construct($cache, $auth, $pathParams = array()) - { - parent::__construct($cache, $auth, $pathParams); - - // create instance of DynamicSub class - $this->_dynamicSub = new DynamicSub($cache, $auth, $pathParams); - } - - /** - * @param mixed $name property name - * @return bool indicating if this property exists (Does not mean there is a instance. Use isset to check if the instance exists) - */ - public function exists($name) { - if(!$this->existsSub($name)) { - return $this->existsDynamicSub($name); - } else { - return true; - } - } - - /** - * @param mixed $name sub name - * @return bool indicating if a subpath with this name exists (Does not mean there is a instance. Use isset to check if the instance exists) - */ - public function existsSub($name) { - return parent::exists($name); - } - - /** - * @param mixed $name - * @return bool indicating if the offset exists for the dynamic subpath (Does not mean there is a instance. Use isset to check if the instance exists) - * @throws NoResponseException - */ - public function existsDynamicSub($name) { - return $this->_dynamicSub->exists($name); - } - - /** - * @param mixed $offset - * @return bool indicating if there is a instance for this offset - */ - public function offsetExists($offset) - { - return $this->_dynamicSub->offsetExists($offset); - } - - /** - * @param mixed $offset - * @return mixed instance for this offset - */ - public function offsetGet($offset) - { - return $this->_dynamicSub->offsetGet($offset); - } - - /** - * @param mixed $offset - * @param mixed $value - */ - public function offsetSet($offset, $value) - { - $this->_dynamicSub->offsetSet($offset, $value); - } - - /** - * @param mixed $offset - * deletes the instance at $offset - */ - public function offsetUnset($offset) - { - $this->_dynamicSub->offsetUnset($offset); - } -} \ No newline at end of file diff --git a/src/APIEndpointPaged.php b/src/APIEndpointPaged.php deleted file mode 100644 index 3ab2ed2..0000000 --- a/src/APIEndpointPaged.php +++ /dev/null @@ -1,216 +0,0 @@ - - * @package GISwrapper - * @version 0.2 - */ -class APIEndpointPaged extends APIEndpoint implements \Iterator, \Countable -{ - /** - * @var object containing the returned elements - */ - private $_data; - - /** - * @var bool indicating if there is loaded data - */ - private $_loaded; - - /** - * @var int number of total pages - */ - private $_pages; - - /** - * @var int - */ - private $_currentItem; - - /** - * @var int number of elements on the current page - */ - private $_pageItems; - - /** - * @var object containing the facets returned by some paged endpoints - */ - private $_facets; - - /** - * @var int number of total elements in the last request - */ - private $_count; - - // $_currentPage is already declared in the class Endpoint for use in the get method - // $_perPage is already declared in the class Endpoint for use in the get method - - /** - * @var int page to start on with foreach loop - */ - private $_startPage; - - /** - * APIEndpointPaged constructor. - * @param array $cache parsed swagger file for this api - * @param AuthProvider $auth - * @param array $pathParams array with values for dynamic parts of the path - */ - function __construct($cache, $auth, $pathParams = array()) - { - parent::__construct($cache, $auth, $pathParams); - $this->_loaded = false; - } - - /** - * load the current page - * @throws OperationNotAvailableException - * @throws ParameterRequiredException - */ - private function load() { - $res = $this->get(); - - $this->_data = $res->data; - - if(isset($res->facets)) { - $this->_facets = $res->facets; - } else { - $this->_facets = false; - } - - $this->_currentPage = $res->paging->current_page; - $this->_pages = $res->paging->total_pages; - $this->_pageItems = count($res->data); - $this->_count = $res->paging->total_items; - $this->_loaded = true; - } - - /** - * @return object containing the facets of the endpoint - */ - public function getFacets() { - if(!$this->_loaded) $this->load(); - return $this->_facets; - } - - /** - * Return the current element - */ - public function current() - { - return $this->_data[$this->_currentItem]; - } - - /** - * Move forward to next element - */ - public function next() - { - $this->_currentItem++; - if ($this->_currentItem >= $this->_pageItems) { - $this->_currentPage++; - if ($this->_currentPage <= $this->_pages) { - $expectedPage = $this->_currentPage; - $this->load(); - if($this->_currentPage != $expectedPage) { - throw new InvalidAPIResponseException("Got page " . $this->_currentPage . ' but expected page' . $expectedPage); - } - $this->_currentItem = 0; - } - } - } - - /** - * Return the key of the current element - */ - public function key() - { - if(isset($this->_data[$this->_currentItem]->id)) { - return $this->_data[$this->_currentItem]->id; - } else { - return $this->_currentPage . '_' . $this->_currentItem; - } - } - - /** - * Checks if current position is valid if $operation is null and else if the parameters of this endpoint are valid for the http method - * @param null|string $operation null or the http method - * @return bool - */ - public function valid($operation = null) - { - if($operation !== null) { - return parent::valid($operation); - } elseif($this->_currentItem < $this->_pageItems && $this->_currentPage <= $this->_pages) { - return true; - } - return false; - } - - /** - * Rewind the Iterator to the first element - */ - public function rewind() - { - $this->_currentItem = 0; - if($this->_startPage != null) { - $this->_currentPage = $this->_startPage; - } else { - $this->_currentPage = 1; - } - $this->load(); - } - - /** - * @return int number of elements with the current parameters - * @throws \Exception - */ - public function count() { - $p = $this->_currentPage; - $this->_currentPage = 1; - try { - $res = $this->get(); - } catch(\Exception $e) { - $this->_currentPage = $p; - throw $e; - } - $this->_currentPage = $p; - return $res->paging->total_items; - } - - /** - * @return int number of elements in the last request - */ - public function lastCount() { - return $this->_count; - } - - /** - * @return int number of the current page - */ - public function currentPage() { - if($this->_currentPage != null) { - return $this->_currentPage; - } else { - return 1; - } - } - - /** - * @param int $page page to start foreach loop with - */ - public function setStartPage($page) { - $this->_startPage = $page; - } - - /** - * @param int $number number of items per page - */ - public function setPerPage($number) { - $this->_perPage = $number; - } -} \ No newline at end of file diff --git a/src/APIEndpointPagedDynamicSub.php b/src/APIEndpointPagedDynamicSub.php deleted file mode 100644 index 3c1c694..0000000 --- a/src/APIEndpointPagedDynamicSub.php +++ /dev/null @@ -1,94 +0,0 @@ -_dynamicSub = new DynamicSub($cache, $auth, $pathParams); - } - - /** - * @param mixed $name property name - * @return bool indicating if this property exists (Does not mean there is a instance. Use isset to check if the instance exists) - */ - public function exists($name) { - if(!$this->existsSub($name)) { - return $this->existsDynamicSub($name); - } else { - return true; - } - } - - /** - * @param mixed $name sub name - * @return bool indicating if a subpath with this name exists (Does not mean there is a instance. Use isset to check if the instance exists) - */ - public function existsSub($name) { - return parent::exists($name); - } - - /** - * @param mixed $name - * @return bool indicating if the offset exists for the dynamic subpath (Does not mean there is a instance. Use isset to check if the instance exists) - * @throws NoResponseException - */ - public function existsDynamicSub($name) { - return $this->_dynamicSub->exists($name); - } - - /** - * @param mixed $offset - * @return bool indicating if there is a instance for this offset - */ - public function offsetExists($offset) - { - return $this->_dynamicSub->offsetExists($offset); - } - - /** - * @param mixed $offset - * @return mixed instance for this offset - */ - public function offsetGet($offset) - { - return $this->_dynamicSub->offsetGet($offset); - } - - /** - * @param mixed $offset - * @param mixed $value - */ - public function offsetSet($offset, $value) - { - $this->_dynamicSub->offsetSet($offset, $value); - } - - /** - * @param mixed $offset - * deletes the instance at $offset - */ - public function offsetUnset($offset) - { - $this->_dynamicSub->offsetUnset($offset); - } -} \ No newline at end of file diff --git a/src/APISubFactory.php b/src/APISubFactory.php deleted file mode 100644 index 2831c07..0000000 --- a/src/APISubFactory.php +++ /dev/null @@ -1,42 +0,0 @@ - - * @package GISwrapper - * @version 0.2 - */ -class APISubFactory -{ - /** - * @param array $cache parsed swagger file for this api - * @param AuthProvider $auth - * @param array $pathParams array with values for dynamic parts of the path - * @return API|APIDynamicSub|APIEndpoint|APIEndpointDynamicSub|APIEndpointPaged|APIEndpointPagedDynamicSub - */ - public static function factory($cache, $auth, $pathParams = array()) { - if($cache['endpoint']) { - if($cache['paged']) { - if($cache['dynamicSub']) { - return new APIEndpointPagedDynamicSub($cache, $auth, $pathParams); - } else { - return new APIEndpointPaged($cache, $auth, $pathParams); - } - } else { - if($cache['dynamicSub']) { - return new APIEndpointDynamicSub($cache, $auth, $pathParams); - } else { - return new APIEndpoint($cache, $auth, $pathParams); - } - } - } else { - if($cache['dynamicSub']) { - return new APIDynamicSub($cache, $auth, $pathParams); - } else { - return new API($cache, $auth, $pathParams); - } - } - } -} \ No newline at end of file diff --git a/src/DynamicSub.php b/src/DynamicSub.php deleted file mode 100644 index 0702c36..0000000 --- a/src/DynamicSub.php +++ /dev/null @@ -1,152 +0,0 @@ - - * @package GISwrapper - * @version 0.2 - */ -class DynamicSub implements \ArrayAccess -{ - /** - * @var AuthProvider - */ - private $_auth; - - /** - * @var array - */ - private $_cache; - - /** - * @var array - */ - private $_pathParams; - - /** - * @var string property name of the dynamic sub part - */ - private $_dynamicSub; - - /** - * @var array instances of the dynamic sub part - */ - private $_dynamicInstances; - - /** - * DynamicSub constructor. - * @param array $cache parsed swagger file for this api - * @param AuthProvider $auth - * @param array $pathParams array with values for dynamic parts of the path - * @throws RequirementInvalidEndpointException - */ - public function __construct($cache, $auth, $pathParams = array()) - { - $this->_auth = $auth; - $this->_cache = $cache; - $this->_pathParams = $pathParams; - $this->_dynamicInstances = array(); - - // find dynamic sub - $this->_dynamicSub = null; - foreach($cache['subs'] as $name => $sub) { - if($sub['dynamic']) { - if($this->_dynamicSub != null) { - throw new RequirementInvalidEndpointException("Found a second dynamic endpoint as sub endpoint"); - } else { - $this->_dynamicSub = $name; - } - } - } - if($this->_dynamicSub == null) { - throw new RequirementInvalidEndpointException("Could not find dynamic endpoint"); - } - } - - /** - * @param mixed $offset - * @return bool indicating if the resource at this offset exists - * @throws InvalidAPIResponseException - * @throws NoResponseException - */ - public function exists($offset) { - $url = $this->_cache['subs'][$this->_dynamicSub]['path']; - - // replace all dynamic path parts - foreach($this->_pathParams as $name => $value) { - $url = str_replace($name, $value, $url); - } - - // insert offset in the request - $url = str_replace($this->_dynamicSub, $offset, $url) . '?'; - - // get request - try { - $res = GET::request($url, $this->_auth); - } catch(NoResponseException $e) { - if(substr($e, 0, 4) == 'http') { - throw $e; - } else { - return false; - } - } - - // check if object exists - if(is_object($res)) { - if(isset($res->status) && ($res->status->code == 404 || $res->status->code == 500)) { - return false; - } else { - return true; - } - } else { - return false; - } - } - - /** - * @param mixed $offset - * @return bool indicating if this offset is instantiated - */ - public function offsetExists($offset) - { - return isset($this->_dynamicInstances[$offset]); - } - - /** - * @param mixed $offset - * @return mixed returns the instance at this offset - */ - public function offsetGet($offset) - { - if(!isset($this->_dynamicInstances[$offset])) { - $pathParams = $this->_pathParams; - $pathParams[$this->_dynamicSub] = $offset; - $this->_dynamicInstances[$offset] = APISubFactory::factory($this->_cache['subs'][$this->_dynamicSub], $this->_auth, $pathParams); - } - return $this->_dynamicInstances[$offset]; - } - - /** - * @param mixed $offset - * @param mixed $value - */ - public function offsetSet($offset, $value) - { - if(is_object($value) && ($value instanceof API || is_subclass_of($value, API::class))) { - $this->_dynamicInstances[$offset] = $value; - } else { - trigger_error("Object for offset " . $offset . " does not have the right type", E_USER_ERROR); - } - } - - /** - * @param mixed $offset offset of the instance to be destroyed - */ - public function offsetUnset($offset) - { - unset($this->_dynamicInstances[$offset]); - } -} \ No newline at end of file diff --git a/src/GET.php b/src/GET.php deleted file mode 100644 index baa1961..0000000 --- a/src/GET.php +++ /dev/null @@ -1,51 +0,0 @@ - - * @package GISwrapper - * @version 0.2 - */ -class GET -{ - /** - * @param string $url - * @param AuthProvider $auth - * @return object representing the requested resource - * @throws InvalidAPIResponseException - * @throws NoResponseException - */ - public static function request($url, $auth) { - // init curl request - $req = curl_init(); - curl_setopt($req, CURLOPT_RETURNTRANSFER, true); - - $attempts = 0; - $res = false; - while($res === false && $attempts < 3) { - curl_setopt($req, CURLOPT_URL, $url . 'access_token=' . $auth->getToken()); - $res = curl_exec($req); - if(curl_getinfo($req, CURLINFO_HTTP_CODE) == 401 && $attempts < 2) { - $auth->getNewToken(); - $res = false; - } elseif($res) { - $res = json_decode($res); - if($res === null) $res = false; - } - $attempts++; - } - - // validate response - if($res === false) { - throw new NoResponseException("Could not load endpoint " . $url); - } elseif($res == null) { - echo curl_getinfo($req, CURLOPT_URL); - throw new InvalidAPIResponseException("Invalid Response on " . $url); - } else { - return $res; - } - } -} \ No newline at end of file diff --git a/src/GIS.php b/src/GIS.php index a3fa92b..603a55c 100644 --- a/src/GIS.php +++ b/src/GIS.php @@ -3,114 +3,62 @@ /** * Class GIS - * entry point to the GIS / Parsing of swagger files + * entry point to the GIS * - * @author Karl Johann Schubert + * @author Lukas Ehnle * @package GISwrapper - * @version 0.2 + * @version 0.3 */ class GIS { - /** - * @var AuthProvider - */ - private $_auth; - - /** - * @var array - */ - private $_subs; - - /** - * @var array - */ - private $_cache; + private $api; /** * GIS constructor. * @param AuthProvider $auth - * @param string|array $apidoc url of apidocs or already parsed array * @throws InvalidAuthProviderException - * @throws InvalidSwaggerFormatException * @throws NoResponseException * @throws RequirementsException */ - function __construct($auth, $apidoc = "https://gis-api.aiesec.org/v2/docs.json") + function __construct($auth) { // check that $auth implements the AuthProvider interface if ($auth instanceof AuthProvider) { - $this->_auth = $auth; + API::createInstance($auth); + $this->api = new APIEndpoint(); } else { throw new InvalidAuthProviderException("The given object does not implement the AuthProvider interface."); } - - // proceed cache - if(is_array($apidoc)) { - $this->_cache = $apidoc; - } else { - $this->_cache = $this->generateSimpleCache($apidoc); - } - - // initialize array with sub endpoints and apis - $this->_subs = array(); } /** * @param mixed $name property name * @return mixed value of the property - * @throws InvalidSwaggerFormatException * @throws NoResponseException * @throws RequirementsException */ public function __get($name) { - if(array_key_exists($name, $this->_subs)) { - return $this->_subs[$name]; - } elseif(array_key_exists($name, $this->_cache)) { - if(!is_array($this->_cache[$name])) { - $this->_cache[$name] = $this->proceedSubCache($this->_cache[$name], $name); - } - $this->_subs[$name] = APISubFactory::factory($this->_cache[$name], $this->_auth); - return $this->_subs[$name]; - } else { - trigger_error("Property $name does not exists.", E_USER_ERROR); - } + return $this->api->__get($name); } /** * @param mixed $name name of the property * @param mixed $value value to set for the property - * @throws InvalidSwaggerFormatException * @throws NoResponseException * @throws RequirementsException */ public function __set($name, $value) { - if(array_key_exists($name, $this->_cache)) { - if($value instanceof API || is_subclass_of($value, API::class)) { - $this->_subs[$name] = $value; - } elseif(is_array($value)) { - if(!isset($this->_subs[$name])) { - if(!is_array($this->_cache[$name])) { - $this->_cache[$name] = $this->proceedSubCache($this->_cache[$name], $name); - } - $this->_subs[$name] = APISubFactory::factory($this->_cache[$name], $this->_auth); - } - foreach($value as $key => $v) { - $this->_subs[$name]->$key = $v; - } - } - } else { - trigger_error("Property " . $name . " does not exist", E_USER_ERROR); - } + return $this->api->__set($name, $value); } /** - * @param $name proeperty name + * @param $name property name * @return bool indicating if the property is instantiated */ public function __isset($name) { - return isset($this->_subs[$name]); + return $this->api->__isset($name); } /** @@ -118,217 +66,7 @@ public function __isset($name) */ public function __unset($name) { - if(isset($this->_subs[$name])) { - unset($this->_subs[$name]); - } - } - - /** - * @param $name property name - * @return bool indicating if the property exists (Does not mean it is instantiated. Use isset for this) - */ - public function exists($name) { - return array_key_exists($name, $this->_cache); - } - - /** - * @return array containing the current state of the swagger file parsing - */ - public function getCache() { - return $this->_cache; - } - - /** - * @param string $apidoc url of swagger file - * @return array containing only the parsed root swagger file - * @throws InvalidSwaggerFormatException - * @throws NoResponseException - * @throws RequirementsException - */ - public static function generateSimpleCache($apidoc = "https://gis-api.aiesec.org/v2/docs.json") { - $cache = array(); - $root = GIS::loadJSON($apidoc); - - if($root === false) { - throw new NoResponseException("Could not load swagger root file"); - } elseif($root === null || !isset($root->apis) || !is_array($root->apis) || !isset($root->basePath)) { - throw new InvalidSwaggerFormatException("Invalid swagger file"); - } else { - if(!in_array('application/json', $root->produces)) { - throw new RequirementsException("API does not produce JSON"); - } else { - foreach($root->apis as $api) { - $name = explode('.', basename($api->path))[0]; - $cache[$name] = $root->basePath . str_replace("{format}", "json", $api->path); - } - } - } - return $cache; + $this->api->__unset($name); } - /** - * @param string $apidoc url of swagger file - * @return array containing the parsing result of all swagger files - * @throws InvalidSwaggerFormatException - * @throws NoResponseException - * @throws RequirementsException - */ - public static function generateFullCache($apidoc = "https://gis-api.aiesec.org/v2/docs.json") { - $cache = GIS::generateSimpleCache($apidoc); - foreach($cache as $name => $data) { - if(!is_array($data)) $cache[$name] = GIS::proceedSubCache($data, $name); - } - return $cache; - } - - /** - * @param string $url to the sub swagger file - * @param string $baseName name of this section - * @return array parsed sub swagger file - * @throws InvalidSwaggerFormatException - * @throws NoResponseException - * @throws RequirementsException - */ - private static function proceedSubCache($url, $baseName) { - // prepare cache with API as root - $cache = array('endpoint' => false, 'dynamicSub' => false); - - // load api manifest - $manifest = GIS::loadJSON($url); - if($manifest === false) { - throw new NoResponseException("Could not load API swagger file"); - } elseif($manifest === null) { - throw new InvalidSwaggerFormatException("Invalid API swagger file"); - } else { - foreach($manifest->apis as $api) { - // prepare endpoint - $endpoint = array( - 'summary' => (isset($api->summary)) ? $api->summary : null, - 'path' => str_replace('.{format}', '.json', $manifest->basePath . $api->path), - 'endpoint' => true, - 'dynamic' => false, - 'dynamicSub' => false, - 'subs' => array(), - 'paged' => false, - 'operations' => array(), - 'params' => array() - ); - // when the filename part of the path starts with a {, the endpoint is dynamic - if(substr(basename($api->path), 0, 1) == '{') $endpoint['dynamic'] = true; - - // add all the operations - foreach($api->operations as $operation) { - // check for json support - if(!in_array('application/json', $operation->produces)) { - throw new RequirementsException("An Operation does not produce JSON"); - } - - // add operation - if(!in_array($operation->httpMethod, $endpoint['operations'])) { - $endpoint['operations'][] = $operation->httpMethod; - } - - // add parameters - foreach($operation->parameters as $parameter) { - if($parameter->name == "page" || $parameter->name == "per_page") { - $endpoint['paged'] = true; - } elseif($parameter->name != "access_token" && $parameter->paramType != "path") { - $m = array( - 'type' => $parameter->dataType, - 'required' => $parameter->required - ); - $names = explode('[', $parameter->name); - - if(!isset($endpoint['params'][$names[0]])) { - $endpoint['params'][$names[0]] = array('subparams' => array(), 'operations' => array()); - } - - if(count($names) == 1) { // level 1 parameter - // place data about this method in the endpoint - $endpoint['params'][$names[0]]['operations'][$operation->httpMethod] = $m; - } else { // level n parameter - $ref = &$endpoint['params'][$names[0]]; - unset($names[0]); - foreach($names as $name) { - // remove the closing bracket from the array notation - $name = str_replace(']', '', $name); - - // if intermediate param does not exist yet, create it - if(!isset($ref['subparams'][$name])) $ref['subparams'][$name] = array('subparams' => array(), 'operations' => array()); - - // move reference to the next subparam - $ref = &$ref['subparams'][$name]; - } - - // place data about this method in the endpoint - $ref['operations'][$operation->httpMethod] = $m; - } - } - } - } - - // prepare path for endpoint placement - $path = str_replace('.{format}', '', $api->path); - $path = str_replace('/' . $manifest->apiVersion . '/' . $baseName . '/', '' , $path); - $path = explode('/', $path); - - // place endpoint - if(str_replace('.{format}', '', $api->path) == '/' . $manifest->apiVersion . '/' . $baseName) { // root endpoint - if(isset($cache['subs']) && is_array($cache['subs'])) $endpoint['subs'] = $cache['subs']; - if(isset($cache['dynamicSub']) && $cache['dynamicSub']) $endpoint['dynamicSub'] = true; - - $cache = $endpoint; - } elseif(count($path) == 1) { // level 1 sub endpoint - // check for already added subs as well as the dynamicSub property and keep them - if(isset($cache['subs'][$path[0]]['subs'])) $endpoint['subs'] = $cache['subs'][$path[0]]['subs']; - if(isset($cache['subs'][$path[0]]['dynamicSub']) && $cache['subs'][$path[0]]['dynamicSub']) $endpoint['dynamicSub'] = true; - - // place endpoint - $cache['subs'][$path[0]] = $endpoint; - - // check if endpoint is dynamic and set dynamicSub of root endpoint/api accordingly - if($endpoint['dynamic']) $cache['dynamicSub'] = true; - } else { // level n sub endpoint - $ref = &$cache; - foreach($path as $p) { - // if intermediate endpoint or api does not exist yet, create it as API - if(!isset($ref['subs'][$p])) { - $ref['subs'][$p] = array('endpoint' => false, 'dynamic' => false, 'dynamicSub' => false, 'subs' => array()); - if(substr($p, 0, 1) == '{') $ref['subs'][$p]['dynamic'] = true; - } - - // check if we are at a dynamic endpoint and if yes set dynamicSub, before we move the reference forward - if(substr($p, 0, 1) == '{') $ref['dynamicSub'] = true; - - // move reference to next path part - $ref = &$ref['subs'][$p]; - } - // check for already added subs as well as the dynamicSub property and keep them - if(isset($ref['subs']) && is_array($ref['subs'])) $endpoint['subs'] = $ref['subs']; - if(isset($ref['dynamicSub']) && $ref['dynamicSub']) $endpoint['dynamicSub'] = true; - - // place endpoint - $ref = $endpoint; - } - } - } - return $cache; - } - - /** - * @param string $url - * @return bool|object - */ - private static function loadJSON($url) { - $root = false; - $attempts = 0; - while(!$root && $root !== null && $attempts < 3) { - $root = file_get_contents($url); - if($root !== false) { - $root = json_decode($root); - } - $attempts++; - } - return $root; - } -} \ No newline at end of file +} diff --git a/src/ParameterArrayType.php b/src/ParameterArrayType.php deleted file mode 100644 index 3792a43..0000000 --- a/src/ParameterArrayType.php +++ /dev/null @@ -1,207 +0,0 @@ - - * @package GISwrapper - * @version 0.2 - */ -class ParameterArrayType extends ParameterDefaultType implements \ArrayAccess, \Iterator, \Countable -{ - /** - * @var array - */ - private $_values; - - /** - * @var int - */ - private $_currentKey; - - /** - * @var array - */ - private $_currentKeys; - - /** - * ParameterArrayType constructor. - * @param array $cache parsed swagger file for this parameters - * @param bool $strict true if this parameter is an array for all operations which it is part of - */ - public function __construct($cache, $strict) - { - parent::__construct($cache); - $this->_values = array(); - $this->_strict = $strict; - } - - /** - * @param mixed $offset - * @return bool indicating if this offset is instantiated - */ - public function offsetExists($offset) - { - return isset($this->_values[$offset]); - } - - /** - * @param mixed $offset - * @return mixed instance of this offset if there are subparameters or else the value at this offset - */ - public function offsetGet($offset) - { - if(!isset($this->_values[$offset])) { - $this->_values[$offset] = new ParameterDefaultType($this->_cache); - } - if($this->_values[$offset]->hasChilds() || $this->_values[$offset] instanceof ParameterArrayType) { - return $this->_values[$offset]; - } else { - return $this->_values[$offset]->value(); - } - } - - /** - * @param mixed $offset - * @param mixed $value Parameter instance or value for the offset - */ - public function offsetSet($offset, $value) - { - if($value instanceof ParameterDefaultType) { - if(is_null($offset)) { - $this->_values[] = $value; - } else { - $this->_values[$offset] = $value; - } - } else { - if(is_null($offset)) { - $val = new ParameterDefaultType($this->_cache); - $val->value($value); - $this->_values[] = $val; - } else { - if(!isset($this->_values[$offset])) { - $this->_values[$offset] = new ParameterDefaultType($this->_cache); - } - $this->_values[$offset]->value($value); - } - } - } - - /** - * @param mixed $offset offset of the instance to be destroyed - */ - public function offsetUnset($offset) - { - unset($this->_values[$offset]); - } - - /** - * returns the instance at the current offset, or the value if there are no subparameters - * @return mixed - */ - public function current() - { - if($this->_values[$this->_currentKeys[$this->_currentKey]]->hasChilds() || $this->_values[$this->_currentKeys[$this->_currentKey]] instanceof ParameterArrayType) { - return $this->_values[$this->_currentKeys[$this->_currentKey]]; - } else { - return $this->_values[$this->_currentKeys[$this->_currentKey]]->value(); - } - } - - /** - * move to the next offset - */ - public function next() - { - $this->_currentKey++; - } - - /** - * @return mixed key of the current offset - */ - public function key() - { - return $this->_currentKeys[$this->_currentKey]; - } - - /** - * Rewind the Iterator to the first element - */ - public function rewind() - { - $this->_currentKey = 0; - $this->_currentKeys = array_keys($this->_values); - } - - /** - * @return int number of elements of this parameter - */ - public function count() - { - return count($this->_values); - } - - /** - * Checks if current position is valid if $operation is null and else if this parameter is valid for the http method - * @param null|string $operation null or the http method - * @return bool - */ - public function valid($operation = null) { - if($operation === null) { - return isset($this->_currentKeys[$this->_currentKey]); - } else { - if(isset($this->_cache['operations'][$operation])) { - if($this->_cache['operations'][$operation]['type'] == "Array") { - if($this->hasChilds()) { - foreach ($this->_values as $value) { - if (!$value->valid($operation)) { - return false; - } - } - return true; - } else { - if($this->_cache['operations'][$operation]['required'] && count($this->_values) == 0) { - return false; - } - foreach ($this->_values as $value) { - if(!is_scalar($value->value()) || $value->value() === null) { - return false; - } - } - return true; - } - } else { - return parent::valid($operation); - } - } else { - return true; - } - } - } - - /** - * @param string $operation http method - * @return array|null|string value of the parameter for the specified http method - */ - public function getRequestValue($operation) - { - if($this->_cache['operations'][$operation]['type'] == "Array") { - $r = array(); - foreach ($this->_values as $key => $value) { - $v = $value->getRequestValue($operation); - if ($v !== null) { - $r[] = $v; - } - } - if (count($r) > 0) { - return $r; - } else { - return null; - } - } else { - return parent::getRequestValue($operation); - } - } -} \ No newline at end of file diff --git a/src/ParameterDefaultType.php b/src/ParameterDefaultType.php deleted file mode 100644 index 372b5bc..0000000 --- a/src/ParameterDefaultType.php +++ /dev/null @@ -1,316 +0,0 @@ - - * @package GISwrapper - * @version 0.2 - */ -class ParameterDefaultType -{ - /** - * @var array - */ - protected $_subparams; - - /** - * @var array - */ - protected $_cache; - - /** - * @var mixed - */ - protected $_value; - - /** - * @var bool - */ - protected $_strict; - - /** - * ParameterDefaultType constructor. - * @param array $cache parsed swagger file for this parameter - */ - function __construct($cache) - { - $this->_cache = $cache; - $this->_subparams = array(); - $this->_strict = false; - } - - /** - * @param mixed $name name of the subparameter - * @return null|mixed property value or instance - */ - public function __get($name) { - if(array_key_exists($name, $this->_cache['subparams'])) { - if(!isset($this->_subparams[$name])) { - $this->_subparams[$name] = ParameterFactory::factory($this->_cache['subparams'][$name]); - } - if($this->_subparams[$name]->hasChilds() || $this->_subparams[$name] instanceof ParameterArrayType) { - return $this->_subparams[$name]; - } else { - return $this->_subparams[$name]->get(); - } - } else { - trigger_error("Property " . $name . " does not exists", E_USER_WARNING); - return null; - } - } - - /** - * @param $name Name of the subparameter - * @param $value Sets the child $name to $value if it is an object or sets the value of $name to $value if $value is not a object - */ - public function __set($name, $value) { - if(array_key_exists($name, $this->_cache['subparams'])) { - if($value instanceof ParameterDefaultType || is_subclass_of($value, ParameterDefaultType::class)) { - $this->_subparams[$name] = $value; - } else { - if(!isset($this->_subparams[$name])) { - $this->_subparams[$name] = ParameterFactory::factory($this->_cache['subparams'][$name]); - } - if(is_scalar($value) || $value instanceof \DateTime) { - $this->_subparams[$name]->value($value); - } elseif(is_array($value)) { - // recreate subparam to reset other keys and keep scalar value if existent - $v = ((isset($this->_subparams[$name]) && is_scalar($this->_subparams[$name]->value())) ? $this->_subparams[$name]->value() : null); - $this->_subparams[$name] = ParameterFactory::factory($this->_cache['subparams'][$name]); - $this->_subparams[$name]->value($v); - - //proceed array - if($this->_subparams[$name] instanceof ParameterArrayType) { - foreach($value as $key => $v) { - $this->_subparams[$name]->offsetSet($key, $v); - } - } else { - foreach($value as $key => $v) { - $this->_subparams[$name]->$key = $v; - } - } - } else { - trigger_error("Invalid value for property " . $name, E_USER_ERROR); - } - } - } else { - trigger_error("Property " . $name . " does not exist.", E_USER_WARNING); - } - } - - /** - * convert this parameter to a string - * @return string - */ - public function __toString() - { - if($this->hasChilds()) { - return "ArrayParameter"; - } else { - return strval($this->_value); - } - } - - /** - * @param mixed $name property name of the instance to be destroyed - */ - public function __unset($name) { - if(isset($this->_subparams[$name])) { - unset($this->_subparams[$name]); - } - } - - /** - * @param $name property name - * @return bool indicating if the property is instantiated - */ - public function __isset($name) { - return isset($this->_subparams[$name]); - } - - /** - * @param $name property name - * @return bool indicating if the property exists (Does not mean it is instantiated. Use isset for this) - */ - public function exists($name) { - return isset($this->_cache['subparams'][$name]); - } - - /** - * @param mixed|null $value sets the value of this parameter if $value is not null - * @return mixed|null - */ - public function value($value = null) { - if($this->hasChilds()) { - if($value === null) { - $r = array(); - foreach($this->_subparams as $name => $param) { - $v = $param->get(); - if($v !== null) { - $r[$name] = $v; - } - } - if(count($r) > 0) { - return $r; - } else { - return null; - } - } else { - if(is_array($value)) { - $this->_subparams = array(); - foreach($value as $key => $v) { - if(array_key_exists($key, $this->_cache['subparams'])) { - if(!isset($this->_subparams[$key])) { - $this->_subparams[$key] = ParameterFactory::factory($this->_cache['subparams'][$key]); - } - $this->_subparams[$key]->value($v); - } else { - trigger_error("Property " . $key . " does not exist", E_USER_ERROR); - } - } - } else { - trigger_error("Can not set value of Parameter with subparameters", E_USER_ERROR); - } - } - } else { - if ($value !== null) { - if(is_scalar($value) || $value instanceof \DateTime) { - if($this->_strict) { - trigger_error("Can not set a scalar value to a Parameter which is in all operations an Array.", E_USER_ERROR); - } else { - $this->_value = $value; - } - } else { - trigger_error("Property value must be scalar.", E_USER_ERROR); - } - } - return $this->_value; - } - } - - /** - * @return mixed|null The value of this parameter - */ - public function get() { - return $this->value(); - } - - /** - * @param $value Sets the value of this parameter - */ - public function set($value) { - $this->value($value); - } - - /** - * @return bool indicating if this parameter has subparameters - */ - public function hasChilds() { - return (count($this->_cache['subparams']) > 0); - } - - /** - * @param $operation http method to check for - * @return bool - * @throws InvalidParameterTypeException - */ - public function valid($operation) { - if(array_key_exists($operation, $this->_cache['operations'])) { - switch($this->_cache['operations'][$operation]['type']) { - case 'Integer': - if(is_int($this->_value)) { - return true; - } else { - return false; - } - break; - - case 'String': - if(is_string($this->_value)) { - return true; - } else { - return false; - } - break; - - case 'Date': - case 'DateTime': - if($this->_value instanceof \DateTime) { - return true; - } else { - return false; - } - break; - - case 'Virtus::Attribute::Boolean': - if(is_bool($this->_value)) { - return true; - } else { - return false; - } - break; - - case 'Hash': - foreach($this->_cache['subparams'] as $name => $subparam) { - if(isset($this->_subparams[$name])) { - if(!$this->_subparams[$name]->valid($operation)) return false; - } elseif(isset($subparam['operations'][$operation]) && $subparam['operations'][$operation]['required']) { - return false; - } - } - return true; - break; - - case 'Array': - if($this->hasChilds()) { - foreach($this->_cache['subparams'] as $name => $subparam) { - if(isset($this->_subparams[$name])) { - if(!$this->_subparams[$name]->valid($operation)) return false; - } elseif(isset($subparam['operations'][$operation]) && $subparam['operations'][$operation]['required']) { - return false; - } - } - return true; - } else { - return false; - } - break; - - default: - throw new InvalidParameterTypeException("Can not handle parameter type " . $this->_cache['operations'][$operation]['type']); - } - } else { - return true; - } - } - - /** - * @param $operation http method - * @return array|null|mixed value of this parameter for the specified http method - */ - public function getRequestValue($operation) { - if($this->hasChilds()) { - $r = array(); - foreach($this->_cache['subparams'] as $name => $param) { - if(array_key_exists($operation, $param['operations'])) { - if(isset($this->_subparams[$name])) { - $v = $this->_subparams[$name]->getRequestValue($operation); - if($v !== null) { - $r[$name] = $v; - } - } - } - } - if(count($r) > 0) { - return $r; - } else { - return null; - } - } else { - return $this->_value; - } - } -} \ No newline at end of file diff --git a/src/ParameterFactory.php b/src/ParameterFactory.php deleted file mode 100644 index 4fd46de..0000000 --- a/src/ParameterFactory.php +++ /dev/null @@ -1,34 +0,0 @@ - - * @package GISwrapper - * @version 0.2 - */ -class ParameterFactory -{ - /** - * @param array $cache parsed swagger file for this parameter - * @return ParameterArrayType|ParameterDefaultType - */ - public static function factory($cache) { - $array = false; - $strict = true; - foreach($cache['operations'] as $o) { - if($o['type'] == "Array") { - $array = true; - break; - } else { - $strict = false; - } - } - if($array) { - return new ParameterArrayType($cache, $strict); - } else { - return new ParameterDefaultType($cache); - } - } -} \ No newline at end of file diff --git a/tests/.gitignore b/tests/.gitignore deleted file mode 100644 index 4f4773f..0000000 --- a/tests/.gitignore +++ /dev/null @@ -1 +0,0 @@ -config.php diff --git a/tests/APITest.php b/tests/APITest.php deleted file mode 100644 index 879406f..0000000 --- a/tests/APITest.php +++ /dev/null @@ -1,525 +0,0 @@ -_cache = array( - 'api_endpoint' => array( - 'summary' => '', - 'path' => '', - 'endpoint' => true, - 'dynamic' => false, - 'dynamicSub' => false, - 'subs' => array( - 'api' => array( - 'endpoint' => false, - 'dynamic' => false, - 'dynamicSub' => false, - 'subs' => array() - ) - ), - 'params' => array( - 'some_id' => array( - 'subparams' => array(), - 'operations' => array( - 'GET' => array( - 'type' => 'Integer', - 'required' => true - ) - ) - ) - ), - 'paged' => false, - 'operations' => array('GET') - ), - 'api_endpoint_dynamicSub' => array( - 'summary' => '', - 'path' => '', - 'endpoint' => true, - 'dynamic' => false, - 'dynamicSub' => true, - 'subs' => array( - '{dynamic}' => array( - 'summary' => '', - 'path' => 'file://' . __DIR__ . '/{dynamic}.json', - 'endpoint' => true, - 'dynamic' => true, - 'dynamicSub' => false, - 'subs' => array(), - 'params' => array(), - 'paged' => false, - 'operations' => array('GET') - ), - 'someSub' => array() - ), - 'params' => array(), - 'paged' => false, - 'operations' => array('GET') - ), - 'api_paged_endpoint' => array( - 'summary' => '', - 'path' => 'file://' . __DIR__ . '/paged.json', - 'endpoint' => true, - 'dynamic' => false, - 'dynamicSub' => false, - 'subs' => array(), - 'params' => array(), - 'paged' => true, - 'operations' => array('GET') - ), - 'api_paged_endpoint_dynamicSub' => array( - 'summary' => '', - 'path' => '', - 'endpoint' => true, - 'dynamic' => false, - 'dynamicSub' => true, - 'subs' => array( - '{dynamic}' => array( - 'summary' => '', - 'path' => 'file://' . __DIR__ . '/{dynamic}.json', - 'endpoint' => true, - 'dynamic' => true, - 'dynamicSub' => false, - 'subs' => array(), - 'params' => array(), - 'paged' => false, - 'operations' => array('GET') - ), - 'someSub' => array() - ), - 'params' => array(), - 'paged' => true, - 'operations' => array('GET') - ), - 'api' => array( - 'endpoint' => false, - 'dynamic' => false, - 'dynamicSub' => false, - 'subs' => array( - 'anotherAPI' => array( - 'endpoint' => false, - 'dynamic' => false, - 'dynamicSub' => false, - 'subs' => array() - ) - ) - ), - 'api_dynamicSub' => [ - 'endpoint' => false, - 'dynamic' => false, - 'dynamicSub' => true, - 'subs' => array( - '{dynamic}' => array( - 'summary' => '', - 'path' => 'file://' . __DIR__ . '/{dynamic}.json', - 'endpoint' => true, - 'dynamic' => true, - 'dynamicSub' => false, - 'subs' => array(), - 'params' => array(), - 'paged' => false, - 'operations' => array('GET') - ), - 'someSub' => array() - ) - ], - 'status' => array( - 'endpoint' => false, - 'dynamic' => false, - 'dynamicSub' => false, - 'subs' => array( - 'activeRole' => array( - 'summary' => '', - 'path' => 'file://' . __DIR__ . '/activeRole.json', - 'endpoint' => true, - 'dynamic' => false, - 'dynamicSub' => false, - 'subs' => array(), - 'params' => array(), - 'paged' => false, - 'operations' => array('GET') - ), - 'unauthorized' => array( - 'summary' => '', - 'path' => 'file://' . __DIR__ . '/unauthorized.json', - 'endpoint' => true, - 'dynamic' => false, - 'dynamicSub' => false, - 'subs' => array(), - 'params' => array(), - 'paged' => false, - 'operations' => array('GET') - ), - 'invalid' => array( - 'summary' => '', - 'path' => 'file://' . __DIR__ . '/invalid.json', - 'endpoint' => true, - 'dynamic' => false, - 'dynamicSub' => false, - 'subs' => array(), - 'params' => array(), - 'paged' => false, - 'operations' => array('GET') - ) - ) - ), - 'noGet' => array( - 'summary' => '', - 'path' => '', - 'endpoint' => true, - 'dynamic' => false, - 'dynamicSub' => false, - 'subs' => array(), - 'params' => array(), - 'paged' => false, - 'operations' => array('POST') - ), - ); - $this->_user = new \GISwrapper\AuthProviderEXPA(EXPA_USER, EXPA_PW); - $this->_gis = new \GISwrapper\GIS($this->_user, $this->_cache); - - $this->_files = array(); - - // create testfile for dynamic Sub - $file1 = __DIR__ . '/12.json'; - file_put_contents($file1, '{"id": "12", "name": "Test"}'); - $this->_files[] = $file1; - - // create testfiles for pagedEndpoint (can not simulate the page parameter on the filesystem) - $file2 = __DIR__ . '/paged.json'; - file_put_contents($file2, file_get_contents(__DIR__ . '/assets/page1.json')); - $this->_files[] = $file2; - - // create testfile for ActiveRoleException - $file3 = __DIR__ . '/activeRole.json'; - file_put_contents($file3, '{"status": {"code": "403", "message": "Active role required to view this content."}}'); - $this->_files[] = $file3; - - // create testfile for InvalidAPIResponseExceptionException - $file4 = __DIR__ . '/unauthorized.json'; - file_put_contents($file4, '{"status": {"code": "403", "message": "You are not authorized to perform the requested action"}}'); - $this->_files[] = $file4; - - // create testfile for ActiveRoleException - $file5 = __DIR__ . '/invalid.json'; - file_put_contents($file5, '{"status": {"code": "500", "message": "Server Error"}}'); - $this->_files[] = $file5; - } - - public function testGIS() { - $this->assertEquals($this->_cache, $this->_gis->getCache()); - - $this->assertTrue($this->_gis->exists('api')); - $this->assertTrue($this->_gis->exists('api_endpoint')); - $this->assertTrue($this->_gis->exists('api_endpoint_dynamicSub')); - $this->assertTrue($this->_gis->exists('api_paged_endpoint')); - $this->assertTrue($this->_gis->exists('api_paged_endpoint_dynamicSub')); - $this->assertFalse($this->_gis->exists('unexistend_api')); - - $this->assertFalse(isset($this->_gis->api)); - $this->assertFalse(isset($this->_gis->api_endpoint)); - $this->assertFalse(isset($this->_gis->api_endpoint_dynamicSub)); - $this->assertFalse(isset($this->_gis->api_paged_endpoint)); - $this->assertFalse(isset($this->_gis->api_paged_endpoint_dynamicSub)); - - $this->assertNotNull($this->_gis->api); - $this->assertNotNull($this->_gis->api_endpoint); - $this->assertNotNull($this->_gis->api_endpoint_dynamicSub); - $this->assertNotNull($this->_gis->api_paged_endpoint); - $this->assertNotNull($this->_gis->api_paged_endpoint_dynamicSub); - - $this->assertTrue(isset($this->_gis->api)); - $this->assertTrue(isset($this->_gis->api_endpoint)); - $this->assertTrue(isset($this->_gis->api_endpoint_dynamicSub)); - $this->assertTrue(isset($this->_gis->api_paged_endpoint)); - $this->assertTrue(isset($this->_gis->api_paged_endpoint_dynamicSub)); - } - - public function testInstanceClasses() { - $this->assertInstanceOf('\GISwrapper\API', $this->_gis->api); - $this->assertInstanceOf('\GISwrapper\APIEndpointPagedDynamicSub', $this->_gis->api_paged_endpoint_dynamicSub); - $this->assertInstanceOf('\GISwrapper\APIEndpoint', $this->_gis->api_paged_endpoint_dynamicSub[0]); - $this->assertInstanceOf('\GISwrapper\APIEndpointPaged', $this->_gis->api_paged_endpoint); - $this->assertInstanceOf('\GISwrapper\APIEndpointDynamicSub', $this->_gis->api_endpoint_dynamicSub); - $this->assertInstanceOf('\GISwrapper\APIEndpoint', $this->_gis->api_endpoint_dynamicSub[0]); - $this->assertInstanceOf('\GISwrapper\APIEndpoint', $this->_gis->api_endpoint); - } - - public function testUnset() { - $this->assertFalse(isset($this->_gis->api)); - $this->assertNotNull($this->_gis->api); - $this->assertTrue(isset($this->_gis->api)); - unset($this->_gis->api); - $this->assertFalse(isset($this->_gis->api)); - } - - public function testAPI() { - $this->assertTrue($this->_gis->api->exists('anotherAPI')); - $this->assertFalse($this->_gis->api->exists('nonExistendAPI')); - - unset($this->_gis->api->anotherAPI); - $this->assertFalse(isset($this->_gis->api->anotherAPI)); - $this->assertNotNull($this->_gis->api->anotherAPI); - $this->assertTrue(isset($this->_gis->api->anotherAPI)); - } - - public function testEndpoint() { - $this->assertFalse(isset($this->_gis->api_endpoint->api)); - $this->assertFalse(isset($this->_gis->api_endpoint->some_id)); - - $this->assertTrue($this->_gis->api_endpoint->exists('api')); - $this->assertTrue($this->_gis->api_endpoint->exists('some_id')); - $this->assertFalse($this->_gis->api_endpoint->exists('unexistend_api')); - $this->assertFalse($this->_gis->api_endpoint->exists('unexistend_param')); - - $this->assertNotNull($this->_gis->api_endpoint->api); - $this->_gis->api_endpoint->some_id = 10; - $this->assertEquals(10, $this->_gis->api_endpoint->some_id); - - $this->assertTrue(isset($this->_gis->api_endpoint->api)); - $this->assertTrue(isset($this->_gis->api_endpoint->some_id)); - - unset($this->_gis->api_endpoint->api); - unset($this->_gis->api_endpoint->some_id); - - $this->assertFalse(isset($this->_gis->api_endpoint->api)); - $this->assertFalse(isset($this->_gis->api_endpoint->some_id)); - - $this->assertEquals(['GET'], $this->_gis->api_endpoint->getOperations()); - - $this->assertFalse($this->_gis->api_endpoint->valid('GET')); - $this->assertFalse($this->_gis->api_endpoint->valid('POST')); - $this->_gis->api_endpoint->some_id = 12; - $this->assertTrue($this->_gis->api_endpoint->valid('GET')); - $this->assertFalse($this->_gis->api_endpoint->valid('POST')); - } - - public function testEndpointDynamicSub() { - // test offsetExists - $this->assertFalse(isset($this->_gis->api_endpoint_dynamicSub[12])); - $this->assertFalse(isset($this->_gis->api_endpoint_dynamicSub[13])); - $this->assertNotNull($this->_gis->api_endpoint_dynamicSub[12]); - $this->assertNotNull($this->_gis->api_endpoint_dynamicSub[13]); - $this->assertTrue(isset($this->_gis->api_endpoint_dynamicSub[12])); - $this->assertTrue(isset($this->_gis->api_endpoint_dynamicSub[13])); - - // test exists - $this->assertTrue($this->_gis->api_endpoint_dynamicSub->exists('someSub')); - $this->assertFalse($this->_gis->api_endpoint_dynamicSub->exists('{dynamic}')); - $this->assertFalse($this->_gis->api_endpoint_dynamicSub->exists('nonExistentSub')); - $this->assertTrue($this->_gis->api_endpoint_dynamicSub->exists('12')); - $this->assertFalse($this->_gis->api_endpoint_dynamicSub->exists('13')); - - // test existsSub - $this->assertTrue($this->_gis->api_endpoint_dynamicSub->existsSub('someSub')); - $this->assertFalse($this->_gis->api_endpoint_dynamicSub->existsSub('{dynamic}')); - $this->assertFalse($this->_gis->api_endpoint_dynamicSub->existsSub('nonExistentSub')); - $this->assertFalse($this->_gis->api_endpoint_dynamicSub->existsSub('12')); - - // test existsDynamicSub - $this->assertTrue($this->_gis->api_endpoint_dynamicSub->existsDynamicSub('12')); - $this->assertFalse($this->_gis->api_endpoint_dynamicSub->existsDynamicSub('13')); - $this->assertFalse($this->_gis->api_endpoint_dynamicSub->existsDynamicSub('someSub')); - - // test offsetGet - $el = $this->_gis->api_endpoint_dynamicSub[12]; - $this->assertNotNull($el); - - // test offsetSet - $this->_gis->api_endpoint_dynamicSub[12] = $el; - $this->assertEquals($el, $this->_gis->api_endpoint_dynamicSub[12]); - - // test offsetUnset - unset($this->_gis->api_endpoint_dynamicSub[12]); - $this->assertFalse(isset($this->api_endpoint_dynamicSub[12])); - } - - public function testEndpointPaged() { - // check Iterator Interface - $i = 1; - foreach($this->_gis->api_paged_endpoint as $id => $el) { - $this->assertEquals($i, $id); - - $this->assertObjectHasAttribute('id', $el); - $this->assertObjectHasAttribute('name', $el); - $this->assertEquals("element", substr($el->name, 0, 7)); - - $this->assertEquals($id, $el->id); - - // check that we are not in an infinite loop - $this->assertLessThan(5, $i, "Loop running to long"); - - // increment $i - $i++; - } - $this->assertEquals(5, $i); - - // check Facets - $facets = $this->_gis->api_paged_endpoint->getFacets(); - $this->assertNotNull($facets); - $this->assertObjectHasAttribute("statusA", $facets); - $this->assertObjectHasAttribute("statusB", $facets); - $this->assertEquals(12, $facets->statusA); - $this->assertEquals(24, $facets->statusB); - - // test count - $this->assertEquals(4, $this->_gis->api_paged_endpoint->lastCount()); - $this->assertCount(4, $this->_gis->api_paged_endpoint); - } - - public function testEndpointPagedDynamicSub() { - // test offsetExists - $this->assertFalse(isset($this->_gis->api_paged_endpoint_dynamicSub[12])); - $this->assertFalse(isset($this->_gis->api_paged_endpoint_dynamicSub[13])); - $this->assertNotNull($this->_gis->api_paged_endpoint_dynamicSub[12]); - $this->assertNotNull($this->_gis->api_paged_endpoint_dynamicSub[13]); - $this->assertTrue(isset($this->_gis->api_paged_endpoint_dynamicSub[12])); - $this->assertTrue(isset($this->_gis->api_paged_endpoint_dynamicSub[13])); - - // test exists - $this->assertTrue($this->_gis->api_paged_endpoint_dynamicSub->exists('someSub')); - $this->assertFalse($this->_gis->api_paged_endpoint_dynamicSub->exists('{dynamic}')); - $this->assertFalse($this->_gis->api_paged_endpoint_dynamicSub->exists('nonExistentSub')); - $this->assertTrue($this->_gis->api_paged_endpoint_dynamicSub->exists('12')); - $this->assertFalse($this->_gis->api_paged_endpoint_dynamicSub->exists('13')); - - // test existsSub - $this->assertTrue($this->_gis->api_paged_endpoint_dynamicSub->existsSub('someSub')); - $this->assertFalse($this->_gis->api_paged_endpoint_dynamicSub->existsSub('{dynamic}')); - $this->assertFalse($this->_gis->api_paged_endpoint_dynamicSub->existsSub('nonExistentSub')); - $this->assertFalse($this->_gis->api_paged_endpoint_dynamicSub->existsSub('12')); - - // test existsDynamicSub - $this->assertTrue($this->_gis->api_paged_endpoint_dynamicSub->existsDynamicSub('12')); - $this->assertFalse($this->_gis->api_paged_endpoint_dynamicSub->existsDynamicSub('13')); - $this->assertFalse($this->_gis->api_paged_endpoint_dynamicSub->existsDynamicSub('someSub')); - - // test offsetGet - $el = $this->_gis->api_paged_endpoint_dynamicSub[12]; - $this->assertNotNull($el); - - // test offsetSet - $this->_gis->api_paged_endpoint_dynamicSub[12] = $el; - $this->assertEquals($el, $this->_gis->api_paged_endpoint_dynamicSub[12]); - - // test offsetUnset - unset($this->_gis->api_paged_endpoint_dynamicSub[12]); - $this->assertFalse(isset($this->api_paged_endpoint_dynamicSub[12])); - } - - public function testAPIDynamicSub() { - // test offsetExists - $this->assertFalse(isset($this->_gis->api_dynamicSub[12])); - $this->assertFalse(isset($this->_gis->api_dynamicSub[13])); - $this->assertNotNull($this->_gis->api_dynamicSub[12]); - $this->assertNotNull($this->_gis->api_dynamicSub[13]); - $this->assertTrue(isset($this->_gis->api_dynamicSub[12])); - $this->assertTrue(isset($this->_gis->api_dynamicSub[13])); - - // test exists - $this->assertTrue($this->_gis->api_dynamicSub->exists('someSub')); - $this->assertFalse($this->_gis->api_dynamicSub->exists('{dynamic}')); - $this->assertFalse($this->_gis->api_dynamicSub->exists('nonExistentSub')); - $this->assertTrue($this->_gis->api_dynamicSub->exists('12')); - $this->assertFalse($this->_gis->api_dynamicSub->exists('13')); - - // test existsSub - $this->assertTrue($this->_gis->api_dynamicSub->existsSub('someSub')); - $this->assertFalse($this->_gis->api_dynamicSub->existsSub('{dynamic}')); - $this->assertFalse($this->_gis->api_dynamicSub->existsSub('nonExistentSub')); - $this->assertFalse($this->_gis->api_dynamicSub->existsSub('12')); - - // test existsDynamicSub - $this->assertTrue($this->_gis->api_dynamicSub->existsDynamicSub('12')); - $this->assertFalse($this->_gis->api_dynamicSub->existsDynamicSub('13')); - $this->assertFalse($this->_gis->api_dynamicSub->existsDynamicSub('someSub')); - - // test offsetGet - $el = $this->_gis->api_dynamicSub[12]; - $this->assertNotNull($el); - - // test offsetSet - $this->_gis->api_dynamicSub[12] = $el; - $this->assertEquals($el, $this->_gis->api_dynamicSub[12]); - - // test offsetUnset - unset($this->_gis->api_dynamicSub[12]); - $this->assertFalse(isset($this->api_dynamicSub[12])); - } - - /** - * @expectedException \GISwrapper\ParameterRequiredException - */ - public function testParameterRequiredException() { - $this->_gis->api_endpoint->get(); - } - - /** - * @expectedException \GISwrapper\OperationNotAvailableException - * @expectedExceptionMessage Operation GET is not available - */ - public function testOperationNotAvailableExceptionGET() { - $this->_gis->noGet->get(); - } - - /** - * @expectedException \GISwrapper\OperationNotAvailableException - * @expectedExceptionMessage Operation PATCH is not available - */ - public function testOperationNotAvailableExceptionPATCH() { - $this->_gis->api_endpoint->update(); - } - - /** - * @expectedException \GISwrapper\OperationNotAvailableException - * @expectedExceptionMessage Operation POST is not available - */ - public function testOperationNotAvailableExceptionPOST() { - $this->_gis->api_endpoint->create(); - } - - /** - * @expectedException \GISwrapper\OperationNotAvailableException - * @expectedExceptionMessage Operation DELETE is not available - */ - public function testOperationNotAvailableExceptionDELETE() { - $this->_gis->api_endpoint->delete(); - } - - /** - * @expectedException \GISwrapper\ActiveRoleRequiredException - */ - public function testStatusActiveRoleRequired() { - $this->_gis->status->activeRole->get(); - } - - /** - * @expectedException \GISwrapper\UnauthorizedException - */ - public function testStatusUnauthorized() { - $this->_gis->status->unauthorized->get(); - } - - /** - * @expectedException \GISwrapper\InvalidAPIResponseException - * @expectedExceptionMessage Server Error - */ - public function testInvalidResponse() { - $this->_gis->status->invalid->get(); - } - - public function tearDown() { - foreach($this->_files as $file) { - unlink($file); - } - } -} \ No newline at end of file diff --git a/tests/AuthProviderTest.php b/tests/AuthProviderTest.php deleted file mode 100644 index 04522d9..0000000 --- a/tests/AuthProviderTest.php +++ /dev/null @@ -1,539 +0,0 @@ - - * @version 0.2 - */ -class AuthProviderTest extends PHPUnit_Framework_TestCase -{ - - /** - * @expectedException \GISwrapper\InvalidAuthProviderException - */ - public function testInvalidAuthProviderException() { - $gis = new \GISwrapper\GIS(new StdClass()); - } - - /** - * @expectedException \GISwrapper\InvalidCredentialsException - */ - public function testInvalidCredentialsExceptionCombined() { - $user = new \GISwrapper\AuthProviderCombined(EXPA_USER, md5(microtime())); - $user->getToken(); - } - - /** - * @expectedException \GISwrapper\InvalidCredentialsException - */ - public function testInvalidCredentialsExceptionEXPA() { - $user = new \GISwrapper\AuthProviderEXPA(EXPA_USER, md5(microtime())); - $user->getToken(); - } - - /** - * @expectedException \GISwrapper\InvalidCredentialsException - */ - public function testInvalidCredentialsExceptionOP() { - $user = new \GISwrapper\AuthProviderOP(OP_USER, md5(microtime())); - $user->getToken(); - } - - /** - * @covers \GISwrapper\AuthProviderEXPA::__construct - * @covers \GISwrapper\AuthProviderEXPA::getToken - * @covers \GISwrapper\AuthProviderEXPA::getNewToken - * @covers \GISwrapper\AuthProviderEXPA::getExpiresAt - * @covers \GISwrapper\AuthProviderEXPA::generateNewToken - */ - public function testAuthProviderEXPA() { - $user = new \GISwrapper\AuthProviderEXPA(EXPA_USER, EXPA_PW); - $token = $user->getToken(); - $expires = $user->getExpiresAt(); - - // check token - $this->assertStringMatchesFormat('%x', $token, "First token doesn't match the format"); - - // check expiration timestamp - $this->assertNotNull($expires, "Expiration date for first token is null"); - $this->assertTrue(is_int($expires), "First token expiration date is not a timestamp"); - $this->assertGreaterThan(3540, $expires - time(), "First token expires too early"); - - // sleep 2 seconds for expiration date - sleep(2); - - // generate new token - $token2 = $user->getNewToken(); - - // check token - $this->assertStringMatchesFormat('%x', $token2, "Second token doesn't match the format"); - $this->assertNotEquals($token, $token2, "Both tokens are the same"); - - // check timestamp - $this->assertNotNull($user->getExpiresAt(), "Expiration date for second token is null"); - $this->assertTrue(is_int($user->getExpiresAt()), "Second token expiration date is not a timestamp"); - $this->assertGreaterThan($expires, $user->getExpiresAt(), "Both tokens have the same expiration date"); - - // check that new token was saved - $token = $user->getToken(); - $this->assertEquals($token, $token2, "New token wasn't saved"); - } - - /** - * @covers \GISwrapper\AuthProviderOP::__construct - * @covers \GISwrapper\AuthProviderOP::getToken - * @covers \GISwrapper\AuthProviderOP::getNewToken - * @covers \GISwrapper\AuthProviderOP::getExpiresAt - * @covers \GISwrapper\AuthProviderOP::generateNewToken - * @covers \GISwrapper\AuthProviderOP::proceedToken - */ - public function testAuthProviderOP() { - $user = new \GISwrapper\AuthProviderOP(OP_USER, OP_PW); - $token = $user->getToken(); - $expires = $user->getExpiresAt(); - - // check token - $this->assertStringMatchesFormat('%x', $token, "First token doesn't match the format"); - - // check expiration timestamp - $this->assertNotNull($expires, "Expiration date for first token is null"); - $this->assertTrue(is_int($expires), "First token expiration date is not a timestamp"); - $this->assertGreaterThan(3540, $expires - time(), "First token expires too early"); - - // sleep 2 seconds for expiration date - sleep(2); - - // generate new token - $token2 = $user->getNewToken(); - - // check token - $this->assertStringMatchesFormat('%x', $token2, "Second token doesn't match the format"); - $this->assertNotEquals($token, $token2, "Both tokens are the same"); - - // check timestamp - $this->assertNotNull($user->getExpiresAt(), "Expiration date for second token is null"); - $this->assertTrue(is_int($user->getExpiresAt()), "Second token expiration date is not a timestamp"); - $this->assertGreaterThan($expires, $user->getExpiresAt(), "Both tokens have the same expiration date"); - - // check that new token was saved - $token = $user->getToken(); - $this->assertEquals($token, $token2, "New token wasn't saved"); - } - - /** - * @covers \GISwrapper\AuthProviderCombined::__construct - * @covers \GISwrapper\AuthProviderCombined::getToken - * @covers \GISwrapper\AuthProviderCombined::getNewToken - * @covers \GISwrapper\AuthProviderCombined::getExpiresAt - * @covers \GISwrapper\AuthProviderCombined::generateNewToken - * @covers \GISwrapper\AuthProviderCombined::isEXPA - * @covers \GISwrapper\AuthProviderCombined::isOP - * @covers \GISwrapper\AuthProviderCombined::getType - * @covers \GISwrapper\AuthProviderCombined::getCurrentPerson - */ - public function testAuthProviderCombinedEXPA() { - $user = new \GISwrapper\AuthProviderCombined(EXPA_USER, EXPA_PW); - $token = $user->getToken(); - $expires = $user->getExpiresAt(); - - // check token - $this->assertStringMatchesFormat('%x', $token, "First token doesn't match the format"); - - // check expiration timestamp - $this->assertNotNull($expires, "Expiration date for first token is null"); - $this->assertTrue(is_int($expires), "First token expiration date is not a timestamp"); - $this->assertGreaterThan(3540, $expires - time(), "First token expires too early"); - - // check type - $this->assertTrue($user->isEXPA(), "isEXPA() didn't returned true for EXPA User"); - $this->assertFalse($user->isOP(), "isOP() didn't returned false for EXPA User"); - $this->assertEquals('EXPA', $user->getType(), "getType() didn't returned EXPA"); - - // sleep 2 seconds for expiration date - sleep(2); - - // generate new token - $token2 = $user->getNewToken(); - - // check token - $this->assertStringMatchesFormat('%x', $token2, "Second token doesn't match the format"); - $this->assertNotEquals($token, $token2, "Both tokens are the same"); - - // check timestamp - $this->assertNotNull($user->getExpiresAt(), "Expiration date for second token is null"); - $this->assertTrue(is_int($user->getExpiresAt()), "Second token expiration date is not a timestamp"); - $this->assertGreaterThan($expires, $user->getExpiresAt(), "Both tokens have the same expiration date"); - - // check type - $this->assertTrue($user->isEXPA(), "isEXPA() didn't returned true for EXPA User"); - $this->assertFalse($user->isOP(), "isOP() didn't returned false for EXPA User"); - $this->assertEquals('EXPA', $user->getType(), "getType() didn't returned EXPA"); - - // check that new token was saved - $token = $user->getToken(); - $this->assertEquals($token, $token2, "New token wasn't saved"); - - // check current Person - $this->assertObjectHasAttribute('person', $user->getCurrentPerson()); - $this->assertTrue(is_int($user->getCurrentPerson()->person->id)); - $this->assertNotCount(0, $user->getCurrentPerson()->current_positions); - } - - /** - * @covers \GISwrapper\AuthProviderCombined::__construct - * @covers \GISwrapper\AuthProviderCombined::getToken - * @covers \GISwrapper\AuthProviderCombined::getNewToken - * @covers \GISwrapper\AuthProviderCombined::getExpiresAt - * @covers \GISwrapper\AuthProviderCombined::generateNewToken - * @covers \GISwrapper\AuthProviderCombined::isEXPA - * @covers \GISwrapper\AuthProviderCombined::isOP - * @covers \GISwrapper\AuthProviderCombined::getType - * @covers \GISwrapper\AuthProviderCombined::getCurrentPerson - */ - public function testAuthProviderCombinedOP() { - $user = new \GISwrapper\AuthProviderCombined(OP_USER, OP_PW); - $token = $user->getToken(); - $expires = $user->getExpiresAt(); - - // check token - $this->assertStringMatchesFormat('%x', $token, "First token doesn't match the format"); - - // check expiration timestamp - $this->assertNotNull($expires, "Expiration date for first token is null"); - $this->assertTrue(is_int($expires), "First token expiration date is not a timestamp"); - $this->assertGreaterThan(3540, $expires - time(), "First token expires too early"); - - // check type - $this->assertFalse($user->isEXPA(), "isEXPA() didn't returned false for OP User"); - $this->assertTrue($user->isOP(), "isOP() didn't returned true for OP User"); - $this->assertEquals('OP', $user->getType(), "getType() didn't returned OP"); - - // sleep 2 seconds for expiration date - sleep(2); - - // generate new token - $token2 = $user->getNewToken(); - - // check token - $this->assertStringMatchesFormat('%x', $token2, "Second token doesn't match the format"); - $this->assertNotEquals($token, $token2, "Both tokens are the same"); - - // check timestamp - $this->assertNotNull($user->getExpiresAt(), "Expiration date for second token is null"); - $this->assertTrue(is_int($user->getExpiresAt()), "Second token expiration date is not a timestamp"); - $this->assertGreaterThan($expires, $user->getExpiresAt(), "Both tokens have the same expiration date"); - - // check type - $this->assertFalse($user->isEXPA(), "isEXPA() didn't returned false for OP User"); - $this->assertTrue($user->isOP(), "isOP() didn't returned true for OP User"); - $this->assertEquals('OP', $user->getType(), "getType() didn't returned OP"); - - // check that new token was saved - $token = $user->getToken(); - $this->assertEquals($token, $token2, "New token wasn't saved"); - - // check current Person - $this->assertObjectHasAttribute('person', $user->getCurrentPerson()); - $this->assertTrue(is_int($user->getCurrentPerson()->person->id)); - $this->assertCount(0, $user->getCurrentPerson()->current_positions); - } - - /** - * @covers \GISwrapper\AuthProviderEXPA::__construct - * @covers \GISwrapper\AuthProviderEXPA::getToken - * @covers \GISwrapper\AuthProviderEXPA::getExpiresAt - * @covers \GISwrapper\AuthProviderEXPA::generateNewToken - * @covers \GISwrapper\AuthProviderEXPA::getSession - * @covers \GISwrapper\AuthProviderEXPA::setSession - */ - public function testAuthProviderEXPAsession() { - $session = './' . md5(microtime) . '.session'; - - $user = new \GISwrapper\AuthProviderEXPA(EXPA_USER, EXPA_PW); - $user->setSession($session); - $token = $user->getToken(); - $expires = $user->getExpiresAt(); - - // check token - $this->assertStringMatchesFormat('%x', $token, "First token does not match format"); - - // check getSession - $this->assertEquals($session, $user->getSession(), "Session file path wasn't saved correctly"); - - // check that session file exists - $this->assertTrue(file_exists($session), "Session file does not exist"); - - // sleep 2 seconds for expiration date - sleep(2); - - // reuse session - $user2 = new \GISwrapper\AuthProviderEXPA($session); - $token2 = $user2->getToken(); - - // check token - $this->assertStringMatchesFormat('%x', $token2, "Second token does not match format"); - $this->assertNotEquals($token, $token2, "Second token is not different from first one"); - - // check expiration date - $this->assertGreaterThan($expires, $user2->getExpiresAt(), "Both tokens have the same expiration date"); - - // delete session - unlink($session); - } - - /** - * @covers \GISwrapper\AuthProviderOP::__construct - * @covers \GISwrapper\AuthProviderOP::getToken - * @covers \GISwrapper\AuthProviderOP::getExpiresAt - * @covers \GISwrapper\AuthProviderOP::generateNewToken - * @covers \GISwrapper\AuthProviderOP::proceedToken - * @covers \GISwrapper\AuthProviderOP::getSession - * @covers \GISwrapper\AuthProviderOP::setSession - */ - public function testAuthProviderOPsession() { - $session = './' . md5(microtime) . '.session'; - - $user = new \GISwrapper\AuthProviderOP(EXPA_USER, EXPA_PW); - $user->setSession($session); - $token = $user->getToken(); - $expires = $user->getExpiresAt(); - - // check token - $this->assertStringMatchesFormat('%x', $token, "First token does not match format"); - - // check getSession - $this->assertEquals($session, $user->getSession(), "Session file path wasn't saved correctly"); - - // check that session file exists - $this->assertTrue(file_exists($session), "Session file does not exist"); - - // sleep 2 seconds for expiration date - sleep(2); - - // reuse session - $user2 = new \GISwrapper\AuthProviderOP($session); - $token2 = $user2->getToken(); - - // check token - $this->assertStringMatchesFormat('%x', $token2, "Second token does not match format"); - $this->assertNotEquals($token, $token2, "Second token is not different from first one"); - - // check expiration date - $this->assertGreaterThan($expires, $user2->getExpiresAt(), "Both tokens have the same expiration date"); - - // delete session - unlink($session); - } - - /** - * @covers \GISwrapper\AuthProviderCombined::__construct - * @covers \GISwrapper\AuthProviderCombined::getToken - * @covers \GISwrapper\AuthProviderCombined::getExpiresAt - * @covers \GISwrapper\AuthProviderCombined::generateNewToken - * @covers \GISwrapper\AuthProviderCombined::getSession - * @covers \GISwrapper\AuthProviderCombined::setSession - * @covers \GISwrapper\AuthProviderCombined::isOP - */ - public function testAuthProviderCombinedOPsession() { - $session = './' . md5(microtime) . '.session'; - - $user = new \GISwrapper\AuthProviderCombined(OP_USER, OP_PW); - $user->setSession($session); - $token = $user->getToken(); - $expires = $user->getExpiresAt(); - - // check token - $this->assertStringMatchesFormat('%x', $token, "First token does not match format"); - - // check getSession - $this->assertEquals($session, $user->getSession(), "Session file path wasn't saved correctly"); - - // check that session file exists - $this->assertTrue(file_exists($session), "Session file does not exist"); - - // sleep 2 seconds for expiration date - sleep(2); - - // reuse session - $user2 = new \GISwrapper\AuthProviderCombined($session); - $token2 = $user2->getToken(); - - // check token - $this->assertStringMatchesFormat('%x', $token2, "Second token does not match format"); - $this->assertNotEquals($token, $token2, "Second token is not different from first one"); - - // check type - $this->assertTrue($user2->isOP(), "Token is not a OP token"); - - // check expiration date - $this->assertGreaterThan($expires, $user2->getExpiresAt(), "Both tokens have the same expiration date"); - - // delete session - unlink($session); - } - - /** - * @covers \GISwrapper\AuthProviderCombined::__construct - * @covers \GISwrapper\AuthProviderCombined::getToken - * @covers \GISwrapper\AuthProviderCombined::getExpiresAt - * @covers \GISwrapper\AuthProviderCombined::generateNewToken - * @covers \GISwrapper\AuthProviderCombined::getSession - * @covers \GISwrapper\AuthProviderCombined::setSession - * @covers \GISwrapper\AuthProviderCombined::isEXPA - */ - public function testAuthProviderCombinedEXPAsession() { - $session = './' . md5(microtime) . '.session'; - - $user = new \GISwrapper\AuthProviderCombined(EXPA_USER, EXPA_PW); - $user->setSession($session); - $token = $user->getToken(); - $expires = $user->getExpiresAt(); - - // check token - $this->assertStringMatchesFormat('%x', $token, "First token does not match format"); - - // check getSession - $this->assertEquals($session, $user->getSession(), "Session file path wasn't saved correctly"); - - // check that session file exists - $this->assertTrue(file_exists($session), "Session file does not exist"); - - // sleep 2 seconds for expiration date - sleep(2); - - // reuse session - $user2 = new \GISwrapper\AuthProviderCombined($session); - $token2 = $user2->getToken(); - - // check token - $this->assertStringMatchesFormat('%x', $token2, "Second token does not match format"); - $this->assertNotEquals($token, $token2, "Second token is not different from first one"); - - // check type - $this->assertTrue($user2->isEXPA(), "Token is not a EXPA token"); - - // check expiration date - $this->assertGreaterThan($expires, $user2->getExpiresAt(), "Both tokens have the same expiration date"); - - // delete session - unlink($session); - } - - /** - * @covers \GISwrapper\AuthProviderEXPA::__construct - * @covers \GISwrapper\AuthProviderEXPA::getToken - * @covers \GISwrapper\AuthProviderEXPA::generateNewToken - * @covers \GISwrapper\AuthProviderEXPA::setSession - */ - public function testAuthProviderEXPAinvalidSession() { - // create session file - $session = './' . md5(microtime) . '.session'; - file_put_contents($session, "..."); - - $user = new \GISwrapper\AuthProviderEXPA(EXPA_USER, EXPA_PW); - $user->setSession($session); - $token = $user->getToken(); - - $this->assertStringMatchesFormat('%x', $token, "Token doesn't match format"); - - unlink($session); - } - - /** - * @covers \GISwrapper\AuthProviderOP::__construct - * @covers \GISwrapper\AuthProviderOP::getToken - * @covers \GISwrapper\AuthProviderOP::generateNewToken - * @covers \GISwrapper\AuthProviderOP::proceedToken - * @covers \GISwrapper\AuthProviderOP::setSession - */ - public function testAuthProviderOPinvalidSession() { - // create session file - $session = './' . md5(microtime) . '.session'; - file_put_contents($session, "..."); - - $user = new \GISwrapper\AuthProviderOP(OP_USER, OP_PW); - $user->setSession($session); - $token = $user->getToken(); - - $this->assertStringMatchesFormat('%x', $token, "Token doesn't match format"); - - unlink($session); - } - - /** - * @covers \GISwrapper\AuthProviderCombined::__construct - * @covers \GISwrapper\AuthProviderCombined::getToken - * @covers \GISwrapper\AuthProviderCombined::generateNewToken - * @covers \GISwrapper\AuthProviderCombined::setSession - * @covers \GISwrapper\AuthProviderCombined::isEXPA - */ - public function testAuthProviderCombinedEXPAinvalidSession() { - // create session file - $session = './' . md5(microtime) . '.session'; - file_put_contents($session, "..."); - - $user = new \GISwrapper\AuthProviderCombined(EXPA_USER, EXPA_PW); - $user->setSession($session); - $token = $user->getToken(); - - $this->assertStringMatchesFormat('%x', $token, "Token doesn't match format"); - $this->assertTrue($user->isEXPA(), "token is not an EXPA token"); - - unlink($session); - } - - /** - * @covers \GISwrapper\AuthProviderCombined::__construct - * @covers \GISwrapper\AuthProviderCombined::getToken - * @covers \GISwrapper\AuthProviderCombined::generateNewToken - * @covers \GISwrapper\AuthProviderCombined::setSession - * @covers \GISwrapper\AuthProviderCombined::isOP - */ - public function testAuthProviderCombinedOPinvalidSession() { - // create session file - $session = './' . md5(microtime) . '.session'; - file_put_contents($session, "..."); - - $user = new \GISwrapper\AuthProviderCombined(OP_USER, OP_PW); - $user->setSession($session); - $token = $user->getToken(); - - $this->assertStringMatchesFormat('%x', $token, "Token doesn't match format"); - $this->assertTrue($user->isOP(), "token is not an OP token"); - - unlink($session); - } - - /** - * @covers \GISwrapper\AuthProviderShadow::__construct - * @covers \GISwrapper\AuthProviderShadow::getToken - * @covers \GISwrapper\AuthProviderShadow::getNewToken - * @covers \GISwrapper\AuthProviderShadow::getAuthProvider - */ - public function testAuthProviderShadow() { - $sub = new \GISwrapper\AuthProviderEXPA(EXPA_USER, EXPA_PW); - $user = new \GISwrapper\AuthProviderShadow("sometoken", $sub); - $this->assertEquals("sometoken", $user->getToken()); - - $token = $user->getNewToken(); - $this->assertNotEquals("sometoken", $token); - $this->assertStringMatchesFormat('%x', $token, "Token doesn't match format"); - - $this->assertEquals($sub, $user->getAuthProvider()); - } - - /** - * @expectedException \GISwrapper\InvalidCredentialsException - * @expectedExceptionMessage Could not get token from sub auth provider - */ - public function testAuthProviderShadowException() { - $user = new \GISwrapper\AuthProviderShadow("sometoken"); - $user->getNewToken(); - } -} \ No newline at end of file diff --git a/tests/OnlineTest.php b/tests/OnlineTest.php deleted file mode 100644 index 999e234..0000000 --- a/tests/OnlineTest.php +++ /dev/null @@ -1,109 +0,0 @@ -_user = new \GISwrapper\AuthProviderEXPA(EXPA_USER, EXPA_PW); - $this->_gis = new \GISwrapper\GIS($this->_user); - } - - public function testGetUid() { - $uid = $this->_gis->current_person->get()->person->id; - $this->assertNotNull($uid); - - return $uid; - } - - public function testOpportunityCreate() { - $title = "Opportunity to test PHP-GIS-Wrapper"; - $pid = 1; - - $this->_gis->opportunities = ['opportunity' => ['title' => $title, 'programme_id' => $pid]]; - $this->assertEquals($title, $this->_gis->opportunities->opportunity->title); - - unset($this->_gis->opportunities); - $this->_gis->opportunities->opportunity = ['title' => $title, 'programme_id' => $pid]; - $this->assertEquals($title, $this->_gis->opportunities->opportunity->title); - - unset($this->_gis->opportunities); - $this->_gis->opportunities->opportunity->title = $title; - $this->_gis->opportunities->opportunity->programme_id = $pid; - $this->_gis->opportunities->opportunity->branch_id = "325363"; - $this->_gis->opportunities->opportunity->host_lc_id = "257"; - $this->assertEquals($title, $this->_gis->opportunities->opportunity->title); - - $res = $this->_gis->opportunities->create(); - $this->assertEquals($title, $res->title); - - return $res->id; - } - - /** - * @depends testGetUid - * @depends testOpportunityCreate - */ - public function testAddManager($uid, $oid) { - $this->_gis->opportunities[$oid]->opportunity->manager_ids[] = $uid; - $this->assertNotNull($this->_gis->opportunities[$oid]->opportunity->manager_ids[0]); - $this->_gis->opportunities[$oid]->update(); - - $this->assertEquals($uid, $this->_gis->opportunities[$oid]->get()->managers[0]->id); - - return $oid; - } - - /** - * @depends testAddManager - */ - public function testDelete($oid) { - $this->_gis->opportunities[$oid]->delete(); - $this->assertFalse($this->_gis->opportunities->existsDynamicSub($oid)); - } - - public function testGetRequestWithParams() { - $this->_gis->opportunities = [ - 'filters' => [ - 'languages' => [ - [ - 'id' => 24, - 'option' => 'required' - ], - ], - 'programmes' => [1, 2] - ] - ]; - - $this->assertEquals(24, $this->_gis->opportunities->filters->languages[0]->id); - $this->assertEquals('required', $this->_gis->opportunities->filters->languages[0]->option); - $this->assertEquals(1, $this->_gis->opportunities->filters->programmes[0]); - $this->assertEquals(2, $this->_gis->opportunities->filters->programmes[1]); - - $i = 0; - foreach($this->_gis->opportunities as $o) { - // limit to 10 opportunities - if($i >= 10) break; - $i++; - - // check that programme filter works - $this->assertTrue(in_array($o->programmes->id, [1, 2])); - - // get full opportunity to check for language - $o = $this->_gis->opportunities[$o->id]->get(); - $languages = array(); - foreach($o->languages as $l) { - $languages[$l->id] = $l->option; - } - $this->assertArrayHasKey(24, $languages); - - // unset opportunity - unset($this->_gis->opportunities[$o->id]); - } - } -} \ No newline at end of file diff --git a/tests/ParamsTest.php b/tests/ParamsTest.php deleted file mode 100644 index 32ab5f0..0000000 --- a/tests/ParamsTest.php +++ /dev/null @@ -1,363 +0,0 @@ -_cache = [ - 'endpoint' => [ - 'summary' => '', - 'path' => '', - 'endpoint' => true, - 'dynamic' => false, - 'dynamicSub' => false, - 'subs' => [], - 'params' => [ - 'arrayStrict' => [ - 'subparams' => [], - 'operations' => [ - 'GET' => [ - 'type' => 'Array', - 'required' => true - ] - ] - ], - 'arrayStrictUnrequired' => [ - 'subparams' => [], - 'operations' => [ - 'GET' => [ - 'type' => 'Array', - 'required' => false - ] - ] - ], - 'arrayStrictSub' => [ - 'subparams' => [ - 'param_1' => [ - 'subparams' => [], - 'operations' => [ - 'GET' => [ - 'type' => 'String', - 'required' => true - ] - ] - ], - 'param_2' => [ - 'subparams' => [], - 'operations' => [ - 'GET' => [ - 'type' => 'String', - 'required' => false - ] - ] - ] - ], - 'operations' => [ - 'GET' => [ - 'type' => 'Array', - 'required' => false - ] - ] - ], - 'mixed' => [ - 'subparams' => [], - 'operations' => [ - 'POST' => [ - 'type' => 'Integer', - 'required' => true - ], - 'GET' => [ - 'type' => 'Array', - 'required' => true - ] - ] - ], - 'string' => [ - 'subparams' => [], - 'operations' => [ - 'GET' => [ - 'type' => 'String', - 'required' => false - ] - ] - ] - ], - 'paged' => false, - 'operations' => ['GET'] - ], - 'magic' => [ - 'summary' => '', - 'path' => '', - 'endpoint' => true, - 'dynamic' => false, - 'dynamicSub' => false, - 'subs' => [], - 'params' => [ - 'sub' => [ - 'subparams' => [ - 'a' => [ - 'subparams' => [], - 'operations' => [ - 'GET' => [ - 'type' => 'Integer', - 'required' => false - ] - ] - ], - 'b' => [ - 'subparams' => [], - 'operations' => [ - 'GET' => [ - 'type' => 'String', - 'required' => false - ] - ] - ] - ], - 'operations' => [ - 'GET' => [ - 'type' => 'Hash', - 'required' => false - ] - ] - ], - 'array' => [ - 'subparams' => [ - 'sub' => [ - 'subparams' => [], - 'operations' => [ - 'GET' => [ - 'type' => 'String', - 'required' => false - ] - ] - ] - ], - 'operations' => [ - 'GET' => [ - 'type' => 'Array', - 'required' => false - ] - ] - ] - ], - 'paged' => false, - 'operations' => ['GET'] - ], - 'validation' => [ - 'summary' => '', - 'path' => '', - 'endpoint' => true, - 'dynamic' => false, - 'dynamicSub' => false, - 'subs' => [], - 'params' => [ - 'int' => [ - 'subparams' => [], - 'operations' => [ - 'GET' => [ - 'type' => 'Integer', - 'required' => true - ] - ] - ], - 'string' => [ - 'subparams' => [], - 'operations' => [ - 'GET' => [ - 'type' => 'String', - 'required' => true - ] - ] - ], - 'date' => [ - 'subparams' => [], - 'operations' => [ - 'GET' => [ - 'type' => 'Date', - 'required' => true - ] - ] - ], - 'bool' => [ - 'subparams' => [], - 'operations' => [ - 'GET' => [ - 'type' => 'Virtus::Attribute::Boolean', - 'required' => false - ] - ] - ], - ], - 'paged' => false, - 'operations' => ['GET', 'POST'] - ] - ]; - $this->_user = new \GISwrapper\AuthProviderEXPA(EXPA_USER, EXPA_PW); - $this->_gis = new \GISwrapper\GIS($this->_user, $this->_cache); - } - - public function testKeys() - { - $this->assertNotNull($this->_gis->endpoint->arrayStrict); - $this->assertNotNull($this->_gis->endpoint->arrayStrictSub); - $this->assertNotNull($this->_gis->endpoint->arrayStrictSub[0]); - $this->assertNotNull($this->_gis->endpoint->mixed); - $this->assertNull($this->_gis->endpoint->string); - } - - public function testInstances() { - $this->assertInstanceOf('\GISwrapper\ParameterArrayType', $this->_gis->endpoint->arrayStrict); - $this->assertInstanceOf('\GISwrapper\ParameterArrayType', $this->_gis->endpoint->arrayStrictSub); - $this->assertInstanceOf('\GISwrapper\ParameterArrayType', $this->_gis->endpoint->mixed); - } - - public function testArrayStrict() { - $this->_gis->endpoint->arrayStrict[] = 13; - $this->_gis->endpoint->arrayStrict[] = 14; - $this->_gis->endpoint->arrayStrict[2] = 15; - - $this->assertEquals(13, $this->_gis->endpoint->arrayStrict[0]); - $this->assertEquals(14, $this->_gis->endpoint->arrayStrict[1]); - $this->assertEquals(15, $this->_gis->endpoint->arrayStrict[2]); - - foreach($this->_gis->endpoint->arrayStrict as $key => $val) { - $this->assertGreaterThan(12, $val); - $this->_gis->endpoint->arrayStrict[$key] = 12; - } - - $this->assertEquals(12, $this->_gis->endpoint->arrayStrict[0]); - $this->assertEquals(12, $this->_gis->endpoint->arrayStrict[1]); - $this->assertEquals(12, $this->_gis->endpoint->arrayStrict[2]); - } - - public function testArrayStrictError() { - // needs to be implemented - } - - public function testArrayStrictSub() { - $this->assertInstanceOf('\GISwrapper\ParameterDefaultType', $this->_gis->endpoint->arrayStrictSub[0]); - $this->assertInstanceOf('\GISwrapper\ParameterDefaultType', $this->_gis->endpoint->arrayStrictSub[1]); - $this->assertInstanceOf('\GISwrapper\ParameterDefaultType', $this->_gis->endpoint->arrayStrictSub[2]); - - foreach($this->_gis->endpoint->arrayStrictSub as $key => $el) { - $this->assertNull($el->param_1); - $this->assertNull($el->param_2); - $this->_gis->endpoint->arrayStrictSub[$key]->param_1 = "Test Param 1"; - $this->_gis->endpoint->arrayStrictSub[$key]->param_2 = "Test Param 2"; - } - - $this->assertCount(3, $this->_gis->endpoint->arrayStrictSub); - $this->assertTrue(isset($this->_gis->endpoint->arrayStrictSub[1])); - - foreach($this->_gis->endpoint->arrayStrictSub as $el) { - $this->assertEquals("Test Param 1", $el->param_1); - $this->assertEquals("Test Param 2", $el->param_2); - } - - unset($this->_gis->endpoint->arrayStrictSub[1]); - - $this->assertFalse(isset($this->_gis->endpoint->arrayStrictSub[1])); - } - - public function testArrayStrictSubError() { - // need to be implemented - } - - public function testArrayValidation() { - $this->assertFalse($this->_gis->endpoint->valid('GET')); - $this->assertFalse($this->_gis->endpoint->arrayStrict->valid('GET')); - - $this->_gis->endpoint->arrayStrict = [0, 1, 2]; - - $this->assertTrue($this->_gis->endpoint->arrayStrict->valid('GET')); - - $this->_gis->endpoint->arrayStrict = []; - - $this->assertFalse($this->_gis->endpoint->arrayStrict->valid('GET')); - $this->assertTrue($this->_gis->endpoint->arrayStrictUnrequired->valid('GET')); - } - - public function testMixed() { - $this->assertFalse($this->_gis->endpoint->mixed->valid('GET')); - $this->assertFalse($this->_gis->endpoint->mixed->valid('POST')); - - $this->_gis->endpoint->mixed = 12; - - $this->assertFalse($this->_gis->endpoint->mixed->valid('GET')); - $this->assertTrue($this->_gis->endpoint->mixed->valid('POST')); - - $this->_gis->endpoint->mixed = [1, 2, 3]; - - $this->assertTrue($this->_gis->endpoint->mixed->valid('GET')); - $this->assertTrue($this->_gis->endpoint->mixed->valid('POST')); - - $this->_gis->endpoint->mixed = 13; - - $this->assertTrue($this->_gis->endpoint->mixed->valid('GET')); - $this->assertTrue($this->_gis->endpoint->mixed->valid('POST')); - } - - public function testString() { - $this->_gis->endpoint->arrayStrict = [1, 2, 3]; - $this->_gis->endpoint->mixed = [1, 2, 3]; - - $this->assertTrue($this->_gis->endpoint->valid('GET')); - - $this->_gis->endpoint->string = 12; - - $this->assertFalse($this->_gis->endpoint->valid('GET')); - - $this->_gis->endpoint->string = "12"; - - $this->assertTrue($this->_gis->endpoint->valid('GET')); - } - - public function testTypeValidation() { - // int string date bool - $this->assertFalse($this->_gis->validation->valid('GET')); - - $this->assertTrue($this->_gis->validation->valid('POST')); - - $this->_gis->validation->int = 0.00; - $this->_gis->validation->string = 0.00; - $this->_gis->validation->date = 0.00; - $this->_gis->validation->bool = 0.00; - - $this->assertFalse($this->_gis->validation->valid('GET')); - - $this->_gis->validation->int = 10; - $this->_gis->validation->string = "10"; - date_default_timezone_set('Europe/Berlin'); - $this->_gis->validation->date = new DateTime(); - $this->_gis->validation->bool = true; - - $this->assertTrue($this->_gis->validation->valid('GET')); - } - - public function testMagicFunctions() { - $this->assertTrue(($this->_gis->magic->array == "ArrayParameter")); - - $this->assertTrue($this->_gis->magic->sub->exists('a')); - $this->assertFalse($this->_gis->magic->sub->exists('c')); - - $this->assertFalse(isset($this->_gis->magic->sub->a)); - $this->_gis->magic->sub->a = 10; - $this->assertTrue(isset($this->_gis->magic->sub->a)); - $this->assertTrue(($this->_gis->magic->sub->a == "10")); - - unset($this->_gis->magic->sub->a); - $this->assertFalse(isset($this->_gis->magic->sub->a)); - - $this->_gis->magic->sub = ['a' => 10, 'b' => "20"]; - $this->assertEquals(10, $this->_gis->magic->sub->a); - $this->assertEquals("20", $this->_gis->magic->sub->b); - } -} \ No newline at end of file diff --git a/tests/SwaggerParserTest.php b/tests/SwaggerParserTest.php deleted file mode 100644 index efa7d06..0000000 --- a/tests/SwaggerParserTest.php +++ /dev/null @@ -1,104 +0,0 @@ - - * @version 0.2 - */ -class SwaggerParserTest extends PHPUnit_Framework_TestCase -{ - private $_simpleCache; - private $_fullCache; - - public function setUp() { - $this->_simpleCache = \GISwrapper\GIS::generateSimpleCache(__DIR__ . '/assets/shortened/docs.json'); - $this->_fullCache = \GISwrapper\GIS::generateFullCache(__DIR__ . '/assets/shortened/docs.json'); - } - - public function testSimpleCache() { - $this->assertCount(2, $this->_simpleCache, "Too many endpoints"); - $this->assertArraySubset(['applications' => './tests/assets/shortened/applications.json'], $this->_simpleCache); - $this->assertArraySubset(['organisations' => './tests/assets/shortened/organisations.json'], $this->_simpleCache); - } - - public function testFullCacheEndpoints() { - // check that the right endpoints exist - $this->assertCount(2, $this->_fullCache, "Too many endpoints"); - $this->assertArrayHasKey('applications', $this->_fullCache, "Endpoint applications missing"); - $this->assertArrayHasKey('organisations', $this->_fullCache, "Endpoint organisations missing"); - } - - public function testFullCacheApplicationsEndpoint() { - $this->checkEndpointKeys($this->_fullCache['applications']); - $this->assertEquals('', $this->_fullCache['applications']['summary'], 'Wrong summary'); - $this->assertEquals('https://gis-api.aiesec.org/v2/applications.json', $this->_fullCache['applications']['path'], 'wrong path'); - $this->assertTrue($this->_fullCache['applications']['endpoint'], "parameter endpoint not true"); - $this->assertFalse($this->_fullCache['applications']['dynamic'], "parameter dynamic not false"); - $this->assertFalse($this->_fullCache['applications']['dynamicSub'], "parameter dynamicSub not false"); - $this->assertTrue($this->_fullCache['applications']['paged'], "parameter paged not true"); - $this->assertArraySubset(['operations' => ['POST', 'GET']], $this->_fullCache['applications']); - } - - public function testFullCacheApplicationsSubs() { - $this->assertArrayHasKey('batch', $this->_fullCache['applications']['subs'], "Sub endpoint batch missing"); - $this->assertCount(1, $this->_fullCache['applications']['subs'], "too many subs"); - $this->checkEndpointKeys($this->_fullCache['applications']['subs']['batch'], "Sub endpoint batch invalid"); - } - - public function testFullCacheApplicationsParams() { - $this->checkArrayKeys(['application', 'filters'], $this->_fullCache['applications']['params']); - $this->assertCount(2, $this->_fullCache['applications']['params'], "Too many parameters"); - - $this->checkParamKeys($this->_fullCache['applications']['params']['application']); - $this->checkParamKeys($this->_fullCache['applications']['params']['filters']); - - // check some required settings - $this->assertTrue($this->_fullCache['applications']['params']['application']['operations']['POST']['required'], "application parameter required not true"); - $this->assertTrue($this->_fullCache['applications']['params']['application']['subparams']['opportunity_id']['operations']['POST']['required'], "opportunity_id required parameter not true"); - $this->assertFalse($this->_fullCache['applications']['params']['application']['subparams']['person_id']['operations']['POST']['required'], "person_id required parameter not false"); - } - - public function testFullCacheOrganisationsEndpoint() { - $this->checkEndpointKeys($this->_fullCache['organisations']); - $this->assertEquals('', $this->_fullCache['organisations']['summary'], 'Wrong summary'); - $this->assertEquals('https://gis-api.aiesec.org/v2/organisations.json', $this->_fullCache['organisations']['path'], 'wrong path'); - $this->assertTrue($this->_fullCache['organisations']['endpoint'], "parameter endpoint not true"); - $this->assertFalse($this->_fullCache['organisations']['dynamic'], "parameter dynamic not false"); - $this->assertTrue($this->_fullCache['organisations']['dynamicSub'], "parameter dynamicSub not true"); - $this->assertFalse($this->_fullCache['organisations']['paged'], "parameter paged not false"); - $this->assertArraySubset(['operations' => ['POST', 'GET']], $this->_fullCache['organisations']); - } - - public function testFullCacheOrganisationsSubs() { - $this->assertCount(1, $this->_fullCache['organisations']['subs'], "too many subs"); - $this->assertArrayHasKey('{organisation_id}', $this->_fullCache['organisations']['subs'], "missing {organisation_id} sub endpoint"); - - $this->checkAPIKeys($this->_fullCache['organisations']['subs']['{organisation_id}']); - $this->assertTrue($this->_fullCache['organisations']['subs']['{organisation_id}']['dynamic'], "parameter dynamic not true"); - $this->assertFalse($this->_fullCache['organisations']['subs']['{organisation_id}']['dynamicSub'], "parameter dynamicSub not false"); - } - - private function checkParamKeys($param) { - $this->checkArrayKeys(['subparams', 'operations'], $param); - } - - private function checkEndpointKeys($endpoint) { - $this->checkArrayKeys(['summary', 'path', 'endpoint', 'dynamic', 'dynamicSub', 'paged', 'operations', 'subs', 'params'], $endpoint); - } - - private function checkAPIKeys($api) { - $this->checkArrayKeys(['endpoint', 'dynamic', 'dynamicSub', 'subs'], $api); - } - - private function checkArrayKeys($keys, $haystack) { - foreach($keys as $key) { - $this->assertArrayHasKey($key, $haystack, "Missing key $key"); - } - } -} \ No newline at end of file diff --git a/tests/assets/page1.json b/tests/assets/page1.json deleted file mode 100644 index 116988c..0000000 --- a/tests/assets/page1.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "paging": { - "current_page": "1", - "total_pages": "1", - "total_items": "4" - }, - "facets": { - "statusA": "12", - "statusB": "24" - }, - "data": [ - { - "id": 1, - "name": "element one" - }, - { - "id": 2, - "name": "element two" - }, - { - "id": 3, - "name": "element three" - }, - { - "id": 4, - "name": "element four" - } - ] -} \ No newline at end of file diff --git a/tests/assets/shortened/applications.json b/tests/assets/shortened/applications.json deleted file mode 100644 index de774da..0000000 --- a/tests/assets/shortened/applications.json +++ /dev/null @@ -1 +0,0 @@ -{"apiVersion":"v2","swaggerVersion":"1.2","resourcePath":"","apis":[{"path":"/v2/applications.{format}","operations":[{"produces":["application/json"],"notes":"","summary":"Create a new application","nickname":"POST--version-applications---format-","httpMethod":"POST","parameters":[{"paramType":"form","name":"access_token","description":"Access Token with create_application rights.","type":"String","dataType":"String","required":true},{"paramType":"form","name":"application","description":null,"type":"Hash","dataType":"Hash","required":true},{"paramType":"form","name":"application[opportunity_id]","description":"Reference to an Opportunity","type":"Integer","dataType":"Integer","required":true},{"paramType":"form","name":"application[person_id]","description":"Reference to the Person creating the Opportunity (needs special permissions to use it).","type":"Integer","dataType":"Integer","required":false}]},{"produces":["application/json"],"notes":"","summary":"Returns all applications.","nickname":"GET--version-applications---format-","httpMethod":"GET","parameters":[{"paramType":"query","name":"access_token","description":"Access Token with read_all_applications rights.","type":"String","dataType":"String","required":true},{"paramType":"query","name":"page","description":"Specify page number. Return 25 results per page.","type":"Integer","dataType":"Integer","required":false},{"paramType":"query","name":"per_page","description":"Specify number of elements per page (default = 25).","type":"Integer","dataType":"Integer","required":false},{"paramType":"query","name":"filters","description":null,"type":"Hash","dataType":"Hash","required":false},{"paramType":"query","name":"filters[my]","description":"Get applications managed by a TN/EP manager.","type":"String","dataType":"String","required":false}]}]},{"path":"/v2/applications/batch.{format}","operations":[{"produces":["application/json"],"notes":"","summary":"Create new applications from an Array of info (Very restricted access).","nickname":"POST--version-applications-batch---format-","httpMethod":"POST","parameters":[]},{"produces":["application/json"],"notes":"","summary":"Delete all previously batch created Applications (Very restricted access).","nickname":"DELETE--version-applications-batch---format-","httpMethod":"DELETE","parameters":[]}]}],"basePath":"https://gis-api.aiesec.org"} \ No newline at end of file diff --git a/tests/assets/shortened/docs.json b/tests/assets/shortened/docs.json deleted file mode 100644 index 4cc05c0..0000000 --- a/tests/assets/shortened/docs.json +++ /dev/null @@ -1 +0,0 @@ -{"apiVersion":"v2","swaggerVersion":"1.2","produces":["application/json"],"operations":[],"apis":[{"path":"/applications.{format}"},{"path":"/organisations.{format}"}],"info":{},"basePath":"./tests/assets/shortened"} \ No newline at end of file diff --git a/tests/assets/shortened/organisations.json b/tests/assets/shortened/organisations.json deleted file mode 100644 index 52e5e15..0000000 --- a/tests/assets/shortened/organisations.json +++ /dev/null @@ -1 +0,0 @@ -{"apiVersion":"v2","swaggerVersion":"1.2","resourcePath":"","apis":[{"path":"/v2/organisations/{organisation_id}/branches.{format}","operations":[{"produces":["application/json"],"notes":"","summary":"Create a new branch","nickname":"POST--version-organisations--organisation_id-branches---format-","httpMethod":"POST","parameters":[]},{"produces":["application/json"],"notes":"","summary":"Return all branches of {:organisation_id}","nickname":"GET--version-organisations--organisation_id-branches---format-","httpMethod":"GET","parameters":[]},{"produces":["application/json"],"notes":"","summary":"Update {:branch_id}'s attributes","nickname":"PATCH--version-organisations--organisation_id-branches--branch_id---format-","httpMethod":"PATCH","parameters":[{"paramType":"path","name":"organisation_id","description":"","type":"String","dataType":"String","required":false},{"paramType":"path","name":"branch_id","description":"","type":"String","dataType":"String","required":false},{"paramType":"form","name":"access_token","description":"Access Token with update_branch rights.","type":"String","dataType":"String","required":true},{"paramType":"path","name":"branch","description":null,"type":"Hash","dataType":"Hash","required":true},{"paramType":"form","name":"branch[name]","description":"Branch's name.","type":"String","dataType":"String","required":false},{"paramType":"form","name":"branch[summary]","description":"Branch's punchline.","type":"String","dataType":"String","required":false},{"paramType":"form","name":"branch[description]","description":"Branch's description.","type":"String","dataType":"String","required":false},{"paramType":"form","name":"branch[home_lc_id]","description":"Branch's home LC ID.","type":"Integer","dataType":"Integer","required":false},{"paramType":"form","name":"branch[status]","description":"Branch's status.","type":"String","dataType":"String","required":false},{"paramType":"form","name":"branch[contact_info]","description":null,"type":"Hash","dataType":"Hash","required":false},{"paramType":"form","name":"branch[contact_info][phone]","description":"Phone number.","type":"String","dataType":"String","required":false},{"paramType":"form","name":"branch[contact_info][website]","description":"Website address.","type":"String","dataType":"String","required":false},{"paramType":"form","name":"branch[contact_info][facebook]","description":"Facebook username.","type":"String","dataType":"String","required":false},{"paramType":"form","name":"branch[contact_info][twitter]","description":"Twitter handle.","type":"String","dataType":"String","required":false},{"paramType":"form","name":"branch[contact_info][instagram]","description":"Instagram username.","type":"String","dataType":"String","required":false},{"paramType":"form","name":"branch[contact_info][linkedin]","description":"Linkedin page.","type":"String","dataType":"String","required":false},{"paramType":"form","name":"branch[contact_info][email]","description":"Email","type":"String","dataType":"String","required":false},{"paramType":"form","name":"branch[address_info]","description":null,"type":"Hash","dataType":"Hash","required":false},{"paramType":"form","name":"branch[address_info][address_1]","description":"Address 1.","type":"String","dataType":"String","required":false},{"paramType":"form","name":"branch[address_info][address_2]","description":"Address 2.","type":"String","dataType":"String","required":false},{"paramType":"form","name":"branch[address_info][postcode]","description":"Postcode.","type":"String","dataType":"String","required":false},{"paramType":"form","name":"branch[address_info][city]","description":"City.","type":"String","dataType":"String","required":false},{"paramType":"form","name":"branch[address_info][country]","description":"Country.","type":"String","dataType":"String","required":false},{"paramType":"form","name":"branch[address_info][lat]","description":"Latitude.","type":"Float","dataType":"Float","required":false},{"paramType":"form","name":"branch[address_info][lng]","description":"Longitude.","type":"Float","dataType":"Float","required":false},{"paramType":"form","name":"branch[contact_people]","description":null,"type":"Array","dataType":"Array","required":false},{"paramType":"form","name":"branch[contact_people][name]","description":"Name of the contact person.","type":"String","dataType":"String","required":false},{"paramType":"form","name":"branch[contact_people][email]","description":"Email of the contact person.","type":"String","dataType":"String","required":false},{"paramType":"form","name":"branch[contact_people][position]","description":"Position of the contact person.","type":"String","dataType":"String","required":false},{"paramType":"form","name":"branch[contact_people][phone]","description":"Phone of the contact person.","type":"String","dataType":"String","required":false}]},{"produces":["application/json"],"notes":"","summary":"Delete {:branch_id}","nickname":"DELETE--version-organisations--organisation_id-branches--branch_id---format-","httpMethod":"DELETE","parameters":[]}]},{"path":"/v2/organisations/{organisation_id}/employees.{format}","operations":[{"produces":["application/json"],"notes":"","summary":"View {:organisation_id}'s attributes","nickname":"GET--version-organisations--organisation_id-employees---format-","httpMethod":"GET","parameters":[]},{"produces":["application/json"],"notes":"","summary":"Invite a user to become an employee of the organisation","nickname":"POST--version-organisations--organisation_id-employees---format-","httpMethod":"POST","parameters":[]},{"produces":["application/json"],"notes":"","summary":"Remove a person from the employee list of the given branches or the entire organisation","nickname":"DELETE--version-organisations--organisation_id-employees---format-","httpMethod":"DELETE","parameters":[]}]},{"path":"/v2/organisations.{format}","operations":[{"produces":["application/json"],"notes":"","summary":"Create a new organisation","nickname":"POST--version-organisations---format-","httpMethod":"POST","parameters":[]},{"produces":["application/json"],"notes":"","summary":"Return all organisations","nickname":"GET--version-organisations---format-","httpMethod":"GET","parameters":[]}]}],"basePath":"https://gis-api.aiesec.org"} \ No newline at end of file diff --git a/tests/config.example.php b/tests/config.example.php deleted file mode 100644 index 99bb9e0..0000000 --- a/tests/config.example.php +++ /dev/null @@ -1,16 +0,0 @@ - - * @version: 0.2 - */ - -define("EXPA_USER", ""); -define("EXPA_PW", ""); - -define("OP_USER", ""); -define("OP_PW", ""); \ No newline at end of file