Endpoint   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 91
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 21
c 2
b 1
f 0
dl 0
loc 91
ccs 0
cts 34
cp 0
rs 10
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A tolerateTimeout() 0 5 1
A send() 0 22 4
A getParameters() 0 3 1
A setParameters() 0 5 1
1
<?php
2
3
namespace Tequilarapido\Twit\Endpoints;
4
5
use Tequilarapido\Twit\TwitApp;
6
7
abstract class Endpoint
8
{
9
    /** @var TwitApp */
10
    protected $app;
11
12
    /** @var array */
13
    protected $parameters;
14
15
    /** @var callable */
16
    protected $tolerateTimeoutCallback;
17
18
    /**
19
     * Endpoint constructor.
20
     *
21
     * @param TwitApp $app
22
     */
23
    public function __construct(TwitApp $app)
24
    {
25
        $this->app = $app;
26
    }
27
28
    /** @return array */
29
    abstract protected function getDefaultParameters();
30
31
    /** @return mixed */
32
    abstract protected function execute();
33
34
    /**
35
     * Sets tolerate timeout callback.
36
     *
37
     * @param callable $callback
38
     * @return $this
39
     */
40
    public function tolerateTimeout(callable  $callback)
41
    {
42
        $this->tolerateTimeoutCallback = $callback;
43
44
        return $this;
45
    }
46
47
    /**
48
     * Sets request parameters.
49
     *
50
     * @param array $parameters
51
     * @return $this
52
     */
53
    public function setParameters(array $parameters)
54
    {
55
        $this->parameters = $parameters;
56
57
        return $this;
58
    }
59
60
    /**
61
     * Call twitter api either directly or resuming when timeout exception occcurs.
62
     *
63
     * We noticed that from time to time twitter api call will timeout,
64
     * this is a way to hook in and resume avoiding breaking the fetch process.
65
     *
66
     *
67
     * @return mixed
68
     * @throws \Exception
69
     */
70
    public function send()
71
    {
72
        // No tolorate callback ?
73
        if (! $this->tolerateTimeoutCallback) {
74
            return $this->execute();
75
        }
76
77
        // With timeout tolerating
78
        try {
79
            return $this->execute();
80
        } catch (\Exception $e) {
81
            if (! str_contains($e->getMessage(), 'Operation timed out')) {
82
                throw $e;
83
            }
84
85
            app()->log->error($e);
86
87
            // Reset callback for next calls
88
            $callback = $this->tolerateTimeoutCallback;
89
            $this->tolerateTimeoutCallback = null;
90
91
            return $callback();
92
        }
93
    }
94
95
    protected function getParameters()
96
    {
97
        return array_merge($this->parameters, $this->getDefaultParameters());
98
    }
99
}
100