invokeSafe() public static method

Invokes internal PHP function with own error handler.
public static invokeSafe ( $function, array $args, $onError ) : mixed
$args array
return mixed
Example #1
0
 /**
  * Sends email.
  * @return void
  */
 public function send(Message $mail)
 {
     $tmp = clone $mail;
     $tmp->setHeader('Subject', NULL);
     $tmp->setHeader('To', NULL);
     $parts = explode(Message::EOL . Message::EOL, $tmp->generateMessage(), 2);
     $args = array(str_replace(Message::EOL, PHP_EOL, $mail->getEncodedHeader('To')), str_replace(Message::EOL, PHP_EOL, $mail->getEncodedHeader('Subject')), str_replace(Message::EOL, PHP_EOL, $parts[1]), str_replace(Message::EOL, PHP_EOL, $parts[0]));
     if ($this->commandArgs) {
         $args[] = (string) $this->commandArgs;
     }
     $res = Nette\Utils\Callback::invokeSafe('mail', $args, function ($message) use(&$info) {
         $info = ": {$message}";
     });
     if ($res === FALSE) {
         throw new Nette\InvalidStateException("Unable to send email{$info}.");
     }
 }
 /**
  * Returns the JSON representation of a value.
  * @param  mixed
  * @param  int  accepts Json::PRETTY
  * @return string
  */
 public static function encode($value, $options = 0)
 {
     $flags = PHP_VERSION_ID >= 50400 ? JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | ($options & self::PRETTY ? JSON_PRETTY_PRINT : 0) : 0;
     if (PHP_VERSION_ID < 50500) {
         $json = Callback::invokeSafe('json_encode', array($value, $flags), function ($message) {
             // needed to receive 'recursion detected' error
             throw new JsonException($message);
         });
     } else {
         $json = json_encode($value, $flags);
     }
     if ($error = json_last_error()) {
         $message = isset(static::$messages[$error]) ? static::$messages[$error] : (PHP_VERSION_ID >= 50500 ? json_last_error_msg() : 'Unknown error');
         throw new JsonException($message, $error);
     }
     $json = str_replace(array("
", "
"), array('\\u2028', '\\u2029'), $json);
     return $json;
 }
Example #3
0
 /**
  * Create a new image from the image stream in the string.
  * @param  string
  * @param  mixed  detected image format
  * @return Image
  * @throws ImageException
  */
 public static function fromString($s, &$format = NULL)
 {
     if (!extension_loaded('gd')) {
         throw new Nette\NotSupportedException('PHP extension GD is not loaded.');
     }
     if (func_num_args() > 1) {
         trigger_error(__METHOD__ . '() second argument $format is deprecated; use finfo_buffer() instead.', E_USER_DEPRECATED);
         $format = @static::getFormatFromString($s);
     }
     return new static(Callback::invokeSafe('imagecreatefromstring', array($s), function ($message) {
         throw new ImageException($message);
     }));
 }
Example #4
0
 /**
  * Starts and initializes session data.
  * @throws Nette\InvalidStateException
  * @return void
  */
 public function start()
 {
     if (self::$started) {
         return;
     }
     $this->configure($this->options);
     $id =& $_COOKIE[session_name()];
     if (!is_string($id) || !preg_match('#^[0-9a-zA-Z,-]{22,128}\\z#i', $id)) {
         unset($_COOKIE[session_name()]);
     }
     // session_start returns FALSE on failure only sometimes
     Nette\Utils\Callback::invokeSafe('session_start', array(), function ($message) use(&$error) {
         $error = $message;
     });
     $this->response->removeDuplicateCookies();
     if ($error) {
         @session_write_close();
         // this is needed
         throw new Nette\InvalidStateException($error);
     }
     self::$started = TRUE;
     /* structure:
     			__NF: BrowserKey, Data, Meta, Time
     				DATA: section->variable = data
     				META: section->variable = Timestamp, Browser, Version
     		*/
     $nf =& $_SESSION['__NF'];
     // regenerate empty session
     if (empty($nf['Time'])) {
         $nf['Time'] = time();
         $this->regenerated = TRUE;
     }
     // browser closing detection
     $browserKey = $this->request->getCookie('nette-browser');
     if (!$browserKey) {
         $browserKey = Nette\Utils\Strings::random();
     }
     $browserClosed = !isset($nf['B']) || $nf['B'] !== $browserKey;
     $nf['B'] = $browserKey;
     // resend cookie
     $this->sendCookie();
     // process meta metadata
     if (isset($nf['META'])) {
         $now = time();
         // expire section variables
         foreach ($nf['META'] as $section => $metadata) {
             if (is_array($metadata)) {
                 foreach ($metadata as $variable => $value) {
                     if (!empty($value['B']) && $browserClosed || !empty($value['T']) && $now > $value['T'] || isset($nf['DATA'][$section][$variable]) && is_object($nf['DATA'][$section][$variable]) && (isset($value['V']) ? $value['V'] : NULL) != Nette\Reflection\ClassType::from($nf['DATA'][$section][$variable])->getAnnotation('serializationVersion')) {
                         if ($variable === '') {
                             // expire whole section
                             unset($nf['META'][$section], $nf['DATA'][$section]);
                             continue 2;
                         }
                         unset($nf['META'][$section][$variable], $nf['DATA'][$section][$variable]);
                     }
                 }
             }
         }
     }
     if ($this->regenerated) {
         $this->regenerated = FALSE;
         $this->regenerateId();
     }
     register_shutdown_function(array($this, 'clean'));
 }
Example #5
0
 /**
  * Create a new image from the image stream in the string.
  * @param  string
  * @param  mixed  detected image format
  * @return self
  * @throws ImageException
  */
 public static function fromString($s, &$format = NULL)
 {
     if (!extension_loaded('gd')) {
         throw new Nette\NotSupportedException('PHP extension GD is not loaded.');
     }
     if (func_num_args() > 1) {
         $tmp = @getimagesizefromstring($s)[2];
         // @ - strings smaller than 12 bytes causes read error
         $format = in_array($tmp, [self::JPEG, self::PNG, self::GIF], TRUE) ? $tmp : NULL;
     }
     return new static(Callback::invokeSafe('imagecreatefromstring', [$s], function ($message) {
         throw new ImageException($message);
     }));
 }
Example #6
0
 /**
  * Starts and initializes session data.
  * @throws Nette\InvalidStateException
  * @return void
  */
 public function start()
 {
     if (self::$started) {
         return;
     }
     $this->configure($this->options);
     $id = $this->request->getCookie(session_name());
     if (is_string($id) && preg_match('#^[0-9a-zA-Z,-]{22,128}\\z#i', $id)) {
         session_id($id);
     } else {
         unset($_COOKIE[session_name()]);
     }
     try {
         // session_start returns FALSE on failure only sometimes
         Nette\Utils\Callback::invokeSafe('session_start', [], function ($message) use(&$e) {
             $e = new Nette\InvalidStateException($message);
         });
     } catch (\Exception $e) {
     }
     if ($e) {
         @session_write_close();
         // this is needed
         throw $e;
     }
     self::$started = TRUE;
     /* structure:
     			__NF: BrowserKey, Data, Meta, Time
     				DATA: section->variable = data
     				META: section->variable = Timestamp, Browser
     		*/
     $nf =& $_SESSION['__NF'];
     // regenerate empty session
     if (empty($nf['Time'])) {
         $nf['Time'] = time();
         $this->regenerated = TRUE;
     }
     // browser closing detection
     $browserKey = $this->request->getCookie('nette-browser');
     if (!is_string($browserKey) || !preg_match('#^[0-9a-z]{10}\\z#', $browserKey)) {
         $browserKey = Nette\Utils\Random::generate();
     }
     $browserClosed = !isset($nf['B']) || $nf['B'] !== $browserKey;
     $nf['B'] = $browserKey;
     // resend cookie
     $this->sendCookie();
     // process meta metadata
     if (isset($nf['META'])) {
         $now = time();
         // expire section variables
         foreach ($nf['META'] as $section => $metadata) {
             if (is_array($metadata)) {
                 foreach ($metadata as $variable => $value) {
                     if (!empty($value['B']) && $browserClosed || !empty($value['T']) && $now > $value['T']) {
                         // whenBrowserIsClosed || Time
                         if ($variable === '') {
                             // expire whole section
                             unset($nf['META'][$section], $nf['DATA'][$section]);
                             continue 2;
                         }
                         unset($nf['META'][$section][$variable], $nf['DATA'][$section][$variable]);
                     }
                 }
             }
         }
     }
     if ($this->regenerated) {
         $this->regenerated = FALSE;
         $this->regenerateId();
     }
     register_shutdown_function([$this, 'clean']);
 }
Example #7
0
 /** @internal */
 public static function pcre($func, $args)
 {
     static $messages = array(PREG_INTERNAL_ERROR => 'Internal error', PREG_BACKTRACK_LIMIT_ERROR => 'Backtrack limit was exhausted', PREG_RECURSION_LIMIT_ERROR => 'Recursion limit was exhausted', PREG_BAD_UTF8_ERROR => 'Malformed UTF-8 data', 5 => 'Offset didn\'t correspond to the begin of a valid UTF-8 code point');
     $res = Callback::invokeSafe($func, $args, function ($message) use($args) {
         // compile-time error, not detectable by preg_last_error
         throw new RegexpException($message . ' in pattern: ' . implode(' or ', (array) $args[0]));
     });
     if (($code = preg_last_error()) && ($res === NULL || !in_array($func, array('preg_filter', 'preg_replace_callback', 'preg_replace')))) {
         throw new RegexpException((isset($messages[$code]) ? $messages[$code] : 'Unknown error') . ' (pattern: ' . implode(' or ', (array) $args[0]) . ')', $code);
     }
     return $res;
 }
Example #8
0
 /**
  * Create a new image from the image stream in the string.
  * @param  string
  * @param  mixed  detected image format
  * @return self
  * @throws ImageException
  */
 public static function fromString($s, &$format = NULL)
 {
     if (!extension_loaded('gd')) {
         throw new Nette\NotSupportedException('PHP extension GD is not loaded.');
     }
     if (func_num_args() > 1) {
         $format = @static::getFormatFromString($s);
         // @ suppress trigger_error
     }
     return new static(Callback::invokeSafe('imagecreatefromstring', array($s), function ($message) {
         throw new ImageException($message);
     }));
 }
Example #9
0
 /**
  * Move uploaded file to new location.
  * @param  string
  * @return self
  */
 public function move($dest)
 {
     $dir = dirname($dest);
     @mkdir($dir, 0777, TRUE);
     // @ - dir may already exist
     if (!is_dir($dir)) {
         throw new Nette\InvalidStateException("Directory '{$dir}' cannot be created. " . error_get_last()['message']);
     }
     @unlink($dest);
     // @ - file may not exists
     Nette\Utils\Callback::invokeSafe(is_uploaded_file($this->tmpName) ? 'move_uploaded_file' : 'rename', [$this->tmpName, $dest], function ($message) use($dest) {
         throw new Nette\InvalidStateException("Unable to move uploaded file '{$this->tmpName}' to '{$dest}'. {$message}");
     });
     @chmod($dest, 0666);
     // @ - possible low permission to chmod
     $this->tmpName = $dest;
     return $this;
 }
Example #10
0
	/** @internal */
	public static function pcre($func, $args)
	{
		$res = Callback::invokeSafe($func, $args, function ($message) use ($args) {
			// compile-time error, not detectable by preg_last_error
			throw new RegexpException($message . ' in pattern: ' . implode(' or ', (array) $args[0]));
		});

		if (($code = preg_last_error()) // run-time error, but preg_last_error & return code are liars
			&& ($res === NULL || !in_array($func, array('preg_filter', 'preg_replace_callback', 'preg_replace')))
		) {
			throw new RegexpException(NULL, $code, implode(' or ', (array) $args[0]));
		}
		return $res;
	}
Example #11
0
 private static function createResource($file)
 {
     if (!extension_loaded('gd')) {
         throw new NotSupportedException('PHP extension GD is not loaded.');
     }
     static $funcs = [self::JPEG => 'imagecreatefromjpeg', self::PNG => 'imagecreatefrompng', self::GIF => 'imagecreatefromgif'];
     $info = @getimagesize($file);
     // @ - files smaller than 12 bytes causes read error
     $format = $info[2];
     if (!isset($funcs[$format])) {
         throw new UnknownImageFileException(is_file($file) ? "Unknown type of file '{$file}'." : "File '{$file}' not found.");
     }
     return Callback::invokeSafe($funcs[$format], [$file], function ($message) {
         throw new ImageException($message);
     });
 }