private function readBytes($length)
 {
     $stream = null;
     for ($cc = 0; $cc < $length; $cc++) {
         if ($this->file->eof()) {
             return null;
         }
         $stream .= $this->file->fgetc();
     }
     return $stream;
 }
Exemplo n.º 2
0
 /**
  * @param $file
  * @param null $defaultPatternPattern
  */
 public function __construct($file, $defaultPatternPattern = null)
 {
     parent::__construct($defaultPatternPattern);
     $this->file = new \SplFileObject($file, 'r');
     $i = 0;
     while (!$this->file->eof()) {
         $this->file->current();
         $this->file->next();
         $i++;
     }
     $this->lineCount = $i;
     $this->parser = $this->getDefaultParser();
 }
function test($name)
{
    echo "==={$name}===\n";
    $o = new SplFileObject(dirname(__FILE__) . '/' . $name);
    var_dump($o->key());
    while (($c = $o->fgetc()) !== false) {
        var_dump($o->key(), $c, $o->eof());
    }
    echo "===EOF?===\n";
    var_dump($o->eof());
    var_dump($o->key());
    var_dump($o->eof());
}
Exemplo n.º 4
0
 /**
  * @param        $file
  * @param int    $days
  * @param string $pattern
  */
 public function __construct($file, $days = 1, $pattern = 'default')
 {
     $this->file = new \SplFileObject($file, 'r');
     $i = 0;
     while (!$this->file->eof()) {
         $this->file->current();
         $this->file->next();
         $i++;
     }
     $this->days = $days;
     $this->pattern = $pattern;
     $this->lineCount = $i;
     $this->parser = $this->getDefaultParser($days, $pattern);
 }
Exemplo n.º 5
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if (parent::execute($input, $output)) {
         $this->loadOCConfig();
         $properties = array('string $id', 'string $template', 'array $children', 'array $data', 'string $output');
         // TODO: get all library classes as well, maybe extract from registry somehow...
         $searchLine = "abstract class Controller {";
         $pathToController = "engine/controller.php";
         $catalogModels = $this->getModels(\DIR_APPLICATION);
         $adminModels = $this->getModels(str_ireplace("catalog/", "admin/", \DIR_APPLICATION));
         $textToInsert = array_unique(array_merge($properties, $catalogModels, $adminModels));
         //get line number where start Controller description
         $fp = fopen(\DIR_SYSTEM . $pathToController, 'r');
         $lineNumber = $this->getLineOfFile($fp, $searchLine);
         fclose($fp);
         //regenerate Controller text with properties
         $file = new \SplFileObject(\DIR_SYSTEM . $pathToController);
         $file->seek($lineNumber);
         $tempFile = sprintf("<?php %s \t/**%s", PHP_EOL, PHP_EOL);
         foreach ($textToInsert as $val) {
             $tempFile .= sprintf("\t* @property %s%s", $val, PHP_EOL);
         }
         $tempFile .= sprintf("\t**/%s%s%s", PHP_EOL, $searchLine, PHP_EOL);
         while (!$file->eof()) {
             $tempFile .= $file->fgets();
         }
         //write Controller
         $fp = fopen(\DIR_SYSTEM . $pathToController, 'w');
         fwrite($fp, $tempFile);
         fclose($fp);
     }
 }
Exemplo n.º 6
0
function upload_hathdl()
{
    $file = new SplFileObject($_FILES['ehgfile']['tmp_name']);
    $gid = -1;
    $page = -1;
    $title = null;
    $tags = null;
    while (!$file->eof()) {
        $line = $file->fgets();
        $line = trim($line);
        $token = explode(' ', $line);
        if (strcmp($token[0], 'GID') == 0) {
            $gid = intval($token[1]);
        } else {
            if (strcmp($token[0], 'FILES') == 0) {
                $page = intval($token[1]);
            } else {
                if (strcmp($token[0], 'TITLE') == 0) {
                    $title = trim(preg_replace('TITLE', '', $line));
                } else {
                    if (strcmp($token[0], 'Tags:') == 0) {
                        $tags = trim(preg_replace('Tags:', '', $line));
                    }
                }
            }
        }
    }
    shell_exec('cp ' . $_FILES['ehgfile']['tmp_name'] . ' hentaiathome/hathdl/');
    $info['gid'] = $gid;
    $info['page'] = $page;
    $info['title'] = $title;
    $info['tags'] = $tags;
    return $info;
}
Exemplo n.º 7
0
 /**
  * True if not EOF
  *
  * @return boolean
  */
 public function valid()
 {
     if (null === $this->_file) {
         $this->_openFile();
     }
     return $this->_file && !$this->_file->eof();
 }
