text:
<file_sep><?php

namespace Framework\Database;

use PDO;

class Connection
{
	protected $pdo;

	public function __construct(array $config)
	{
		try {
			$this->pdo = new PDO(
				"mysql:host={$config['host']};dbname={$config['name']}",
				$config['username'],
			 	$config['password'],
			 	$config['options']
		 	);
		} catch (PDOException $e) {
			die($e->getMessage());
		}
	}
	public function selectStatement(string $table, string $query, array $values)
	{
		$statement = $this->pdo->prepare($query);
		$statement->execute($values);
		return $statement->fetchAll(PDO::FETCH_CLASS, "App\\Model\\".ucfirst($table));
	}
	public function statement(string $query, array $values)
	{
		$statement = $this->pdo->prepare($query);
		$statement->execute(array_values($values));

		return $this->pdo->lastInsertId();
	}
	public function updateStatement(string $query, array $values)
	{
		$statement = $this->pdo->prepare($query);
		return $statement->execute($values);
	}
}<file_sep><?php template('header'); ?>

Agentes: Editar

    <form method="POST" action="/agentes">
        <input type="hidden" name="_method" value="PATCH">

            Nome
            <input type="text" class="form-control" name="nome" id="nome" placeholder="Nome" value="<?= $agente->nome; ?>">

            CPF
            <input type="text" class="form-control" name="cpf" id="cpf" placeholder="xxx.xxx.xxx-xx" value="<?= $agente->cpf; ?>">

            Estado
            <input type="text" class="form-control" name="estado" id="estado" placeholder="UF" value="<?= $agente->estado; ?>">

            Cidade
            <input type="text" class="form-control" name="cidade" id="cidade" placeholder="Cidade" value="<?= $agente->cidade; ?>">

            Usuário
            <input type="text" class="form-control" name="usuario" id="usuario" placeholder="Usuário" value="<?= $agente->usuario->username; ?>">

            Senha
            <input type="password" class="form-control" name="senha" id="senha" placeholder="Senha">

        <button type="submit" class="btn btn-default">Submit</button>
    </form>

<?php template('footer'); ?><file_sep><?php

use Framework\Application;

if (!function_exists('view')) {
    function view(string $view, array $data = [])
    {
        return Application::container('view')->make($view, $data);
    }
}
if (!function_exists('redirect')) {
    function redirect(string $to)
    {
        return Application::container('view')->redirect($to);
    }
}
if (!function_exists('template')) {
    function template(string $file)
    {
        return Application::container('view')->template($file);
    }
}
if (!function_exists('assets')) {
    function assets(string $asset, string $type)
    {
        return Application::container('view')->assets($asset, $type);
    }
}

if (!function_exists('dd')) {
    /**
     * Dump and Die
     * @param  mixed $value
     * @return mixed
     */
    function dd($value)
    {
        die(dump($value));
    }
}
if (!function_exists('container')) {
    function container(string $service)
    {
        return Application::container($service);
    }
}
if (!function_exists('request')) {
    function request(string $attr)
    {
        return Application::container('request')->getRequest($attr);
    }
}
if (!function_exists('number')) {
    function number($value) {
        return preg_replace('/\D/', '', $value);
    }
}
<file_sep><?php

namespace Framework\Database;

use ReflectionClass;

class DatabaseCollection
{
	public function __construct($all)
	{
		$this->add($all);
	}
	/**
	 * Add a route to DatabaseCollection
	 * @param Route $route [description]
	 */
	public function add($item)
	{
		$this->all = $item;

		return $this;
	}
	public function first()
	{
		if (is_array($this->all) && $this->all != [])
			return $this->all[0];
		return $this->all;
	}
	public function last()
	{
		if (is_array($this->all))
			return end($this->all);
		return $this->all;
	}
	public function all()
	{
		return $this->all;
	}
	public function __call($method, $parameters)
	{
		foreach ($this->all as $key => $item)
			$item->{$method} = $item->{$method}()->{$method};

		return $this;
	}
}
<file_sep><?php

namespace Framework\Database;

use Framework\Database\QueryBuilder;
use ReflectionClass;
use ReflectionProperty;

abstract class Model
{
	/**
	 * Do QueryBuilder access from Model Childrens
	 * @param  [type] $name      [description]
	 * @param  [type] $arguments [description]
	 * @return [type]            [description]
	 */
	public static function __callStatic($method, $parameters)
    {
     	$instance = (new static)->queryBuilder();
        return call_user_func_array([$instance, $method], $parameters);
    }
	public function save()
	{
		$query = $this->queryBuilder();

        // Has register, edit
        if ($this->hasAttribute('id')) {
            return $query->update((array)$this->getAttributes(), $this->table());
        }
        // Else, insert
		return $query->insert($this->getAttributes(), $this->table());
	}
	public function queryBuilder()
	{
		return new QueryBuilder($this->connection(), $this->table());
	}

	/**
	 * Retorna uma instacia da conexao
	 * @return PDO
	 */
	private function connection()
	{
		return container('connection');
	}
	public function table()
	{
		return strtolower(
			str_replace("App\\Model\\", "", get_class($this))
		);
	}
    public function hasOne(string $model, string $key = null, string $foreignkey = null)
    {
        $attribute = strtolower(str_replace("App\\", "", $model));

        $result = $this->queryBuilder()
            ->setTable($attribute)
            ->select()
            ->where($key, $this->{$foreignkey})->get()->all();

        $this->setAttribute($attribute, $result[0]);

        return $this;
    }
	public function setAttribute($key, $value)
	{
		//$classReflection = new ReflectionClass(get_class($this));

		// Verifica se o atribuito foi instanciado no model
		//if ($classReflection->hasProperty($key))
		$this->{$key} = $value;
	}
	public function getAttribute($key)
	{
		return $this->{$key};
	}
	public function getAttributes()
	{
		return $this;
	}
    public function hasAttribute($key)
    {
        if (isset($this->{$key}))
            return true;
        return false;
    }
	/**
     * Dynamically retrieve attributes on the model.
     *
     * @param  string  $key
     * @return mixed
     */
    public function __get($key)
    {
        return $this->getAttribute($key);
    }
    /**
     * Dynamically set attributes on the model.
     *
     * @param  string  $key
     * @param  mixed  $value
     * @return void
     */
    public function __set($key, $value)
    {
        $this->setAttribute($key, $value);
    }
}
<file_sep><?php

