Skip to content

Commit

Permalink
Merge pull request #9 from edalzell/support-entries
Browse files Browse the repository at this point in the history
Work w/ saving entries, so can use Workshop’ish stuff
  • Loading branch information
aryehraber authored Jan 13, 2021
2 parents 2ecf1a4 + 11bcfc3 commit 5741cea
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 5 deletions.
1 change: 1 addition & 0 deletions config/captcha.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
'service' => 'Recaptcha', // options: Recaptcha / Hcaptcha
'sitekey' => env('CAPTCHA_SITEKEY', ''),
'secret' => env('CAPTCHA_SECRET', ''),
'collections' => [],
'forms' => [],
'error_message' => 'Captcha failed.',
'disclaimer' => '',
Expand Down
11 changes: 6 additions & 5 deletions src/CaptchaServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

namespace AryehRaber\Captcha;

use AryehRaber\Captcha\Listeners\ValidateEntry;
use AryehRaber\Captcha\Listeners\ValidateFormSubmission;
use Statamic\Events\EntrySaving;
use Statamic\Events\FormSubmitted;
use Statamic\Providers\AddonServiceProvider;
use AryehRaber\Captcha\Listeners\ValidateFormSubmission;

class CaptchaServiceProvider extends AddonServiceProvider
{
Expand All @@ -15,9 +17,8 @@ class CaptchaServiceProvider extends AddonServiceProvider
];

protected $listen = [
FormSubmitted::class => [
ValidateFormSubmission::class,
],
FormSubmitted::class => [ValidateFormSubmission::class],
EntrySaving::class => [ValidateEntry::class],
];

protected $routes = [
Expand All @@ -26,7 +27,7 @@ class CaptchaServiceProvider extends AddonServiceProvider

public function register()
{
$this->app->bind(Captcha::class, function() {
$this->app->bind(Captcha::class, function () {
$service = config('captcha.service');
$class = "AryehRaber\\Captcha\\{$service}";

Expand Down
39 changes: 39 additions & 0 deletions src/Listeners/ValidateEntry.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace AryehRaber\Captcha\Listeners;

use AryehRaber\Captcha\Captcha;
use Illuminate\Validation\ValidationException;
use Statamic\Entries\Entry;
use Statamic\Events\EntrySaving;
use Statamic\Statamic;

class ValidateEntry
{
protected $captcha;

public function __construct(Captcha $captcha)
{
$this->captcha = $captcha;
}

public function handle(EntrySaving $event)
{
/** @var Entry */
$entry = $event->entry;

if (Statamic::isCpRoute()) {
return $entry;
}

if (! in_array($entry->collectionHandle(), config('captcha.collections', []))) {
return $entry;
}

if ($this->captcha->verify()->invalidResponse()) {
throw ValidationException::withMessages(['captcha' => config('captcha.error_message')]);
}

return $entry;
}
}

0 comments on commit 5741cea

Please sign in to comment.