Completed
Pull Request — master (#7)
by Andreas
02:04
created

ApiCfpWriter::write()   C

Complexity

Conditions 8
Paths 20

Size

Total Lines 69
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 1
Metric Value
c 3
b 1
f 1
dl 0
loc 69
rs 6.5437
cc 8
eloc 48
nc 20
nop 1

How to fix   Long Method   

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 Symfony\Component\Console\Output\OutputInterface;
36
37
class ApiCfpWriter implements WriterInterface
38
{
39
    protected $baseUri;
40
41
    protected $bearerToken;
42
43
    protected $client;
44
45
    protected $output;
46
47
    public function __construct($baseUri, $bearerToken, $client = null)
48
    {
49
        $this->baseUri     = $baseUri;
50
        $this->bearerToken = $bearerToken;
51
        if (null === $client) {
52
            $client = new Client([
53
                'headers' => [
54
                    'Accept' => 'application/json',
55
                ]
56
            ]);
57
        }
58
        $this->client = $client;
59
        $this->output = new NullOutput();
60
    }
61
62
    public function write(Cfp $cfp)
63
    {
64
        $body = [
65
            'name'           => $cfp->conferenceName,
66
            'dateCfpStart'   => $cfp->dateStart->format('c'),
67
            'dateCfpEnd'     => $cfp->dateEnd->format('c'),
68
            'dateEventStart' => $cfp->eventStartDate->format('c'),
69
            'dateEventEnd'   => $cfp->eventEndDate->format('c'),
70
            'timezone'       => $cfp->timezone,
71
            'uri'            => $cfp->uri,
72
            'eventUri'       => $cfp->conferenceUri,
73
            'iconUri'        => $cfp->iconUri,
74
            'description'    => $cfp->description,
75
            'location'       => $cfp->location,
76
            'latitude'       => $cfp->latitude,
77
            'longitude'      => $cfp->longitude,
78
            'tags'           => $cfp->tags,
79
        ];
80
81
        try {
82
            $this->client->request('GET', sprintf(
83
                $this->baseUri . '/%1$s',
84
                sha1($cfp->conferenceUri)
85
            ), []);
86
            $exists = true;
87
        } catch (BadResponseException $e) {
88
            $exists = false;
89
        }
90
91
        try {
92
            if ($exists === false) {
93
                // Doesn't exist, so create it
94
95
                $response = $this->client->request('POST', sprintf(
96
                    $this->baseUri
97
                ), [
98
                    'headers' => [
99
                        'Authenticate' => 'Bearer ' . $this->bearerToken,
100
                    ],
101
                    'form_params' => $body
102
                ]);
103
            } else {
104
                // Exists, so update it
105
                $response = $this->client->request('PUT', sprintf(
106
                    $this->baseUri . '/%1$s',
107
                    sha1($cfp->conferenceUri)
108
                ), [
109
                    'headers' => [
110
                        'Authenticate' => 'Bearer ' . $this->bearerToken,
111
                    ],
112
                    'form_params' => $body
113
                ]);
114
            }
115
        } catch (BadResponseException $e) {
116
            $this->output->writeln($e->getMessage());
117
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type declared by the interface Callingallpapers\Writer\WriterInterface::write of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
118
        } catch (\Exception $e) {
119
            $this->output->writeln($e->getMessage());
120
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type declared by the interface Callingallpapers\Writer\WriterInterface::write of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
121
        }
122
123
        $this->output->writeln(sprintf(
124
            'Conference "%1$s" succcessfully %2$s.',
125
            $cfp->conferenceName,
126
            ($exists)?'updated':'created'
127
        ));
128
129
        return isset($response) && ($response->getStatusCode() === 200 || $response->getStatusCode() === 201);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return isset($response) ...tStatusCode() === 201); (boolean) is incompatible with the return type declared by the interface Callingallpapers\Writer\WriterInterface::write of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
130
    }
131
132
    public function setOutput(OutputInterface $output)
133
    {
134
        $this->output = $output;
135
    }
136
}
137