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

examples/Metrica/Management/delegates.php (1 issue)

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: naxel
4
 * Date: 17.02.14 12:41
5
 */
6
use Yandex\Metrica\Management\ManagementClient;
7
8
$delegates = array();
9
$errorMessage = false;
10
11
//Is auth
12 View Code Duplication
if (isset($_COOKIE['yaAccessToken']) && isset($_COOKIE['yaClientId'])) {
13
    $settings = require_once '../../settings.php';
14
15
    try {
16
        $managementClient = new ManagementClient($_COOKIE['yaAccessToken']);
17
18
        //GET /delegates
19
        /**
20
         * @see http://api.yandex.ru/metrika/doc/beta/management/delegates/delegates.xml
21
         */
22
        $delegates = $managementClient->delegates()->getDelegates();
23
    } catch (\Exception $ex) {
24
        $errorMessage = $ex->getMessage();
25
        if ($errorMessage === 'PlatformNotAllowed') {
26
            $errorMessage .= '<p>Возможно, у приложения нет прав на доступ к ресурсу. Попробуйте '
27
                . '<a href="' . rtrim(str_replace($_SERVER['DOCUMENT_ROOT'], '', __DIR__), "/") . '/../OAuth/' . '">авторизироваться</a> и повторить.</p>';
28
        }
29
        echo $errorMessage;
30
    }
31
} ?>
32
33
<!doctype html>
34
<html lang="en-US">
35
<head>
36
    <meta charset="UTF-8">
37
    <title>Yandex.SDK: Metrica Demo</title>
38
39
    <link rel="stylesheet" href="//yandex.st/bootstrap/3.0.3/css/bootstrap.min.css">
40
    <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
41
    <link rel="stylesheet" href="/examples/Disk/css/style.css">
42
43
</head>
44
<body>
45
46
<div class="container">
47
    <div class="jumbotron">
48
        <h2><a href="/examples/Metrica"><span class="glyphicon glyphicon-tasks"></span></a> Пример работы с Яндекс Метрикой</h2>
49
    </div>
50
    <ol class="breadcrumb">
51
        <li><a href="/examples">Examples</a></li>
52
        <li><a href="/examples/Metrica">Metrica</a></li>
53
        <li class="active">Delegates</li>
54
    </ol>
55
    <?php
56 View Code Duplication
    if (!isset($_COOKIE['yaAccessToken']) || !isset($_COOKIE['yaClientId'])) {
57
        ?>
58
        <div class="alert alert-info">
59
            Для просмотра этой страницы вам необходимо авторизироваться.
60
            <a id="goToAuth" href="/examples/OAuth" class="alert-link">Перейти на страницу авторизации</a>.
61
        </div>
62
    <?php
63
    } else {
64
        if ($errorMessage) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errorMessage of type string|false 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...
65
            ?>
66
            <div class="alert alert-danger"><?= $errorMessage ?></div>
67
        <?php
68
        } else {
69
            ?>
70
            <div>
71
                <h3>Представители:</h3>
72
                <table id="delegatesTable" class="table table-striped table-bordered table-hover">
73
                    <thead>
74
                    <tr>
75
                        <td>Пользователь</td>
76
                        <td>Дата создания</td>
77
                        <td>Комментарий</td>
78
                    </tr>
79
                    </thead>
80
                    <tbody>
81
                    <?php
82
                    if ($delegates instanceof Traversable) {
83
                        foreach ($delegates as $delegate) {
84
                            ?>
85
                            <tr data-user-login="<?= $delegate->getUserLogin() ?>">
86
                                <td><?= $delegate->getUserLogin() ?></td>
87
                                <td><?= $delegate->getCreatedAt() ?></td>
88
                                <td><?= $delegate->getComment() ?></td>
89
                                <td style="text-align: center">
90
                                    <button type="button" class="btn btn-danger deleteDelegate">
91
                                            <span title="Удалить"
92
                                                  class="glyphicon glyphicon-trash"></span>
93
                                    </button>
94
                                </td>
95
                            </tr>
96
97
                        <?php
98
                        }
99
                    }
100
                    ?>
101
                    </tbody>
102
                </table>
103
                <button id="openAddDelegateModal" type="button" class="btn btn-success">
104
                        <span title="Добавить представителя"
105
                              class="glyphicon glyphicon-plus"> Добавить представителя</span>
106
                </button>
107
            </div>
108
        <?php
109
        }
110
    }
111
    ?>
112
</div>
113
114
<!-- Modal -->
115
<div class="modal fade" id="errorModal" tabindex="-1" role="dialog" aria-hidden="true">
116
    <div class="modal-dialog">
117
        <div class="modal-content">
118
            <div class="modal-header">
119
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
120
                <h4 class="modal-title">Ошибка</h4>
121
            </div>
122
            <div class="modal-body">
123
                <div id="errorMessage"></div>
124
            </div>
125
            <div class="modal-footer">
126
                <button type="button" class="btn btn-default" data-dismiss="modal">Закрыть</button>
127
            </div>
128
        </div>
129
    </div>
130
</div>
131
132
133
<!-- Modal -->
134
<div class="modal fade" id="addDelegateModal" tabindex="-1" role="dialog" aria-hidden="true">
135
    <div class="modal-dialog">
136
        <div class="modal-content">
137
            <div class="modal-header">
138
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
139
                <h4 class="modal-title">Добавление представителя</h4>
140
            </div>
141
            <div class="modal-body">
142
                <form class="form-horizontal" role="form">
143
                    <div class="form-group">
