Пример #1
1
    return $app->json(array('success' => true));
});
$app->get('/pessoas', function () use($app) {
    $stmt = $app['db']->query("Select * from pessoas");
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    return $app->json($result);
});
$app->get('/pessoas/{id}', function ($id) use($app) {
    $stmt = $app['db']->prepare("Select * from pessoas where id=:id");
    $stmt->bindParam('id', $id);
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    return $app->json($result);
});
$app->put('/pessoas/{id}', function (Request $request, $id) use($app) {
    $data = $request->getContent();
    parse_str($data, $out);
    $stmt = $app['db']->prepare("update pessoas set nome=:nome, email=:email where id=:id");
    $stmt->bindParam('id', $id);
    $stmt->bindParam('nome', $out['nome']);
    $stmt->bindParam('email', $out['email']);
    $stmt->execute();
    return $app->json(array('success' => true));
});
$app->delete('/pessoas/{id}', function ($id) use($app) {
    $stmt = $app['db']->prepare("delete from pessoas where id=:id");
    $stmt->bindParam('id', $id);
    $stmt->execute();
    return $app->json(array('success' => true));
});
$app->run();
Пример #2
0
 * @returns string
 */
$app->get('/items/data/{itemId}', function (Silex\Application $app, $itemId) {
    if ($app['session']->get('user_id') === null) {
        $app->abort(403, "Request is not allowed.");
        exit;
    }
    $itemId = trim($itemId);
    $qb = $app['db']->createQueryBuilder()->select('*')->from('services')->where('id = ?')->setParameter(0, $itemId);
    $result = $qb->execute()->fetch();
    $result['idp'] = intval($result['idp']);
    $result['balance'] = floatval($result['balance']);
    $result['min_balance'] = floatval($result['min_balance']);
    $result['credit_limit'] = floatval($result['credit_limit']);
    return $app->json($result);
});
$app->put('/items/update/{itemId}', function (Silex\Application $app, $itemId) {
    if ($app['session']->get('user_id') === null) {
        $app->abort(403, "Request is not allowed.");
        exit;
    }
    $data = json_decode($app['request']->getContent(), true);
    $qb = $app['db']->createQueryBuilder()->update('services')->set('idp', ':idp')->set('login', ':login')->set('email', ':email')->set('balance', ':balance')->set('calc_rate_type', ':calc_rate_type')->set('bank', ':bank')->set('dlr_method', ':dlr_method')->set('min_balance', ':min_balance')->set('dlr_data', ':dlr_data')->set('url', ':url')->set('credit_limit', ':credit_limit')->where('id = :id');
    foreach ($data as $key => $value) {
        $qb->setParameter(":{$key}", $value);
    }
    $update = $qb->execute();
    $result = array('success' => $update != false);
    return $app->json($result);
});
$app->run();
Пример #3
0
    $username = $app['request']->get('username');
    $password = $app['request']->get('password');
    $firstName = $app['request']->get('firstName');
    $lastName = $app['request']->get('lastName');
    $user = new User($username, $password, $firstName, $lastName);
    //******* needs to store user in persistence *******
    return new Response(json_encode($user), 201);
});
$app->put('/user/{username}', function ($username) use($app) {
    //******* needs to modify existing object not create *******
    $item = null;
    $password = $app['request']->get('password');
    $firstName = $app['request']->get('firstName');
    $lastName = $app['request']->get('lastName');
    foreach ($GLOBALS['users'] as $struct) {
        if ($username == $struct->username) {
            $struct->password = $password;
            $struct->firstName = $firstName;
            $struct->lastName = $lastName;
            $item = $struct;
        }
    }
    return new Response(json_encode($item), 200);
});
$app->get('/user', function () use($app) {
    //******* needs to get users from persistence *******
    //$users = apc_fetch('users');
    //apc_store('users',$users,0);
    return new Response(json_encode($GLOBALS['users']), 200);
});
$app->get('/user/{username}', function ($username) use($app) {
    //******* needs to get user with correct username out of persistence *******
Пример #4
0
    $m->annotator->annotations->insert($post, array('safe' => true));
    $post['id'] = (string) $post['_id'];
    unset($post['_id']);
    return $app->json($post);
});
$app->get('/annotations/{id}', function ($id) use($app) {
    $m = new Mongo();
    $post = $m->annotator->annotations->findOne(array('_id' => new MongoId($id)));
    $post['id'] = (string) $post['_id'];
    unset($post['_id']);
    return $app->json($post);
});
$app->put('/annotations/{id}', function (Request $request, $id) use($app) {
    $post = $app['data'];
    unset($post['id']);
    $m = new Mongo();
    $m->annotator->annotations->update(array('_id' => new MongoId($id)), array('$set' => $post));
    return new Response('', 303, array('Location' => $request->getUri()));
});
$app->delete('/annotations/{id}', function (Request $request, $id) use($app) {
    $m = new Mongo();
    $m->annotator->annotations->remove(array('_id' => new MongoId($id)));
    return new Response('', 204);
});
/***
 *
 * Auth Endpoint.
 * @see https://github.com/okfn/annotator/wiki/Authentication
 *
 */
$app->get('/auth/token', function () use($app) {
Пример #5
0
    }
});
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__));
$app->register(new Silex\Provider\ServiceControllerServiceProvider());
$app->register(new Shop\Database\DatabaseServiceProvider());
$app['illuminate.capsule']->bootEloquent();
$app['illuminate.capsule']->setAsGlobal();
$app['db.controller'] = $app->share(function () use($app) {
    return new Shop\Database\DBController($app, new \Shop\Database\Schema());
});
$app['db.controller']->createDB();
$app['home.controller'] = $app->share(function () use($app) {
    return new Shop\Home\HomeController($app);
});
$app['products.controller'] = $app->share(function () use($app) {
    return new Shop\Products\ProductsController($app, $app['request'], new Shop\Products\ProductModel());
});
$app->get('/', 'home.controller:index');
$app->get('/products', 'products.controller:index');
$app->put('/products/{id}', 'products.controller:update');
$app->post('/products', 'products.controller:insert');
$app->delete('/products/{id}', 'products.controller:delete');
$app->post('/admin', function () use($app) {
    $admin = (require_once $app['base_dir'] . '/backend/config/admin.php');
    $input = $app['request']->request->all();
    if ($admin['username'] == $input['username'] && $admin['password'] == $input['password']) {
        return new Symfony\Component\HttpFoundation\Response(200);
    }
    //    return new Symfony\Component\HttpFoundation\Response(500);
});
$app->run();
Пример #6
0
$app->put('/{entity}/{id}', function ($entity, $id, Request $request) use($app, $em, $filter, $entityCache) {
    if ($entityCache) {
        $entityCache->setNamespace($entity);
        $cacheKey = $entity;
    }
    $serializer = new service\Serializer();
    $serializer->setGroups(array('entity', $entity));
    $entityName = 'model\\' . ucfirst($entity);
    if (!($data = $request->get($entity))) {
        return new Response('Missing parameters.', 400, array('Content-Type' => 'text/json'));
    }
    if (!($entity = $em->find($entityName, $id))) {
        return new Response('Not found.', 404, array('Content-Type' => 'text/json'));
    }
    try {
        $class = new \ReflectionClass($entity);
        foreach ($data as $name => $value) {
            if (is_array($value)) {
                //it's a relationship to another entity
                $id = $value['id'];
                $relatedEntity = 'model\\' . ucfirst($name);
                if (isset($value['entityName'])) {
                    $relatedEntity = 'model\\' . ucfirst($value['entityName']);
                }
                $value = $em->find($relatedEntity, $id);
            }
            $method = 'set' . ucfirst($name);
            if ($class->hasMethod($method)) {
                call_user_func(array($entity, $method), $value);
            }
        }
        $entity->setUpdated(date('Y-m-d H:i:s'));
        $errors = $app['validator']->validate($entity);
        if (count($errors) > 0) {
            foreach ($errors as $r) {
                $app['monolog']->addError($r);
            }
            return new Response('Invalid parameters.', 400, array('Content-Type' => 'text/json'));
        }
        //Filter entity
        $filter->filterEntity($entity);
        //$em->persist($entity);
        $em->flush();
    } catch (Exception $e) {
        $app['monolog']->addError($e->getMessage());
        return new Response($e->getMessage(), 500, array('Content-Type' => 'text/json'));
    }
    //clean cache. Entity and all related entities
    if ($entityCache) {
        $entityCache->delete($cacheKey);
        $entityCache->delete($cacheKey . '_' . $id);
        $metadata = $em->getClassMetadata($entityName);
        foreach ($metadata->getAssociationMappings() as $assoc) {
            $cacheKey = explode('\\', $assoc['targetEntity']);
            $relatedEntity = strtolower($cacheKey[1]);
            $entityCache->setNamespace($relatedEntity);
            $entityCache->deleteAll();
        }
    }
    return new Response($serializer->serialize($entity, 'json'), 200, array('Content-Type' => 'text/json'));
});
Пример #7
0
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    return $app->json($result);
});
$app->post('/contatos', function (Request $request) use($app) {
    $data = $request->getContent();
    parse_str($data, $out);
    $stmt = $app['db']->prepare("INSERT INTO contacts(name, email, cellphone) VALUE(:name, :email, :cellphone)");
    $stmt->bindParam('name', $out['name']);
    $stmt->bindParam('email', $out['email']);
    $stmt->bindParam('cellphone', $out['cellphone']);
    $stmt->execute();
    return $app->json(array('success' => true));
});
$app->put('/contatos/{id}', function (Request $request, $id) use($app) {
    $data = $request->getContent();
    parse_str($data, $out);
    $stmt = $app['db']->prepare("UPDATE contacts SET name=:name, email=:email, cellphone=:cellphone WHERE id=:id");
    $stmt->bindParam('id', $id);
    $stmt->bindParam('name', $out['name']);
    $stmt->bindParam('email', $out['email']);
    $stmt->bindParam('cellphone', $out['cellphone']);
    $stmt->execute();
    return $app->json(array('success' => true));
});
$app->delete('/contatos/{id}', function ($id) use($app) {
    $stmt = $app['db']->prepare("DELETE FROM contacts WHERE id=:id");
    $stmt->bindParam('id', $id);
    $stmt->execute();
    return $app->json(array('success' => true));
});
$app->run();
Пример #8
0
	//
	// Document REST interface
	//
	$app->post('api/v1.0/document/{name}', function($name) use ($app) {
		$controller = new \Controller\Json();
		return $controller->createFile($name);
		return json_encode(['status'=>"got here POST", 'name' => $name]);
	});
	$app->get('api/v1.0/document/{name}', function($name) use ($app) {
		$controller = new \Controller\Json();
		return $controller->openFile($name);
		return json_encode(['status'=>"got here GET", 'name' => $name]);
	});
	$app->put('api/v1.0/document/{name}', function(Request $request) use ($app) {
		$controller = new \Controller\Json();
		return $controller->saveFile($request);
		return json_encode(['status'=>"got here PUT", 'req' => $request]);
	});
	$app->delete('api/v1.0/document/{name}', function($name) use ($app) {
		$controller = new \Controller\Json();
		return $controller->deleteFile($name);
		return json_encode(['status'=>"got here DELETE", 'name' => $name]);
	});

	$app->match('/api/v1.0/document/update', '\\Controller\\Json::saveFile');

	//
	// Photo upload
	//
	$app->match('/api/v1.0/upload', function (Request $request) use ($app) {
Пример #9
0
});
$app->get('/users/{id}', function (Silex\Application $app, $id) {
    $user = $app['doctrine']->getRepository('App\\Entity\\User')->find($id);
    if (empty($user)) {
        throw new \InvalidArgumentException("User not found", 404);
    }
    return $app->json(['id' => $user->getId(), 'firstName' => $user->getFirstName(), 'lastName' => $user->getLastName()]);
});
$app->post('/users', function (Silex\Application $app, \Symfony\Component\HttpFoundation\Request $request) {
    $user = new \App\Entity\User();
    $user->setFirstName($request->get('firstName'));
    $user->setLastName($request->get('lastName'));
    $app['doctrine']->persist($user);
    $app['doctrine']->flush();
    return $app->json(['id' => $user->getId(), 'firstName' => $user->getFirstName(), 'lastName' => $user->getLastName()]);
});
$app->put('/users/{id}', function (Silex\Application $app, \Symfony\Component\HttpFoundation\Request $request, $id) {
    $user = $app['doctrine']->getRepository('App\\Entity\\User')->find($id);
    $user->setFirstName($request->get('firstName'));
    $user->setLastName($request->get('lastName'));
    $app['doctrine']->merge($user);
    $app['doctrine']->flush();
    return $app->json(['id' => $user->getId(), 'firstName' => $user->getFirstName(), 'lastName' => $user->getLastName()]);
});
$app->delete('/users/{id}', function (Silex\Application $app, $id) {
    $user = $app['doctrine']->getRepository('App\\Entity\\User')->find($id);
    $app['doctrine']->remove($user);
    $app['doctrine']->flush();
    return $app->json([]);
});
return $app;
Пример #10
0
        return new Response((string) $errors, 400);
    }
    $store = $app['store'];
    return $app->json($store->get($id));
});
$app->post('/todos', function (Request $request) use($app) {
    $store = $app['store'];
    $data = json_decode($request->getContent());
    $todo = $store->create($data);
    return $app->json($todo, 201);
});
$app->put('/todos/{id}', function ($id, Request $request) use($app) {
    $errors = $app['validator']->validateValue($id, new Assert\Length(array('min' => 24, 'max' => 24)));
    if (count($errors) > 0) {
        return new Response((string) $errors, 400);
    }
    $store = $app['store'];
    $data = json_decode($request->getContent());
    $store->update($id, $data);
    return new Response('', 204);
});
$app->delete('/todos/{id}', function ($id) use($app) {
    $errors = $app['validator']->validateValue($id, new Assert\Length(array('min' => 24, 'max' => 24)));
    if (count($errors) > 0) {
        return new Response((string) $errors, 400);
    }
    $store = $app['store'];
    $store->remove($id);
    return new Response('', 200);
});
return $app;
Пример #11
0
        $app->abort(404, 'The user could not be found');
    }
    return $app['twig']->render('edit-user.html.twig', array('user' => $user->data, 'id' => $id));
    // return "Lets edit".$id;
})->bind("edit-user");
//put
$app->put('/users/{id}', function (Request $request, Silex\Application $app, $id) {
    $client = new GuzzleHttp\Client();
    $res = $client->request('PUT', "https://basic-rails-api.herokuapp.com/api/v1/users/" . $id, ["query" => ["name" => $request->get('name'), "email" => $request->get('email'), "password" => $request->get('password'), "password_confirmation" => $request->get('password_confirmation')]]);
    $resp = json_decode($res->getBody());
    // print_r($resp);
    if (!$resp->status) {
        // print_r($resp);
        foreach ($resp->data as $key => $value) {
            echo $key . " : {";
            foreach ($value as $num => $err) {
                echo $err . ",";
            }
            echo "}" . "<br>";
        }
        echo "<a href='/users/" . $id . "/edit'>Retry</a><br>";
        return "Form contains errors..";
    }
    return new Response("User updated! <a href='/users/" . $id . "'>check out</a>", 201);
});
//delete
$app->delete('/users/{id}', function (Silex\Application $app, $id) {
    $client = new GuzzleHttp\Client();
    $res = $client->delete("https://basic-rails-api.herokuapp.com/api/v1/users/" . $id);
    $resp = json_decode($res->getBody());
    if (!$resp->status) {
Пример #12
0
    }
});
$app->post('/firms/{firm_id}/ratings', function ($firm_id, Request $request) use($app) {
    $post = array('firm_id' => $firm_id, 'name' => $request->request->get('name'), 'rating' => $request->request->get('rating'));
    $app['db']->insert('ratings', $post);
    $post['id'] = $app['db']->lastInsertId();
    return $app->json($post);
});
$app->put('/ratings/{id}', function ($id, Request $request) use($app) {
    $put = array();
    $firm_id = $request->request->get('firm_id');
    if ($firm_id) {
        $put['firm_id'] = $firm_id;
    }
    $name = $request->request->get('name');
    if ($name) {
        $put['name'] = $name;
    }
    $rating = $request->request->get('rating');
    if ($rating) {
        $put['rating'] = $rating;
    }
    $result = $app['db']->update('ratings', $put, array('id' => $id));
    return $app->json(array('n_updated' => $result));
});
$app->delete('/firms/{firm_id}/ratings', function ($firm_id, Request $request) use($app) {
    $id = $request->query->get('id');
    $result = $app['db']->delete('ratings', array('firm_id' => $firm_id, 'id' => $id));
    return $app->json(array('n_deleted' => $result));
});
$app->run();
Пример #13
0
$app->get('/tasks-json/{listId}', function ($listId) use($service) {
    if ($service instanceof GtaskHelperCached) {
        $service->resetListCache($listId);
    }
    $data = $service->getTasksInListArray($listId);
    return new Response(json_encode($data), 200, array('Content-Type' => 'application/json'));
});
// ADD TASK
$app->post('/list/{listId}/tasks', function (Request $request, $listId) use($service) {
    $task = json_decode($request->getContent());
    $addedTask = $service->addTask($listId, $task->title);
    /* @var $task \Google_Service_Tasks_Task */
    return new Response(json_encode(GtaskHelper::taskToArray($addedTask)), 200, array('Content-Type' => 'application/json'));
});
// EDIT TASK TITLE
//$app->put('/list/{listId}/task/{taskId}/edit-title/{title}', function (Request $request, $listId, $taskId, $newTitle) use ($service) {
//    $service->editTaskTitle($listId, $taskId, $newTitle);
//
//    return new Response(json_encode('ok'), 200, array('Content-Type' => 'application/json'));
//});
// EDIT TASK LIST
$app->put('/list/{listId}/task/{taskId}/change-list/{newListId}', function (Request $request, $listId, $taskId, $newListId) use($service) {
    $service->moveTaskToList($listId, $taskId, $newListId);
    return new Response(json_encode('ok'), 200, array('Content-Type' => 'application/json'));
});
// DELETE
$app->delete('/list/{listId}/tasks/{taskId}', function ($listId, $taskId) use($service) {
    $ret = $service->deleteTasks($listId, [$taskId]);
    return new Response(json_encode($ret), 200, array('Content-Type' => 'application/json'));
});
$app->run();
Пример #14
0
<?php

