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

examples/Dictionary/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
$settings = require_once '../settings.php';
3
use Yandex\Dictionary\DictionaryClient;
4
use Yandex\Common\Exception\ForbiddenException;
5
use Yandex\Dictionary\Exception\DictionaryException;
6
7
$errorMessage = false;
8
9
// Is auth
10
if (isset($_COOKIE['yaAccessToken']) && isset($_COOKIE['yaClientId'])) {
11
12
    if (!isset($settings["dictionary"]["key"]) || !$settings["dictionary"]["key"]) {
13
        throw new DictionaryException('Empty dictionary key. Get key from https://tech.yandex.ru/keys/get/?service=dict');
14
    }
15
16
    $dictionaryClient = new DictionaryClient($settings["dictionary"]["key"]);
17
18
    if (isset($_POST['word']) && $_POST['word'] && isset($_POST['language']) && $_POST['language']) {
19
        $translation = explode('-', $_POST['language']);
20
        if (count($translation) === 2) {
21
            $from = $translation[0];
22
            $to   = $translation[1];
23
            $dictionaryClient
24
                ->setTranslateFrom($from)
25
                ->setTranslateTo($to);
26
            $result = $dictionaryClient->lookup($_POST['word']);
27
            if ($result) {
28
                /** @var \Yandex\Dictionary\DictionaryDefinition $dictionaryDefinition */
29
                $dictionaryDefinition  = $result[0];
30
                $dictionaryTranslation = $dictionaryDefinition->getTranslations();
31
                /** @var \Yandex\Dictionary\DictionaryTranslation $dictionaryTranslation */
32
                $dictionaryTranslation = $dictionaryDefinition->getTranslations()[0];
33
                $word                  = $dictionaryTranslation->getText();
34
            }
35
        }
36
    }
37
38
    try {
39
        $languages = $dictionaryClient->getLanguages();
40
    } catch (ForbiddenException $ex) {
41
        $errorMessage = $ex->getMessage();
42
        $errorMessage .= '<p>Возможно, у приложения нет прав на доступ к ресурсу. Попробуйте '
43
            . '<a href="' . rtrim(str_replace($_SERVER['DOCUMENT_ROOT'], '', __DIR__), "/") . "/../OAuth/" .
44
            '">авторизироваться</a> и повторить.</p>';
45
    } catch (Exception $ex) {
46
        $errorMessage = $ex->getMessage();
47
    }
48
}
49
?>
50
<!doctype html>
51
<html lang="en-US">
52
<head>
53
    <meta charset="UTF-8">
54
    <title>Yandex PHP Library: DataSync Demo</title>
55
    <link rel="stylesheet" href="//yandex.st/bootstrap/3.0.0/css/bootstrap.min.css">
56
    <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
57
    <link rel="stylesheet" href="/examples/Disk/css/style.css">
58
</head>
59
<body>
60
<div class="container">
61
    <div class="jumbotron">
62
        <h2><span class="glyphicon glyphicon-shopping-cart"></span> Пример работы с API Словаря</h2>
63
    </div>
64
    <ol class="breadcrumb">
65
        <li><a href="/examples">Examples</a></li>
66
        <li class="active">Dictionary</li>
67
    </ol>
68
    <?php
69
    if (!isset($_COOKIE['yaAccessToken']) || !isset($_COOKIE['yaClientId'])) {
70
        ?>
71
        <div class="alert alert-info">
72
            Для просмотра этой страници вам необходимо авторизироваться.
73
            <a id="goToAuth"
74
               href="<?php echo rtrim(str_replace($_SERVER['DOCUMENT_ROOT'], '', __DIR__), "/") . '/../OAuth/' ?>"
75
               class="alert-link">Перейти на страницу авторизации</a>.
76
        </div>
77
    <?php
78
    } elseif ($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...
79
        ?>
80
        <div class="alert alert-danger">
81
            <?= $errorMessage ?>
82
        </div>
83
    <?php
84
    } elseif (isset($languages)) {
85
        ?>
86
        <div>
87
            <form class="form-horizontal" action="index.php" method="post">
88
                <div class="form-group">
89
                    <label for="inputLanguage" class="col-sm-4 control-label">Язык</label>
90
91
                    <div class="col-sm-8">
92
                        <select class="form-control" name="language" id="inputLanguage">
93
                            <?php foreach ($languages as $languageNames) { ?>
0 ignored issues
show
The expression $languages of type array|false is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
94
                                <option value="<?= $languageNames[0] . '-' . $languageNames[1] ?>"
95
                                    <?= ($_POST['language'] === $languageNames[0] . '-' . $languageNames[1]) ?
96
                                        'selected' : '' ?>
97
                                    >
98
                                    <?= $languageNames[0] . ' - ' . $languageNames[1] ?>
99
                                </option>
100
                            <?php
101
                            }
102
                            ?>
103
                        </select>
104
                    </div>
105
                </div>
106
107
                <div class="form-group">
108
109
                    <label for="inputWord" class="col-sm-4 control-label">Слово</label>
110
111
                    <div class="col-sm-8">
112
                        <input type="text" class="form-control" id="inputWord" name="word"
113
                               placeholder="Слово">
114
                    </div>
115
                </div>
116
                <div class="form-group">
117
                    <label class="col-sm-4 control-label">Перевод</label>
118
119
                    <div class="col-sm-8">
120
                        <?= (isset($word)) ? $word : '' ?>
121
                    </div>
122
                </div>
123
                <button type="submit" class="btn btn-primary">Перевести</button>
124
            </form>
125
        </div>
126
127
    <?php
128
    }
129
    ?>
130
    <script src="http://yandex.st/jquery/2.0.3/jquery.min.js"></script>
131
    <script src="http://yandex.st/jquery/cookie/1.0/jquery.cookie.min.js"></script>
132
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
133
    <script>
134
        $(function () {
135
            $('#goToAuth').click(function (e) {
136
                $.cookie('back', location.href, {expires: 256, path: '/'});
137
            });
138
        });
139
    </script>
140
</body>
141
</html>
142