/**
  * Helper method
  *
  * @param   string name
  * @param   lang.XPClass class
  * @throws  unittest.AssertionFailedError
  */
 protected function defineInterface($name, $parents, $bytes)
 {
     if (interface_exists(xp::reflect($name), FALSE)) {
         $this->fail('Interface "' . $name . '" may not exist!');
     }
     return ClassLoader::defineInterface($name, $parents, $bytes);
 }
Пример #2
0
 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);
 }
Пример #3
0
 /**
  * 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();
 }
Пример #4
0
 /**
  * Constructor. Accepts one of the following:
  *
  * <ul>
  *   <li>The values TRUE or FALSE</li>
  *   <li>An integer - any non-zero value will be regarded TRUE</li>
  *   <li>The strings "true" and "false", case-insensitive</li>
  *   <li>Numeric strings - any non-zero value will be regarded TRUE</li>
  * </ul>
  *
  * @param   var value
  * @throws  lang.IllegalArgumentException if value is not acceptable
  */
 public function __construct($value)
 {
     if (TRUE === $value || FALSE === $value) {
         $this->value = $value;
     } else {
         if (is_int($value)) {
             $this->value = 0 !== $value;
         } else {
             if ('0' === $value) {
                 $this->value = FALSE;
             } else {
                 if (is_string($value) && ($l = strlen($value)) && strspn($value, '1234567890') === $l) {
                     $this->value = TRUE;
                 } else {
                     if (0 === strncasecmp($value, 'true', 4)) {
                         $this->value = TRUE;
                     } else {
                         if (0 === strncasecmp($value, 'false', 5)) {
                             $this->value = FALSE;
                         } else {
                             throw new IllegalArgumentException('Not a valid boolean: ' . xp::stringOf($value));
                         }
                     }
                 }
             }
         }
     }
 }
Пример #5
0
 /**
  * Export this keypair
  *
  * @param   string passphrase default NULL
  * @return  string key
  */
 public function export($passphrase = null)
 {
     if (false === openssl_pkey_export($this->_res, $out, $passphrase)) {
         throw new SecurityException('Could not export key: ' . \xp::stringOf(OpenSslUtil::getErrors()));
     }
     return $out;
 }
Пример #6
0
 /**
  * Processes cell value
  *
  * @param   var in
  * @return  var
  * @throws  lang.FormatException
  */
 public function process($in)
 {
     if (!(null === $in || is_numeric($in))) {
         throw new \lang\FormatException('Cannot format non-number ' . \xp::stringOf($in));
     }
     return $this->proceed(number_format($in, $this->decimals, $this->decimalPoint, $this->thousandsSeparator));
 }
 /**
  * Matches implementation
  * 
  * @param   var value
  * @return  bool
  */
 public function matches($value)
 {
     if (NULL === $value && $this->matchNull) {
         return TRUE;
     }
     return xp::typeof($value) == XPClass::forName($this->type)->getName();
 }
Пример #8
0
 /**
  * Processes cell value
  *
  * @param   var in
  * @return  var
  * @throws  lang.FormatException
  */
 public function process($in)
 {
     if (!$in->getClass()->isEnum()) {
         throw new FormatException('Cannot format non-enum ' . xp::stringOf($in));
     }
     return $this->proceed($in->name());
 }
 /**
  * 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();
 }
Пример #10
0
 /**
  * Creates a string representation of this object. In general, the toString 
  * method returns a string that "textually represents" this object. The result 
  * should be a concise but informative representation that is easy for a 
  * person to read. It is recommended that all subclasses override this method.
  * 
  * Per default, this method returns:
  * ```
  *   [fully-qualified-class-name] '{' [members-and-value-list] '}'
  * ```
  * 
  * Example:
  * ```
  *   lang.Object {
  *     __id => "0.43080500 1158148350"
  *   }
  * ```
  *
  * @return  string
  */
 public function toString()
 {
     if (!$this->__id) {
         $this->__id = uniqid('', true);
     }
     return \xp::stringOf($this);
 }
