| Server IP : 65.108.144.40 / Your IP : 216.73.217.165 Web Server : Apache/2.4.52 (Ubuntu) System : Linux ubuntu-8gb-hel1-1 5.15.0-173-generic #183-Ubuntu SMP Fri Mar 6 13:29:34 UTC 2026 x86_64 User : dev ( 1000) PHP Version : 8.2.30 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : ON | Pkexec : ON Directory : /var/www/html/project-slim/app/Services/ |
Upload File : |
<?php
namespace App\Services;
use App\Models\User;
use App\Models\Role;
use App\Repositories\Interfaces\UserRepositoryInterface;
use App\Validators\UserValidator;
use App\Exceptions\ValidationException;
use App\Exceptions\UnauthorizedException;
use Illuminate\Pagination\LengthAwarePaginator;
class UserService
{
private UserRepositoryInterface $userRepository;
private UserValidator $validator;
public function __construct(UserRepositoryInterface $userRepository, UserValidator $validator)
{
$this->userRepository = $userRepository;
$this->validator = $validator;
}
/**
* Get user by ID
*/
public function getUserById(int $id): ?User
{
return $this->userRepository->findById($id);
}
/**
* Get user by email
*/
public function getUserByEmail(string $email): ?User
{
return $this->userRepository->findByEmail($email);
}
/**
* Create a new user
*/
public function createUser(array $data): User
{
// Validate input data
$validation = $this->validator->validateCreate($data);
if (!$validation->isValid()) {
throw new ValidationException('Validation failed', $validation->getErrors());
}
// Hash password
if (isset($data['password'])) {
$data['password_hash'] = password_hash($data['password'], PASSWORD_DEFAULT);
unset($data['password']);
}
return $this->userRepository->create($data);
}
/**
* Update user
*/
public function updateUser(int $id, array $data): ?User
{
$user = $this->userRepository->findById($id);
if (!$user) {
return null;
}
// Validate input data
$validation = $this->validator->validateUpdate($data, $id);
if (!$validation->isValid()) {
throw new ValidationException('Validation failed', $validation->getErrors());
}
// Hash password if provided
if (isset($data['password'])) {
$data['password_hash'] = password_hash($data['password'], PASSWORD_DEFAULT);
unset($data['password']);
}
return $this->userRepository->update($id, $data);
}
/**
* Delete user
*/
public function deleteUser(int $id): bool
{
return $this->userRepository->delete($id);
}
/**
* Get paginated users
*/
public function getUsers(int $page = 1, int $limit = 20, array $filters = []): LengthAwarePaginator
{
return $this->userRepository->getAll($page, $limit, $filters);
}
/**
* Search users
*/
public function searchUsers(string $term, int $page = 1, int $limit = 20): LengthAwarePaginator
{
return $this->userRepository->search($term, $page, $limit);
}
/**
* Get users by company
*/
public function getUsersByCompany(int $companyId, int $page = 1, int $limit = 20): LengthAwarePaginator
{
return $this->userRepository->getByCompany($companyId, $page, $limit);
}
/**
* Activate user
*/
public function activateUser(int $id): bool
{
return $this->userRepository->activate($id);
}
/**
* Deactivate user
*/
public function deactivateUser(int $id): bool
{
return $this->userRepository->deactivate($id);
}
/**
* Verify user email
*/
public function verifyUser(int $id): bool
{
return $this->userRepository->verify($id);
}
/**
* Update user password (simplified version for admin)
*/
public function updatePassword(int $id, string $newPassword): bool
{
// Validate new password
$validation = $this->validator->validatePassword(['password' => $newPassword]);
if (!$validation->isValid()) {
throw new ValidationException('Password validation failed', $validation->getErrors());
}
$newPasswordHash = password_hash($newPassword, PASSWORD_DEFAULT);
return $this->userRepository->updatePassword($id, $newPasswordHash);
}
/**
* Update user password with current password verification
*/
public function updatePasswordSecure(int $id, string $currentPassword, string $newPassword): bool
{
$user = $this->userRepository->findById($id);
if (!$user) {
return false;
}
// Verify current password
if (!password_verify($currentPassword, $user->password_hash)) {
throw new UnauthorizedException('Current password is incorrect');
}
// Validate new password
$validation = $this->validator->validatePassword(['password' => $newPassword]);
if (!$validation->isValid()) {
throw new ValidationException('Password validation failed', $validation->getErrors());
}
$newPasswordHash = password_hash($newPassword, PASSWORD_DEFAULT);
return $this->userRepository->updatePassword($id, $newPasswordHash);
}
/**
* Reset user password (admin only)
*/
public function resetPassword(int $id, string $newPassword): bool
{
// Validate new password
$validation = $this->validator->validatePassword(['password' => $newPassword]);
if (!$validation->isValid()) {
throw new ValidationException('Password validation failed', $validation->getErrors());
}
$newPasswordHash = password_hash($newPassword, PASSWORD_DEFAULT);
return $this->userRepository->updatePassword($id, $newPasswordHash);
}
/**
* Assign role to user
*/
public function assignRole(int $userId, string $roleName): bool
{
// Validate role exists
$role = Role::where('role_name', $roleName)->first();
if (!$role) {
throw new ValidationException('Invalid role specified', ['role' => 'Invalid role specified']);
}
return $this->userRepository->assignRole($userId, $roleName);
}
/**
* Remove role from user
*/
public function removeRole(int $userId, string $roleName): bool
{
return $this->userRepository->removeRole($userId, $roleName);
}
/**
* Check if user has permission for a module
*/
public function hasPermission(int $userId, string $moduleName): bool
{
$user = $this->userRepository->findById($userId);
if (!$user) {
return false;
}
return $user->hasModulePermission($moduleName);
}
/**
* Get user permissions
*/
public function getUserPermissions(int $userId): array
{
$user = $this->userRepository->findById($userId);
if (!$user) {
return [];
}
return $user->getAccessibleModules();
}
/**
* Bulk activate users
*/
public function bulkActivate(array $userIds): int
{
return $this->userRepository->bulkActivate($userIds);
}
/**
* Bulk deactivate users
*/
public function bulkDeactivate(array $userIds): int
{
return $this->userRepository->bulkDeactivate($userIds);
}
/**
* Bulk delete users
*/
public function bulkDelete(array $userIds): int
{
return $this->userRepository->bulkDelete($userIds);
}
/**
* Get user statistics
*/
public function getStatistics(): array
{
return $this->userRepository->getStatistics();
}
/**
* Update user profile
*/
public function updateProfile(int $userId, array $data): ?User
{
// Only allow profile fields
$allowedFields = ['first_name', 'last_name'];
$profileData = array_intersect_key($data, array_flip($allowedFields));
if (empty($profileData)) {
return $this->userRepository->findById($userId);
}
return $this->userRepository->update($userId, $profileData);
}
/**
* Update user profile by email
*/
public function updateProfileByEmail(string $email, array $data): ?User
{
$user = $this->userRepository->findByEmail($email);
if (!$user) {
return null;
}
// Only allow profile fields
$allowedFields = ['first_name', 'last_name'];
$profileData = array_intersect_key($data, array_flip($allowedFields));
if (empty($profileData)) {
return $user;
}
return $this->userRepository->update($user->id, $profileData);
}
/**
* Set user flag
*/
public function setUserFlag(int $userId, string $flagKey, bool $value): bool
{
$user = $this->userRepository->findById($userId);
if (!$user) {
return false;
}
$user->setFlag($flagKey, $value);
return true;
}
/**
* Get user flag
*/
public function getUserFlag(int $userId, string $flagKey): bool
{
$user = $this->userRepository->findById($userId);
if (!$user) {
return false;
}
return $user->getFlagValue($flagKey);
}
}