Exemplo n.º 8
0
 /**
  * Returns a line form the CSV file and advances the pointer to the next one
  *
  * @param Model $Model
  * @param SplFileObject $handle CSV file handler
  * @return array list of attributes fetched from the CSV file
  */
 protected function _getCSVLine(Model &$Model, SplFileObject $handle)
 {
     if ($handle->eof()) {
         return false;
     }
     return $handle->fgetcsv($this->settings[$Model->alias]['delimiter'], $this->settings[$Model->alias]['enclosure']);
 }
Exemplo n.º 9
0
 public function actionIndex($path = null, $fix = null)
 {
     if ($path === null) {
         $path = YII_PATH;
     }
     echo "Checking {$path} for files with BOM.\n";
     $checkFiles = CFileHelper::findFiles($path, array('exclude' => array('.gitignore')));
     $detected = false;
     foreach ($checkFiles as $file) {
         $fileObj = new SplFileObject($file);
         if (!$fileObj->eof() && false !== strpos($fileObj->fgets(), self::BOM)) {
             if (!$detected) {
                 echo "Detected BOM in:\n";
                 $detected = true;
             }
             echo $file . "\n";
             if ($fix) {
                 file_put_contents($file, substr(file_get_contents($file), 3));
             }
         }
     }
     if (!$detected) {
         echo "No files with BOM were detected.\n";
     } else {
         if ($fix) {
             echo "All files were fixed.\n";
         }
     }
 }
Exemplo n.º 10
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $values = $form_state->getValues();
     $file = File::load($values['file'][0]);
     // Load File entity.
     $read_file = new \SplFileObject($file->url());
     // Create file handler.
     $lines = 1;
     $in_queue = 0;
     $queue = \Drupal::queue('eventninja');
     // Load queue
     while (!$read_file->eof()) {
         $data = $read_file->fgetcsv(';');
         if ($lines > 1) {
             // skip headers
             $user = user_load_by_mail($data[1]);
             if ($user === false) {
                 // Verify if user with specified email does not exist.
                 $queue->createItem($data);
                 $in_queue++;
             } else {
                 $this->logger('eventninja')->log(RfcLogLevel::NOTICE, 'User {mail} hasn\'t been created.', ['mail' => $data[1]]);
             }
         }
         $lines++;
     }
     if ($lines > 1) {
         drupal_set_message($this->t('@num records was scheduled for import', array('@num' => $in_queue)), 'success');
     } else {
         drupal_set_message($this->t('File contains only headers'), 'error');
     }
 }
Exemplo n.º 11
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $filename = $input->getArgument('filename');
     if (!file_exists($filename)) {
         throw new \Symfony\Component\HttpKernel\Exception\BadRequestHttpException("Le fichier {$filename} n'existe pas.");
     }
     // Indicateurs
     $i = 0;
     // Nombre de mots-clés importés
     $em = $this->getContainer()->get('doctrine')->getManager();
     $categorieRepository = $em->getRepository('ComptesBundle:Categorie');
     $file = new \SplFileObject($filename);
     while (!$file->eof()) {
         $line = $file->fgets();
         list($word, $categorieID) = explode(':', $line);
         $word = trim($word);
         $categorieID = (int) $categorieID;
         $categorie = $categorieRepository->find($categorieID);
         if ($categorie === null) {
             throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException("La catégorie n°{$categorieID} est inconnue.");
         }
         $keyword = new Keyword();
         $keyword->setWord($word);
         $keyword->setCategorie($categorie);
         // Indicateurs
         $i++;
         // Enregistrement
         $em->persist($keyword);
     }
     // Persistance des données
     $em->flush();
     // Indicateurs
     $output->writeln("<info>{$i} mots-clés importés</info>");
 }
