public function Extract($zn, $to, $index = array(-1))
 {
     $ok = 0;
     $zip = @fopen($zn, 'rb');
     if (!$zip) {
         return -1;
     }
     $cdir = $this->ReadCentralDir($zip, $zn);
     $pos_entry = $cdir['offset'];
     if (!is_array($index)) {
         $index = array($index);
     }
     for ($i = 0; $index[$i]; $i++) {
         if (intval($index[$i]) != $index[$i] || $index[$i] > $cdir['entries']) {
             return -1;
         }
     }
     $re = 0;
     for ($i = 0; $i < $cdir['entries']; $i++) {
         @fseek($zip, $pos_entry);
         $header = $this->ReadCentralFileHeaders($zip);
         $header['index'] = $i;
         $pos_entry = ftell($zip);
         @rewind($zip);
         fseek($zip, $header['offset']);
         if (in_array("-1", $index) || in_array($i, $index)) {
             $stat[$header['filename']] = $this->ExtractFile($header, $to, $zip);
         }
         $re = $stat[$header['filename']];
     }
     fclose($zip);
     return $re;
 }
Exemple #2
0
 public function dump(\Twig_Environment $env, $context)
 {
     if (!$env->isDebug()) {
         return;
     }
     if (2 === func_num_args()) {
         $vars = array();
         foreach ($context as $key => $value) {
             if (!$value instanceof \Twig_Template) {
                 $vars[$key] = $value;
             }
         }
         $vars = array($vars);
     } else {
         $vars = func_get_args();
         unset($vars[0], $vars[1]);
     }
     $dump = fopen('php://memory', 'r+b');
     $dumper = new HtmlDumper($dump);
     foreach ($vars as $value) {
         $dumper->dump($this->cloner->cloneVar($value));
     }
     rewind($dump);
     return stream_get_contents($dump);
 }
function updateIndex($lang, $file)
{
    $fileData = readFileData($file);
    $filename = $file->getPathName();
    list($filename) = explode('.', $filename);
    $path = $filename . '.html';
    $id = str_replace($lang . '/', '', $filename);
    $id = str_replace('/', '-', $id);
    $id = trim($id, '-');
    $url = implode('/', array(ES_URL, ES_INDEX, $lang, $id));
    $data = array('contents' => $fileData['contents'], 'title' => $fileData['title'], 'url' => $path);
    $data = json_encode($data);
    $size = strlen($data);
    $fh = fopen('php://memory', 'rw');
    fwrite($fh, $data);
    rewind($fh);
    echo "Sending request:\n\tfile: {$file}\n\turl: {$url}\n";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_PUT, true);
    curl_setopt($ch, CURLOPT_INFILE, $fh);
    curl_setopt($ch, CURLOPT_INFILESIZE, $size);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    $metadata = curl_getinfo($ch);
    if ($metadata['http_code'] > 400) {
        echo "[ERROR] Failed to complete request.\n";
        var_dump($response);
        exit(2);
    }
    curl_close($ch);
    fclose($fh);
    echo "Sent {$file}\n";
}
Exemple #4
0
 private function getMockFunctions()
 {
     $functions = $this->getMock('FtpLib\\Functions', array('connect', 'ssl_connect', 'login', 'pasv', 'fput', 'delete', 'mkdir', 'chdir', 'fget', 'rmdir', 'nlist', 'size', 'close'));
     $functions->expects($this->any())->method('connect')->will($this->returnValue(true));
     $functions->expects($this->any())->method('ssl_connect')->will($this->returnValue(true));
     $functions->expects($this->any())->method('login')->will($this->returnValue(true));
     $functions->expects($this->any())->method('pasv')->will($this->returnValue(true));
     $functions->expects($this->any())->method('fput')->will($this->returnValue(true));
     $functions->expects($this->any())->method('delete')->will($this->returnValue(true));
     $functions->expects($this->any())->method('mkdir')->will($this->returnValue(true));
     $functions->expects($this->any())->method('chdir')->will($this->returnValue(true));
     $functions->expects($this->any())->method('chdir')->will($this->returnValue(true));
     $functions->expects($this->any())->method('rmdir')->will($this->returnValue(true));
     $functions->expects($this->any())->method('close')->will($this->returnValue(true));
     $functions->expects($this->any())->method('size')->will($this->returnValue(1));
     $functions->expects($this->any())->method('nlist')->will($this->returnCallback(function () {
         return array('filename1', 'filename2');
     }));
     $functions->expects($this->any())->method('fget')->will($this->returnCallback(function ($ftp_stream, $handle, $remote_file, $mode) {
         $tempHandle = fopen('php://temp', 'w+');
         fwrite($tempHandle, 'foo', strlen('foo'));
         rewind($tempHandle);
         $handle = $tempHandle;
         // AFAIK this doesn't work. PHP clones the parameters and cannot use references
         return true;
     }));
     return $functions;
 }
 /**
  * This method creates a new resource, and it seeds
  * the resource with lorem ipsum text. The returned
  * resource is readable, writable, and seekable.
  *
  * @param string $mode
  *
  * @return resource
  */
 public function resourceFactory($mode = 'r+')
 {
     $stream = fopen('php://temp', $mode);
     fwrite($stream, $this->text);
     rewind($stream);
     return $stream;
 }