Пример #11
0
 /**
  * Find an entry
  *
  * @param   string name
  * @return  peer.ftp.FtpEntry entry or NULL if nothing was found
  * @throws  io.IOException in case listing fails
  * @throws  peer.ProtocolException in case listing yields an unexpected result
  */
 protected function findEntry($name)
 {
     if (NULL === ($list = $this->connection->listingOf($this->name . $name, '-ald'))) {
         return NULL;
         // Not found
     }
     // If we get more than one result and the first result ends with a
     // dot, the server ignored the "-d" option and listed the directory's
     // contents instead. In this case, replace the "." by the directory
     // name. Otherwise, we don't expect more than one result!
     $entry = $list[0];
     if (($s = sizeof($list)) > 1) {
         if ('.' === $entry[strlen($entry) - 1]) {
             $entry = substr($entry, 0, -1) . basename($name);
         } else {
             throw new ProtocolException('List "' . $this->name . $name . '" yielded ' . $s . ' result(s), expected: 1 (' . xp::stringOf($list) . ')');
         }
     }
     // Calculate base
     $base = $this->name;
     if (FALSE !== ($p = strrpos(rtrim($name, '/'), '/'))) {
         $base .= substr($name, 0, $p + 1);
     }
     return $this->connection->parser->entryFrom($entry, $this->connection, $base);
 }
 /**
  * Register an algorithm
  *
  * @param   string name
  * @param   lang.XPClass<security.password.Algorithm> impl
  * @throws  lang.IllegalArgumentException in case the given class is not an Algorithm 
  */
 public static function setAlgorithm($name, \lang\XPClass $impl)
 {
     if (!$impl->isSubclassOf('security.password.Algorithm')) {
         throw new \lang\IllegalArgumentException('Given argument is not an Algorithm class (' . \xp::stringOf($impl) . ')');
     }
     self::$algorithms[$name] = $impl;
 }
Пример #13
0
 static function __static()
 {
     self::$UNKNOWN = new self(0, 'UNKNOWN', xp::null(), xp::null());
     self::$JSON = new self(1, 'JSON', new RestJsonSerializer(), new RestJsonDeserializer());
     self::$XML = new self(2, 'XML', new RestXmlSerializer(), new RestXmlDeserializer());
     self::$FORM = new self(3, 'FORM', xp::null(), new RestFormDeserializer());
 }
 /**
  * Read a record
  *
  * @param   string[] fields if omitted, class fields are used in order of appearance
  * @return  lang.Object or NULL if end of the file is reached
  */
 public function read(array $fields = array())
 {
     if (NULL === ($values = $this->readValues())) {
         return NULL;
     }
     if (!$fields) {
         foreach ($this->class->getFields() as $f) {
             $fields[] = $f->getName();
         }
     }
     // Create an object by deserialization. This enables us to also set
     // private and protected fields as well as avoids the constructor call.
     $n = xp::reflect($this->class->getName());
     $s = 'O:' . strlen($n) . ':"' . $n . '":' . sizeof($fields) . ':{';
     foreach ($fields as $i => $name) {
         $f = $this->class->getField($name);
         switch ($f->getModifiers() & (MODIFIER_PUBLIC | MODIFIER_PROTECTED | MODIFIER_PRIVATE)) {
             case MODIFIER_PUBLIC:
                 $s .= serialize($f->getName());
                 break;
             case MODIFIER_PROTECTED:
                 $s .= serialize("*" . $f->getName());
                 break;
             case MODIFIER_PRIVATE:
                 $s .= serialize("" . $n . "" . $f->getName());
                 break;
         }
         $s .= serialize($values[$i]);
     }
     $s .= '}';
     return unserialize($s);
 }
Пример #15
0
 /**
  * Invoke match. Returns the handler's result for the first condition to 
  * match the given value. If no condition matched and no default handler
  * was installed, an exception is raised.
  *
  * @param  var $value
  * @return var
  * @throws lang.IllegalArgumentException
  */
 public function __invoke($value)
 {
     if ($this->mapping) {
         $f = $this->mapping;
         $expr = $f($value);
     } else {
         $expr = $value;
     }
     if (null === $expr) {
         $type = null;
     } else {
         $type = gettype($expr);
     }
     if (isset($this->primitive[$type])) {
         return $this->primitive[$type]($value, $this);
     } else {
         foreach ($this->instance as $conditional) {
             if ($conditional->condition->matches($expr)) {
                 $f = $conditional->handle;
                 return $f($value, $this);
             }
         }
     }
     if ($this->otherwise) {
         $f = $this->otherwise;
         return $f($value, $this);
     } else {
         throw new IllegalArgumentException('Unhandled type ' . \xp::typeOf($expr));
     }
 }
Пример #16
0
 /**
  * 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>';
 }
Пример #17
0
 /**
  * Locate a font
  *
  * @param   string font
  * @return  string
  */
 protected function locate($font)
 {
     $windows = strncasecmp(PHP_OS, 'Win', 3) === 0;
     // Compile extension list
     $extensions = ['.ttf', '.TTF'];
     if (strncasecmp($ext = substr($font, -4, 4), '.ttf', 4) === 0) {
         $font = substr($font, 0, -4);
         $extensions[] = $ext;
     }
     // Compose TTF search path
     if ($windows) {
         $search = ['.\\', getenv('WINDIR') . '\\fonts\\'];
     } else {
         $search = ['./', '/usr/X11R6/lib/X11/fonts/TrueType/', '/usr/X11R6/lib/X11/fonts/truetype/', '/usr/X11R6/lib/X11/fonts/TTF/', '/usr/share/fonts/TrueType/', '/usr/share/fonts/truetype/', '/usr/openwin/lib/X11/fonts/TrueType/'];
     }
     // Check for absolute filenames
     if (DIRECTORY_SEPARATOR === $font[0] || $windows && strlen($font) > 1 && (':' === $font[1] || '/' === $font[0])) {
         array_unshift($search, dirname($font) . DIRECTORY_SEPARATOR);
         $font = basename($font);
     }
     // Search
     foreach ($search as $dir) {
         foreach ($extensions as $ext) {
             if (file_exists($q = $dir . $font . $ext)) {
                 return $q;
             }
         }
     }
     throw new \lang\IllegalArgumentException('Could not locate font "' . $font . '[' . implode(', ', $extensions) . ']" in ' . \xp::stringOf($search));
 }
Пример #18
0
 /**
  * Matches implementation
  * 
  * @param   var value
  * @return  bool
  */
 public function matches($value)
 {
     if (null === $value && $this->matchNull) {
         return true;
     }
     return \xp::typeof($value) == \lang\XPClass::forName($this->type)->getName();
 }
 /**
  * Constructor
  *
  * @param   var stream either an io.streams.OutputStream or an io.Stream (BC)
  * @throws  lang.IllegalArgumentException when types are not met
  */
 public function __construct($stream)
 {
     $this->stream = deref($stream);
     if ($this->stream instanceof OutputStream) {
         // Already open
     } else {
         if ($this->stream instanceof Stream) {
             $this->stream->open(STREAM_MODE_WRITE);
         } else {
             throw new IllegalArgumentException('Expected either an io.streams.OutputStream or an io.Stream, have ' . xp::typeOf($this->stream));
         }
     }
     if (self::$GD_USERSTREAMS_BUG) {
         $this->writer = function ($writer, $stream, $handle) {
             ob_start();
             $r = $writer->output($handle);
             if ($r) {
                 $stream->write(ob_get_contents());
             }
             ob_end_clean();
             return $r;
         };
     } else {
         // Use output buffering with a callback method to capture the
         // image(gd|jpeg|png|...) functions' output.
         $this->writer = function ($writer, $stream, $handle) {
             ob_start(function ($data) use($stream) {
                 $stream->write($data);
             });
             $r = $writer->output($handle);
             ob_end_flush();
             return $r;
         };
     }
 }
Пример #20
0
 /**
  * Constructor
  *
  * @param   var $arg either an io.streams.OutputStream, an io.File or an io.Stream (BC)
  * @throws  lang.IllegalArgumentException when types are not met
  */
 public function __construct($arg)
 {
     if ($arg instanceof OutputStream) {
         $this->write($arg);
     } else {
         if ($arg instanceof File) {
             $this->write($arg->out());
         } else {
             if ($arg instanceof Stream) {
                 // BC
                 $this->stream = $arg;
                 $this->writer = function ($writer, $stream, $handle) {
                     ob_start();
                     if ($r = $writer->output($handle)) {
                         $stream->open(STREAM_MODE_WRITE);
                         $stream->write(ob_get_contents());
                         $stream->close();
                     }
                     ob_end_clean();
                     return $r;
                 };
             } else {
                 throw new IllegalArgumentException('Expected either an io.streams.OutputStream or an io.File, have ' . \xp::typeOf($arg));
             }
         }
     }
 }
 /**
  * Send a message
  *
  * @param   peer.mail.Message message the Message object to send
  * @return  bool success
  */
 public function send($message)
 {
     // Sanity check: Is this a message?
     if (!$message instanceof Message) {
         throw new TransportException('Can only send messages (given: ' . xp::typeOf($message) . ')', new IllegalArgumentException('Parameter message is not a Message object'));
     }
     // Sanity check: Do we have at least one recipient?
     $to = '';
     for ($i = 0, $s = sizeof($message->to); $i < $s; $i++) {
         if (!$message->to[$i] instanceof InternetAddress) {
             continue;
         }
         // Ignore!
         $to .= $message->to[$i]->toString($message->getCharset()) . ', ';
     }
     if (empty($to)) {
         throw new TransportException('No recipients defined (recipients[0]: ' . xp::typeOf($message->to[0]), new IllegalArgumentException('Recipient #0 is not an InternetAddress object'));
     }
     // Copy message and unset To / Subject. PHPs mail() function will add them
     // to the mail twice, otherwise
     $tmp = clone $message;
     unset($tmp->to);
     unset($tmp->subject);
     if (FALSE === mail(substr($to, 0, -2), QuotedPrintable::encode($message->getSubject(), $message->getCharset()), strtr($message->getBody(), array("\r\n" => "\n", "\r" => "\n")), rtrim($tmp->getHeaderString(), "\n"), $this->parameters)) {
         throw new TransportException('Could not send mail to ' . xp::stringOf($message->to[0]), new IOException('Call to mail() failed'));
     }
     return TRUE;
 }
