<?php

function handle_request()
{
    if ($_SERVER["REQUEST_METHOD"] == "GET") {
        handle_get($_GET);
    } else if ($_SERVER["REQUEST_METHOD"] == "POST") {
        handle_post(get_post_data());
    }
}

function get_post_data()
{
    return json_decode(file_get_contents('php://input'), true);
}

function handle_get($request_data) {
    $file_path = get_space_file_path($request_data["space_id"]);

    $content = file_get_contents($file_path);
    echo $content;
}

function handle_post($request_data) {
    $file_path = get_space_file_path($request_data["space_id"]);

    file_put_contents($file_path, $request_data["graph"]);
}

function get_space_file_path($space_id) {
    return __DIR__."/".$space_id.".json";
}

handle_request();