GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

UserController   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 185
Duplicated Lines 7.57 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 14
c 0
b 0
f 0
lcom 1
cbo 1
dl 14
loc 185
rs 10

9 Methods

Rating   Name   Duplication   Size   Complexity  
A connect() 0 16 1
A isSession() 0 5 2
B get() 14 31 2
B signup() 0 46 3
A postBadge() 0 16 1
A getBadge() 0 16 1
A markBadgeAsCompleted() 0 14 1
A deleteUserBadge() 0 12 1
A getTicket() 0 16 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace BitPrepared\Bundle\D1b0Workspace\Controller\V1;
4
5
use Symfony\Component\HttpFoundation\Request;
6
use Symfony\Component\HttpFoundation\Response;
7
use Symfony\Component\HttpFoundation\JsonResponse;
8
use Silex\Application;
9
use Silex\Api\ControllerProviderInterface;
10
use Monolog\Logger;
11
use RedBeanPHP\Facade as R;
12
use BitPrepared\Bundle\D1b0Workspace\Exception\UnauthorizedException;
13
14
class UserController implements ControllerProviderInterface
15
{
16
    public $DATE_FORMAT = 'Y-m-d\TH:i:s\Z';
17
18
    private $app;
19
20
21
    public function connect(Application $app)
22
    {
23
        $this->app = $app;
24
        $factory = $app['controllers_factory'];
25
        # il mount point e' precedente e non serve prima
26
        $this->app['db'];
27
        //R::fancyDebug( TRUE );
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
28
        $factory->post('/signup', array($this, 'signup'));
29
        $factory->get('/{id}', array($this, 'get'))->before([$this, 'isSession']);
30
        $factory->post('/{id}/badge', array($this, 'postBadge'))->before([$this, 'isSession']);
31
        $factory->get('/{id}/badge/{id_badge}', array($this, 'getBadge'))->before([$this, 'isSession']);
32
        $factory->patch('/{id}/badge/{id_badge}/completed', array($this, 'markBadgeAsCompleted'))->before([$this, 'isSession']);
33
        $factory->delete('/{id}/badge/{id_badge}', array($this, 'deleteUserBadge'))->before([$this, 'isSession']);
34
        $factory->get('/{id}/ticket', array($this, 'getTicket'))->before([$this, 'isSession']);
35
        return $factory;
36
    }
37
38
    public function isSession(Request $request, Application $app) {
39
            if ($this->app['session']->has('user') !== true) {
40
                throw new UnauthorizedException("errore", 1);
41
            }
42
    }
43
44
    public function get($id, Request $request)
45
    {
46
        $user = R::findOne('user', 'id = ?', ["$id"]);
47
        $headers = [];
48
49
        $output = [
50
            'name'=>$user->name,
51
            'surname'=>$user->surname,
52
            'authmode'=>$user->authmode,
53
            'skills'=>'',
54
        ];
55
56
        $badges = R::findAll('userbadgecomplete', 'WHERE user = ?', [$id]);
57
        $badgeList = [];
58 View Code Duplication
        foreach ($badges as $badge) {
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...
59
            array_push($badgeList,
60
                [
61
                    'badge'=>[
62
                        'id'=>intval($badge['id']),
63
                        'name'=>$badge['name'],
64
                        'description'=>$badge['description'],
65
                        'img'=>$badge['img']
66
                    ],
67
                    'clove'=>intval($badge['clove']),
68
                    'completed'=>boolval($badge['completed'])
69
                ]
70
            );
71
        }
72
        $output['skills'] = $badgeList;
73
        return JsonResponse::create($output, 200, $headers)->setSharedMaxAge(300);
74
    }
75
76
    public function signup(Request $request)
77
    {
78
        //TODO ricordarsi di salvare in log il login ^^
79
        // $this->app['monolog']->addInfo(sprintf("Required '%s'.", 'status'));
0 ignored issues
show
Unused Code Comprehensibility introduced by
74% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
80
        $this->app->log('log info', [], Logger::INFO); //grazie al traits <- da trasformare prima in app
81
        $data = json_decode($request->getContent(), true);
82
        //TODO: https://github.com/justinrainbow/json-schema VALIDARE LA ROBA IN INPUT
83
84
        $authMode = $data['authMode'];
85
        $id = -1;
86
        if ($authMode === 'Email') {
87
            /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
66% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
88
            $user = R::dispense('user');
89
            $user->authMode=$data['authMode'];
90
            $user->name=$data['name'];
91
            $user->surname=$data['surname'];
92
            $user->surname=$data['surname'];*/
93
            try {
94
                $user = R::dispense('user');
95
                //$user->import($data);
0 ignored issues
show
Unused Code Comprehensibility introduced by
86% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
96
                $size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB);
97
                $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
98
                $user->salt = $iv;
99
                $user->pwd = hash("sha256", $iv.$data['password']);
100
                $user->status = "checking";
101
                //$user->id="11";
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
102
                $user->name = $data['name'];
103
                $user->email = $data['email'];
104
                $user->surname = $data['surname'];
105
                $user->authmode = $data['authMode'];
106
                $user->inserttime = date($this->DATE_FORMAT);
107
                $user->updatetime = date('Y-m-d G:i:s');
108
                $id = R::store($user);
109
                $res = (object)["id" => $id];
110
            }catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The class BitPrepared\Bundle\D1b0W...Controller\V1\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
111
                echo $e;
112
            }
113
114
        }else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
