/** * Connect * * @param bool reconnect default FALSE * @return bool success * @throws rdbms.SQLConnectException */ public function connect($reconnect = false) { if (is_resource($this->handle)) { return true; } // Already connected if (!$reconnect && false === $this->handle) { return false; } // Previously failed connecting $this->_obs && $this->notifyObservers(new \rdbms\DBEvent(\rdbms\DBEvent::CONNECT, $reconnect)); if ($this->flags & DB_PERSISTENT) { $this->handle = mssql_pconnect($this->dsn->getHost(), $this->dsn->getUser(), $this->dsn->getPassword()); } else { $this->handle = mssql_connect($this->dsn->getHost(), $this->dsn->getUser(), $this->dsn->getPassword()); } if (!is_resource($this->handle)) { $e = new \rdbms\SQLConnectException(trim(mssql_get_last_message()), $this->dsn); \xp::gc(__FILE__); throw $e; } \xp::gc(__FILE__); $this->_obs && $this->notifyObservers(new \rdbms\DBEvent(\rdbms\DBEvent::CONNECTED, $reconnect)); return parent::connect(); }
/** * Connect * * @param bool reconnect default FALSE * @return bool success * @throws rdbms.SQLConnectException */ public function connect($reconnect = FALSE) { if (is_resource($this->handle)) { return TRUE; } // Already connected if (!$reconnect && FALSE === $this->handle) { return FALSE; } // Previously failed connecting $this->_obs && $this->notifyObservers(new DBEvent(DBEvent::CONNECT, $reconnect)); if ($this->flags & DB_PERSISTENT) { $this->handle = sybase_pconnect($this->dsn->getHost(), $this->dsn->getUser(), $this->dsn->getPassword(), 'iso_1'); } else { $this->handle = sybase_connect($this->dsn->getHost(), $this->dsn->getUser(), $this->dsn->getPassword(), 'iso_1'); } if (!is_resource($this->handle)) { $e = new SQLConnectException(trim(sybase_get_last_message()), $this->dsn); xp::gc(__FILE__); throw $e; } xp::gc(__FILE__); $this->_obs && $this->notifyObservers(new DBEvent(DBEvent::CONNECTED, $reconnect)); return parent::connect(); }
public function gc() { trigger_error('Test'); $this->assertEquals([__FILE__ => [__LINE__ - 2 => ['Test' => ['class' => NULL, 'method' => 'trigger_error', 'cnt' => 1]]]], \xp::$errors); \xp::gc(); $this->assertEquals([], \xp::$errors); }
public function gc() { trigger_error('Test'); $this->assertEquals(array(__FILE__ => array(__LINE__ - 2 => array('Test' => array('class' => NULL, 'method' => 'trigger_error', 'cnt' => 1)))), xp::$errors); xp::gc(); $this->assertEquals(array(), xp::$errors); }
/** * Finalizes the processor. * * @return string */ public function finalize() { static $classes = array(T_VARIABLE => 'variable', T_CLASS => 'keyword', T_INTERFACE => 'keyword', T_EXTENDS => 'keyword', T_IMPLEMENTS => 'keyword', T_CATCH => 'keyword', T_THROW => 'keyword', T_TRY => 'keyword', T_NEW => 'keyword', T_FUNCTION => 'keyword', T_FOR => 'keyword', T_IF => 'keyword', T_ELSE => 'keyword', T_SWITCH => 'keyword', T_WHILE => 'keyword', T_FOREACH => 'keyword', T_RETURN => 'keyword', T_STATIC => 'modifier', T_ABSTRACT => 'modifier', T_PUBLIC => 'modifier', T_PRIVATE => 'modifier', T_PROTECTED => 'modifier', T_FINAL => 'modifier', T_DNUMBER => 'number', T_LNUMBER => 'number', T_CONSTANT_ENCAPSED_STRING => 'string', T_COMMENT => 'comment', '{' => 'bracket', '}' => 'bracket', '(' => 'bracket', ')' => 'bracket'); // Tokenize buffer $tokens = token_get_all('<?php ' . trim($this->buffer, "\r\n") . '?>'); if (!is_array($tokens) || xp::errorAt(__FILE__, __LINE__ - 1)) { $e = new FormatException('Cannot parse "' . $this->buffer . '"'); xp::gc(__FILE__); throw $e; } // Create HTML $current = NULL; $out = ''; for ($i = 1, $s = sizeof($tokens) - 1; $i < $s; $i++) { $token = $tokens[$i]; $class = isset($classes[$token[0]]) ? $classes[$token[0]] : 'default'; // Handle annotations if (is_array($token) && T_COMMENT === $token[0] && '#' === $token[1][0]) { $class = 'annotation'; } if ($current != $class) { $out .= '</span><span class="' . $class . '">'; $current = $class; } $out .= strtr(htmlspecialchars(is_array($token) ? $token[1] : $token), array("\n" => '<br/>', "\r" => '')); } // Skip leading "</span>" (7) return '</p><code>' . substr($out, 7) . ($current ? '</span>' : '') . '</code><p>'; }
/** * Constructor * * @see php://pspell_new * @param string language * @param string spelling * @param string jargon * @param string encoding * @param int mode * @throws lang.IllegalArgumentException */ public function __construct($language, $spelling = NULL, $jargon = NULL, $encoding = NULL, $mode = PSPELL_NORMAL) { if (FALSE === ($this->handle = pspell_new($language, $spelling, $jargon, $encoding, $mode))) { $e = new IllegalArgumentException('Could not create spell checker'); xp::gc(__FILE__); throw $e; } }
/** * Write a string * * @param var arg */ public function write($arg) { if (false === fwrite($this->fd, $arg)) { $e = new IOException('Could not write ' . strlen($arg) . ' bytes to ' . $this->name . ' channel'); \xp::gc(__FILE__); throw $e; } }
/** * Read image * * @param string uri * @return resource * @throws img.ImagingException */ public function readImageFromUri($uri) { if (FALSE === ($r = imagecreatefromxbm($uri))) { $e = new ImagingException('Cannot read image from "' . $uri . '"'); xp::gc(__FILE__); throw $e; } return $r; }
/** * Read image * * @param string uri * @return resource * @throws img.ImagingException */ public function readImageFromUri($uri) { if (false === ($r = imagecreatefrompng($uri))) { $e = new \img\ImagingException('Cannot read image from "' . $uri . '"'); \xp::gc(__FILE__); throw $e; } return $r; }
/** * Read a string * * @param int limit default 8192 * @return string */ public function read($limit = 8192) { if (false === ($bytes = fread($this->fd, $limit))) { $e = new IOException('Could not read ' . $limit . ' bytes from ' . $this->name . ' channel'); \xp::gc(__FILE__); throw $e; } return $bytes; }
/** * Read image via imagecreatefromstring() * * @param string bytes * @return resource * @throws img.ImagingException */ public function readImageFromString($bytes) { if (FALSE === ($r = imagecreatefromstring($bytes))) { $e = new ImagingException('Cannot read image'); xp::gc(__FILE__); throw $e; } return $r; }
/** * Read image via imagecreatefromgif() * * @param string uri * @return resource * @throws img.ImagingException */ protected function readImage0($uri) { if (FALSE === ($r = imagecreatefromgif($uri))) { $e = new ImagingException('Cannot read image'); xp::gc(__FILE__); throw $e; } return $r; }
/** * / * * @param var other * @return math.BigNum */ public function divide($other) { if (NULL === ($r = bcdiv($this->num, $other instanceof self ? $other->num : $other))) { $e = key(xp::$errors[__FILE__][__LINE__ - 1]); xp::gc(__FILE__); throw new IllegalArgumentException($e); } return new self($r); }
/** * Crypt a given plain-text string * * @param string plain * @param string salt * @return string */ public function crypt($plain, $salt) { $crypted = crypt($plain, $salt); if (strlen($crypted) < 13) { // Crypted contains error $message = key(@\xp::$errors[__FILE__][__LINE__ - 3]); \xp::gc(__FILE__); throw new CryptoException('Failed to crypt: ' . $message); } \xp::gc(__FILE__); return $crypted; }
/** * Helper method * * @param string xml * @return php.DOMDocument * @throws xml.XMLFormatException if the given XML is not well-formed or unparseable */ protected function loadXML($xml) { $doc = new DOMDocument(); if (!$doc->loadXML($xml)) { $errors = libxml_get_errors(); libxml_clear_errors(); $e = new XMLFormatException(rtrim($errors[0]->message), $errors[0]->code, $errors[0]->file, $errors[0]->line, $errors[0]->column); xp::gc(__FILE__); throw $e; } return $doc; }
/** * Creates the socket instance * * @param string socket default NULL * @return peer.Socket */ public function newInstance($socket = null) { if (null === $socket) { $socket = $this->locate(); } if (!($fd = fopen($socket, 'r+'))) { $e = new IOException('Cannot open pipe "' . $socket . '"'); \xp::gc(__FILE__); throw $e; } return new Socket(null, null, $fd); }
public function lazyRead() { $p = new Properties('@@does-not-exist.ini@@'); // This cannot be done via expect annotation because it would also catch if // an exception was thrown from util.Properties' constructor. We explicitely // want the exception to be thrown later on! try { $p->readString('section', 'key'); $this->fail('Expected exception not thrown', null, 'io.IOException'); } catch (IOException $expected) { \xp::gc(); } }
/** * Returns next token * * @return string */ public function nextToken() { $pos = $this->pos; $len = $this->len; $bytes = $this->bytes; while ($pos < $len) { $c = $bytes[$pos]; if ('"' === $c) { $string = ''; $o = $pos + 1; do { $end = strcspn($bytes, '"\\', $o) + $o; if ($end < $len) { if ('\\' === $bytes[$end]) { $string .= substr($bytes, $o, $end - $o) . $this->escaped($end, $len, $consumed); $o = $end + $consumed; continue; } else { if ($c === $bytes[$end]) { $string .= substr($bytes, $o, $end - $o); $encoded = iconv($this->encoding, \xp::ENCODING, $string); if (false === $encoded) { $e = new FormatException('Illegal ' . $this->encoding . ' encoding'); \xp::gc(__FILE__); throw $e; } $this->pos = ++$end; return [true, $encoded]; } } } throw new FormatException('Unclosed string ' . $string); } while ($o); } else { if (1 === strspn($c, '{[:]},')) { $this->pos = $pos + 1; return $c; } else { if (1 === strspn($c, " \r\n\t")) { $pos += strspn($bytes, " \r\n\t", $pos); continue; } else { $span = strcspn($bytes, "{[:]},\" \r\n\t", $pos); $this->pos = $pos + $span; return substr($bytes, $pos, $span); } } } } return null; }
/** @return void */ public function rewind() { if (null === $this->handle) { if (!is_resource($handle = opendir($this->base->asFolder()->getURI()))) { $e = new IOException('Cannot open folder ' . $this->base); \xp::gc(__FILE__); throw $e; } $this->handle = $handle; } else { rewinddir($this->handle); } $this->next(); }
static function __static() { self::$instance = new self(); // Workaround for bugs in older PHP versions, see MD5HexHashImplementation's // class apidoc for an explanation. Earlier versions returned LONG_MAX for // hex numbers larger than LONG_MAX. Use 2^64 + 1 as hex literal and see if // it's "truncated", using the slower hexdec(md5()) implementation then. if (PHP_INT_MAX === @0x20c49ba5e35423 || 0 === "0x1" + 0) { \xp::gc(__FILE__, __LINE__ - 1); $impl = \lang\XPClass::forName('util.collections.MD5HexHashImplementation')->newInstance(); } else { $impl = new MD5HashImplementation(); } self::$instance->setImplementation($impl); }
/** * Retrieve an ImageInfo object from a file * * @param io.File file * @return img.util.ImageInfo * @throws img.ImagingException in case extracting information from image file fails */ public static function fromFile($file) { if (FALSE === ($data = getimagesize($file->getURI(), $segments))) { $e = new ImagingException('Cannot load image information from ' . $file->getURI()); xp::gc(__FILE__); throw $e; } with($i = new ImageInfo()); $i->width = $data[0]; $i->height = $data[1]; $i->type = $data[2]; $i->mime = image_type_to_mime_type($data[2]); isset($data['bits']) && ($i->bits = $data['bits']); isset($data['channels']) && ($i->channels = $data['channels']); $i->segments = $segments; return $i; }
/** * Performs the run and returns the result * * @return util.profiling.Outcome */ public function perform() { $reflect = $this->measurable->method()->_reflect; $arguments = $this->measurable->arguments(); \xp::gc(); $t = (new Timer())->start(); try { for ($i = 0; $i < $this->times; $i++) { $result = $reflect->invokeArgs($this->measurable, $arguments); } return new Result($this, $t->elapsedTime(), $result); } catch (Throwable $e) { return new Exception($this, $t->elapsedTime(), $e); } catch (\Exception $e) { return new Exception($this, $t->elapsedTime(), new IllegalStateException($e->getMessage())); } }
/** * Creates a new timezone from a given name. * * @param string timezone name or NULL to use default timezone * @throws lang.IllegalArgumentException if timezone is unknown */ public function __construct($tz) { switch (TRUE) { case is_string($tz): $this->tz = timezone_open($tz); break; case is_null($tz): $this->tz = timezone_open(date_default_timezone_get()); break; case $tz instanceof DateTimeZone: $this->tz = $tz; } if (!$this->tz instanceof DateTimeZone) { $e = new IllegalArgumentException('Invalid timezone identifier given: "' . $tz . '"'); xp::gc(__FILE__); throw $e; } }
/** * Constructor * * @param var arg either a string or an int * @param string charset default NULL */ public function __construct($arg, $charset = NULL) { if (is_int($arg)) { $this->buffer = iconv('UCS-4BE', 'utf-8', pack('N', $arg)); return; } $charset = strtoupper($charset ? $charset : iconv_get_encoding('input_encoding')); // Convert the input to internal encoding $this->buffer = iconv($charset, 'utf-8', $arg); if (xp::errorAt(__FILE__, __LINE__ - 1)) { $message = key(xp::$errors[__FILE__][__LINE__ - 2]); xp::gc(__FILE__); throw new FormatException($message . ($charset == 'utf-8' ? ' with charset ' . $charset : $message . ' while converting input from ' . $charset . ' to ' . 'utf-8')); } if (1 != ($l = iconv_strlen($this->buffer, 'utf-8'))) { throw new IllegalArgumentException('Given argument is too long (' . $l . ')'); } }
/** * Read from a file * * @deprecated Use img.io.MetaDataReader instead * @param io.File file * @param var default default void what should be returned in case no data is found * @return img.util.IptcData * @throws lang.FormatException in case malformed meta data is encountered * @throws lang.ElementNotFoundException in case no meta data is available * @throws img.ImagingException in case reading meta data fails */ public static function fromFile(File $file) { if (FALSE === getimagesize($file->getURI(), $info)) { $e = new ImagingException('Cannot read image information from ' . $file->getURI()); xp::gc(__FILE__); throw $e; } if (!isset($info['APP13'])) { if (func_num_args() > 1) { return func_get_arg(1); } throw new ElementNotFoundException('Cannot get IPTC information from ' . $file->getURI() . ' (no APP13 marker)'); } if (!($iptc = iptcparse($info['APP13']))) { throw new FormatException('Cannot parse IPTC information from ' . $file->getURI()); } // Parse creation date if (3 == sscanf(@$iptc['2#055'][0], '%4d%2d%d', $year, $month, $day)) { $created = Date::create($year, $month, $day, 0, 0, 0); } else { $created = NULL; } with($i = new self()); $i->setTitle(@$iptc['2#005'][0]); $i->setUrgency(@$iptc['2#010'][0]); $i->setCategory(@$iptc['2#015'][0]); $i->setSupplementalCategories(@$iptc['2#020']); $i->setKeywords(@$iptc['2#025']); $i->setSpecialInstructions(@$iptc['2#040'][0]); $i->setDateCreated($created); $i->setAuthor(@$iptc['2#080'][0]); $i->setAuthorPosition(@$iptc['2#085'][0]); $i->setCity(@$iptc['2#090'][0]); $i->setState(@$iptc['2#095'][0]); $i->setCountry(@$iptc['2#101'][0]); $i->setOriginalTransmissionReference(@$iptc['2#103'][0]); $i->setHeadline(@$iptc['2#105'][0]); $i->setCredit(@$iptc['2#110'][0]); $i->setSource(@$iptc['2#115'][0]); $i->setCopyrightNotice(@$iptc['2#116'][0]); $i->setCaption(@$iptc['2#120'][0]); $i->setWriter(@$iptc['2#122'][0]); return $i; }
/** Iterate over all entries */ public function getIterator() : \Traversable { if (null === $this->handle) { if (!is_resource($handle = opendir($this->base->asFolder()->getURI()))) { $e = new IOException('Cannot open folder ' . $this->base); \xp::gc(__FILE__); throw $e; } $this->handle = $handle; } else { rewinddir($this->handle); } while (false !== ($entry = readdir($this->handle))) { if ('.' === $entry || '..' === $entry) { continue; } (yield $entry => new Path($this->base, $entry)); } }
/** * Constructor. Creates a new date object through either a * <ul> * <li>integer - interpreted as timestamp</li> * <li>string - parsed into a date</li> * <li>php.DateTime object - will be used as is</li> * <li>NULL - creates a date representing the current instance</li> * </ul> * * Timezone assignment works through these rules: * . If the time is given as string and contains a parseable timezone identifier * that one is used. * . If no timezone could be determined, the timezone given by the * second parameter is used * . If no timezone has been given as second parameter, the system's default * timezone is used. * * @param var in default NULL either a string or a Unix timestamp or DateTime object, defaulting to now * @param string timezone default NULL string of timezone * @throws lang.IllegalArgumentException in case the date is unparseable */ public function __construct($in = NULL, TimeZone $timezone = NULL) { if ($in instanceof DateTime) { $this->date = $in; } else { if ((string) (int) $in === (string) $in) { // Specially mark timestamps for parsing (we assume here that strings // containing only digits are timestamps) $this->date = date_create('@' . $in, timezone_open('UTC')); date_timezone_set($this->date, $timezone ? $timezone->getHandle() : timezone_open(date_default_timezone_get())); } else { $this->date = $timezone ? date_create($in, $timezone->getHandle()) : date_create($in); if (FALSE === $this->date || xp::errorAt(__FILE__, __LINE__ - 1)) { $e = new IllegalArgumentException('Given argument is neither a timestamp nor a well-formed timestring: ' . xp::stringOf($in)); xp::gc(__FILE__); throw $e; } } } }
/** * Connect * * @param bool reconnect default FALSE * @return bool success * @throws rdbms.SQLConnectException */ public function connect($reconnect = false) { if (is_resource($this->handle)) { return true; } // Already connected if (!$reconnect && false === $this->handle) { return false; } // Previously failed connecting $this->_obs && $this->notifyObservers(new \rdbms\DBEvent(\rdbms\DBEvent::CONNECT, $reconnect)); // Build connection string. In PostgreSQL, a dbname must _always_ // be specified. $cs = 'dbname=' . $this->dsn->getDatabase(); if ($this->dsn->getHost()) { $cs .= ' host=' . $this->dsn->getHost(); } if ($this->dsn->getPort()) { $cs .= ' port=' . $this->dsn->getPort(); } if ($this->dsn->getUser()) { $cs .= ' user='******' password=' . $this->dsn->getPassword(); } if ($this->flags & DB_PERSISTENT) { $this->handle = pg_pconnect($cs); } else { $this->handle = pg_connect($cs); } if (!is_resource($this->handle)) { $e = new \rdbms\SQLConnectException(rtrim(pg_last_error()), $this->dsn); \xp::gc(__FILE__); throw $e; } $this->_obs && $this->notifyObservers(new \rdbms\DBEvent(\rdbms\DBEvent::CONNECTED, $reconnect)); return true; }
/** * Define class from a given name and source * * @param string type * @param string class * @param var parent either a string or a lang.XPClass * @param string src * @param string[] imports * @return lang.XPClass */ protected static function define($type, $class, $parent, $src, array $imports = []) { $emitter = self::emitter(); $emitter->clearMessages(); $syntax = Syntax::forName('xp'); $class = 'Source' . $class; $scope = new TaskScope(new CompilationTask(new FileSource(new File(__FILE__), $syntax), new NullDiagnosticListener(), new FileManager(), $emitter)); // Parent class if ($parent instanceof XPClass) { $extends = (new XPClass(self::class))->getPackage()->getName() . '.' . $parent->getName(); $scope->addResolved($extends, new TypeReflection($parent)); $scope->addTypeImport($extends); } else { $extends = $parent; } // Emit $r = $emitter->emit($syntax->parse(new MemoryInputStream(implode("\n", $imports) . ' public ' . $type . ' ' . $class . ' ' . ($extends ? ' extends ' . $extends : '') . $src), $class), $scope); \xp::gc(); // DEBUG $r->writeTo(\util\cmd\Console::$out->getStream()); $r->executeWith([]); return XPClass::forName($r->type()->name()); }
/** * Write a string to the socket * * @param string str * @return int bytes written * @throws peer.SocketException in case of an error */ public function write($str) { if (false === ($bytesWritten = fputs($this->_sock, $str, $len = strlen($str)))) { $e = new SocketException('Write of ' . $len . ' bytes to socket failed: ' . $this->getLastError()); \xp::gc(__FILE__); throw $e; } return $bytesWritten; }