Application::getToken()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 11
rs 10
1
<?php
2
/**
3
 * This file is part of comment_management
4
 * User: Sinan TURGUT <[email protected]>
5
 * Date: 24.06.2019
6
 * php version 7.2
7
 *
8
 * @category Assessment
9
 * @package  CommentManagement
10
 * @author   Sinan TURGUT <[email protected]>
11
 * @license  See LICENSE file
12
 * @link     https://dev.sinanturgut.com.tr
13
 */
14
15
16
namespace CommentManagement;
17
18
use PDO;
19
use PDOException;
20
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...
21
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...
22
23
/**
24
 * Class Application
25
 * @package CommentManagement
26
 */
27
class Application
28
{
29
    /**
30
     * @var PDO
31
     */
32
    private $db;
33
34
    /**
35
     * Application constructor.
36
     */
37
    public function __construct()
38
    {
39
        defined('DS') ?: define('DS', DIRECTORY_SEPARATOR);
40
        defined('ENVROOT') ?: define('ENVROOT', dirname(__DIR__) . DS);
41
        if (file_exists(ENVROOT . '.env')) {
42
            $dotenv = new Dotenv(ENVROOT);
43
            try {
44
                $dotenv->load();
45
            } catch (InvalidFileException $e) {
0 ignored issues
show
Bug introduced by
The type CommentManagement\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...
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
46
            } catch (InvalidPathException $e) {
0 ignored issues
show
Bug introduced by
The type CommentManagement\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...
47
            }
48
        }
49
50
        define('DB_CONNECTION', getenv('DB_CONNECTION'));
51
        define('DATABASE_HOST', getenv('DB_HOST'));
52
        define('DATABASE_NAME', getenv('DB_DATABASE'));
53
        define('DATABASE_USERNAME', getenv('DB_USERNAME'));
54
        define('DATABASE_PASSWORD', getenv('DB_PASSWORD'));
55
56
        try {
57
            $this->db = new PDO(DB_CONNECTION.':host='.DATABASE_HOST.';dbname='.DATABASE_NAME, DATABASE_USERNAME, DATABASE_PASSWORD);
58
        } catch (PDOException $e) {
59
            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...
60
        }
61
    }
62
63
    /**
64
     * @throws \GuzzleHttp\Exception\GuzzleException
65
     */
66
    public function run()
67
    {
68
        if (!$_SERVER['REQUEST_URI'])
69
        {
70
            header('Content-Type: application/json; charset=UTF-8');
71
        }
72
73
        if ($_SERVER['REQUEST_URI'] == '/comment/list') {
74
            $post = json_decode(file_get_contents('php://input'),true);
75
            $product_id = $post['product_id'];
76
            $comments = $this->db->prepare('SELECT * FROM comments where product_id=:product_id');
77
            $comments->execute(['product_id'=>$product_id]);
78
            echo json_encode($comments->fetchAll(PDO::FETCH_OBJ), JSON_UNESCAPED_UNICODE);
79
            return;
80
        }
81
82
        if ($_SERVER['REQUEST_URI'] == '/comment/add') {
83
84
            $token = $this->getToken();
85
            if(!$token) {
86
                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...
87
            }
88
89
            $client = new Client();
90
            $headers = [
91
                'Authorization' => 'Bearer ' . $token,
92
                'Accept'        => 'application/json',
93
            ];
94
            $res = $client->request('GET', 'http://user_management_nginx_1/user/checkToken',
95
                [
96
                    'headers' => $headers,
97
                    'exceptions' => false
98
                ]
99
            );
100
            $httpCode = $res->getStatusCode();
101
            if($httpCode!=200)
102
            {
103
                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...
104
            }
105
106
            $response = json_decode($res->getBody(),1);
107
108
109
110
            $post = json_decode(file_get_contents('php://input'),true);
111
112
            $data = [
113
                'product_id' => $post['product_id'],
114
                'comment' => $post['comment'],
115
                'user_id' => $response['user']['id'],
116
                'user_name' => $response['user']['username'],
117
                'comment_date' => date('Y-m-d H:i:s')
118
            ];
119
            $sql = "INSERT INTO comments (product_id, comment, user_id, user_name, comment_date) VALUES 
120
                    (:product_id, :comment, :user_id, :user_name, :comment_date)";
121
            $stmt= $this->db->prepare($sql);
122
            $stmt->execute($data);
123
124
            die(json_encode(['id'=>$this->db->lastInsertId()], JSON_UNESCAPED_UNICODE));
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
            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...
126
        }
127
128
        die('<h2 style="text-align: center;">Comment 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...
129
    }
130
131
    /**
132
     * @return |null
0 ignored issues
show
Documentation Bug introduced by
The doc comment |null at position 0 could not be parsed: Unknown type name '|' at position 0 in |null.
Loading history...
133
     */
134
    private function getToken()
135
    {
136
        $result = null;
137
        if (isset($_SERVER["HTTP_AUTHORIZATION"])) {
138
            list($type, $data) = explode(" ", $_SERVER["HTTP_AUTHORIZATION"], 2);
139
            if (strcasecmp($type, "Bearer") == 0) {
140
                $result = $data;
141
            }
142
        }
143
144
        return $result;
145
    }
146
147
}