/** * {@inheritdoc} */ public function read() { if (null === $this->csv) { if (mime_content_type($this->filePath) === 'application/zip') { $this->extractZipArchive(); } $this->csv = new \SplFileObject($this->filePath); $this->csv->setFlags(\SplFileObject::READ_CSV | \SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY | \SplFileObject::DROP_NEW_LINE); $this->csv->setCsvControl($this->delimiter, $this->enclosure, $this->escape); $this->fieldNames = $this->csv->fgetcsv(); } $data = $this->csv->fgetcsv(); if (false !== $data) { if ($data === array(null) || $data === null) { return null; } if ($this->stepExecution) { $this->stepExecution->incrementSummaryInfo('read'); } if (count($this->fieldNames) !== count($data)) { throw new InvalidItemException('pim_base_connector.steps.csv_reader.invalid_item_columns_count', $data, array('%totalColumnsCount%' => count($this->fieldNames), '%itemColumnsCount%' => count($data), '%csvPath%' => $this->csv->getRealPath(), '%lineno%' => $this->csv->key())); } $data = array_combine($this->fieldNames, $data); } else { throw new \RuntimeException('An error occured while reading the csv.'); } return $data; }
protected function buildQueue() { $projectDir = $this->getProjectDir(); $outputDir = $this->getOutputDir(); $item = new \SplFileObject($this->getSingleFile()); if ($item->isFile()) { try { $factory = new View\Factory($item->getRealPath()); $view = $factory->create(); $view->setSiteConfig($this->getSiteConfig())->setOutputDir($outputDir); $this->addView($view); } catch (\Exception $e) { $this->getOutputter()->stderr(str_replace($projectDir, '', $item->getRealPath()) . ': ' . $e->getMessage()); } } return $this; }
public function testParseFile() { $content = 'test'; $fileObject = new \SplFileObject(tempnam(sys_get_temp_dir(), 'test_'), 'w+'); $fileObject->fwrite($content); $parserMock = $this->getMockForAbstractClass($this->parserClassName, array(), '', true, true, true, array('parseContent')); $parserMock->expects($this->once())->method('parseContent')->with($this->equalTo($content))->will($this->returnArgument(0)); $this->assertSame($content, $parserMock->parseFile($fileObject->getRealPath())); }
public function testSetWhereValueSetIsntAsLongAsSlice() { $fileObject = new \SplFileObject(__DIR__ . '/Fixtures/lazy_line_' . $this->getFaker()->word . '.txt', 'w+'); $fileObject->fwrite(str_repeat(' ', 10)); $fileObject->fwrite("\n"); $fileObject->fwrite(str_repeat(' ', 10)); $line = new FileSystemLine($fileObject, 11, 10); $line['0:5'] = 'we'; $this->assertEquals('we ', (string) $line); unlink($fileObject->getRealPath()); }
/** * Delete a key from the cache * * @param string $key Identifier for the data * @return bool True if the value was successfully deleted, false if it didn't * exist or couldn't be removed */ public function delete($key) { $key = $this->_key($key); if ($this->_setKey($key) === false || !$this->_init) { return false; } $path = $this->_File->getRealPath(); $this->_File = null; //@codingStandardsIgnoreStart return @unlink($path); //@codingStandardsIgnoreEnd }
/** * Adds the coverage contained in $coverageFile and deletes the file afterwards * @param string $coverageFile Code coverage file * @throws \RuntimeException When coverage file is empty */ public function addCoverageFromFile($coverageFile) { if ($coverageFile === null || !file_exists($coverageFile)) { return; } $file = new \SplFileObject($coverageFile); if (0 === $file->getSize()) { throw new \RuntimeException("Coverage file {$file->getRealPath()} is empty. This means a PHPUnit process has crashed."); } $this->addCoverage($this->getCoverageObject($file)); unlink($file->getRealPath()); }
/** * Construct a new file object and set defaults. * * @param string $file * @param string $mode * @param bool $include * @param stream $context * @return Interspire_File */ public function __construct($file, $mode = 'r', $include = false, $context = null) { if ($context) { parent::__construct($file, $mode, $include, $context); } else { parent::__construct($file, $mode, $include); } if (method_exists('SplFileObject', 'getRealPath')) { // getRealPath is PHP >= 5.2.2 $this->realpath = parent::getRealPath(); } else { $this->realpath = realpath($file); } }
public function purgeAll($check_expiry = false) { if (!$this->is_init) { return false; } $dir = dir($this->settings['path']); if ($check_expiry) { if (is_numeric($check_expiry)) { $now = $check_expiry; } else { $now = time(); } $threshold = $now - $this->settings['cache_duration']; } $prefixLength = strlen($this->settings['key_prefix']); while (($entry = $dir->read()) !== false) { if (substr($entry, 0, $prefixLength) !== $this->settings['key_prefix']) { continue; } if ($this->_openFile($entry) === false) { continue; } if ($check_expiry) { $mtime = $this->file->getMTime(); if ($mtime > $threshold) { continue; } $expires = (int) $this->file->current(); if ($expires > $now) { continue; } } $path = $this->file->getRealPath(); $this->file = null; if (file_exists($path)) { unlink($path); } } $dir->close(); return true; }
/** * {@inheritdoc} */ public function read() { if (null === $this->csv) { $this->initializeRead(); } $data = $this->csv->fgetcsv(); if (false !== $data) { if ([null] === $data || null === $data) { return null; } if ($this->stepExecution) { $this->stepExecution->incrementSummaryInfo('read_lines'); } if (count($this->fieldNames) !== count($data)) { throw new InvalidItemException('pim_connector.steps.csv_reader.invalid_item_columns_count', $data, ['%totalColumnsCount%' => count($this->fieldNames), '%itemColumnsCount%' => count($data), '%csvPath%' => $this->csv->getRealPath(), '%lineno%' => $this->csv->key()]); } $data = array_combine($this->fieldNames, $data); } else { throw new \RuntimeException('An error occurred while reading the csv.'); } return $data; }
/** * Used to clear a directory of matching files. * * @param string $path The path to search. * @param integer $now The current timestamp * @param integer $threshold Any file not modified after this value will be deleted. * @return void */ protected function _clearDirectory($path, $now, $threshold) { $prefixLength = strlen($this->settings['prefix']); if (!is_dir($path)) { return; } $dir = dir($path); while (($entry = $dir->read()) !== false) { if (substr($entry, 0, $prefixLength) !== $this->settings['prefix']) { continue; } $filePath = $path . $entry; if (!file_exists($filePath) || is_dir($filePath)) { continue; } $file = new SplFileObject($path . $entry, 'r'); if ($threshold) { $mtime = $file->getMTime(); if ($mtime > $threshold) { continue; } $expires = (int) $file->current(); if ($expires > $now) { continue; } } if ($file->isFile()) { $filePath = $file->getRealPath(); $file = null; //@codingStandardsIgnoreStart @unlink($filePath); //@codingStandardsIgnoreEnd } } }
/** * @return bool */ public function purge() { // no unlink because there's an add after that requires the file to exist return file_put_contents($this->file->getRealPath(), ''); }
/** * Get the full path to a file located in the tests resources * @param string $relativePath * @return string */ public function getResource($relativePath) { $file = new \SplFileObject($relativePath, 'rb', true); return $file->getRealPath(); }
<?php set_include_path('tests'); chdir(dirname(dirname(__FILE__))); // ext/spl $fo = new SplFileObject('fileobject_004.phpt', 'r', true); var_dump($fo->getPath()); var_dump($fo->getFilename()); var_dump($fo->getRealPath()); ?> ==DONE==
/** * Reads and decodes json from given file. * * @param \SplFileObject $file * @return mixed */ private function getComposerLockData(\SplFileObject $file) { $json = file_get_contents($file->getRealPath()); return json_decode($json); }
/** * Divide large CSV file into several parts and return list of part files * * @param \SplFileObject $file File object * * @return array */ public function divideCSVFile($file) { $result = array(); $outputFileFormat = basename($file->getRealPath()); $f = fopen($file->getRealPath(), 'rb'); // Part file index $fi = 1; // Row index $i = 0; $ip = 0; // Delta (sum of rows in all previous part files) $delta = 0; $content = ''; $pendingContent = ''; $columns = $this->getKeyColumns(); // Subdirectory of tmp dir to write CSV part files $subDir = time(); while (true) { $fields = fgetcsv($f, 0, ',', '"'); if (false !== $fields && 1 === count($fields) && null === $fields[0]) { // Skip blank lines continue; } if (null === $header) { // Initialize header $this->processHeaderRow(array($fields)); $header = $this->getCSVString($fields); continue; } $save = false; if (false !== $fields) { // Get current row content $currentRow = $this->getCSVString($fields); $isSubrow = true; if (!empty($prevFields)) { // Check if next line is subrow of current $isEmpty = true; foreach ($columns as $column) { $prevKey = $this->getColumnValue($column, $prevFields); $isEmpty = $isEmpty && !(bool) $prevKey; if (!$isEmpty && $prevKey !== $this->getColumnValue($column, $fields)) { $isSubrow = false; break; } } $isSubrow = $isEmpty ? false : $isSubrow; } else { $isSubrow = false; } if (!$isSubrow) { $prevFields = $fields; } // Prepare content if ($isSubrow) { // Current row is a subrow or one of previous rows - add this to $pendingContent $pendingContent .= $currentRow; $ip++; } else { // Current row is a complete row - merge $pendingContent into $content... $content .= $pendingContent; $i += $ip; // ...then initialize $pendingContent with current row value $pendingContent = $currentRow; $ip = 1; } if ($i >= static::MAX_PART_FILE_ROWS && $content) { $save = true; } } if ($save || false === $fields) { $outputFile = LC_DIR_TMP . $subDir . LC_DS . preg_replace('/(\\.csv)$/', sprintf('.part-%02d.csv', $fi++), $outputFileFormat); if (!\Includes\Utils\FileManager::write($outputFile, $header . $content)) { \XLite\Logger::getInstance()->log('Cannot write file ' . $outputFile); $result = array(); break; } $result[] = array('file' => $outputFile, 'delta' => $delta); $delta += $i; $i = 0; $content = ''; } if (false === $fields) { break; } } // while return $result; }
/** * The main business logic of the class: opens the import file passed as an argument and parses its content. * Note that the parsing is delegated to sub-classes (cf. Template Method design pattern) * Note also that it's a business method and is not relevant to the CoR pattern. * * @param SplFileObject $file * * @return mixed */ protected function handle(SplFileObject $file) { // The following line of code is only for debug & demo purposes: echo static::CLASS . " is the handler for {$file->getExtension()} files\n"; $content = file_get_contents($file->getRealPath()); return $this->parseContent($content); }
/** * Take value and turn it into a string suitable for inclusion in * the http body (form parameter). If it's a string, pass through unchanged * If it's a datetime object, format it in ISO8601 * * @param string|\SplFileObject $value the value of the form parameter * * @return string the form string */ public function toFormValue($value) { if ($value instanceof \SplFileObject) { return $value->getRealPath(); } else { return $this->toString($value); } }
public function __construct(\SplFileObject $file, $rowNodeName = 'node', $rootNodeName = 'root') { $this->filename = $file->getRealPath(); $this->rowNodeName = $rowNodeName; $this->rootNodeName = $rootNodeName; }
public function testFileWithoutTrailingLineEnding() { $fileObject = new \SplFileObject(__DIR__ . '/Fixtures/' . $this->getFaker()->word . '.txt', 'w+'); $fileObject->fwrite('line'); $file = new FileSystemFile(4, $fileObject, "\n"); $file->addLine('line'); $this->assertEquals("line\nline", $file); $this->assertEquals(file_get_contents($fileObject->getRealPath()), $file); unlink($fileObject->getRealPath()); }
/** * @param $id * @param SplFileObject $file * @param bool $force * * @return bool */ public final function storeFile($id, SplFileObject $file, $force = false) { return $this->storeFileByPath($id, $file->getRealPath(), $force); }