Exemple #6
0
 function extract_file($zn, $to, $index = array(-1))
 {
     $ok = 0;
     $zip = @fopen($zn, 'rb');
     if (!$zip) {
         return -1;
     }
     $cdir = $this->rc_dir($zip, $zn);
     $pos_entry = $cdir['offset'];
     if (!is_array($index)) {
         $index = array($index);
     }
     for ($i = 0; isset($index[$i]); $i++) {
         if (intval($index[$i]) != $index[$i] || $index[$i] > $cdir['entries']) {
             return -1;
         }
     }
     for ($i = 0; $i < $cdir['entries']; $i++) {
         @fseek($zip, $pos_entry);
         $header = $this->rcf_header($zip);
         $header['index'] = $i;
         $pos_entry = ftell($zip);
         @rewind($zip);
         fseek($zip, $header['offset']);
         if (in_array("-1", $index) || in_array($i, $index)) {
             $stat[$header['filename']] = $this->uncompress($header, $to, $zip);
         }
     }
     fclose($zip);
     return $stat;
 }
 public static function createTmpFile($data)
 {
     $tmp_file = tmpfile();
     fwrite($tmp_file, $data);
     rewind($tmp_file);
     return $tmp_file;
 }
Exemple #8
0
 /**
  * Generates a CSV string from given array data
  *
  * @param array $data
  *
  * @throws \RuntimeException
  *
  * @return string
  */
 public function generate(array $data)
 {
     $fileHandle = fopen('php://temp', 'w');
     if (!$fileHandle) {
         throw new \RuntimeException("Cannot open temp file handle (php://temp)");
     }
     if (!is_array($data[0])) {
         $data = [$data];
     }
     $tmpPlaceholder = 'MJASCHEN_COLLMEX_WORKAROUND_PHP_BUG_43225_' . time();
     foreach ($data as $line) {
         // workaround for PHP bug 43225: temporarily insert a placeholder
         // between a backslash directly followed by a double-quote (for
         // string field values only)
         array_walk($line, function (&$item) use($tmpPlaceholder) {
             if (!is_string($item)) {
                 return;
             }
             $item = preg_replace('/(\\\\+)"/m', '$1' . $tmpPlaceholder . '"', $item);
         });
         fputcsv($fileHandle, $line, $this->delimiter, $this->enclosure);
     }
     rewind($fileHandle);
     $csv = stream_get_contents($fileHandle);
     fclose($fileHandle);
     // remove the temporary placeholder from the final CSV string
     $csv = str_replace($tmpPlaceholder, '', $csv);
     return $csv;
 }
 /**
  * A function to encapsulate rest based calls using the curl library.
  * 
  * @params $url      - OK to have ?foo=bar
  * @params $method   - GET/PUT/POST/DELETE
  * @params $payload  - data to send in if PUT/POST
  * @return array($response_code=>$data) - the function does NOT format response data.
  */
 public function restCall($endpoint, $method = 'GET', $payload = null, $headers = null)
 {
     if (empty($endpoint)) {
         return array(ResponseCodes::MISSING_PARAM => 'Missing server endpoint. This is the URL you intended to call and it was empty.');
     }
     $verifySSL = get_cfg_var('environment') == 'production' ? true : false;
     $curl = curl_init();
     curl_setopt($curl, CURLOPT_URL, $endpoint);
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
     curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $verifySSL);
     /*
      * Set the header to json since we will pass json out for all calls.
      */
     curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
     /*
      * Set any headers we were passed. We support a string or an array of strings.
      */
     if (!empty($headers)) {
         if (is_array($headers)) {
             curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
         } else {
             curl_setopt($curl, CURLOPT_HTTPHEADER, array($headers));
         }
     }
     /*
      * Default method is GET
      */
     $method = empty($method) ? 'GET' : strtoupper($method);
     /*
      * Based on the method passed in, we need to set our data
      */
     if ($method == 'POST') {
         curl_setopt($curl, CURLOPT_POST, TRUE);
         curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
     }
     if ($method == 'PUT') {
         $fh = fopen('php://memory', 'w+');
         fwrite($fh, $payload);
         rewind($fh);
         curl_setopt($curl, CURLOPT_INFILE, $fh);
         curl_setopt($curl, CURLOPT_INFILESIZE, strlen($payload));
         curl_setopt($curl, CURLOPT_PUT, TRUE);
     }
     if ($method == 'DELETE') {
         curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
         if (!empty($payload)) {
             curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
         }
     }
     /*
      * Execute the request
      */
     $data = trim(curl_exec($curl));
     $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
     @fclose($fh);
     if (preg_match('/^({|\\[)/', $data) && preg_match('/(}|\\])$/m', $data)) {
         $data = json_encode($data, true);
     }
     return array($code => $data);
 }
 public static function dom($stream)
 {
     rewind($stream);
     $actual = stream_get_contents($stream);
     $html = DOMDocument::loadHTML($actual);
     return simplexml_import_dom($html);
 }
	function rewind()
	{
		if (!$this->fp) return;
		rewind($this->fp);
		$this->rowno = 0;
		$this->next();
	}
 public function testDoWrite()
 {
     $output = new StreamOutput($this->stream);
     $output->writeln('foo');
     rewind($output->getStream());
     $this->assertEquals('foo' . PHP_EOL, stream_get_contents($output->getStream()), '->doWrite() writes to the stream');
 }
Exemple #13
0
 /**
  * Resets the input stream.
  */
 public function reset()
 {
     if (!is_resource($this->_stream)) {
         throw new Opl_Stream_Exception('Input stream is not opened.');
     }
     rewind($this->_stream);
 }
 /**
  * 记录本次生成后的最大id,下次从这个id开始生成
  * @param $id
  * @return bool
  */
 public function logMaxIdForThisTime($id)
 {
     rewind($this->logHandler);
     $byte = fwrite($this->logHandler, $id);
     fflush($this->logHandler);
     return $byte > 0;
 }
 public function RawAction()
 {
     $dataUriRegex = "/data:image\\/([\\w]*);([\\w]*),/i";
     //running a regex against a data uri might be slow.
     //Streams R fun.
     //  To avoid lots of processing before needed, copy just the first bit of the incoming data stream to a variable for checking.  rewind the stream after.  Part of the data will be MD5'd for storage.
     // note for
     $body = $this->detectRequestBody();
     $tempStream = fopen('php://temp', 'r+');
     stream_copy_to_stream($body, $tempStream, 500);
     rewind($tempStream);
     $uriHead = stream_get_contents($tempStream);
     $netid = isset($_SERVER['NETID']) ? $_SERVER['NETID'] : "notSet";
     $filename = $netid;
     $matches = array();
     // preg_match_all returns number of matches.
     if (0 < preg_match_all($dataUriRegex, $uriHead, $matches)) {
         $extension = $matches[1][0];
         $encoding = $matches[2][0];
         $start = 1 + strpos($uriHead, ",");
         $imageData = substr($uriHead, $start);
         // THERES NO ARRAY TO STRING CAST HERE PHP STFU
         $filename = (string) ("./cache/" . $filename . "-" . md5($imageData) . "." . $extension);
         $fileHandle = fopen($filename, "c");
         stream_filter_append($fileHandle, 'convert.base64-decode', STREAM_FILTER_WRITE);
         stream_copy_to_stream($body, $fileHandle, -1, $start);
     }
 }
