|
- <?php
-
- declare(strict_types=1);
-
- namespace App\Repositories;
-
- use App\Models\Employee;
- use Core\Repository;
-
- class EmployeeRepository extends Repository
- {
- protected string $table = 'employees';
- protected string $primaryKey = 'id';
-
- public function create(Employee $employee): bool
- {
- return $this->database->execute(
- 'INSERT INTO employees (first_name, last_name, email, department, job_title, start_date)
- VALUES (:first_name, :last_name, :email, :department, :job_title, :start_date)',
- [
- 'first_name' => $employee->firstName,
- 'last_name' => $employee->lastName,
- 'email' => $employee->email,
- 'department' => $employee->department,
- 'job_title' => $employee->jobTitle,
- 'start_date' => $employee->startDate,
- ]
- );
- }
-
- public function findByEmail(string $email): ?array
- {
- return $this->database->first(
- 'SELECT * FROM employees WHERE email = :email',
- ['email' => $email]
- );
- }
-
- /**
- * @return list<array<string, mixed>>
- */
- public function latest(int $limit = 8): array
- {
- $limit = max(1, $limit);
-
- return $this->database->query(
- "SELECT * FROM employees ORDER BY created_at DESC, id DESC LIMIT {$limit}"
- );
- }
-
- /**
- * @return list<array<string, mixed>>
- */
- public function search(string $search = ''): array
- {
- [$whereClause, $parameters] = $this->buildSearchClause($search);
-
- return $this->database->query(
- 'SELECT id, first_name, last_name, email, department, job_title, start_date, created_at
- FROM employees' . $whereClause . '
- ORDER BY created_at DESC, id DESC',
- $parameters
- );
- }
-
- public function countMatching(string $search = ''): int
- {
- [$whereClause, $parameters] = $this->buildSearchClause($search);
- $row = $this->database->first(
- 'SELECT COUNT(*) AS total FROM employees' . $whereClause,
- $parameters
- );
-
- return (int) ($row['total'] ?? 0);
- }
-
- public function countDepartments(string $search = ''): int
- {
- [$whereClause, $parameters] = $this->buildSearchClause($search);
- $row = $this->database->first(
- 'SELECT COUNT(DISTINCT department) AS total FROM employees' . $whereClause,
- $parameters
- );
-
- return (int) ($row['total'] ?? 0);
- }
-
- public function newestMatching(string $search = ''): ?array
- {
- [$whereClause, $parameters] = $this->buildSearchClause($search);
-
- return $this->database->first(
- 'SELECT id, first_name, last_name, department, job_title, start_date
- FROM employees' . $whereClause . '
- ORDER BY created_at DESC, id DESC
- LIMIT 1',
- $parameters
- );
- }
-
- /**
- * @return array{0:string,1:array<string,string>}
- */
- private function buildSearchClause(string $search): array
- {
- $search = trim($search);
-
- if ($search === '') {
- return ['', []];
- }
-
- return [
- ' WHERE first_name LIKE :search
- OR last_name LIKE :search
- OR email LIKE :search
- OR department LIKE :search
- OR job_title LIKE :search
- OR start_date LIKE :search',
- ['search' => '%' . $search . '%'],
- ];
- }
- }
|