Completed
Push — master ( 2a302c...68e9dc )
by Jacob
14:11
created

CommentSubmitModule::fetch_errors()   B

Complexity

Conditions 10
Paths 64

Size

Total Lines 18
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 7.2765
c 0
b 0
f 0
cc 10
eloc 15
nc 64
nop 0

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
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 10 and the first side effect is on line 3.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
Loader::load('utility', [
4
    'Request',
5
    'Validate',
6
]);
7
8
use Jacobemerick\Web\Domain\Comment\Comment\ServiceCommentRepository;
9
10
class CommentSubmitModule
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
11
{
12
13
    private $site;
14
    private $path;
15
    private $fullPath;
16
17
    public function __construct($site, $path, $fullPath, $pageTitle)
0 ignored issues
show
Unused Code introduced by
The parameter $pageTitle is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
18
    {
19
        $this->site = $site;
20
        $this->path = $path;
21
        $this->fullPath = $fullPath;
22
    }
23
24
    public function activate()
25
    {
26
        // todo why is this responsible for checking on valid calls
27
        if (!Request::hasPost()) {
28
            return false;
29
        }
30
        if (!Request::getPost('submit') == 'Submit Comment') {
31
            return false;
32
        }
33
        if (!Request::getPost('catch') !== '') {
34
            return false;
35
        }
36
37
        $errors = $this->checkValidation();
38
        if (count($errors) > 0) {
39
            return $errors;
40
        }
41
42
        $commentId = $this->save(Request::getPost());
43
        // todo broken notifications
44
        $this->redirectToComment($commentId);
45
    }
46
47
    private function checkValidation()
48
    {
49
        $errors = array();
50
        if (!Validate::checkRequest('post', 'name', 'name')) {
51
            $errors['name'] = 'You must include a valid name';
52
        }
53
        if (!Validate::checkRequest('post', 'email', 'email')) {
54
            $errors['email'] = 'You must include a valid email';
55
        }
56
        if (Request::getPost('website') && !Validate::checkRequest('post', 'website', 'url')) {
57
            $errors['website'] = 'Please enter a valid website';
58
        }
59
        if (!Validate::checkRequest('post', 'comment', 'string')) {
60
            $errors['comment'] = 'You must enter a comment';
61
        }
62
        if (Request::getPost('notify') && Request::getPost('notify') != 'check') {
63
            $errors['notify'] = 'You entered an invalid notify request';
64
        }
65
        if (Request::getPost('reply') && !Validate::checkRequest('post', 'reply', 'integer')) {
66
            $errors['reply'] = 'You entered an invalid reply request';
67
        }
68
69
        return $errors;
70
    }
71
72
    private function save(array $data)
0 ignored issues
show
Coding Style introduced by
save uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
73
    {
74
        $path = $_SERVER['REQUEST_URI'];
75
        $path = explode('/', $path);
76
        $path = array_filter($path);
77
        $path = array_slice($path, 0, 2);
78
        $path = implode('/', $path);
79
80
        $body = [
81
            'commenter' => [
82
                'name' => $data['name'],
83
                'email' => $data['email'],
84
                'website' => $data['website'],
85
            ],
86
            'body' => $data['comment'],
87
            'should_notify' => (isset($data['notify']) && $data['notify'] == 'check'),
88
            'domain' => (URLDecode::getSite() == 'blog' ? 'blog.jacobemerick.com' : 'waterfallsofthekeweenaw.com'),
89
            'path' => $path,
90
            'url' => "{$this->fullPath}#comment-{{id}}",
91
            'thread' => 'comments',
92
            'reply_to' => ($data['type'] == 'new' ? 0 : $data['type']),
93
            'ip_address' => $_SERVER['REMOTE_ADDR'],
94
            'user_agent' => $_SERVER['HTTP_USER_AGENT'],
95
            'referrer' => $_SERVER['HTTP_REFERER'],
96
        ];
97
98
        global $container;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
99
        $repository = new ServiceCommentRepository($container['comment_service_api']);
100
        try {
101
            $response = $repository->createComment($body);
102
        } catch (Exception $e) {
103
            $container['logger']->warning("CommentService | Create | {$e->getMessage()}");
104
        }
105
106
        return $response->getId();
0 ignored issues
show
Bug introduced by
The method getId cannot be called on $response (of type array<string,string|arra...ng","thread":"string"}>).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
107
    }
108
109
    private function redirectToComment($commentId)
110
    {
111
        $url = '';
112
        $url .= $this->fullPath;
113
        $url .= "#comment-{$commentId}";
114
115
        Loader::loadNew('controller', 'Error303Controller', array($url))->activate();
116
        exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method redirectToComment() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
117
    }
118
}
119