HOME FORUMS MEMBERS RECENT POSTS LOG IN  
× Авторизация
Имя пользователя:
Пароль:
Нет аккаунта? Регистрация
Баннер 1   Баннер 2
НОВЫЕ ТОРГОВАЯ НОВОСТИ ЧАТ
loading...
Скрыть
Вернуться   ANTICHAT > ПРОГРАММИРОВАНИЕ > Общие вопросы программирования
   
 
 
Опции темы Поиск в этой теме Опции просмотра

  #1  
Старый 28.10.2019, 13:01
Desquire
Познавший АНТИЧАТ
Регистрация: 07.05.2015
Сообщений: 1,791
С нами: 5799746

Репутация: 1388


По умолчанию

На прошлой неделе был мини диалог с один из уважаемых людей, который так или иначе связан с пхп.

Мне был отплавен код ниже.

Так как у меня чсв не маленькое, я и ответил - о это полный ппц, тут рефакторить почти все... и в твоих интересах этот код больше не кому не показывать.

Мне отетили - это типо для второй менее важной части, должно работать на калькуляторе, за чистоту я не парился. И мол покажи мастер класс на на примере этого класса как надо...

Ну а что, я простой друпал девелепер с хорошим чсв... Х*ли нет, когда да?

Цитата:
Сообщение от Спойлер  


PHP:


Код:
session_id = $session_id;
        if ($sid !== false)
            $this->sid = $sid;
        if ($pid !== false)
            $this->project_id = $pid;
    }

    public function set_session($session_id){

        $this->session_id = $session_id;

    }

    /*
     *  Метод авторизации
     *  $email - Принемает емаил
     *  $password - Принемает пароль
     *  $remember - Запомнить пользователя, сессия продливается на 3 месяца
     *  $utm_source - источник входа
     *  $id_promo - ид промо бонуса
     *  $promo_bonus - бонусы выбранные пользователем
     *
     */

    public function login($email, $password, $remember = 'on', $utm_source = 'APPLICATION', $id_promo = 0, $promo_bonus = array()){
        $this->act = 'login';
        $this->method = 'Linage2AccountsAuth';
        $this->data = array(
            'login-email' => $email,
            'login-password' => $password,
            'utm_source' => $utm_source,
            'promo' => $id_promo,
            'promo_bonus' => $promo_bonus,
            'login-remember-me' => $remember,
        );

        return $this;
    }

    public function forgot($email){
        $this->act = 'forgot';
        $this->method = 'Linage2AccountsAuth';
        $this->data = array(
            'reminder-email' => $email,
        );

        return $this;
    }

    public function subscription($email){
        $this->act = 'subscription';
        $this->method = 'Linage2AccountsAuth';
        $this->data = array(
            'subscription-email' => $email,
        );

        return $this;
    }

    public function register($prefix, $login, $email, $password, $password_verify, $referal = '', $utm_source = 'APPLICATION', $id_promo = 0, $promo_bonus = array()){
        $this->act = 'register';
        $this->method = 'Linage2AccountsAuth';
        $this->data = array(
            'register-account' => $prefix . $login,
            'register-email' => $email,
            'register-password' => $password,
            'register-password-verify' => $password_verify,
            'register-referal' => $referal,
            'utm_source' => $utm_source,
            'promo' => $id_promo,
            'promo_bonus' => $promo_bonus,
        );

        return $this;
    }

    public function create_game_account($prefix, $login, $password, $password_verify,  $utm_source = 'APPLICATION'){
        $this->act = 'create_game_account';
        $this->method = 'Linage2AccountsAuth';
        $this->data = array(
            'register-account' => $prefix . $login,
            'register-password' => $password,
            'register-password-verify' => $password_verify,
            'utm_source' => $utm_source,
        );

        return $this;
    }

    public function change_password_game_account($login, $password_old, $password_new,  $password_verify, $pin){
        $this->act = 'change_password_game_account';
        $this->method = 'Linage2AccountsAuth';
        $this->data = array(
            'change-password-account' => $login,
            'change-password-old' => $password_old,
            'change-password-new' => $password_new,
            'change-password-verify' => $password_verify,
            'change-password-pin' => $pin,
        );

        return $this;
    }

    public function game_account_teleport_char($login, $char_id){
        $this->act = 'game_account_teleport_char';
        $this->method = 'Linage2AccountsAuth';
        $this->data = array(
            'teleport-account' => $login,
            'teleport-char' => $char_id,

        );

        return $this;
    }

    public function recovery_password_game_account($login, $pin){

        $this->act = 'recovery_password_game_account';
        $this->method = 'Linage2AccountsAuth';
        $this->data = array(
            'recovery-password-account' => $login,
            'recovery-password-pin' => $pin,

        );

        return $this;
    }

    public function change_password_ma($password_new, $password_old, $password_old_verify,  $pin){
        $this->act = 'recovery_pin';
        $this->method = 'Linage2AccountsAuth';
        $this->data = array(
            'change-password-old' => $password_new,
            'change-password-new' => $password_old,
            'change-password-verify' => $password_old_verify,
            'change-password-pin' => $pin,
        );

        return $this;
    }

    public function recovery_pin(){
        $this->act = 'recovery_pin';
        $this->method = 'Linage2AccountsAuth';
        $this->data = array(
            'action' => 'recovery-pin',
        );

        return $this;
    }

    public function disabled_hwid($login,  $pin){
        $this->act = 'disabled_hwid';
        $this->method = 'Linage2AccountsAuth';
        $this->data = array(
            'disabled-hwid-account' => $login,
            'disabled-hwid-pin' => $pin,
        );

        return $this;
    }

    public function pin_enable(){
        $this->act = 'pin_systems';
        $this->method = 'Linage2AccountsAuth';
        $this->data = array(
            'action' => 'pin_enable',
        );

        return $this;
    }

    public function pin_disabled($pin){
        $this->act = 'pin_systems';
        $this->method = 'Linage2AccountsAuth';
        $this->data = array(
            'action' => 'pin_disabled',
            'change-disabled-pin' => $pin,
        );

        return $this;
    }

    public function balance_update(){
        $this->act = 'balance_update';
        $this->method = 'PaymentSystem';
        $this->data = array(
            'action' => 'balance_update',
        );

        return $this;
    }

    public function poll_msg($notice_id, $rating){
        $this->act = 'poll_msg';
        $this->method = 'NoticeSystem';
        $this->data = array(
            'notice_id' => $notice_id,
            'rating' => $rating,
        );

        return $this;
    }

    public function close_msg($notice_id){
        $this->act = 'close_msg';
        $this->method = 'NoticeSystem';
        $this->data = array(
            'notice_id' => $notice_id,
        );

        return $this;
    }

    public function select_language($lang = 'rus'){
        $this->act = 'select_language';
        $this->method = 'Linage2AccountsAuth';
        $this->data = array(
            'lang' => $lang

        );

        return $this;
    }

    public function select_server($server_id){
        $this->act = 'select_server';
        $this->method = 'Linage2AccountsAuth';
        $this->data = array(
            'server' => $server_id
        );

        return $this;
    }

    //Примечание если бонус код выдается на персонажа, в окне вода выводим строчки с выбором персонажа, ответ будет таким$reply['action'] == 'show_account'
    public function bonus_code($code, $account_id = 0, $char_id = 0){
        $this->act = 'activation';
        $this->method = 'BonusCod';
        $this->data = array(
            'bonus-cod' => $code,
            'account' => $account_id,
            'char' => $char_id,
        );

        return $this;
    }

    public function get_rating(){
        $this->act = 'getRating';
        $this->method = 'GameRating';
        $this->data = array(
            'temp' => 0
        );

        return $this;
    }

    public function send(){

        $Params = array(
            'act' => $this->act,
            'method' => $this->method,
            'pid' => $this->project_id,
            'data' => $this->data,
            'time' => time(),
            'gzc' => $this->gzc,
            'ip' => '127.0.0.1', //ип пользователя
            'secret_key' => $this->secret_key,
            'sid' => $this->sid,
            'user' => array(
                'name' => 'updater',
                'platform' => 'desktop',
            ),
        );

        if ($this->session_id !== false)
            $Params['session'] = $this->session_id;

        # Формируем параметры и создаем секретный ключ
        $Params = array_merge(
            array(
                "api_key" => hash("sha512", json_encode($Params) . "|" . $this->key)
            ),
            $Params
        );

        $Params = array("POST" => json_encode($Params));

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->api_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($Params));
        $response = curl_exec($ch);

        if($this->gzc)
            $POST = json_decode(@gzuncompress($response) ,true);
        else
            $POST = json_decode($response,true);

        return $POST;
    }

}
Добавлю чуть инфы - я друпал дев, у нас свои кодинг стандарты.

Поэтому это все что дальше будет в теме, мое личое виденье и на правильность и адекватность не претендует.

Ближе к делу...

Часть \ пример 1:

У нас есть работающие приложение, в котором нужно привести в орядок ТОЛЬКО этот класс.

Логику мы НЕ меняем, только косметика.