Exemple #16
0
 /**
  * Lets the browser render an image file
  * @param String $path The path to the image file
  * @param String $timestamp Cache timestamp - if not provided, this will have to be found out (at the cost of disk access)
  * @param String $mime The image mimetype - if not provided, this will have to be found out (at the cost of disk access)
  * @return Void
  */
 public function show($path, $timestamp = null, $mime = null)
 {
     $headers = function_exists('apache_request_headers') ? apache_request_headers() : array();
     if (is_null($timestamp)) {
         $timestamp = $this->_readTimestampFromFile($path);
     }
     if (is_null($mime)) {
         $mime = $this->_readMimeTypeFromFile($path);
     }
     header("Content-Type: {$mime}");
     header("Cache-Control: maxage=" . 24 * 60 * 60 . ', must-revalidate');
     //In seconds
     header("Pragma: public");
     // Checking if the client is validating his cache and if it is current.
     if (isset($headers['If-Modified-Since']) && strtotime($headers['If-Modified-Since']) == $timestamp) {
         // Client's cache IS current, so we just respond '304 Not Modified'.
         header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $timestamp) . ' GMT', true, 304);
     } else {
         // Image not cached or cache outdated, we respond '200 OK' and output the image.
         header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $timestamp) . ' GMT', true, 200);
         header('Content-Length: ' . filesize($path));
         $resource = fopen($path, 'rb');
         rewind($resource);
         fpassthru($resource);
         fclose($resource);
     }
 }
 function parseFile(&$file)
 {
     $fp =& $file->getRawFile();
     rewind($fp);
     // easiest to grab the file as a single string and use the (natively compiled) preg stuff
     $contents = fread($fp, $file->getFileSize());
     $errors = array();
     $entries = array();
     /* preg_match_all chokes on especially large inputs ... we have to do it the hard way
     		if (! preg_match_all('!<Placemark[^>]*>.*?</Placemark>!s', $contents, $matches))
     			return array( array('No <Placemark> tags found'), NULL );
     */
     $startOffset = 0;
     $matches = array(array());
     while (($startOffset = stripos($contents, "<placemark", $startOffset)) !== FALSE) {
         $endOffset = stripos($contents, "</placemark>", $startOffset);
         if ($endOffset != FALSE) {
             $placemarkText = substr($contents, $startOffset, $endOffset - $startOffset + 12);
             array_push($matches[0], $placemarkText);
             $startOffset = $endOffset + 12;
         }
     }
     foreach ($matches[0] as $placemarkText) {
         try {
             $entries[] =& $this->_makeNewEntry($placemarkText);
         } catch (Exception $e) {
             array_push($errors, $e->getMessage());
         }
     }
     if ($errors) {
         return array($errors, NULL);
     }
     return array(NULL, &$entries);
 }
 public function test5Transactions()
 {
     $inputFile = fopen('php://memory', 'w+');
     $outputFile = fopen('php://memory', 'w+');
     $csv = array(array('AMOUNT' => 100, 'OPERATIONTYPE' => 'payment', 'CARDCODE' => '5555556778250000', 'CARDVALIDITYDATE' => $this->tools->getFutureValidityDate(), 'CARDCVV' => '123', 'CARDFULLNAME' => 'John Doe', 'ORDERID' => 'order_' . time(), 'CLIENTIDENT' => 'john.doe', 'CLIENTEMAIL' => 'john.doe42', 'CLIENTEMAIL' => '*****@*****.**', 'DESCRIPTION' => 'Test', 'CLIENTUSERAGENT' => 'firefox', 'CLIENTIP' => '1.2.3.4', 'VERSION' => '2.0'), array('AMOUNT' => 100, 'OPERATIONTYPE' => 'payment', 'CARDCODE' => '5555554530114002', 'CARDVALIDITYDATE' => $this->tools->getFutureValidityDate(), 'CARDCVV' => '123', 'CARDFULLNAME' => 'John Doe', 'ORDERID' => 'order_' . time(), 'CLIENTIDENT' => 'john.doe', 'CLIENTEMAIL' => 'john.doe42', 'CLIENTEMAIL' => '*****@*****.**', 'DESCRIPTION' => 'Test', 'CLIENTUSERAGENT' => 'firefox', 'CLIENTIP' => '1.2.3.4', 'VERSION' => '2.0'), array('AMOUNT' => 100, 'OPERATIONTYPE' => 'payment', 'CARDCODE' => '', 'CARDVALIDITYDATE' => $this->tools->getFutureValidityDate(), 'CARDCVV' => '123', 'CARDFULLNAME' => 'John Doe', 'ORDERID' => 'order_' . time(), 'CLIENTIDENT' => 'john.doe', 'CLIENTEMAIL' => 'john.doe42', 'CLIENTEMAIL' => '*****@*****.**', 'DESCRIPTION' => 'Test', 'CLIENTUSERAGENT' => 'firefox', 'CLIENTIP' => '1.2.3.4', 'VERSION' => '2.0'), array('AMOUNT' => 100, 'OPERATIONTYPE' => 'payment', 'CARDCODE' => '5555556778250000', 'CARDVALIDITYDATE' => $this->tools->getFutureValidityDate(), 'CARDCVV' => '123', 'CARDFULLNAME' => 'John Doe', 'ORDERID' => 'order_' . time(), 'CLIENTIDENT' => 'john.doe', 'CLIENTEMAIL' => 'john.doe42', 'CLIENTEMAIL' => '*****@*****.**', 'DESCRIPTION' => 'Test', 'CLIENTUSERAGENT' => 'firefox', 'CLIENTIP' => '1.2.3.4', 'VERSION' => '2.0'));
     fputcsv($inputFile, array_keys(current($csv)), ';');
     foreach ($csv as $line) {
         fputcsv($inputFile, $line, ';');
     }
     rewind($inputFile);
     $batchApi = Be2bill_Api_ClientBuilder::buildSandboxBatchClient($this->getIdentifier(), $this->getPassword());
     $batchApi->setInputFile($inputFile);
     $batchApi->attach(new Be2bill_Api_Batch_Observer_Debug());
     $batchApi->attach(new Be2bill_Api_Batch_Observer_FileReport($outputFile));
     $batchApi->run();
     rewind($outputFile);
     $i = 0;
     while (!feof($outputFile)) {
         $line = fgetcsv($outputFile, null, ';');
         // HACK for phpunit version >= 5.2
         if ($line) {
             $i++;
         }
     }
     $this->expectOutputRegex('/Line 1.+\\nLine 2.+\\nLine 3.+\\nLine 4.+\\n/');
     $this->assertEquals(5, $i);
 }
