Completed
Push — master ( 6d46d3...77c36b )
by Charles
03:52
created

Json25519ResponseFormatter::formatJson()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 65
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 0
Metric Value
c 6
b 0
f 0
dl 0
loc 65
rs 8.6195
cc 5
eloc 39
nc 5
nop 1

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
namespace yrc\web;
4
5
use yrc\web\JsonResponseFormatter;
6
use yii\web\NotAcceptableHttpException;
7
use yrc\web\Json25519Parser;
8
use yrc\models\redis\EncryptionKey;
9
use yii\web\HttpException;
10
11
use Yii;
12
13
class Json25519ResponseFormatter extends JsonResponseFormatter
14
{
15
    /**
16
     * Take the response generated by JsonResponseFormatter and anonymously encrypt it
17
     * @param array $response
18
     */
19
    protected function formatJson($response)
20
    {
21
        // Generate a new encryption key
22
        $key = EncryptionKey::generate();
23
        $public = Yii::$app->request->getHeaders()->get(Json25519Parser::PUBLICKEY_HEADER, null);
24
25
        if ($public === null) {
26
            $response->statusCode = 400;
27
            $response->content = '';
28
            $response->getHeaders('x-reason', Yii::t('yrc', 'Accept: application/vnd.25519+json requires x-pubkey header to be set.'));
0 ignored issues
show
Bug introduced by
The method getHeaders cannot be called on $response (of type array).

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...
29
            return;
30
        }
31
32
        $rawPublic = \base64_decode($public);
33
        if (strlen($rawPublic) !== 32) {
34
            $response->statusCode = 400;
35
            $response->getHeaders()->set('x-reason', Yii::t('yrc', 'Public key is not 32 bytes in length.'));
0 ignored issues
show
Bug introduced by
The method getHeaders cannot be called on $response (of type array).

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...
36
            return;
37
        }
38
39
        parent::formatJson($response);
0 ignored issues
show
Documentation introduced by
$response is of type array, but the function expects a object<yrc\web\Response>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
40
        $response->getHeaders()->set('Content-Type', 'application/vnd.25519+json; charset=UTF-8');
0 ignored issues
show
Bug introduced by
The method getHeaders cannot be called on $response (of type array).

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...
41
42
        // Calculate the keypair
43
        $keyPair = \sodium_crypto_box_keypair_from_secretkey_and_publickey(
44
            \base64_decode($key->secret),
0 ignored issues
show
Documentation introduced by
The property secret does not exist on object<yrc\models\redis\EncryptionKey>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
45
            $rawPublic
46
        );
47
48
        // Encrypt the content
49
        $nonce = \random_bytes(SODIUM_CRYPTO_BOX_NONCEBYTES);
50
        $content = \sodium_crypto_box(
51
            $response->content,
52
            $nonce,
53
            $keyPair
54
        );
55
56
        // If the user is authenticated, we can sign the request using the signature associated to the session.
57
        // If they are not authenticated, we can skip the signature generation
58
        if (!Yii::$app->user->isGuest) {
59
            $token = Yii::$app->user->getIdentity()->getToken();
60
            if ($token === null) {
61
                $response->statusCode = 406;
62
                $response->content = '';
63
                Yii::warning([
64
                    'message' => 'Could not fetch token keypair. Unable to generate encrypted response.'
65
                ]);
66
                return;
67
            }
68
69
            // Sign the request using the new authentication key
70
            $signature = \sodium_crypto_sign_detached(
71
                $content,
72
                \base64_decode($token->secret_sign_kp)
73
            );
74
75
            // Sign the raw response and send the signature alongside the header
76
            $response->getHeaders()->set('x-sigpubkey', \base64_encode($token->getSignPublicKey()));
0 ignored issues
show
Bug introduced by
The method getHeaders cannot be called on $response (of type array).

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...
77
            $response->getHeaders()->set('x-signature', \base64_encode($signature));
0 ignored issues
show
Bug introduced by
The method getHeaders cannot be called on $response (of type array).

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...
78
        }
79
80
        $response->getHeaders()->set('x-nonce', \base64_encode($nonce));
0 ignored issues
show
Bug introduced by
The method getHeaders cannot be called on $response (of type array).

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...
81
        $response->getHeaders()->set('x-pubkey', \base64_encode($key->getBoxPublicKey()));
0 ignored issues
show
Bug introduced by
The method getHeaders cannot be called on $response (of type array).

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...
82
        $response->content = \base64_encode($content);
83
    }
84
}
85