PHP code example of jonathansilva / nano

1. Go to this page and download the library: Download jonathansilva/nano library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jonathansilva / nano example snippets




= Nano\Core\Router\Instance::create();

$app->use('App\Middleware\Token\Assert');

$app->notFound('App\Callback\Page\NotFound');

$app->get('/about', fn ($req, $res) => $res->view('about'));

$app->get('/hello/{name}', function ($req, $res) {
    echo $req->params()->name;
});

$app->post('/api/test', function ($req, $res) {
    $res->json(200, array('message' => 'Hello World!'));
});

$app->start();

$app->get(
    '/me', // Path
    'App\Callback\Page\Me', // Callback
    ['App\Middleware\Token\Ensure'] // Middleware
);

$app->get('/login', 'App\Callback\Page\Login@index');

$app->get('/login', 'App\Callback\Page\Login');

class Login
{
    public function handle($req, $res)
    {
        // TODO
    }
}

$app->load(__DIR__ . '/src/routes.xml');

$app->use('App\Middleware\A');
$app->use('App\Middleware\B');



namespace App\Middleware\Token;

use Nano\Core\Security\{ CSRF, JWT };

class Assert
{
    public function handle($req, $res)
    {
        CSRF::assert($req, $res);
        JWT::assert($req, $res, '/login');
    }
}



namespace App\Middleware\Token;

use Nano\Core\Security\JWT;

class Ensure
{
    public function handle($req, $res)
    {
        JWT::ensure($req, $res, '/login');
    }
}

$app->get(
    '/dashboard',
    'App\Callback\Page\Dashboard',
    ['App\Middleware\Token\Ensure', 'App\Middleware\Token\Role::admin']
);



namespace App\Middleware;

use App\Service\Auth\Role as Service;
use Exception;