namespace App\Controller;

class HomeController
{
	public function __construct()
	{
		//$agentes = $this->database->all('agente');
		return view('index');
	}
	public function index()
	{
		echo 'qualquer coisa';
	}
}<file_sep><?php

namespace Framework;

use Framework\Container;
use Framework\Database\Connection;
use Framework\Database\QueryBuilder;
use Framework\Request;
use Framework\Routing\Router;
use Symfony\Component\Debug\Debug;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;

class Application
{
    protected $config;

    protected $database;

    protected static $container;

    public function __construct($base_path = "")
    {
        $this->setContainer(new Container());

        $container = $this->container();

        $container->register('config', require 'config.php');
        $container->register(
            'connection',
            new Connection($container->get('config')['database'])
        );
        $container->register('request', new Request(SymfonyRequest::createFromGlobals()));
        $container->register('view', new View());

        $this->debug($container->get('config')['env']);
    }
    public static function setContainer(Container $container)
    {
        static::$container = $container;
    }
    public static function container(string $id = NULL)
    {
        if ($id != NULL)
            return static::$container->get($id);
        return static::$container;
    }
    private function debug(string $env)
    {
        if ($env == 'development')
            return Debug::enable();
    }
    public function run()
    {
        $request = $this->container('request');

        return Router::load('routes.php')
            ->direct(
                trim($request->request->getRequestUri(),'/'),
                $request->getMethod());
    }
}
<file_sep><?php

namespace App\Controller;

use App\Model\Agente;
use App\Model\Usuario;
use Framework\Request;

class AgenteController
{
    public function index()
    {
        $agentes = Agente::select()->get()->usuario()->all();

        return view('agente.index', ['agentes' => $agentes]);
    }
    public function create()
    {
        return view('agente.create');
    }
    public function store()
    {
        $usuario = new Usuario;

        $usuario->username = $_POST['usuario'];
        $usuario->senha = crypt($_POST['senha']);
        $usuario->tipo = 2;

        $usuario = $usuario->save();

        $agente = new Agente;

        $agente->nome = $_POST['nome'];
        $agente->cpf = $_POST['cpf'];
        $agente->estado = $_POST['estado'];
        $agente->cidade = $_POST['cidade'];
        $agente->id_usuario = $usuario->id;

        $agente->save();

        header("location: /agentes");
    }
    public function show(Request $request)
    {
        $agente = Agente::find($request->get('id'))->usuario();

        return view('agente.show', ['agente' => $agente]);
    }
    public function edit()
    {
        $agente = Agente::find($_GET['id'])->usuario();

        return view('agente.edit', ['agente' => $agente]);
    }
    public function update()
    {
        $agente = Agente::find($_GET['id']);

        $agente->nome = $_POST['nome'];
        $agente->cpf = $_POST['cpf'];
        $agente->estado = $_POST['estado'];
        $agente->cidade = $_POST['cidade'];

        $agente->updateAgente($agente);

        $usuario = $agente->usuario()->usuario;
        $usuario->username = $_POST['usuario'];
        $usuario->senha = $_POST['senha'];
        $usuario->tipo = $_POST['tipo'];
        $usuario->perm = $_POST['perm'];

        $agente->updateUsuario($usuario);

        header("location: /agentes");
    }
    public function destroy()
    {
    }
}
<file_sep><?php

namespace App\Model;

use Framework\Database\Model;

class Agente extends Model
{
    public function usuario()
    {
        return $this->hasOne('App\Usuario', 'id', 'id_usuario');
    }
}
<file_sep><?php

namespace App\Model;

use Framework\Database\Model;

class Usuario extends Model
{
}
<file_sep><?php

namespace Framework\Routing;

use Framework\Application;

class Route
{
	protected $method;

	protected $uri;

	protected $controller;

	protected $action;

	protected $request;

	protected $regex;

	protected $compiled;

	public function __construct(string $method, string $uri, string $controller)
	{
		$this->method = $method;
		$this->uri = $uri;
		$this->controller = $controller;

		if (Application::container('request')->getMethod() == $this->method) {
			$this->request = $this->matches(
				$this, Application::container('request')->getMethod()
			);
		}
	}
	/**
	 * Return the route method
	 * @return [type] [description]
	 */
	public function getMethod()
	{
		return $this->method;
	}
	/**
	 * Return the route uri
	 * @param Route $route [description]
	 */
	public function getUri()
	{
		return $this->uri;
	}
	public function getRegex()
	{
		return $this->regex;
	}
	public function getController()
	{
		return $this->controller;
	}
	public function setCompiled()
	{
		$this->regex = preg_replace(
			'/\{([\w]+)}/', '(?P<$1>[^/]++)', $this->uri
		);

		/*preg_match(
			"/".str_replace("/", "\/", $this->regex)."/",
			$requestUri, $matches
		);

		return $this->unsetNoMatchesKey($matches);*/
	}
	public function formatRegex()
	{
		$this->regex = "#^/{$this->regex}$#s";
	}
	public function matches($routes, string $requestUri)
	{
		$this->setCompiled();
		$this->formatRegex();
	}

	private function unsetNoMatchesKey(array $matches = NULL)
	{
		// Remove all unncessary key
		foreach ($matches as $key => $value) {
		    if (is_int($key))
		        unset($matches[$key]);
		}
		return $matches;
	}
}
<file_sep><!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Vacina Digital</title>

	<link rel="stylesheet" type="text/css" href="/public/css/styles.css">

    <?= assets('bootstrap.css.bootstrap', 'css'); ?>

    <?= assets('jquery', 'js'); ?>
    <?= assets('bootstrap.js.bootstrap', 'js'); ?>

Vacina Digital

<file_sep><?php template('admin.header'); ?>

<?= assets('mask', 'js'); ?>

Agentes: Editar

<form class="row" method="POST" action="/admin/agentes/<?= $agente->id; ?>">
  <input type="hidden" name="_method" value="PATCH">

      Nome
      <input type="text" class="form-control" name="agente[nome]" id="nome" placeholder="Nome" value="<?= $agente->nome; ?>">

      CPF
      <input type="text" class="form-control" name="agente[cpf]" id="cpf" placeholder="xxx.xxx.xxx-xx" value="<?= $agente->cpf; ?>">

      CEP
      <input type="text" class="form-control" name="agente[cep]" id="cep" placeholder="xxxxx-xxx" value="<?= $agente->cep; ?>">

      Estado
      <input type="text" class="form-control" name="agente[estado]" id="estado" placeholder="UF" value="<?= $agente->estado; ?>">

      Cidade
      <input type="text" class="form-control" name="agente[cidade]" id="cidade" placeholder="Cidade" value="<?= $agente->cidade; ?>">

      Usuário
      <input type="text" class="form-control" name="usuario[usuario]" id="usuario" placeholder="Usuário" value="<?= $agente->usuario->usuario?>">

      Senha
      <input type="password" class="form-control" name="usuario[senha]" id="senha" placeholder="Senha">

      Cofirmar senha
      <input type="password" class="form-control" name="usuario[senha_cofirmation]" id="senha_cofirmation" placeholder="<PASSWORD>">

  <button type="submit" class="btn btn-success pull-right">Salvar</button>
</form>

<?php template('admin.footer'); ?><file_sep><?php

session_start();

require "vendor/autoload.php";

$app = new Framework\Application;

$app->run();

return $app;<file_sep><?php

namespace Framework\Routing;

use Exception;

class Router
{
    public function __construct()
    {
        $this->routes = new RouteCollection;
    }
    /**
     * Load the routes.php file in root directory
     * @param  string $file       The routes.php file
     * @return Framework\Router   Return self
     */
    public static function load(string $file)
    {
        $router = new static;

        require $file;

        return $router;
    }
    public function get(string $uri, $controller)
    {
        $this->routes->add($this->createRoute('GET', $uri, $controller));
    }
    public function post(string $uri, $controller)
    {
        $this->routes->add($this->createRoute('POST', $uri, $controller));
    }
    public function patch(string $uri, $controller)
    {
        $this->routes->add($this->createRoute('PATCH', $uri, $controller));
    }
    public function delete(string $uri, $controller)
    {
        $this->routes->add($this->createRoute('DELETE', $uri, $controller));
    }
    /**
     * Create a new Route
     * @param  string $method     [description]
     * @param  string $uri        [description]
     * @param  string $controller [description]
     * @return Framework\Routing\Route             [description]
     */
    public function createRoute(string $method, string $uri, string $controller)
    {
        return new Route($method, $uri, $controller);
    }

    /**
     * Dispatch to the right Controller
     * @param  [type] $uri    [description]
     * @param  [type] $method [description]
     * @return [type]         [description]
     */
    public function direct($uri, $method)
    {
        $path = $uri == '/' ? '/' : "/{$uri}";
        // Find the first ocurrence from routes
        foreach ($this->routes->routes[$method] as $key => $route) {
            if (preg_match($route->getRegex(), $path) == true) {

                $this->setRequest($route->getRegex(), $path);

                list($controller, $action) = explode("@", $route->getController());

                return $this->matchController($controller, $action);
            }
        }
        throw new Exception("Route {$uri} not found");
    }
    public function matchController($controller, $action)
    {
        $args = [];
        $controller = "App\\Controller\\{$controller}";
        $method = new \ReflectionMethod($controller, $action);

        foreach ($method->getParameters() as $param)
            $args[] = (string)$param->getType();

        foreach ($args as $key => $value)
            $args[$key] = container('request');

        return $method->invokeArgs(new $controller, $args);
    }
    public function setRequest(string $regex, string $path)
    {
        preg_match($regex, $path, $matches);

        $matches = $this->unsetNoMatchesKey($matches);

        foreach ($matches as $key => $value) {
            container('request')->request->query->set($key, $value);
        }
    }
    private function unsetNoMatchesKey(array $matches = NULL)
    {
        // Remove all unncessary key
        foreach ($matches as $key => $value) {
            if (is_int($key))
                unset($matches[$key]);
        }
        return $matches;
    }
}
<file_sep><?php template('admin.header'); ?>

Agentes

      Novo agente

          #
          Usuário
          Nome
          CPF
          Estado
          Cidade

        <?php foreach ($agentes as $agente): ?>

            <?= $agente->id; ?>
              <?= $agente->usuario->usuario; ?>
              <?= $agente->nome; ?>
              <?= $agente->cpf; ?>
              <?= $agente->estado; ?>
              <?= $agente->cidade; ?>
              <a href="agentes/<?= $agente->id; ?>/editar" class="glyphicon glyphicon-pencil">

        <?php endforeach; ?>

<?php template('admin.footer'); ?>
<file_sep><?php

namespace Framework\Database;

use ReflectionClass;
use Framework\Database\DatabaseCollection as Collection;

class QueryBuilder
{
	/**
	 * Connection Instance
	 * @var Framework\Database\Connection
	 */
	protected $connection;

	/**
	 * Set the query Type e.g Select, Update, Insert, Delete
	 * @var string
	 */
	protected $sqlQuery;

	/**
	 * All wheres from query
	 * @var array
	 */
	protected $wheres = [];

	/**
	 * All where's values from query
	 * @var array
	 */
	protected $values = [];

	/**
	 * The table name
	 * @var string
	 */
	protected $table = "";

	protected $leftJoin = "";

	public function __construct(Connection $connection, $table = NULL)
	{
		$this->connection = $connection;

		if (!is_null($table))
			$this->setTable($table);
	}

