Completed
Push — master ( 8e5658...112fe2 )
by Dominik
03:26
created

AzineHybridAuth::getInstance()   F

Complexity

Conditions 13
Paths 288

Size

Total Lines 47
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 182

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 47
ccs 0
cts 32
cp 0
rs 3.7737
c 1
b 0
f 0
cc 13
eloc 27
nc 288
nop 2
crap 182

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Azine\HybridAuthBundle\Services;
4
5
use Azine\HybridAuthBundle\DependencyInjection\AzineHybridAuthExtension;
6
use Azine\HybridAuthBundle\Entity\HybridAuthSessionData;
7
use Doctrine\Common\Persistence\ObjectManager;
8
use Symfony\Component\HttpFoundation\Cookie;
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
11
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
12
use Symfony\Component\Security\Core\User\UserInterface;
13
14
class AzineHybridAuth
15
{
16
    /**
17
     * ID of the sessionDataCookie.
18
     */
19
    const cookieName = 'azine_hybridauth_session';
20
21
    /**
22
     * @var ObjectManager
23
     */
24
    private $objectManager;
25
26
    /**
27
     * @var UserInterface
28
     */
29
    private $currentUser;
30
31
    /**
32
     * @var bool
33
     */
34
    private $storeForUser;
35
36
    /**
37
     * @var bool
38
     */
39
    private $storeAsCookie;
40
41
    /**
42
     * @var int
43
     */
44
    private $expiresInDays;
45
46
    /**
47
     * Configured Instances of HybridAuth.
48
     *
49
     * @var array or HybridAuth
50
     */
51
    private $instances = array();
52
53
    /**
54
     * HybridAuth configuration.
55
     *
56
     * @var array
57
     */
58
    private $config;
59
60
    /**
61
     * @param UrlGeneratorInterface $router
62
     * @param TokenStorageInterface $tokenStorage
63
     * @param ObjectManager         $manager
64
     * @param array                 $config
65
     * @param bool                  $storeForUser
66
     * @param $storeAsCookie
67 2
     * @param $expiresInDays
68 2
     */
69 2
    public function __construct(UrlGeneratorInterface $router, TokenStorageInterface $tokenStorage, ObjectManager $manager, $config, $storeForUser, $storeAsCookie, $expiresInDays)
70 2
    {
71 2
        $base_url = $router->generate($config[AzineHybridAuthExtension::ENDPOINT_ROUTE], array(), UrlGeneratorInterface::ABSOLUTE_URL);
72 2
        $config[AzineHybridAuthExtension::BASE_URL] = $base_url;
73 2
        $this->config = $config;
74 2
        $this->objectManager = $manager;
75 2
        $this->storeForUser = $storeForUser;
76
        $this->storeAsCookie = $storeAsCookie;
77
        $user = $tokenStorage->getToken()->getUser();
78 2
        if ($user instanceof UserInterface) {
79 2
            $this->currentUser = $user;
80
        }
81
        $this->expiresInDays = $expiresInDays;
82
    }
83
84
    /**
85
     * Get a Hybrid_Auth instance initialised for the given provider.
86
     * HybridAuthSessions will be restored from DB and/or cookies, according to the bundle configuration.
87
     *
88
     * @param $cookieSessionData
89
     * @param $provider
90
     *
91
     * @return \Hybrid_Auth
92
     */
93
    public function getInstance($cookieSessionData, $provider)
94
    {
95
        if (array_key_exists($provider, $this->instances)) {
96
            $hybridAuth = $this->instances[$provider];
97
        } else {
98
            $hybridAuth = new \Hybrid_Auth($this->config);
99
            $this->instances[$provider] = $hybridAuth;
100
        }
101
        $restoredFromDB = false;
102
        $sessionData = null;
103
        $isExpiredSession = false;
104
105
        $result = null;
106
        if($this->currentUser instanceof UserInterface) {
107
            $result = $this->objectManager->getRepository('AzineHybridAuthBundle:HybridAuthSessionData')->findOneBy(array('username' => $this->currentUser->getUsername(), 'provider' => $provider));
108
        }
109
110
        if ($result instanceof HybridAuthSessionData) {
111
            $isExpiredSession = $this->isExpiredSession($result);
112
        }
113
114
        if ($isExpiredSession) {
115
            $this->deleteSession($provider);
116
        }
117
118
        if (!$isExpiredSession && $this->storeForUser && $this->currentUser instanceof UserInterface) {
119
            // try from database
120
            if ($result) {
121
                $sessionData = $result->getSessionData();
122
                $restoredFromDB = true;
123
            }
124
        }
125
        if (null === $sessionData && null !== $cookieSessionData) {
126
            // try from cookie
127
            $sessionData = gzinflate($cookieSessionData);
128
129
            // user is looged in but auth session is not yet stored in db => store now
130
            if (!$restoredFromDB) {
131
                $this->saveAuthSessionData($sessionData, $provider);
132
            }
133
        }
134
        if ($sessionData) {
135
            $hybridAuth->restoreSessionData($sessionData);
136
        }
137
138
        return $hybridAuth;
139
    }
140
141
    /**
142
     * @param Request $request
143
     * @param $provider
144
     * @param $sessionData
145
     *
146
     * @return Cookie | null
147
     */
148
    public function storeHybridAuthSessionData(Request $request, $provider, $sessionData)
149
    {
150
        $this->saveAuthSessionData($sessionData, $provider);
151
152
        if ($this->storeAsCookie) {
153
            return new Cookie($this->getCookieName($provider), gzdeflate($sessionData), new \DateTime($this->expiresInDays.' days'), '/', $request->getHost(), $request->isSecure(), true);
0 ignored issues
show
Documentation introduced by
new \DateTime($this->expiresInDays . ' days') is of type object<DateTime>, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
154
        }
155
156
        return null;
157
    }
158
159
    /**
160
     * Delete the HybridAuthSessionData entity from the database.
161
     *
162
     * @param $provider
163
     */
164
    public function deleteSession($provider)
165
    {
166
        if ($this->currentUser instanceof UserInterface) {
167
            $result = $this->objectManager->getRepository('AzineHybridAuthBundle:HybridAuthSessionData')->findOneBy(array('username' => $this->currentUser->getUsername(), 'provider' => $provider));
168
            if ($result) {
169
                $this->objectManager->remove($result);
170
                $this->objectManager->flush();
171
            }
172
        }
173
    }
174
175
    /**
176
     * Save as HybridAuthSessionData entity to the database.
177
     * Checks the bundle configuration before saving.
178
     *
179
     * @param $sessionData
180
     * @param $provider
181
     */
182
    private function saveAuthSessionData($sessionData, $provider)
183
    {
184
        if ($this->storeForUser && $this->currentUser instanceof UserInterface) {
185
            $hybridAuthData = $this->objectManager->getRepository('AzineHybridAuthBundle:HybridAuthSessionData')->findOneBy(array('username' => $this->currentUser->getUsername(), 'provider' => strtolower($provider)));
186
            if (!$hybridAuthData) {
187
                $hybridAuthData = new HybridAuthSessionData();
188
                $hybridAuthData->setUserName($this->currentUser->getUsername());
189
                $hybridAuthData->setProvider(strtolower($provider));
190
191
                $expirationDate = new \DateTime();
192
                $expirationDate->modify('+ '.$this->expiresInDays.' day');
193
194
                $hybridAuthData->setExpiresAt($expirationDate);
195
                $this->objectManager->persist($hybridAuthData);
196
            }
197
            $hybridAuthData->setSessionData($sessionData);
198
            $this->objectManager->flush();
199
        }
200
    }
201
202
    public function getCookieName($provider)
203
    {
204
        return self::cookieName.'_'.strtolower($provider);
205
    }
206
207
    /**
208
     * Use this function to get access to a HybridAuthProvider.
209
     *
210
     * Calling this method will log the user in (make a roundtrip to the providers site and back to your site again)
211
     * and call the page again that you came from.
212
     *
213
     * When logged (allready) it will return the hybridAuth provider.
214
     *
215
     * @param $authSessionData
216
     * @param string $provider_id
217
     * @param bool   $require_login
218
     *
219
     * @return \Hybrid_Provider_Model
220
     */
221
    public function getProvider($authSessionData, $provider_id, $require_login = true)
222
    {
223
        $adapter = $this->getInstance($authSessionData, $provider_id)->getAdapter($provider_id);
224
        if ($require_login && !$adapter->isUserConnected()) {
225
            $adapter->login();
226
        }
227
228
        return $adapter;
229
    }
230
231
    /**
232
     * Check if the current user has allowed access to the given provider.
233
     *
234
     * @param Request $request
235
     * @param string  $provider_id
236
     *
237
     * @return bool true if access to the provider is granted for this app
238
     */
239
    public function isConnected(Request $request, $provider_id)
240
    {
241
        $sessionData = $request->cookies->get($this->getCookieName($provider_id));
242
        $adapter = $this->getInstance($sessionData, $provider_id)->getAdapter($provider_id);
243
        $connected = $adapter->isUserConnected();
244
245
        return $connected;
246
    }
247
248
    /**
249
     * Get the Xing Adapter.
250
     *
251
     * @return \Hybrid_Providers_XING
252
     */
253
    public function getXing()
254
    {
255
        return $this->getProvider(null, 'xing');
256
    }
257
258
    /**
259
     * Get the Xing api (OAuthClient).
260
     *
261
     * @return \OAuth1Client
262
     */
263
    public function getXingApi()
264
    {
265
        return $this->getXing()->api();
266
    }
267 2
268
    /**
269 2
     * Get the LinkedIn Adapter.
270
     *
271 1
     * @return \Hybrid_Providers_LinkedIn
272
     */
273
    public function getLinkedIn()
274 1
    {
275
        return $this->getProvider(null, 'linkedin');
276
    }
277
278
    /**
279
     * Get the LinkedIn api (LinkedIn PHP-client).
280
     *
281
     * @return \LinkedIn
282
     */
283
    public function getLinkedInApi()
284
    {
285
        return $this->getLinkedIn()->api();
286
    }
287
288
    /**
289
     * Get if auth token is expired.
290
     *
291
     * @param HybridAuthSessionData $data
292
     *
293
     * @return bool
294
     */
295
    public function isExpiredSession(HybridAuthSessionData $data)
296
    {
297
        if ($data->getExpiresAt() < new \DateTime()) {
298
            return true;
299
        }
300
301
        return false;
302
    }
303
}
304