115
116
        }
117
118
        $headers = [];
119
        //TODO redirect to other page (/security/callback?authMode=Email)
120
        return JsonResponse::create($res, 200, $headers)->setSharedMaxAge(300);
0 ignored issues
show
Bug introduced by
The variable $res does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
121
    }
122
123
    public function postBadge($id, Request $request)
124
    {
125
        //TODO valiadre id in funzione della sessione utente (altrimenti chiunque aggiunge badge a chiunque)
126
        $data = json_decode($request->getContent(), true);
127
128
        $userbadge = R::dispense('userbadge');
129
        $userbadge->user = $id;
130
        $userbadge->badge = $data['id'];
131
        $userbadge->inserttime = date($this->DATE_FORMAT);
132
        $userbadge->updatetime = date($this->DATE_FORMAT);
133
        $id = R::store($userbadge);
134
135
        $res = (object)["id" => $id];
136
        $headers = [];
137
        return JsonResponse::create($res, 200, $headers)->setSharedMaxAge(300);
138
    }
139
140
    public function getBadge($id, $id_badge, Request $request)
141
    {
142
        $badge = R::findOne('userbadgecomplete', 'WHERE user = ? AND badge = ?', [$id, $id_badge]);
143
        $res = [
144
                    'badge'=>[
145
                        'id'=>intval($badge['badge']),
146
                        'name'=>$badge['name'],
147
                        'description'=>$badge['description'],
148
                        'img'=>$badge['img']
149
                    ],
150
                    'clove'=>intval($badge['clove']),
151
                    'completed'=>boolval($badge['completed'])
152
                ];
153
        $headers = [];
154
        return JsonResponse::create($res, 200, $headers)->setSharedMaxAge(300);
155
    }
156
    public function markBadgeAsCompleted($id, $id_badge, Request $request) {
157
        $userbadge = R::findOne('userbadge', "WHERE user = ? AND badge = ?", [$id, $id_badge]);
158
        $userbadge->user = $id;
159
        $userbadge->badge = $id_badge;
160
        $userbadge->updatetime = date($this->DATE_FORMAT);
161
        $userbadge->completed = 1;
162
        $id = R::store($userbadge);
0 ignored issues
show
Unused Code introduced by
$id is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
163
        $headers = [];
0 ignored issues
show
Unused Code introduced by
$headers is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
164
        $response = new Response();
165
        $response->headers->set('Content-Type', 'text/html');
166
        $response->setStatusCode(Response::HTTP_NO_CONTENT);
167
        $response->setSharedMaxAge(300);
168
        return $response;
169
    }
170
    public function deleteUserBadge($id, $id_badge, Request $request) {
171
        $userbadge = R::load('userbadge', $id_badge);
172
        $userbadge->deleted = 1;
173
        $userbadge->updatetime = date($this->DATE_FORMAT);
174
        $id = R::store($userbadge);
0 ignored issues
show
Unused Code introduced by
$id is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
175
        $headers = [];
0 ignored issues
show
Unused Code introduced by
$headers is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
176
        $response = new Response();
177
        $response->headers->set('Content-Type', 'text/html');
178
        $response->setStatusCode(Response::HTTP_NO_CONTENT);
179
        $response->setSharedMaxAge(300);
180
        return $response;
181
    }
182
    public function getTicket($id, Request $request) {
183
        $ticketRaw = R::findAll('ticket', 'WHERE user = ? AND (NOT status = "closed")', [$id]);
184
185
        $tickets = [];
186
        foreach ($ticketRaw as $ticket) {
187
            array_push($tickets, [
188
                "id"=>intval($ticket['id']),
189
                "message"=>$ticket['message'],
190
                "url"=>$ticket['url'],
191
                "priority"=>$ticket['priority']
192
            ]);
193
        }
194
195
        $headers = [];
196
        return JsonResponse::create($tickets, 200, $headers)->setSharedMaxAge(300);
197
    }
198
}
199