1<?php
2
3namespace OAuth\Common\Service;
4
5use OAuth\Common\Consumer\CredentialsInterface;
6use OAuth\Common\Http\Client\ClientInterface;
7use OAuth\Common\Http\Uri\Uri;
8use OAuth\Common\Http\Uri\UriInterface;
9use OAuth\Common\Exception\Exception;
10use OAuth\Common\Storage\TokenStorageInterface;
11
12/**
13 * Abstract OAuth service, version-agnostic
14 */
15abstract class AbstractService implements ServiceInterface
16{
17    /** @var Credentials */
18    protected $credentials;
19
20    /** @var ClientInterface */
21    protected $httpClient;
22
23    /** @var TokenStorageInterface */
24    protected $storage;
25
26    /**
27     * @param CredentialsInterface  $credentials
28     * @param ClientInterface       $httpClient
29     * @param TokenStorageInterface $storage
30     */
31    public function __construct(
32        CredentialsInterface $credentials,
33        ClientInterface $httpClient,
34        TokenStorageInterface $storage
35    ) {
36        $this->credentials = $credentials;
37        $this->httpClient = $httpClient;
38        $this->storage = $storage;
39    }
40
41    /**
42     * @param UriInterface|string $path
43     * @param UriInterface        $baseApiUri
44     *
45     * @return UriInterface
46     *
47     * @throws Exception
48     */
49    protected function determineRequestUriFromPath($path, UriInterface $baseApiUri = null)
50    {
51        if ($path instanceof UriInterface) {
52            $uri = $path;
53        } elseif (stripos($path, 'http://') === 0 || stripos($path, 'https://') === 0) {
54            $uri = new Uri($path);
55        } else {
56            if (null === $baseApiUri) {
57                throw new Exception(
58                    'An absolute URI must be passed to ServiceInterface::request as no baseApiUri is set.'
59                );
60            }
61
62            $uri = clone $baseApiUri;
63            if (false !== strpos($path, '?')) {
64                $parts = explode('?', $path, 2);
65                $path = $parts[0];
66                $query = $parts[1];
67                $uri->setQuery($query);
68            }
69
70            if ($path[0] === '/') {
71                $path = substr($path, 1);
72            }
73
74            $uri->setPath($uri->getPath() . $path);
75        }
76
77        return $uri;
78    }
79
80    /**
81     * Accessor to the storage adapter to be able to retrieve tokens
82     *
83     * @return TokenStorageInterface
84     */
85    public function getStorage()
86    {
87        return $this->storage;
88    }
89
90    /**
91     * @return string
92     */
93    public function service()
94    {
95        // get class name without backslashes
96        $classname = get_class($this);
97
98        return preg_replace('/^.*\\\\/', '', $classname);
99    }
100}
101