Created
January 25, 2016 18:19
-
-
Save felipefrancisco/5779344255d688a7ae02 to your computer and use it in GitHub Desktop.
EmployeeService.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Created by PhpStorm. | |
* User: fx_om | |
* Date: 18/12/2015 | |
* Time: 16:14 | |
*/ | |
namespace App\Services; | |
use Validator; | |
class EmployeeService extends Service | |
{ | |
protected $employeeRepository; | |
protected $userService; | |
protected $clientService; | |
public function __construct( | |
\App\Repositories\EmployeeRepository $employeeRepository, | |
\App\Services\UserService $userService, | |
\App\Services\ClientService $clientService | |
) { | |
parent::__construct(); | |
$this->employeeRepository = $employeeRepository; | |
$this->userService = $userService; | |
$this->clientService = $clientService; | |
} | |
public function save($data) { | |
\DB::beginTransaction(); | |
try { | |
$employeeData = $data; | |
unset($employeeData['user']); | |
$validator = Validator::make( | |
$employeeData, | |
array( | |
'employee_type_id' => ['required', 'exists:employee_type,id'], | |
'distributor_id' => ['required', 'exists:distributor,id'] | |
) | |
); | |
if($validator->fails()) | |
$this->throwValidationException($this->request, $validator); | |
if(!empty($data['id'])) { | |
$original = $this->employeeRepository->firstOrFail($data['id']); | |
if($data['distributor_id'] != $original->distributor_id) | |
$this->detachFromTeams($data['id']); | |
} | |
$employee = $this->employeeRepository->save($data); | |
$userData = $data['user']; | |
$this->userService->save($employee, $userData); | |
\DB::commit(); | |
return $employee; | |
} | |
catch(\Exception $e) { | |
\DB::rollback(); | |
throw $e; | |
} | |
} | |
public function saveTeams($data) { | |
$validator = Validator::make( | |
$data, | |
array( | |
'id' => ['required'], | |
'teams' => ['required','arrayVal'] | |
) | |
); | |
if($validator->fails()) | |
$this->throwValidationException($this->request, $validator); | |
return $this->employeeRepository->saveTeams($data); | |
} | |
/** | |
* @param $id | |
* @return \Illuminate\Database\Eloquent\Builder | |
*/ | |
public function getClients($id) { | |
$query = $this->clientService->byEmployeeId($id); | |
return $query; | |
} | |
public function detachFromTeams($id) { | |
$employee = $this->employeeRepository->firstOrFail($id); | |
$employee->teams()->detach(); | |
return $employee; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment