/** * Register assertion handler in php * * @returns void */ public static function register() { assert_options(ASSERT_ACTIVE, 1); assert_options(ASSERT_WARNING, 0); assert_options(ASSERT_QUIET_EVAL, 1); assert_options(ASSERT_CALLBACK, array('libfajr\\Assert', 'myAssertHandler')); }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (!Session::has('role')) { return redirect('/login'); } if (!isset($_COOKIE['login'])) { $visitorCount = 1; } $setTime = time() + 3600; if (isset($_COOKIE['login'])) { $visitorCount = $_COOKIE['login'] + 1; setCookie('login', $visitorCount, $setTime); } else { setCookie('login', $visitorCount, $setTime); } if (!Session::has('anchor')) { session(['anchor' => '2']); } assert_options(ASSERT_ACTIVE, 1); assert_options(ASSERT_WARNING, 0); assert_options(ASSERT_QUIET_EVAL, 1); assert_options(ASSERT_CALLBACK, 'my_assert_handler'); $old_error_handler = set_error_handler("myErrorHandler"); return $next($request); }
function ERAssertInRange($expr, $min, $max, $description) { $expression = eval("return {$expr};"); assert_options(ASSERT_CALLBACK, create_function('$file, $line, $code', "echo \"{$description}; expected in range ({$min}),({$max}) but found ({$expression})\n" . '";')); $success = assert("(({$expr}) >= ({$min})) && (({$expr}) <= ({$max}))"); assertion_increase($success); }
function assert_in_function() { assert_options(ASSERT_ACTIVE, true); $value = '2'; var_dump(assert(is_string($value))); var_dump(assert('is_string($value)')); }
/** * Determine whether a module is enabled. * * Will return false if the given module doesn't exists. * * @param string $module Name of the module * * @return bool True if the given module is enabled, false otherwise. * * @throws Exception If module.enable is set and is not boolean. */ public static function isModuleEnabled($module) { $moduleDir = self::getModuleDir($module); if (!is_dir($moduleDir)) { return false; } $globalConfig = SimpleSAML_Configuration::getOptionalConfig(); $moduleEnable = $globalConfig->getArray('module.enable', array()); if (isset($moduleEnable[$module])) { if (is_bool($moduleEnable[$module]) === true) { return $moduleEnable[$module]; } throw new Exception("Invalid module.enable value for for the module {$module}"); } if (assert_options(ASSERT_ACTIVE) && !file_exists($moduleDir . '/default-enable') && !file_exists($moduleDir . '/default-disable')) { SimpleSAML_Logger::error("Missing default-enable or default-disable file for the module {$module}"); } if (file_exists($moduleDir . '/enable')) { return true; } if (!file_exists($moduleDir . '/disable') && file_exists($moduleDir . '/default-enable')) { return true; } return false; }
/** * Install this assertion handler. * * This function will register this assertion handler. If will not enable assertions if they are * disabled. */ public static function installHandler() { assert_options(ASSERT_WARNING, 0); assert_options(ASSERT_BAIL, 0); assert_options(ASSERT_QUIET_EVAL, 0); assert_options(ASSERT_CALLBACK, array('SimpleSAML_Error_Assertion', 'onAssertion')); }
/** * Runs tests and outputs report. This function will run all functions * beginning with test_ found in all files provided as arguments. Invalid * files are skipped. * * @param string|array $files Either a string or an array of test files * * @return bool True if all tests passes, false otherwise */ public static function run($files) { static $tokens = array(); $failures = array(); assert_options(ASSERT_ACTIVE, true); assert_options(ASSERT_BAIL, false); assert_options(ASSERT_WARNING, false); assert_options(ASSERT_QUIET_EVAL, false); assert_options(ASSERT_CALLBACK, function ($file, $line, $assert, $description = null) use(&$failures, &$tokens) { $failures[] = array('file' => $file, 'line' => $line, 'assert' => $assert, 'description' => $description); }); if (is_string($files)) { $files = (array) $files; } $asserts = 0; $tests = 0; $t0 = microtime(true); foreach ($files as $file) { if (!(is_string($file) && is_readable($file))) { continue; } $source = file_get_contents($file); $asserts = preg_match_all('/assert\\(/im', $source, $_); if (preg_match_all('/function (test_(?:[a-z_][a-z0-9_]*))\\(/im', $source, $matches)) { $functions = $matches[1]; require_once $file; foreach ($functions as $f) { if (is_callable($f)) { $tests += 1; call_user_func($f); } } } } $t = round(microtime(true) - $t0, 3); ob_start(); if ($failures) { print 'Failed ' . count($failures) . " of {$asserts} assert(s) in {$tests} test(s) - completed in {$t} seconds." . PHP_EOL; print str_repeat('-', 79) . PHP_EOL; foreach ($failures as $i => $failure) { print $i + 1 . ". {$failure['file']}:{$failure['line']}" . PHP_EOL; if (strlen($failure['assert'])) { print "\t{$failure['assert']}" . PHP_EOL; } print str_repeat('-', 79) . PHP_EOL; } } else { print "Passed {$asserts} assert(s) in {$tests} test(s) - completed in {$t} seconds." . PHP_EOL; } $report = ob_get_clean(); if (php_sapi_name() == 'cli') { echo $report; } else { echo '<pre>' . PHP_EOL; echo $report; echo '</pre>' . PHP_EOL; } return empty($failures); }
static function setup() { set_error_handler(array("\\libraries\\ExceptionHandler", "error_handler")); set_exception_handler(array("\\libraries\\ExceptionHandler", 'exception_handler')); register_shutdown_function(array("\\libraries\\ExceptionHandler", "check_for_fatal")); assert_options(ASSERT_ACTIVE, true); assert_options(ASSERT_CALLBACK, array("\\libraries\\ExceptionHandler", '_assert_failure')); }
function main($argv) { ini_set('error_reporting', E_ALL | E_STRICT); ini_set('display_errors', 'on'); assert_options(ASSERT_CALLBACK, 'assert_cb'); $proc = new phpjs(); $proc->translate_file($argv[1]); }
public static function setAssertionsLevel1($enable) { assert('is_bool($enable)', vs(isset($this), get_defined_vars())); assert_options(ASSERT_ACTIVE, $enable); if (self::$ms_anyFailedAssertionIsFatal && $enable) { assert_options(ASSERT_BAIL, true); } }
protected function assertsInitialize() { assert_options(ASSERT_ACTIVE, static::$ASSERT_ACTIVE); assert_options(ASSERT_WARNING, static::$ASSERT_WARNING); assert_options(ASSERT_BAIL, static::$ASSERT_BAIL); assert_options(ASSERT_QUIET_EVAL, static::$ASSERT_QUIET_EVAL); assert_options(ASSERT_CALLBACK, [$this, static::ASSERT_FAILED_METHOD]); }
/** * Reset assert() options * * @return void */ public static function resetAssertOptions() { assert_options(ASSERT_ACTIVE, 1); assert_options(ASSERT_WARNING, 1); assert_options(ASSERT_BAIL, 0); assert_options(ASSERT_QUIET_EVAL, 0); assert_options(ASSERT_CALLBACK, null); }
/** @return void */ public function refreshAssertBindings() { assert_options(ASSERT_CALLBACK, array($this, 'assertCallback')); assert_options(ASSERT_ACTIVE, 1); assert_options(ASSERT_WARNING, 0); assert_options(ASSERT_QUIET_EVAL, 1); assert_options(ASSERT_BAIL, 0); }
/** * */ protected function setAssertHandling() { // Active assert and make it quiet assert_options(ASSERT_ACTIVE, 1); assert_options(ASSERT_WARNING, 0); assert_options(ASSERT_QUIET_EVAL, 1); // Set up the callback assert_options(ASSERT_CALLBACK, array($this, 'assertHandler')); }
public static function register() { self::$oldhandler = set_error_handler(array(__CLASS__, '__php_handleError'), E_ALL); \set_exception_handler(array(__CLASS__, '__php_handleException')); // Active assert and make it quiet assert_options(ASSERT_ACTIVE, 1); assert_options(ASSERT_WARNING, 0); assert_options(ASSERT_QUIET_EVAL, 1); assert_options(ASSERT_CALLBACK, array(__CLASS__, '__php_handleAssert')); }
/** * @ignore */ function vs($dummy, $vars) { // This internal function is used by assertions to put debugging information about the variables that are defined // at the point of a failing assertion and the object's properties at that point into a string to subsequently log // it into a file, send it by mail to the administrator etc. if (assert_options(ASSERT_ACTIVE) !== 1) { // Assertions are disabled, so nothing to do. return; } return CDebug::definedVarsToString($vars); }
static function start() { Bundle::start('htmlki'); error_reporting(-1); static::$logged = array(); assert_options(ASSERT_BAIL, 1); if (!static::$attached) { static::$attached = true; \Event::listen('laravel.log', array(get_called_class(), 'onLog')); } }
public function __construct() { $this->xmlSerializer = new XmlSerializer(); $this->builder = new ServicesBuilder(); Logger::setLogFile('C:\\log.txt'); // Enable PHP asserts assert_options(ASSERT_ACTIVE, 1); assert_options(ASSERT_WARNING, 0); assert_options(ASSERT_QUIET_EVAL, 1); assert_options(ASSERT_CALLBACK, 'Tests\\Framework\\RestProxyTestBase::assertHandler'); }
function __construct($reporter = null) { if (!$reporter) { $reporter = new StoryRunnerCliReporter(); } $this->attach($reporter); assert_options(ASSERT_ACTIVE, 1); assert_options(ASSERT_WARNING, 0); assert_options(ASSERT_QUIET_EVAL, 1); assert_options(ASSERT_CALLBACK, array($this, 'assert_handler')); }
public static function isValid() { if (!assert_options(ASSERT_ACTIVE)) { return true; } $bt = self::debugBacktrace(null, 1); extract($bt); //to $file, $line, $function, $class, $object, $type, $args if (!$args) { return true; } #speed improve $r = new ReflectionMethod($class, $function); $doc = $r->getDocComment(); $cache_id = $class . $type . $function; preg_match_all('~ [\\r\\n]++ [\\x20\\t]++ \\* [\\x20\\t]++ @param [\\x20\\t]++ \\K #memory reduce ( [_a-z]++[_a-z\\d]*+ (?>[|/,][_a-z]+[_a-z\\d]*)*+ ) #1 types [\\x20\\t]++ &?+\\$([_a-z]++[_a-z\\d]*+) #2 name ~sixSX', $doc, $params, PREG_SET_ORDER); $parameters = $r->getParameters(); //d($args, $params, $parameters); if (count($parameters) > count($params)) { $message = 'phpDoc %d piece(s) @param description expected in %s%s%s(), %s given, ' . PHP_EOL . 'called in %s on line %d ' . PHP_EOL . 'and defined in %s on line %d'; $message = sprintf($message, count($parameters), $class, $type, $function, count($params), $file, $line, $r->getFileName(), $r->getStartLine()); trigger_error($message, E_USER_NOTICE); } foreach ($args as $i => $value) { if (!isset($params[$i])) { return true; } if ($parameters[$i]->name !== $params[$i][2]) { $param_num = $i + 1; $message = 'phpDoc @param %d in %s%s%s() must be named as $%s, $%s given, ' . PHP_EOL . 'called in %s on line %d ' . PHP_EOL . 'and defined in %s on line %d'; $message = sprintf($message, $param_num, $class, $type, $function, $parameters[$i]->name, $params[$i][2], $file, $line, $r->getFileName(), $r->getStartLine()); trigger_error($message, E_USER_NOTICE); } $hints = preg_split('~[|/,]~sSX', $params[$i][1]); if (!self::checkValueTypes($hints, $value)) { $param_num = $i + 1; $message = 'Argument %d passed to %s%s%s() must be an %s, %s given, ' . PHP_EOL . 'called in %s on line %d ' . PHP_EOL . 'and defined in %s on line %d'; $message = sprintf($message, $param_num, $class, $type, $function, implode('|', $hints), (is_object($value) ? get_class($value) . ' ' : '') . gettype($value), $file, $line, $r->getFileName(), $r->getStartLine()); trigger_error($message, E_USER_WARNING); return false; } } return true; }
public static function Init($active = true) { assert_options(ASSERT_ACTIVE, $active); if (!$active) { return false; } assert_options(ASSERT_WARNING, 0); assert_options(ASSERT_QUIET_EVAL, 1); assert_options(ASSERT_CALLBACK, array(__CLASS__, 'Handler')); assert("function_exists('output')"); assert("function_exists('pretty_path')"); }
/** * 构造函数 * @return void */ public function __construct() { //@ob_start(); register_shutdown_function(array($this, 'shutdown')); set_exception_handler(array($this, 'handleException')); set_error_handler(array($this, 'handleError'), ini_get('error_reporting')); assert_options(ASSERT_ACTIVE, true); assert_options(ASSERT_BAIL, true); assert_options(ASSERT_WARNING, true); assert_options(ASSERT_CALLBACK, array($this, 'handleAssert')); !self::$_corePath && (self::$_corePath = (include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'classes.php')); self::setAutoLoad(); }
/** * Load all basic services needed for Midgard MVC usage. This includes configuration, authorization and the component loader. */ public function load_base_services(array $local_configuration = null) { // Load the context helper and initialize first context $this->context = new midgardmvc_core_helpers_context(); $this->configuration = new midgardmvc_core_services_configuration_chain($local_configuration); if (!$this->configuration->development_mode) { // Disable assertions assert_options(ASSERT_ACTIVE, false); return; } assert_options(ASSERT_ACTIVE, true); assert_options(ASSERT_WARNING, true); assert_options(ASSERT_CALLBACK, 'midgardmvc_core_exceptionhandler::handle_assert'); }
/** * Tests turning assertion exceptions on doesn't turn assertions on in PHP 7. * * Currently the ASSERT_EXCEPTION setting doesn't activate assertions on its * own. It probably never will, but keeping this test around out of paranoia. */ public function testAssertException() { if (version_compare(PHP_VERSION, '7.0.0-dev') >= 0) { assert_options(ASSERT_ACTIVE, 0); assert_options(ASSERT_EXCEPTION, 0); // This line will be skipped. assert(false); assert_options(ASSERT_EXCEPTION, 1); // This line SHOULD be skipped. assert(false); } // If we reach this line, all is well. $this->assertTrue(TRUE); }
private function __construct($argv) { $this->argv = $argv; $this->is_phar = !empty(Phar::Running()); if ($this->is_phar) { $this->executable = $_SERVER['SCRIPT_NAME']; $this->projects_root = substr(dirname(dirname(dirname(__DIR__))), 7); $this->dir_root = 'phar://' . $this->executable; assert_options(ASSERT_ACTIVE, 0); error_reporting(0); ini_set('display_errors', 0); } else { $this->executable = $_SERVER['SCRIPT_NAME']; $this->dir_root = dirname(dirname(__DIR__)); $this->projects_root = dirname(dirname(__DIR__)); assert_options(ASSERT_ACTIVE, 1); assert_options(ASSERT_BAIL, 1); error_reporting(E_ALL); ini_set('display_errors', 1); } $configFiles = array('/etc/exakat.ini', '/etc/exakat/exakat.ini', $this->projects_root . '/config/config-default.ini', $this->projects_root . '/config/exakat.ini'); foreach ($configFiles as $id => $configFile) { if (file_exists($configFile)) { $inis[] = parse_ini_file($configFile); } else { unset($configFiles[$id]); } } $this->configFile = call_user_func_array('array_merge', $inis); if (empty($this->configFile['php'])) { $this->configFile['php'] = !isset($_SERVER['_']) ? $_SERVER['_'] : '/usr/bin/env php '; } // then read the config from the commandline (if any) $this->readCommandline(); // then read the config for the project in its folder if (isset($this->commandline['project'])) { $this->readProjectConfig($this->commandline['project']); $this->codePath = realpath($this->projects_root . '/projects/' . $this->commandline['project'] . '/code'); } else { $this->codePath = '/No/Path/To/Code'; } // build the actual config. Project overwrite commandline overwrites config, if any. $this->options = array_merge($this->defaultConfig, $this->configFile, $this->projectConfig, $this->commandline); if ($this->options['neo4j_folder'][0] !== '/') { $this->options['neo4j_folder'] = $this->projects_root . '/' . $this->options['neo4j_folder']; } $this->options['neo4j_folder'] = realpath($this->options['neo4j_folder']); $this->options['configFiles'] = $configFiles; }
public static function setupAssertions() { assert_options(ASSERT_WARNING, 0); assert_options(ASSERT_BAIL, 0); if (self::$devmode) { assert_options(ASSERT_QUIET_EVAL, 0); assert_options(ASSERT_ACTIVE, 1); assert_options(ASSERT_CALLBACK, 'coreError::devAssertHandler'); } else { assert_options(ASSERT_QUIET_EVAL, 1); // this could fail silently! assert_options(ASSERT_ACTIVE, 1); assert_options(ASSERT_CALLBACK, 'coreError::prodAssertHandler'); } }
/** * Блок автотестов. Вызов: * Config::autotest(); */ public static function autotest() { // Активируем проверку утверждений и сделаем его фоновым assert_options(ASSERT_ACTIVE, 1); assert_options(ASSERT_WARNING, 0); assert_options(ASSERT_QUIET_EVAL, 1); // Зададим callback-функцию assert_options(ASSERT_CALLBACK, 'self::_autotest'); // Проверки $tests = array('Достаем сохраненный конфиг' => 'is_array(Config::getConfig())', 'Записываем пустой конфиг' => 'is_bool(Config::setConfig( array() ))', 'Объединение с пустым конфигом' => 'Config:: mergeConfig( array() )'); echo '-=' . __CLASS__ . '=-'; foreach ($tests as $description => $test) { echo $description . (assert($test) ? ' .... OK' : ' .... False') . "\n"; } }
/** * Initialize assertion class * @return void */ public function __construct() { if (is_null(self::$rootconfig)) { $spyc = new Spyc(); self::$rootconfig = $spyc->loadFile(PlainConfig::getInstance()->getConfigDirectory() . DIRECTORY_SEPARATOR . 'root.yml'); } $this->status = self::$rootconfig['Plain']['assert_' . self::$rootconfig['Plain']['application']]; if ($this->getStatus() == self::ENABLED) { assert_options(ASSERT_ACTIVE, 1); assert_options(ASSERT_WARNING, 0); assert_options(ASSERT_BAIL, 0); assert_options(ASSERT_CALLBACK, array(__CLASS__, 'fail')); } else { assert_options(ASSERT_ACTIVE, 0); } }
/** * Kijk of een knowledge base klopt en ingeladen kan worden. * * @param string file bestandsnaam van knowledge.xml * @return object[] */ public function lint($file) { $errors = array(); $previous_assert_mode = assert_options(ASSERT_BAIL); assert_options(ASSERT_BAIL, false); set_error_handler(function ($number, $message, $file, $line) use(&$errors) { if (preg_match('/^assert\\(\\): (.+?)$/', $message, $match)) { $message = html_entity_decode($match[1]); } $errors[] = (object) compact('number', 'message', 'file', 'line'); }); $this->parse($file); assert_options(ASSERT_BAIL, $previous_assert_mode); restore_error_handler(); return $errors; }
/** * Determine whether a module is enabled. * * Will return FALSE if the given module doesn't exists. * * @param string $module Name of the module * @return bool TRUE if the given module is enabled, FALSE if not. */ public static function isModuleEnabled($module) { $moduleDir = self::getModuleDir($module); if (!is_dir($moduleDir)) { return FALSE; } if (assert_options(ASSERT_ACTIVE) && !file_exists($moduleDir . '/default-enable') && !file_exists($moduleDir . '/default-disable')) { SimpleSAML_Logger::error("Missing default-enable or default-disable file for the module {$module}"); } if (file_exists($moduleDir . '/enable')) { return TRUE; } if (!file_exists($moduleDir . '/disable') && file_exists($moduleDir . '/default-enable')) { return TRUE; } return FALSE; }