Created
February 17, 2014 15:44
-
-
Save sasezaki/9052945 to your computer and use it in GitHub Desktop.
Trap Reserved Username For ZfcUser module
This file contains hidden or 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 TrapReservedUsernameForZfcUser; | |
use Zend\Mvc\MvcEvent; | |
use Zend\Validator\ValidatorChain; | |
use Zend\Validator\Callback; | |
use ZfcUser\Validator\NoRecordExists; | |
class Module | |
{ | |
public function onBootstrap(MvcEvent $e) | |
{ | |
$sm = $e->getApplication()->getServiceManager(); | |
$form = $sm->get('zfcuser_register_form'); | |
$inputFilter = $form->getInputFilter(); | |
$this->insertReservedUsernameValidatorToInput($inputFilter->get('username')); | |
} | |
private function insertReservedUsernameValidatorToInput($input) | |
{ | |
$usernameValidator = function($name) { | |
// borrowed from | |
// http://qiita.com/phimcall/items/4c559b70f70ea7f1953b | |
$list = 'index, home, top, help, about, security, contact, connect, support, faq, form, mail, update, mobile, phone, portal'; | |
return !in_array($name, explode(", ", $list)); | |
}; | |
$validators = $input->getValidatorChain()->getValidators(); | |
$validators = $this->insertCallbackValidatorBeforeNoRecordExists($validators, $usernameValidator); | |
$validatorChain = new ValidatorChain(); | |
foreach ($validators as $validator) { | |
$validatorChain->attach($validator['instance'], $validator['breakChainOnFailure']); | |
} | |
$input->setValidatorChain($validatorChain); | |
} | |
private function insertCallbackValidatorBeforeNoRecordExists($validators, $callback) | |
{ | |
$newValidators = []; | |
$newValidatorCount = count($validators) + 1; | |
for ($i = 0, $k = 0; $i < $newValidatorCount; $i++, $k++) { | |
if ($validators[$k]['instance'] instanceof NoRecordExists) { | |
$newValidators[$i]['instance'] = new Callback($callback); | |
$newValidators[$i]['breakChainOnFailure'] = false; | |
++$i; | |
} | |
$newValidators[$i] = $validators[$k]; | |
} | |
return $newValidators; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment