microserviciile de register, login finalizate

This commit is contained in:
Cerbu Andrei Mihnea
2023-06-15 22:21:53 +03:00
parent a739a66ae4
commit 4e585ba278
159 changed files with 4775 additions and 1747 deletions
+12
View File
@@ -0,0 +1,12 @@
RewriteEngine On
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "*"
Header set Access-Control-Allow-Methods "*"
</IfModule>
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L]
+8
View File
@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/." isTestSource="false" packagePrefix="app\" />
<sourceFolder url="file://$MODULE_DIR$/spec" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/tests" isTestSource="true" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/api.knowyourfood.iml" filepath="$PROJECT_DIR$/.idea/api.knowyourfood.iml" />
</modules>
</component>
</project>
+25
View File
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MessDetectorOptionsConfiguration">
<option name="transferred" value="true" />
</component>
<component name="PHPCSFixerOptionsConfiguration">
<option name="transferred" value="true" />
</component>
<component name="PHPCodeSnifferOptionsConfiguration">
<option name="highlightLevel" value="WARNING" />
<option name="transferred" value="true" />
</component>
<component name="PhpIncludePathManager">
<include_path>
<path value="$PROJECT_DIR$/vendor/composer" />
</include_path>
</component>
<component name="PhpProjectSharedConfiguration" php_language_level="8.2" />
<component name="PhpStanOptionsConfiguration">
<option name="transferred" value="true" />
</component>
<component name="PsalmOptionsConfiguration">
<option name="transferred" value="true" />
</component>
</project>
+12
View File
@@ -0,0 +1,12 @@
{
"name": "andrei_robert/api.knowyourfood",
"autoload": {
"psr-4": {
"app\\": "./"
}
},
"require": {
"ext-curl": "*",
"ext-ssh2": "*"
}
}
+20
View File
@@ -0,0 +1,20 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "d0c0dc1923200d7104286e6b4706aaad",
"packages": [],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"prefer-stable": false,
"prefer-lowest": false,
"platform": {
"ext-curl": "*"
},
"platform-dev": [],
"plugin-api-version": "2.3.0"
}
+96
View File
@@ -0,0 +1,96 @@
<?php
namespace app\core;
Class DVC
{
public static string $nameOfResponsePackage = "response_package";
public static string $successName = "Success";
public static string $genericExceptionName = "GenericErrorException";
public static string $invalidTokenName = "InvalidTokenException";
public static string $invalidRequestName = "InvalidRequestException";
public static string $invalidCurlStructureName = "InvalidCurlStructureException";
public static string $invalidBodyName = "InvalidBodyException";
public static string $alreadyExistsName = "AlreadyExistsException";
public static string $userNotExistingName = "userNotExistingException";
public static string $fieldNotExistingName = "FieldNotExistingException";
public static string $pageNotFoundName = "pageNotfoundException";
public static string $forbiddenAccessName = "forbiddenAccessException";
public static string $serviceNotFoundName = "FieldNotFoundException";
public static string $returnCode = "returnCode";
public static string $returnMessage = "returnMessage";
public static int $successReturnCode = 460;
public static function getArrayResponse(string $name): array
{
return match ($name){
DVC::$successName => [
DVC::$returnCode => 460,
DVC::$returnMessage => "Operation done successfully"
],
DVC::$genericExceptionName => [
DVC::$returnCode => 461,
DVC::$returnMessage => "Internal Server Error"
],
DVC::$invalidTokenName => [
DVC::$returnCode => 462,
DVC::$returnMessage => "Unauthorized access"
],
DVC::$invalidRequestName => [
DVC::$returnCode => 463,
DVC::$returnMessage => "Service doesn't provide this type of request"
],
DVC::$invalidBodyName => [
DVC::$returnCode => 464,
DVC::$returnMessage => "Not valid parameters sent"
],
DVC::$alreadyExistsName => [
DVC::$returnCode => 465,
DVC::$returnMessage => "Field already existing"
],
DVC::$fieldNotExistingName => [
DVC::$returnCode => 466,
DVC::$returnMessage => "Field not existing anymore"
],
DVC::$invalidCurlStructureName => [
DVC::$returnCode => 467,
DVC::$returnMessage => "cURL class needs URL, request method and headers to run"
],
DVC::$userNotExistingName => [
DVC::$returnCode => 468,
DVC::$returnMessage => "User account doesn't exists"
],
DVC::$pageNotFoundName => [
DVC::$returnCode => 469,
DVC::$returnMessage => "Page not found"
],
DVC::$forbiddenAccessName => [
DVC::$returnCode => 470,
DVC::$returnMessage => "You are not authorised to access this page"
],
DVC::$serviceNotFoundName => [
DVC::$returnCode => 471,
DVC::$returnMessage => "Service not existing"
]
};
}
public static function getHttpCodeWithCode(int $code): int
{
return match ($code){
460 => 200,
461 => 500,
462 => 401,
463 => 405,
464 => 400,
465, 466 => 204,
467 => 409,
468, 469, 471 => 404,
470 => 403,
default => 100
};
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
namespace app\core;
class Request{
public function getPath(): string
{
return $_SERVER['REQUEST_URI'];
}
public function method(): string
{
return $_SERVER['REQUEST_METHOD'];
}
public function getToken(): ?string
{
return array_key_exists("Authorization",apache_request_headers()) ?
apache_request_headers()["Authorization"] : NULL;
}
public function getAuthRequest(): string
{
return array_key_exists("Auth-Request", apache_request_headers()) ?
apache_request_headers()["Auth-Request"] : "default";
}
public function getBody(): ?array
{
if(!array_key_exists("Content-Length", apache_request_headers())) return NULL;
$bytesToRead = intval(apache_request_headers()["Content-Length"]);
if($bytesToRead == 0) return NULL;
$inputStream = fopen('php://input', 'r');
$jsonData = fread($inputStream, $bytesToRead);
fclose($inputStream);
$jsonData = json_decode($jsonData, true);
return empty($jsonData) ? [] : $jsonData;
}
}
+105
View File
@@ -0,0 +1,105 @@
<?php
namespace app\core;
use app\exceptions\InvalidTokenException;
use app\exceptions\ServiceNotFoundException;
use app\external_requests\CurlRequestBuilder;
use Exception;
class Router
{
private array $routes = [];
private array $accessTokens = [];
private Request $request;
private ?string $token;
public function __construct(Request $request, ?string $token)
{
$this->request = $request;
$this->token = $token;
}
public function set($path, $callback): void
{
$this->routes[$path] = $callback;
}
public function getHeaders(string $path): array
{
$array = $_SESSION['headers_configuration'][$path];
if($path === '/authentication'){
$array = $array[$this->request->getAuthRequest()];
}
$array["Content-Length"] = empty($this->request->getBody()) ? 0 : strlen(json_encode($this->request->getBody()));
$toReturn = array();
foreach ($array as $key => $value){
$value = $key . ": " . $value;
$toReturn[] = $value;
}
return $toReturn;
}
public function resolve(): void
{
try {
if (!$this->isTokenValid()) throw new InvalidTokenException();
$path = $this->request->getPath();
$method = $this->request->method();
$body = $this->request->getBody();
$callback = $this->routes[$path] ?? false;
if (!$callback) throw new ServiceNotFoundException();
$headers = $this->getHeaders($path);
$requestBuilder = new CurlRequestBuilder();
$requestBuilder->setRequest($method);
$requestBuilder->setUrl($callback);
$requestBuilder->setHeaders($headers);
$requestBuilder->setBody($body);
$requestBuilder->setIsReturnable(true);
$request = $requestBuilder->getCurlRequestObject();
$response = $request->makeRequest();
$this->writeResponse(
DVC::getHttpCodeWithCode(DVC::$successReturnCode),
DVC::$successReturnCode, $response
);
} catch (Exception $e){
$this->writeResponse(DVC::getHttpCodeWithCode($e->getCode()),
$e->getCode(), $e->getMessage()
);
}
}
private function isTokenValid(): bool
{
$validToken = hash('md5', 'api.knowyourfood');
return $validToken == $this->token;
}
private function writeResponse(int $httpCode, int $returnCode, string $returnMessage): void
{
header("Content-Disposition: ".DVC::$nameOfResponsePackage);
header("Content-Type: application/json");
http_response_code($httpCode);
if($httpCode != 200) {
echo json_encode([
"code" => $returnCode,
"message" => $returnMessage
]);
}else{
echo $returnMessage;
}
}
}
+2 -1
View File
@@ -1,7 +1,8 @@
<?php
global $config;
$config = [
'userClass' => \app\models\User::class,
'db' => [
'dsn' => 'mysql:host=localhost;port=3306;dbname=Web',
'user' => 'root',
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace app\exceptions;
use app\core\DVC;
use Exception;
class GenericErrorException extends Exception
{
public function __construct()
{
$array = DVC::getArrayResponse(DVC::$genericExceptionName);
parent::__construct($array[DVC::$returnMessage], $array[DVC::$returnCode]);
}
}
@@ -0,0 +1,14 @@
<?php
namespace app\exceptions;
use app\core\DVC;
use Exception;
class InvalidCurlStructureException extends Exception
{
public function __construct()
{
$array = DVC::getArrayResponse(DVC::$invalidCurlStructureName);
parent::__construct($array[DVC::$returnMessage], $array[DVC::$returnCode]);
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace app\exceptions;
use app\core\DVC;
use Exception;
class InvalidTokenException extends Exception
{
public function __construct()
{
$array = DVC::getArrayResponse(DVC::$invalidTokenName);
parent::__construct($array[DVC::$returnMessage], $array[DVC::$returnCode]);
}
}
@@ -0,0 +1,13 @@
<?php
namespace app\exceptions;
use app\core\DVC;
use Exception;
class ServiceNotFoundException extends Exception
{
public function __construct()
{
$array = DVC::getArrayResponse(DVC::$serviceNotFoundName);
parent::__construct($array[DVC::$returnMessage], $array[DVC::$returnCode]);
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
namespace app\external_requests;
use app\exceptions\GenericErrorException;
use CurlHandle;
class CurlRequest
{
private string $url;
private string $request;
private array $headers;
private ?array $body;
private bool $isReturnable;
protected function __construct(string $url, string $request, array $headers, ?array $body, bool $isReturnable)
{
$this->url = $url;
$this->request = $request;
$this->headers = $headers;
$this->body = $body;
$this->isReturnable = $isReturnable;
}
/**
* @throws GenericErrorException
*/
public function makeRequest(): string
{
$curl = curl_init();
$this->setCurlBody($curl);
$response = curl_exec($curl);
if(!$response){
throw new GenericErrorException();
}
if(curl_errno($curl)){
echo curl_error($curl);
die;
}
curl_close($curl);
return $response;
}
public function setCurlBody(CurlHandle &$curl): void
{
curl_setopt($curl, CURLOPT_URL, $this->url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->request);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, $this->isReturnable);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl,CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($this->body));
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace app\external_requests;
use app\exceptions\InvalidCurlStructureException;
class CurlRequestBuilder extends CurlRequest
{
private ?string $url = NULL;
private ?string $request = NULL;
private ?array $headers = NULL;
private ?array $body = NULL;
private bool $isReturnable = false;
public function __construct(){}
public function setUrl(?string $url): void{$this->url = $url;}
public function setHeaders(?array $headers): void{$this->headers = $headers;}
public function setRequest(?string $request): void{$this->request = $request;}
public function setBody(?array $body): void{$this->body = $body;}
public function setIsReturnable(?bool $isReturnable): void{$this->isReturnable = $isReturnable;}
private function areMainParametersNotSet(): bool{
return $this->url == NULL || $this->request == NULL || $this->headers == NULL;
}
/**
* @throws InvalidCurlStructureException
*/
public function getCurlRequestObject(): CurlRequest{
if($this->areMainParametersNotSet()){
throw new InvalidCurlStructureException();
}
return new CurlRequest($this->url, $this->request, $this->headers, $this->body, $this->isReturnable);
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
$headers_array = [
"/authentication" => [
"register" => [
"Content-Type" => "application/json",
"Authorization" => hash('md5', 'service_authentication'),
"Auth-Request" => "register"
],
"login" => [
"Content-Type" => "application/json",
"Authorization" => hash('md5', 'service_authentication'),
"Auth-Request" => "login"
],
"default" => [
"Content-Type" => "application/json",
"Authorization" => hash('md5', 'service_authentication')
],
]
];
$_SESSION['headers_configuration'] = $headers_array;
+16
View File
@@ -0,0 +1,16 @@
<?php
require_once __DIR__.'/vendor/autoload.php';
require_once 'headers_config.php';
use app\core\Request;
use app\core\Router;
$request = new Request();
$router = new Router($request, $request->getToken());
$router->set("/authentication", '89.137.67.2:702');
$request->getAuthRequest();
$router->resolve();
+1
View File
@@ -0,0 +1 @@
<?php
+25
View File
@@ -0,0 +1,25 @@
<?php
// autoload.php @generated by Composer
if (PHP_VERSION_ID < 50600) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
$err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL;
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, $err);
} elseif (!headers_sent()) {
echo $err;
}
}
trigger_error(
$err,
E_USER_ERROR
);
}
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit345c1a817a7f402322a2ecae01a96071::getLoader();
+585
View File
@@ -0,0 +1,585 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Autoload;
/**
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
*
* $loader = new \Composer\Autoload\ClassLoader();
*
* // register classes with namespaces
* $loader->add('Symfony\Component', __DIR__.'/component');
* $loader->add('Symfony', __DIR__.'/framework');
*
* // activate the autoloader
* $loader->register();
*
* // to enable searching the include path (eg. for PEAR packages)
* $loader->setUseIncludePath(true);
*
* In this example, if you try to use a class in the Symfony\Component
* namespace or one of its children (Symfony\Component\Console for instance),
* the autoloader will first look for the class under the component/
* directory, and it will then fallback to the framework/ directory if not
* found before giving up.
*
* This class is loosely based on the Symfony UniversalClassLoader.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @see https://www.php-fig.org/psr/psr-0/
* @see https://www.php-fig.org/psr/psr-4/
*/
class ClassLoader
{
/** @var \Closure(string):void */
private static $includeFile;
/** @var ?string */
private $vendorDir;
// PSR-4
/**
* @var array[]
* @psalm-var array<string, array<string, int>>
*/
private $prefixLengthsPsr4 = array();
/**
* @var array[]
* @psalm-var array<string, array<int, string>>
*/
private $prefixDirsPsr4 = array();
/**
* @var array[]
* @psalm-var array<string, string>
*/
private $fallbackDirsPsr4 = array();
// PSR-0
/**
* @var array[]
* @psalm-var array<string, array<string, string[]>>
*/
private $prefixesPsr0 = array();
/**
* @var array[]
* @psalm-var array<string, string>
*/
private $fallbackDirsPsr0 = array();
/** @var bool */
private $useIncludePath = false;
/**
* @var string[]
* @psalm-var array<string, string>
*/
private $classMap = array();
/** @var bool */
private $classMapAuthoritative = false;
/**
* @var bool[]
* @psalm-var array<string, bool>
*/
private $missingClasses = array();
/** @var ?string */
private $apcuPrefix;
/**
* @var self[]
*/
private static $registeredLoaders = array();
/**
* @param ?string $vendorDir
*/
public function __construct($vendorDir = null)
{
$this->vendorDir = $vendorDir;
self::initializeIncludeClosure();
}
/**
* @return string[]
*/
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();
}
/**
* @return array[]
* @psalm-return array<string, array<int, string>>
*/
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
/**
* @return array[]
* @psalm-return array<string, string>
*/
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
/**
* @return array[]
* @psalm-return array<string, string>
*/
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
/**
* @return string[] Array of classname => path
* @psalm-return array<string, string>
*/
public function getClassMap()
{
return $this->classMap;
}
/**
* @param string[] $classMap Class to filename map
* @psalm-param array<string, string> $classMap
*
* @return void
*/
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
* @param string $prefix The prefix
* @param string[]|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*
* @return void
*/
public function add($prefix, $paths, $prepend = false)
{
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
(array) $paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
(array) $paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = (array) $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
(array) $paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param string[]|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
(array) $paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
(array) $paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
(array) $paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
* @param string $prefix The prefix
* @param string[]|string $paths The PSR-0 base directories
*
* @return void
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param string[]|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
/**
* Turns on searching the include path for class files.
*
* @param bool $useIncludePath
*
* @return void
*/
public function setUseIncludePath($useIncludePath)
{
$this->useIncludePath = $useIncludePath;
}
/**
* Can be used to check if the autoloader uses the include path to check
* for classes.
*
* @return bool
*/
public function getUseIncludePath()
{
return $this->useIncludePath;
}
/**
* Turns off searching the prefix and fallback directories for classes
* that have not been registered with the class map.
*
* @param bool $classMapAuthoritative
*
* @return void
*/
public function setClassMapAuthoritative($classMapAuthoritative)
{
$this->classMapAuthoritative = $classMapAuthoritative;
}
/**
* Should class lookup fail if not found in the current class map?
*
* @return bool
*/
public function isClassMapAuthoritative()
{
return $this->classMapAuthoritative;
}
/**
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
*
* @param string|null $apcuPrefix
*
* @return void
*/
public function setApcuPrefix($apcuPrefix)
{
$this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
}
/**
* The APCu prefix in use, or null if APCu caching is not enabled.
*
* @return string|null
*/
public function getApcuPrefix()
{
return $this->apcuPrefix;
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*
* @return void
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
if (null === $this->vendorDir) {
return;
}
if ($prepend) {
self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
} else {
unset(self::$registeredLoaders[$this->vendorDir]);
self::$registeredLoaders[$this->vendorDir] = $this;
}
}
/**
* Unregisters this instance as an autoloader.
*
* @return void
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
if (null !== $this->vendorDir) {
unset(self::$registeredLoaders[$this->vendorDir]);
}
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return true|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
$includeFile = self::$includeFile;
$includeFile($file);
return true;
}
return null;
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
if (null !== $this->apcuPrefix) {
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
if ($hit) {
return $file;
}
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if (false === $file && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if (null !== $this->apcuPrefix) {
apcu_add($this->apcuPrefix.$class, $file);
}
if (false === $file) {
// Remember that this class does not exist.
$this->missingClasses[$class] = true;
}
return $file;
}
/**
* Returns the currently registered loaders indexed by their corresponding vendor directories.
*
* @return self[]
*/
public static function getRegisteredLoaders()
{
return self::$registeredLoaders;
}
/**
* @param string $class
* @param string $ext
* @return string|false
*/
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath . '\\';
if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) {
if (file_exists($file = $dir . $pathEnd)) {
return $file;
}
}
}
}
}
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
/**
* @return void
*/
private static function initializeIncludeClosure()
{
if (self::$includeFile !== null) {
return;
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*
* @param string $file
* @return void
*/
self::$includeFile = \Closure::bind(static function($file) {
include $file;
}, null, null);
}
}
+359
View File
@@ -0,0 +1,359 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer;
use Composer\Autoload\ClassLoader;
use Composer\Semver\VersionParser;
/**
* This class is copied in every Composer installed project and available to all
*
* See also https://getcomposer.org/doc/07-runtime.md#installed-versions
*
* To require its presence, you can require `composer-runtime-api ^2.0`
*
* @final
*/
class InstalledVersions
{
/**
* @var mixed[]|null
* @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}|array{}|null
*/
private static $installed;
/**
* @var bool|null
*/
private static $canGetVendors;
/**
* @var array[]
* @psalm-var array<string, array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
private static $installedByVendor = array();
/**
* Returns a list of all package names which are present, either by being installed, replaced or provided
*
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackages()
{
$packages = array();
foreach (self::getInstalled() as $installed) {
$packages[] = array_keys($installed['versions']);
}
if (1 === \count($packages)) {
return $packages[0];
}
return array_keys(array_flip(\call_user_func_array('array_merge', $packages)));
}
/**
* Returns a list of all package names with a specific type e.g. 'library'
*
* @param string $type
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackagesByType($type)
{
$packagesByType = array();
foreach (self::getInstalled() as $installed) {
foreach ($installed['versions'] as $name => $package) {
if (isset($package['type']) && $package['type'] === $type) {
$packagesByType[] = $name;
}
}
}
return $packagesByType;
}
/**
* Checks whether the given package is installed
*
* This also returns true if the package name is provided or replaced by another package
*
* @param string $packageName
* @param bool $includeDevRequirements
* @return bool
*/
public static function isInstalled($packageName, $includeDevRequirements = true)
{
foreach (self::getInstalled() as $installed) {
if (isset($installed['versions'][$packageName])) {
return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false;
}
}
return false;
}
/**
* Checks whether the given package satisfies a version constraint
*
* e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call:
*
* Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3')
*
* @param VersionParser $parser Install composer/semver to have access to this class and functionality
* @param string $packageName
* @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package
* @return bool
*/
public static function satisfies(VersionParser $parser, $packageName, $constraint)
{
$constraint = $parser->parseConstraints((string) $constraint);
$provided = $parser->parseConstraints(self::getVersionRanges($packageName));
return $provided->matches($constraint);
}
/**
* Returns a version constraint representing all the range(s) which are installed for a given package
*
* It is easier to use this via isInstalled() with the $constraint argument if you need to check
* whether a given version of a package is installed, and not just whether it exists
*
* @param string $packageName
* @return string Version constraint usable with composer/semver
*/
public static function getVersionRanges($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
$ranges = array();
if (isset($installed['versions'][$packageName]['pretty_version'])) {
$ranges[] = $installed['versions'][$packageName]['pretty_version'];
}
if (array_key_exists('aliases', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']);
}
if (array_key_exists('replaced', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']);
}
if (array_key_exists('provided', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']);
}
return implode(' || ', $ranges);
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['version'])) {
return null;
}
return $installed['versions'][$packageName]['version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getPrettyVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['pretty_version'])) {
return null;
}
return $installed['versions'][$packageName]['pretty_version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference
*/
public static function getReference($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['reference'])) {
return null;
}
return $installed['versions'][$packageName]['reference'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path.
*/
public static function getInstallPath($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null;
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @return array
* @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}
*/
public static function getRootPackage()
{
$installed = self::getInstalled();
return $installed[0]['root'];
}
/**
* Returns the raw installed.php data for custom implementations
*
* @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect.
* @return array[]
* @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}
*/
public static function getRawData()
{
@trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED);
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
self::$installed = include __DIR__ . '/installed.php';
} else {
self::$installed = array();
}
}
return self::$installed;
}
/**
* Returns the raw data of all installed.php which are currently loaded for custom implementations
*
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
public static function getAllRawData()
{
return self::getInstalled();
}
/**
* Lets you reload the static array from another file
*
* This is only useful for complex integrations in which a project needs to use
* this class but then also needs to execute another project's autoloader in process,
* and wants to ensure both projects have access to their version of installed.php.
*
* A typical case would be PHPUnit, where it would need to make sure it reads all
* the data it needs from this class, then call reload() with
* `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure
* the project in which it runs can then also use this class safely, without
* interference between PHPUnit's dependencies and the project's dependencies.
*
* @param array[] $data A vendor/composer/installed.php data set
* @return void
*
* @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $data
*/
public static function reload($data)
{
self::$installed = $data;
self::$installedByVendor = array();
}
/**
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
private static function getInstalled()
{
if (null === self::$canGetVendors) {
self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders');
}
$installed = array();
if (self::$canGetVendors) {
foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
if (isset(self::$installedByVendor[$vendorDir])) {
$installed[] = self::$installedByVendor[$vendorDir];
} elseif (is_file($vendorDir.'/composer/installed.php')) {
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require $vendorDir.'/composer/installed.php';
$installed[] = self::$installedByVendor[$vendorDir] = $required;
if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) {
self::$installed = $installed[count($installed) - 1];
}
}
}
}
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require __DIR__ . '/installed.php';
self::$installed = $required;
} else {
self::$installed = array();
}
}
if (self::$installed !== array()) {
$installed[] = self::$installed;
}
return $installed;
}
}
+21
View File
@@ -0,0 +1,21 @@
Copyright (c) Nils Adermann, Jordi Boggiano
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+10
View File
@@ -0,0 +1,10 @@
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
);
+9
View File
@@ -0,0 +1,9 @@
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
);
+10
View File
@@ -0,0 +1,10 @@
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'app\\' => array($baseDir . '/'),
);
+36
View File
@@ -0,0 +1,36 @@
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit345c1a817a7f402322a2ecae01a96071
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
/**
* @return \Composer\Autoload\ClassLoader
*/
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInit345c1a817a7f402322a2ecae01a96071', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
spl_autoload_unregister(array('ComposerAutoloaderInit345c1a817a7f402322a2ecae01a96071', 'loadClassLoader'));
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit345c1a817a7f402322a2ecae01a96071::getInitializer($loader));
$loader->register(true);
return $loader;
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInit345c1a817a7f402322a2ecae01a96071
{
public static $prefixLengthsPsr4 = array (
'a' =>
array (
'app\\' => 4,
),
);
public static $prefixDirsPsr4 = array (
'app\\' =>
array (
0 => __DIR__ . '/../..' . '/',
),
);
public static $classMap = array (
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit345c1a817a7f402322a2ecae01a96071::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit345c1a817a7f402322a2ecae01a96071::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInit345c1a817a7f402322a2ecae01a96071::$classMap;
}, null, ClassLoader::class);
}
}
+5
View File
@@ -0,0 +1,5 @@
{
"packages": [],
"dev": true,
"dev-package-names": []
}
+23
View File
@@ -0,0 +1,23 @@
<?php return array(
'root' => array(
'name' => 'andrei_robert/api.knowyourfood',
'pretty_version' => '1.0.0+no-version-set',
'version' => '1.0.0.0',
'reference' => NULL,
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev' => true,
),
'versions' => array(
'andrei_robert/api.knowyourfood' => array(
'pretty_version' => '1.0.0+no-version-set',
'version' => '1.0.0.0',
'reference' => NULL,
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev_requirement' => false,
),
),
);
-3
View File
@@ -1,3 +0,0 @@
DB_DSN = mysql:host=localhost;port=3306;dbname=Web
DB_USER = root
DB_PASSWORD = root
Regular → Executable
View File
+2 -12
View File
@@ -1,14 +1,4 @@
ErrorDocument 403 /404.php
ErrorDocument 404 /404.php
DirectoryINdex index.php
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]
RewriteCond %{REQUEST_URI} !^/$
RewriteCond %{REQUEST_URI} !^/admin
RewriteRule .*/ [L,R=301]
</IfModule>
RewriteRule ^(.*)$ index.php [L]
Regular → Executable
+4 -10
View File
@@ -1,17 +1,11 @@
{
"name": "andrei/knowyourfood",
"authors": [
{
"name": "Cerbu Andrei Mihnea",
"email": "andreimihneacerbu@gmail.com"
}
],
"autoload" : {
"psr-4" : {
"name": "andrei_cerbu/knowyourfood",
"autoload": {
"psr-4": {
"app\\": "./"
}
},
"require": {
"vlucas/phpdotenv": "^5.5"
"ext-curl": "*"
}
}
Generated Regular → Executable
+5 -473
View File
@@ -4,485 +4,17 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "c85ce2bf1fa0099ca65ec02d2a26abb1",
"packages": [
{
"name": "graham-campbell/result-type",
"version": "v1.1.1",
"source": {
"type": "git",
"url": "https://github.com/GrahamCampbell/Result-Type.git",
"reference": "672eff8cf1d6fe1ef09ca0f89c4b287d6a3eb831"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/GrahamCampbell/Result-Type/zipball/672eff8cf1d6fe1ef09ca0f89c4b287d6a3eb831",
"reference": "672eff8cf1d6fe1ef09ca0f89c4b287d6a3eb831",
"shasum": ""
},
"require": {
"php": "^7.2.5 || ^8.0",
"phpoption/phpoption": "^1.9.1"
},
"require-dev": {
"phpunit/phpunit": "^8.5.32 || ^9.6.3 || ^10.0.12"
},
"type": "library",
"autoload": {
"psr-4": {
"GrahamCampbell\\ResultType\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Graham Campbell",
"email": "hello@gjcampbell.co.uk",
"homepage": "https://github.com/GrahamCampbell"
}
],
"description": "An Implementation Of The Result Type",
"keywords": [
"Graham Campbell",
"GrahamCampbell",
"Result Type",
"Result-Type",
"result"
],
"support": {
"issues": "https://github.com/GrahamCampbell/Result-Type/issues",
"source": "https://github.com/GrahamCampbell/Result-Type/tree/v1.1.1"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/graham-campbell/result-type",
"type": "tidelift"
}
],
"time": "2023-02-25T20:23:15+00:00"
},
{
"name": "phpoption/phpoption",
"version": "1.9.1",
"source": {
"type": "git",
"url": "https://github.com/schmittjoh/php-option.git",
"reference": "dd3a383e599f49777d8b628dadbb90cae435b87e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/schmittjoh/php-option/zipball/dd3a383e599f49777d8b628dadbb90cae435b87e",
"reference": "dd3a383e599f49777d8b628dadbb90cae435b87e",
"shasum": ""
},
"require": {
"php": "^7.2.5 || ^8.0"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
"phpunit/phpunit": "^8.5.32 || ^9.6.3 || ^10.0.12"
},
"type": "library",
"extra": {
"bamarni-bin": {
"bin-links": true,
"forward-command": true
},
"branch-alias": {
"dev-master": "1.9-dev"
}
},
"autoload": {
"psr-4": {
"PhpOption\\": "src/PhpOption/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"Apache-2.0"
],
"authors": [
{
"name": "Johannes M. Schmitt",
"email": "schmittjoh@gmail.com",
"homepage": "https://github.com/schmittjoh"
},
{
"name": "Graham Campbell",
"email": "hello@gjcampbell.co.uk",
"homepage": "https://github.com/GrahamCampbell"
}
],
"description": "Option Type for PHP",
"keywords": [
"language",
"option",
"php",
"type"
],
"support": {
"issues": "https://github.com/schmittjoh/php-option/issues",
"source": "https://github.com/schmittjoh/php-option/tree/1.9.1"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/phpoption/phpoption",
"type": "tidelift"
}
],
"time": "2023-02-25T19:38:58+00:00"
},
{
"name": "symfony/polyfill-ctype",
"version": "v1.27.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-ctype.git",
"reference": "5bbc823adecdae860bb64756d639ecfec17b050a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/5bbc823adecdae860bb64756d639ecfec17b050a",
"reference": "5bbc823adecdae860bb64756d639ecfec17b050a",
"shasum": ""
},
"require": {
"php": ">=7.1"
},
"provide": {
"ext-ctype": "*"
},
"suggest": {
"ext-ctype": "For best performance"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "1.27-dev"
},
"thanks": {
"name": "symfony/polyfill",
"url": "https://github.com/symfony/polyfill"
}
},
"autoload": {
"files": [
"bootstrap.php"
],
"psr-4": {
"Symfony\\Polyfill\\Ctype\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Gert de Pagter",
"email": "BackEndTea@gmail.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill for ctype functions",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"ctype",
"polyfill",
"portable"
],
"support": {
"source": "https://github.com/symfony/polyfill-ctype/tree/v1.27.0"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2022-11-03T14:55:06+00:00"
},
{
"name": "symfony/polyfill-mbstring",
"version": "v1.27.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-mbstring.git",
"reference": "8ad114f6b39e2c98a8b0e3bd907732c207c2b534"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/8ad114f6b39e2c98a8b0e3bd907732c207c2b534",
"reference": "8ad114f6b39e2c98a8b0e3bd907732c207c2b534",
"shasum": ""
},
"require": {
"php": ">=7.1"
},
"provide": {
"ext-mbstring": "*"
},
"suggest": {
"ext-mbstring": "For best performance"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "1.27-dev"
},
"thanks": {
"name": "symfony/polyfill",
"url": "https://github.com/symfony/polyfill"
}
},
"autoload": {
"files": [
"bootstrap.php"
],
"psr-4": {
"Symfony\\Polyfill\\Mbstring\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill for the Mbstring extension",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"mbstring",
"polyfill",
"portable",
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-mbstring/tree/v1.27.0"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2022-11-03T14:55:06+00:00"
},
{
"name": "symfony/polyfill-php80",
"version": "v1.27.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-php80.git",
"reference": "7a6ff3f1959bb01aefccb463a0f2cd3d3d2fd936"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/7a6ff3f1959bb01aefccb463a0f2cd3d3d2fd936",
"reference": "7a6ff3f1959bb01aefccb463a0f2cd3d3d2fd936",
"shasum": ""
},
"require": {
"php": ">=7.1"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "1.27-dev"
},
"thanks": {
"name": "symfony/polyfill",
"url": "https://github.com/symfony/polyfill"
}
},
"autoload": {
"files": [
"bootstrap.php"
],
"psr-4": {
"Symfony\\Polyfill\\Php80\\": ""
},
"classmap": [
"Resources/stubs"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Ion Bazan",
"email": "ion.bazan@gmail.com"
},
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"polyfill",
"portable",
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-php80/tree/v1.27.0"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2022-11-03T14:55:06+00:00"
},
{
"name": "vlucas/phpdotenv",
"version": "v5.5.0",
"source": {
"type": "git",
"url": "https://github.com/vlucas/phpdotenv.git",
"reference": "1a7ea2afc49c3ee6d87061f5a233e3a035d0eae7"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/1a7ea2afc49c3ee6d87061f5a233e3a035d0eae7",
"reference": "1a7ea2afc49c3ee6d87061f5a233e3a035d0eae7",
"shasum": ""
},
"require": {
"ext-pcre": "*",
"graham-campbell/result-type": "^1.0.2",
"php": "^7.1.3 || ^8.0",
"phpoption/phpoption": "^1.8",
"symfony/polyfill-ctype": "^1.23",
"symfony/polyfill-mbstring": "^1.23.1",
"symfony/polyfill-php80": "^1.23.1"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.4.1",
"ext-filter": "*",
"phpunit/phpunit": "^7.5.20 || ^8.5.30 || ^9.5.25"
},
"suggest": {
"ext-filter": "Required to use the boolean validator."
},
"type": "library",
"extra": {
"bamarni-bin": {
"bin-links": true,
"forward-command": true
},
"branch-alias": {
"dev-master": "5.5-dev"
}
},
"autoload": {
"psr-4": {
"Dotenv\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Graham Campbell",
"email": "hello@gjcampbell.co.uk",
"homepage": "https://github.com/GrahamCampbell"
},
{
"name": "Vance Lucas",
"email": "vance@vancelucas.com",
"homepage": "https://github.com/vlucas"
}
],
"description": "Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.",
"keywords": [
"dotenv",
"env",
"environment"
],
"support": {
"issues": "https://github.com/vlucas/phpdotenv/issues",
"source": "https://github.com/vlucas/phpdotenv/tree/v5.5.0"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/vlucas/phpdotenv",
"type": "tidelift"
}
],
"time": "2022-10-16T01:01:54+00:00"
}
],
"content-hash": "d99f7bada71212307c9485da334476d5",
"packages": [],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"prefer-stable": false,
"prefer-lowest": false,
"platform": [],
"platform": {
"ext-curl": "*"
},
"platform-dev": [],
"plugin-api-version": "2.3.0"
}
+58 -40
View File
@@ -1,70 +1,88 @@
<?php
namespace app\controllers;
use app\core\middlewares\AuthMiddleware;
use app\core\Application;
use app\core\Controller;
use app\core\Request;
use app\core\Response;
use app\models\LoginForm;
use app\models\User;
use app\models\LoginModel;
use app\core\Model;
use app\models\RegisterModel;
class AuthController extends Controller{
public function __construct(){
$this->registerMiddleware(new AuthMiddleware(['profile']));
}
public function login(Request $request, Response $response){
$loginForm = new LoginForm();
public static function loginPage(Request $request): string
{
$model = new LoginModel();
if($request->isPost()){
$loginForm->loadData($request->getBody());
if($loginForm->validate() && $loginForm->login()){
$response->redirect('home');
exit;
$model->loadData($request->getPOSTBody());
$model->checkForErrors();
if($model->hasErrors()){
self::setControllerParams("Login", "Login", "Auth", $model);
return Application::$app->controller->render();
}
$model->removeErrors();
$body = $model->createBody();
$headers = $model->createHeaders(json_encode($body));
$model->setParametersForRequest("GET", $headers, $body);
$model->execute();
if($model->isRequestFulfilled()){
//Application::$app->response->redirect("homepage");
}
$this->setLayout('auth');
return $this->render('login', [
'model' => $loginForm
]);
$model->setRequestError();
self::setControllerParams("Login", "Login", "Auth", $model);
return Application::$app->controller->render();
}
$this->setLayout('auth');
return $this->render('login', [
'model' => $loginForm
]);
self::setControllerParams("Login", "Login", "Auth", $model);
return Application::$app->controller->render();
}
public function register(Request $request, $response){
$user = new User();
public static function registerPage(Request $request): string
{
$model = new RegisterModel();
if($request->isPost()){
$user->loadData($request->getBody());
$model->loadData($request->getPOSTBody());
$model->checkForErrors();
if($user->validate() && $user->save()){
$response->redirect('home');
exit;
if($model->hasErrors()){
self::setControllerParams("Register", "Register", "Auth", $model);
return Application::$app->controller->render();
}
$model->removeErrors();
$body = $model->createBody();
$headers = $model->createHeaders(json_encode($body));
$model->setParametersForRequest("PUT", $headers, $body);
$model->execute();
if($model->isRequestFulfilled()){
Application::$app->response->redirect("login");
}
$this->setLayout('auth');
return $this->render('register', [
'model'=>$user
]);
$model->setRequestError();
self::setControllerParams("Register", "Register", "Auth", $model);
return Application::$app->controller->render();
}
$this->setLayout('auth');
return $this->render('register', [
'model'=>$user
]);
self::setControllerParams("Register", "Register", "Auth", $model);
return Application::$app->controller->render();
}
public function logout($request, $response){
Application::$app->logout();
$response->redirect('/');
}
public function profile(){
return $this->render('profile');
public static function setControllerParams(string $title, string $view, string $layout, ?Model $model): void
{
Application::$app->controller->setLayout($layout);
Application::$app->controller->setModel($model);
Application::$app->controller->setTitle($title);
Application::$app->controller->setView($view);
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
namespace app\controllers;
use app\core\Application;
use app\core\Controller;
use app\core\Model;
use app\core\Request;
use app\core\Response;
use app\models\ContactForm;
class SiteController extends Controller
{
public function Homepage(): string
{
return $this->render();
}
public function profile(): string
{
return $this->render('profile');
}
public static function renderMainPage(): string
{
Application::$app->view->setLayout('Main');
return Application::$app->view->renderLayout();
}
public function _404(): string
{
return $this->render();
}
public function _403(): string
{
return $this->render();
}
protected static function setControllerParams(string $title, string $view, string $layout, ?Model $model)
{
// TODO: Implement setControllerParams() method.
}
}
@@ -1,55 +0,0 @@
<?php
namespace app\controllers;
use app\core\Application;
use app\core\Controller;
use app\core\Request;
use app\core\Response;
use app\models\ContactForm;
class SiteController extends Controller
{
public function contact(Request $request, Response $response)
{
$contact = new ContactForm();
if ($request->isPost()) {
$contact->loadData($request->getBody());
if ($contact->validate() && $contact->send()) {
Application::$app->session->setFlash('success', 'The form has been succesfully sent!');
var_dump($_SESSION['flash_messages']);
$response->redirect('contact');
exit;
}
return $this->render('contact', [
'model' => $contact
]);
}
return $this->render('contact', [
'model' => $contact
]);
}
public function home()
{
$params = [
'name' => "TheCodeholic"
];
return $this->render('home', $params);
}
public function profile()
{
return $this->render('profile');
}
public function _404()
{
return $this->render('_404');
}
}
+15 -66
View File
@@ -1,93 +1,42 @@
<?php
namespace app\core;
use app\core\exceptions\ForbiddenException;
use app\core\exceptions\NotFoundException;
class Application
use AllowDynamicProperties;
use app\exceptions\ForbiddenAccessException;
use app\exceptions\PageNotFoundException;
#[AllowDynamicProperties] class Application
{
public static string $ROOT_DIR;
public string $userClass;
public string $layout = 'main';
public static Application $app;
public Router $router;
public Request $request;
public Response $response;
public static Application $app;
public ?Controller $controller = null;
public Database $db;
public Session $session;
public ?DbModel $user;
public View $view;
public function __construct($rootPath, array $config)
public function __construct()
{
self::$ROOT_DIR = $rootPath;
$this->userClass = $config['userClass'];
self::$ROOT_DIR = dirname(__DIR__);
self::$app = $this;
$this->request = new Request();
$this->response = new Response();
$this->router = new Router($this->request, $this->response);
$this->router = new Router($this->request);
$this->view = new View();
$this->db = new Database($config['db']);
$this->session = new Session();
$primaryValue = $this->session->get('user');
if ($primaryValue) {
$userObj = new $this->userClass();
$primaryKey = $userObj->primaryKey();
$this->user = $userObj->findOne([$primaryKey => $primaryValue]);
} else {
$this->user = null;
}
}
public function setController($controller)
{
$this->controller = $controller;
}
public function getController()
{
return $this->controller;
}
public function login(DbModel $user)
{
$this->user = $user;
$primaryKey = $user->primaryKey();
$primaryValue = $user->{$primaryKey};
$this->session->set('user', $primaryValue);
return true;
}
public function logout()
{
$this->user = null;
$this->session->remove('user');
}
public static function isLoggedIn()
{
return !self::$app->user;
}
public function run()
public function run(): void
{
try{
echo $this->router->resolve();
}catch(ForbiddenException $e){
$this->response->setStatusCode(403);
echo $this->view->renderView('_error', [
'exception' => $e
]);
}catch(NotFoundException $e){
$this->response->setStatusCode(404);
echo $this->view->renderView('_error', [
'exception' => $e
]);
echo $this->router->resolve();
}catch(ForbiddenAccessException $e){
}catch(PageNotFoundException $e){
}
}
}
Regular → Executable
+17 -17
View File
@@ -1,26 +1,26 @@
<?php
namespace app\core;
use app\core\middlewares\BaseMiddleware;
class Controller{
public string $layout = 'main';
public string $action = '';
protected array $middlewares = [];
abstract class Controller{
protected string $view = "";
protected string $title = "";
protected string $layout = "";
protected ?Model $model = NULL;
public function render(): string
{
Application::$app->view->setLayout($this->layout);
Application::$app->view->setTitle($this->title);
Application::$app->view->setView($this->view);
Application::$app->view->setModel($this->model);
public function render($view, $params = []){
return Application::$app->view->renderView($view, $params);
return Application::$app->view->render();
}
public function setLayout($layout){
$this->layout = $layout;
}
protected static abstract function setControllerParams(string $title, string $view, string $layout, ?Model $model);
public function registerMiddleware(BaseMiddleware $middleware){
$this->middlewares[] = $middleware;
}
public function getMiddlewares(){
return $this->middlewares;
}
public function setView(string $view): void {$this->view = $view;}
public function setTitle(string $title): void {$this->title = $title;}
public function setLayout(string $layout): void {$this->layout = $layout;}
public function setModel(?Model $model): void {$this->model = $model;}
}
+96
View File
@@ -0,0 +1,96 @@
<?php
namespace app\core;
Class DVC
{
public static string $nameOfResponsePackage = "response_package";
public static string $successName = "Success";
public static string $genericExceptionName = "GenericErrorException";
public static string $invalidTokenName = "InvalidTokenException";
public static string $invalidRequestName = "InvalidRequestException";
public static string $invalidCurlStructureName = "InvalidCurlStructureException";
public static string $invalidBodyName = "InvalidBodyException";
public static string $alreadyExistsName = "AlreadyExistsException";
public static string $userNotExistingName = "userNotExistingException";
public static string $fieldNotExistingName = "FieldNotExistingException";
public static string $pageNotFoundName = "pageNotfoundException";
public static string $forbiddenAccessName = "forbiddenAccessException";
public static string $serviceNotFoundName = "FieldNotFoundException";
public static string $returnCode = "returnCode";
public static string $returnMessage = "returnMessage";
public static int $successReturnCode = 460;
public static function getArrayResponse(string $name): array
{
return match ($name){
DVC::$successName => [
DVC::$returnCode => 460,
DVC::$returnMessage => "Operation done successfully"
],
DVC::$genericExceptionName => [
DVC::$returnCode => 461,
DVC::$returnMessage => "Internal Server Error"
],
DVC::$invalidTokenName => [
DVC::$returnCode => 462,
DVC::$returnMessage => "Unauthorized access"
],
DVC::$invalidRequestName => [
DVC::$returnCode => 463,
DVC::$returnMessage => "Service doesn't provide this type of request"
],
DVC::$invalidBodyName => [
DVC::$returnCode => 464,
DVC::$returnMessage => "Not valid parameters sent"
],
DVC::$alreadyExistsName => [
DVC::$returnCode => 465,
DVC::$returnMessage => "Field already existing"
],
DVC::$fieldNotExistingName => [
DVC::$returnCode => 466,
DVC::$returnMessage => "Field not existing anymore"
],
DVC::$invalidCurlStructureName => [
DVC::$returnCode => 467,
DVC::$returnMessage => "cURL class needs URL, request method and headers to run"
],
DVC::$userNotExistingName => [
DVC::$returnCode => 468,
DVC::$returnMessage => "User account doesn't exists"
],
DVC::$pageNotFoundName => [
DVC::$returnCode => 469,
DVC::$returnMessage => "Page not found"
],
DVC::$forbiddenAccessName => [
DVC::$returnCode => 470,
DVC::$returnMessage => "You are not authorised to access this page"
],
DVC::$serviceNotFoundName => [
DVC::$returnCode => 471,
DVC::$returnCode => "Service not existing"
]
};
}
public static function getHttpCodeWithCode(int $code): int
{
return match ($code){
460 => 200,
461 => 500,
462 => 401,
463 => 405,
464 => 400,
465, 466 => 204,
467 => 409,
468, 469, 471 => 404,
470 => 403,
default => 100
};
}
}
Regular → Executable
View File
-51
View File
@@ -1,51 +0,0 @@
<?php
namespace app\core;
abstract class DbModel extends Model{
abstract public function tableName(): string;
abstract public function attributes(): array;
abstract public function primaryKey(): string;
public function save(){
$tableName = $this->tableName();
$attributes = $this->attributes();
$params = array_map(fn($attr) => ":$attr", $attributes);
$statement = self::prepare("INSERT INTO $tableName ("
.implode(',', $attributes)
.") VALUES ("
.implode(',', $params)
.")"
);
foreach($attributes as $attribute){
$statement->bindValue(":$attribute", $this->{$attribute});
}
$statement->execute();
return true;
}
public static function prepare($sql){
return Application::$app->db->pdo->prepare($sql);
}
public function findOne($where){
$tableName = static::tableName();
$attributes = array_keys($where);
$sql = implode("AND ", array_map(fn($attr) => "$attr = :$attr", $attributes));
$statement = self::prepare("SELECT * from $tableName WHERE $sql");
foreach($where as $key => $item){
$statement->bindValue(":$key", $item);
}
$statement->execute();
return $statement->fetchObject(static::class);
}
}
Regular → Executable
+89 -74
View File
@@ -2,103 +2,118 @@
namespace app\core;
use app\external_requests\CurlRequestBuilder;
abstract class Model{
public const RULE_REQUIRED = 'required';
public const RULE_EMAIL = 'email';
public const RULE_MIN = 'min';
public const RULE_MAX = 'max';
public const RULE_UNIQUE = 'unique';
public array $errors = array();
public function loadData($data){
private ?string $request = NULL;
private string $url = "192.168.0.13:701/authentication";
private ?array $headers = [];
private ?array $body = [];
private ?int $code = NULL;
private ?string $message = NULL;
public function loadData($data): void
{
foreach ($data as $key => $value){
if(property_exists($this, $key)){
$this->{$key} = $value;
}
}
}
abstract public function rules():array;
public function labels(): array{
return [];
}
public array $errors = [];
private function addErrorForRule(string $attribute, string $rule, $params =[]){
$message = $this->errorMessages()[$rule] ?? '';
foreach($params as $key => $value){
$message = str_replace("{{$key}}", $value, $message);
}
$this->errors[$attribute][] = $message;
}
public function addError(string $attribute, string $message){
$this->errors[$attribute][] = $message;
}
public function errorMessages(){
abstract public function rules(): array;
public abstract function labels(): array;
public function errorMessages(): array{
return [
self::RULE_REQUIRED => 'This field is required',
self::RULE_EMAIL => 'This field must be valid email address',
self::RULE_MIN => 'Min length of this field must be {min}',
self::RULE_MAX => 'Max length of this field must be {max}',
self::RULE_UNIQUE => 'Email already exists'
self::RULE_EMAIL => 'This field must be a valid email address',
];
}
public function validate(){
foreach($this->rules() as $attribute => $rules){
$value = $this->{$attribute};
foreach($rules as $rule){
$ruleName = $rule;
if(!is_string($ruleName)){
$ruleName = $rule[0];
public function checkForErrors(): void{
foreach($this->rules() as $field => $rules){
$value = $this->{$field};
foreach ($rules as $rule){
if($rule == self::RULE_REQUIRED && !strlen($value)) {
$this->addError($field, $this->errorMessages()[$rule]);
break;
}
if($ruleName === self::RULE_REQUIRED && !$value){
$this->addErrorForRule($attribute, self::RULE_REQUIRED);
}
if($ruleName === self::RULE_EMAIL && !filter_var($value, FILTER_VALIDATE_EMAIL)){
$this->addErrorForRule($attribute, self::RULE_EMAIL);
}
if($ruleName === self::RULE_MIN && strlen($value) < $rule['min']){
$this->addErrorForRule($attribute, self::RULE_MIN, $rule);
}
if($ruleName === self::RULE_MAX && strlen($value) > $rule['max']){
$this->addErrorForRule($attribute, self::RULE_MAX, $rule);
}
if($ruleName === self::RULE_UNIQUE){
$className = $rule['class'];
$uniqueAttr = $rule['attirubute'] ?? $attribute;
$tableName = $className::tableName();
$statement = Application::$app->db->prepare(("SELECT * FROM $tableName WHERE $uniqueAttr = :attr"));
$statement->bindValue(":attr", $value);
$statement->execute();
$record = $statement->fetchObject();
if($record){
$this->addErrorForRule($attribute, SELF::RULE_UNIQUE);
}
if($rule == self::RULE_EMAIL && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
$this->addError($field, $this->errorMessages()[$rule]);
break;
}
}
}
return empty($this->errors);
}
public function hasError($attribute){
return $this->errors[$attribute] ?? false;
protected abstract function createBody(): array;
protected abstract function createHeaders(string $body): array;
protected abstract function formatHeaderArray(array $headers): array;
public function setParametersForRequest(string $request, array $headers, array $body): void
{
$this->request = $request;
$this->headers = $headers;
$this->body = $body;
}
public function getFirstError($attribute){
return $this->errors[$attribute][0] ?? '';
public function execute(): void
{
$requestBuilder = new CurlRequestBuilder();
$requestBuilder->setRequest($this->request);
$requestBuilder->setUrl($this->url);
$requestBuilder->setHeaders($this->headers);
$requestBuilder->setBody($this->body);
$requestBuilder->setIsReturnable(true);
$curl = $requestBuilder->getCurlRequestObject();
$response = json_decode($curl->makeRequest(), true);
$this->code = $response["code"];
$this->message = $response["message"];
}
public function isRequestFulfilled(): bool
{
return $this->code == DVC::$successReturnCode;
}
public function setRequestError(): void
{
Application::$app->view->setActionError($this->message);
}
public function addError($attribute, $message): void
{
$this->errors[$attribute] = $message;
}
public function removeErrors(): void
{
unset($this->errors);
$this->errors = array();
}
public function hasErrors(): bool
{
return count($this->errors);
}
public function getError($field): ?string
{
return array_key_exists($field, $this->errors) ? $this->errors[$field] : NULL;
}
public function getValueForField($field):string
{
return $this->{$field};
}
}
Regular → Executable
+24 -24
View File
@@ -3,47 +3,47 @@
namespace app\core;
class Request{
private int $lengthOfRoot;
public function __construct(){
$this->lengthOfRoot = strlen('knowyourfood') + 1;
}
public function getPath(){//identificam din URL pe pagina trebuie accesata
$path = $_SERVER['REQUEST_URI'];
$path = substr($path, $this->lengthOfRoot);
$position = strpos($path, '?');
if(!$position){
return $path;
}
return substr($path, 0, $position);
public function getPath(): string
{
return $_SERVER['REQUEST_URI'];
}
public function method(){
return strtolower($_SERVER['REQUEST_METHOD']);
public function method():string
{
return $_SERVER['REQUEST_METHOD'];
}
public function isGet(){
return $this->method() === 'get';
public function isGet(): bool
{
return $_SERVER['REQUEST_METHOD'] === "GET";
}
public function isPost(){
return $this->method() === 'post';
public function isPost(): bool
{
return $_SERVER['REQUEST_METHOD'] === "POST";
}
//bazat pe tipul de request, accesam tuplele key/value pentru a identifica body ul requestului
public function getBody(){
public function getGETBody(): ?array
{
$body = [];
if($this->method() === 'get'){
if($this->method() === 'GET'){
foreach($_GET as $key => $value){
$body[$key] = filter_input(INPUT_GET, $key, FILTER_SANITIZE_SPECIAL_CHARS);
}
}
if($this->method() === 'post'){
return $body;
}
public function getPOSTBody(): ?array
{
$body = [];
if($this->method() === 'POST'){
foreach($_POST as $key => $value){
$body[$key] = filter_input(INPUT_POST, $key, FILTER_SANITIZE_SPECIAL_CHARS);
}
Regular → Executable
View File
Regular → Executable
+16 -18
View File
@@ -1,31 +1,31 @@
<?php
namespace app\core;
use app\core\exceptions\NotFoundException;
use app\exceptions\PageNotFoundException;
class Router
{
public Request $request;
public Response $response;
protected array $routes = [];
public function __construct(Request $request, Response $response)
public function __construct(Request $request)
{
$this->request = $request;
$this->response = $response;
}
public function get($path, $callback)
public function get($path, $callback): void
{
$this->routes['get'][$path] = $callback;
$this->routes['GET'][$path] = $callback;
}
public function post($path, $callback)
public function post($path, $callback): void
{
$this->routes['post'][$path] = $callback;
$this->routes['POST'][$path] = $callback;
}
/**
* @throws PageNotFoundException
*/
public function resolve()
{
$path = $this->request->getPath();
@@ -33,18 +33,16 @@ class Router
$callback = $this->routes[$method][$path] ?? false;
if (!$callback) {
throw new NotFoundException();
throw new PageNotFoundException();
}
$controller = new $callback[0]();
Application::$app->controller = $controller;
$controller->action = $callback[1];
$callback[0] = $controller;
Application::$app->controller = new $callback[0]();
foreach ($controller->getMiddlewares() as $middleware) {
$middleware->execute();
}
/*
* TODO:
* de adaugat aici middleware urile asociate unui controller
*/
return call_user_func($callback, $this->request, $this->response);
return call_user_func($callback, $this->request);
}
}
Regular → Executable
-41
View File
@@ -3,46 +3,5 @@
namespace app\core;
class Session{
protected const FLASH_KEY = 'flash_messages';
public function __construct(){
session_start();
foreach($_SESSION[self::FLASH_KEY] as $key => &$flashMessage){
$flashMessage['remove'] = 'true';
}
}
public function setFlash($key, $message){
$_SESSION[self::FLASH_KEY][$key] = [
'value' => $message,
'remove' => 'false'
];
}
public function getFlash($key){
return $_SESSION[self::FLASH_KEY][$key]['value'] ?? false;
}
public function set($key, $value){
$_SESSION[$key] = $value;
}
public function get($key){
return $_SESSION[$key];
}
public function remove($key){
unset($_SESSION[$key]);
}
public function __destruct(){
$flashMessages = $_SESSION[self::FLASH_KEY] ?? [];
foreach($flashMessages as $key => &$flashMessage){
if($flashMessage['remove'] == 'true'){
unset($flashMessages[$key]);
}
}
$_SESSION[self::FLASH_KEY] = $flashMessages;
}
}
Regular → Executable
+29 -29
View File
@@ -3,43 +3,43 @@
namespace app\core;
class View{
public string $title = '';
private string $title = '';
private string $view = '';
private string $layout = 'main';
private ?Model $model = NULL;
private string $actionError = '';
protected function layoutContent()
public function render(): string
{
$layout = Application::$app->layout;
if (Application::$app->controller) {
$layout = Application::$app->controller->layout;
}
ob_start();
include_once Application::$ROOT_DIR . "/views/layouts/$layout.php";
return ob_get_clean();
}
public function renderView($view, $params = [])
{
$viewContent = $this->renderOnlyView($view, $params);
$layoutContent = $this->layoutContent();
$viewContent = $this->renderView();
$layoutContent = $this->renderLayout();
return str_replace('{{content}}', $viewContent, $layoutContent);
}
public function renderContent($viewContent)
public function renderView(): string
{
$layoutContent = $this->layoutContent();
return str_replace('{{content}}', $viewContent, $layoutContent);
}
protected function renderOnlyView($view, $params)
{
foreach ($params as $key => $value) {
$$key = $value;
}
ob_start();
include_once Application::$ROOT_DIR."/views/$view.php";
include_once Application::$ROOT_DIR . "/views/$this->view.php";
return ob_get_clean();
}
public function renderLayout(): string
{
ob_start();
include_once Application::$ROOT_DIR . "/views/layouts/HTML/$this->layout.php";
return ob_get_clean();
}
public function setLayout($layout): void {$this->layout = $layout;}
public function setTitle($title): void {$this->title = $title;}
public function setView($view): void {$this->view = $view;}
public function setModel(?Model $model): void {$this->model = $model;}
public function setActionError(string $actionError): void {$this->actionError = $actionError;}
public function getTitle(): string {return $this->title;}
public function getView(): string {return $this->view;}
public function getLayout(): string {return $this->layout;}
public function getModel(): ?Model {return $this->model;}
public function getActionError(): string {return $this->actionError;}
}
@@ -1,8 +0,0 @@
<?php
namespace app\core\exceptions;
class ForbiddenException extends \Exception{
protected $code = 403;
protected $message = 'You do not have permission to access this page';
}
@@ -1,8 +0,0 @@
<?php
namespace app\core\exceptions;
class NotFoundException extends \Exception{
protected $code = 404;
protected $message = 'Page not found';
}
-35
View File
@@ -1,35 +0,0 @@
<?php
namespace app\core\form;
use app\core\Model;
abstract class BaseField
{
public Model $model;
public string $attribute;
public function __construct(Model $model, string $attribute)
{
$this->model = $model;
$this->attribute = $attribute;
}
abstract public function renderInput(): string;
public function __toString()
{
return sprintf('
<div class="mb-3">
<label>%s</label>
%s
<div class="invalid-feedback">
%s
</div>
</div>
',
$this->model->labels()[$this->attribute] ?? $this->attribute,
$this->renderInput(),
$this->model->getFirstError($this->attribute)
);
}
}
View File
-43
View File
@@ -1,43 +0,0 @@
<?php
namespace app\core\form;
use app\core\Model;
class Field{
public const TYPE_TEXT = 'text';
public const TYPE_PASSWORD = 'password';
public string $type;
public Model $model;
public string $attribute;
public function __construct(Model $model, string $attribute){
$this->type = self::TYPE_TEXT;
$this->model = $model;
$this->attribute = $attribute;
}
public function __toString(){
return sprintf('
<div class="mb-3">
<label>%s</label>
<input type="%s" name="%s" value="%s" class="form-control%s">
<div class="invalid-feedback">
%s
</div>
</div>
',
$this->model->labels()[$this->attribute] ?? $this->attribute,
$this->type,
$this->attribute,
$this->model->{$this->attribute},
$this->model->hasError($this->attribute) ? ' is invalid' : '',
$this->model->getFirstError($this->attribute)
);
}
public function passwordField(){
$this->type = self::TYPE_PASSWORD;
return $this;
}
}
Regular → Executable
+17 -9
View File
@@ -4,20 +4,28 @@ namespace app\core\form;
use app\core\Model;
class Form{
public static function begin($action, $method){
echo sprintf('<form action ="%s" method ="%s">', $action, $method);
return new Form();
private string $formDestinationPage = "";
public function __construct(string $formDestinationPage){
$this->formDestinationPage = $formDestinationPage;
}
public function beginForm(): void
{
echo "<form action='$this->formDestinationPage' method ='POST'>";
}
public static function end(){
echo '</form>';
public function endForm(): void
{
echo "</form>";
}
public function inputField(Model $model, $attribute){
return new InputField($model, $attribute);
public function renderInputField(string $type, string $name, string $placeholder, string $value, ?string $error): void
{
echo new InputField($type, $name, $placeholder, $value, $error);
}
public function button(){
return new Button();
public function renderButton(): void
{
echo new Button();
}
}
+30 -24
View File
@@ -2,35 +2,41 @@
namespace app\core\form;
use app\core\Model;
class InputField extends BaseField
class InputField
{
public const TYPE_TEXT = 'text';
public const TYPE_PASSWORD = 'password';
private string $type;
private string $name;
private string $placeholder;
private string $value;
private ?string $error;
public string $type;
public function __construct(Model $model, string $attribute)
public function __construct(string $type, string $name, string $placeholder, string $value, ?string $error)
{
$this->type = self::TYPE_TEXT;
parent::__construct($model, $attribute);
$this->type = $this->getInputType($type);
$this->name = $name;
$this->placeholder = $placeholder;
$this->value = $value;
$this->error = $error;
}
public function passwordField()
public function __toString():string
{
$this->type = self::TYPE_PASSWORD;
return $this;
}
public function renderInput(): string
{
return sprintf(
'<input type="%s" name="%s" value="%s" class="form-control%s">',
$this->type,
$this->attribute,
$this->model->{$this->attribute},
$this->model->hasError($this->attribute) ? ' is invalid' : ''
$field = sprintf(
'<input type="%s" name="%s" placeholder="%s" value="%s">',
$this->type, $this->name, $this->placeholder, $this->value
);
$errorField = NULL;
if(!$this->error == NULL){
$errorField = sprintf('<p class="errorStyle">%s</p>', $this->error);
}
return $field.$errorField;
}
private function getInputType(string $type): string{
return match($type){
"username", "email" => "text",
"password" => "password"
};
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace app\core\form;
use app\core\Model;
class Region extends BaseField
{
public const TYPE_TEXT = 'region';
public string $type;
public function __construct(Model $model, string $attribute)
{
$this->type = self::TYPE_TEXT;
parent::__construct($model, $attribute);
}
public function startSelect(): string
{
return sprintf('<select class="%s" name="%s">',
$this->type,
$this->type,
);
}
public function content(): ?string
{
return null;
}
public function endSelect(): string
{
return '</select>';
}
public function renderInput(): string
{
return $this->startSelect().$this->content().$this->endSelect();
}
}
View File
@@ -1,21 +0,0 @@
<?php
namespace app\core\middlewares;
use app\core\Application;
use app\core\exceptions\ForbiddenException;
class AuthMiddleware extends BaseMiddleware{
public array $actions = [];
public function __construct(array $actions = []){
$this->actions = $actions;
}
public function execute(){
if(Application::isLoggedIn()){
if(empty($this->actions) || in_array(Application::$app->controller->action, $this->actions)){
throw new ForbiddenException;
}
}
}
}
@@ -1,7 +0,0 @@
<?php
namespace app\core\middlewares;
abstract class BaseMiddleware{
abstract public function execute();
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace app\exceptions;
use app\core\DVC;
use Exception;
class ForbiddenAccessException extends Exception
{
public function __construct()
{
$array = DVC::getArrayResponse(DVC::$forbiddenAccessName);
parent::__construct($array[DVC::$returnMessage], $array[DVC::$returnCode]);
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace app\exceptions;
use app\core\DVC;
use Exception;
class GenericErrorException extends Exception
{
public function __construct()
{
$array = DVC::getArrayResponse(DVC::$genericExceptionName);
parent::__construct($array[DVC::$returnMessage], $array[DVC::$returnCode]);
}
}
+14
View File
@@ -0,0 +1,14 @@
<?php
namespace app\exceptions;
use app\core\DVC;
use Exception;
class InvalidCurlStructureException extends Exception
{
public function __construct()
{
$array = DVC::getArrayResponse(DVC::$invalidCurlStructureName);
parent::__construct($array[DVC::$returnMessage], $array[DVC::$returnCode]);
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace app\exceptions;
use app\core\DVC;
use Exception;
class PageNotFoundException extends Exception
{
public function __construct()
{
$array = DVC::getArrayResponse(DVC::$pageNotFoundName);
parent::__construct($array[DVC::$returnMessage], $array[DVC::$returnCode]);
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace app\external_requests;
use app\exceptions\GenericErrorException;
class CurlRequest
{
private string $url;
private string $request;
private array $headers;
private ?array $body;
private bool $isReturnable;
protected function __construct(string $url, string $request, array $headers, ?array $body, bool $isReturnable)
{
$this->url = $url;
$this->request = $request;
$this->headers = $headers;
$this->body = $body;
$this->isReturnable = $isReturnable;
}
/**
* @throws GenericErrorException
*/
public function makeRequest(): string
{
$curl = curl_init();
$this->setCurlBody($curl);
$response = curl_exec($curl);
if(!$response){
throw new GenericErrorException();
}
curl_close($curl);
return $response;
}
public function setCurlBody(\CurlHandle &$curl): void
{
curl_setopt($curl, CURLOPT_URL, $this->url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->request);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, $this->isReturnable);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl,CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($this->body));
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace app\external_requests;
use app\exceptions\InvalidCurlStructureException;
class CurlRequestBuilder extends CurlRequest
{
private ?string $url = NULL;
private ?string $request = NULL;
private ?array $headers = NULL;
private ?array $body = NULL;
private bool $isReturnable = false;
public function __construct(){}
public function setUrl(?string $url): void{$this->url = $url;}
public function setHeaders(?array $headers): void{$this->headers = $headers;}
public function setRequest(?string $request): void{$this->request = $request;}
public function setBody(?array $body): void{$this->body = $body;}
public function setIsReturnable(?bool $isReturnable): void{$this->isReturnable = $isReturnable;}
private function areMainParametersNotSet(): bool{
return $this->url == NULL || $this->request == NULL || $this->headers == NULL;
}
/**
* @throws InvalidCurlStructureException
*/
public function getCurlRequestObject(): CurlRequest{
if($this->areMainParametersNotSet()){
throw new InvalidCurlStructureException("Invalid structure for making a request");
}
return new CurlRequest($this->url, $this->request, $this->headers, $this->body, $this->isReturnable);
}
}
Regular → Executable
+7 -23
View File
@@ -5,37 +5,21 @@ use app\core\Application;
use app\controllers\SiteController;
require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/dbconfig.php';
/*
Clasa Application se va ocupa de stocarea asocierilor dintre o pagina si controller-ul corespunzator. Deoarece prin .htaccess am fortat
ca user ul sa ajunga mereu in acest 'index.php' la orice URL specificat, putem identifica din URL ce pagina vrea sa acceseze pentru a apela
un GET cu controller-ul, view ul si model ul corespunzator, ori printr-un submit sa se ajunga la metoda corespunzatoare de POST care sa intoarca
un raspuns valid.
*/
$app = new Application();
$app = new Application('.', $config);
$app->router->get('/', [SiteController::class, 'renderMainPage']);
$app->router->get('/homepage', [SiteController::class, 'homepage']);
$app->router->get('/', [SiteController::class, '/']);
$app->router->get('/login', [AuthController::class, 'loginPage']);
$app->router->post('/login', [AuthController::class, 'loginPage']);
$app->router->get('/home', [SiteController::class, 'home']);
$app->router->get('/_404', [SiteController::class, '_404']);
$app->router->get('/contact', [SiteController::class, 'contact']);
$app->router->post('/contact', [SiteController::class, 'contact']);
$app->router->get('/login', [AuthController::class, 'login']);
$app->router->post('/login', [AuthController::class, 'login']);
$app->router->get('/register', [AuthController::class, 'register']);
$app->router->post('/register', [AuthController::class, 'register']);
$app->router->get('/register', [AuthController::class, 'registerPage']);
$app->router->post('/register', [AuthController::class, 'registerPage']);
$app->router->get('/profile', [AuthController::class, 'profile']);
$app->router->post('/profile', [AuthController::class, 'profile']);
$app->router->get('/logout', [AuthController::class, 'logout']);
$app->router->get('/login/{id}', [SiteController::class, 'login']);
$app->run();
-10
View File
@@ -1,10 +0,0 @@
<?php
use app\core\Application;
require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/dbconfig.php';
$app = new Application('.', $config);
$app->db->applyMigrations();
-25
View File
@@ -1,25 +0,0 @@
<?php
use app\core\Application;
class m01_initial{
public function up(){
$db = Application::$app->db;
$SQL = "CREATE TABLE users(
id INT AUTO_INCREMENT,
email VARCHAR(255) NOT NULL,
firstname VARCHAR(255) NOT NULL,
lastname VARCHAR(255) NOT NULL,
status TINYINT NOT NULL,
create_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) Engine=INNODB;
";
$db->pdo->exec($SQL);
}
public function down(){
$db = Application::$app->db;
$SQL = "DROP TABLE users";
$db->pdo->exec($SQL);
}
}
@@ -1,17 +0,0 @@
<?php
use app\core\Application;
class m02_add_password_column{
public function up(){
$db = Application::$app->db;
$SQL = "ALTER TABLE users ADD COLUMN password VARCHAR(512) NOT NULL";
$db->pdo->exec($SQL);
}
public function down(){
$db = Application::$app->db;
$SQL = "ALTER TABLE users DROP COLUMN password";
$db->pdo->exec($SQL);
}
}
View File
-40
View File
@@ -1,40 +0,0 @@
<?php
namespace app\models;
use app\core\Application;
use app\core\Model;
class LoginForm extends Model{
public string $email = '';
public string $password = '';
public function rules(): array{
return [
'email' => [self::RULE_REQUIRED, self::RULE_EMAIL],
'password' => [self::RULE_REQUIRED]
];
}
public function labels():array {
return [
'email' => 'Email',
'password' => 'Password'
];
}
public function login(){
$user = new User();
$user = $user->findOne(['email' => $this->email]);
if(!$user){
$this->addError('email', 'User does not exist with this email');
return false;
}
if(!password_verify($this->password, $user->password)){
$this->addError('password', 'Incorrect password');
return false;
}
return Application::$app->login($user);
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
namespace app\models;
use app\core\Model;
class LoginModel extends Model{
public string $email = '';
public string $password = '';
public function rules(): array
{
return [
'email' => [self::RULE_REQUIRED, self::RULE_EMAIL],
'password' => [self::RULE_REQUIRED]
];
}
public function labels():array
{
return [
'email' => 'Email',
'password' => 'Password'
];
}
public function createBody(): array
{
$body = array();
$body["values"] = [
"email" => $this->email,
"password" => $this->password
];
return $body;
}
public function createHeaders(string $body): array
{
$headers = array();
$headers["Content-type"] = "application/json";
$headers["Content-Length"] = strlen($body);
$headers["Authorization"] = hash('md5', 'api.knowyourfood');
$headers["Auth-Request"] = "login";
return $this->formatHeaderArray($headers);
}
protected function formatHeaderArray(array $headers): array{
$array = array();
foreach ($headers as $key => $value){
$array[] = $key . ": " . $value;
}
return $array;
}
}
+59
View File
@@ -0,0 +1,59 @@
<?php
namespace app\models;
use app\core\Model;
class RegisterModel extends Model{
public string $username = '';
public string $email = '';
public string $password = '';
public function rules(): array{
return [
'username' => [self::RULE_REQUIRED],
'email' => [self::RULE_REQUIRED, self::RULE_EMAIL],
'password' => [self::RULE_REQUIRED]
];
}
public function labels():array {
return [
'username' => 'Username',
'email' => 'Email',
'password' => 'Password',
];
}
public function createBody(): array
{
$body = array();
$body["values"] = [
"username" => $this->username,
"email" => $this->email,
"password" => $this->password
];
return $body;
}
public function createHeaders(string $body): array
{
$headers = array();
$headers["Content-type"] = "application/json";
$headers["Content-Length"] = strlen($body);
$headers["Authorization"] = hash('md5', 'api.knowyourfood');
$headers["Auth-Request"] = "register";
return $this->formatHeaderArray($headers);
}
protected function formatHeaderArray(array $headers): array{
$array = array();
foreach ($headers as $key => $value){
$array[] = $key . ": " . $value;
}
return $array;
}
}
-53
View File
@@ -1,53 +0,0 @@
<?php
namespace app\models;
use app\core\DbModel;
class User extends DbModel{
const STATUS_INACTIVE = 0;
const STATUS_ACTIVE = 1;
CONST STATUS_DELETED = 2;
public string $firstname = '';
public string $lastname = '';
public int $status = self::STATUS_INACTIVE;
public string $email = '';
public string $password = '';
public function save(){
$this->status = self::STATUS_INACTIVE;
$this->password = password_hash($this->password, PASSWORD_DEFAULT);
return parent::save();
}
public function tableName(): string{
return 'users';
}
public function rules(): array{
return [
'firstname' => [self::RULE_REQUIRED],
'lastname' => [self::RULE_REQUIRED],
'email' => [self::RULE_REQUIRED, self::RULE_EMAIL, [self::RULE_UNIQUE, 'class' => self::class]],
'password' => [self::RULE_REQUIRED, [self::RULE_MIN, 'min' => 8], [self::RULE_MAX, 'max' => 15]]
];
}
public function primaryKey(): string{
return 'id';
}
public function labels():array {
return [
'firstname' => 'First name',
'lastname' => 'Last name',
'email' => 'Email',
'password' => 'Password'
];
}
public function attributes(): array{
return ['firstname', 'lastname', 'email', 'password', 'status'];
}
}
Regular → Executable
View File
+28
View File
@@ -0,0 +1,28 @@
<?php
use app\core\Application;
use app\core\form\Form;
$form = new Form('login');
$model = Application::$app->view->getModel();
$loginError = Application::$app->view->getActionError();
if(!$loginError == ''){
echo "<p class='errorStyle'>$loginError</p>";
}
echo '<hr class="hr1">';
$form->beginForm();
foreach($model->labels() as $key=>$value){
$form->renderInputField(
$key, $key, $value, $model->getValueForField($key), $model->getError($key)
);
}
echo '<hr class="hr1">';
$form->renderButton();
$form->endForm();
+28
View File
@@ -0,0 +1,28 @@
<?php
use app\core\Application;
use app\core\form\Form;
$form = new Form('register');
$model = Application::$app->view->getModel();
$loginError = Application::$app->view->getActionError();
if(!$loginError == ''){
echo "<p class='errorStyle'>$loginError</p>";
}
echo '<hr class="hr1">';
$form->beginForm();
foreach($model->labels() as $key=>$value){
$form->renderInputField(
$key, $key, $value, $model->getValueForField($key), $model->getError($key)
);
}
echo '<hr class="hr1">';
$form->renderButton();
$form->endForm();
-1
View File
@@ -1 +0,0 @@
<h1><?php echo $exception->getCode() ?> - <?php echo $exception->getMessage();?> </h1>
-12
View File
@@ -1,12 +0,0 @@
<?php
use app\core\form\Form;
use app\core\form\TextareaField;
$this->title = 'Contact';
$form = Form::begin('', 'post');
echo $form->inputField($model, 'subject');
echo new TextareaField($model, 'body');
echo $form->button();
Form::end();
?>
-6
View File
@@ -1,6 +0,0 @@
<?php
$this->title = 'Home';
?>
<h1>Home</h1>
<h2> Welcome <?php echo $name;?> to our site!</h2>
+148
View File
@@ -0,0 +1,148 @@
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Josefin Sans', sans-serif;
}
html,
body{
height: 100%;
}
body{
background-image: url("../Images/background/background.jpg");
background-size: cover;
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
}
body{
display: flex;
flex-direction: column;
justify-content: space-evenly;
align-items: center;
}
h1{
color: white;
text-shadow:
-1px -1px 0 #000,
0 -1px 0 #000,
1px -1px 0 #000,
1px 0 0 #000,
1px 1px 0 #000,
0 1px 0 #000,
-1px 1px 0 #000,
-1px 0 0 #000;
}
.hr1{
width: 70%;
}
.Title{
margin: 3vh;
margin-top: 0;
font-size: 3rem;
}
input, button{
margin: 1rem;
margin-left: 0;
margin-right: 0;
background-color: #60FF8C;
border: 0.1em solid black;
border-radius: 20px;
padding: 1vh;
padding-left: 5vh;
padding-right: 5vh;
min-width: 100%;
cursor: default;
}
button{
background-color: #FF5555
}
button:hover{
background-color: #FF2B2B;
cursor: pointer;
}
.Inputs{
display: flex;
flex-direction: column;
}
.Inputs > *, button{
padding: 1rem;
}
input[type="radio"]{
margin:0;
}
input:focus{
outline: none;
}
.LoginButtons{
width: 70%;
}
.LoginForm{
display: flex;
flex-direction: column;
justify-content: center;
width: 100%;
}
.errorStyle{
text-align: center;
color: white;
}
.LoginButtons hr{
width:100%;
}
.BigContainer{
background-color: rgba(0, 0, 0, 0.5);
border-radius: 20px;
position: fixed;
display: flex;
flex-direction: column;
align-items: center;
padding: 2rem;
transform: scale(1);
flex: 100%;
width:50%;
}
@media screen and (max-width: 800px){
*{
overflow: hidden;
}
.BigContainer{
margin-top: 5vh;
margin-bottom: 5vh;
min-width: 70%;
transform: scale(1);
}
.Inputs > *{
width: 100%;
}
h1{
font-size: 1rem;
text-align: center;
}
.LoginButtons{
width:100%;
}
.hr1{
width:100%;
}
}
+100
View File
@@ -0,0 +1,100 @@
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Josefin Sans', sans-serif;
}
html,
body {
height: 100%;
}
body {
background-image: url("../Images/background/background.jpg");
background-size: cover;
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
}
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
h1, h3 {
color: white;
text-shadow: -1px -1px 0 #000, 0 -1px 0 #000, 1px -1px 0 #000, 1px 0 0 #000, 1px 1px 0 #000, 0 1px 0 #000, -1px 1px 0 #000, -1px 0 0 #000;
}
.Title {
margin: 5vh;
font-size: 3rem;
}
button {
margin: 1rem;
background-color: #60FF8C;
border: 0.1em solid black;
border-radius: 20px;
padding: 1vh;
padding-left: 5vh;
padding-right: 5vh;
max-width: 100%;
cursor: default;
width: 100%;
}
button:hover {
margin: 1rem;
background-color: #FF5555;
border: 0.1em solid black;
border-radius: 20px;
padding: 1vh;
padding-left: 5vh;
padding-right: 5vh;
max-width: 100%;
cursor: pointer;
width: 100%;
}
.RegisterButton {
margin-bottom: 0;
}
.RegisterButton:hover {
margin-bottom: 0;
cursor: pointer;
}
.LoginButtons {
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 0;
margin-top: 0;
}
.BigContainer {
position: fixed;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
transform: scale(1.5);
flex: 100%;
}
@media screen and (max-width: 888px) {
.BigContainer {
width: 30%;
}
h1, h3 {
font-size: 1rem;
text-align: center;
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
use app\core\Application;
$pathToCSS = "/views/layouts/CSS/styleAuth.css";
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href=<?php echo $pathToCSS ?> />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Josefin+Sans&display=swap" rel="stylesheet">
<title><?php echo Application::$app->view->getTitle()?></title>
</head>
<body>
<div class="BigContainer">
<h1 class="Title"><?php echo Application::$app->view->getTitle()?></h1>
<div class="LoginForm">
{{content}}
</div>
</div>
</body>
</html>
+28
View File
@@ -0,0 +1,28 @@
<?php $pathToCSS = "/views/layouts/CSS/styleMain.css";?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1">
<link rel="stylesheet" type="text/css" href=<?php echo $pathToCSS ?>>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Josefin+Sans&display=swap" rel="stylesheet">
<title>Know Your Food.</title>
</head>
<body>
<div class="BigContainer">
<h1 class="Title">Know Your Food.</h1>
<div class="LoginButtons">
<h3>If you have an account already</h3>
<button type="button" class="LoginButton" onclick="location.href='login'">Login</button>
<h3>or</h3>
<button type="button" class="RegisterButton" onclick="location.href='register'">Register</button>
</div>
</div>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 417 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 312 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More