Example #1
0
<?php

require __DIR__ . '/../vendor/autoload.php';
use RecipeSearch\Constants;
use RecipeSearch\Util;
// Add recipe if one was submitted
if (count($_POST) > 0) {
    // Connect to Elasticsearch (1-node cluster)
    $esPort = getenv('APP_ES_PORT') ?: 9200;
    $client = new Elasticsearch\Client(['hosts' => ['localhost:' . $esPort]]);
    // Convert recipe title to ID
    $id = Util::recipeTitleToId($_POST['title']);
    // Check if recipe with this ID already exists
    $exists = $client->exists(['id' => $id, 'index' => Constants::ES_INDEX, 'type' => Constants::ES_TYPE]);
    if ($exists) {
        $message = 'A recipe with this title already exists. You can view it ' . '<a href="/view.php?id=' . $id . '">here</a> or rename your recipe.';
    } else {
        // Index the recipe in Elasticsearch
        $recipe = $_POST;
        $recipe['tags'] = Util::recipeTagsToArray($_POST['tags']);
        $document = ['id' => $id, 'index' => Constants::ES_INDEX, 'type' => Constants::ES_TYPE, 'body' => $recipe];
        $client->index($document);
        // Redirect user to recipe view page
        $message = 'Recipe added!';
        header('Location: /view.php?id=' . $id . '&message=' . $message);
        exit;
    }
}
?>
<html>
<head>