Exemplo n.º 12
0
 /**
  * Load file content and decode the json
  */
 protected function loadJson()
 {
     $lines = '';
     while (!$this->file->eof()) {
         $lines .= $this->file->fgets();
     }
     $this->json = json_decode($lines);
 }
Exemplo n.º 13
0
 public function __construct($csvFile)
 {
     $file = new SplFileObject($csvFile);
     while (!$file->eof()) {
         $csv[] = $file->fgetcsv();
     }
     $this->File = $csv;
 }
Exemplo n.º 14
0
 public function __construct($filepath)
 {
     $file = new \SplFileObject($filepath);
     $this->path = $file->getFilename();
     while (!$file->eof()) {
         $this->content .= $file->fgets();
     }
 }
Exemplo n.º 15
0
 /**
  * Write the compiled csv to disk and return the file name
  *
  * @param array $sortedHeaders An array of sorted headers
  *
  * @return string The csv filename where the data was written
  */
 public function prepare($cacheFile, $sortedHeaders)
 {
     $csvFile = $cacheFile . '.csv';
     $handle = fopen($csvFile, 'w');
     // Generate a csv version of the multi-row headers to write to disk
     $headerRows = [[], []];
     foreach ($sortedHeaders as $idx => $header) {
         if (!is_array($header)) {
             $headerRows[0][] = $header;
             $headerRows[1][] = '';
         } else {
             foreach ($header as $headerName => $subHeaders) {
                 $headerRows[0][] = $headerName;
                 $headerRows[1] = array_merge($headerRows[1], $subHeaders);
                 if (count($subHeaders) > 1) {
                     /**
                      * We need to insert empty cells for the first row of headers to account for the second row
                      * this acts as a faux horizontal cell merge in a csv file
                      * | Header 1 | <---- 2 extra cells ----> |
                      * | Sub 1    | Subheader 2 | Subheader 3 |
                      */
                     $headerRows[0] = array_merge($headerRows[0], array_fill(0, count($subHeaders) - 1, ''));
                 }
             }
         }
     }
     fputcsv($handle, $headerRows[0]);
     fputcsv($handle, $headerRows[1]);
     // TODO: Track memory usage
     $file = new \SplFileObject($cacheFile);
     while (!$file->eof()) {
         $csvRow = [];
         $row = json_decode($file->current(), true);
         if (!is_array($row)) {
             // Invalid json data -- don't process this row
             continue;
         }
         foreach ($sortedHeaders as $idx => $header) {
             if (!is_array($header)) {
                 $csvRow[] = isset($row[$header]) ? $row[$header] : '';
             } else {
                 // Multi-row header, so we need to set all values
                 $nestedHeaderName = array_keys($header)[0];
                 $nestedHeaders = $header[$nestedHeaderName];
                 foreach ($nestedHeaders as $nestedHeader) {
                     $csvRow[] = isset($row[$nestedHeaderName][$nestedHeader]) ? $row[$nestedHeaderName][$nestedHeader] : '';
                 }
             }
         }
         fputcsv($handle, $csvRow);
         $file->next();
     }
     $file = null;
     // Get rid of the file handle that SplFileObject has on cache file
     unlink($cacheFile);
     fclose($handle);
     return $csvFile;
 }
 private function content(SplFileObject $file)
 {
     $result = "";
     $file->fseek(0);
     while (!$file->eof()) {
         $result .= $file->fread(1024);
     }
     return $result;
 }
Exemplo n.º 17
0
 /**
  * @param \SplFileObject $stream
  *
  * Reads the file to parse its lines
  */
 public function readFile(\SplFileObject $stream)
 {
     $stream->setFlags(\SplFileObject::READ_CSV | \SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY | \SplFileObject::DROP_NEW_LINE);
     while (!$stream->eof()) {
         $this->parseLine($stream->current());
         $stream->next();
     }
     $stream = null;
 }
 /**
  * Parses a file of data into a php array.
  *
  * @param \SplFileObject $file
  *
  * @return array
  */
 public function parse(\SplFileObject $file)
 {
     $result = [];
     $delimiter = $this->options['delimiter'];
     $enclosure = $this->options['enclosure'];
     $escape = $this->options['escape'];
     while (!$file->eof()) {
         $this->formatLine($result, $file->fgetcsv($delimiter, $enclosure, $escape));
     }
     return $result;
 }
