Completed
Push — master ( 96fdaa...0a9a0f )
by vistart
06:12
created

RestModuleTrait::transRouteToName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 0
loc 4
rs 10
c 1
b 0
f 1
ccs 0
cts 2
cp 0
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
3
/**
4
 *  _   __ __ _____ _____ ___  ____  _____
5
 * | | / // // ___//_  _//   ||  __||_   _|
6
 * | |/ // /(__  )  / / / /| || |     | |
7
 * |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link http://vistart.name/
9
 * @copyright Copyright (c) 2016 vistart
10
 * @license http://vistart.name/license/
11
 */
12
13
namespace vistart\Models\traits;
14
15
/**
16
 * This trait is used for building module with RESTful API.
17
 *
18
 * @version 2.0
19
 * @author vistart <[email protected]>
20
 */
21
trait RestModuleTrait
22
{
23
24
    /**
25
     * This event will move response data into array which contains `success` and
26
     * `data` elements, and replace status code with 200.
27
     * @param \yii\base\Event $event
28
     */
29
    protected function responseBeforeSend($event)
30
    {
31
        $response = $event->sender;
32
        /* @var $response \yii\web\Response */
33
        if ($response->data !== null) {
34
            // Clear the 'type' property in all responses.
35
            if (isset($response->data['type'])) {
36
                unset($response->data['type']);
37
            }
38
            $response->data = [
39
                'success' => $response->isSuccessful,
40
                'data' => $response->data
41
            ];
42
            $response->statusCode = 200;
43
        }
44
    }
45
46
    /**
47
     * replace '_' with '/'.
48
     * @param string $route
49
     * @return string 
50
     */
51
    public static function transRouteToName($route)
52
    {
53
        return str_replace('/', '_', $route);
54
    }
55
56
    /**
57
     * Get API name.
58
     * @param string $route
59
     * @return string
60
     */
61
    public static function getApiName($route)
62
    {
63
        return 'api_' . self::transRouteToName($route);
64
    }
65
66
    public static function getApiRateLimiterName($route)
67
    {
68
        return static::getApiName($route) . '_ratelimiter';
69
    }
70
}
71