class Role
{
    public function handle($req, $res, $args)
    {
        try {
            $id = $req->query()->data->id;

            $role = new Service()->getRoleByUserId($id);

            if (!in_array($role, $args)) {
                $res->redirect('/me');
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }
}



namespace App\Callback\Page;

use App\Service\Book\Read as Service;
use Exception;

class Book
{
    public function handle($req, $res)
    {
        try {
            $filter = $req->query()->filter ?? null;

            $res->view('books', array('books' => new Service()->all($filter)));
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }
}



namespace App\Callback\Payment;

use Nano\Core\Error;
use Exception;

class Create
{
    public function handle($req, $res)
    {
        try {
            $url = 'https://...';

            $headers = [
                'Content-Type: application/json',
                'Authorization: Bearer TOKEN'
            ];

            $body = json_encode(array(...));

            $data = $req->http()->post($url, $headers, $body);

            if (!$data) {
                throw new Exception('Erro ao realizar requisição');
            }

            $info = json_decode($data);

            $res->json($info->status, array('message' => $info->message));
        } catch (Exception $e) {
            Error::throwJsonException(500, $e->getMessage());
        }
    }
}



namespace App\Callback\Book;

use App\Service\Book\Create as Service;
use Nano\Core\Error;
use Exception;

class Create
{
    public function handle($req, $res)
    {
        try {
            $rules = [
                'title' => 'date($rules);

            $data = $req->data();

            $res->json(201, array('message' => new Service()->register($data)));
        } catch (Exception $e) {
            Error::throwJsonException(500, $e->getMessage());
        }
    }
}

$rules = [
    'password' => '

$req->validate($rules, 'en-US');



namespace App\Callback\Book;

use Nano\Core\Error;
use Exception;

class Read
{
    public function handle($req, $res)
    {
        try {
            // TODO
        } catch (Exception $e) {
            Error::throwJsonException(500, $e->getMessage());
        }
    }
}



namespace App\Callback\Page;

class Home
{
    public function handle($req, $res)
    {
        $res->view('home', array('welcome' => 'Welcome to Nano!'));
    }
}

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE');
header('Access-Control-Allow-Headers: Origin, Accept, Content-Type, Authorization, X-Requested-With');



namespace App\Callback\Page;

use Nano\Core\View\Form;

class Register
{
    public function handle($req, $res)
    {
        if ($req->hasCookie('token')) {
            $res->redirect('/me');
        }

        $form = Form::session($req);

        $res->view('register', [
            'csrf' => $form->csrf,
            'errors' => $form->errors
        ]);
    }
}



namespace App\Callback\User;

use App\Service\User\Create as Service;
use Nano\Core\Error;
use Exception;

class Create
{
    public function handle($req, $res)
    {
        try {
            $rules = [
                'name' => 'oken', new Service()->register($data));
            $res->redirect('/me');
        } catch (Exception $e) {
            $req->setSession('errors', Error::parse($e->getMessage()));
            $res->redirect('/cadastro');
        }
    }
}



namespace App\Service\User;

use Nano\Core\Database;
use Nano\Core\Security\JWT;
use Exception;
use PDO;

class Create
{
    private PDO $db;

    public function __construct()
    {
        $this->db = Database::instance();
    }

    public function register(object $data): string
    {
        if ($this->emailExists($data->email)) {
            throw new Exception('O e-mail informado já existe');
        }

        $hash = password_hash($data->password, PASSWORD_ARGON2ID);

        try {
            $query = "INSERT INTO users (name, email, password) VALUES (:name, :email, :password)";

            $stmt = $this->db->prepare($query);
            $stmt->bindValue(':name', $data->name, PDO::PARAM_STR);
            $stmt->bindValue(':email', $data->email, PDO::PARAM_STR);
            $stmt->bindValue(':password', $hash, PDO::PARAM_STR);
            $stmt->execute();

            return JWT::encode(array('id' => $this->db->lastInsertId()));
        } catch (PDOException $e) {
            throw new Exception('Erro ao cadastrar, tente novamente');
        }
    }

    private function emailExists(string $email): bool
    {
        $query = "SELECT id FROM users WHERE email = :email LIMIT 1";

        $stmt = $this->db->prepare($query);
        $stmt->execute(array(':email' => $email));

        return (bool) $stmt->fetchColumn();
    }
}



namespace App\Callback\Page;

use Nano\Core\View\Form;

class Login
{
    public function handle($req, $res)
    {
        if ($req->hasCookie('token')) {
            $res->redirect('/me');
        }

        $form = Form::session($req);

        $res->view('login', [
            'csrf' => $form->csrf,
            'errors' => $form->errors
        ]);
    }
}



namespace App\Callback\Auth;

use App\Service\Auth\Login as Service;
use Nano\Core\Error;
use Exception;

class Login
{
    public function handle($req, $res)
    {
        try {
            $rules = [
                'email' => '('/me');
        } catch (Exception $e) {
            $req->setSession('errors', Error::parse($e->getMessage()));
            $res->redirect('/login');
        }
    }
}



namespace App\Service\Auth;

use Nano\Core\Database;
use Nano\Core\Security\JWT;
use Exception;
use PDO;

class Login
{
    private PDO $db;

    public function __construct()
    {
        $this->db = Database::instance();
    }

    public function authenticate(object $data): string
    {
        $query = "SELECT id, password FROM users WHERE email = :email";

        $stmt = $this->db->prepare($query);
        $stmt->execute(array(':email' => $data->email));

        $result = $stmt->fetchObject();

        if (!password_verify($data->password, $result->password)) {
            throw new Exception('E-mail ou senha inválido');
        }

        return JWT::encode(array('id' => $result->id));
    }
}



namespace App\Callback\Auth;

class Logout
{
    public function handle($req, $res)
    {
        if ($req->hasCookie('token')) {
            $req->removeCookie('token');
            $res->redirect('/login');
        }

        $res->redirect('/');
    }
}



namespace App\Callback\Page;

use App\Service\User\Read as Service;
use Exception;

class Me
{
    public function handle($req, $res)
    {
        try {
            $id = $req->query()->data->id;

            $res->view('me', array('data' => new Service()->getUserInfoById($id)));
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }
}
nginx
location / {
    if ($script_filename !~ "-f") {
        rewrite ^(.*)$ /index.php?uri=/$1 break;
    }
}
html
{% foreach ($errors as $value): %}
    <div>{{ $value }}</div>
{% endforeach; %}