Skip to content
Closed
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
The diff you're trying to view is too large. We only load the first 3000 changed files.
7 changes: 7 additions & 0 deletions .htaccess
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^$ public/index.php [L]
RewriteRule (.*) public/$1 [L]
90 changes: 90 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,93 @@ A API deverá atender às seguintes exigências:
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.**


# API de Contato

## Observações
```
O sistema foi desenvolvido como uma API para envio e recebimento de contatos
O banco de dados SqLite já está configurado, porém o sistema aceita a utilização do MySql como banco de dados.
```

## Configurações
1 - habilitar a conexão PDO e o SQLITE
```
extension=php_pdo.dll
extension=php_sqlite.dll
```
2 - criar um vhost
```
<VirtualHost *:80>
DocumentRoot "C:/xampp/htdocs/contato.local"
ServerName contato.local
ErrorLog "logs/contato_local-error.log"
CustomLog "logs/contato_local-access.log" common
</VirtualHost>
```
3 - redirecionar o hosts
* C:\Windows\System32\drivers\etc\hosts
* 127.0.0.1 contato.local

4 - testar URL
* Validar se retorna o seguinte texto
```
Contacts
Developer: Caio Santos
Email: santoscaio@gmail.com
```

5 - Efetuar as requisições com o seguinte usuário e senha
```
usuário: ecs-php
senha: santoscaio
```

## Endpoints (*CRUD de contato*)
- Todos os retornos são respondidos em HTTP mais a informação em JSON
- Atualmente uso o postman para consumo e teste de api's
- Inserir contato
- Insere um novo contato no banco de dados
- method: **POST**
- http://contato.local/contato
- Campos: **[nome, email, telefone, descricao]**
- Campos **obrigatórios: [nome, email, descricao]**
- Retorno: **id**
- Atualizar contato
- Atualiza um contato no banco de dados
- method: **PUT**
- http://contato.local/contato/[id]
- Campo obrigatório: **[id]**
- Campos opcionais: **[nome, email, telefone, descricao]**
- Retorno: **id**
- Exemplo: http://contato.local/contato/1
- Buscar contato
- Busca um contato no banco de dados
- method: **GET**
- http://contato.local/contato/[id]
- Campo obrigatório: **[id]**
- Retorno: **dados do contato**
- Exemplo: http://contato.local/contato/1
- Deletar contato
- Deleta um contato no banco de dados
- method: **DELETE**
- http://contato.local/contato/[id]
- Campo obrigatório: **[id]**
- Retorno: **id**
- Exemplo: http://contato.local/contato/1

# Extra Documentation
## Semantics and Content of HTTP
https://tools.ietf.org/html/rfc7231

## List of HTTP status codes
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes


# Lumen PHP Framework
## Official Documentation
Documentation for the framework can be found on the [Lumen website](http://lumen.laravel.com/docs).

## License
The Lumen framework is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT)
Empty file added app/Console/Commands/.gitkeep
Empty file.
29 changes: 29 additions & 0 deletions app/Console/Kernel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Laravel\Lumen\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
//
];

/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
//
}
}
10 changes: 10 additions & 0 deletions app/Events/Event.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace App\Events;

use Illuminate\Queue\SerializesModels;

abstract class Event
{
use SerializesModels;
}
46 changes: 46 additions & 0 deletions app/Exceptions/Handler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

namespace App\Exceptions;

use Exception;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
HttpException::class,
];

/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
return parent::report($e);
}

/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
// return parent::render($request, $e);
$msg = 'Bad Request!';
return response()->json($msg, '404');
}
}
119 changes: 119 additions & 0 deletions app/Http/Controllers/ContactController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
<?php

namespace App\Http\Controllers;

use DB;
use Illuminate\Http\Request;
use Symfony\Component\Config\Definition\Exception\Exception;
use App\Models as Model;

class ContactController extends Controller {

public function select($id) {
try {
if (isset($id)) {
$contato = Model\Contacts::where('id_contact', array($id))->get()->toArray();
if (count($contato) == 0) {
abort('404');
} else {
return response()->json($contato);
}
} else {
abort('404');
}
} catch (Exception $e) {
abort('404');
}
}

public function insert(Request $request) {
try {
$data = $request->all();
if (isset($data['name'])) {
$insertContact = New Model\Contacts();
$insertContact->name = $data['name'];
$insertContact->phone = $data['phone'];
$insertContact->email = $data['email'];
$insertContact->description = $data['description'];

$statusContact = $insertContact->save();

if ($statusContact) {
$json['id'] = DB::getPdo()->lastInsertId();
return response()->json($json, 201);
} else {
abort('404');
}
} else {
abort('404');
}
} catch (Exception $e) {
abort('404');
}
}

public function update(Request $request, $id) {
try {
$data = $request->all();

if (isset($id) && is_numeric($id) && $id > 0) {
$updateContact = New Model\Contacts();
if (isset($data['name'])) {
$updateFields['name'] = $data['name'];
}
if (isset($data['phone'])) {
$updateFields['phone'] = $data['phone'];
}
if (isset($data['email'])) {
$updateFields['email'] = $data['email'];
}
if (isset($data['description'])) {
$updateFields['description'] = $data['description'];
}

$updateContact->id_contact = $id;
$statusContact = $updateContact->where('id_contact', $id)->update($updateFields);

if ($statusContact) {
$json['id'] = $id;
return response()->json($json, 201);
} else {
abort('404');
}
} else {
abort('404');
}
} catch (Exception $e) {
abort('404');
}
}

public function delete($id) {
try {
if (isset($id)) {
$validateContact = Model\Contacts::where('id_contact', array($id))->get()->toArray();
if (count($validateContact) == 0) {
abort('404');
} else {
$idContact = $validateContact[0]['id_contact'];
$deleteContact = New Model\Contacts();
$deleteContact->id_contact = $idContact;

$statusContact = $deleteContact->destroy($idContact);

if ($statusContact) {
$json['id'] = $id;
return response()->json($json, 200);
} else {
abort('404');
}
}
} else {
abort('404');
}
} catch (Exception $e) {
abort('404');
}
}

}
10 changes: 10 additions & 0 deletions app/Http/Controllers/Controller.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace App\Http\Controllers;

use Laravel\Lumen\Routing\Controller as BaseController;

class Controller extends BaseController
{
//
}
23 changes: 23 additions & 0 deletions app/Http/Middleware/BasicAuthMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace App\Http\Middleware;

use Closure;

class BasicAuthMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next) {
if($request->getUser() != 'ecs-php' || $request->getPassword() != 'santoscaio') {
$headers = array('WWW-Authenticate' => 'Basic');
return response('Authentication required', 401, $headers);
}
return $next($request);
}
}
20 changes: 20 additions & 0 deletions app/Http/Middleware/ExampleMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace App\Http\Middleware;

use Closure;

class ExampleMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request);
}
}
Loading