Completed
Push — master ( cd83d2...33c740 )
by Andreas
01:48
created

ApiCfpWriter::write()   D

Complexity

Conditions 14
Paths 113

Size

Total Lines 86
Code Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 0
Metric Value
c 6
b 0
f 0
dl 0
loc 86
rs 4.7331
cc 14
eloc 59
nc 113
nop 2

How to fix   Long Method    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
 * Copyright (c) 2015-2016 Andreas Heigl<[email protected]>
4
 *
5
 * Permission is hereby granted, free of charge, to any person obtaining a copy
6
 * of this software and associated documentation files (the "Software"), to deal
7
 * in the Software without restriction, including without limitation the rights
8
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
 * copies of the Software, and to permit persons to whom the Software is
10
 * furnished to do so, subject to the following conditions:
11
 *
12
 * The above copyright notice and this permission notice shall be included in
13
 * all copies or substantial portions of the Software.
14
 *
15
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
 * THE SOFTWARE.
22
 *
23
 * @author    Andreas Heigl<[email protected]>
24
 * @copyright 2015-2016 Andreas Heigl/callingallpapers.com
25
 * @license   http://www.opensource.org/licenses/mit-license.php MIT-License
26
 * @version   0.0
27
 * @since     01.12.2015
28
 * @link      http://github.com/heiglandreas/callingallpapers-cli
29
 */
30
namespace Callingallpapers\Writer;
31
32
use Callingallpapers\Entity\Cfp;
33
use GuzzleHttp\Client;
34
use GuzzleHttp\Exception\BadResponseException;
35
use GuzzleHttp\TransferStats;
36
use Symfony\Component\Console\Output\OutputInterface;
37
38
class ApiCfpWriter implements WriterInterface
39
{
40
    protected $baseUri;
41
42
    protected $bearerToken;
43
44
    protected $client;
45
46
    protected $output;
47
48
    public function __construct($baseUri, $bearerToken, $client = null)
49
    {
50
        $this->baseUri     = $baseUri;
51
        $this->bearerToken = $bearerToken;
52
        if (null === $client) {
53
            $client = new Client([
54
                'headers' => [
55
                    'Accept' => 'application/json',
56
                ],
57
                'allow_redirects' => [
58
                    'strict' => true,
59
                    'max' => 5,
60
                ],
61
            ]);
62
        }
63
        $this->client = $client;
64
        $this->output = new NullOutput();
65
    }
66
67
    public function write(Cfp $cfp, $source)
68
    {
69
        try {
70
            $uri = '';
71
            $this->client->get($cfp->conferenceUri, [
72
                'on_stats' => function (TransferStats $stats) use (&$uri) {
73
                    $uri = (string) $stats->getEffectiveUri();
74
                }
75
            ]);
76
        } catch (\Exception $e) {
77
            throw new \InvalidArgumentException('Event-URI could not be verified: ' . $e->getMessage());
78
        }
79
        $cfp->conferenceUri = $uri;
80
81
        $body = [
82
            'name'           => $cfp->conferenceName,
83
            'dateCfpEnd'     => $cfp->dateEnd->format('c'),
84
            'dateEventStart' => $cfp->eventStartDate->format('c'),
85
            'dateEventEnd'   => $cfp->eventEndDate->format('c'),
86
            'timezone'       => $cfp->timezone,
87
            'uri'            => $cfp->uri,
88
            'eventUri'       => $cfp->conferenceUri,
89
            'iconUri'        => $cfp->iconUri,
90
            'description'    => $cfp->description,
91
            'location'       => $cfp->location,
92
            'latitude'       => $cfp->latitude,
93
            'longitude'      => $cfp->longitude,
94
            'tags'           => $cfp->tags,
95
            'source'         => $source,
96
        ];
97
98
        if ($cfp->dateStart instanceof \DateTimeInterface) {
99
            $body['dateCfpStart'] = $cfp->dateStart->format('c');
100
        }
101
102
        try {
103
            $this->client->request('GET', sprintf(
104
                $this->baseUri . '/%1$s',
105
                sha1($cfp->conferenceUri)
106
            ), []);
107
            $exists = true;
108
        } catch (BadResponseException $e) {
109
            $exists = false;
110
        }
111
112
        try {
113
            if ($exists === false) {
114
                // Doesn't exist, so create it
115
                $response = $this->client->request('POST', sprintf(
116
                    $this->baseUri
117
                ), [
118
                    'headers' => [
119
                        'Authorization' => 'Bearer ' . $this->bearerToken,
120
                    ],
121
                    'form_params' => $body
122
                ]);
123
            } else {
124
                // Exists, so update it
125
                $response = $this->client->request('PUT', sprintf(
126
                    $this->baseUri . '/%1$s',
127
                    sha1($cfp->conferenceUri)
128
                ), [
129
                    'headers' => [
130
                        'Authorization' => 'Bearer ' . $this->bearerToken,
131
                    ],
132
                    'form_params' => $body
133
                ]);
134
            }
135
        } catch (BadResponseException $e) {
136
            $this->output->writeln($e->getMessage());
137
            return $e->getMessage();
138
        } catch (\Exception $e) {
139
            $this->output->writeln($e->getMessage());
140
            return $e->getMessage();
141
        }
142
143
        if ($response && ($response->getStatusCode() === 200 || $response->getStatusCode() === 201)) {
144
            $this->output->writeln(sprintf(
145
                'Conference "%1$s" succcessfully %2$s.',
146
                $cfp->conferenceName,
147
                ($exists) ? 'updated' : 'created'
148
            ));
149
        }
150
151
        return (isset($response) && ($response->getStatusCode() === 200 || $response->getStatusCode() === 201))?'Success':'Failure';
152
    }
153
154
    public function setOutput(OutputInterface $output)
155
    {
156
        $this->output = $output;
157
    }
158
}
159