Skip to content

Instantly share code, notes, and snippets.

@Danielss89
Created April 30, 2012 22:06
Show Gist options
  • Save Danielss89/2563072 to your computer and use it in GitHub Desktop.
Save Danielss89/2563072 to your computer and use it in GitHub Desktop.
Force SSL on ZF2
<?php
namespace DanForceSSL;
use Zend\Module\Manager,
Zend\EventManager\StaticEventManager,
Zend\Module\Consumer\AutoloaderProvider;
class Module implements AutoloaderProvider
{
protected static $options;
public function init(Manager $moduleManager)
{
$moduleManager->events()->attach('loadModules.post', array($this, 'modulesLoaded'));
$sharedEvents = $moduleManager->events()->getSharedCollections();
$sharedEvents->attach('Zend\Mvc\Application', 'route', array($this, 'checkHTTPS'), -10);
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function checkHTTPS($e)
{
$fqController = $e->getRouteMatch()->getParam("controller");
$explode = explode("\\", $fqController); // Yes, need new name :D
$namespace = $explode[0];
$action = $e->getRouteMatch()->getParam("action");
if(array_key_exists($namespace, $this->getOption("modules")->toArray()) OR
array_key_exists($fqController, $this->getOption("controllers")->toArray()) OR // Need to create a var with actionConfig from below
array_key_exists($fqController, $this->getOption("actions")->toArray()) AND $this->getOption("actions")->toArray()[$fqController] == $action)
{
$request = $e->getRequest();
$uri = $request->uri();
if($uri->getScheme() !== "https")
{
$uri->setScheme("https");
$response = $e->getResponse();
$response->headers()->addHeaderLine('Location', $request->getUri());
return $response;
}
}
}
public function modulesLoaded($e)
{
$config = $e->getConfigListener()->getMergedConfig();
static::$options = $config['danforcessl'];
}
/**
* Borrowed from ZfcUser
* @TODO: Come up with a better way of handling module settings/options
*/
public static function getOption($option)
{
if (!isset(static::$options[$option])) {
return null;
}
return static::$options[$option];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment