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
22 changes: 22 additions & 0 deletions controllers/SiteController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace app\controllers;

use app\services\OoptimoUserService;
use yii\data\ArrayDataProvider;
use yii\web\Controller;

class SiteController extends Controller{
Expand Down Expand Up @@ -33,4 +35,24 @@ public function actionIndex(){
public function actionTest1(){
return $this->render('test1');
}

/**
* Displays test 2.
*
* @return string
*/
public function actionTest2(){
$ooptimoUserService = new OoptimoUserService();
$data = $ooptimoUserService->fetchData();
//Procesado de los datos en la capa de servicios
$usuarios = $ooptimoUserService->process($data);

$dataProvider = new ArrayDataProvider([
'allModels' => $usuarios,
'pagination' => ['pageSize'=>15]
]);

// Mostrar los usuarios
return $this->render('test2', ['usuarios' => $usuarios, 'dataProvider' => $dataProvider]);
}
}
79 changes: 79 additions & 0 deletions models/OoptimoUser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

namespace app\models;


use yii\base\Model;

class OoptimoUser extends Model
{
public $id;
public $userId;
public $title;
public $body;

/**
* @return mixed
*/
public function getId()
{
return $this->id;
}

/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}

/**
* @return mixed
*/
public function getUserId()
{
return $this->userId;
}

/**
* @param mixed $userId
*/
public function setUserId($userId)
{
$this->userId = $userId;
}

/**
* @return mixed
*/
public function getTitle()
{
return $this->title;
}

/**
* @param mixed $title
*/
public function setTitle($title)
{
$this->title = $title;
}

/**
* @return mixed
*/
public function getBody()
{
return $this->body;
}

/**
* @param mixed $body
*/
public function setBody($body)
{
$this->body = $body;
}

}
35 changes: 35 additions & 0 deletions services/OoptimoUserService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace app\services;

use app\models\OoptimoUser;

class OoptimoUserService
{
private $apiUrl = 'https://jsonplaceholder.typicode.com/posts';

function fetchData(){
// Obtener datos de la API
$response = file_get_contents($this->apiUrl);

if ($response === false) {
return [];
}

// Decodificar JSON
return json_decode($response, true);
}

function process($usuarios){
$usuarios = array_map( function($usuario){
$tmpUser = new OoptimoUser();
$tmpUser->setTitle( htmlspecialchars($usuario['title']) );
$tmpUser->setBody(htmlspecialchars($usuario['body']));
$tmpUser->setId( htmlspecialchars($usuario['id']) );
$tmpUser->setUserId( htmlspecialchars($usuario['userId']) );
return $tmpUser;
}, $usuarios);
return $usuarios;
}

}
3 changes: 2 additions & 1 deletion views/site/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
<p>Solve the following exercises:</p>

<ul>
<li><a href="<?=Url::to(['site/test1'])?>">Test 1 — Consume API</a></li>
<li><a href="<?=Url::to(['site/test1'])?>">Test 1 — Consume API (acceso directo mediante javascript)</a></li>
<li><a href="<?=Url::to(['site/test2'])?>">Test 2 — Consume API (filtrando los datos por backend)</a></li>
</ul>

<p>If you have any questions or issues, feel free to send an email with your queries to <a href="mailto:asunyer@ooptimo.com">asunyer@ooptimo.com</a>, and we will try to assist you as soon as possible.</p>
Expand Down
37 changes: 36 additions & 1 deletion views/site/test1.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<div class="body-content">
<div class="row mt-5">
<div class="col-md-12">
<h2>Test 1 — Consume API</h2>
<h2>Test 1 — Consume API (filtrando los datos por backend, mediante framework Yii2)</h2>
<p>The goal is to load data from an external API and display it on screen.</p>
<p>We will use the "Fake API" <a href="https://jsonplaceholder.typicode.com/" target="_blank">JSONPlaceholder</a> to load data.<br>Use this endpoint: <code>https://jsonplaceholder.typicode.com/posts</code>, and display a list on this same page with the data retrieved.</p>

Expand All @@ -28,6 +28,41 @@
<div class="posts-list">
<div class="row mt-4">
<h2>Posts</h2>
<div id="user-list" class="list-group"></div>
</div>
</div>
</div>

<script>
const apiUrl = 'https://jsonplaceholder.typicode.com/posts';

async function fetchAndDisplayUsers() {
try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(`Error fetching data: ${response.status}`);
}
const users = await response.json();
const userList = document.getElementById('user-list');

users.forEach(user => {
const userItem = document.createElement('div');
const template = `<div style="margin:1em" class="card border border-primary">
<div class="card-body">
<h4 class="card-title">Id: ${user.id}</h4>
<p class="card-text">userId: ${user.userId} <br/> title: ${user.title} <br/> body: ${user.body}</p>
</div>
</div>`;

userItem.innerHTML = template;
userList.appendChild(userItem);
});
} catch (error) {
console.error('Error al obtener usuarios:', error);
}
}

window.onload = function(e){
fetchAndDisplayUsers();
}
</script>
41 changes: 41 additions & 0 deletions views/site/test2.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

/** @var yii\web\View $this */
/** @var \yii\data\ArrayDataProvider $dataProvider */

$this->title = 'Test 2 — ooptimo';
?>
<div class="site-test1">
<div class="body-content">
<div class="row mt-5">
<div class="col-md-12">
<h2>Test 2 — Consumir API (filtrando los datos por backend, mediante framework Yii2)</h2>
<p>El objetivo es cargar datos de una API externa y mostrarlos en pantalla.</p>
<p>Usaremos la "Fake API" <a href="https://jsonplaceholder.typicode.com/" target="_blank">JSONPlaceholder</a> para cargar datos.<br>Usa este endpoint: <code>https://jsonplaceholder.typicode.com/posts</code>, y muestra una lista en esta misma página con los datos obtenidos.</p>

<h5>Ayuda</h5>
<ul>
<li>Estamos usando el framework MVC Yii v2: <a href="https://www.yiiframework.com/doc/guide/2.0/en" target="_blank">Guia</a>.</li>
<li>La API externa es la de JSONPlaceholder: <a href="https://jsonplaceholder.typicode.com/guide/" target="_blank">Guia</a></li>
<li>Los archivos relevantes estan en <code>/controllers</code>, <code>/models</code> y <code>/views</code>.</li>
<li>Para los estilos puedes editar directamente el archivo <code>/web/css/site.css</code>.</li>
</ul>
</div>
</div>
</div>

<hr>

<div class="posts-list">
<div class="row mt-4">
<h2>Posts</h2>
<?php

echo \yii\grid\GridView::widget([
'dataProvider' => $dataProvider,
]);

?>
</div>
</div>
</div>
5 changes: 5 additions & 0 deletions web/css/site.css
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,8 @@ main > .container {
margin-top: 5px;
color: #999;
}

.pagination a{
margin:2px;
text-decoration: none;
}