Passed
Push — master ( 93b814...b98178 )
by Vinicius Lourenço
07:16
created
src/Scheduler/SchedulerServiceProvider.php 1 patch
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -12,50 +12,50 @@
 block discarded – undo
12 12
 
13 13
 class SchedulerServiceProvider extends ServiceProvider
14 14
 {
15
-    /**
16
-     * Perform post-registration booting of services.
17
-     *
18
-     * @return void
19
-     */
20
-    public function boot()
21
-    {
22
-        $this->publishes([
23
-            __DIR__.'/../config/config.php' => config_path('scheduler.php'),
24
-        ]);
25
-
26
-        $this->loadMigrationsFrom(__DIR__.'/Migrations');
27
-        $this->loadTranslationsFrom(__DIR__.'/Translations', 'scheduler');
28
-
29
-        $this->publishes([
30
-            __DIR__.'/Translations' => resource_path('lang/vendor/scheduler'),
31
-        ]);
32
-    }
33
-
34
-    /**
35
-     * Register the application services.
36
-     *
37
-     * @return void
38
-     */
39
-    public function register()
40
-    {
41
-        $this->app->singleton(Scheduler::class, function ($app) {
42
-            return new Scheduler($app);
43
-        });
44
-
45
-        $this->app->alias(Scheduler::class, 'scheduler');
46
-
47
-        $this->mergeConfig();
48
-    }
49
-
50
-    /**
51
-     * Mescla configurações do usuário com as configurações do Scheduler.
52
-     *
53
-     * @return void
54
-     */
55
-    private function mergeConfig()
56
-    {
57
-        $this->mergeConfigFrom(
58
-            __DIR__.'/../config/config.php', 'scheduler'
59
-        );
60
-    }
15
+	/**
16
+	 * Perform post-registration booting of services.
17
+	 *
18
+	 * @return void
19
+	 */
20
+	public function boot()
21
+	{
22
+		$this->publishes([
23
+			__DIR__.'/../config/config.php' => config_path('scheduler.php'),
24
+		]);
25
+
26
+		$this->loadMigrationsFrom(__DIR__.'/Migrations');
27
+		$this->loadTranslationsFrom(__DIR__.'/Translations', 'scheduler');
28
+
29
+		$this->publishes([
30
+			__DIR__.'/Translations' => resource_path('lang/vendor/scheduler'),
31
+		]);
32
+	}
33
+
34
+	/**
35
+	 * Register the application services.
36
+	 *
37
+	 * @return void
38
+	 */
39
+	public function register()
40
+	{
41
+		$this->app->singleton(Scheduler::class, function ($app) {
42
+			return new Scheduler($app);
43
+		});
44
+
45
+		$this->app->alias(Scheduler::class, 'scheduler');
46
+
47
+		$this->mergeConfig();
48
+	}
49
+
50
+	/**
51
+	 * Mescla configurações do usuário com as configurações do Scheduler.
52
+	 *
53
+	 * @return void
54
+	 */
55
+	private function mergeConfig()
56
+	{
57
+		$this->mergeConfigFrom(
58
+			__DIR__.'/../config/config.php', 'scheduler'
59
+		);
60
+	}
61 61
 }
62 62
\ No newline at end of file
Please login to merge, or discard this patch.
src/Scheduler/Models/ScheduleStatus.php 1 patch
Indentation   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -14,33 +14,33 @@
 block discarded – undo
14 14
 
15 15
 class ScheduleStatus extends Model
16 16
 {
17
-    use SoftDeletes;
17
+	use SoftDeletes;
18 18
 
19 19
 	/**
20
-     * Os atributos que podem ser atribuíveis em massa.
21
-     *
22
-     * @var array
23
-     */
24
-    protected $fillable = [
25
-    	'name', 'description'
26
-    ];
20
+	 * Os atributos que podem ser atribuíveis em massa.
21
+	 *
22
+	 * @var array
23
+	 */
24
+	protected $fillable = [
25
+		'name', 'description'
26
+	];
27 27
 
28
-    /**
29
-     * Os atributos que devem ser transformados para data.
30
-     *
31
-     * @var array
32
-     */
33
-    protected $dates = [
34
-    	'deleted_at'
35
-    ];
28
+	/**
29
+	 * Os atributos que devem ser transformados para data.
30
+	 *
31
+	 * @var array
32
+	 */
33
+	protected $dates = [
34
+		'deleted_at'
35
+	];
36 36
 
37
-    /**
38
-     * Construtor para inicilizar a váriavel table.
39
-     */
40
-    public function __construct(array $attributes = [])
41
-    {
42
-        parent::__construct($attributes);
37
+	/**
38
+	 * Construtor para inicilizar a váriavel table.
39
+	 */
40
+	public function __construct(array $attributes = [])
41
+	{
42
+		parent::__construct($attributes);
43 43
 
44
-        $this->table = Config::get('scheduler.schedule_status_table');
45
-    }
44
+		$this->table = Config::get('scheduler.schedule_status_table');
45
+	}
46 46
 }
