Completed
Push — master ( 100f13...cbf27e )
by Andreas
10s
created

ApiCfpWriter::write()   C

Complexity

Conditions 13
Paths 112

Size

Total Lines 76
Code Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 0
Metric Value
dl 0
loc 76
rs 5.0353
c 6
b 0
f 0
cc 13
eloc 52
nc 112
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\CfpFilter\CfpFilterInterface;
33
use Callingallpapers\CfpFilter\FilterList;
34
use Callingallpapers\Entity\Cfp;
35
use GuzzleHttp\Client;
36
use GuzzleHttp\Exception\BadResponseException;
37
use GuzzleHttp\TransferStats;
38
use Symfony\Component\Console\Output\OutputInterface;
39
40
class ApiCfpWriter implements WriterInterface
41
{
42
    protected $baseUri;
43
44
    protected $bearerToken;
45
46
    protected $client;
47
48
    protected $output;
49
50
    private $filter = null;
51
52
    public function __construct($baseUri, $bearerToken, $client = null)
53
    {
54
        $this->baseUri     = $baseUri;
55
        $this->bearerToken = $bearerToken;
56 View Code Duplication
        if (null === $client) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
57
            $client = new Client([
58
                'headers' => [
59
                    'Accept' => 'application/json',
60
                ],
61
            ]);
62
        }
63
        $this->client = $client;
64
        $this->output = new NullOutput();
65
        $this->filter = new FilterList();
66
    }
67
68
    public function setFilter(CfpFilterInterface $filter)
69
    {
70
        $this->filter = $filter;
71
    }
72
73
    public function write(Cfp $cfp, $source)
74
    {
75
        $cfp = $this->filter->filter($cfp);
76
77
        $body = [
78
            'name'           => $cfp->conferenceName,
79
            'dateCfpEnd'     => $cfp->dateEnd->format('c'),
80
            'dateEventStart' => $cfp->eventStartDate->format('c'),
81
            'dateEventEnd'   => $cfp->eventEndDate->format('c'),
82
            'timezone'       => $cfp->timezone,
83
            'uri'            => $cfp->uri,
84
            'eventUri'       => $cfp->conferenceUri,
85
            'iconUri'        => $cfp->iconUri,
86
            'description'    => $cfp->description,
87
            'location'       => $cfp->location,
88
            'latitude'       => $cfp->latitude,
89
            'longitude'      => $cfp->longitude,
90
            'tags'           => $cfp->tags,
91
            'source'         => $source,
92
        ];
93
94
        if ($cfp->dateStart instanceof \DateTimeInterface) {
95
            $body['dateCfpStart'] = $cfp->dateStart->format('c');
96
        }
97
98
        try {
99
            $this->client->request('GET', sprintf(
100
                $this->baseUri . '/%1$s',
101
                sha1($cfp->conferenceUri)
102
            ), []);
103
            $exists = true;
104
        } catch (BadResponseException $e) {
105
            $exists = false;
106
        }
107
108
        try {
109
            if ($exists === false) {
110
                // Doesn't exist, so create it
111
                $response = $this->client->request('POST', sprintf(
112
                    $this->baseUri
113
                ), [
114
                    'headers' => [
115
                        'Authorization' => 'Bearer ' . $this->bearerToken,
116
                    ],
117
                    'form_params' => $body
118
                ]);
119
            } else {
120
                // Exists, so update it
121
                $response = $this->client->request('PUT', sprintf(
122
                    $this->baseUri . '/%1$s',
123
                    sha1($cfp->conferenceUri)
124
                ), [
125
                    'headers' => [
126
                        'Authorization' => 'Bearer ' . $this->bearerToken,
127
                    ],
128
                    'form_params' => $body
129
                ]);
130
            }
131
        } catch (BadResponseException $e) {
132
            $this->output->writeln($e->getMessage());
133
            return $e->getMessage();
134
        } catch (\Exception $e) {
135
            $this->output->writeln($e->getMessage());
136
            return $e->getMessage();
137
        }
138
139
        if ($response && ($response->getStatusCode() === 200 || $response->getStatusCode() === 201)) {
140
            $this->output->writeln(sprintf(
141
                'Conference "%1$s" succcessfully %2$s.',
142
                $cfp->conferenceName,
143
                ($exists) ? 'updated' : 'created'
144
            ));
145
        }
146
147
        return (isset($response) && ($response->getStatusCode() === 200 || $response->getStatusCode() === 201))?'Success':'Failure';
148
    }
149
150
    public function setOutput(OutputInterface $output)
151
    {
152
        $this->output = $output;
153
    }
154
}
155