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
39 changes: 23 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,27 +1,34 @@
# WordPress Back-end Challenge
# Apiki Favoritos

Desafio para os futuros programadores back-end em WordPress da Apiki.
Plugin WordPress para favoritar posts via WP REST API.

## Introdução
## Instalação

Desenvolva um Plugin em WordPress que implemente a funcionalidade de favoritar posts para usuários logados usando a [WP REST API](https://developer.wordpress.org/rest-api/).
1. Copie a pasta `apiki-favoritos` para `wp-content/plugins/`
2. Ative o plugin no painel do WordPress em **Plugins > Plugins instalados**
3. A tabela `apiki_favoritos` será criada automaticamente no banco de dados

**Especifícações**:
## Endpoints

* Possibilidade de favoritar e desfavoritar um post;
* Persistir os dados em uma [tabela a parte](https://codex.wordpress.org/Creating_Tables_with_Plugins);
Base URL: `/wp-json/apiki/v1`

## Instruções
### Listar favoritos

1. Efetue o fork deste repositório e crie um branch com o seu nome e sobrenome. (exemplo: fulano-dasilva)
2. Após finalizar o desafio, crie um Pull Request.
3. Aguarde algum contribuidor realizar o code review.
```
GET /wp-json/apiki/v1/favoritos
```

## Pré-requisitos
Retorna todos os posts favoritados pelo usuário logado.

* PHP >= 5.6
* Orientado a objetos
### Favoritar um post

## Dúvidas
```
POST /wp-json/apiki/v1/favoritos/{post_id}
```

### Desfavoritar um post

```
DELETE /wp-json/apiki/v1/favoritos/{post_id}
```

Em caso de dúvidas, crie uma issue.
20 changes: 20 additions & 0 deletions apiki-favoritos.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php
/**
* Plugin Name: Apiki Favoritos
* Description: Permite que usuários logados favoritem e desfavoritem posts via WP REST API.
* Version: 1.0.0
* Author: David Lucas
* License: MIT
*/

declare(strict_types=1);

require_once plugin_dir_path(__FILE__) . 'src/class-tabela.php';
require_once plugin_dir_path(__FILE__) . 'src/class-favoritos.php';

register_activation_hook(__FILE__, ['Tabela', 'criar']);

add_action('rest_api_init', function () {
$favoritos = new Favoritos();
$favoritos->registrarRotas();
});
182 changes: 182 additions & 0 deletions src/class-favoritos.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
<?php
/**
* Classe responsável pelas rotas e lógica de favoritos.
*
* @package ApikiFavoritosPosts
*/

declare(strict_types=1);

/**
* Favoritos via WP REST API.
*/
class Favoritos
{
/**
* Namespace da API.
*
* @var string
*/
private $_namespace = 'apiki/v1';

/**
* Nome da tabela.
*
* @var string
*/
private $_tabela;

/**
* Construtor.
*/
public function __construct()
{
global $wpdb;
$this->_tabela = $wpdb->prefix . Tabela::NOME;
}

/**
* Registra as rotas da REST API.
*
* @return void
*/
public function registrarRotas()
{
register_rest_route($this->_namespace, '/favoritos', [
'methods' => 'GET',
'callback' => [$this, 'listar'],
'permission_callback' => [$this, 'usuarioLogado'],
]);

register_rest_route($this->_namespace, '/favoritos/(?P<post_id>\d+)', [
'methods' => 'POST',
'callback' => [$this, 'favoritar'],
'permission_callback' => [$this, 'usuarioLogado'],
]);

register_rest_route($this->_namespace, '/favoritos/(?P<post_id>\d+)/deletar', [
'methods' => 'POST',
'callback' => [$this, 'desfavoritar'],
'permission_callback' => [$this, 'usuarioLogado'],
]);
}

/**
* Verifica se o usuário está logado.
*
* @return bool
*/
public function usuarioLogado()
{
return is_user_logged_in();
}

/**
* Lista os posts favoritados pelo usuário logado.
*
* @return WP_REST_Response
*/
public function listar()
{
global $wpdb;

$usuarioId = get_current_user_id();
$favoritos = $wpdb->get_results(
$wpdb->prepare(
"SELECT post_id, criado_em FROM {$this->_tabela}
WHERE usuario_id = %d ORDER BY criado_em DESC",
$usuarioId
)
);

return rest_ensure_response($favoritos);
}

/**
* Favorita um post para o usuário logado.
*
* @param WP_REST_Request $requisicao dados da requisição.
*
* @return WP_REST_Response
*/
public function favoritar($requisicao)
{
global $wpdb;

$postId = (int) $requisicao['post_id'];
$usuarioId = get_current_user_id();

if (!get_post($postId)) {
return new WP_REST_Response(
['mensagem' => 'Post não encontrado.'],
404
);
}

$jaFavoritado = $wpdb->get_var(
$wpdb->prepare(
"SELECT id FROM {$this->_tabela}
WHERE usuario_id = %d AND post_id = %d",
$usuarioId,
$postId
)
);

if ($jaFavoritado) {
return new WP_REST_Response(
['mensagem' => 'Post já está nos favoritos.'],
409
);
}

$wpdb->insert(
$this->_tabela,
[
'usuario_id' => $usuarioId,
'post_id' => $postId,
],
['%d', '%d']
);

return new WP_REST_Response(
['mensagem' => 'Post favoritado com sucesso.'],
201
);
}

/**
* Desfavorita um post para o usuário logado.
*
* @param WP_REST_Request $requisicao dados da requisição.
*
* @return WP_REST_Response
*/
public function desfavoritar($requisicao)
{
global $wpdb;

$postId = (int) $requisicao['post_id'];
$usuarioId = get_current_user_id();

$deletado = $wpdb->delete(
$this->_tabela,
[
'usuario_id' => $usuarioId,
'post_id' => $postId,
],
['%d', '%d']
);

if (!$deletado) {
return new WP_REST_Response(
['mensagem' => 'Post não está nos favoritos.'],
404
);
}

return new WP_REST_Response(
['mensagem' => 'Post desfavoritado com sucesso.'],
200
);
}
}
46 changes: 46 additions & 0 deletions src/class-tabela.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php
/**
* Classe que cria a tabela de favoritos no banco de dados.
*
* @package ApikiFavoritos
*/

declare(strict_types=1);

/**
* Tabela de favoritos.
*/
class Tabela
{
/**
* Nome da tabela no banco.
*
* @var string
*/
const NOME = 'apiki_favoritos';

/**
* Cria a tabela de favoritos no banco de dados.
*
* @return void
*/
public static function criar()
{
global $wpdb;

$tabela = $wpdb->prefix . self::NOME;
$charset = $wpdb->get_charset_collate();

$sql = "CREATE TABLE IF NOT EXISTS {$tabela} (
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
usuario_id BIGINT(20) UNSIGNED NOT NULL,
post_id BIGINT(20) UNSIGNED NOT NULL,
criado_em DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY usuario_post (usuario_id, post_id)
) {$charset};";

require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta($sql);
}
}