Exemplo n.º 19
0
 /**
  * @return int
  */
 public function getTotal()
 {
     if ($this->total === null) {
         $this->csvFile->fseek(0);
         $lines = 0;
         while (!$this->csvFile->eof()) {
             $lines += substr_count($this->csvFile->fread(8192), $this->lineSeparator);
         }
         $this->total = (int) $lines;
     }
     return $this->total;
 }
Exemplo n.º 20
0
 /**
  * Imports given JSON file
  * @param string $filePath Path to a JSON file with data to import
  * @return array Array with import output - metadata, status, warnings and errors
  */
 public function importFile($filePath)
 {
     $this->tmpFile = new SplFileObject($filePath, "r");
     $curState = new JSONImportStateStart(array('meta' => array(), 'result' => array(), 'user_id' => $this->params['user_id']));
     $result = array('success' => false);
     $stepResult = false;
     while (!$this->tmpFile->eof()) {
         $curLine = trim($this->tmpFile->fgets());
         $stepResult = $curState->processLine($curLine);
         // Returns next state for processing
         if (!is_array($stepResult)) {
             $curState = $stepResult;
             // Returned array with results
         } else {
             $result = $stepResult;
             $result['success'] = true;
             break;
         }
     }
     return $result;
 }
Exemplo n.º 21
0
 public static function SendNewOrderMessage($account, $orderId, $PriceSum)
 {
     $file = new SplFileObject(__ROOT__ . '/application/EmailService/EmailTemplates/order.txt');
     $message = '';
     while (!$file->eof()) {
         $message = $message . $file->fgets();
     }
     $message = str_replace('@AccountName', $account->account_name, $message);
     $message = str_replace('@OrderId', $orderId, $message);
     $message = str_replace('@Price', $PriceSum, $message);
     mail($account->email, 'Регистрация', $message, 'Content-type:text/html;');
 }
Exemplo n.º 22
0
 /**
  *
  * 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;
 }
Exemplo n.º 23
0
 /**
  * @param \Closure $callback
  */
 protected function parseFile(\Closure $callback)
 {
     while (!$this->file->eof()) {
         if (strlen($this->delim) == 1) {
             $data = $this->file->fgetcsv($this->delim, $this->enclosure);
         } else {
             $data = explode($this->delim, $this->file->fgets());
             $data = array_map(function ($row) {
                 return mb_convert_encoding(trim($row, $this->enclosure), "UTF-8", "Windows-1252,ISO-8859-15");
             }, $data);
             if ($this->debug) {
                 break;
             }
             /*
              $enclosure = $this->enclosure;
              array_walk($data, function(&$val) use ($enclosure) {
                 return trim($val, $enclosure);
             });
             */
         }
         $callback($data);
     }
 }
Exemplo n.º 24
0
 /**
  * @test
  */
 public function dump()
 {
     $root = vfsStream::setup('root');
     vfsStream::newFile('directives.csv')->at($root);
     $dumper = new FileDumper(vfsStream::url('root/directives.csv'));
     $values = [['add', 'file1', 'file1'], ['add', 'file2', 'file2']];
     $dumper->dump($values);
     $reader = new \SplFileObject(vfsStream::url('root/directives.csv'));
     $actual = [];
     while ($reader->eof() === false) {
         $actual[] = $reader->fgetcsv();
     }
     $this->assertEquals($values, $actual);
 }
 /**
  * Parses a file of data into a php array.
  *
  * @param \SplFileObject $file
  *
  * @return array
  */
 public function parse(\SplFileObject $file)
 {
     $delimiter = $this->options['delimiter'];
     $enclosure = $this->options['enclosure'];
     $escape = $this->options['escape'];
     $header = $file->fgetcsv($delimiter, $enclosure, $escape);
     $result = [];
     while (!$file->eof()) {
         $line = $file->fgetcsv($delimiter, $enclosure, $escape);
         // If row is not a blank line.
         if (!empty($line[0])) {
             $result[] = array_combine($header, $line);
         }
     }
     return $result;
 }
Exemplo n.º 26
0
 public function do_work()
 {
     if ($this->done) {
         return;
     }
     $file = new SplFileObject($this->csv_file);
     $file->seek($this->current_line);
     $n = 0;
     while ($n < $this->settings['batch-size']) {
         if ($file->eof()) {
             $this->done = true;
             break;
         }
         $line = $file->current();
         // Some code to circumvent limitations in str_getcsv() while PHP #46569 is fixed.
         $line = str_replace('\\n', "\n", $line);
         // We can't use fgetcsv() directly due to https://bugs.php.net/bug.php?id=46569.
         $line_data = str_getcsv($line, $this->settings['csv-file-separator']);
         $file->next();
         $n++;
         $this->current_line = $file->key();
         $this->processed_lines++;
         if (!$line_data || count($line_data) == 1 && empty($line_data[0])) {
             continue;
         }
         list($listing_data, $errors) = $this->sanitize_and_validate_row($line_data);
         if ($errors) {
             foreach ($errors as $e) {
                 $this->errors[] = array('line' => $this->current_line, 'content' => $line, 'error' => $e);
             }
             $this->rejected++;
             continue;
         }
         $result = $this->import_row($listing_data);
         @set_time_limit(2);
         if (is_wp_error($result)) {
             foreach ($result->get_error_messages() as $e) {
                 $this->errors[] = array('line' => $this->current_line, 'content' => $line, 'error' => $e);
             }
             $this->rejected++;
             continue;
         }
         $this->imported++;
     }
     $file = null;
     $this->state_persist();
 }
Exemplo n.º 27
0
 /**
  * Extracts data from the file
  * @param  SplFileObject $fileObject  File object.
  * @throws                            Invalid data exception.
  * @return array                      Filtered data.
  */
 private function extractData($fileObject)
 {
     $data = array();
     while (!$fileObject->eof()) {
         $line = trim($fileObject->fgets());
         if (!empty($line)) {
             //2 or more white spaces in case of team name with a space
             $parts = preg_split('/\\s{2,}/', $line);
             if (count($parts) == 9) {
                 $data[] = $parts;
             } else {
                 throw new Exception('Invalid data');
             }
         }
     }
     return $data;
 }
Exemplo n.º 28
0
 private function displaySource(\Exception $e)
 {
     $source = '';
     $file = new \SplFileObject($e->getFile());
     $lineNum = $e->getLine() - 4;
     if ($lineNum < 1) {
         $lineNum = 1;
     }
     $file->seek($lineNum);
     for ($l = 0; $l < 8; $l++) {
         if ($file->eof()) {
             break;
         }
         $source .= $file->current();
         $file->next();
     }
     return $source;
 }
Exemplo n.º 29
0
 /**
  * Evaluates the closure and the code in the reset of the file. This sets
  * the code for the closure, the namespace it is declared in (if any) and
  * any applicable namespace imports
  * @param ReflectionFunction The reflected function of the closure
  * @return String The code the closure runs 
  */
 private function evaluate(\ReflectionFunction $reflection)
 {
     $code = '';
     $full = '';
     $file = new \SplFileObject($reflection->getFileName());
     while (!$file->eof()) {
         if ($file->key() >= $reflection->getStartLine() - 1 && $file->key() < $reflection->getEndLine()) {
             $code .= $file->current();
         }
         $full .= $file->current();
         $file->next();
     }
     //@todo this assumes the function will be the only one on that line
     $begin = strpos($code, 'function');
     //@todo this assumes the } will be the only one on that line
     $end = strrpos($code, '}');
     $this->code = substr($code, $begin, $end - $begin + 1);
     $this->extractDetail($full);
 }
Exemplo n.º 30
0
function processCsv($file, $omitTitles = true)
{
    $csv = new SplFileObject($file);
    $records = 0;
    if ($omitTitles) {
        // Get the first line but do nothing with it
        $csv->getCurrentLine();
    }
    while (!$csv->eof()) {
        // Get the current line
        $line = $csv->fgetcsv();
        // Skip blank lines that return a single null element
        if (count($line) > 1 && !is_null($line[0])) {
            (yield $line);
            $records++;
        }
    }
    return "{$records} records processed from {$file}";
}