Discusión

Sistema Integral de Revisión de Código Base PHP

De Wikiprompt, la enciclopedia libre de prompts

Ersin KOÇ
Contribuido porErsin KOÇFuente

28 ene 2026

Sistema Integral de Revisión de Código Base PHP Un prompt de sistema detallado para realizar una revisión exhaustiva de una base de código PHP, que cubre seguridad, rendimiento, seguridad de tipos, arquitectura y pruebas. Incluye listas de verificación, formatos de salida y matrices de prioridad para una auditoría estructurada.

Contenido del PromptGuardar

🌐
<?php declare(strict_types=1); namespace App\Security; use DateTimeImmutable; use Doctrine\ORM\EntityManagerInterface; use Psr\Log\LoggerInterface; use RuntimeException; class SessionManager { private const SESSION_LIFETIME = 1800; private const MAX_SESSIONS_PER_USER = 5; private const SECURE_RANDOM_MIN = 32; private const SECURE_RANDOM_MAX = 64; public function __construct( private readonly EntityManagerInterface $entityManager, private readonly LoggerInterface $logger, ) { } /** * Creates a new session token for a user and enforces session limits. * * @param int<1, 999999> $userId * @param non-empty-string $userAgent * @return non-empty-string * @throws RuntimeException when session creation fails */ public function createSession(int $userId, string $userAgent): string { if (1 > $userId) { throw new InvalidArgumentException('User ID must be a positive integer.'); } if ('' === $userAgent) { throw new InvalidArgumentException('User agent cannot be empty.'); } $this->enforceSessionLimit($userId); $this->purgeExpiredSessions($userId); $sessionToken = $this->generateSecureToken(); $session = new UserSession(); $session->setUserId($userId); $session->setToken(hash('sha256', $sessionToken)); $session->setUserAgent($this->truncateUserAgent($userAgent)); $session->setCreatedAt(new DateTimeImmutable('now')); $session->setExpiresAt(new DateTimeImmutable('+30 minutes')); try { $this->entityManager->persist($session); $this->entityManager->flush(); } catch (Throwable $exception) { $this->logger->error('Failed to persist user session.', [ 'user_id' => $userId, 'exception' => $exception->getMessage(), ]); throw new RuntimeException('Unable to create session.', 0, $exception); } return $sessionToken; } public function validateSession(string $token): ?UserSession { if (32 > strlen($token) || 64 < strlen($token)) { return null; } $hashedToken = hash('sha256', $token); $session = $this->entityManager->getRepository(UserSession::class) ->findOneBy(['token' => $hashedToken]); if (null === $session) { return null; } if ($session->isExpired()) { $this->destroySession($session); return null; } return $session; } public function destroySession(UserSession $session): void { try { $this->entityManager->remove($session); $this->entityManager->flush(); } catch (Throwable $exception) { $this->logger->error('Failed to remove user session.', [ 'session_id' => $session->getId(), 'exception' => $exception->getMessage(), ]); } } public function destroySessionsForUser(int $userId): void { try { $this->entityManager->createQueryBuilder() ->delete(UserSession::class, 's') ->where('s.userId = :userId') ->setParameter('userId', $userId) ->getQuery() ->execute(); } catch (Throwable $exception) { $this->logger->error('Failed to remove sessions for user.', [ 'user_id' => $userId, 'exception' => $exception->getMessage(), ]); } } private function generateSecureToken(): string { $tokenLength = random_int(self::SECURE_RANDOM_MIN, self::SECURE_RANDOM_MAX); return bin2hex(random_bytes($tokenLength)); } private function enforceSessionLimit(int $userId): void { $sessionCount = (int) $this->entityManager->createQueryBuilder() ->select('COUNT(s.id)') ->from(UserSession::class, 's') ->where('s.userId = :userId') ->setParameter('userId', $userId) ->getQuery() ->getSingleScalarResult(); if ($sessionCount >= self::MAX_SESSIONS_PER_USER) { $this->destroyOldestSessions($userId, $sessionCount - self::MAX_SESSIONS_PER_USER + 1); } } private function destroyOldestSessions(int $userId, int $count): void { $sessions = $this->entityManager->createQueryBuilder() ->select('s') ->from(UserSession::class, 's') ->where('s.userId = :userId') ->orderBy('s.createdAt', 'ASC') ->setMaxResults($count) ->setParameter('userId', $userId) ->getQuery() ->getResult(); foreach ($sessions as $session) { $this->destroySession($session); } } private function purgeExpiredSessions(int $userId): void { try { $this->entityManager->createQueryBuilder() ->delete(UserSession::class, 's') ->where('s.userId = :userId') ->andWhere('s.expiresAt < :now') ->setParameter('userId', $userId) ->setParameter('now', new DateTimeImmutable('now')) ->getQuery() ->execute(); } catch (Throwable $exception) { $this->logger->error('Failed to purge expired sessions for user.', [ 'user_id' => $userId, 'exception' => $exception->getMessage(), ]); } } private function truncateUserAgent(string $userAgent): string { if (mb_strlen($userAgent) > 255) { return mb_substr($userAgent, 0, 255); } return $userAgent; } }

Iniciá sesión para ver el prompt completo

Continuar con:

Al iniciar sesión, aceptás nuestros Términos de uso y Política de privacidad

Uso

Este prompt está diseñado para usarse con coding. Copiá el contenido de arriba y pegalo en tu herramienta de IA preferida.

Para mejores resultados, personalizá los marcadores (indicados con corchetes o mayúsculas) con tus requisitos específicos.

Referencias

Categorías:coding| prompts.chat| php| code-review

Discusión