/** * {@inheritdoc} */ public function write($item) { if (!is_array($item) && !is_scalar($item)) { throw new UnsupportedItemTypeException(sprintf('%s only supports items of type scalar or array', __CLASS__)); } $this->file->fwrite(json_encode($item) . PHP_EOL); }
public function testParseFileObject() { $parser = new ABOParser(); $reflectionParser = new \ReflectionClass($this->parserClassName); $method = $reflectionParser->getMethod('parseFileObject'); $method->setAccessible(true); # Positive statement $fileObject = new \SplFileObject(tempnam(sys_get_temp_dir(), 'test_'), 'w+'); $fileObject->fwrite('0740000000000012345Test s.r.o. 01011400000000100000+00000000080000+00000000060000' . '+00000000040000+002010214 ' . PHP_EOL); $fileObject->fwrite('0750000000000012345000000000015678900000000020010000000400002000000001100100000120000000013050114' . 'Tran 1 01102050114' . PHP_EOL); $fileObject->fwrite('0750000000000012345000000000025678900000000020020000000600001000000002100200000220000000023070114' . 'Tran 2 01101070114' . PHP_EOL); $fileObject->fwrite('0760000000000012345000000000025678900000000020020000000600001000000002100200000220000000023070114' . 'Tran 2 01101070114' . PHP_EOL); $statement = $method->invokeArgs($parser, array($fileObject)); $this->assertInstanceOf('\\JakubZapletal\\Component\\BankStatement\\Statement\\Statement', $statement); # Statement $this->assertSame($statement, $parser->getStatement()); $this->assertEquals('12345', $statement->getAccountNumber()); $this->assertEquals(new \DateTime('2014-01-01 12:00:00'), $statement->getDateLastBalance()); $this->assertSame(1000.0, $statement->getLastBalance()); $this->assertSame(800.0, $statement->getBalance()); $this->assertSame(400.0, $statement->getCreditTurnover()); $this->assertSame(600.0, $statement->getDebitTurnover()); $this->assertEquals(2, $statement->getSerialNumber()); $this->assertEquals(new \DateTime('2014-02-01 12:00:00'), $statement->getDateCreated()); # Transactions $statement->rewind(); $this->assertCount(2, $statement); $transaction = $statement->current(); $this->assertEquals('156789/1000', $transaction->getCounterAccountNumber()); $this->assertEquals(2001, $transaction->getReceiptId()); $this->assertSame(400.0, $transaction->getCredit()); $this->assertNull($transaction->getDebit()); $this->assertEquals(11, $transaction->getVariableSymbol()); $this->assertEquals(12, $transaction->getConstantSymbol()); $this->assertEquals(13, $transaction->getSpecificSymbol()); $this->assertEquals('Tran 1', $transaction->getNote()); $this->assertEquals(new \DateTime('2014-01-05 12:00:00'), $transaction->getDateCreated()); $transaction = $statement->next(); $this->assertNull($transaction->getCredit()); $this->assertSame(600.0, $transaction->getDebit()); # Negative statement $fileObject = new \SplFileObject(tempnam(sys_get_temp_dir(), 'test_'), 'w+'); $fileObject->fwrite('0740000000000012345Test s.r.o. 01011400000000100000-00000000080000-00000000060000-00000000040000' . '-002010214 ' . PHP_EOL); $fileObject->fwrite('0750000000000012345000000000015678900000000020010000000400005000000001100100000120000000013050114' . 'Tran 1 01102050114' . PHP_EOL); $fileObject->fwrite('0750000000000012345000000000025678900000000020020000000600004000000002100200000220000000023070114' . 'Tran 2 01101070114' . PHP_EOL); $statement = $method->invokeArgs($parser, array($fileObject)); # Statement $this->assertSame(-1000.0, $statement->getLastBalance()); $this->assertSame(-800.0, $statement->getBalance()); $this->assertSame(-400.0, $statement->getCreditTurnover()); $this->assertSame(-600.0, $statement->getDebitTurnover()); # Transactions $statement->rewind(); $transaction = $statement->current(); $this->assertSame(-400.0, $transaction->getCredit()); $transaction = $statement->next(); $this->assertSame(-600.0, $transaction->getDebit()); }
function createIniFile($path) { $configFile = new SplFileObject($path . DIRECTORY_SEPARATOR . 'theme', 'w'); $base = array('Name' => 'Twitch Icons via SpazTwitch', 'Description' => 'Thanks to twitchemotes.com for the API.', 'Icon' => '25.png', 'Author' => 'Omnifox'); foreach ($base as $k => $v) { $configFile->fwrite("{$k}={$v}" . PHP_EOL); } $configFile->fwrite(PHP_EOL); return $configFile; }
/** * {@inheritdoc} */ public function writeToStream(SplFileObject $fileObject, $encryptionKey) { $value = $this->value; if (null !== $encryptionKey) { $value = \Bacon\Pdf\Utils\EncryptionUtils::rc4($encryptionKey, $value); } $fileObject->fwrite('<'); $fileObject->fwrite(chunk_split(bin2hex($value), 255, "\n")); $fileObject->fwrite('>'); }
/** * Writes the given snapshotEvent to the {@link #snapshotEventFile}. * Prepends a long value to the event in the file indicating the bytes to skip when reading the {@link #eventFile}. * * @param DomainEventMessageInterface $snapshotEvent The snapshot to write to the {@link #snapshotEventFile} * @throws EventStoreException */ public function writeSnapshotEvent(DomainEventMessageInterface $snapshotEvent) { try { $offset = $this->calculateOffset($snapshotEvent); $this->snapshotEventFile->fwrite(pack("N", $offset)); $eventMessageWriter = new FilesystemEventMessageWriter($this->snapshotEventFile, $this->eventSerializer); $eventMessageWriter->writeEventMessage($snapshotEvent); } catch (\Exception $ex) { throw new EventStoreException("Error writing a snapshot event", 0, $ex); } }
/** * Inline all classes from path to single file * */ public function inline($path, $ext, $filename) { $this->setPath($path); $this->setFileExt($ext); $classes = $this->readClasses(); $inlined = new SplFileObject(__DIR__ . '/' . $filename, 'w'); $inlined->fwrite('<?php'); foreach ($classes as $class) { $inlined->fwrite($this->cleanClass($class)); } }
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()); }
/** * @return void */ public function testWriteLine() { $filePath = __DIR__ . '/example_write1.txt'; $fileObject = new FileWriter($filePath, 'a+'); $fileObject->writeLine("foo"); $fileObject->writeLine("bar"); $fileObject->writeLine(" some string " . PHP_EOL . "with line breaks \n\r" . PHP_EOL); $filePath = __DIR__ . '/example_write2.txt'; $fileObject = new \SplFileObject($filePath, 'a+'); $fileObject->fwrite("foo" . PHP_EOL); $fileObject->fwrite("bar" . PHP_EOL); }
/** * @inheritdoc */ public function getFile() { if ($this->file === null) { try { $this->file = new TempFile(); $this->file->fwrite($this->data); $this->file->fseek(0); } catch (\RuntimeException $e) { throw new TransportException($e->getMessage(), null, $e); } } return $this->file; }
/** * {@inheritdoc} */ public function write(\SplFileObject $file, $text, $newLineAtEnd = false) { $originalSeek = $file->ftell(); // Refresh file size clearstatcache($file->getFilename()); if ($file->getSize() - $file->ftell() > 0) { $contentAfter = $file->fread($file->getSize() - $file->ftell()); } else { $contentAfter = ''; } $file->fseek($originalSeek); $file->fwrite($text . ($newLineAtEnd ? PHP_EOL : '')); $file->fwrite($contentAfter); return $file; }
/** * Write data for key into cache * * @param string $key Identifier for the data * @param mixed $data Data to be cached * @return bool True if the data was successfully cached, false on failure */ public function write($key, $data) { if ($data === '' || !$this->_init) { return false; } $key = $this->_key($key); if ($this->_setKey($key, true) === false) { return false; } $lineBreak = "\n"; if ($this->_config['isWindows']) { $lineBreak = "\r\n"; } if (!empty($this->_config['serialize'])) { if ($this->_config['isWindows']) { $data = str_replace('\\', '\\\\\\\\', serialize($data)); } else { $data = serialize($data); } } $duration = $this->_config['duration']; $expires = time() + $duration; $contents = $expires . $lineBreak . $data . $lineBreak; if ($this->_config['lock']) { $this->_File->flock(LOCK_EX); } $this->_File->rewind(); $success = $this->_File->ftruncate(0) && $this->_File->fwrite($contents) && $this->_File->fflush(); if ($this->_config['lock']) { $this->_File->flock(LOCK_UN); } $this->_File = null; return $success; }
public function write(\SplFileObject $file, \de\codenamephp\platform\core\file\property\Entries $propertyFile) { foreach ($propertyFile->getEntries() as $entry) { $file->fwrite(sprintf('%s=%s' . PHP_EOL, $entry->getKey(), $entry->getValue())); } return $this; }
public function __invoke($file, $minify = null) { if (!is_file($this->getOptions()->getPublicDir() . $file)) { throw new \InvalidArgumentException('File "' . $this->getOptions()->getPublicDir() . $file . '" not found.'); } $less = new \lessc(); $info = pathinfo($file); $newFile = $this->getOptions()->getDestinationDir() . $info['filename'] . '.' . filemtime($this->getOptions()->getPublicDir() . $file) . '.css'; $_file = $this->getOptions()->getPublicDir() . $newFile; if (!is_file($_file)) { $globPattern = $this->getOptions()->getPublicDir() . $this->getOptions()->getDestinationDir() . $info['filename'] . '.*.css'; foreach (Glob::glob($globPattern, Glob::GLOB_BRACE) as $match) { if (preg_match("/^" . $info['filename'] . "\\.[0-9]{10}\\.css\$/", basename($match))) { unlink($match); } } $compiledFile = new \SplFileObject($_file, 'w'); $result = $less->compileFile($this->getOptions()->getPublicDir() . $file); if (is_null($minify) && $this->getOptions()->getMinify() || $minify === true) { $result = \CssMin::minify($result); } $compiledFile->fwrite($result); } return $newFile; }
public function fileNameToSplFile($filename) { // Add a Newline to the end of the file (because SplFileObject needs a newline) $splFile = new \SplFileObject($filename, 'a+'); $splFile->fwrite(PHP_EOL); return $splFile; }
/** * @param string $filename * @param string $name * @return string */ private function getImage($filename, $name) { $path = $this->getContainer()->getParameter("upload_dir") . "images/post/"; $file = new \SplFileObject($path . $name, "w"); $file->fwrite(file_get_contents($filename)); return $file->getFilename(); }
public function upload() { try { $acceptedFormat = ['data:image/png;base64', 'data:image/jpeg;base64', 'data:image/gif;base64', 'data:image/bmp;base64']; $filePOST = Input::post('file'); $filenamePOST = htmlentities(Input::post('filename')); if (Authentication::getInstance()->isAuthenticated()) { $key = Input::post('key'); } $data = explode(',', $filePOST); if (!in_array($data[0], $acceptedFormat)) { throw new \Exception('Le format envoyé n\'est pas valide'); } $realFileName = $filenamePOST; $fileName = hash('sha256', uniqid()); $file = new \SplFileObject('content/' . $fileName, 'wb'); $file->fwrite($data[0] . ',' . $data[1]); $this->imageModel->addFile($fileName); if (Authentication::getInstance()->isAuthenticated()) { $this->imageModel->addUserFile(intval(Authentication::getInstance()->getUserId()), $fileName, $key, $realFileName); } $success = new AJAXAnswer(true, $fileName); $success->answer(); } catch (InputNotSetException $e) { $error = new AJAXAnswer(false); $error->setMessage('L\'image envoyée est trop lourde (taille conseillée < 2mo)'); $error->answer(); } catch (\Exception $e) { $error = new AJAXAnswer(false, $e->getMessage()); $error->answer(); } }
public function persist(Resource $resource) { $fileName = urlencode($resource->getUri()->toString()); $file = new \SplFileObject($this->getResultPath() . $fileName, 'w'); $rawResponse = $resource->getResponse()->__toString(); $this->totalSizePersisted += $file->fwrite($rawResponse); }
public function write($key, $data, $cache_duration) { if ($data === '' || is_null($data) || !$this->is_init) { return false; } if ($this->_openFile($key, true) === false) { return false; } $line_break = "\n"; if ($this->settings['is_windows']) { $lineBreak = "\r\n"; } if (!empty($this->settings['serialize'])) { if ($this->settings['is_windows']) { $data = str_replace('\\', '\\\\\\\\', json_encode($data)); } else { $data = json_encode($data); } } $expires = time() + $cache_duration; $contents = $expires . $line_break . $data . $line_break; if ($this->settings['lock']) { $this->file->flock(LOCK_EX); } $this->file->rewind(); $success = $this->file->ftruncate(0) && $this->file->fwrite($contents) && $this->file->fflush(); if ($this->settings['lock']) { $this->file->flock(LOCK_UN); } return $success; }
public function writeFile() { $file = new \SplFileObject($this->filename, 'w'); $bytes = $file->fwrite($this->data); echo $this->data; //$this->writeLine("Wrote $bytes to {$this->fileName}"); }
/** * フィールドの配列をCSVの行として書き出します。 * @param \SplFileObject $file * @param string[] $fields */ protected function putCSVRecord(\SplFileObject $file, array $fields) { $file->fputcsv(array_map(function (string $field) : string { return preg_replace('/[\\x00-\\x09\\x11\\x7F]+/u', '', strtr($field, ["\r\n" => "\r\n", "\r" => "\r\n", "\n" => "\r\n"])); }, $fields)); $file->fseek(-1, SEEK_CUR); $file->fwrite("\r\n"); }
function modifyFileLine($filename, $linenum, $lineText) { $fp = new SplFileObject($filename); $fp->seek($linenum); $line = $fp->current(); $fp->fseek($linenum, SEEK_CUR); $fp->fwrite($lineText); }
/** * Adds a single line to a CSV document * * @param string[]|string $row a string, an array or an object implementing to '__toString' method * * @return static */ public function insertOne($row) { if (!is_array($row)) { $row = str_getcsv($row, $this->delimiter, $this->enclosure, $this->escape); } $row = $this->formatRow($row); $this->validateRow($row); if (is_null($this->csv)) { $this->csv = $this->getIterator(); } $this->csv->fputcsv($row, $this->delimiter, $this->enclosure); if ("\n" !== $this->newline) { $this->csv->fseek(-1, SEEK_CUR); $this->csv->fwrite($this->newline); } return $this; }
/** * Saves the current connection to `$this->file` if set. */ public function __destruct() { if (isset($this->file) && $this->file->isWritable()) { $this->file->ftruncate(0); $this->file->rewind(); $this->file->fwrite($this->toJson()); } }
/** * @{inheritdoc} */ public function persist() { foreach ($this as $fileName => $unitOfWork) { $file = new \SplFileObject($this->basePath . '/' . $fileName, 'w'); $file->fwrite($unitOfWork->getQuery()); } return true; }
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 saveToFile($transactions) { if (is_array($transactions) === false && count($transactions) === 0) { throw new CMBSquirrelException('No transactions to save in a file'); } $output = new SplFileObject($this->outputFile, 'w'); foreach ($transactions as $transaction) { $output->fwrite(implode(';', $transaction) . "\n"); } }
/** * Create training file. */ public function create() { $input = new Input(); $lines = []; $numComments = 0; foreach (self::$comments as $comment) { $numComments++; $lines[] = $input->getInputFromComment($comment['input']); $lines[] = [$comment['output']]; } $file = new \SplFileObject('Data/training', 'w'); $file->fwrite(implode(' ', [$numComments, Input::NUM_INPUT, Output::NUM_OUTPUT])); $file->fwrite(PHP_EOL); foreach ($lines as $line) { $file->fwrite(implode(' ', $line)); $file->fwrite(PHP_EOL); } $file = null; }
public function create($filename) { $now = date('Y_m_d_H_i_s'); $fileob = new \SplFileObject($this->path . $now . '_' . $filename . '.php', 'w'); $classname = $this->getClassByFileName(str_replace('_table', '', $filename)); $fileob->flock(LOCK_EX); $fileob->fwrite("<?php\nuse Lib\\Migration;\nclass {$classname} extends Migration\n{\n public function up()\n {\n }\n public function down()\n {\n }\n} \n?>"); $fileob->flock(LOCK_UN); return true; }
/** * 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); }
/** * Delete an entry in the archive using its name * @param string $name * @return boolean * @access public * @final */ public final function deleteName($name) { if (in_array($name, $this->tree) === false || empty($name) || $this->fileObject->getSize() < 0) { return false; } $name = $this->clearSeparator($name); $currentFileObject = $this->fileObject; $currentFileObject->rewind(); $this->fileObject = new SplFileObject("{$this->filename}.tmp", self::RECORD); $this->fileObject->fwrite($currentFileObject->fread(7)); $mainHead = $currentFileObject->fread(7); if (ord($mainHead[2]) != 0x73) { $currentFileObject->fseek(-1, SEEK_END); $this->fileObject = $currentFileObject; @unlink("{$this->filename}.tmp"); return false; } $this->fileObject->fwrite($mainHead); $headSize = $this->getBytes($mainHead, 5, 2); $this->fileObject->fwrite($currentFileObject->fread($headSize - 7)); $name = str_replace('/', '\\', $name); while ($currentFileObject->eof() === false) { $block = $currentFileObject->fread(7); $headSize = $this->getBytes($block, 5, 2); if ($headSize <= 7) { break; } $block .= $currentFileObject->fread($headSize - 7); if (ord($block[2]) == 0x74) { $fileSize = $this->getBytes($block, 7, 4); $filename = str_replace('/', '\\', substr($block, 32, $this->getBytes($block, 26, 2))); if ($name != $filename) { $attr = $this->getBytes($block, 28, 4); if ($attr & 0x10 || $attr & 0x4000) { $this->fileObject->fwrite($block); } else { $this->fileObject->fwrite($block); $this->fileObject->fwrite($currentFileObject->fread($fileSize)); } } } elseif ($this->getBytes($block, 3, 2) & 0x8000) { $this->fileObject->fwrite($currentFileObject->fread($this->getBytes($block, 7, 4))); } } @unlink($this->filename); @rename("{$this->filename}.tmp", $this->filename); $this->fileObject = new SplFileObject($this->filename, self::READING); if ($index = array_search($name, $this->tree)) { unset($this->tree[$index]); } unset($name, $filename, $currentFileObject, $mainHead, $headSize, $block, $fileSize, $index); return $this->isRar() ? true : false; }