47 47
\ No newline at end of file
Please login to merge, or discard this patch.
src/Scheduler/Facades/Scheduler.php 1 patch
Indentation   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -19,13 +19,13 @@
 block discarded – undo
19 19
  */
20 20
 class Scheduler extends Facade
21 21
 {
22
-    /**
23
-     * Get the registered name of the component.
24
-     *
25
-     * @return string
26
-     */
27
-    protected static function getFacadeAccessor()
28
-    {
29
-        return 'scheduler';
30
-    }
22
+	/**
23
+	 * Get the registered name of the component.
24
+	 *
25
+	 * @return string
26
+	 */
27
+	protected static function getFacadeAccessor()
28
+	{
29
+		return 'scheduler';
30
+	}
31 31
 }
32 32
\ No newline at end of file
Please login to merge, or discard this patch.
src/Scheduler/Exceptions/CustomException.php 1 patch
Indentation   +120 added lines, -120 removed lines patch added patch discarded remove patch
@@ -10,124 +10,124 @@
 block discarded – undo
10 10
 
11 11
 class CustomException extends \Exception
12 12
 {
13
-    /**
14
-     * Model que não pertence ao usuário
15
-     *
16
-     * @var mixed
17
-     */
18
-    protected $model;
19
-
20
-    /**
21
-     * Key para o arquivo de tradução de exceções.
22
-     *
23
-     * @var string
24
-     */
25
-    protected $trans;
26
-
27
-    /**
28
-     * HTTP Status Code
29
-     *
30
-     * @var int
31
-     */
32
-    protected $statusCode;
33
-
34
-    /**
35
-     * Atributo usado como key para substituir por um texto.
36
-     *
37
-     * @var array|string
38
-     */
39
-    protected $attributes = 'model';
40
-
41
-    /**
42
-     * Diz se o alias será no singular ou no plural.
43
-     *
44
-     * @var string
45
-     */
46
-    protected $aliastype = 'singular';
47
-
48
-    /**
49
-     * Valor passado para o atributo
50
-     *
51
-     * @var array|string|null
52
-     */
53
-    protected $values = null;
54
-
55
-    /**
56
-     * Indica se a model será printada com lower case.
57
-     *
58
-     * @var boolean
59
-     */
60
-    protected $lowercase = false;
61
-
62
-    /**
63
-     * Construtor da exceção
64
-     *
65
-     * @param mixed $model
66
-     */
67
-    public function __construct($model = 'foo')
68
-    {
69
-        $this->model = $model;
70
-    }
71
-
72
-    /**
73
-     * Render the exception as an HTTP response.
74
-     *
75
-     * @return \Illuminate\Http\JsonResponse
76
-     */
77
-    public function render()
78
-    {
79
-        return response()->
80
-            /** @scrutinizer ignore-call */
81
-            json([
82
-            'messages' => trans('scheduler::exceptions.'. $this->trans, $this->parseValues())
83
-        ], $this->statusCode);
84
-    }
85
-
86
-    /**
87
-     * Dá parse nos valores para a string de tradução.
88
-     *
89
-     * @return array
90
-     */
91
-    protected function parseValues()
92
-    {
93
-        if(is_array($this->attributes) && is_array($this->values))
94
-            return collect($this->attributes)->combine($this->values)->all();
95
-
96
-        return [ $this->attributes => $this->values ?? $this->isLower() ];
97
-    }
98
-
99
-    /**
100
-     * Verifica se é lowercase e retorna de acordo.
101
-     *
102
-     * @return string
103
-     */
104
-    protected function isLower()
105
-    {
106
-        return $this->lowercase ? strtolower($this->getAlias()) : $this->getAlias();
107
-    }
108
-
109
-    /**
110
-     * Retorna o alias da model.
111
-     *
112
-     * @return string
113
-     */
114
-    protected function getAlias()
115
-    {
116
-        if(is_object($this->model))
117
-            $this->model = get_class($this->model);
118
-
119
-        return collect(trans('scheduler::exceptions.aliases.'. $this->aliastype))->search($this->model) ?: 'Recurso';
120
-    }
121
-
122
-    /**
123
-     * Seta os valores.
124
-     *
125
-     * @param mixed $values
126
-     */
127
-    public function setValues($values)
128
-    {
129
-        $this->values = $values;
130
-
131
-        return $this;
132
-    }
13
+	/**
14
+	 * Model que não pertence ao usuário
15
+	 *
16
+	 * @var mixed
17
+	 */
18
+	protected $model;
19
+
20
+	/**
21
+	 * Key para o arquivo de tradução de exceções.
22
+	 *
23
+	 * @var string
24
+	 */
25
+	protected $trans;
26
+
27
+	/**
28
+	 * HTTP Status Code
29
+	 *
30
+	 * @var int
31
+	 */
32
+	protected $statusCode;
33
+
34
+	/**
35
+	 * Atributo usado como key para substituir por um texto.
36
+	 *
37
+	 * @var array|string
38
+	 */
39
+	protected $attributes = 'model';
40
+
41
+	/**
42
+	 * Diz se o alias será no singular ou no plural.
43
+	 *
44
+	 * @var string
45
+	 */
46
+	protected $aliastype = 'singular';
47
+
48
+	/**
49
+	 * Valor passado para o atributo
50
+	 *
51
+	 * @var array|string|null
52
+	 */
53
+	protected $values = null;
54
+
55
+	/**
56
+	 * Indica se a model será printada com lower case.
57
+	 *
58
+	 * @var boolean
59
+	 */
60
+	protected $lowercase = false;
61
+
62
+	/**
63
+	 * Construtor da exceção
64
+	 *
65
+	 * @param mixed $model
66
+	 */
67
+	public function __construct($model = 'foo')
68
+	{
69
+		$this->model = $model;
70
+	}
71
+
72
+	/**
73
+	 * Render the exception as an HTTP response.
74
+	 *
75
+	 * @return \Illuminate\Http\JsonResponse
76
+	 */
77
+	public function render()
78
+	{
79
+		return response()->
80
+			/** @scrutinizer ignore-call */
81
+			json([
82
+			'messages' => trans('scheduler::exceptions.'. $this->trans, $this->parseValues())
83
+		], $this->statusCode);
84
+	}
85
+
86
+	/**
87
+	 * Dá parse nos valores para a string de tradução.
88
+	 *
89
+	 * @return array
90
+	 */
91
+	protected function parseValues()
92
+	{
93
+		if(is_array($this->attributes) && is_array($this->values))
94
+			return collect($this->attributes)->combine($this->values)->all();
95
+
96
+		return [ $this->attributes => $this->values ?? $this->isLower() ];
97
+	}
98
+
99
+	/**
100
+	 * Verifica se é lowercase e retorna de acordo.
101
+	 *
102
+	 * @return string
103
+	 */
104
+	protected function isLower()
105
+	{
106
+		return $this->lowercase ? strtolower($this->getAlias()) : $this->getAlias();
107
+	}
108
+
109
+	/**
110
+	 * Retorna o alias da model.
111
+	 *
112
+	 * @return string
113
+	 */
114
+	protected function getAlias()
115
+	{
116
+		if(is_object($this->model))
117
+			$this->model = get_class($this->model);
118
+
119
+		return collect(trans('scheduler::exceptions.aliases.'. $this->aliastype))->search($this->model) ?: 'Recurso';
120
+	}
121
+
122
+	/**
123
+	 * Seta os valores.
124
+	 *
125
+	 * @param mixed $values
126
+	 */
127
+	public function setValues($values)
128
+	{
129
+		$this->values = $values;
130
+
131
+		return $this;
132
+	}
133 133
 }
Please login to merge, or discard this patch.
src/Scheduler/Migrations/2018_08_18_225643_create_schedule_status_table.php 1 patch
Indentation   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -15,29 +15,29 @@
 block discarded – undo
15 15
 
16 16
 class CreateScheduleStatusTable extends Migration
17 17
 {
18
-    /**
19
-     * Run the migrations.
20
-     *
21
-     * @return void
22
-     */
23
-    public function up()
24
-    {
25
-        Schema::create(Config::get('scheduler.schedule_status_table'), function (Blueprint $table) {
26
-            $table->increments('id');
27
-            $table->string('name')->unique();
28
-            $table->text('description')->nullable();
29
-            $table->timestamps();
30
-            $table->softDeletes();
31
-        });
32
-    }
18
+	/**
19
+	 * Run the migrations.
20
+	 *
21
+	 * @return void
22
+	 */
23
+	public function up()
24
+	{
25
+		Schema::create(Config::get('scheduler.schedule_status_table'), function (Blueprint $table) {
26
+			$table->increments('id');
27
+			$table->string('name')->unique();
28
+			$table->text('description')->nullable();
29
+			$table->timestamps();
30
+			$table->softDeletes();
31
+		});
32
+	}
33 33
 
34
-    /**
35
-     * Reverse the migrations.
36
-     *
37
-     * @return void
38
-     */
39
-    public function down()
40
-    {
41
-        Schema::drop(Config::get('scheduler.schedule_status_table'));
42
-    }
34
+	/**
35
+	 * Reverse the migrations.
36
+	 *
37
+	 * @return void
38
+	 */
39
+	public function down()
40
+	{
41
+		Schema::drop(Config::get('scheduler.schedule_status_table'));
42
+	}
43 43
 }
44 44
\ No newline at end of file
Please login to merge, or discard this patch.
src/Scheduler/Scheduler.php 1 patch
Indentation   +192 added lines, -192 removed lines patch added patch discarded remove patch
@@ -18,196 +18,196 @@
 block discarded – undo
18 18
 
19 19
 class Scheduler
