Completed
Push — master ( 1dc1a5...f8d9f6 )
by Anton
10s
created

examples/Metrica/Management/accounts.php (3 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * User: Tanya Kalashnik
4
 * Date: 15.07.14 18:18
5
 */
6
7
use Yandex\Metrica\Management\ManagementClient;
8
9
10
$accounts = array();
11
$errorMessage = false;
12
13
//Is auth
14 View Code Duplication
if (isset($_COOKIE['yaAccessToken']) && isset($_COOKIE['yaClientId'])) {
0 ignored issues
show
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...
15
    $settings = require_once '../../settings.php';
16
17
18
    try {
19
        $managementClient = new ManagementClient($_COOKIE['yaAccessToken']);
20
21
        /**
22
         * @see http://api.yandex.ru/metrika/doc/beta/management/accounts/accounts.xml
23
         */
24
        $accounts = $managementClient->accounts()->getAccounts();
25
    } catch (\Exception $ex) {
26
        $errorMessage = $ex->getMessage();
27
        if ($errorMessage === 'PlatformNotAllowed') {
28
            $errorMessage .= '<p>Возможно, у приложения нет прав на доступ к ресурсу. Попробуйте '
29
                . '<a href="' . rtrim(str_replace($_SERVER['DOCUMENT_ROOT'], '', __DIR__), "/") . '/../OAuth/' . '">авторизироваться</a> и повторить.</p>';
30
        }
31
    }
32
}
33
?>
34
<!doctype html>
35
<html lang="en-US">
36
<head>
37
    <meta charset="UTF-8">
38
    <title>Yandex.SDK: Metrica Demo</title>
39
40
    <link rel="stylesheet" href="//yandex.st/bootstrap/3.0.3/css/bootstrap.min.css">
41
    <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
42
    <link rel="stylesheet" href="/examples/Disk/css/style.css">
43
44
</head>
45
<body>
46
47
<div class="container">
48
    <div class="jumbotron">
49
        <h2><a href="/examples/Metrica"><span class="glyphicon glyphicon-tasks"></span></a> Пример работы с Яндекс Метрикой</h2>
50
    </div>
51
    <ol class="breadcrumb">
52
        <li><a href="/examples">Examples</a></li>
53
        <li><a href="/examples/Metrica">Metrica</a></li>
54
        <li class="active">Accounts</li>
55
    </ol>
56
    <?php
57 View Code Duplication
    if (!isset($_COOKIE['yaAccessToken']) || !isset($_COOKIE['yaClientId'])) {
0 ignored issues
show
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...
58
        ?>
59
        <div class="alert alert-info">
60
            Для просмотра этой страницы вам необходимо авторизироваться.
61
            <a id="goToAuth" href="/examples/OAuth" class="alert-link">Перейти на страницу авторизации</a>.
62
        </div>
63
    <?php
64
    } else {
65
        if ($errorMessage) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errorMessage of type false|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
66
            ?>
67
            <div class="alert alert-danger"><?= $errorMessage ?></div>
68
        <?php
69
        } else {
70
            ?>
71
            <div>
72
                <h3>Аккаунты:</h3>
73
                <table id="accountTable" class="table table-striped table-bordered table-hover">
74
                    <thead>
75
                    <tr>
76
                        <td>Пользователь</td>
77
                        <td>Дата создания</td>
78
                    </tr>
79
                    </thead>
80
                    <tbody>
81
                    <?php
82
                    if ($accounts instanceof Traversable) {
83
                        foreach ($accounts as $account) {
84
                            ?>
85
                            <tr data-user-login="<?= $account->getUserLogin() ?>">
86
                                <td><?= $account->getUserLogin() ?></td>
87
                                <td><?= $account->getCreatedAt() ?></td>
88
                                <td style="text-align: center">
89
                                    <button type="button" class="btn btn-danger deleteAccount">
90
                                                <span title="Удалить"
91
                                                      class="glyphicon glyphicon-trash"></span>
92
                                    </button>
93
                                </td>
94
                            </tr>
95
96
                        <?php
97
                        }
98
                    }
99
                    ?>
100
                    </tbody>
101
                </table>
102
            </div>
103
        <?php
104
        }
105
    }
106
    ?>
107
</div>
108
109
<!-- Modal -->
110
<div class="modal fade" id="errorModal" tabindex="-1" role="dialog" aria-hidden="true">
111
    <div class="modal-dialog">
112
        <div class="modal-content">
113
            <div class="modal-header">
114
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
115
                <h4 class="modal-title">Ошибка</h4>
116
            </div>
117
            <div class="modal-body">
118
                <div id="errorMessage"></div>
119
            </div>
120
            <div class="modal-footer">
121
                <button type="button" class="btn btn-default" data-dismiss="modal">Закрыть</button>
122
            </div>
123
        </div>
124
    </div>
125
</div>
126
127
128
<!-- Modal -->
129
<div class="modal fade" id="deleteAccountModal" tabindex="-1" role="dialog" aria-hidden="true">
130
    <div class="modal-dialog">
131
        <div class="modal-content">
132
            <div class="modal-header">
133
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
134
                <h4 class="modal-title">Удалить аккаунт?</h4>
135
            </div>
136
            <div class="modal-body">
137
                <input type="hidden" id="deleteUserLogin">
138
            </div>
139
            <div class="modal-footer">
140
                <button type="button" class="btn btn-default" data-dismiss="modal">Отмена</button>
141
                <button type="button" id="deleteAccount" class="btn btn-danger">Удалить!</button>
142
            </div>
143
        </div>
144
    </div>
145
</div>
146
147
<script src="http://yandex.st/jquery/2.0.3/jquery.min.js"></script>
148
<script src="http://yandex.st/jquery/cookie/1.0/jquery.cookie.min.js"></script>
149
<script src="http://yandex.st/bootstrap/3.0.3/js/bootstrap.min.js"></script>
150
151
<script>
152
$(function () {
153
154
    $('#goToAuth').click(function (e) {
155
        $.cookie('back', location.href, { expires: 256, path: '/' });
156
    });
157
158
    var $accountTable = $("#accountTable");
159
160
    $accountTable.on('click', '.deleteAccount', function () {
161
        var $el = $(this);
162
        var userLogin = $el.parents('tr').data('user-login');
163
        $('#deleteCounterId').val(userLogin);
164
        $('#deleteAccountModal').modal('show');
165
    });
166
    
167
168
    $('#deleteAccount').click(function () {
169
170
        var userLogin = $.trim($('#deleteCounterId').val());
171
        $.post(
172
            "/examples/Metrica/api.php",
173
            {
174
                method: 'deleteAccount',
175
                userLogin: userLogin
176
            },
177
            function (data) {
178
179
                $('#deleteAccountModal').modal('hide');
180
181
                var response = JSON.parse(data);
182
                if (response.status === 'ok' && response.result !== null) {
183
184
                    $("#accountTable").find('tbody>tr').each(function () {
185
                        if ($(this).data('user-login') == response.result.id) {
186
                            $(this).replaceWith('');
187
                        }
188
                    });
189
190
                } else {
191
                    displayError(response.message);
192
                }
193
            }
194
        );
195
    });
196
197
});
198
199
200
/**
201
 * @param message string
202
 */
203
function displayError(message) {
204
    $('#errorMessage').text(message);
205
    $('#errorModal').modal('show');
206
}
207
208
</script>
209
</body>
210
</html>
211