Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions src/Controller/ApiController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?php

namespace App\Controller;

use App\Service\CacheService;
use App\Service\ValidationService;

class ApiController
{
private $cache;
private $validator;
private $rateLimits = [];

public function __construct()
{
$this->cache = new CacheService(1800);
$this->validator = new ValidationService();
}

public function handleRequest($method, $path, $data = [])
{
if (!$this->checkRateLimit($path)) {
return ['status' => 429,'body' => ['error' => 'Too many requests']];
}

switch ($method) {
case 'GET':
return $this->handleGet($path, $data);
case 'POST':
return $this->handlePost($path, $data);
case 'PUT':
return $this->handlePut($path, $data);
case 'DELETE':
return $this->handleDelete($path, $data);
default:
return ['status' => 405,'body' => ['error' => 'Method not allowed']];
}
}

private function handleGet($path, $params)
{
$cacheKey = 'get_'.md5($path.serialize($params));
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use of insecure md5() function found


Using md5(), sha1() function is not recommended to generate secure passwords. Due to its fast nature to compute passwords too quickly, these functions can become really easy to crack a password using brute force attack.

It is recommended to use PHP's password hashing function password_hash() to create a secure password hash.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use of insecure md5() function found


Using md5(), sha1() function is not recommended to generate secure passwords. Due to its fast nature to compute passwords too quickly, these functions can become really easy to crack a password using brute force attack.

It is recommended to use PHP's password hashing function password_hash() to create a secure password hash.

$cached = $this->cache->get($cacheKey);
if ($cached !== null) {
return ['status' => 200,'body' => $cached,'cached' => true];
}

$result = ['data' => [],'meta' => ['path' => $path,'params' => $params,'timestamp' => time()]];
$this->cache->set($cacheKey, $result);
return ['status' => 200,'body' => $result,'cached' => false];
}

private function handlePost($path, $data)
{
$rules = ['name' => 'required|min:2|max:100','email' => 'required|email','age' => 'numeric|min:0|max:150'];
if (!$this->validator->validate($data, $rules)) {
return ['status' => 422,'body' => ['errors' => $this->validator->getErrors()]];
}
return ['status' => 201,'body' => ['message' => 'Created','data' => $data]];
}

private function handlePut($path, $data)
{
if (empty($data)) {
return ['status' => 400,'body' => ['error' => 'No data provided']];
}
return ['status' => 200,'body' => ['message' => 'Updated','data' => $data]];
}

private function handleDelete($path, $data)
{
return ['status' => 200,'body' => ['message' => 'Deleted']];
}

private function checkRateLimit($path)
{
$now = time();
$window = 60;
$maxRequests = 100;

if (!isset($this->rateLimits[$path])) {
$this->rateLimits[$path] = [];
}

$this->rateLimits[$path] = array_filter($this->rateLimits[$path], function ($timestamp) use ($now, $window) {
return($now - $timestamp) < $window;
});

if (count($this->rateLimits[$path]) >= $maxRequests) {
return false;
}

$this->rateLimits[$path][] = $now;
return true;
}
}
79 changes: 79 additions & 0 deletions src/Repository/EventRepository.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

namespace App\Repository;

class EventRepository
{
private $events = [];
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The private property $events is not used


The class contains unused private property. These private class properties should be removed as they can sometimes lead to confusion while reading the code.

It is also recommended that you review these unused private properties, in case they were added for later use in the code, but the author missed using them.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The private property $events is not used


The class contains unused private property. These private class properties should be removed as they can sometimes lead to confusion while reading the code.

It is also recommended that you review these unused private properties, in case they were added for later use in the code, but the author missed using them.

private $listeners = [];
private $history = [];
private $maxHistory = 500;

public function subscribe($eventName, $callback, $priority = 0)
{
if (!isset($this->listeners[$eventName])) {
$this->listeners[$eventName] = [];
}
$this->listeners[$eventName][] = ['callback' => $callback,'priority' => $priority];
usort($this->listeners[$eventName], function ($a, $b) {
return $b['priority'] - $a['priority'];
});
}

public function dispatch($eventName, $payload = [])
{
$event = ['name' => $eventName,'payload' => $payload,'timestamp' => microtime(true),'stopped' => false];
$this->history[] = $event;
if (count($this->history) > $this->maxHistory) {
array_shift($this->history);
}

if (!isset($this->listeners[$eventName])) {
return $event;
}

foreach ($this->listeners[$eventName] as $listener) {
if ($event['stopped']) {
break;
}
$result = call_user_func($listener['callback'], $event);
if ($result === false) {
$event['stopped'] = true;
}
}
return $event;
}

public function getHistory($eventName = null, $limit = 10)
{
if ($eventName === null) {
return array_slice($this->history, -$limit);
}
$filtered = array_filter($this->history, function ($e) use ($eventName) {
return $e['name'] === $eventName;
});
return array_slice($filtered, -$limit);
}

public function removeListeners($eventName)
{
unset($this->listeners[$eventName]);
}

public function getListenerCount($eventName = null)
{
if ($eventName !== null) {
return isset($this->listeners[$eventName]) ? count($this->listeners[$eventName]) : 0;
}
$total = 0;
foreach ($this->listeners as $listeners) {
$total += count($listeners);
}
return $total;
}

public function clearHistory()
{
$this->history = [];
}
}
79 changes: 79 additions & 0 deletions src/Service/CacheService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

