Skip to content

Commit

Permalink
add views response
Browse files Browse the repository at this point in the history
  • Loading branch information
AbdallaMohammed committed Jan 8, 2021
1 parent 843ca58 commit 6eb2724
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 5 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
},
"autoload": {
"psr-4": {
"AbdallaMohammed\\Forms\\": "src/"
"AbdallaMohammed\\Form\\": "src/"
}
},
"autoload-dev": {
Expand Down
58 changes: 54 additions & 4 deletions src/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Illuminate\Validation\Rule;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\View;
use Illuminate\Session\Store as Session;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Responsable;
Expand All @@ -23,6 +24,16 @@ class Form implements Responsable, Arrayable
*/
protected $method = 'POST';

/**
* @var string
*/
protected $view = '';

/**
* @var string
*/
protected $data = [];

/**
* @var Request
*/
Expand Down Expand Up @@ -326,6 +337,17 @@ public function stepConfig(?int $step = null): Step
return $this->steps->get($step ?? $this->currentStep());
}

/**
* @param mixed ...$params
*/
public function useView(...$params)
{
$this->view = func_get_arg(0);
$this->data = is_array(func_get_arg(1)) ? func_get_arg(1) : [];

return $this;
}

/**
* Handle the validated request.
*
Expand Down Expand Up @@ -373,13 +395,41 @@ protected function setupSession(): void
/**
* Render the request as a response.
*
* @return JsonResponse
* @return JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\Contracts\View\View
*/
protected function renderResponse()
{
return new JsonResponse((object) [
'form' => $this->toArray(),
]);
if (! $this->usesViews() || $this->needsJsonResponse()) {
return new JsonResponse((object) [
'form' => $this->toArray(),
]);
}

if (! $this->request->isMethod('GET')) {
return redirect()->back();
}

return View::make($this->view, array_merge([
'form' => $this,
], $this->data));
}

/**
* Request needs JSON response.
*
* @return bool
*/
protected function needsJsonResponse(): bool
{
return $this->request->wantsJson() || $this->request->isXmlHttpRequest();
}

/**
* @return bool
*/
protected function usesViews(): bool
{
return ! empty($this->view) && is_string($this->view);
}

/**
Expand Down

0 comments on commit 6eb2724

Please sign in to comment.