Skip to content

Instantly share code, notes, and snippets.

@johnfmorton
Created October 19, 2022 18:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnfmorton/65cb1b0ae4c04f4c35b28b7f4bbc6e36 to your computer and use it in GitHub Desktop.
Save johnfmorton/65cb1b0ae4c04f4c35b28b7f4bbc6e36 to your computer and use it in GitHub Desktop.
Craft CMS 4.x SHA512 filter for use in a module
<?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());
}
}
}
<?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