20 20
 {
21
-    /**
22
-     * Laravel application
23
-     *
24
-     * @var \Illuminate\Foundation\Application
25
-     */
26
-    public $app;
27
-
28
-    /**
29
-     * Create a new confide instance.
30
-     *
31
-     * @param \Illuminate\Foundation\Application $app
32
-     *
33
-     * @return void
34
-     */
35
-    public function __construct($app)
36
-    {
37
-        $this->app = $app;
38
-    }
39
-
40
-    /**
41
-     * Escopo de uma consulta que busca horarios pela data de início.
42
-     *
43
-     * @param string $model_type
44
-     * @param string|\Carbon\Carbon $start_at
45
-     * @param string|\Carbon\Carbon $end_at
46
-     * @return bool
47
-     */
48
-    public function hasScheduleBetween($model_type, $start_at, $end_at)
49
-    {
50
-        if(!Config::get('scheduler.enable_schedule_conflict'))
51
-            return false;
52
-
53
-        return !is_null(
54
-            Schedule::latest()
55
-                ->where('model_type', $model_type)
56
-                ->where('start_at', '>=', $start_at)
57
-                ->where('end_at', '<=', $end_at)
58
-                ->first()
59
-        );
60
-    }
61
-
62
-    /**
63
-     * Retorna os horários disponiveis hoje para uma determinada model.
64
-     * .
65
-     * @param  string  $model_type Tipo da model
66
-     * @param  int    $duration Serve para facilitar na hora de buscar horários livres
67
-     *                          que precisem ter uma certa duração.
68
-     * @param \Carbon\Carbon|null $openingTime Serve como referencia para buscar horários livres.
69
-     *                                         Se for nulo, ele busca a referencia da config.
70
-     * @return array
71
-     */
72
-    public function availableToday($model_type, $duration, $openingTime = null)
73
-    {
74
-        return $this->availableOn($model_type, Carbon::now(), $duration, $openingTime);
75
-    }
76
-
77
-    /**
78
-     * Retorna os horários disponiveis em um determinado dia para uma certa model.
79
-     *
80
-     * @param  string  $model_type Tipo da model
81
-     * @param  \Carbon\Carbon $today Data para o qual ele irá fazer a busca.
82
-     * @param  int    $durationMinutes Serve para facilitar na hora de buscar horários livres
83
-     *                          que precisem ter uma certa duração.
84
-     * @param \Carbon\Carbon|null $openingTime Serve como referencia para buscar horários livres.
85
-     *                                         Se for nulo, ele busca a referencia da config.
86
-     * @return array
87
-     */
88
-    public function availableOn($model_type, $today, $durationMinutes, $openingTime = null)
89
-    {
90
-        $openingTime = $openingTime ?? Carbon::parse(Config::get('scheduler.opening_time'))->setDateFrom($today);
91
-        $closingTime = Carbon::parse(Config::get('scheduler.closing_time'))->setDateFrom($today);
92
-
93
-        $livres = [];
94
-        $today = Carbon::parse($today->toDateString());
95
-        while($openingTime <= $closingTime)
96
-        {
97
-            $add = true;
98
-
99
-            $opening = Carbon::parse($openingTime->toDateTimeString());
100
-            $closing = Carbon::parse($openingTime->toDateTimeString())->addMinutes($durationMinutes);
101
-
102
-            foreach (Schedule::where('model_type', $model_type)->orderBy('start_at', 'DESC')->cursor() as $schedule) {
103
-                $start = Carbon::parse($schedule->start_at);
104
-                $begin = Carbon::parse($start->toDateString());
105
-
106
-                if($begin->greaterThan($today))
107
-                    break;
108
-
109
-                if($begin->notEqualTo($today))
110
-                    continue;
111
-
112
-                $end = Carbon::parse($schedule->end_at);
113
-
114
-                if($this->isShouldntAdd($opening, $closing, $start, $end))
115
-                    $add = false;
116
-            }
117
-
118
-            if($add && $closing->lessThanOrEqualTo($closingTime))
119
-                $livres[] = [
120
-                    'start_at' => $opening,
121
-                    'end_at' => $closing
122
-                ];
123
-
124
-            $openingTime->addMinutes($durationMinutes);
125
-        }
126
-
127
-        return $livres;
128
-    }
129
-
130
-    /**
131
-     * Verifica se ele não deve ser adicionado ao array de horários livres.
132
-     *
133
-     * @param  \Carbon\Carbon  $opening
134
-     * @param  \Carbon\Carbon  $closing
135
-     * @param  \Carbon\Carbon  $start
136
-     * @param  \Carbon\Carbon  $end
137
-     * @return boolean
138
-     */
139
-    private function isShouldntAdd($opening, $closing, $start, $end)
140
-    {
141
-        return $start <= $opening && $end >= $closing;
142
-    }
143
-
144
-    /**
145
-     * Valida e retorna os dados formatados de forma correta em um [array].
146
-     *
147
-     * @param  \Carbon\Carbon|string $start_at  Data em que será agendado, pode ser em string ou em numa classe Carbon.
148
-     * @param  \Carbon\Carbon|string|int|null $end_at   Data em que acabada esse agendamento, pode ser em string, ou numa classe Carbon
149
-     *                                                  ou em int(sendo considerado os minutos de duração).
150
-     * @param  int|null $status Status desse horário ao ser agendado.
151
-     * @return array
152
-     *
153
-     * @throws \H4ad\Scheduler\Exceptions\CantAddWithoutEnd
154
-     * @throws \H4ad\Scheduler\Exceptions\EndCantBeforeStart
155
-     * @throws \H4ad\Scheduler\Exceptions\CantAddWithSameStartAt
156
-     */
157
-    public function validateSchedule($model_type, $start_at, $end_at = null, $status = null)
158
-    {
159
-        if(!Config::get('scheduler.enable_schedule_without_end') && is_null($end_at))
160
-            throw new CantAddWithoutEnd;
161
-
162
-        $start_at  = $this->parseToCarbon($start_at);
163
-
164
-        if(!is_null($end_at)) {
165
-            $end_at = $this->parseToCarbon($end_at, $start_at);
166
-
167
-            if($start_at->greaterThan($end_at))
168
-                throw new EndCantBeforeStart;
169
-        }
170
-
171
-        if($this->hasScheduleBetween($model_type, $start_at, $end_at ?? $start_at))
172
-            throw new CantAddWithSameStartAt;
173
-
174
-        return compact('model_type', 'start_at', 'end_at', 'status');
175
-    }
176
-
177
-    /**
178
-     * Faz um parse na data e retorna uma instância em Carbon.
179
-     *
180
-     * @param  \Carbon\Carbon|string|int $date Data final que será transformada numa instancia Carbon.
181
-     * @param  \Carbon\Carbon $reference Data de referencia quando o [date] é inteiro.
182
-     * @return \Carbon\Carbon
183
-     *
184
-     * @throws \H4ad\Scheduler\Exceptions\IntInvalidArgument
185
-     */
186
-    public function parseToCarbon($date, $reference = null)
187
-    {
188
-        if($date instanceof Carbon)
189
-            return $date;
190
-
191
-        if(is_string($date))
192
-            return Carbon::parse($date);
193
-
194
-        if(is_int($date) && !is_null($reference))
195
-            return Carbon::parse($reference->toDateTimeString())->addMinutes($date);
196
-
197
-        throw new IntInvalidArgument;
198
-    }
199
-
200
-    /**
201
-     * Faz um parse e retorna um Schedule.
202
-     *
203
-     * @param  \Carbon\Carbon|string|int $value Valor que representará a data ou o id a ser buscado.
204
-     * @return \H4ad\Scheduler\Models\Schedule|null
205
-     */
206
-    public function parseToSchedule($value)
207
-    {
208
-        if(is_int($value))
209
-            return Schedule::find($value);
210
-
211
-        return Schedule::byStartAt($value)->first();
212
-    }
21
+	/**
22
+	 * Laravel application
23
+	 *
24
+	 * @var \Illuminate\Foundation\Application
25
+	 */
26
+	public $app;
27
+
28
+	/**
29
+	 * Create a new confide instance.
30
+	 *
31
+	 * @param \Illuminate\Foundation\Application $app
32
+	 *
33
+	 * @return void
34
+	 */
35
+	public function __construct($app)
36
+	{
37
+		$this->app = $app;
38
+	}
39
+
40
+	/**
41
+	 * Escopo de uma consulta que busca horarios pela data de início.
42
+	 *
43
+	 * @param string $model_type
44
+	 * @param string|\Carbon\Carbon $start_at
45
+	 * @param string|\Carbon\Carbon $end_at
46
+	 * @return bool
47
+	 */
48
+	public function hasScheduleBetween($model_type, $start_at, $end_at)
49
+	{
50
+		if(!Config::get('scheduler.enable_schedule_conflict'))
51
+			return false;
52
+
53
+		return !is_null(
54
+			Schedule::latest()
55
+				->where('model_type', $model_type)
56
+				->where('start_at', '>=', $start_at)
57
+				->where('end_at', '<=', $end_at)
58
+				->first()
59
+		);
60
+	}
61
+
62
+	/**
63
+	 * Retorna os horários disponiveis hoje para uma determinada model.
64
+	 * .
65
+	 * @param  string  $model_type Tipo da model
66
+	 * @param  int    $duration Serve para facilitar na hora de buscar horários livres
67
+	 *                          que precisem ter uma certa duração.
68
+	 * @param \Carbon\Carbon|null $openingTime Serve como referencia para buscar horários livres.
69
+	 *                                         Se for nulo, ele busca a referencia da config.
70
+	 * @return array
71
+	 */
72
+	public function availableToday($model_type, $duration, $openingTime = null)
73
+	{
74
+		return $this->availableOn($model_type, Carbon::now(), $duration, $openingTime);
75
+	}
76
+
77
+	/**
78
+	 * Retorna os horários disponiveis em um determinado dia para uma certa model.
79
+	 *
80
+	 * @param  string  $model_type Tipo da model
81
+	 * @param  \Carbon\Carbon $today Data para o qual ele irá fazer a busca.
82
+	 * @param  int    $durationMinutes Serve para facilitar na hora de buscar horários livres
83
+	 *                          que precisem ter uma certa duração.
84
+	 * @param \Carbon\Carbon|null $openingTime Serve como referencia para buscar horários livres.
85
+	 *                                         Se for nulo, ele busca a referencia da config.
86
+	 * @return array
87
+	 */
88
+	public function availableOn($model_type, $today, $durationMinutes, $openingTime = null)
89
+	{
90
+		$openingTime = $openingTime ?? Carbon::parse(Config::get('scheduler.opening_time'))->setDateFrom($today);
91
+		$closingTime = Carbon::parse(Config::get('scheduler.closing_time'))->setDateFrom($today);
92
+
93
+		$livres = [];
94
+		$today = Carbon::parse($today->toDateString());
95
+		while($openingTime <= $closingTime)
96
+		{
97
+			$add = true;
98
+
99
+			$opening = Carbon::parse($openingTime->toDateTimeString());
100
+			$closing = Carbon::parse($openingTime->toDateTimeString())->addMinutes($durationMinutes);
101
+
102
+			foreach (Schedule::where('model_type', $model_type)->orderBy('start_at', 'DESC')->cursor() as $schedule) {
103
+				$start = Carbon::parse($schedule->start_at);
104
+				$begin = Carbon::parse($start->toDateString());
105
+
106
+				if($begin->greaterThan($today))
107
+					break;
108
+
109
+				if($begin->notEqualTo($today))
110
+					continue;
111
+
112
+				$end = Carbon::parse($schedule->end_at);
113
+
114
+				if($this->isShouldntAdd($opening, $closing, $start, $end))
115
+					$add = false;
116
+			}
117
+
118
+			if($add && $closing->lessThanOrEqualTo($closingTime))
119
+				$livres[] = [
120
+					'start_at' => $opening,
121
+					'end_at' => $closing
122
+				];
123
+
124
+			$openingTime->addMinutes($durationMinutes);
125
+		}
126
+
127
+		return $livres;
128
+	}
129
+
130
+	/**
131
+	 * Verifica se ele não deve ser adicionado ao array de horários livres.
132
+	 *
133
+	 * @param  \Carbon\Carbon  $opening
134
+	 * @param  \Carbon\Carbon  $closing
135
+	 * @param  \Carbon\Carbon  $start
136
+	 * @param  \Carbon\Carbon  $end
137
+	 * @return boolean
138
+	 */
139
+	private function isShouldntAdd($opening, $closing, $start, $end)
140
+	{
141
+		return $start <= $opening && $end >= $closing;
142
+	}
143
+
144
+	/**
145
+	 * Valida e retorna os dados formatados de forma correta em um [array].
146
+	 *
147
+	 * @param  \Carbon\Carbon|string $start_at  Data em que será agendado, pode ser em string ou em numa classe Carbon.
148
+	 * @param  \Carbon\Carbon|string|int|null $end_at   Data em que acabada esse agendamento, pode ser em string, ou numa classe Carbon
149
+	 *                                                  ou em int(sendo considerado os minutos de duração).
150
+	 * @param  int|null $status Status desse horário ao ser agendado.
151
+	 * @return array
152
+	 *
153
+	 * @throws \H4ad\Scheduler\Exceptions\CantAddWithoutEnd
154
+	 * @throws \H4ad\Scheduler\Exceptions\EndCantBeforeStart
155
+	 * @throws \H4ad\Scheduler\Exceptions\CantAddWithSameStartAt
156
+	 */
157
+	public function validateSchedule($model_type, $start_at, $end_at = null, $status = null)
158
+	{
159
+		if(!Config::get('scheduler.enable_schedule_without_end') && is_null($end_at))
160
+			throw new CantAddWithoutEnd;
161
+
162
+		$start_at  = $this->parseToCarbon($start_at);
163
+
164
+		if(!is_null($end_at)) {
165
+			$end_at = $this->parseToCarbon($end_at, $start_at);
166
+
167
+			if($start_at->greaterThan($end_at))
168
+				throw new EndCantBeforeStart;
169
+		}
170
+
171
+		if($this->hasScheduleBetween($model_type, $start_at, $end_at ?? $start_at))
172
+			throw new CantAddWithSameStartAt;
173
+
174
+		return compact('model_type', 'start_at', 'end_at', 'status');
175
+	}
176
+
177
+	/**
178
+	 * Faz um parse na data e retorna uma instância em Carbon.
179
+	 *
180
+	 * @param  \Carbon\Carbon|string|int $date Data final que será transformada numa instancia Carbon.
181
+	 * @param  \Carbon\Carbon $reference Data de referencia quando o [date] é inteiro.
182
+	 * @return \Carbon\Carbon
183
+	 *
184
+	 * @throws \H4ad\Scheduler\Exceptions\IntInvalidArgument
185
+	 */
186
+	public function parseToCarbon($date, $reference = null)
187
+	{
188
+		if($date instanceof Carbon)
189
+			return $date;
190
+
191
+		if(is_string($date))
192
+			return Carbon::parse($date);
193
+
194
+		if(is_int($date) && !is_null($reference))
195
+			return Carbon::parse($reference->toDateTimeString())->addMinutes($date);
196
+
197
+		throw new IntInvalidArgument;
198
+	}
199
+
200
+	/**
201
+	 * Faz um parse e retorna um Schedule.
202
+	 *
203
+	 * @param  \Carbon\Carbon|string|int $value Valor que representará a data ou o id a ser buscado.
204
+	 * @return \H4ad\Scheduler\Models\Schedule|null
205
+	 */
206
+	public function parseToSchedule($value)
207
+	{
208
+		if(is_int($value))
209
+			return Schedule::find($value);
210
+
211
+		return Schedule::byStartAt($value)->first();
212
+	}
213 213
 }
