Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support a after upload hook on contained model scope #63

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/HasImageUploads.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ trait HasImageUploads
* @var string[]
*/
private $imagesFields = [];
/**
* After all upload hook
*/
private $afterUploadHook;
/**
* All the file fields for model
*
Expand Down Expand Up @@ -154,6 +158,14 @@ public function getDefinedFileFields(): array
{
return static::$fileFields ?? $this->filesFields;
}
/**
* Get after_upload hook defined on model
*
*/
public function getAfterUploadHook()
{
return static::$uploadedHook ?? $this->afterUploadHook;
}

/**
* Get upload field options
Expand Down Expand Up @@ -482,6 +494,28 @@ protected function triggerAfterSaveHook($image): self

return $this;
}
/**
* Trigger user defined after upload hook.
*
* @return $this
* @throws \Exception
*/
protected function triggerAfterUploadHook(): self
{
$hook = $this->getAfterUploadHook();
if (isset($hook)) {
if (is_callable($hook)) {
$hook($this);
}
// We assume that the user is passing the hook class name
if (is_string($hook)) {
$instance = app($hook);
$instance->handle($this);
}
}

return $this;
}

/**
* Process image upload
Expand Down Expand Up @@ -753,6 +787,7 @@ public function enableAutoUpload(): self
*/
protected function autoUpload(): void
{
$isUpload = false;
foreach ($this->getDefinedUploadFields() as $key => $val) {
$field = is_int($key) ? $val : $key;
$options = Arr::wrap($val);
Expand All @@ -774,6 +809,10 @@ protected function autoUpload(): void
$field
);
}
$isUpload = true;
}
if ($isUpload) {
$this->triggerAfterUploadHook();
}
}

Expand Down