Exemple #19
0
 public function analyze($handle)
 {
     $meta = stream_get_meta_data($handle);
     if (file_exists($meta['uri'])) {
         $type = 'file';
         $source = $meta['uri'];
     } else {
         $type = 'buffer';
         rewind($handle);
         $source = fread($handle, 1000000);
     }
     $result = call_user_func("finfo_{$type}", $this->_resource, $source, FILEINFO_MIME);
     if (strpos($result, 'application/ogg') === 0) {
         $full = call_user_func("finfo_{$type}", $this->_resource, $source);
         list($type, $attributes) = explode(';', $result, 2);
         if (strpos($full, 'video') !== false) {
             $type = 'video/ogg';
         } elseif (strpos($full, 'audio') !== false) {
             $type = 'audio/ogg';
         }
         return "{$type};{$attributes}";
     }
     if ($result != 'application/x-empty') {
         return $result;
     }
 }
 /**
  * Returns input stream.
  */
 protected function getInputStream($input)
 {
     $stream = fopen('php://memory', 'r+', FALSE);
     fwrite($stream, $input);
     rewind($stream);
     return $stream;
 }
function mc_format_csv($data)
{
    $keyed = false;
    // Create a stream opening it with read / write mode
    $stream = fopen('data://text/plain,' . "", 'w+');
    // Iterate over the data, writting each line to the text stream
    foreach ($data as $key => $val) {
        foreach ($val as $v) {
            $values = get_object_vars($v);
            if (!$keyed) {
                $keys = array_keys($values);
                fputcsv($stream, $keys);
                $keyed = true;
            }
            fputcsv($stream, $values);
        }
    }
    // Rewind the stream
    rewind($stream);
    // You can now echo it's content
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=my-calendar.csv");
    header("Pragma: no-cache");
    header("Expires: 0");
    echo stream_get_contents($stream);
    // Close the stream
    fclose($stream);
    die;
}
 public function createICal($nid)
 {
     $node = \Drupal\node\Entity\Node::load($nid);
     $eventdate = $node->get('field_event_date')->getValue();
     $title = $node->get('title')->getValue();
     $title = $title[0]['value'];
     $startdate = $eventdate[0]['value'];
     $enddate = $eventdate[1]['value'];
     if (empty($enddate)) {
         $enddate = $startdate;
     }
     $startdate = self::convertDateToICal($startdate);
     $enddate = self::convertDateToICal($enddate);
     $filecontents = self::buildICSFile($startdate, $enddate, $title, $nid);
     // open raw memory as file so no temp files needed, you might run out of memory though
     $file = fopen('php://memory', 'w');
     fwrite($file, $filecontents);
     // reset the file pointer to the start of the file
     rewind($file);
     // tell the browser it's going to be a calendar file
     header('Content-Type: text/calendar; charset=utf-8');
     // tell the browser we want to save it instead of displaying it
     header('Content-Disposition: attachment; filename="calendar.ics";');
     header('Cache-Control: store, no-cache, must-revalidate, post-check=0, pre-check=0');
     // make php send the generated file to the browser
     fpassthru($file);
     exit;
     /*
     	return array(
     		'#type' => 'markup',
     		'#markup' => $this->t('Hello, ical World!<pre>' . $filecontents . "</pre>"),
     	);
     */
 }