Пример #22
0
 /**
  * Executes this check
  *
  * @param   xp.compiler.ast.Node node
  * @param   xp.compiler.types.Scope scope
  * @return  bool
  */
 public function verify(\xp\compiler\ast\Node $node, \xp\compiler\types\Scope $scope)
 {
     $a = \cast($node, 'xp.compiler.ast.AssignmentNode');
     if (!$this->isWriteable($a->variable)) {
         return ['A403', 'Cannot assign to ' . ($a->variable instanceof \lang\Generic ? nameof($a->variable) : \xp::stringOf($a->variable)) . 's'];
     }
 }
Пример #23
0
 /**
  * Set a LogCategory for tracing communication
  *
  * @param  util.log.LogCategory $cat pass NULL to stop tracing
  * @return void
  * @throws lang.IllegalArgumentException in case a of a type mismatch
  */
 public function setTrace($cat)
 {
     if (null !== $cat && !$cat instanceof LogCategory) {
         throw new IllegalArgumentException('Expected a LogCategory, have ' . \xp::typeOf($cat));
     }
     $this->cat = $cat;
 }
 /**
  * Retrieve a single bean
  *
  * @param   string name
  * @return  remote.reflect.BeanDescription or NULL if nothing is found
  */
 public function bean($name)
 {
     if (!isset($this->beans[$name])) {
         return xp::null();
     }
     return $this->beans[$name];
 }
 /**
  * Creates a string representation of this iterator
  *
  * @return  string
  */
 public function toString()
 {
     $s = $this->getClassName() . '(' . $this->_size . ")@{\n";
     for ($i = 0; $i < $this->_size; $i++) {
         $s .= '  ' . xp::stringOf($this->list[$i], '  ') . "\n";
     }
     return $s . '}';
 }
 /**
  * Creates a string representation of this object
  *
  * @return  string
  */
 public function toString()
 {
     $s = $this->getClassName() . '@(' . $this->__name . ") {\n";
     foreach (array_keys($this->__members) as $member) {
         $s .= sprintf("  [%-20s] %s\n", $member, xp::stringOf($this->__members[$member]));
     }
     return $s . '}';
 }
Пример #27
0
 /**
  * Add a Mime Part
  *
  * @param   peer.mail.MimePart part
  * @return  peer.mail.MimePart the part added
  * @throws  lang.IllegalArgumentException if part argument is not a peer.mail.MimePart
  */
 public function addPart($part)
 {
     if (!$part instanceof MimePart) {
         throw new IllegalArgumentException('Parameter part is not a peer.mail.MimePart (given: ' . \xp::typeOf($part) . ')');
     }
     $this->parts[] = $part;
     return $part;
 }
 /**
  * Creates a string representation of this object
  *
  * @return  string
  */
 public function toString()
 {
     $fields = '';
     foreach (array_keys($this->fields) as $name) {
         $fields .= sprintf("  [%-20s] %s\n", $name, xp::stringOf($this->fields[$name]));
     }
     return sprintf("%s@(name= %s) {\n%s}", $this->getClassName(), $this->className, $fields);
 }
 /**
  * Creates a string representation of this handler
  *
  * @return  string
  */
 public function toString()
 {
     $s = sprintf("%s@{\n" . "  [name               ] %s\n" . "  [identifier         ] %s\n" . "  [wrapper            ] %s\n", nameof($this), $this->name, $this->identifier, $this->wrapper ? nameof($this->wrapper) : '(null)');
     foreach (array_keys($this->values[HVAL_PERSISTENT]) as $key) {
         $s .= sprintf("  [%-20s] %s\n", $key, \xp::typeOf($this->values[$key]));
     }
     return $s . '}';
 }
Пример #30
0
 /**
  * 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;
     }
 }