/** * Constructor * * @param io.streams.InputStream in */ public function __construct(InputStream $in) { $this->in = Streams::readableFd($in); if (!stream_filter_append($this->in, 'convert.base64-decode', STREAM_FILTER_READ)) { throw new \io\IOException('Could not append stream filter'); } }
public function get_contents_read_returns_less_than_size() { $f = new File(Streams::readableFd(newinstance(MemoryInputStream::class, ['Test'], ['read' => function ($size = 4096) { return parent::read(min(1, $size)); }]))); $this->assertEquals('Test', FileUtil::getContents($f)); }
/** * Returns entry content * * @param io.archive.zip.ZipEntry entry * @return string */ protected function entryContent(\io\archive\zip\ZipEntry $entry) { if ($entry->isDirectory()) { return null; } else { return (string) Streams::readAll($entry->getInputStream()); } }
/** * Returns entry content; or NULL for directories * * @param io.archive.zip.ZipEntry $entry * @return string */ protected function entryContent(ZipEntry $entry) { if ($entry->isDirectory()) { return null; } else { return (string) Streams::readAll($entry->in()); } }
/** * Constructor * * @param io.streams.OutputStream out * @param int lineLength limit maximum line length */ public function __construct(OutputStream $out, $lineLength = 0) { $params = $lineLength ? ['line-length' => $lineLength, 'line-break-chars' => "\n"] : []; $this->out = Streams::writeableFd($out); if (!stream_filter_append($this->out, 'convert.base64-encode', STREAM_FILTER_WRITE, $params)) { throw new \io\IOException('Could not append stream filter'); } }
/** * Retrieve string representation of part * * @return string */ public function getData() { $bytes = Streams::readAll($this->stream); // Create headers $headers = ''; $headers .= 'Content-Disposition: form-data; name="' . $this->name . '"; filename="' . $this->filename . '"' . self::CRLF; $headers .= 'Content-Type: ' . $this->contentType . self::CRLF; $headers .= 'Content-Length: ' . strlen($bytes) . self::CRLF; // Return payload return $headers . self::CRLF . $bytes; }
/** * Assertion helper * * @param io.archive.zip.ZipArchiveReader reader * @throws unittest.AssertionFailedError */ protected function assertSecuredEntriesIn($reader) { with($it = $reader->usingPassword('secret')->iterator()); $entry = $it->next(); $this->assertEquals('password.txt', $entry->getName()); $this->assertEquals(15, $entry->getSize()); $this->assertEquals('Secret contents', (string) Streams::readAll($entry->in())); $entry = $it->next(); $this->assertEquals('very.txt', $entry->getName()); $this->assertEquals(20, $entry->getSize()); $this->assertEquals('Very secret contents', (string) Streams::readAll($entry->in())); }
public function boxResource() { $fd = Streams::readableFd(new MemoryInputStream('test')); try { Primitive::boxed($fd); } catch (IllegalArgumentException $expected) { return; } finally { fclose($fd); // Necessary, PHP will segfault otherwise } $this->fail('Expected exception not caught', null, 'lang.IllegalArgumentException'); }
/** * Returns a DOM object for this response's contents. Lazy/Cached. * * @return php.DOMDocument */ public function getDom() { if (null === $this->dom) { $this->dom = new \DOMDocument(); // HHVM blocks all external resources by default, and the .ini setting // "hhvm.libxml.ext_entity_whitelist" cannot be set via ini_set(). if (defined('HHVM_VERSION')) { @$this->dom->loadHTML(Streams::readAll($this->response->getInputStream())); } else { @$this->dom->loadHTMLFile(Streams::readableUri($this->response->getInputStream())); } } return $this->dom; }
/** @param io.streams.InputStream */ private function read($stream) { $this->stream = $stream; if ($this instanceof UriReader && !self::$GD_USERSTREAMS_BUG) { $this->reader = function ($reader, $stream) { return $reader->readImageFromUri(Streams::readableUri($stream)); }; } else { $this->reader = function ($reader, $stream) { $bytes = ''; while ($stream->available() > 0) { $bytes .= $stream->read(); } $stream->close(); return $reader->readImageFromString($bytes); }; } }
/** * Constructor * * @param io.streams.OutputStream out * @param int level default 6 * @throws lang.IllegalArgumentException if the level is not between 0 and 9 */ public function __construct(OutputStream $out, $level = 6) { if ($level < 0 || $level > 9) { throw new \lang\IllegalArgumentException('Level ' . $level . ' out of range [0..9]'); } // Write GZIP format header: // * ID1, ID2 (Identification, \x1F, \x8B) // * CM (Compression Method, 8 = deflate) // * FLG (Flags, use 0) // * MTIME (Modification time, Un*x timestamp) // * XFL (Extra flags, 2 = compressor used maximum compression) // * OS (Operating system, 255 = unknown) $out->write(pack('CCCCVCC', 0x1f, 0x8b, 8, 0, time(), 2, 255)); // Now, convert stream to file handle and append deflating filter $this->out = Streams::writeableFd($out); if (!($this->filter = stream_filter_append($this->out, 'zlib.deflate', STREAM_FILTER_WRITE, $level))) { fclose($this->out); $this->out = null; throw new \io\IOException('Could not append stream filter'); } $this->md = CRC32::digest(); }
/** * Creates a new fixture * * @param string $str * @return org.yaml.Input */ protected function newFixture($str = '') { return new FileInput(new File(Streams::readableFd(new MemoryInputStream($str)))); }
public function stream_open($path, $mode, $options, $opened_path) { parent::stream_open($path, $mode, $options, $opened_path); $this->length = parent::$streams[$this->id]->available(); return true; }
/** * Get data * * @return string */ public function content() { return Streams::readAll($this->input); }
public function load_from_default_class_loader() { $loader = new FilesIn(self::$temp); $this->assertEquals('Mustache template {{id}}', Streams::readAll($loader->load('test'))); }
/** * Runs suite * * @param string[] args * @return int exitcode */ public function run(array $args) { if (!$args) { return $this->usage(); } // Setup suite $suite = new TestSuite(); // Parse arguments $sources = new Vector(); $listener = TestListeners::$DEFAULT; $arguments = []; $colors = null; try { for ($i = 0, $s = sizeof($args); $i < $s; $i++) { if ('-v' == $args[$i]) { $listener = TestListeners::$VERBOSE; } else { if ('-q' == $args[$i]) { $listener = TestListeners::$QUIET; } else { if ('-cp' == $args[$i]) { foreach (explode(PATH_SEPARATOR, $this->arg($args, ++$i, 'cp')) as $element) { ClassLoader::registerPath($element, null); } } else { if ('-e' == $args[$i]) { $arg = ++$i < $s ? $args[$i] : '-'; if ('-' === $arg) { $sources->add(new EvaluationSource(Streams::readAll($this->in->getStream()))); } else { $sources->add(new EvaluationSource($this->arg($args, $i, 'e'))); } } else { if ('-l' == $args[$i]) { $arg = $this->arg($args, ++$i, 'l'); $class = XPClass::forName(strstr($arg, '.') ? $arg : 'xp.unittest.' . ucfirst($arg) . 'Listener'); $arg = $this->arg($args, ++$i, 'l'); if ('-?' == $arg || '--help' == $arg) { return $this->listenerUsage($class); } $output = $this->streamWriter($arg); $instance = $suite->addListener($class->newInstance($output)); // Get all @arg-annotated methods $options = []; foreach ($class->getMethods() as $method) { if ($method->hasAnnotation('arg')) { $arg = $method->getAnnotation('arg'); if (isset($arg['position'])) { $options[$arg['position']] = $method; } else { $name = isset($arg['name']) ? $arg['name'] : strtolower(preg_replace('/^set/', '', $method->getName())); $short = isset($arg['short']) ? $arg['short'] : $name[0]; $options[$name] = $options[$short] = $method; } } } $option = 0; } else { if ('-o' == $args[$i]) { if (isset($options[$option])) { $name = '#' . ($option + 1); $method = $options[$option]; } else { $name = $this->arg($args, ++$i, 'o'); if (!isset($options[$name])) { $this->err->writeLine('*** Unknown listener argument ' . $name . ' to ' . nameof($instance)); return 2; } $method = $options[$name]; } $option++; if (0 == $method->numParameters()) { $pass = []; } else { $pass = $this->arg($args, ++$i, 'o ' . $name); } try { $method->invoke($instance, $pass); } catch (TargetInvocationException $e) { $this->err->writeLine('*** Error for argument ' . $name . ' to ' . $instance->getClassName() . ': ' . $e->getCause()->toString()); return 2; } } else { if ('-?' == $args[$i] || '--help' == $args[$i]) { return $this->usage(); } else { if ('-a' == $args[$i]) { $arguments[] = $this->arg($args, ++$i, 'a'); } else { if ('-w' == $args[$i]) { $this->arg($args, ++$i, 'w'); } else { if ('--color' == substr($args[$i], 0, 7)) { $remainder = (string) substr($args[$i], 7); if (!array_key_exists($remainder, self::$cmap)) { throw new IllegalArgumentException('Unsupported argument for --color (must be <empty>, "on", "off", "auto" (default))'); } $colors = self::$cmap[$remainder]; } else { if (strstr($args[$i], '.ini')) { $sources->add(new PropertySource(new Properties($args[$i]))); } else { if (strstr($args[$i], \xp::CLASS_FILE_EXT)) { $sources->add(new ClassFileSource(new File($args[$i]))); } else { if (strstr($args[$i], '.**')) { $sources->add(new PackageSource(Package::forName(substr($args[$i], 0, -3)), true)); } else { if (strstr($args[$i], '.*')) { $sources->add(new PackageSource(Package::forName(substr($args[$i], 0, -2)))); } else { if (false !== ($p = strpos($args[$i], '::'))) { $sources->add(new ClassSource(XPClass::forName(substr($args[$i], 0, $p)), substr($args[$i], $p + 2))); } else { if (is_dir($args[$i])) { $sources->add(new FolderSource(new Folder($args[$i]))); } else { $sources->add(new ClassSource(XPClass::forName($args[$i]))); } } } } } } } } } } } } } } } } } } catch (Throwable $e) { $this->err->writeLine('*** ', $e->getMessage()); \xp::gc(); return 2; } if ($sources->isEmpty()) { $this->err->writeLine('*** No tests specified'); return 2; } // Set up suite $l = $suite->addListener($listener->newInstance($this->out)); if ($l instanceof ColorizingListener) { $l->setColor($colors); } foreach ($sources as $source) { try { $tests = $source->testCasesWith($arguments); foreach ($tests as $test) { $suite->addTest($test); } } catch (NoSuchElementException $e) { $this->err->writeLine('*** Warning: ', $e->getMessage()); continue; } catch (IllegalArgumentException $e) { $this->err->writeLine('*** Error: ', $e->getMessage()); return 2; } catch (MethodNotImplementedException $e) { $this->err->writeLine('*** Error: ', $e->getMessage(), ': ', $e->method, '()'); return 2; } } // Run it! if (0 == $suite->numTests()) { return 3; } else { $r = $suite->run(); return $r->failureCount() > 0 ? 1 : 0; } }
public function load_from_default_class_loader() { $loader = new ResourcesIn(ClassLoader::getDefault()); $this->assertEquals('Mustache template {{id}}', Streams::readAll($loader->load('com/github/mustache/unittest/template'))); }
public function getInputStreams() { $this->conn->connect(); $dir = $this->conn->rootDir()->getDir('htdocs'); for ($i = 0; $i < 2; $i++) { try { $s = $dir->getFile('index.html')->getInputStream(); $this->assertEquals("<html/>\n", Streams::readAll($s)); } catch (\io\IOException $e) { $this->fail('Round ' . ($i + 1), $e, null); } } }
public function getInputStream() { $source = 'Console::writeLine("Hello");'; $this->assertEquals($source, Streams::readAll($this->newInstance($source)->getInputStream())); }
/** * Unmarshal XML to an object * * @param xml.parser.InputSource source * @param string classname * @param [:var] inject * @return lang.Object * @throws lang.ClassNotFoundException * @throws xml.XMLFormatException * @throws lang.reflect.TargetInvocationException * @throws lang.IllegalArgumentException */ public function unmarshalFrom(InputSource $input, $classname, $inject = []) { libxml_clear_errors(); $doc = new \DOMDocument(); if (!$doc->load(Streams::readableUri($input->getStream()))) { $e = libxml_get_last_error(); throw new XMLFormatException(trim($e->message), $e->code, $input->getSource(), $e->line, $e->column); } $xpath = new XPath($doc); // Class factory based on tag name, reference to a static method which is called with // the class name and returns an XPClass instance. $class = \lang\XPClass::forName($classname); if ($class->hasAnnotation('xmlmapping', 'factory')) { if ($class->hasAnnotation('xmlmapping', 'pass')) { $factoryArgs = []; foreach ($class->getAnnotation('xmlmapping', 'pass') as $pass) { $factoryArgs[] = self::contentOf($xpath->query($pass, $doc->documentElement)); } } else { $factoryArgs = [$doc->documentElement->nodeName]; } $class = $class->getMethod($class->getAnnotation('xmlmapping', 'factory'))->invoke(null, $factoryArgs); } return self::recurse($xpath, $doc->documentElement, $class, $inject); }
public function load() { $content = 'Mustache template {{id}}'; $loader = new InMemory(['test' => $content]); $this->assertEquals($content, Streams::readAll($loader->load('test'))); }
/** * Returns a new EncapsedStream instance * * @return io.EncapsedStream */ public function newStream($contents = '', $start = 0, $length = 0) { return new EncapsedStream(new File(Streams::readableFd(new MemoryInputStream($contents))), $start, $length); }
public function is_file() { $this->assertTrue(is_file(Streams::readableUri(new MemoryInputStream('Hello')))); }
public function printStackTrace() { $out = new MemoryOutputStream(); $e = new Throwable('Test'); $e->printStackTrace(Streams::writeableFd($out)); $this->assertEquals($e->toString(), $out->getBytes()); }
public function usableInSave() { $out = new MemoryOutputStream(); // Create DOM and save it to stream $dom = new \DOMDocument(); $dom->appendChild($dom->createElement('root'))->appendChild($dom->createElement('child', 'übercoder')); $dom->save(Streams::writeableUri($out)); // Check file contents $this->assertEquals('<?xml version="1.0"?>' . "\n" . '<root><child>übercoder</child></root>', trim($out->getBytes())); }
public function creating_archive() { $contents = ['lang/Object.class.php' => '<?php class Object { }', 'lang/Type.class.php' => '<?php class Type extends Object { }']; $out = new MemoryOutputStream(); $a = new Archive(new File(Streams::writeableFd($out))); $a->open(Archive::CREATE); foreach ($contents as $filename => $bytes) { $a->addBytes($filename, $bytes); } $a->create(); $file = new File(Streams::readableFd(new MemoryInputStream($out->getBytes()))); $this->assertEntries(new Archive($file), $contents); }