Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
vendor/
.idea/
68 changes: 34 additions & 34 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,34 +1,34 @@
# A tarefa
Sua tarefa consiste em desenvolver uma API RESTful para manipular um determinado recurso. Deverá ser utilizado o framework Silex.

# Requisitos
A escolha do recurso deverá ser feita pelo desenvolvedor, atendendo apenas os requisitos mínimos abaixo:

* Deverá conter um ID
* Deverá conter pelo menos quatro propriedades (exemplos: nome, email, etc.)
* Deverá conter campos que armazenem as datas de criação e alteração do recurso

A API deverá atender às seguintes exigências:

* Listagem de todos os recursos
* Busca de um recurso pelo ID
* Criação de um novo recurso
* Alteração de um recurso existente
* Exclusão de um recurso
* Aceitar e retornar apenas JSON
* Deverá possuir algum método de autenticação para utilização de seus endpoints

# Ferramentas
* PHP
* Banco de dados MySQL
* Framework Silex

# Fluxo de desenvolvimento
1. Faça um fork deste repositório
2. Crie uma nova branch e nomeie-a com seu usuário do Github
3. Quando o desenvolvimento estiver concluído, faça um pull request

# Padrões de nomenclatura
1. Código fonte, nome do banco de dados, tabelas e campos devem estar em inglês

**Inclua no seu commit todos os arquivos necessários para que possamos testar o código.**
**Ambiente utilizado**
* PHP 7.0.4
* MySQL 5.7.11

1. Criar o bando de dados rodando o script _`database.sql`_
2. Acessar a raiz do projeto pelo terminal e digitar o comando `composer install`
3. Ainda no terminal digitar o comando `php -S localhost:80 -t application/`

**Autenticação**
```
curl -X POST http://localhost:80/login -H 'content-type: application/json' -d '{"user":"admin", "password":"123"}'
```
**Observação:** Salvar o token retornado para as demais requisições

**Listar todos**
```
curl -X GET http://localhost:80/livros -H 'cache-control: no-cache' -H 'content-type: application/json' -H 'x-access-token: {token}'
```
**Listar um**
```
curl -X GET http://localhost:80/livro/{id} -H 'cache-control: no-cache' -H 'content-type: application/json' -H 'x-access-token: {token}'
```
**Inserir**
```
curl -X POST http://localhost:80/livro -H 'cache-control: no-cache' -H 'content-type: application/json' -H 'x-access-token: {token}' -d '{"title": "{valor}", "author": "{valor}", "publishing_company": "{valor}", "pages": {valor}}'
```
**Alterar**
```
curl -X PUT http://localhost:80/livro/{id} -H 'cache-control: no-cache' -H 'content-type: application/json' -H 'x-access-token: {token}' -d '{"title": "{valor}", "author": "{valor}", "publishing_company": "{valor}", "pages": {valor}}'
```
**Deletar**
```
curl -X DELETE http://localhost:80/livro/{id} -H 'cache-control: no-cache' -H 'content-type: application/json' -H 'x-access-token: {token}'
```
95 changes: 95 additions & 0 deletions application/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
<?php
date_default_timezone_set('America/Sao_Paulo');
require_once __DIR__ . '/../vendor/autoload.php';

use Symfony\Component\HttpFoundation\Request;

$app = new Silex\Application();

$dsn = 'mysql:dbname=test_thideoli;host=localhost;charset=utf8';
try {
$pdo = new PDO($dsn, 'root', '');
} catch (PDOException $e) {
echo 'Falha ao conectar: ' . $e->getMessage();
}

$app->before(function(Request $request) use ($app) {
if($request->isMethod('GET'))
return;
if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
$data = json_decode($request->getContent(), true);
$request->request->replace(is_array($data) ? $data : array());
} else {
return $app->json(array('error' => true, 'message' => 'Cabeçalho somente com Content-Type: application/json'), 404);
}
});

$app->before(function(Request $request) use ($app) {
echo $request->getPathInfo();
if($request->getPathInfo() == '/login')
return;
$token = $request->headers->get('x-access-token');
if(!$token)
return $app->json(array('error' => true, 'message' => 'Não a token'), 403);
if(md5('admin123') != $token)
return $app->json(array('error' => true, 'message' => 'Token inválido'), 403);
});

// POST /login
$app->post('/login', function(Request $request) use ($app) {
if($request->get('user') == 'admin' && $request->get('password') == '123')
return $app->json(array('error' => false, 'message' => null, 'content' => array('token' => md5('admin123'))));
else
return $app->json(array('error' => true, 'message' => 'Dado(s) incorreto(s).', 'content' => null), 401);
});

// GET /livros
$app->get('/livros', function () use ($app, $pdo) {
$statement = $pdo->prepare('select id, title, author, publishing_company, pages, inserted_in, changed_in from books');
$statement->execute();
$books = $statement->fetchAll(PDO::FETCH_ASSOC);
return $app->json(array('error' => false, 'message' => null, 'content' => array('books' => $books)));
});

// GET /livro/{id}
$app->get('/livro/{id}', function ($id) use ($app, $pdo) {
$statement = $pdo->prepare('select id, title, author, publishing_company, pages, inserted_in, changed_in from books where id=?');
$statement->execute([$id]);
$book = $statement->fetchAll(PDO::FETCH_ASSOC);
if(empty($book))
return $app->json(array('error' => true, 'message' => 'Livro não encontrado.', 'content' => null), 404);
return $app->json(array('error' => false, 'message' => null, 'content' => array('book' => $book)));
})->assert('id', '\d+');

// POST /livro
$app->post('/livro', function(Request $request) use ($app, $pdo) {
$data = json_decode($request->getContent(), true);
$statement = $pdo->prepare('insert into books (title, author, publishing_company, pages, inserted_in) VALUES(:title, :author, :publishing_company, :pages, now())');
$statement->execute($data);
$id = $pdo->lastInsertId();
if($id > 0)
return $app->json(array('error' => false, 'message' => 'Livro inserido', 'content' => array('id' => $id)), 201);
return $app->json(array('error' => true, 'message' => 'Livro não inserido', 'content' => null), 404);
});

// PUT /livro/{id}
$app->put('/livro/{id}', function(Request $request, $id) use ($app, $pdo) {
$data = json_decode($request->getContent(), true);
$data['id'] = $id;
$statement = $pdo->prepare('update books set title=:title, author=:author, publishing_company=:publishing_company, pages=:pages, changed_in=now() where id=:id');
$statement->execute($data);
if($statement->rowCount() < 1)
return $app->json(array('error' => true, 'message' => 'Livro não encontrado', 'content' => null), 404);
return $app->json(array('error' => false, 'message' => 'Livro alterado', 'content' => array('book' => $data)));
})->assert('id', '\d+');

// DELETE /livro/{id}
$app->delete('/livro/{id}', function($id) use ($app, $pdo) {
$statement = $pdo->prepare('delete from books where id = ?');
$statement->execute([$id]);
if($statement->rowCount() < 1)
return $app->json(array('error' => true, 'message' => 'Livro não encontrado', 'content' => null), 404);
return $app->json(array('error' => false, 'message' => 'Livro deletado', 'content' => null));
})->assert('id', '\d+');

$app->run();
5 changes: 5 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"require": {
"silex/silex": "~2.0"
}
}
Loading