	/**
	 * Make a select by ID as parameter
	 * @param  int  $id
	 * @param  array  $columns
	 * @return Framework\Database\DatabaseCollection
	 */
	public function find(int $id, array $columns = ['*'])
	{
		$query = $this->select($columns)->where('id', $id);
		return $query->first($columns);
	}
	/**
	 * Get the first result from query
	 * @param  array  $columns
	 * @return Framework\Database\DatabaseCollection
	 */
	public function first(array $columns = ['*'])
	{
		if (is_null($this->sqlQuery))
			$this->select($columns);

		$result = $this->selectStatement();

		if (is_null($result))
			return false;

		$collection = new Collection($result);

		return $collection->first();
	}
	/**
	 * Make a select string
	 * @param  array  $columns
	 * @return static
	 */
	public function select(array $columns = ['*'], string $alias = null)
	{
		$this->sqlQuery =
			sprintf(
				"SELECT %s FROM %s",
				implode(', ', $columns),
				$this->table
			);

		if (!is_null($alias))
			$this->as($alias);

		return $this;
	}
	public function as(string $alias)
	{
		$this->sqlQuery .= " as {$alias}";
		return $this;
	}
	public function leftJoin(string $table, string $on)
	{
		$this->leftJoin = sprintf(" LEFT JOIN %s ON %s", $table, $on);
		$this->sqlQuery .= $this->leftJoin;
		return $this;
	}
	/**
	 * Format all wheres and values
	 * @param  string $column
	 * @param  mixed $comp
	 * @param  mixed $value
	 * @return static
	 */
	public function where(string $column, $comp, $value = NULL)
	{
		if ($value == NULL) {
			$value = $comp;
			$comp = "=";
		}

		$this->values[$column] = $value;
		$this->wheres[$column] = "{$column} {$comp} :{$column}";

		return $this;
	}
	public function insert($values, string $table)
	{
		if (empty($values))
			return true;

		$values = (array)$values;

		$columns = 	implode(",", array_keys($values));
		$columnized = $this->columnize($values);

		$query = "INSERT INTO {$table}({$columns}) VALUES({$columnized})";

		$id = $this->connection->statement($query, $values);

		return $this->find($id);
	}
	public function update(array $values, string $table, string $where = null)
	{
		$columns = "";
		if (empty($values))
			return true;

		foreach ($values as $key => $value) {
			$columns .= "{$key}=:{$key},";
		}
		$columns = trim($columns, ',');

		if (is_null($where)) {
			$where = "id = :where";
			$values['where'] = $values['id'];
		} else {
			$values['where'] = $where;
		}

		$query = "UPDATE {$table} SET {$columns} WHERE {$where}";

		$this->connection->updateStatement($query, $values);

		return $this->find($values['id']);
	}
	public function columnize(array $values)
	{
		$qmark = "";
		foreach ($values as $value)
			$qmark .= "?,";

		return trim($qmark, ",");
	}
	public function get()
	{
		$results = $this->selectStatement();

		if (is_null($results))
			return false;

		$collection = new Collection($results);

		return $collection;
	}
	public function makeQuery()
	{
		$where = "";
		if ($this->wheres != []) {
			$where = "WHERE ";
			foreach ($this->wheres as $value) {
				$where .= "$value AND ";
			}
			$where = trim($where, "AND ");
		}
		return "{$this->sqlQuery} {$where}";
	}
	public function setTable(string $table)
	{
		$this->table = $table;

		return $this;
	}
	public function selectStatement()
	{
		return $this->connection->selectStatement(
			$this->table,
			$this->makeQuery(),
			$this->values
		);
	}
}
<file_sep># Vacina Digital
## Projeto Interdisciplinar de Computação

Plataforma de controle de vacinas.

### Utilizar
* PHP 7
* MySql 5.7
* Apache 2.4

### Como Utilizar
* Faça o clone do projeto: git clone https://github.com/edgaryonemura/vacina-digital.git
* Entre na pasta do projeto: cd vacina-digital
* Faça uma cópia do arquivo "config.env.php" -- IMPORTANTE MANTER O ARQUIVO "config.env.php"
* Substitua o nome da cópia para "config.php"
* Configure o "config.php" conforme seu ambiente
* Faça o download do Composer:
* Windows: https://getcomposer.org/Composer-Setup.exe
* Unix: https://getcomposer.org/download/
* Abra o terminal ou o cmd(Windows)
* Navegue até a pasta do projeto clonado "vacina-digital", pelo terminal: cd caminho/do/projeto/vacina-digital
* Instale todas as dependencias e o mapeamento do autoload: composer install
* Instale o git: https://git-scm.com/

### Workflow do GIT/GITHUB
#### Sincroniza o projeto remoto(GITHUB) com o projeto local(Sua máquina)
* git fetch

#### Faz o download dos arquivos remotos(Apenas daqueles que foram alterados ou adicionados por outro colaborador), para seu projeto local
* git pull

#### Verifica em qual branch você está atualmente
* git branch

#### Cria uma nova branch localmente, para que se possa trabalhar em alguma alteração especifica
#### [ IMPORTANTE ] nunca altere diretamente na branch master
* git checkout -b nome-da-branch
* --> *ex: git checkout -b atualizando-usuario-controller*

#### Verifica quais arquivos foram alterados:
* git status

#### Adiciona um arquivo alterado para branch
* git add nome-do-arquivo

### Ou Adiciona TODOS arquivos alterados para a branch
* git add -A

#### Faz um commit(comentário) para os arquivos adicionados (Se forem adicionados varios arquivos, todos teram o mesmo commit)
* git commit -m "algum comentário!"

#### Volta para a branch master
* git checkout master

#### Fundi as duas branch através das diferença
* git merge nome-da-branch

#### Faz o upload dos arquivos local para os arquivos remoto(GITHUB)
* git push

### Outros Comandos importantes

#### Desfaz mudanças
##### Verifica quais arquivos foram alterados/criados/deletados
* git status

##### Desfaz todas mudanças listadas pelo comando acima
* git checkout -f

##### Não deve mostrar nenhum arquivo!
* git status

### Membros do Desenvolvimento
* <NAME>
* <NAME>
* <NAME>

<file_sep><?php

namespace Framework;

use Pimple\Container as PimpleContainer;

class Container
{
    public $container;

    public function __construct()
    {
        $this->container = new PimpleContainer();
    }
    public function register(string $name, $value)
    {
        $this->container->offsetSet($name, $value);
    }
    public function get(string $id)
    {
        return $this->container->offsetGet($id);
    }
}<file_sep><?php

namespace Framework;

use Symfony\Component\HttpFoundation\Request as SymfonyRequest;

class Request
{
    public function __construct(SymfonyRequest $request)
    {
        $this->request = $request;
    }
    public function post($key)
    {
        return $this->request->request->get($key);
    }
    public function get($key)
    {
        return $this->request->query->get($key);
    }
    public function getMethod()
    {
        if (!$this->post('_method')) {
            return $this->request->getMethod();
        }
        return $this->post('_method');
    }
}<file_sep><?php

namespace App\Controller\Admin;

use App\Model\Usuario;
use Framework\Request;

class LoginController
{
    public function index()
    {
        return view('admin.login');
    }
    public function login(Request $request)
    {
        $email = $request->post('email');
        $senha = $request->post('senha');

        $usuario = Usuario::select(['id','usuario','senha'])
            ->where('usuario', $email)->get()->first();

        if ($usuario) {
            if (crypt($senha, $usuario->senha) == $usuario->senha) {
                $_SESSION['usuario'] = [
                    'id' => $usuario->id,
                    'nome' => $usuario->usuario
                ];
                return redirect("admin.agentes");
            }
        }

        return view('admin.login');
    }
}
<file_sep><?php

namespace Framework\Routing;

class RouteCollection
{
	/**
     * An array with all routes, separeted by method
     * @var array
     */
	public $routes = [
		'GET' => [],
		'POST' => [],
		'PATCH' => [],
		'DELETE' => []
	];
	/**
	 * Add a route to RouteCollection
	 * @param Route $route [description]
	 */
	public function add(Route $route)
	{
		$this->routes[$route->getMethod()][$route->getUri()] = $route;
	}
}
<file_sep><?php template('header'); ?>

Lista de Agentes

ID: <?= $agente->id; ?>

Usuário: <?= $agente->usuario->usuario; ?>

Nome: <?= $agente->nome; ?>

CPF: <?= $agente->cpf; ?>

<?php template('footer'); ?>
<file_sep>
Copyright - 2016

<file_sep><?php template('admin.header'); ?>

Lista de Agentes

      <a href="/admin/agentes/<?= $agente->id; ?>/editar" class="col-md-12 btn btn-primary">Editar

ID: <?= $agente->id; ?>

Usuário: <?= $agente->usuario->usuario; ?>

Nome: <?= $agente->nome; ?>

CPF: <?= $agente->cpf; ?>

      Voltar

<?php template('admin.footer'); ?>
<file_sep><?php template('header'); ?>

Agentes

                #
                Usuário
                Nome
                CPF
                Estado
                Cidade

            <?php foreach ($agentes as $agente): ?>

                    <?= $agente->id; ?>
                    <?= $agente->usuario->username; ?>
                    <?= $agente->nome; ?>
                    <?= $agente->cpf; ?>
                    <?= $agente->estado; ?>
                    <?= $agente->cidade; ?>
                    <a href="agentes/<?= $agente->id; ?>/editar" class="glyphicon glyphicon-pencil">

            <?php endforeach; ?>

<?php template('footer'); ?><file_sep>-- MySQL Script generated by MySQL Workbench
-- 08/25/16 20:41:10
-- Model: New Model    Version: 1.0
-- MySQL Workbench Forward Engineering

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

-- -----------------------------------------------------
-- Schema vacina
-- -----------------------------------------------------

-- -----------------------------------------------------
-- Schema vacina
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `vacina` DEFAULT CHARACTER SET utf8 ;
USE `vacina` ;