require_once 'silex.phar';
require_once dirname(__DIR__) . '/src/MaintenanceExtension.php';
$app = new Silex\Application();
$app->register(new \MaintenanceExtension(), array('maintenance.lock' => __DIR__ . '/maintenance', 'maintenance.file' => __DIR__ . '/maintenance.html'));
$app->get('/', function () use($app) {
    return '/';
});
$app->post('/', function () use($app) {
    return '/';
});
$app->put('/', function () use($app) {
    return '/';
});
$app->delete('/', function () use($app) {
    return '/';
});
if (getenv('SILEX_TEST')) {
    return $app;
}
$app->run();
Пример #15
0
});
//Event controller
$app['events.controller'] = $app->share(function ($id, $request) use($app) {
    return new app\Controller\EventsController();
});
/**
 * Routes definition
 */
//GET /events for listing all eventes
$app->get('/events', 'events.controller:index');
//GET /events/{id} for listing specific event
$app->get('/events/{id}', 'events.controller:show');
//POST /events for creating new event
$app->post('/events', 'events.controller:create');
//PUT /events/{id} for updating exisiting event
$app->put('/events/{id}', 'events.controller:update');
//DELETE /events/{ID} for deleting specific event
$app->delete('/events/{id}', 'events.controller:delete');
/**
 * Default error handler
 */
$app->error(function (\Exception $e, $code) {
    $message = NULL;
    switch ($code) {
        case 400:
            $message = 'Bad request.';
            break;
        case 404:
            $message = 'Page not found.';
            break;
        default:
Пример #16
0
$silex->get('/api/{resource}/{id}/', function ($resource, $id) use($silex) {
    $res = array();
    $q = mysql_query("SELECT * FROM {$resource} WHERE id = '{$id}'");
    while ($c = mysql_fetch_assoc($q)) {
        $res[] = $c;
    }
    return new Response(json_encode($res), 200, array('Content-Type' => 'application/json'));
});
// POST     /{resource}     Create
$silex->post('/api/{resource}/', function ($resource, Request $request) use($silex) {
    parse_str($request->getContent(), $data);
    $query = "INSERT INTO {$resource} (" . implode(', ', array_keys($data)) . ") VALUES ('" . implode("', '", $data) . "')";
    mysql_query($query);
    return new Response(mysql_affected_rows(), 200);
});
// PUT  /{resource}/{id}    Update
$silex->put('/api/{resource}/{id}/', function ($resource, $id, Request $request) use($silex) {
    parse_str($request->getContent(), $data);
    $data_mod = array();
    foreach ($data as $key => $value) {
        $data_mod[] = "{$key} = '{$value}'";
    }
    $query = "UPDATE {$resource} SET " . implode(', ', $data_mod) . " WHERE id = {$id}";
    mysql_query($query);
    return new Response(mysql_affected_rows(), 200);
});
// DELETE   /{resource}/{id}    Destroy
$silex->delete('/api/{resource}/{id}/', function ($resource, $id) use($silex) {
    $q = mysql_query("DELETE FROM {$resource} WHERE id = '{$id}'");
    return new Response(mysql_affected_rows(), 200);
});
Пример #17
0
// "books" API
$app->get('/books', function () use($app) {
    return $app->json($app['books_db']->all());
})->after($addLinkToSchema);
$app->post('/books', function (Request $request) use($app) {
    $id = $app['books_db']->add(json_decode($request->getContent(), true));
    $app['books_db']->persist();
    $response = new Response(201);
    $response->headers->set('location', '/books/' . $id);
    return $response;
})->before($checkJSON)->before($checkBook)->after($addLinkToSchema);
$app->get('/books/{id}', function (Request $request) use($app) {
    return $app->json($request->get('book'));
})->before($checkBookId)->after($addLinkToSchema);
$app->put('/books/{id}', function (Request $request) use($app) {
    $app['books_db']->set($request->get('id'), json_decode($request->getContent(), true));
    $app['books_db']->persist();
    return new Response(null, 204);
})->before($checkBookId)->before($checkJSON)->before($checkBook)->after($addLinkToSchema);
$app->delete('/books/{id}', function (Request $request) use($app) {
    $app['books_db']->remove($request->get('id'));
    $app['books_db']->persist();
    return new Response(null, 204);
})->before($checkBookId);
$app->delete('/books', function () use($app) {
    $app['books_db']->clear();
    $app['books_db']->persist();
    return new Response(null, 204);
});
// Start server (kinda)
$app->run();
Пример #18
0
    }
    //Filter entity
    $filter->filterEntity($entity);
    $em->persist($entity);
    $em->flush();
    return new Response($entity->toJson());
});
$app->put('/{entity}/{id}', function ($entity, $id, Request $request) use($app, $em, $filter) {
    if (!($data = $request->get($entity))) {
        return new Response('Missing parameters.', 400, array('Content-Type' => 'text/json'));
    }
    if (!($entity = $em->find('model\\' . ucfirst($entity), $id))) {
        return new Response('Not found.', 404, array('Content-Type' => 'text/json'));
    }
    $entity->set($data);
    $entity->setUpdated(new \DateTime("now"));
    if (count($app['validator']->validate($entity)) > 0) {
        return new Response('Invalid parameters.', 400, array('Content-Type' => 'text/json'));
    }
    //Filter entity
    $filter->filterEntity($entity);
    $em->persist($entity);
    $em->flush();
    return new Response($entity->toJson(), 200);
});
$app->delete('/{entity}/{id}', function ($entity, $id) use($app, $em) {
    if (!($entity = $em->find('model\\' . ucfirst($entity), $id))) {
        return new Response('Data not found.', 404, array('Content-Type' => 'text/json'));
    }
    $em->remove($entity);
    $em->flush();
    return new Response('Data deleted.', 200);
Пример #19
0
    $name = $app['request']->get('name');
    $phone = $app['request']->get('phone');
    $result = $app['db']->insert('phonebook', array('name' => $name, 'phone' => $phone));
    if (!$result) {
        return $app->abort(500, 'User not added');
    }
    $id = $app['db']->lastInsertId();
    return $app->json(array('status' => 'ok', 'message' => 'User successfully added', 'id' => $id));
});
//Обновить пользователя
$app->put('/api/users/{id}', function ($id) use($app) {
    $name = $app['request']->get('name');
    $phone = $app['request']->get('phone');
    $sql = 'SELECT * FROM phonebook WHERE id = ?';
    $user = $app['db']->fetchAssoc($sql, array($id));
    if (!$user) {
        return $app->abort(400, 'User not exists');
    }
    $result = $app['db']->update('phonebook', array('name' => $name, 'phone' => $phone), array('id' => $id));
    return $app->json(array('status' => 'ok', 'message' => 'User successfully updated'));
})->assert('id', '\\d+');
//Удалить пользователя
$app->delete('/api/users/{id}', function ($id) use($app) {
    $result = $app['db']->delete('phonebook', array('id' => $id));
    if (!$result) {
        return $app->abort(400, 'User not exists');
    }
    return $app->json(array('status' => 'ok', 'message' => 'User successfully deleted'));
})->assert('id', '\\d+');
//Обработчик ошибок
$app->error(function (\Exception $e, $code) use($app) {
Пример #20
0
Файл: api.php Проект: bazylu/web
    $response->setEncodingOptions(JSON_NUMERIC_CHECK);
    $response->setData($clients);
    return $response;
});
$app->get('/client/{clientId}', function ($clientId) use($app, $DataProvider) {
    $clientDetails = $DataProvider->getClient($clientId);
    if (!$clientDetails) {
        return $app->json(['errorMessage' => 'Client Not Found'], 404);
    }
    return $app->json($clientDetails);
});
$app->put('/client/{clientId}', function (Request $request, $clientId) use($app, $DataProvider) {
    $clientDetails = $DataProvider->getClient($clientId);
    if (!$clientDetails) {
        return $app->json(['errorMessage' => 'Client Not Found'], 404);
    }
    $updateData = $DataProvider->getRequestData();
    $result = $DataProvider->updateClient($clientId, $updateData);
    return $app->json(['message' => 'Client updated!']);
});
$app->post('/client', function (Request $request) use($app, $DataProvider) {
    $insertData = $DataProvider->getRequestData();
    $newClientId = $DataProvider->saveNewClient($insertData);
    if (false == $newClientId) {
        return $app->json(['errorMessage' => 'Can not insert user'], 500);
    }
    $clientDetails = $DataProvider->getClient($newClientId);
    return $app->json(['message' => 'Client created!', 'client' => $clientDetails]);
});
$app->delete('/client/{clientId}', function (Request $request, $clientId) use($app, $DataProvider) {
    $DataProvider->deleteClient($clientId);
Пример #21
0
<?php

require_once __DIR__ . '/../vendor/autoload.php';
use Silex\Provider\MonologServiceProvider;
$app = new Silex\Application();
$app->register(new MonologServiceProvider(), array('monolog.logfile' => __DIR__ . '/../logs/dev.log'));
$app->match('/', function () use($app) {
    $app['monolog']->addInfo('Logging example in the status route');
    return 'Up and running.';
})->method('GET|POST');
/* [START] here we hardcode happy flow functionality for user stories */
$app->get('/vehicles', function () use($app) {
    return '[{"id":123, "name": "Pansy"}]';
});
$app->post('/vehicles', function () use($app) {
    return '{"id":123, "name": "Pansy"}';
});
$app->put('/vehicles/{id}', function ($id) use($app) {
    return sprintf('{"id":%s, "name": "Pansy updated"}', $id);
});
/* [ END ] here we hardcode happy flow functionality for user stories */
return $app;