214 214
\ No newline at end of file
Please login to merge, or discard this patch.
src/Scheduler/Traits/SchedulerModelTrait.php 1 patch
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -24,27 +24,27 @@  discard block
 block discarded – undo
24 24
 trait SchedulerModelTrait
25 25
 {
26 26
 	/**
27
-     * Define a one-to-one relationship.
28
-     *
29
-     * @param  string  $related
30
-     * @param  string  $foreignKey
31
-     * @param  string  $localKey
32
-     * @return \Illuminate\Database\Eloquent\Relations\HasOne
33
-     */
34
-    abstract public function hasOne($related, $foreignKey = null, $localKey = null);
27
+	 * Define a one-to-one relationship.
28
+	 *
29
+	 * @param  string  $related
30
+	 * @param  string  $foreignKey
31
+	 * @param  string  $localKey
32
+	 * @return \Illuminate\Database\Eloquent\Relations\HasOne
33
+	 */
34
+	abstract public function hasOne($related, $foreignKey = null, $localKey = null);
35 35
 
36 36
 	/**
37
-     * Get the value of the model's primary key.
38
-     *
39
-     * @return mixed
40
-     */
37
+	 * Get the value of the model's primary key.
38
+	 *
39
+	 * @return mixed
40
+	 */
41 41
 	abstract public function getKey();
42 42
 
43 43
 	/**
44
-     * Retorna apenas o horário que possui o mesmo [model_id] do [parent] dessa [trait].
45
-     *
46
-     * @return \Illuminate\Database\Eloquent\Relations\HasOne
47
-     */
44
+	 * Retorna apenas o horário que possui o mesmo [model_id] do [parent] dessa [trait].
45
+	 *
46
+	 * @return \Illuminate\Database\Eloquent\Relations\HasOne
47
+	 */
48 48
 	public function schedules()
49 49
 	{
50 50
 		return $this->hasOne(Config::get('scheduler.schedules_table'), 'model_id');
@@ -72,8 +72,8 @@  discard block
 block discarded – undo
72 72
 	 *
73 73
 	 * @param  int    $duration Serve para facilitar na hora de buscar horários livres
74 74
 	 *                          que precisem ter uma certa duração.
75
-     * @param \Carbon\Carbon|null $openingTime Serve como referencia para buscar horários livres.
76
-     *                                         Se for nulo, ele busca a referencia da config.
75
+	 * @param \Carbon\Carbon|null $openingTime Serve como referencia para buscar horários livres.
76
+	 *                                         Se for nulo, ele busca a referencia da config.
77 77
 	 * @return array
78 78
 	 */
79 79
 	public function availableToday($duration = 0, $openingTime = null)
@@ -87,8 +87,8 @@  discard block
 block discarded – undo
87 87
 	 * @param  string|\Carbon\Carbon $date Data para o qual ele irá fazer a busca.
88 88
 	 * @param  int    $duration Serve para facilitar na hora de buscar horários livres
89 89
 	 *                          que precisem ter uma certa duração.
90
-     * @param \Carbon\Carbon|null $openingTime Serve como referencia para buscar horários livres.
91
-     *                                         Se for nulo, ele busca a referencia da config.
90
+	 * @param \Carbon\Carbon|null $openingTime Serve como referencia para buscar horários livres.
91
+	 *                                         Se for nulo, ele busca a referencia da config.
92 92
 	 * @return array
93 93
 	 */
94 94
 	public function availableOn($date, $duration = 0, $openingTime = null)
Please login to merge, or discard this patch.
src/Scheduler/Contracts/SchedulerModelTrait.php 1 patch
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -11,27 +11,27 @@  discard block
 block discarded – undo
11 11
 interface SchedulerModelInterface
12 12
 {
13 13
 	/**
14
-     * Define a one-to-one relationship.
15
-     *
16
-     * @param  string  $related
17
-     * @param  string  $foreignKey
18
-     * @param  string  $localKey
19
-     * @return \Illuminate\Database\Eloquent\Relations\HasOne
20
-     */
21
-    abstract public function hasOne($related, $foreignKey = null, $localKey = null);
14
+	 * Define a one-to-one relationship.
15
+	 *
16
+	 * @param  string  $related
17
+	 * @param  string  $foreignKey
18
+	 * @param  string  $localKey
19
+	 * @return \Illuminate\Database\Eloquent\Relations\HasOne
20
+	 */
21
+	abstract public function hasOne($related, $foreignKey = null, $localKey = null);
22 22
 
23 23
 	/**
24
-     * Get the value of the model's primary key.
25
-     *
26
-     * @return mixed
27
-     */
24
+	 * Get the value of the model's primary key.
25
+	 *
26
+	 * @return mixed
27
+	 */
28 28
 	abstract public function getKey();
29 29
 
30 30
 	/**
31
-     * Retorna apenas os horários que possuem o mesmo [model_type] do [parent] dessa [trait].
32
-     *
33
-     * @return \Illuminate\Database\Eloquent\Relations\HasMany
34
-     */
31
+	 * Retorna apenas os horários que possuem o mesmo [model_type] do [parent] dessa [trait].
32
+	 *
33
+	 * @return \Illuminate\Database\Eloquent\Relations\HasMany
34
+	 */
35 35
 	public function schedules();
36 36
 
37 37
 	/**
@@ -50,8 +50,8 @@  discard block
 block discarded – undo
50 50
 	 *
51 51
 	 * @param  int    $duration Serve para facilitar na hora de buscar horários livres
52 52
 	 *                          que precisem ter uma certa duração.
53
-     * @param \Carbon\Carbon|null $openingTime Serve como referencia para buscar horários livres.
54
-     *                                         Se for nulo, ele busca a referencia da config.
53
+	 * @param \Carbon\Carbon|null $openingTime Serve como referencia para buscar horários livres.
54
+	 *                                         Se for nulo, ele busca a referencia da config.
55 55
 	 * @return array
56 56
 	 */
57 57
 	public function availableToday($duration = 0, $openingTime = null);
@@ -62,8 +62,8 @@  discard block
 block discarded – undo
62 62
 	 * @param  string|\Carbon\Carbon $date Data para o qual ele irá fazer a busca.
63 63
 	 * @param  int    $duration Serve para facilitar na hora de buscar horários livres
64 64
 	 *                          que precisem ter uma certa duração.
65
-     * @param \Carbon\Carbon|null $openingTime Serve como referencia para buscar horários livres.
66
-     *                                         Se for nulo, ele busca a referencia da config.
65
+	 * @param \Carbon\Carbon|null $openingTime Serve como referencia para buscar horários livres.
66
+	 *                                         Se for nulo, ele busca a referencia da config.
67 67
 	 * @return array
68 68
 	 */
69 69
 	public function availableOn($date, $duration = 0, $openingTime = null);
Please login to merge, or discard this patch.
src/Scheduler/Migrations/2018_08_18_225944_create_schedules_table.php 1 patch
Indentation   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -15,33 +15,33 @@
 block discarded – undo
15 15
 
16 16
 class CreateSchedulesTable extends Migration
17 17
 {
18
-    /**
19
-     * Run the migrations.
20
-     *
21
-     * @return void
22
-     */
23
-    public function up()
24
-    {
25
-        Schema::create(Config::get('scheduler.schedules_table'), function (Blueprint $table) {
26
-            $table->increments('id');
27
-            $table->string('model_type');
28
-            $table->integer('model_id');
29
-            $table->timestamp('start_at');
30
-            $table->timestamp('end_at')->nullable();
31
-            $table->integer('status')->nullable();
32
-            $table->json('data')->nullable();
33
-            $table->timestamps();
34
-            $table->softDeletes();
35
-        });
36
-    }
18
+	/**
19
+	 * Run the migrations.
20
+	 *
21
+	 * @return void
22
+	 */
23
+	public function up()
24
+	{
25
+		Schema::create(Config::get('scheduler.schedules_table'), function (Blueprint $table) {
26
+			$table->increments('id');
27
+			$table->string('model_type');
28
+			$table->integer('model_id');
29
+			$table->timestamp('start_at');
30
+			$table->timestamp('end_at')->nullable();
31
+			$table->integer('status')->nullable();
32
+			$table->json('data')->nullable();
33
+			$table->timestamps();
34
+			$table->softDeletes();
35
+		});
36
+	}
37 37
 
38
-    /**
39
-     * Reverse the migrations.
40
-     *
41
-     * @return void
42
-     */
43
-    public function down()
44
-    {
45
-        Schema::drop(Config::get('scheduler.schedules_table'));
46
-    }
38
+	/**
39
+	 * Reverse the migrations.
40
+	 *
41
+	 * @return void
42
+	 */
43
+	public function down()
44
+	{
45
+		Schema::drop(Config::get('scheduler.schedules_table'));
46
+	}
47 47
 }
48 48
\ No newline at end of file
Please login to merge, or discard this patch.