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

examples/Metrica/Analytics/index.php (2 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: 28.07.14 11:13
5
 */
6
7
use Yandex\Metrica\Management\ManagementClient;
8
9
$counters = array();
10
$errorMessage = false;
11
12
//Is auth
13 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...
14
    $settings = require_once '../../settings.php';
15
16
    try {
17
        $managementClient = new ManagementClient($_COOKIE['yaAccessToken']);
18
19
        $paramsObj = new \Yandex\Metrica\Management\Models\CountersParams();
20
        $paramsObj
21
            /**
22
             * Тип счетчика. Возможные значения:
23
             * simple ― счетчик создан пользователем в Метрике;
24
             * partner ― счетчик импортирован из РСЯ.
25
             */
26
            ->setType(\Yandex\Metrica\Management\AvailableValues::TYPE_SIMPLE)
27
            ->setField('goals,mirrors,grants,filters,operations');
28
29
        /**
30
         * @see http://api.yandex.ru/metrika/doc/beta/management/counters/counters.xml
31
         */
32
        $counters = $managementClient->counters()->getCounters($paramsObj)->getCounters();
33
    } catch (\Exception $ex) {
34
        $errorMessage = $ex->getMessage();
35
        if ($errorMessage === 'PlatformNotAllowed') {
36
            $errorMessage .= '<p>Возможно, у приложения нет прав на доступ к ресурсу. Попробуйте '
37
                . '<a href="' . rtrim(str_replace($_SERVER['DOCUMENT_ROOT'], '', __DIR__), "/") . '/../OAuth/' . '">авторизироваться</a> и повторить.</p>';
38
        }
39
    }
40
}
41
?>
42
<!doctype html>
43
<html lang="en-US">
44
<head>
45
    <meta charset="UTF-8">
46
    <title>Yandex.SDK: Metrica Demo</title>
47
48
    <link rel="stylesheet" href="//yandex.st/bootstrap/3.0.3/css/bootstrap.min.css">
49
    <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
50
    <link rel="stylesheet" href="/examples/Disk/css/style.css">
51
52
</head>
53
<body>
54
55
<div class="container">
56
    <div class="jumbotron">
57
        <h2><a href="/examples/Metrica"><span class="glyphicon glyphicon-tasks"></span></a> Пример работы с Яндекс Метрикой</h2>
58
    </div>
59
    <ol class="breadcrumb">
60
        <li><a href="/examples">Examples</a></li>
61
        <li><a href="/examples/Metrica">Metrica</a></li>
62
        <li class="active">Analytics</li>
63
    </ol>
64
    <?php
65
    if (!isset($_COOKIE['yaAccessToken']) || !isset($_COOKIE['yaClientId'])) {
66
        ?>
67
        <div class="alert alert-info">
68
            Для просмотра этой страницы вам необходимо авторизироваться.
69
            <a id="goToAuth" href="/examples/OAuth" class="alert-link">Перейти на страницу авторизации</a>.
70
        </div>
71
    <?php
72
    } else {
73
        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...
74
            ?>
75
            <div class="alert alert-danger"><?= $errorMessage ?></div>
76
        <?php
77
        } else {
78
            ?>
79
            <div>
80
                <h3>Счетчики:</h3>
81
                <table id="countersTable" class="table table-striped table-bordered table-hover">
82
                    <thead>
83
                    <tr>
84
                        <td>ID</td>
85
                        <td>Название</td>
86
                        <td>Количество посещений</td>
87
                    </tr>
88
                    </thead>
89
                    <tbody>
90
                    <?php
91
                    if ($counters instanceof Traversable) {
92
                        foreach ($counters as $counter) {
93
                            ?>
94
                            <tr data-counter-id="<?= $counter->getId() ?>">
95
                                <td><?= $counter->getId() ?></td>
96
                                <td><?= $counter->getName() ?></td>
97
                                <td class="pageviews"></td>
98
                                <td>
99
                                    <a href="/examples/Metrica/Analytics/by-country.php?counter-id=<?= $counter->getId(
100
                                    ) ?>"
101
                                       class="btn btn-primary">Отчет по странам</a><br/>
102
                                </td>
103
                            </tr>
104
105
                        <?php
106
                        }
107
                    }
108
                    ?>
109
                    </tbody>
110
                </table>
111
            </div>
112
        <?php
113
        }
114
    }
115
    ?>
116
</div>
117
118
<!-- Modal -->
119
<div class="modal fade" id="errorModal" tabindex="-1" role="dialog" aria-hidden="true">
120
    <div class="modal-dialog">
121
        <div class="modal-content">
122
            <div class="modal-header">
123
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
124
                <h4 class="modal-title">Ошибка</h4>
125
            </div>
126
            <div class="modal-body">
127
                <div id="errorMessage"></div>
128
            </div>
129
            <div class="modal-footer">
130
                <button type="button" class="btn btn-default" data-dismiss="modal">Закрыть</button>
131
            </div>
132
        </div>
133
    </div>
134
</div>
135
136
<script src="http://yandex.st/jquery/2.0.3/jquery.min.js"></script>
137
<script src="http://yandex.st/bootstrap/3.0.3/js/bootstrap.min.js"></script>
138
139
<script>
140
    $(function() {
141
        $('table tbody tr').each(function() {
142
            var $this = $(this);
143
            $.get(
144
                "/examples/Metrica/api.php",
145
                {
146
                    method: 'getPageViewsCount',
147
                    counterId: $this.data('counter-id')
148
                },
149
                function (data) {
150
                    var response = JSON.parse(data);
151
                    $this.find('td.pageviews').html(response.result)
152
                }
153
            );
154
        });
155
    });
156
</script>
157
158
</body>
159
</html>
160