InteractsWithCookies.php
86 lines
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * Trait for HTTP response classes to attach cookies fluently. |
| 5 | * Attached cookies are pushed into the CookieManager queue rather than stored on the response. |
| 6 | * This keeps a single emission path for responses the framework sends and those WordPress serializes. |
| 7 | * |
| 8 | * @package Framework |
| 9 | * @subpackage Http\Concerns |
| 10 | * @since 1.0.0 |
| 11 | */ |
| 12 | namespace Kirki\Framework\Http\Concerns; |
| 13 | |
| 14 | \defined('ABSPATH') || exit; |
| 15 | use Kirki\Framework\Http\Cookie; |
| 16 | use Kirki\Framework\Managers\CookieManager; |
| 17 | use function Kirki\Framework\app; |
| 18 | trait InteractsWithCookies |
| 19 | { |
| 20 | /** |
| 21 | * Attach a cookie to the response. |
| 22 | * |
| 23 | * Accepts either a Cookie instance or the arguments accepted by the cookie factory. |
| 24 | * The cookie is queued immediately and emitted at the next flush point. |
| 25 | * |
| 26 | * @param mixed $parameters The cookie instance or the factory arguments. |
| 27 | * |
| 28 | * @return $this |
| 29 | * |
| 30 | * @since 1.0.0 |
| 31 | */ |
| 32 | public function with_cookie(...$parameters) |
| 33 | { |
| 34 | $this->cookie_manager()->queue(...$parameters); |
| 35 | return $this; |
| 36 | } |
| 37 | /** |
| 38 | * Attach several cookies to the response. |
| 39 | * |
| 40 | * Accepts a list of Cookie instances or an associative array of names and values. |
| 41 | * |
| 42 | * @param array $cookies The cookies to attach. |
| 43 | * |
| 44 | * @return $this |
| 45 | * |
| 46 | * @since 1.0.0 |
| 47 | */ |
| 48 | public function with_cookies(array $cookies) |
| 49 | { |
| 50 | foreach ($cookies as $name => $cookie) { |
| 51 | if ($cookie instanceof Cookie) { |
| 52 | $this->with_cookie($cookie); |
| 53 | continue; |
| 54 | } |
| 55 | $this->with_cookie((string) $name, (string) $cookie); |
| 56 | } |
| 57 | return $this; |
| 58 | } |
| 59 | /** |
| 60 | * Remove a previously attached cookie before it is emitted. |
| 61 | * |
| 62 | * @param string $name The name of the cookie. |
| 63 | * @param string|null $path The path of the cookie, or null to remove every path. |
| 64 | * |
| 65 | * @return $this |
| 66 | * |
| 67 | * @since 1.0.0 |
| 68 | */ |
| 69 | public function without_cookie(string $name, ?string $path = null) |
| 70 | { |
| 71 | $this->cookie_manager()->unqueue($name, $path); |
| 72 | return $this; |
| 73 | } |
| 74 | /** |
| 75 | * Get the cookie manager instance. |
| 76 | * |
| 77 | * @return CookieManager |
| 78 | * |
| 79 | * @since 1.0.0 |
| 80 | */ |
| 81 | protected function cookie_manager() |
| 82 | { |
| 83 | return app(CookieManager::class); |
| 84 | } |
| 85 | } |
| 86 |