Completed
Push — master ( 53c3c6...647838 )
by Xinjiang
03:18
created

Shorty   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 117
Duplicated Lines 10.26 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 12
loc 117
wmc 18
lcom 1
cbo 1
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getShortUrl() 0 21 3
A getLongUrl() 0 9 1
A generateId() 0 6 1
C alphaID() 12 68 12

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 Soleo\UrlShortener;
4
5
class Shorty
6
{
7
    private $conn;
8
9
    public function __construct(ConnectionInterface $conn)
10
    {
11
        $this->conn = $conn;
12
    }
13
14
    public function getShortUrl($longURL)
15
    {
16
        // validate Long URL first and normalize it
17
        if (strlen($longURL) <= 3) {
18
            throw new \InvalidArgumentException("URL is malformated!");
19
        }
20
        $currentDomain = "localhost";
21
        // Lookup
22
        $slug = $this->conn->reverseLookup($longURL);
23
24
        $fullURL = 'http://'.$currentDomain.'/';
25
        if ($slug) {
26
            return $fullURL.$slug;
27
        } else {
28
            // add new records to DB
29
            $slug = $this->generateId($longURL);
30
            var_dump($slug);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($slug); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
31
            $this->conn->addNewRecord($longURL, $slug);
32
            return $fullURL.$slug;
33
        }
34
    }
35
36
    public function getLongUrl($slug)
37
    {
38
        // filter out invalid string
39
       $slug = preg_replace('[^A_Za_z0-9]', '', $slug);
40
41
        $longURL = $this->conn->lookup($slug);
0 ignored issues
show
Bug introduced by
The call to lookup() misses a required argument $update.

This check looks for function calls that miss required arguments.

Loading history...
42
43
        return $longURL;
44
    }
45
46
    private function generateId($longURL)
0 ignored issues
show
Unused Code introduced by
The parameter $longURL 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...
47
    {
48
        $url_num_id = $this->conn->getIncrementUid();
49
        $slug = $this->alphaID($url_num_id);
50
        return $slug;
51
    }
52
53
    private function alphaID($in, $to_num = false, $pad_up = 3, $passKey = "prephe.ro")
54
    {
55
        $index = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
56
        if ($passKey !== null) {
57
            // Although this function's purpose is to just make the
58
            // ID short - and not so much secure,
59
            // with this patch by Simon Franz (http://blog.snaky.org/)
60
            // you can optionally supply a password to make it harder
61
            // to calculate the corresponding numeric ID
62
63
            for ($n = 0; $n<strlen($index); $n++) {
64
                $i[] = substr($index, $n, 1);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$i was never initialized. Although not strictly required by PHP, it is generally a good practice to add $i = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
65
            }
66
67
            $passhash = hash('sha256', $passKey);
68
            $passhash = (strlen($passhash) < strlen($index))
69
                ? hash('sha512', $passKey)
70
                : $passhash;
71
72
            for ($n=0; $n < strlen($index); $n++) {
73
                $p[] =  substr($passhash, $n, 1);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$p was never initialized. Although not strictly required by PHP, it is generally a good practice to add $p = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
74
            }
75
76
            array_multisort($p,  SORT_DESC, $i);
0 ignored issues
show
Bug introduced by
The variable $i 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...
77
            $index = implode($i);
78
        }
79
80
        $base  = strlen($index);
81
82
        if ($to_num) {
83
            // Digital number  <<--  alphabet letter code
84
            $in  = strrev($in);
85
            $out = 0;
86
            $len = strlen($in) - 1;
87
            for ($t = 0; $t <= $len; $t++) {
88
                $bcpow = bcpow($base, $len - $t);
89
                $out   = $out + strpos($index, substr($in, $t, 1)) * $bcpow;
90
            }
91
92 View Code Duplication
            if (is_numeric($pad_up)) {
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...
93
                $pad_up--;
94
                if ($pad_up > 0) {
95
                    $out -= pow($base, $pad_up);
96
                }
97
            }
98
            $out = sprintf('%F', $out);
99
            $out = substr($out, 0, strpos($out, '.'));
100
        } else {
101
            // Digital number  -->>  alphabet letter code
102 View Code Duplication
            if (is_numeric($pad_up)) {
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...
103
                $pad_up--;
104
                if ($pad_up > 0) {
105
                    $in += pow($base, $pad_up);
106
                }
107
            }
108
109
            $out = "";
110
            for ($t = floor(log($in, $base)); $t >= 0; $t--) {
111
                $bcp = bcpow($base, $t);
112
                $a   = floor($in / $bcp) % $base;
113
                $out = $out . substr($index, $a, 1);
114
                $in  = $in - ($a * $bcp);
115
            }
116
            $out = strrev($out); // reverse
117
        }
118
119
        return $out;
120
    }
121
}
122