Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php namespace Edmunds;
- use EdmundsEndpointsEdmundsEndpointInterface;
- class EdmundsApi {
- private $domain = 'https://api.edmunds.com';
- private $endpoint;
- private $parameters = [
- 'fmt' => 'json',
- 'api_key' => 'api_key_goes_here',
- ];
- public function __construct(EdmundsEndpointInterface $endpoint, $parameters = [])
- {
- $this->endpoint = $endpoint;
- $this->parameters = array_merge($this->parameters, $parameters);
- }
- public function getResult()
- {
- return json_decode(file_get_contents($this->getBuiltUrl()));
- }
- private function getBuiltUrl()
- {
- $url = strtr($this->getBaseUrl(), $this->getRouteParameters());
- if (count($this->getQueryParameters()))
- {
- $url .= '?' . http_build_query($this->getQueryParameters());
- }
- return $url;
- }
- private function getBaseUrl()
- {
- return $this->domain . $this->endpoint->getPath();
- }
- private function getAllParameters()
- {
- return array_merge($this->parameters, $this->endpoint->getParameters());
- }
- private function getRouteParameters()
- {
- return array_intersect_key(
- $this->getAllParameters(),
- array_filter(
- $this->getAllParameters(),
- function($key) {
- return strpos($key, ':') === 0;
- },
- ARRAY_FILTER_USE_KEY
- )
- );
- }
- private function getQueryParameters()
- {
- return array_diff($this->getAllParameters(), $this->getRouteParameters());
- }
- }
- <?php namespace EdmundsEndpoints;
- interface EdmundsEndpointInterface {
- public function getPath();
- public function getParameters();
- }
- <?php namespace EdmundsEndpoints;
- abstract class EdmundsEndpoint implements EdmundsEndpointInterface {
- protected $path;
- protected $parameters = [];
- public function getPath()
- {
- return $this->path;
- }
- public function getParameters()
- {
- return $this->parameters;
- }
- }
- <?php namespace EdmundsEndpoints;
- class ModelYearEndpoint extends EdmundsEndpoint {
- public function __construct($make, $model, $year)
- {
- $this->path = '/api/vehicle/v2/:make/:model/:year';
- $this->parameters[':make'] = $make;
- $this->parameters[':model'] = $model;
- $this->parameters[':year'] = $year;
- }
- }
- <?php namespace EdmundsEndpoints;
- class MaintenanceEndpoint extends EdmundsEndpoint {
- public function __construct($id)
- {
- $this->path = '/v1/api/maintenance/actionrepository/findbymodelyearid';
- $this->parameters['modelyearid'] = $id;
- }
- }
- $model_api = new EdmundsApi(new ModelYearEndpoint($make, $model, $year), ['view' => 'basic']);
- $maint_api = new EdmundsApi(new MaintenanceEndpoint($id));
- $model_result = $model_api->getResult();
- $maint_result = $maint_api->getResult();
Add Comment
Please, Sign In to add comment