-- -----------------------------------------------------
-- Table `vacina`.`usuario`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `vacina`.`usuario` (
  `id` INT NOT NULL AUTO_INCREMENT COMMENT 'id que representa a conta do usuario, este numero é unico',
  `usuario` VARCHAR(45) NOT NULL COMMENT 'nome de usuario, deve ser unico',
  `senha` VARCHAR(32) NOT NULL COMMENT 'senha para realizar o login',
  `tipo` TINYINT(1) NOT NULL COMMENT 'identifica se a conta pertence a um posto de saude, agente de saude ou cidadão',
  `perm` TINYINT(1) NOT NULL COMMENT 'representa o nivel de permissão da conta, variando de 0 a 3, 0 admin, 1 posto de saude, 2 agente de saude e 3 usuario',
  PRIMARY KEY (`id`),
  UNIQUE INDEX `usuario_UNIQUE` (`usuario` ASC))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `vacina`.`cidadao`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `vacina`.`cidadao` (
  `id` INT NOT NULL AUTO_INCREMENT COMMENT 'id da informação para controle da tabela',
  `id_usuario` INT NOT NULL COMMENT 'id do usuario a quem esta informação pertence',
  `nome` VARCHAR(60) NOT NULL COMMENT 'nome completo do usuario',
  `cep` VARCHAR(9) NOT NULL COMMENT 'CEP do usuario',
  `estado` CHAR(2) NOT NULL COMMENT 'id do estado em que o usuario reside',
  `cidade` VARCHAR(60) NOT NULL COMMENT 'id da cidade na qual o usuario reside',
  `bairro` VARCHAR(45) NOT NULL COMMENT 'bairro onde o usuario reside',
  `rua` VARCHAR(60) NOT NULL COMMENT 'nome da rua onde o usuario reside',
  `numero` INT NULL COMMENT 'numero da cada onde o usuario reside',
  `complemento` VARCHAR(20) NULL COMMENT 'informações adicionais para o endereço',
  `telefone` VARCHAR(15) NULL COMMENT 'telefone para contato',
  `cpf` VARCHAR(14) NULL COMMENT 'cpf do usuario',
  `nome_mae` VARCHAR(60) NULL COMMENT 'nome da mãe do usuario',
  `nome_pai` VARCHAR(60) NULL,
  `data_nasc` DATE NULL COMMENT 'data de nascimento do usuario',
  `num_sus` VARCHAR(15) NULL COMMENT 'numero da carteirinha do SUS do usuario',
  `reg_nasc` VARCHAR(32) NULL COMMENT 'numero da certidao de nascimento',
  `local_nasc` VARCHAR(60) NULL COMMENT 'local de nascimento',
  `estado_nasc` CHAR(2) NOT NULL COMMENT 'id do estado em que o usuario nasceu',
  `cidade_nasc` VARCHAR(60) NOT NULL,
  `sexo` CHAR(1) NOT NULL COMMENT 'sexo do usuario',
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `vacina`.`vacina`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `vacina`.`vacina` (
  `id` INT NOT NULL AUTO_INCREMENT COMMENT 'id da vacina',
  `nome` VARCHAR(60) NOT NULL COMMENT 'nome da vacina',
  `doses` INT NOT NULL COMMENT 'numero de doses necessárias',
  `intervalo` INT NOT NULL COMMENT 'intervalo entre as doses em meses',
  `obrigatorio` TINYINT(1) NOT NULL COMMENT 'flag para informar se a vacina é obrigatoria ou não',
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `vacina`.`agente`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `vacina`.`agente` (
  `id` INT NOT NULL AUTO_INCREMENT COMMENT 'id da informação',
  `id_usuario` INT NOT NULL COMMENT 'id do usuario a qual a informação eprtence',
  `nome` VARCHAR(60) NOT NULL COMMENT 'nome completo do agente ou posto de saude',
  `estado` CHAR(2) NOT NULL COMMENT 'estado de atuação do agente/posto de saude',
  `cidade` VARCHAR(60) NOT NULL COMMENT 'id da cidade de atuação do agente/posto de saude',
  `cpf` VARCHAR(12) NOT NULL,
  `id_posto_vinculado` INT NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `cpf_cnpj_UNIQUE` (`cpf` ASC))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `vacina`.`posto`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `vacina`.`posto` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `id_usuario` INT NOT NULL,
  `nome` VARCHAR(60) NOT NULL,
  `telefone` CHAR(11) NULL,
  `cep` CHAR(8) NULL,
  `cidade` VARCHAR(60) NULL,
  `estado` CHAR(2) NULL,
  `bairro` VARCHAR(60) NULL,
  `rua` VARCHAR(60) NULL,
  `numero` INT NULL,
  `complemento` VARCHAR(20) NULL,
  `cnpj` CHAR(15) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `telefone_UNIQUE` (`telefone` ASC),
  UNIQUE INDEX `cidade_UNIQUE` (`cidade` ASC),
  UNIQUE INDEX `estado_UNIQUE` (`estado` ASC),
  UNIQUE INDEX `bairro_UNIQUE` (`bairro` ASC),
  UNIQUE INDEX `rua_UNIQUE` (`rua` ASC),
  UNIQUE INDEX `numero_UNIQUE` (`numero` ASC),
  UNIQUE INDEX `cnpj_UNIQUE` (`cnpj` ASC))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `vacina`.`cidadao_vacina`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `vacina`.`cidadao_vacina` (
  `id_usuario` INT NOT NULL COMMENT 'id a quem o registro pertence',
  `id_vacina` INT NOT NULL COMMENT 'identificação da vacina',
  `dose` INT NOT NULL COMMENT 'dose de aplicação',
  `data` DATE NOT NULL COMMENT 'data da aplicação',
  `id_posto` INT NULL COMMENT 'id do local onde a vacina foi aplicada',
  `id_agente` INT NULL COMMENT 'id do agente que realizou a aplicação')
ENGINE = InnoDB;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
<file_sep><?php

namespace App\Controller\Admin;

class PainelController
{
    public function __construct()
    {
        // Do Auth
    }
    public function index()
    {
        return view('admin.painel');
    }
}
<file_sep><?php

$router->get('', 'HomeController@index');

// Admin Routes
$router->get('admin', 'Admin\LoginController@index');
$router->get('admin/login', 'Admin\LoginController@index');
$router->post('admin/login', 'Admin\LoginController@login');

$router->get('admin/painel', 'Admin\PainelController@index');

$router->get('admin/agentes', 'Admin\AgenteController@index');
$router->get('admin/agentes/cadastrar', 'Admin\AgenteController@create');
$router->post('admin/agentes', 'Admin\AgenteController@store');
$router->get('admin/agentes/{id}', 'Admin\AgenteController@show');
$router->get('admin/agentes/{id}/editar', 'Admin\AgenteController@edit');
$router->patch('admin/agentes/{id}', 'Admin\AgenteController@update');
<file_sep><?php

return [
	'database' => [
		'name' => '',
		'host' => '',
		'username' => '',
		'password' => '',
		'options' => [
			PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING
		]
	],
    // production: desabilita o debug de erro
    // development: habilita o debug de erro
    'env' => 'development'
];
<file_sep><?php template('header'); ?>

	<form method="POST" action="agente">
		<input name="name">
		<input type="submit">
	</form>

<?php template('footer'); ?><file_sep>
Copyright - 2016

<file_sep><!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Login | Vacina Digital</title>

  <link rel="stylesheet" type="text/css" href="/public/css/login.css">

  <?= assets('bootstrap.css.bootstrap', 'css'); ?>

  <?= assets('jquery', 'js'); ?>
  <?= assets('bootstrap.js.bootstrap', 'js'); ?>

Vacina Digital

      <form method="POST" action="/admin/login">

          <input name="email" type="text" class="form-control" id="email" placeholder="E-mail">

          <input name="senha" type="<PASSWORD>" class="form-control" id="senha" placeholder="Senha">

        <button type="submit" class="btn btn-primary btn-block">Entrar</button>
      </form>

<file_sep><?php

namespace App\Controller\Admin;

use App\Model\Agente;
use App\Model\Usuario;
use Framework\Request;

class AgenteController
{
    public function index()
    {
        $agentes = Agente::select()->get()->usuario()->all();

        return view('admin.agente.index', ['agentes' => $agentes]);
    }
    public function create()
    {
        return view('admin.agente.create');
    }
    public function store(Request $request)
    {
        $usuario = new Usuario;

        $usuario->usuario = $request->post('usuario')['usuario'];
        $usuario->senha = crypt($request->post('usuario')['senha'], '');
        $usuario->tipo = 2;

        $usuario = $usuario->save();

        $agente = new Agente;

        $agente->id_usuario = $usuario->id;
        $agente->nome   = $request->post('agente')['nome'];
        $agente->cpf    = number($request->post('agente')['cpf']);
        $agente->cep    = number($request->post('agente')['cep']);
        $agente->estado = $request->post('agente')['estado'];
        $agente->cidade = $request->post('agente')['cidade'];
        $agente->id_posto_vinculado = 1;

        $agente->save();

        return redirect("admin.agentes");
    }
    public function show(Request $request)
    {
        $agente = Agente::find($request->get('id'))->usuario();

        return view('admin.agente.show', ['agente' => $agente]);
    }
    public function edit(Request $request)
    {
        $agente = Agente::find($request->get('id'))->usuario();

        return view('admin.agente.edit', ['agente' => $agente]);
    }
    public function update(Request $request)
    {
        $agente = Agente::find($request->get('id'));

        $agente->nome   = $request->post('agente')['nome'];
        $agente->cpf    = number($request->post('agente')['cpf']);
        $agente->cep    = number($request->post('agente')['cep']);
        $agente->estado = $request->post('agente')['estado'];
        $agente->cidade = $request->post('agente')['cidade'];
        $agente->id_posto_vinculado = 1;

        $agente->save();

        $usuario = $agente->usuario()->usuario;
        $usuario->usuario = $request->post('usuario')['usuario'];
        if ($request->post('usuario')['senha'] != null)
            $usuario->senha   = crypt($request->post('usuario')['senha'], '');
        $usuario->tipo    = 2;

        $usuario->save();

        return redirect("admin.agentes.{$usuario->id}");
    }
    public function destroy()
    {
    }
}
<file_sep><?php

namespace Framework;

class View
{
    public function make(string $view, array $data = [])
    {
        $this->view = $this->formatPath($view);

        $this->view = "{$this->path()}/app/View/{$this->view}.view.php";

        if (file_exists($this->view)) {
            extract($data);
            return require($this->view);
        }
    }
    public function template(string $file)
    {
    	$file = $this->formatPath($file);
    	return require "{$this->path()}/app/View/templates/{$file}.view.php";
    }

    public function path()
    {
    	return dirname(__DIR__);
    }
    public function formatPath(string $path)
    {
        return str_replace(".", "/", $path);
    }
    public function assets(string $asset, string $type)
    {
        if ($type == 'css')
            return "<link href='/assets/{$this->formatPath($asset)}.css' rel='stylesheet'>";
        if ($type == 'js')
            return "";
    }
    public function redirect(string $to)
    {
        $to = $this->formatPath($to);

        return header("Location: /{$to}");
    }
}

languages: Markdown SQL Hack PHP

repo_name: claudiocg/vacina-digital


text:
<repo_name>squiral/Java-BlackJack-TDD<file_sep>/src/test/java/DeckTest.java
import org.junit.Before;
import org.junit.Test;

import static junit.framework.Assert.assertTrue;
import static junit.framework.TestCase.assertEquals;

public class DeckTest {

    Deck deck;
    Card card;

    @Before
    public void before(){
        deck = new Deck();
    }

    @Test
    public void deckStartsPopulated(){
        assertEquals(52, deck.countCards());
    }

    @Test
    public void canDealCard(){
        deck.populateDeck();
        assertTrue(deck.dealCard() instanceof Card);
    }

}

branch_name: refs/heads/master

repo_language: Java

repo_name: squiral/Java-BlackJack-TDD


text:
<repo_name>oskarus202/repo2<file_sep>/README.md
# repo2
(for Zeit.co)

One of the projects - during Colt Steele;s React Course from Udemy - check at: https://www.udemy.com/course/modern-react-bootcamp/

repo_language: Markdown


text:
<file_sep>namespace :gen1 do
  task addAllPokemons: :environment do
    (1..151).each {|id|
      pokemon_evolution_chain = []
      pokemon_types = []
      pokemon = HTTParty.get('https://pokeapi.co/api/v2/pokemon/' + id.to_s)
      pokemon_species = HTTParty.get('https://pokeapi.co/api/v2/pokemon-species/' + pokemon['name'])
      pokemon_evolution_chain_response = HTTParty.get(pokemon_species['evolution_chain']['url'])

      for type in pokemon['types']
        pokemon_types.push(type['type']['name'])
      end

      pokemon_chain = pokemon_evolution_chain_response['chain']
      while !!pokemon_chain && pokemon_chain.has_key?('evolves_to') do
        pokemon_evolution_chain.push(pokemon_chain['species']['name'])
        pokemon_chain = pokemon_chain['evolves_to'][0]
      end

      Pokemon.create(pokemon_number: pokemon['id'], name: pokemon['name'], type: pokemon_types, sprite: pokemon['sprites']['front_default'], evolution_chain: pokemon_evolution_chain)
    }
    puts 'task complete'
  end
end
<file_sep>class Pokemon
  include Mongoid::Document
  include Mongoid::Timestamps
  field :pokemon_number, type: Integer
  field :name, type: String
  field :type, type: Array
  field :sprite, type: String
  field :evolution_chain, type: Array

  validates :pokemon_number, presence: true
  validates :name, presence: true
  validates :type, presence: true
  validates :evolution_chain, presence: true

end
<file_sep>class Api::V1::PokemonController < ApiPokemonController
  before_action :get_pokemon, only: [:show]

  def index
    @pokemon = Pokemon.all
    render json: {
        data: @pokemon
    }
  end

  def show
  end

  def create
    if Pokemon.first.nil?
      @pokemon = Pokemon.new(pokemon_info.merge(pokemon_number: 1))
    else
      last_pokemon_number = Pokemon.asc(:created_at).last.pokemon_number + 1
      @pokemon = Pokemon.new(pokemon_info.merge(pokemon_number: last_pokemon_number))
    end
    if @pokemon.save
      render json: {
          status: "success",
          message: "Pokemon was saved and sent to the PC Storage",
          data: @pokemon
      }
    else
      render json: {
          status: "error",
          message: "Error on save your pokemon...",
          data: @pokemon.errors
      }
    end
  end

  def update
    @pokemon = Pokemon.find(params[:id])
    @pokemon.update(pokemon_info)

    render json: {
        status: "success",
        message: "Pokemon was updated",
        data: @pokemon
    }
  end

  def destroy
    @pokemon = Pokemon.find(params[:id])
    @pokemon.destroy

    render json: {
        status: "success",
        message: "Pokemon was released",
        data: @pokemon
    }
  end

  private

  def get_pokemon
    @pokemon = Pokemon.find(params[:id])
    render json: {
        data: @pokemon
    }
  end

  def pokemon_info
    params.permit(:name, :sprite, :type => [], :evolution_chain => [])
  end

end<file_sep># README

#### Project using Rails and MongoId, make sure you have mongoDB in your computer before use.

##### To populate the database run the task:
* rake gen1:addAllPokemons

##### Deploy rails server:
* rails s

##### Any question please contact me by email:
* <EMAIL>

<file_sep>require 'rails_helper'

RSpec.describe "PokemonController", type: :request do
  describe 'GET/pokemon' do
    it 'status 200' do
      get "/api/v1/pokemon"
      expect(response.status).to eql(200)
    end
  end
  describe "POST /api/v1/pokemon" do
    context "with valid parameters" do
      let(:valid_params) do
        {
            name: "chikorita",
            type: ["grass"],
            evolution_chain: ["chikorita", "bayleef", "meganium"]
        }
      end
      it "creates a new pokemon" do
        post "/api/v1/pokemon", params: valid_params
        expect(response).to have_http_status(:success)
      end

      it "creates a pokemon with the correct attributes" do
        expect {post "/api/v1/pokemon", params: valid_params}.to change(Pokemon, :count).by(1)
      end
    end
  end
  describe "DELETE /api/v1/pokemon" do
    context 'existing pokemon' do
      pokemon = FactoryGirl.create(:pokemon)
      it "delete pokemon" do
        expect {delete "/api/v1/pokemon/" + pokemon.id}.to change(Pokemon, :count).by(-1)
      end
    end
  end
end<file_sep>require 'rails_helper'

RSpec.describe Pokemon, type: :model do
  context "Validate Pokemon" do
    it "Pokemon is valid" do
      pokemon = Pokemon.new
      pokemon.name = "chikorita"
      pokemon.pokemon_number = 152
      pokemon.type = ["grass"]
      pokemon.evolution_chain = ["chikorita", "bayleef", "meganium"]

      expect(pokemon.valid?).to be_truthy
    end
    it "Pokemon is not valid" do
      pokemon = Pokemon.new
      pokemon.name = "chikorita"
      pokemon.pokemon_number = 152
      pokemon.evolution_chain = ["chikorita", "bayleef", "meganium"]

      expect(pokemon.valid?).to be_falsy
    end
  end
end<file_sep>FactoryGirl.define do
  factory :pokemon do
    name "rayquaza"
    type ["dragon"]
    evolution_chain ["rayquaza"]
    pokemon_number 1
  end
end

languages: Markdown Ruby


text:
<file_sep>var filter1 = document.getElementById("filter1");
var leftpanel = document.getElementById("leftpanel");

filter1.addEventListener("click", function(e){
    document.querySelector(".filters").classList.toggle("d-class")
})

repo_language: JavaScript


text:
<file_sep>package data_manage;

import javafx.collections.ObservableList;
import model.Cat;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileManage {
    public void writeToFile(String pathname, ObservableList<Cat> catList) throws IOException {
        FileOutputStream fileOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(pathname);
            objectOutputStream = new ObjectOutputStream(fileOutputStream);
            for (Cat cat : catList) {
                objectOutputStream.writeObject(cat);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            assert objectOutputStream != null;
            objectOutputStream.close();
            fileOutputStream.close();
        }
    }

    public List<Cat> readFile(String pathname) {
        List<Cat> cats = new ArrayList<>();
        FileInputStream fileInputStream = null;
        ObjectInputStream objectInputStream = null;
        try {
            fileInputStream = new FileInputStream(pathname);
            objectInputStream = new ObjectInputStream(fileInputStream);

            while (true) {
                cats.add((Cat) objectInputStream.readObject());
            }
        } catch (EOFException e) {
            e.getMessage();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            assert objectInputStream != null;
        }
        return cats;
    }
}
<file_sep># case_study_m2
Develop by: <NAME>.

Develop date: 15/10/2020

Description: Application for managing hotel for cats with owner's information, cat specific information for monitoring health status.

<file_sep>package model;

import java.util.ArrayList;
import java.util.List;

public class CatManagement implements IManagement<Cat> {
    static List<Cat> cats;

    @Override
    public void add(Cat obj) {
        boolean flag = true;
        for (int i = 0; i < cats.size(); i++) {
            if (obj.getOwnerPhone().equals(cats.get(i).getOwnerPhone())) {
                flag = true;
                break;
            }
        }
        if (flag) {
            cats.add(obj);
        }
    }

    @Override
    public void update(String inputCusPhone, Cat newObj) {

    }

    @Override
    public void delete(String inputCusPhone) {

    }

    @Override
    public List findByPhone(String inputCusPhone) {
        return null;
    }

    @Override
    public List<Cat> findByName(String inputCusName) {
        return null;
    }

    @Override
    public List<Cat> findByCatName(String inputCatName) {
        return null;
    }

    @Override
    public List<Cat> findByCatSpecies(String inputCatSpecies) {
        return null;
    }

    @Override
    public List<Cat> findByCatGender(String inputCatGender) {
        return null;
    }

    @Override
    public List findAll() {
        return null;
    }
}

languages: Java Markdown


text:
<repo_name>cdolivar/gracepoint-map<file_sep>/README.md
# gracepoint-map

branch_name: refs/heads/main

repo_name: cdolivar/gracepoint-map