Application::run()   B
last analyzed

Complexity

Conditions 7
Paths 12

Size

Total Lines 60
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 34
c 1
b 0
f 0
nc 12
nop 0
dl 0
loc 60
rs 8.4426

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
 * This file is part of category_management
4
 * User: Sinan TURGUT <[email protected]>
5
 * Date: 24.06.2019
6
 * php version 7.2
7
 *
8
 * @category Assessment
9
 * @package  CategoryManagement
10
 * @author   Sinan TURGUT <[email protected]>
11
 * @license  See LICENSE file
12
 * @link     https://dev.sinanturgut.com.tr
13
 */
14
15
namespace CategoryManagement;
16
17
use PDO;
18
use PDOException;
19
use GuzzleHttp\Client;
0 ignored issues
show
Bug introduced by
The type GuzzleHttp\Client was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
20
use Dotenv\Dotenv;
0 ignored issues
show
Bug introduced by
The type Dotenv\Dotenv was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
21
22
/**
23
 * Class Application
24
 * @package CategoryManagement
25
 */
26
class Application
27
{
28
    /**
29
     * @var PDO
30
     */
31
    private $db;
32
33
    /**
34
     * Application constructor.
35
     */
36
    public function __construct()
37
    {
38
        defined('DS') ?: define('DS', DIRECTORY_SEPARATOR);
39
        defined('ENVROOT') ?: define('ENVROOT', dirname(__DIR__) . DS);
40
        if (file_exists(ENVROOT . '.env')) {
41
            $dotenv = new Dotenv(ENVROOT);
42
            try {
43
                $dotenv->load();
44
            } catch (InvalidFileException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
Bug introduced by
The type CategoryManagement\InvalidFileException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
45
            } catch (InvalidPathException $e) {
0 ignored issues
show
Bug introduced by
The type CategoryManagement\InvalidPathException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
46
            }
47
        }
48
49
        define('DB_CONNECTION', getenv('DB_CONNECTION'));
50
        define('DATABASE_HOST', getenv('DB_HOST'));
51
        define('DATABASE_NAME', getenv('DB_DATABASE'));
52
        define('DATABASE_USERNAME', getenv('DB_USERNAME'));
53
        define('DATABASE_PASSWORD', getenv('DB_PASSWORD'));
54
55
        try {
56
            $this->db = new PDO(DB_CONNECTION.':host='.DATABASE_HOST.';dbname='.DATABASE_NAME, DATABASE_USERNAME, DATABASE_PASSWORD);
57
        } catch (PDOException $e) {
58
            die($e->getMessage());
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
59
        }
60
    }
61
62
    /**
63
     * @throws \GuzzleHttp\Exception\GuzzleException
64
     */
65
    public function run()
66
    {
67
        if (!$_SERVER['REQUEST_URI'])
68
        {
69
            header('Content-Type: application/json; charset=UTF-8');
70
        }
71
72
        if ($_SERVER['REQUEST_URI'] == '/category/list') {
73
            $categories = $this->db->prepare('SELECT * FROM categories');
74
            $categories->execute();
75
            echo json_encode($categories->fetchAll(PDO::FETCH_OBJ), JSON_UNESCAPED_UNICODE);
76
            return;
77
        }
78
79
        if ($_SERVER['REQUEST_URI'] == '/category/add') {
80
81
            $token = $this->getToken();
82
            if(!$token) {
83
                die(json_encode(['error'=>'authentication error!']));
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
84
            }
85
86
            $client = new Client();
87
            $headers = [
88
                'Authorization' => 'Bearer ' . $token,
89
                'Accept'        => 'application/json',
90
            ];
91
            $res = $client->request('GET', 'http://user_management_nginx_1/user/checkToken',
92
                [
93
                    'headers' => $headers,
94
                    'exceptions' => false
95
                ]
96
            );
97
            $httpCode = $res->getStatusCode();
98
            if($httpCode!=200)
99
            {
100
                die(json_encode(['error'=>'authentication error!']));
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
101
            }
102
103
104
            $response = json_decode($res->getBody(),1);
105
            $isAdmin = $response['user']['is_admin'];
106
107
            if(!$isAdmin) {
108
                die(json_encode(['error'=>'admin only!']));
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
109
            }
110
111
            $post = json_decode(file_get_contents('php://input'),true);
112
113
            $data = [
114
                'category_name' => $post['category_name']
115
            ];
116
            $sql = "INSERT INTO categories (category_name) VALUES (:category_name)";
117
            $stmt= $this->db->prepare($sql);
118
            $stmt->execute($data);
119
120
            die(json_encode(['id'=>$this->db->lastInsertId()]));
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
121
            return;
0 ignored issues
show
Unused Code introduced by
return is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
122
        }
123
124
        die('<h2 style="text-align: center;">Category Management</h2>');
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
125
    }
126
127
    /**
128
     * Get Http Header Bearer Token
129
     *
130
     * @return string |null
131
     */
132
    private function getToken()
133
    {
134
        $result = null;
135
        if (isset($_SERVER["HTTP_AUTHORIZATION"])) {
136
            list($type, $data) = explode(" ", $_SERVER["HTTP_AUTHORIZATION"], 2);
137
            if (strcasecmp($type, "Bearer") == 0) {
138
                $result = $data;
139
            }
140
        }
141
142
        return $result;
143
    }
144
145
}