Skip to content
Open
Show file tree
Hide file tree
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
22 changes: 20 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,24 @@ Cookie notices are boring and this package's default design is no different. It

However, this world shouldn't be a boring place and even if cookie notices are part of a project's legal requirements, why not use it as an opportunity to bring a smile to your audience's face? Cookie modals are now integrated in every digital platform's user experience and therefore they should blend in accordingly: that's why we've built this package with full flexibility in our mind.

For example, after publishing the views, you can fully customize the different buttons, as in this example:

```bladehtml
<form action="{!! $url !!}" {!! $attributes !!}>
@csrf
@if($action === 'reset')
<button type="submit" class="{!! $basename !!}__reset" data-toggle="tooltip">
<span class="icon icon--reset"></span>
<span class="{!! $basename !!}__label">{{ $label }}</span>
</button>
@else
<button type="submit" class="{!! $basename !!}__link">
<span class="{!! $basename !!}__label">{{ $label }}</span>
</button>
@endif
</form>
```

### The views

A good starting point is to take a look at this package's default markup. If not already published, you can access the views using `php artisan vendor:publish --tag=laravel-cookie-consent-views`, this will copy our blade files to your app's `resources/views/vendor/cookie-consent` directory.
Expand Down Expand Up @@ -373,7 +391,7 @@ Our CSS is compiled from a SASS file included in this package's `resources/scss`
Buttons in this package are designed to be easily customizable.
You can pass an array of attributes directly to the `@cookieconsentbutton` component:

```blade
```bladehtml
@cookieconsentbutton(
action: 'reset',
label: 'Manage cookies',
Expand All @@ -391,7 +409,7 @@ In this example:

With this setup, you can freely customize your button styles using pseudo-classes like `:hover`, `:focus`, while keeping a clean and maintainable structure.

For other changes, don't forget [you can publish the package views](#the-views).
For other changes, don't forget [you can publish the package views](#the-views). The `$action` variable lets you customize your button for specific use cases.

### Javascript

Expand Down
62 changes: 39 additions & 23 deletions src/CookiesManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie as CookieFacade;
use Symfony\Component\HttpFoundation\Cookie as CookieComponent;
use Whitecube\LaravelCookieConsent\Enums\CookieConsentState;

class CookiesManager
{
Expand All @@ -17,6 +18,7 @@ class CookiesManager
* The user's current consent preferences.
*/
protected ?array $preferences = null;
protected CookieConsentState $state;

/**
* Create a new Service Manager instance.
Expand All @@ -25,6 +27,7 @@ public function __construct(CookiesRegistrar $registrar, Request $request)
{
$this->registrar = $registrar;
$this->preferences = $this->getCurrentConsentSettings($request);
$this->state = $this->preferences ? CookieConsentState::Configured : CookieConsentState::Pending;
}

/**
Expand All @@ -36,12 +39,12 @@ protected function getCurrentConsentSettings(Request $request): ?array
? json_decode($raw, true)
: null;

if(! $preferences || ! is_int($preferences['consent_at'] ?? null)) {
if (!$preferences || !is_int($preferences['consent_at'] ?? null)) {
return null;
}

// Check duration in case application settings have changed since the cookie was set.
if($preferences['consent_at'] + (config('cookieconsent.cookie.duration') * 60) < time()) {
if ($preferences['consent_at'] + (config('cookieconsent.cookie.duration') * 60) < time()) {
return null;
}

Expand All @@ -53,9 +56,9 @@ protected function getCurrentConsentSettings(Request $request): ?array
*/
protected function makeConsentSettings(array $categories): array
{
return array_reduce($this->registrar->getCategories(), function($values, $category) use ($categories) {
return array_reduce($this->registrar->getCategories(), function ($values, $category) use ($categories) {
$state = in_array($category->key(), $categories);
return array_reduce($category->getCookies(), function($values, $cookie) use ($state) {
return array_reduce($category->getCookies(), function ($values, $cookie) use ($state) {
$values[$cookie->name] = $state;
return $values;
}, $values);
Expand All @@ -76,13 +79,24 @@ public function __call(string $method, array $arguments)
*/
public function shouldDisplayNotice(): bool
{
if(! $this->preferences) {
return true;
if ($this->state === CookieConsentState::Configured) {
$this->state = $this->checkCurrentState() ? CookieConsentState::Pending : CookieConsentState::Configured;
}

// Check if each defined cookie has been shown to the user yet.
return array_reduce($this->registrar->getCategories(), function($state, $category) {
return $state ? true : array_reduce($category->getCookies(), function(bool $state, Cookie $cookie) {
return $this->state->shouldDisplayNotice();
}

public function setCookieConsentState(CookieConsentState $state): self
{
$this->state = $state;

return $this;
}

protected function checkCurrentState(): bool
{
return array_reduce($this->registrar->getCategories(), function ($state, $category) {
return $state ? true : array_reduce($category->getCookies(), function (bool $state, Cookie $cookie) {
return $state ? true : !array_key_exists($cookie->name, $this->preferences);
}, false);
}, false);
Expand All @@ -93,13 +107,13 @@ public function shouldDisplayNotice(): bool
*/
public function hasConsentFor(string $key): bool
{
if(! $this->preferences) {
if ($this->state === CookieConsentState::Configured) {
return false;
}

$groups = array_reduce($this->registrar->getCategories(), function($results, $category) use ($key) {
return array_reduce($category->getDefined(), function(array $results, Cookie|CookiesGroup $instance) use ($key) {
if(is_a($instance, CookiesGroup::class) && $instance->name === $key) {
$groups = array_reduce($this->registrar->getCategories(), function ($results, $category) use ($key) {
return array_reduce($category->getDefined(), function (array $results, Cookie|CookiesGroup $instance) use ($key) {
if (is_a($instance, CookiesGroup::class) && $instance->name === $key) {
$results[] = $instance;
}
return $results;
Expand All @@ -110,8 +124,8 @@ public function hasConsentFor(string $key): bool
? array_unique(array_reduce($groups, fn($cookies, $group) => array_merge($cookies, array_map(fn($cookie) => $cookie->name, $group->getCookies())), []))
: [$key];

foreach($cookies as $cookie) {
if(! boolval($this->preferences[$cookie] ?? false)) return false;
foreach ($cookies as $cookie) {
if (!boolval($this->preferences[$cookie] ?? false)) return false;
}

return true;
Expand All @@ -122,7 +136,7 @@ public function hasConsentFor(string $key): bool
*/
public function accept(string|array $categories = '*'): ConsentResponse
{
if(! is_array($categories) || ! $categories) {
if (!is_array($categories) || !$categories) {
$categories = array_map(fn($category) => $category->key(), $this->registrar->getCategories());
}

Expand All @@ -141,8 +155,8 @@ public function accept(string|array $categories = '*'): ConsentResponse
*/
protected function getConsentResponse(): ConsentResponse
{
return array_reduce($this->registrar->getCategories(), function($response, $category) {
return array_reduce($category->getDefined(), function(ConsentResponse $response, Cookie|CookiesGroup $instance) {
return array_reduce($this->registrar->getCategories(), function ($response, $category) {
return array_reduce($category->getDefined(), function (ConsentResponse $response, Cookie|CookiesGroup $instance) {
return $this->hasConsentFor($instance->name)
? $response->handleConsent($instance)
: $response;
Expand Down Expand Up @@ -173,7 +187,7 @@ public function renderScripts(bool $withDefault = true): string
? $this->getNoticeScripts($withDefault)
: $this->getConsentedScripts($withDefault);

if(strlen($output)) {
if (strlen($output)) {
$output = '<!-- Cookie Consent -->' . $output;
}

Expand Down Expand Up @@ -217,7 +231,7 @@ public function renderView(): string

public function getNoticeMarkup(): string
{
if($policy = config('cookieconsent.policy')) {
if ($policy = config('cookieconsent.policy')) {
$policy = route($policy);
}

Expand All @@ -240,7 +254,7 @@ public function renderButton(string $action, ?string $label = null, array $attri
default => null,
};

if(! $url) {
if (!$url) {
throw new \InvalidArgumentException('Cookie consent action "' . $action . '" does not exist. Try one of these: "accept.all", "accept.essentials", "accept.configuration", "reset".');
}

Expand All @@ -249,7 +263,7 @@ public function renderButton(string $action, ?string $label = null, array $attri
'data-cookie-action' => $action,
], $attributes);

if(! ($attributes['class'] ?? null)) {
if (!($attributes['class'] ?? null)) {
$attributes['class'] = 'cookiebtn';
}

Expand All @@ -264,6 +278,8 @@ public function renderButton(string $action, ?string $label = null, array $attri
'label' => $label ?? $action, // TODO: use lang file
'attributes' => $attributes,
'basename' => $basename,
'action' => $action,
'state' => $this->state,
])->render();
}

Expand All @@ -282,7 +298,7 @@ public function replaceInfoTag(string $wysiwyg): string
$cookieConsentInfo = view('cookie-consent::info', [
'cookies' => $this->registrar,
])->render();

$formattedString = preg_replace(
[
'/\<(\w)[^\>]+\>\@cookieconsentinfo\<\/\1\>/',
Expand Down
27 changes: 27 additions & 0 deletions src/Enums/CookieConsentState.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Whitecube\LaravelCookieConsent\Enums;

enum CookieConsentState
{
// User has yet to configure consent
case Pending;

// User has defined a consent configuration
case Configured;

// User has configured consent but wants to show the modal in order to eventually make changes
// case Updating; TODO: Add for Pull Request 103

// User had configured consent but chose to reset the settings (similar to "pending")
case Reset;

public function shouldDisplayNotice(): bool
{
return match($this) {
static::Pending , static::Reset=> true,
static::Configured => false,
// static::Updating => true,
};
}
}
3 changes: 2 additions & 1 deletion src/Http/Controllers/AcceptAllController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@

use Whitecube\LaravelCookieConsent\CookiesManager;
use Illuminate\Http\Request;
use Whitecube\LaravelCookieConsent\Enums\CookieConsentState;

class AcceptAllController
{
public function __invoke(Request $request, CookiesManager $cookies)
{
return $cookies->accept('*')->toResponse($request);
return $cookies->setCookieConsentState(CookieConsentState::Configured)->accept('*')->toResponse($request);
}
}
3 changes: 3 additions & 0 deletions src/Http/Controllers/ResetController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@

use Whitecube\LaravelCookieConsent\CookiesManager;
use Illuminate\Http\Request;
use Whitecube\LaravelCookieConsent\Enums\CookieConsentState;

class ResetController
{
public function __invoke(Request $request, CookiesManager $cookies)
{
$cookies->setCookieConsentState(CookieConsentState::Reset);

$response = ! $request->expectsJson()
? redirect()->back()
: response()->json([
Expand Down