Exemple #23
0
 public function testApp()
 {
     $app = new Application();
     $app->setAutoExit(false);
     $input = new ArrayInput(array('--version'));
     $stream = fopen('php://memory', 'w', false);
     $output = new StreamOutput($stream);
     $app->run($input, $output);
     rewind($stream);
     $string = trim(fgets($stream));
     $string = preg_replace(array('/\\x1b(\\[|\\(|\\))[;?0-9]*[0-9A-Za-z]/', '/\\x1b(\\[|\\(|\\))[;?0-9]*[0-9A-Za-z]/', '/[\\x03|\\x1a]/'), array('', '', ''), $string);
     $this->assertEquals('Crate (repo)', $string);
     $app->setVersion('1.2.3');
     rewind($stream);
     $app->run($input, $output);
     rewind($stream);
     $string = trim(fgets($stream));
     $string = preg_replace(array('/\\x1b(\\[|\\(|\\))[;?0-9]*[0-9A-Za-z]/', '/\\x1b(\\[|\\(|\\))[;?0-9]*[0-9A-Za-z]/', '/[\\x03|\\x1a]/'), array('', '', ''), $string);
     $this->assertEquals('Crate version 1.2.3 build @git-commit@', $string);
     try {
         trigger_error('Test.', E_USER_WARNING);
     } catch (ErrorException $exception) {
     }
     $this->assertTrue(isset($exception));
 }
 /**
  * @dataProvider complianceProvider
  */
 public function testPassesCompliance($data, $expression, $result, $error, $file, $suite, $case, $compiled, $asAssoc)
 {
     $failed = $evalResult = $failureMsg = false;
     $debug = fopen('php://temp', 'r+');
     $compiledStr = '';
     try {
         if ($compiled) {
             $compiledStr = \JmesPath\Env::COMPILE_DIR . '=on ';
             $fn = self::$defaultRuntime;
             $evalResult = $fn($expression, $data, $debug);
         } else {
             $fn = self::$compilerRuntime;
             $evalResult = $fn($expression, $data, $debug);
         }
     } catch (\Exception $e) {
         $failed = $e instanceof SyntaxErrorException ? 'syntax' : 'runtime';
         $failureMsg = sprintf('%s (%s line %d)', $e->getMessage(), $e->getFile(), $e->getLine());
     }
     rewind($debug);
     $file = __DIR__ . '/compliance/' . $file . '.json';
     $failure = "\n{$compiledStr}php bin/jp.php --file {$file} --suite {$suite} --case {$case}\n\n" . stream_get_contents($debug) . "\n\n" . "Expected: " . $this->prettyJson($result) . "\n\n";
     $failure .= 'Associative? ' . var_export($asAssoc, true) . "\n\n";
     if (!$error && $failed) {
         $this->fail("Should not have failed\n{$failure}=> {$failed} {$failureMsg}");
     } elseif ($error && !$failed) {
         $this->fail("Should have failed\n{$failure}");
     }
     $result = $this->convertAssoc($result);
     $evalResult = $this->convertAssoc($evalResult);
     $this->assertEquals($result, $evalResult, $failure);
 }
