Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Creditsuite\Services\GlobalDataService;
- use App\Creditsuite\Domain\Models\FieldType;
- use App\Creditsuite\Domain\Models\Identity;
- use Exception;
- use Throwable;
- /**
- * Class FieldService
- * @package App\Creditsuite\Services\GlobalDataService
- */
- class FieldService
- {
- /**
- * @var string
- */
- protected $fieldSlug;
- /**
- * @var integer
- */
- protected $fieldId;
- /**
- * @var array
- */
- protected $identities;
- /**
- * @param $fieldSlug
- * @return $this
- */
- public function setFieldSlug($fieldSlug)
- {
- $this->fieldSlug = $fieldSlug;
- return $this;
- }
- /**
- * @param $fieldId
- * @return $this
- */
- public function setFieldId($fieldId)
- {
- $this->fieldId = $fieldId;
- return $this;
- }
- /**
- * @param $identities
- * @return $this
- */
- public function setIdentities($identities)
- {
- $this->identities = $identities;
- return $this;
- }
- /**
- * @throws Exception
- */
- protected function checkFieldId()
- {
- if($this->fieldId) {
- return;
- }
- try {
- $this->fieldId = FieldType::where('slug', $this->fieldSlug)->firstOrFail()
- ->id;
- } catch (Throwable $exception) {
- throw new Exception('FieldService incoming parameters are invalid: fieldType not found');
- }
- }
- /**
- * @throws Exception
- */
- public function validate()
- {
- $this->checkFieldId();
- if(!$this->fieldId || !is_array($this->identities)) {
- throw new Exception('FieldService incoming parameters are invalid');
- }
- }
- /**
- * @param array $identityKeys
- * @param string $fieldSlug
- * @return mixed
- * @throws Exception
- */
- public function versions()
- {
- $this->validate();
- $identities = Identity::whereIn('key', $this->identities)
- ->with([
- 'fields' => function($query) {
- $query
- ->where('field_type_id', $this->fieldId);
- },
- ])
- ->get();
- $fields = $identities->map(function($item) {
- return $item->fields;
- })->collapse()->unique('id')->sortByDesc('updated_at')->values();
- return $fields;
- }
- /**
- * @return null
- * @throws Exception
- */
- public function first()
- {
- $versions = $this->versions();
- return $versions->isNotEmpty() ? $versions->first() : null;
- }
- /**
- * @return null
- * @throws Exception
- */
- public function last()
- {
- $versions = $this->versions();
- return $versions->isNotEmpty() ? $versions->last() : null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement