Completed
Push — master ( e7a469...59da10 )
by Sergio
02:23
created

HitCounterService::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 2
dl 0
loc 7
ccs 5
cts 5
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace coderius\hitCounter\services;
4
5
use Yii;
6
use yii\base\Component;
7
use yii\di\Instance;
8
use coderius\hitCounter\Module;
9
use coderius\hitCounter\components\deviceDetect\IDeviceDetect;
10
use yii\web\Request;
11
use coderius\hitCounter\traits\RequestTrait;
12
use coderius\hitCounter\models\HitCounterModel;
13
use coderius\hitCounter\repositories\HitCounterRepository;
14
use yii\helpers\Inflector;
15
use yii\base\InvalidConfigException;
16
use yii\helpers\StringHelper;
17
use coderius\hitCounter\entities\HitCounter;
18
use yii\helpers\ArrayHelper;
19
use coderius\hitCounter\dto\HitDTO;
20
use yii\web\BadRequestHttpException;
21
22
23
class HitCounterService extends Component{
24
25
    use RequestTrait;
26
27
    private $deviceDetector;
28
    private $repoHitCounter;
29
30 12
    public function __construct(IDeviceDetect $dd, HitCounterRepository $hcr,  $config = [])
31
    {
32 12
        $this->deviceDetector = $dd;
33 12
        $this->repoHitCounter = $hcr;
34 12
        parent::__construct($config);
35
        
36 12
    }
37
38 3
    public function create(HitCounterModel $model, string $entityClass = HitCounter::class): HitCounter
39
    {
40 3
        $dto = (new HitCounterModelDtoAssembler())->writeDto($model);//dto
41 3
        $hit = (new HitCounterDtoAssembler($entityClass))->readDto($dto);
42
43 3
        $this->repoHitCounter->save($hit);
44 3
        return $hit;
45
    }
46
    
47 6
    public function loadModel(Request $request)
48
    {
49 6
        $model = new HitCounterModel();
50 6
        $model->setAttributes($this->detectJsVisitInfo($request));
51 3
        $model->setAttributes($this->detectServerVisitInfo($request));
52 3
        return $model;
53
    }
54
55 6
    private function detectJsVisitInfo(Request $request)
56
    {
57 6
        $array = $request->get();
58 6
        $data = [];
59
        
60 6
        if(isset($array['i'])){
61 3
            $data['counter_id']         = $array['i'];
62 3
            $data['js_cookei_enabled']  = ArrayHelper::getValue($array, 'c', 0);
63 3
            $data['js_java_enabled']    = ArrayHelper::getValue($array, 'j', 0);
64 3
            $data['js_timezone_offset'] = ArrayHelper::getValue($array, 't');
65 3
            $data['js_timezone']        = ArrayHelper::getValue($array, 'tz');
66 3
            $data['js_connection']      = ArrayHelper::getValue($array, 'cnt');
67 3
            $data['js_current_url']     = ArrayHelper::getValue($array, 'u');
68 3
            $data['js_referer_url']     = ArrayHelper::getValue($array, 'r');
69 3
            $data['js_screen_width']    = ArrayHelper::getValue($array, 'w');
70 3
            $data['js_screen_height']   = ArrayHelper::getValue($array, 'h');
71 3
            $data['js_color_depth']     = ArrayHelper::getValue($array, 'd');
72 3
            $data['js_browser_language']= ArrayHelper::getValue($array, 'lg');
73 3
            $data['js_history_length']  = ArrayHelper::getValue($array, 'hl');
74 3
            $data['js_is_toutch_device']= ArrayHelper::getValue($array, 'td', 0);
75 3
            $data['js_processor_ram']   = ArrayHelper::getValue($array, 'ram');
76
77 3
            return $data;
78
        }else{
79 3
           throw new BadRequestHttpException('required get param "i" cannot be empty.'); 
80
        }
81
82
    }   
83
    
84 3
    private function detectServerVisitInfo(Request $request)
85
    {
86
        // $request = Yii::$app->request;
87 3
        $data = [];
88
89
        //Common user data
90 3
        $data['serv_ip']             = $request->getUserIP();
91 3
        $data['serv_user_agent']     = $request->getUserAgent();
92 3
        $data['serv_referer_url']    = $request->getReferrer();
93 3
        $data['serv_server_name']    = $request->getServerName();
94 3
        $data['serv_auth_user_id']   = \Yii::$app->user->isGuest ? null : Yii::$app->user->identity->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface yii\web\IdentityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
95
        
96 3
        $data['serv_port']           = $request->getPort();
97 3
        $data['serv_cookies']        = \yii\helpers\Json::encode($request->getCookies());
98
99
        //Device detect
100 3
        $data['serv_os']     = \yii\helpers\Json::encode($this->deviceDetector->getOs());
101 3
        $data['serv_client'] = \yii\helpers\Json::encode($this->deviceDetector->getClient());
102 3
        $data['serv_device'] = $this->deviceDetector->getDeviceName();
103 3
        $data['serv_brand']  = $this->deviceDetector->getBrandName();
104 3
        $data['serv_model']  = $this->deviceDetector->getModel();
105 3
        $data['serv_bot']    = $this->deviceDetector->getBot();
106
107
        //Organizacion provider detect
108 3
        $data['serv_host_by_ip'] = $this->getHostByAddr();
109 3
        $data['serv_is_proxy_or_vpn'] = (int)$this->isProxyVisit();
110
111
        //Set mark cookie
112 3
        $data['cookie_mark'] = static::pastCookieMark();
113
114 3
        return $data;
115
        
116
    }
117
118 3
    private static function pastCookieMark()
119
    {
120 3
        $request = Yii::$app->request;
0 ignored issues
show
Documentation Bug introduced by
It seems like Yii::app->request can also be of type yii\web\Request. However, the property $request is declared as type yii\console\Request. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
121 3
        $response = Yii::$app->response;
0 ignored issues
show
Documentation Bug introduced by
It seems like Yii::app->response can also be of type yii\web\Response. However, the property $response is declared as type yii\console\Response. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
122
123 3
        $name = static::defaultNameCookieMark();
124
125 3
        if ($request->cookies->has($name)){
126
            return $request->cookies->getValue($name);
127
        }else{
128 3
            $str = Yii::$app->getSecurity()->generateRandomString();
129
            
130
            // add to HTTP
131 3
            $response->cookies->add(new \yii\web\Cookie([
132 3
                'name'  => $name,
133 3
                'value' => $str,
134
            ]));
135
136 3
            return $str;    
137
        }
138
        // throw new InvalidConfigException('Invalid actual name "' . gettype($actualName) . '" specified at "' . get_class($this) . '::normalizeUserAttributeMap"');
139
    }
140
141 6
    public static function defaultNameCookieMark()
142
    {
143 6
        return Inflector::camel2id(StringHelper::basename(__CLASS__));
144
    }
145
146
}