nystudio107 /
craft-seomatic
| 1 | <?php |
||
| 2 | /** |
||
| 3 | * SEOmatic plugin for Craft CMS |
||
| 4 | * |
||
| 5 | * A turnkey SEO implementation for Craft CMS that is comprehensive, powerful, |
||
| 6 | * and flexible |
||
| 7 | * |
||
| 8 | * @link https://nystudio107.com |
||
| 9 | * @copyright Copyright (c) 2017 nystudio107 |
||
| 10 | */ |
||
| 11 | |||
| 12 | namespace nystudio107\seomatic\base; |
||
| 13 | |||
| 14 | use Exception; |
||
| 15 | use nystudio107\seomatic\Seomatic; |
||
| 16 | |||
| 17 | /** |
||
| 18 | * @author nystudio107 |
||
| 19 | * @package Seomatic |
||
| 20 | * @since 3.3.11 |
||
| 21 | */ |
||
| 22 | abstract class NonceItem extends MetaItem implements NonceItemInterface |
||
| 23 | { |
||
| 24 | // Traits |
||
| 25 | // ========================================================================= |
||
| 26 | |||
| 27 | use NonceItemTrait; |
||
| 28 | |||
| 29 | // Public Methods |
||
| 30 | // ========================================================================= |
||
| 31 | |||
| 32 | /** |
||
| 33 | * @inheritdoc |
||
| 34 | */ |
||
| 35 | public function init(): void |
||
| 36 | { |
||
| 37 | parent::init(); |
||
| 38 | if (!empty(Seomatic::$settings->cspNonce)) { |
||
| 39 | $this->nonce = $this->generateNonce(); |
||
| 40 | } |
||
| 41 | } |
||
| 42 | |||
| 43 | /** |
||
| 44 | * @inheritdoc |
||
| 45 | */ |
||
| 46 | public function rules(): array |
||
| 47 | { |
||
| 48 | $rules = parent::rules(); |
||
| 49 | $rules = array_merge($rules, [ |
||
| 50 | [['nonce'], 'string'], |
||
| 51 | ]); |
||
| 52 | |||
| 53 | return $rules; |
||
| 54 | } |
||
| 55 | |||
| 56 | /** |
||
| 57 | * @inheritdoc |
||
| 58 | */ |
||
| 59 | public function fields(): array |
||
| 60 | { |
||
| 61 | $fields = parent::fields(); |
||
| 62 | switch ($this->scenario) { |
||
| 63 | case 'render': |
||
| 64 | $fields = array_diff_key( |
||
| 65 | $fields, |
||
| 66 | array_flip([ |
||
| 67 | 'nonce', |
||
| 68 | ]) |
||
| 69 | ); |
||
| 70 | break; |
||
| 71 | } |
||
| 72 | |||
| 73 | return $fields; |
||
| 74 | } |
||
| 75 | |||
| 76 | /** |
||
| 77 | * Generate a random "nonce" for use Content Security Policy implementations as per: |
||
| 78 | * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src |
||
| 79 | * |
||
| 80 | * @return string|null |
||
| 81 | */ |
||
| 82 | public function generateNonce() |
||
| 83 | { |
||
| 84 | $result = null; |
||
|
0 ignored issues
–
show
Unused Code
introduced
by
Loading history...
|
|||
| 85 | try { |
||
| 86 | $result = bin2hex(random_bytes(22)); |
||
| 87 | } catch (Exception $e) { |
||
| 88 | // That's okay |
||
| 89 | } |
||
| 90 | |||
| 91 | return $result; |
||
| 92 | } |
||
| 93 | } |
||
| 94 |