namespace App\Service;

class CacheService
{
private $store = [];
private $ttl;
private $hits = 0;
private $misses = 0;

public function __construct($ttl = 3600)
{
$this->ttl = $ttl;
}

public function get($key)
{
if (isset($this->store[$key])) {
$entry = $this->store[$key];
if (time() - $entry['created_at'] < $this->ttl) {
$this->hits++;
return $entry['value'];
} else {
unset($this->store[$key]);
}
}
$this->misses++;
return null;
}

public function set($key, $value)
{
$this->store[$key] = ['value' => $value,'created_at' => time()];
}

public function delete($key)
{
if (isset($this->store[$key])) {
unset($this->store[$key]);
return true;
}
return false;
}

public function clear()
{
$this->store = [];
$this->hits = 0;
$this->misses = 0;
}

public function getStats()
{
$total = $this->hits + $this->misses;
return ['hits' => $this->hits,'misses' => $this->misses,'total' => $total,'hit_rate' => $total > 0 ? round($this->hits / $total * 100, 2) : 0,'size' => count($this->store)];
}

public function has($key)
{
return isset($this->store[$key]) && (time() - $this->store[$key]['created_at'] < $this->ttl);
}

public function getMultiple($keys)
{
$results = [];
foreach ($keys as $key) {
$results[$key] = $this->get($key);
}
return $results;
}

public function setMultiple($items)
{
foreach ($items as $key => $value) {
$this->set($key, $value);
}
}
}
86 changes: 86 additions & 0 deletions src/Service/LoggerService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?php

namespace App\Service;

class LoggerService
{
private $logFile;
private $minLevel;
private $buffer = [];
private $bufferSize = 50;
public const LEVELS = ['debug' => 0,'info' => 1,'warning' => 2,'error' => 3,'critical' => 4];

public function __construct($logFile = '/tmp/app.log', $minLevel = 'debug')
{
$this->logFile = $logFile;
$this->minLevel = $minLevel;
}

public function debug($message, $context = [])
{
$this->log('debug', $message, $context);
}
public function info($message, $context = [])
{
$this->log('info', $message, $context);
}
public function warning($message, $context = [])
{
$this->log('warning', $message, $context);
}
public function error($message, $context = [])
{
$this->log('error', $message, $context);
}
public function critical($message, $context = [])
{
$this->log('critical', $message, $context);
}

private function log($level, $message, $context = [])
{
if (self::LEVELS[$level] < self::LEVELS[$this->minLevel]) {
return;
}
$entry = [
'timestamp' => date('Y-m-d H:i:s'),
'level' => strtoupper($level),
'message' => $this->interpolate($message, $context),
'memory' => memory_get_usage(true),
'peak_memory' => memory_get_peak_usage(true),
];
$this->buffer[] = $entry;
if (count($this->buffer) >= $this->bufferSize) {
$this->flush();
}
}

private function interpolate($message, $context)
{
$replace = [];
foreach ($context as $key => $val) {
if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) {
$replace['{'.$key.'}'] = (string)$val;
}
}
return strtr($message, $replace);
}

public function flush()
{
if (empty($this->buffer)) {
return;
}
$lines = [];
foreach ($this->buffer as $entry) {
$lines[] = json_encode($entry);
}
file_put_contents($this->logFile, implode("\n", $lines)."\n", FILE_APPEND | LOCK_EX);
$this->buffer = [];
}

public function __destruct()
{
$this->flush();
}
}
Loading