Created
October 19, 2022 18:31
-
-
Save johnfmorton/65cb1b0ae4c04f4c35b28b7f4bbc6e36 to your computer and use it in GitHub Desktop.
Craft CMS 4.x SHA512 filter for use in a module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace modules; | |
use modules\TwigFilterSha512; | |
use Craft; | |
/** | |
* Custom module class. | |
* | |
* This class will be available throughout the system via: | |
* `Craft::$app->getModule('my-module')`. | |
* | |
* You can change its module ID ("my-module") to something else from | |
* config/app.php. | |
* | |
* If you want the module to get loaded on every request, uncomment this line | |
* in config/app.php: | |
* | |
* 'bootstrap' => ['my-module'] | |
* | |
* Learn more about Yii module development in Yii's documentation: | |
* http://www.yiiframework.com/doc-2.0/guide-structure-modules.html | |
*/ | |
class Module extends \yii\base\Module | |
{ | |
/** | |
* Initializes the module. | |
*/ | |
public function init() | |
{ | |
// Set a @modules alias pointed to the modules/ directory | |
Craft::setAlias('@modules', __DIR__); | |
// Set the controllerNamespace based on whether this is a console or web request | |
if (Craft::$app->getRequest()->getIsConsoleRequest()) { | |
$this->controllerNamespace = 'modules\\console\\controllers'; | |
} else { | |
$this->controllerNamespace = 'modules\\controllers'; | |
} | |
parent::init(); | |
// Custom initialization code goes here... | |
if (Craft::$app->getRequest()->getIsSiteRequest()) { | |
Craft::$app->getView()->registerTwigExtension(new TwigFilterSha512()); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace modules; | |
class TwigFilterSha512 extends \Twig\Extension\AbstractExtension | |
{ | |
public function getName(): string | |
{ | |
return 'sha512'; | |
} | |
public function getFilters(): array | |
{ | |
return [ | |
new \Twig\TwigFilter('sha512', [$this, 'sha512']), | |
]; | |
} | |
public function sha512($string): string | |
{ | |
return hash('sha512', $string); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment