/** * @return string */ public function getSolution() { $txt = 'Solution - ' . $this->getName() . ' :' . PHP_EOL; foreach (array(1, 2) as $part) { try { $txt .= '- Part ' . $part . ' : ' . $this->getAnswer($part) . PHP_EOL; $this->instructionsFile->rewind(); } catch (Exception $exception) { $txt .= 'Exception while executing part ' . $part . ' : ' . $exception->getMessage() . PHP_EOL; } } return $txt; }
/** * Rewind the file pointer * * If a header row has been set, the pointer is set just below the header * row. That way, when you iterate over the rows, that header row is * skipped. */ public function rewind() { $this->file->rewind(); if (null !== $this->headerRowNumber) { $this->file->seek($this->headerRowNumber + 1); } }
/** * Implements Iterator::rewind(). */ public function rewind() { parent::rewind(); if ($this->startPosition) { $this->fseek($this->startPosition); } $this->linesRead = 0; }
public function finalizeFile(\SplFileObject $fileObject) { if ($this->headers !== null) { // Create tmp file with header $fd = fopen('php://temp', 'w+b'); fputcsv($fd, $this->headers); // Copy file content into tmp file $fileObject->rewind(); fwrite($fd, $fileObject->fread($fileObject->getSize())); // Overwrite file content with tmp content rewind($fd); $fileObject->rewind(); $fileObject->fwrite(stream_get_contents($fd)); clearstatcache(true, $fileObject->getPathname()); fclose($fd); } // Remove last line feed $fileObject->ftruncate($fileObject->getSize() - 1); }
/** * Test the words found in Appendix A from Mr. * Ntais's thesis. * * The words are not tested against the stem reported in the appendix * but against the results of Mr. Ntais's canonical implementation in js * found here http://people.dsv.su.se/~hercules/greek_stemmer.gr.html */ public function testFromAppendixA() { $words = new \SplFileObject(TEST_DATA_DIR . '/Stemmers/GreekStemmerTest/appendix-a-words'); $stems = new \SplFileObject(TEST_DATA_DIR . '/Stemmers/GreekStemmerTest/appendix-a-stems'); $words->setFlags(\SplFileObject::DROP_NEW_LINE | \SplFileObject::SKIP_EMPTY); $stems->setFlags(\SplFileObject::DROP_NEW_LINE | \SplFileObject::SKIP_EMPTY); $stems->rewind(); $stemmer = new GreekStemmer(); $this->checkStemmer($stemmer, $words, $stems); }
public function rewind() { parent::rewind(); // If we are getting the first line as columns, take them then skip to // the next line. if ($this->_firstLineIsColumns) { $this->setColumns(parent::current()); parent::next(); } }
/** * Free the used slots * * @param $sliced_report_definitions_count */ private function freeUsedRequestCount($sliced_report_definitions_count) { $this->file_counter->flock(LOCK_EX); $this->file_counter->rewind(); $used_request_count = (int) $this->file_counter->fgets(); $new_used_request_count = $used_request_count - $sliced_report_definitions_count; $this->file_counter->ftruncate(0); $this->file_counter->fwrite($new_used_request_count); $this->file_counter->flock(LOCK_UN); }
/** * Load a set of words and their stems and check if the stemmer * produces the correct stems * * @group Slow */ public function testStemmer() { $words = new \SplFileObject(TEST_DATA_DIR . '/Stemmers/PorterStemmerTest/words.txt'); $stems = new \SplFileObject(TEST_DATA_DIR . '/Stemmers/PorterStemmerTest/stems.txt'); $words->setFlags(\SplFileObject::DROP_NEW_LINE | \SplFileObject::SKIP_EMPTY); $stems->setFlags(\SplFileObject::DROP_NEW_LINE | \SplFileObject::SKIP_EMPTY); $stems->rewind(); $stemmer = new PorterStemmer(); $this->checkStemmer($stemmer, $words, $stems); }
/** * Get writable copy of the file * * @return SplFileObject */ protected function getWritableFile() { if ($this->tmpfile === null) { $this->tmpfile = new \SplTempFileObject(131072); $this->file->rewind(); foreach ($this->file as $line) { $this->tmpfile->fwrite($line); } } return $this->tmpfile; }
/** * {@inheritdoc} */ public function goBeforeCharacter(\SplFileObject $file, $characterNumber) { $file->rewind(); if ($characterNumber < 0 || $characterNumber > $file->getSize()) { throw new OutOfBoundsException(); } for ($i = 0; $i <= $characterNumber - 1; $i++) { $file->fgetc(); } return $file; }
/** * Rewind the \Iterator to the first element */ public function rewind() { $this->_filepos = null; $this->_key = 0; if (null === $this->_file) { $this->_openFile(); } elseif ($this->_file) { $this->_file->rewind(); $this->_file->current(); // Reading first line is necessary for correct loading of file. $this->next(); } }
/** * * because \SplFileObject::fread() is not available before 5.5.11 anyway * * returns the full content of a file, rewinds pointer in the beginning and leaves it at the end * but dont rely on this pointer behaviour * * @param \SplFileObject $fileObject * * @return \SplString|string */ public static function getContent(\SplFileObject $fileObject) { if (class_exists('SplString')) { $result = new \SplString(); } else { $result = ''; } $fileObject->rewind(); while (!$fileObject->eof()) { $result .= $fileObject->fgets(); } return $result; }
/** * Saves the current upload stream to designated target. * * @param {string} Target path to save the contents, cannot be a directory. * @param {?bool} True to append to target file, defaults to replace. * @return {boolean} True on success, false otherwise. */ public function save($path, $append = false) { if (is_dir($path)) { $path = preg_replace('/\\' . preg_quote(DS) . '?$/', '$1/' . $this->getFilename(), $path); } $target = new \SplFileObject($path, $append ? 'a' : 'w'); $this->rewind(); while (!$this->eof()) { $target->fwrite($this->fread(4096)); } $target->fflush(); $target->rewind(); return $target; }
public function testAgainstOriginalSedImplementation() { $tokenizer = new PennTreeBankTokenizer(); $tokenized = new \SplFileObject(TEST_DATA_DIR . "/Tokenizers/PennTreeBankTokenizerTest/tokenized"); $tokenized->setFlags(\SplFileObject::DROP_NEW_LINE); $sentences = new \SplFileObject(TEST_DATA_DIR . "/Tokenizers/PennTreeBankTokenizerTest/test.txt"); $sentences->setFlags(\SplFileObject::DROP_NEW_LINE); $tokenized->rewind(); foreach ($sentences as $sentence) { if ($sentence) { $this->assertEquals($tokenized->current(), implode(" ", $tokenizer->tokenize($sentence)), "Sentence: '{$sentence}' was not tokenized correctly"); } $tokenized->next(); } }
/** * Get raw image data from the SplFileObject. * * @return string * String representation of the raw image binary data */ public function getRaw() { if (!is_null($this->raw)) { return $this->raw; } // Save our current position $position = $this->object->ftell(); $this->object->rewind(); $raw = ''; while ($this->object->valid()) { $raw .= $this->object->fgets(); } // Go back to our original position $this->object->fseek($position); return $this->raw = $raw; }
/** * It skips the file headers * @return boolean * @access private * @final */ private final function skipHead() { if ($this->fileObject->getSize() < 0) { return false; } $this->fileObject->rewind(); $this->fileObject->fseek(7, SEEK_CUR); $mainHead = $this->fileObject->fread(7); if (ord($mainHead[2]) != 0x73) { return false; } $headSize = $this->getBytes($mainHead, 5, 2); $this->fileObject->fseek($headSize - 7, SEEK_CUR); unset($mainHead, $headSize); return true; }
/** * @depends testInit * @return void */ public function testNextLine() { $filePath = __DIR__ . '/example_read.txt'; $fileObject = new FileReader($filePath, 'r', true); $this->assertEquals('Line01', $fileObject->firstLine()); $this->assertEquals('Line02', $fileObject->nextLine()); $this->assertEquals('Line03', $fileObject->nextLine()); $this->assertEquals('Line01', $fileObject->firstLine()); $fileObject = new \SplFileObject($filePath, 'r'); $fileObject->setFlags(\SplFileObject::DROP_NEW_LINE | \SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY); $this->assertEquals('Line01', $fileObject->current()); $fileObject->next(); $this->assertEquals('Line02', $fileObject->current()); $fileObject->next(); $this->assertEquals('Line03', $fileObject->current()); $fileObject->rewind(); $this->assertEquals('Line01', $fileObject->current()); }
public function read($key) { if (!$this->is_init || $this->_openFile($key) === false) { return false; } if ($this->settings['lock']) { $this->file->flock(LOCK_SH); } $this->file->rewind(); $time = time(); $cachetime = intval($this->file->current()); //check for expiry if ($cachetime !== false && ($cachetime < $time || $time + $this->settings['cache_duration'] < $cachetime)) { if ($this->settings['lock']) { $this->file->flock(LOCK_UN); } return false; } $data = ''; $this->file->next(); while ($this->file->valid()) { $data .= $this->file->current(); $this->file->next(); } if ($this->settings['lock']) { $this->file->flock(LOCK_UN); } $data = trim($data); if ($data !== '' && !empty($this->settings['serialize'])) { if ($this->settings['is_windows']) { $data = str_replace('\\\\\\\\', '\\', $data); } $data = json_decode((string) $data, TRUE); } return $data; }
/** * Read a key from the cache * * @param string $key Identifier for the data * @return mixed The cached data, or false if the data doesn't exist, has * expired, or if there was an error fetching it */ public function read($key) { $key = $this->_key($key); if (!$this->_init || $this->_setKey($key) === false) { return false; } if ($this->_config['lock']) { $this->_File->flock(LOCK_SH); } $this->_File->rewind(); $time = time(); $cachetime = (int) $this->_File->current(); if ($cachetime !== false && ($cachetime < $time || $time + $this->_config['duration'] < $cachetime)) { if ($this->_config['lock']) { $this->_File->flock(LOCK_UN); } return false; } $data = ''; $this->_File->next(); while ($this->_File->valid()) { $data .= $this->_File->current(); $this->_File->next(); } if ($this->_config['lock']) { $this->_File->flock(LOCK_UN); } $data = trim($data); if ($data !== '' && !empty($this->_config['serialize'])) { if ($this->_config['isWindows']) { $data = str_replace('\\\\\\\\', '\\', $data); } $data = unserialize((string) $data); } return $data; }
/** * Returns column names of the given CSV file * * @param \SplFileObject $file * @return array */ private function getColumnNames(\SplFileObject $file) { //Rewinds to first line $file->rewind(); $columnNames = $file->current(); //removes UTF-8 BOM foreach ($columnNames as $index => $name) { $columnNames[$index] = str_replace("", '', $name); } return $columnNames; }
/** * {@inheritdoc} */ public function initialize() { if (null !== $this->csv) { $this->csv->rewind(); } }
/** * Overrides the SplFileObject method of the same name. * * @return void * @author "David Hazel" <*****@*****.**> **/ public function rewind() { parent::rewind(); }
/** * @param string $name * @param array $configRaw * @param integer $limit */ protected function callSync($name, $configRaw, $limit) { //normalize config $config = array('last' => isset($configRaw[$name . '_last']) ? $configRaw[$name . '_last'] : 0, 'rows' => isset($configRaw[$name . '_rows']) ? $configRaw[$name . '_rows'] : 0); $filePath = $this->iniConfiguration->getTempPath() . '/' . $name . '.data'; if ($config['rows'] == 0) { //create new request $response = $this->getWrapper()->request('data', $name, array('lastDownload' => $config['last'])); //analyze response switch ($this->getWrapper()->analyzeResponse($response)) { case 'url': //continue to download $this->getWrapper()->download($response->url, $filePath); break; case 'suspend': //suspend processing for time in response return $this->suspend($response->until); default: throw new Api\ApiException('Response from datadepo is unknow'); } } //open file and read header $file = new \SplFileObject($filePath); $header = json_decode($file->fgets(), TRUE); //check number of lines in downloaded file if ($config['rows'] == 0) { $file->seek(PHP_INT_MAX); $linesTotal = $file->key() + 1; if ($header['numRecords'] != $linesTotal - 1) { throw new Api\ApiException('Incompleted file downloaded in ' . $name . ' synchronizer'); } $file->rewind(); } $processCount = $this->iniConfiguration->get('limits', 'processCount'); $collector = $this->createCollector(); $count = 0; //skip line $file->seek($config['rows'] + 1); while ((!$file->eof() || $file->current() !== FALSE) && $count < $limit) { //add line to front $line = $this->wrapLine($file->current()); $collector->add($line); $count++; //process if ($count % $processCount === 0) { $this->processChunk($collector); $collector = $this->createCollector(); } $file->next(); } //sync rest if (count($collector) > 0) { $this->processChunk($collector); } //check num processed if ($count == $limit) { $this->dataStore->setConfig($name . '_rows', $config['rows'] + $count); } else { $this->dataStore->setConfig($name . '_rows', 0); $this->dataStore->setConfig($name . '_last', $header['generatedAt']); } return new Api\DataDepoResponse(Api\DataDepoResponse::CODE_OK, NULL, array('processed' => $count)); }
<?php set_include_path(dirname(dirname(__FILE__))); $path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'fileobject_005.txt'; touch($path); $fo = new SplFileObject('tests' . DIRECTORY_SEPARATOR . 'fileobject_005.txt', 'w+', true); $fo->fwrite("blahlubba"); var_dump($fo->ftruncate(4)); $fo->rewind(); var_dump($fo->fgets(8)); $fo->rewind(); $fo->fwrite("blahlubba"); // This should throw a warning and return NULL since an argument is missing var_dump($fo->ftruncate()); ?> ==DONE==
/** * @param int $offset * @param int $limit * @param string $term * @return array */ protected function paginateLinesSearch($offset, $limit, $term) { $returnLines = array(); $returnLinesCount = 0; $matchingLinesCount = -1; if ($offset === 0) { $offset = -1; } parent::rewind(); if (is_bool($term) || is_null($term)) { trigger_error(sprintf('%s::paginateLines - %s search input seen, which results in empty string when typecast. Please check input value.', get_class($this), gettype($term))); } if (is_scalar($term) || is_object($term) && method_exists($term, '__toString')) { $term = (string) $term; while (parent::valid() && $returnLinesCount < $limit) { if (($current = parent::current()) !== '' && stripos($current, $term) !== false && ++$matchingLinesCount > $offset) { $returnLines[] = $current; $returnLinesCount++; } parent::next(); } parent::rewind(); return $returnLines; } throw new \InvalidArgumentException(sprintf('%s::paginateLines - Search value expected to be castable to string, "%s" seen.', get_class($this), gettype($term))); }
/** * Return to first statement * * @return void */ public function rewind() { parent::rewind(); $this->next(); }
function getForwards(\SplFileObject $log) { $log->rewind(); $lines = []; foreach ($log as $line) { if (strpos($line, ": forwarded") !== false) { $lines[] = $line; } } return $lines; }
/** * Rewind the Iterator to the first element * @link http://php.net/manual/en/iterator.rewind.php * @return void Any returned value is ignored. */ public function rewind() { parent::rewind(); $this->seek($this->line_start_position); }
/** * {@inheritdoc} */ public function rewind() { $this->file->rewind(); }
<?php file_put_contents('SplFileObject_rewind_error001.csv', 'eerste;tweede;derde'); $fo = new SplFileObject('SplFileObject_rewind_error001.csv'); $fo->rewind("invalid");