|
16 | 16 | */ |
17 | 17 |
|
18 | 18 | use Google\Cloud\Datastore\DatastoreClient; |
19 | | -use Silex\Application; |
20 | | -use Symfony\Component\HttpFoundation\Request; |
21 | | -use Symfony\Component\HttpFoundation\Response; |
| 19 | +use Psr\Http\Message\ServerRequestInterface as Request; |
| 20 | +use Psr\Http\Message\ResponseInterface as Response; |
| 21 | +use RKA\Middleware\IpAddress; |
| 22 | +use Slim\Factory\AppFactory; |
22 | 23 |
|
23 | | -// create the Silex application |
24 | | -$app = new Application(); |
| 24 | +// Create App |
| 25 | +$app = AppFactory::create(); |
| 26 | + |
| 27 | +// Display errors |
| 28 | +$app->addErrorMiddleware(true, true, true); |
| 29 | + |
| 30 | +// Add IP address middleware |
| 31 | +$checkProxyHeaders = true; |
| 32 | +$trustedProxies = ['10.0.0.1', '10.0.0.2']; |
| 33 | +$app->add(new IpAddress($checkProxyHeaders, $trustedProxies)); |
| 34 | + |
| 35 | +$app->get('/', function (Request $request, Response $response) { |
| 36 | + $projectId = getenv('GCLOUD_PROJECT'); |
| 37 | + if (empty($projectId)) { |
| 38 | + $response->getBody()->write('Set the GCLOUD_PROJECT environment variable to run locally'); |
| 39 | + return $response; |
| 40 | + } |
25 | 41 |
|
26 | | -$app['datastore'] = function () use ($app) { |
27 | | - $projectId = $app['project_id']; |
28 | 42 | # [START gae_flex_datastore_client] |
29 | 43 | $datastore = new DatastoreClient([ |
30 | 44 | 'projectId' => $projectId |
31 | 45 | ]); |
32 | 46 | # [END gae_flex_datastore_client] |
33 | | - return $datastore; |
34 | | -}; |
35 | | - |
36 | | -$app->get('/', function (Application $app, Request $request) { |
37 | | - if (empty($app['project_id'])) { |
38 | | - return 'Set the GCLOUD_PROJECT environment variable to run locally'; |
39 | | - } |
40 | | - /** @var \Google_Service_Datastore $datastore */ |
41 | | - $datastore = $app['datastore']; |
42 | 47 |
|
43 | 48 | // determine the user's IP |
44 | 49 | $user_ip = get_user_ip($request); |
|
68 | 73 | } |
69 | 74 | # [END gae_flex_datastore_query] |
70 | 75 | array_unshift($visits, "Last 10 visits:"); |
71 | | - return new Response(implode("\n", $visits), 200, |
72 | | - ['Content-Type' => 'text/plain']); |
| 76 | + $response->getBody()->write(implode("\n", $visits)); |
| 77 | + |
| 78 | + return $response |
| 79 | + ->withStatus(200) |
| 80 | + ->withHeader('Content-Type', 'text/plain'); |
73 | 81 | }); |
74 | 82 |
|
75 | 83 | function get_user_ip(Request $request) |
76 | 84 | { |
77 | | - $ip = $request->GetClientIp(); |
| 85 | + $ip = $request->getAttribute('ip_address'); |
78 | 86 | // Keep only the first two octets of the IP address. |
79 | 87 | $octets = explode($separator = ':', $ip); |
80 | 88 | if (count($octets) < 2) { // Must be ip4 address |
|
0 commit comments