144
                        <label for="addDelegateUserLogin" class="col-sm-2 control-label">Пользователь</label>
145
146
                        <div class="col-sm-10">
147
                            <input type="text" class="form-control" id="addDelegateUserLogin" placeholder="Пользователь">
148
                        </div>
149
                    </div>
150
                    <div class="form-group">
151
                        <label for="addDelegateCreateAt" class="col-sm-2 control-label">Дата создания</label>
152
153
                        <div class="col-sm-10">
154
                            <input type="text" class="form-control" id="addDelegateCreateAt" placeholder="Дата создания">
155
                        </div>
156
                    </div>
157
                    <div class="form-group">
158
                        <label for="addDelegateComment" class="col-sm-2 control-label">Комментарий</label>
159
160
                        <div class="col-sm-10">
161
                            <input type="text" class="form-control" id="addDelegateComment" placeholder="Комментарий">
162
                        </div>
163
                    </div>
164
                </form>
165
            </div>
166
            <div class="modal-footer">
167
                <button type="button" class="btn btn-default" data-dismiss="modal">Закрыть</button>
168
                <button type="button" id="createDelegate" class="btn btn-primary">Добавить</button>
169
            </div>
170
        </div>
171
    </div>
172
</div>
173
174
175
<!-- Modal -->
176
<div class="modal fade" id="deleteDelegateModal" tabindex="-1" role="dialog" aria-hidden="true">
177
    <div class="modal-dialog">
178
        <div class="modal-content">
179
            <div class="modal-header">
180
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
181
                <h4 class="modal-title">Удалить представителя?</h4>
182
            </div>
183
            <div class="modal-body">
184
                <input type="hidden" id="deleteDelegateUserLogin">
185
            </div>
186
            <div class="modal-footer">
187
                <button type="button" class="btn btn-default" data-dismiss="modal">Отмена</button>
188
                <button type="button" id="deleteDelegate" class="btn btn-danger">Удалить!</button>
189
            </div>
190
        </div>
191
    </div>
192
</div>
193
194
<script src="http://yandex.st/jquery/2.0.3/jquery.min.js"></script>
195
<script src="http://yandex.st/jquery/cookie/1.0/jquery.cookie.min.js"></script>
196
<script src="http://yandex.st/bootstrap/3.0.3/js/bootstrap.min.js"></script>
197
198
<script>
199
$(function () {
200
201
    $('#goToAuth').click(function (e) {
202
        $.cookie('back', location.href, { expires: 256, path: '/' });
203
    });
204
205
    var $delegatesTable = $("#delegatesTable");
206
207
    $('#openAddDelegateModal').click(function () {
208
        $('#addDelegateModal').modal('show');
209
    });
210
211
    $delegatesTable.on('click', '.deleteDelegate', function () {
212
        var $el = $(this);
213
        var userLogin = $el.parents('tr').data('user-login');
214
        $('#deleteDelegateUserLogin').val(userLogin);
215
        $('#deleteDelegateModal').modal('show');
216
    });
217
218
219
    $('#createDelegate').click(function () {
220
        var userLogin = $.trim($('#addDelegateUserLogin').val());
221
        var createAt = $.trim($('#addDelegateCreateAt').val());
222
        var comment = $.trim($('#addDelegateComment').val());
223
224
        if (userLogin.length === 0 || createAt.length === 0) {
225
            alert('Заполните поле пользователь и/или дата создания.');
226
        }
227
228
        $.post(
229
            "/examples/Metrica/api.php",
230
            {
231
                method: 'addDelegate',
232
                userLogin: userLogin,
233
                createAt: createAt,
234
                comment: comment
235
            },
236
            function (data) {
237
                $('#addDelegateModal').modal('hide');
238
239
                var response = JSON.parse(data);
240
                if (response.status === 'ok' && response.result !== null) {
241
242
                    var html = '\
243
                            <tr data-user-login="' + response.result.user_login + '">\
244
                                <td>' + response.result.user_login + '</td>\
245
                                <td>' + response.result.create_at + '</td>\
246
                                <td>' + response.result.comment + '</td>\
247
                                <td style="text-align: center">\
248
                                    <button type="button" class="btn btn-danger deleteDelegate">\
249
                                            <span title="Удалить" class="glyphicon glyphicon-trash"></span>\
250
                                    </button>\
251
                                </td>\
252
                            </tr>';
253
254
                    $delegatesTable.find('tbody').append(html);
255
256
257
                } else {
258
                    displayError(response.message);
259
                }
260
            }
261
        );
262
    });
263
264
265
    $('#deleteDelegate').click(function () {
266
267
        var userLogin = $.trim($('#deleteDelegateUserLogin').val());
268
        $.post(
269
            "/examples/Metrica/api.php",
270
            {
271
                method: 'deleteDelegate',
272
                userLogin: userLogin
273
            },
274
            function (data) {
275
276
                $('#deleteDelegateModal').modal('hide');
277
278
                var response = JSON.parse(data);
279
                if (response.status === 'ok' && response.result !== null) {
280
281
                    $delegatesTablefind('tbody>tr').each(function () {
282
                        if ($(this).data('user-login') == response.result.user_login) {
283
                            $(this).replaceWith('');
284
                        }
285
                    });
286
287
                } else {
288
                    displayError(response.message);
289
                }
290
            }
291
        );
292
    });
293
294
});
295
296
297
/**
298
 * @param message string
299
 */
300
function displayError(message) {
301
    $('#errorMessage').text(message);
302
    $('#errorModal').modal('show');
303
}
304
305
</script>
306
</body>
307
</html>
308