Passed
Push — master ( 1bb8bb...31bd57 )
by Joël
01:50
created

cliPrinter()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 11
rs 9.9666
1
<?php
2
/**
3
 * Test this example by executing:
4
 * php -S localhost:2626
5
 * Open your favorite browser and go to http://localhost:2626/example.php
6
 * OR
7
 * Print it on stdout using CLI client
8
 * docker build -t google-street-view . && docker run -it --rm --name google-street-view -v "$PWD":/application google-street-view php example.php
9
 */
10
11
ini_set('display_errors', '1');
12
error_reporting(E_ALL);
13
14
$vendorDir = getenv('COMPOSER_VENDOR_DIR') ?: 'vendor';
15
require_once __DIR__.'/../'.$vendorDir.'/autoload.php';
16
17
/**
18
 * You can customize this value to test it
19
 */
20
$imageWidth = 400;
21
$imageHeight = 400;
22
$locationName = 'Forbidden City, Beijing, China';
23
//$locationName = 'A place which not exists';
24
25
use Defro\Google\StreetView\Api;
26
27
$dotEnv = new \Dotenv\Dotenv(__DIR__.'/../');
28
$dotEnv->load();
29
30
$apiKey = getenv('GOOGLE_API_KEY');
31
if (!$apiKey || empty($apiKey)) {
32
    throw new RuntimeException('No Google api key found. Please provide one in .env file.');
33
}
34
35
$client = new \GuzzleHttp\Client();
36
37
$streetView = new Api($client);
38
$streetView
39
    ->setApiKey($apiKey)
40
    ->setImageWidth($imageWidth)
41
    ->setImageHeight($imageHeight)
42
;
43
44
$print = [
45
    '<h1>Google Street view example</h1>',
46
    '<h2>Handle location: "'.$locationName.'"</h2>',
47
];
48
49
try {
50
    $imgUrl = $streetView->getImageUrlByLocation($locationName);
51
    $searchUrl = 'https://www.google.com/maps/search/?api=1&query=';
52
    $searchUrl .= urlencode($locationName);
53
    $print['Display image url by location name'] = [
54
        '<img src="'.$imgUrl.'" alt="'.$locationName.'" />',
55
        'Image URL : <a href="'.$imgUrl.'">'.$imgUrl.'</a>',
56
        'Search URL : <a href="'.$searchUrl.'">'.$searchUrl.'</a>',
57
    ];
58
} catch (Exception $e) {
59
    $print['Display image url by location name'] = 'Error when get image url by location name : '.$e->getMessage();
60
}
61
62
try {
63
    $metadata = $streetView->getMetadata($locationName);
64
    $print['Metadata collect by location name'] = [];
65
    foreach ($metadata as $key => $value) {
66
        $print['Metadata collect by location name'][] = sprintf('%s : %s', $key, $value);
67
    }
68
} catch (Exception $e) {
69
    exit('Error when get metadata : '.$e->getMessage());
70
}
71
72
try {
73
    $imgUrl = $streetView->getImageUrlByPanoramaId($metadata['panoramaId']);
74
    $searchUrl = 'https://www.google.com/maps/@?api=1&map_action=pano&pano=';
75
    $searchUrl .= $metadata['panoramaId'];
76
    $print['Display image url by panorama ID'] = [
77
        '<img src="'.$imgUrl.'" alt="'.$locationName.'" />',
78
        'Image URL : <a href="'.$imgUrl.'">'.$imgUrl.'</a>',
79
        'Search URL : <a href="'.$searchUrl.'">'.$searchUrl.'</a>',
80
    ];
81
} catch (Exception $e) {
82
    $print['Display image url by panorama ID'] = 'Error when get image url by panorama ID : '.$e->getMessage();
83
}
84
85
try {
86
    $imgUrl = $streetView->getImageUrlByLatitudeAndLongitude($metadata['lat'], $metadata['lng']);
87
    $searchUrl = 'https://www.google.com/maps/@?api=1&map_action=pano&viewpoint=';
88
    $searchUrl .= $metadata['lat'].','.$metadata['lng'];
89
    $print['Display image url by latitude and longitude'] = [
90
        '<img src="'.$imgUrl.'" alt="'.$locationName.'" />',
91
        'Image URL : <a href="'.$imgUrl.'">'.$imgUrl.'</a>',
92
        'Search URL : <a href="'.$searchUrl.'">'.$searchUrl.'</a>',
93
    ];
94
} catch (Exception $e) {
95
    $print['Display image url by latitude and longitude'] = 'Error when get image url by latitude and longitude : '.$e->getMessage();
96
}
97
98
if (PHP_SAPI === 'cli') {
99
    cliPrinter($print);
100
} else {
101
    echo '<html><head>';
102
    echo '<title>Google street view API PHP example</title>';
103
    echo '<link rel="icon" type="image/png" href="favicon.png" />';
104
    echo '</head><body>';
105
    echo webPrinter($print);
106
    // TODO add a form to customize location name and other parameter
107
    echo '</body></html>';
108
}
109
110
function cliPrinter($print, $indentationLevel = 0) {
111
    $indentation = str_repeat(' ', $indentationLevel * 2);
112
    foreach ($print as $key => $message) {
113
        if (is_array($message)) {
114
            printf('%s• %s%s', $indentation, strip_tags($key), PHP_EOL);
115
            cliPrinter($message, ++$indentationLevel);
116
            $indentationLevel--;
117
            continue;
118
        }
119
        if (trim(strip_tags($message)) !== '') {
120
            printf('%s• %s%s', $indentation, strip_tags($message), PHP_EOL);
121
        }
122
    }
123
}
124
125
function webPrinter($print, $isList = false) {
126
    $return = '';
127
    foreach ($print as $title => $message) {
128
        if (is_array($message)) {
129
            $return .= '<h3>'.$title.'</h3><ul>'.webPrinter($message, true).'</ul>';
130
            continue;
131
        }
132
        $message = $isList ? '<li>'.$message.'</li>' : $message;
133
        $return .= is_numeric($title)
134
            ? $message
135
            : '<h3>'.$title.'</h3><p>'.$message.'</p>'
136
        ;
137
    }
138
    return $return;
139
}
140
141
exit(0);
142