Exemple #25
0
 /**
  * Returns the VCard-formatted object 
  * 
  * @return stream
  */
 public function get()
 {
     $s = fopen('php://temp', 'r+');
     fwrite($s, $this->_getVCard());
     rewind($s);
     return $s;
 }
Exemple #26
0
    public function setUp()
    {
        $base = 'lithium\\net\\socket';
        $namespace = __NAMESPACE__;
        Mocker::overwriteFunction("{$namespace}\\stream_context_get_options", function ($resource) {
            rewind($resource);
            return unserialize(stream_get_contents($resource));
        });
        Mocker::overwriteFunction("{$base}\\stream_context_create", function ($options) {
            return $options;
        });
        Mocker::overwriteFunction("{$base}\\fopen", function ($file, $mode, $includePath, $context) {
            $handle = fopen("php://memory", "rw");
            fputs($handle, serialize($context));
            return $handle;
        });
        Mocker::overwriteFunction("{$base}\\stream_get_meta_data", function ($resource) {
            return array('wrapper_data' => array('HTTP/1.1 301 Moved Permanently', 'Location: http://www.google.com/', 'Content-Type: text/html; charset=UTF-8', 'Date: Thu, 28 Feb 2013 07:05:10 GMT', 'Expires: Sat, 30 Mar 2013 07:05:10 GMT', 'Cache-Control: public, max-age=2592000', 'Server: gws', 'Content-Length: 219', 'X-XSS-Protection: 1; mode=block', 'X-Frame-Options: SAMEORIGIN', 'Connection: close'));
        });
        Mocker::overwriteFunction("{$base}\\stream_get_contents", function ($resource) {
            return <<<EOD
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>
EOD;
        });
        Mocker::overwriteFunction("{$base}\\feof", function ($resource) {
            return true;
        });
    }
Exemple #27
0
function create_tmp_file($data)
{
    $tmp_file = tmpfile();
    fwrite($tmp_file, $data);
    rewind($tmp_file);
    return $tmp_file;
}
 protected function withFileResource()
 {
     $resource = fopen('php://memory', 'rw');
     fwrite($resource, self::TEST_FILE_CONTENTS);
     rewind($resource);
     $this->mockFileService->expects($this->once())->method('loadFile')->willReturn($resource);
 }
 protected function getInputStream($input)
 {
     $stream = fopen('php://memory', 'r+', false);
     fputs($stream, $input);
     rewind($stream);
     return $stream;
 }
Exemple #30
0
 public function rewind()
 {
     $this->isValid = true;
     rewind($this->getFileHandle());
     $this->iteratorKey = 0;
     $this->iteratorValue = $this->getRecord();
 }