cliPrinter()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
c 2
b 0
f 0
nc 4
nop 2
dl 0
loc 12
rs 9.9666
1
<?php
2
/**
3
 * Example script to test Google Street View client.
4
 *
5
 * Test it with Dockerfile provided, please read documentation...
6
 *
7
 * @category   Example
8
 *
9
 * @author     Joël Gaujard <[email protected]>
10
 * @copyright  2018 Joël Gaujard
11
 * @license    MIT https://github.com/defro/google-streetview/blob/master/LICENSE
12
 *
13
 * @link       https://defro.github.io/google-streetview/docker.html
14
 * @see        docs/docker.md
15
 */
16
ini_set('display_errors', '1');
17
error_reporting(E_ALL);
18
19
require_once __DIR__.'/../vendor/autoload.php';
20
21
use Defro\Google\StreetView\Api;
22
23
/**
24
 * You can customize this value to test it.
25
 */
26
$imageWidth = 400;
27
$imageHeight = 400;
28
$locationName = 'Forbidden City, Beijing, China';
29
//$locationName = 'A place which not exists';
30
31
if (!empty($_GET)) {
32
    $locationName = !empty($_GET['location_name'])
33
        ? htmlspecialchars(stripslashes(trim($_GET['location_name'])))
34
        : $locationName;
35
}
36
37
if (file_exists(__DIR__.'/.env')) {
38
    $dotEnv = new \Dotenv\Dotenv(__DIR__);
39
    $dotEnv->load();
40
}
41
42
$apiKey = getenv('GOOGLE_API_KEY');
43
if (!$apiKey || empty($apiKey)) {
44
    throw new RuntimeException('No Google api key found. Please provide one in .env file.');
45
}
46
47
$client = new \GuzzleHttp\Client();
48
49
$streetView = new Api($client);
50
$streetView
51
    ->setApiKey($apiKey)
52
    ->setImageWidth($imageWidth)
53
    ->setImageHeight($imageHeight);
54
55
$print = [
56
    '<h2>Handle location: "'.$locationName.'"</h2>',
57
];
58
59
try {
60
    $imgUrl = $streetView->getImageUrlByLocation($locationName);
61
    $searchUrl = 'https://www.google.com/maps/search/?api=1&query=';
62
    $searchUrl .= urlencode($locationName);
63
    $print['Image url by location name'] = [
64
        '<img src="'.$imgUrl.'" alt="'.$locationName.'" />',
65
        'Image URL : <a href="'.$imgUrl.'">'.$imgUrl.'</a>',
66
        'Search URL : <a href="'.$searchUrl.'">'.$searchUrl.'</a>',
67
    ];
68
} catch (Exception $e) {
69
    $print['Image url by location name'] = 'Error when get image url by location name : '.$e->getMessage();
70
}
71
72
try {
73
    $metadata = $streetView->getMetadata($locationName);
74
    $print['Metadata collect by location name'] = [];
75
    foreach ($metadata as $key => $value) {
76
        $print['Metadata collect by location name'][] = sprintf('%s : %s', $key, $value);
77
    }
78
} catch (Exception $e) {
79
    exit('Error when get metadata : '.$e->getMessage());
80
}
81
82
try {
83
    $imgUrl = $streetView->getImageUrlByPanoramaId($metadata['panoramaId']);
84
    $searchUrl = 'https://www.google.com/maps/@?api=1&map_action=pano&pano=';
85
    $searchUrl .= $metadata['panoramaId'];
86
    $print['Image url by panorama ID'] = [
87
        '<img src="'.$imgUrl.'" alt="'.$locationName.'" />',
88
        'Image URL : <a href="'.$imgUrl.'">'.$imgUrl.'</a>',
89
        'Search URL : <a href="'.$searchUrl.'">'.$searchUrl.'</a>',
90
    ];
91
} catch (Exception $e) {
92
    $print['Image url by panorama ID'] = 'Error when get image url by panorama ID : '.$e->getMessage();
93
}
94
95
try {
96
    $imgUrl = $streetView->getImageUrlByLatitudeAndLongitude($metadata['lat'], $metadata['lng']);
97
    $searchUrl = 'https://www.google.com/maps/@?api=1&map_action=pano&viewpoint=';
98
    $searchUrl .= $metadata['lat'].','.$metadata['lng'];
99
    $print['Image url by latitude and longitude'] = [
100
        '<img src="'.$imgUrl.'" alt="'.$locationName.'" />',
101
        'Image URL : <a href="'.$imgUrl.'">'.$imgUrl.'</a>',
102
        'Search URL : <a href="'.$searchUrl.'">'.$searchUrl.'</a>',
103
    ];
104
} catch (Exception $e) {
105
    $print['Image url by latitude and longitude'] = 'Error when get image url by latitude and longitude : '.$e->getMessage();
106
}
107
108
if (PHP_SAPI === 'cli') {
109
    cliPrinter($print);
110
} else {
111
    $loader = new \Twig\Loader\FilesystemLoader(__DIR__);
112
    $twig = new \Twig\Environment($loader);
113
    echo $twig->render('index.twig', [
114
        'result'        => webPrinter($print),
115
        'locationName'  => $locationName,
116
    ]);
117
}
118
119
function cliPrinter($print, $indentationLevel = 0)
120
{
121
    $indentation = str_repeat(' ', $indentationLevel * 2);
122
    foreach ($print as $key => $message) {
123
        if (is_array($message)) {
124
            printf('%s• %s%s', $indentation, strip_tags($key), PHP_EOL);
125
            cliPrinter($message, ++$indentationLevel);
126
            $indentationLevel--;
127
            continue;
128
        }
129
        if (trim(strip_tags($message)) !== '') {
130
            printf('%s• %s%s', $indentation, strip_tags($message), PHP_EOL);
131
        }
132
    }
133
}
134
135
function webPrinter($print, $isList = false)
136
{
137
    $return = '';
138
    foreach ($print as $title => $message) {
139
        if (is_array($message)) {
140
            $return .= '<h3>'.$title.'</h3><ul>'.webPrinter($message, true).'</ul>';
141
            continue;
142
        }
143
        $message = $isList ? '<li>'.$message.'</li>' : $message;
144
        $return .= is_numeric($title) ? $message : '<h3>'.$title.'</h3><p>'.$message.'</p>';
145
    }
146
147
    return $return;
148
}
149
150
exit(0);
151