Коментарии отсутсвуют, если мы ее знаем все приложение, то работать будет очень тяжело.

Пример пары методов с коментариями.

Цитата:
Сообщение от Спойлер  


PHP:


Код:
/**
* Set session Id.
*
* @param string $session_id
*   Session Id.
*/
public
function
set_session
(
$session_id
)
{
$this
-
>
session_id
=
$session_id
;
}
/**
* Send request to our API.
*
* @return mixed
*  Decoded response.
*/
public
function
send
(
)
{
$params
=
[
'act'
=
>
$this
-
>
act
,
'method'
=
>
$this
-
>
method
,
'pid'
=
>
$this
-
>
project_id
,
'data'
=
>
$this
-
>
data
,
'time'
=
>
time
(
)
,
'gzc'
=
>
$this
-
>
gzc
,
'ip'
=
>
'127.0.0.1'
,
'secret_key'
=
>
$this
-
>
secret_key
,
'sid'
=
>
$this
-
>
sid
,
'user'
=
>
[
'name'
=
>
'updater'
,
'platform'
=
>
'desktop'
,
]
,
]
;
if
(
$this
-
>
session_id
!==
FALSE
)
{
$params
[
'session'
]
=
$this
-
>
session_id
;
}
$params
=
array_merge
(
[
"api_key"
=
>
hash
(
"sha512"
,
json_encode
(
$params
)
.
"|"
.
$this
-
>
key
)
,
]
,
$params
)
;
$params
=
[
"POST"
=
>
json_encode
(
$params
)
]
;
$ch
=
curl_init
(
)
;
curl_setopt
(
$ch
,
CURLOPT_URL
,
$this
-
>
api_url
)
;
curl_setopt
(
$ch
,
CURLOPT_RETURNTRANSFER
,
TRUE
)
;
curl_setopt
(
$ch
,
CURLOPT_POSTFIELDS
,
http_build_query
(
$params
)
)
;
$response
=
curl_exec
(
$ch
)
;
if
(
$this
-
>
gzc
)
{
return
json_decode
(
@
gzuncompress
(
$response
)
,
TRUE
)
;
}
else
{
return
json_decode
(
$response
,
TRUE
)
;
}
}
Часть 2: wtf is going on?

2.1

Что это за значения?

Под каждое новое приложение будет меняется код?

Код:


Код:
public $project_id = 25;
    public $method = 'Linage2AccountsAuth';
    public $secret_key = 'sdfsdaf4w3r34drfcde';
    public $key = '^28Yi7j+DzQeb';
    public $sid = 251;
    public $api_url = 'http://youApi.s0.someurl.ru/api';
Магические значения вообще вообще не ок.

Опять без пояснений кзначенияем.

2.2 Тут похоже классы ради видимости, и чтобы как-то сгруперовать функции. Так как единственная связть между ними это прокидываение екоьоры значенией.

Все.

В другой часте прилоеднеия испольузется аля

Код:
$api = new API_MMO(глобальные параметры)
$api->login(Куча параметром)
$result = $api->send();
2.3 Судя по всему, о композере и речи не идет...

Эх... зачем использовать отличные либы, когда можносделать костыли самому?

Зачем юзать Guzzle ... Есть же curl_init();

2.4

Шикарное кол-во аргументов.

У нас лимит 10. тут 9. Вроде влезле... Но...Может всетаки можно обойтись всего одним ?)

Код:
register($prefix, $login, $email, $password, $password_verify, $referal = '', $utm_source = 'APPLICATION', $id_promo = 0, $promo_bonus = array())
2.5 Хотел что-то написать про псар, но change_password_game_account и API_MMO

3 Тут должен быть вариант полного рефакторинга, и показать что все это з 300+ строк кода привратиться в 200, из которых 50 будуи коментраии...

Но я ленивая жопа, и друпал разраб, код писать не для меня.

In the end...

Ребят, пишите красивый код Старайтесь читать что-то новое,

Автору первоначального кода, я знаю ты прочитаешь - jupeter/clean-code-php

@kick @Logan22 Знаю вы шарите, особенно в новых версиях пыхи, что подскажите ?)
 
Ответить с цитированием
 





Здесь присутствуют: 1 (пользователей: 0 , гостей: 1)
 


Быстрый переход




ANTICHAT ™ © 2001- Antichat Kft.

×

Внести депозит

Введите сумму USDT:

Принимается только USDT TRC20. Fake/Flash USDT не засчитывается.

×

Вывести депозит

Сумма USDT:

Ваш USDT TRC20 кошелек:

Заявка будет отправлена администратору.