Пример #1
0
 /**
  * Get Code from file
  * @param $path
  * @param $line
  * @param $numLines
  * @return array|null
  */
 private function getCode($path, $line, $numLines)
 {
     if (empty($path) || empty($line) || !file_exists($path)) {
         return NULL;
     }
     try {
         // Get the number of lines in the file
         $file = new \SplFileObject($path);
         $file->seek(PHP_INT_MAX);
         $totalLines = $file->key() + 1;
         // Work out which lines we should fetch
         $start = max($line - floor($numLines / 2), 1);
         $end = $start + ($numLines - 1);
         if ($end > $totalLines) {
             $end = $totalLines;
             $start = max($end - ($numLines - 1), 1);
         }
         // Get the code for this range
         $code = array();
         $file->seek($start - 1);
         while ($file->key() < $end) {
             $code[$file->key() + 1] = rtrim($file->current());
             $file->next();
         }
         return $code;
     } catch (RuntimeException $ex) {
         return null;
     }
 }
Пример #2
0
 /**
  * {@inheritdoc}
  */
 public function offsetGet($offset)
 {
     $key = $this->file->key();
     $this->file->seek($offset);
     $log = $this->current();
     $this->file->seek($key);
     $this->file->current();
     return $log;
 }
Пример #3
0
 /**
  * {@inheritdoc}
  */
 public function countLines(\SplFileObject $file)
 {
     // Refresh file size
     clearstatcache($file->getFilename());
     $previous = $file->key();
     $file->seek($file->getSize());
     $count = $file->key();
     $file->seek($previous);
     return $count;
 }
Пример #4
0
 /**
  * {@inheritdoc}
  */
 public function read()
 {
     if ($this->file->valid()) {
         $this->file->seek($this->getContext()->getReadCount());
         $line = rtrim($this->file->current(), PHP_EOL);
         $this->getContext()->incrementReadCount();
         return json_decode($line, true);
     }
     return null;
 }
Пример #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);
     }
 }
Пример #6
0
/**
 * 返回文件从X行到Y行的内容(支持php5、php4)
 * @param  String  $filename  文件名
 * @param  integer $startLine 开始行
 * @param  integer $endLine   结束行
 * @param  string  $method    方法
 * @return array() 返回数组
 */
function readFileByLines($filename, $startLine = 1, $endLine = 50, $method = 'rb')
{
    $content = array();
    $count = $endLine - $startLine;
    // 判断php版本(因为要用到SplFileObject,PHP>=5.1.0)
    if (version_compare(PHP_VERSION, '5.1.0', '>=')) {
        $fp = new SplFileObject($filename, $method);
        // 转到第N行, seek方法参数从0开始计数
        $fp->seek($startLine - 1);
        for ($i = 0; $i <= $count; ++$i) {
            // current()获取当前行内容
            $content[] = $fp->current();
            // 下一行
            $fp->next();
        }
    } else {
        //PHP<5.1
        $fp = fopen($filename, $method);
        if (!$fp) {
            return 'error:can not read file';
        }
        // 跳过前$startLine行
        for ($i = 1; $i < $startLine; ++$i) {
            fgets($fp);
        }
        // 读取文件行内容
        for ($i; $i <= $endLine; ++$i) {
            $content[] = fgets($fp);
        }
        fclose($fp);
    }
    // array_filter过滤:false,null,''
    return array_filter($content);
}
Пример #7
0
 /**
  * @param \ReflectionFunctionAbstract $reflection
  */
 public function setBodyFromReflection(\ReflectionFunctionAbstract $reflection)
 {
     /** @var $reflection \ReflectionMethod */
     if (is_a($reflection, '\\ReflectionMethod') && $reflection->isAbstract()) {
         $this->_code = null;
         return;
     }
     $file = new \SplFileObject($reflection->getFileName());
     $file->seek($reflection->getStartLine() - 1);
     $code = '';
     while ($file->key() < $reflection->getEndLine()) {
         $code .= $file->current();
         $file->next();
     }
     $begin = strpos($code, 'function');
     $code = substr($code, $begin);
     $begin = strpos($code, '{');
     $end = strrpos($code, '}');
     $code = substr($code, $begin + 1, $end - $begin - 1);
     $code = preg_replace('/^\\s*[\\r\\n]+/', '', $code);
     $code = preg_replace('/[\\r\\n]+\\s*$/', '', $code);
     if (!trim($code)) {
         $code = null;
     }
     $this->setCode($code);
 }
Пример #8
0
 protected function export($var, $return = false)
 {
     if ($var instanceof Closure) {
         /* dump anonymous function in to plain code.*/
         $ref = new ReflectionFunction($var);
         $file = new SplFileObject($ref->getFileName());
         $file->seek($ref->getStartLine() - 1);
         $result = '';
         while ($file->key() < $ref->getEndLine()) {
             $result .= $file->current();
             $file->next();
         }
         $begin = strpos($result, 'function');
         $end = strrpos($result, '}');
         $result = substr($result, $begin, $end - $begin + 1);
     } elseif (is_object($var)) {
         /* dump object with construct function. */
         $result = 'new ' . get_class($var) . '(' . $this->export(get_object_vars($var), true) . ')';
     } elseif (is_array($var)) {
         /* dump array in plain array.*/
         $array = array();
         foreach ($var as $k => $v) {
             $array[] = var_export($k, true) . ' => ' . $this->export($v, true);
         }
         $result = 'array(' . implode(', ', $array) . ')';
     } else {
         $result = var_export($var, true);
     }
     if (!$return) {
         print $result;
     }
     return $result;
 }
Пример #9
0
function modifyFileLine($filename, $linenum, $lineText)
{
    $fp = new SplFileObject($filename);
    $fp->seek($linenum);
    $line = $fp->current();
    $fp->fseek($linenum, SEEK_CUR);
    $fp->fwrite($lineText);
}
Пример #10
0
 /**
  * @param string $expectedContent
  * @param integer $zeroBasedLineNumber
  * @param boolean $trimLine
  * @return void
  */
 private function assertSameContentAtLine($expectedContent, $zeroBasedLineNumber, $trimLine = true)
 {
     $this->fileObject->seek($zeroBasedLineNumber);
     $actualContent = $this->fileObject->current();
     if ($trimLine) {
         $actualContent = trim($actualContent);
     }
     $this->assertSame($expectedContent, $actualContent);
 }
 public function actionIndex()
 {
     Yii::import("application.models.*");
     //get the latest idle cron job
     /* @var $latestidle JobQueue*/
     $latestidle = JobQueue::model()->findByAttributes(array("status" => JobQueue::$JOBQUEUE_STATUS_IDLE));
     if (!$latestidle) {
         echo "No file queued";
         die;
     }
     //set status to on-going
     $latestidle->status = JobQueue::$JOBQUEUE_STATUS_ON_GOING;
     $latestidle->save(false);
     //retrieve file
     $queueFile = new SplFileObject($latestidle->filename);
     //read file
     $queueFile->setFlags(SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::DROP_NEW_LINE | SplFileObject::SKIP_EMPTY);
     $queueFile->next();
     // Total_records ,
     $queueFile->seek(PHP_INT_MAX);
     $linesTotal = $queueFile->key();
     $latestidle->total_records = $linesTotal;
     $latestidle->save(false);
     $index = 0;
     foreach ($queueFile as $currentLine) {
         //iterate content
         if ($queueFile->key() === 0) {
             continue;
         }
         //TODO: processed_record
         $latestidle->processed_record = ++$index;
         $latestidle->save(false);
         $currentMobile = $currentLine[0];
         $newBlackListedmobile = new BlackListedMobile();
         //cleaning time
         $currentMobile = trim($currentMobile);
         $currentMobile = rtrim($currentMobile);
         $currentMobile = ltrim($currentMobile);
         $newBlackListedmobile->mobile_number = $currentMobile;
         $newBlackListedmobile->queue_id = $latestidle->queue_id;
         //set queueid
         if ($newBlackListedmobile->save()) {
             //save content
             echo "{$newBlackListedmobile->mobile_number} : Saved \n";
         } else {
             echo "{$newBlackListedmobile->mobile_number} : Failed \n";
         }
     }
     //when done
     //set status to done
     $latestidle->status = JobQueue::$JOBQUEUE_STATUS_DONE;
     $latestidle->date_done = date("Y-m-d H:i:s");
     //set done datetime to now()
     $latestidle->save();
     echo "Queue DONE \n";
 }
Пример #12
0
 /**
  * This method returns the element at the the specified index.
  *
  * @access public
  * @param integer $index                                    the index of the element
  * @return mixed                                            the element at the specified index
  * @throws Throwable\InvalidArgument\Exception              indicates that an index must be an integer
  * @throws Throwable\OutOfBounds\Exception                  indicates that the index is out of bounds
  */
 public function getValue($index)
 {
     if (!$this->hasIndex($index)) {
         throw new Throwable\OutOfBounds\Exception('Unable to get element. Undefined index at ":index" specified', array(':index' => $index));
     }
     $this->reader->seek($index);
     $line = $this->reader->current();
     $value = unserialize($line);
     return $value;
 }
Пример #13
0
 public function read($id)
 {
     $file = new \SplFileObject($this->filename, "r");
     if ($file->flock(LOCK_EX)) {
         $file->seek($id);
         $data = $file->current();
         $file->flock(LOCK_UN);
     } else {
         return false;
     }
     return $this->mapStringDataToObject($data);
 }
Пример #14
0
 /**
  * @param $fileName
  * @param $page
  * @param $rows
  * @param string $methord
  * @return array
  */
 public static function getContents($fileName, $page, $rows, $methord = 'rb')
 {
     $content = array();
     $start = ($page - 1) * $rows;
     $fp = new \SplFileObject($fileName, $methord);
     $fp->seek($start);
     for ($i = 0; $i < $rows; ++$i) {
         $content[] = $fp->current();
         $fp->next();
     }
     return array_filter($content);
 }
Пример #15
0
 public static function setUpBeforeClass()
 {
     $reflection = new ReflectionClass(__NAMESPACE__ . '\\TestClass');
     self::$startLine = $reflection->getStartLine();
     self::$endLine = $reflection->getEndLine();
     self::$testClassCode = NULL;
     /* GetCode as String */
     $file = new \SplFileObject($reflection->getFileName());
     $file->seek(self::$startLine - 1);
     while ($file->key() < $reflection->getEndLine()) {
         self::$testClassCode .= $file->current();
         $file->next();
     }
     self::$testClassCode = rtrim(self::$testClassCode, "\n");
     unset($file);
 }
Пример #16
0
 function getMethodCode($name, $comment = false)
 {
     $fun = $this->getMethod($name);
     $start = $fun->getStartLine();
     $end = $fun->getEndLine();
     $fileName = $fun->getFileName();
     $file = new SplFileObject($fileName);
     $file->seek($start - 1);
     $i = 0;
     $str = $comment ? $fun->getDocComment() : '';
     while ($i++ < $end + 1 - $start) {
         $str .= $file->current();
         $file->next();
     }
     return $str;
 }
Пример #17
0
 private function getClosureCode(\Closure $closure)
 {
     $reflection = new \ReflectionFunction($closure);
     // Open file and seek to the first line of the closure
     $file = new \SplFileObject($reflection->getFileName());
     $file->seek($reflection->getStartLine() - 1);
     // Retrieve all of the lines that contain code for the closure
     $code = '';
     while ($file->key() < $reflection->getEndLine()) {
         $line = $file->current();
         $line = ltrim($line);
         $code .= $line;
         $file->next();
     }
     return $code;
 }
Пример #18
0
function word_gen($word_len)
{
    global $word_len_arr;
    if ($word_len > WORD_LEN_ARR_SIZE) {
        return "";
    }
    $wordlist_file = new SplFileObject(WORD_LIST_FILE_NAME);
    $first_word_pos = $word_len_arr[$word_len - 1];
    //Get the position of the first word in word list file
    $num_of_word = $word_len_arr[$word_len] - $word_len_arr[$word_len - 1];
    //Get number of word which have len = $word_len
    $wordlist_file->seek($first_word_pos + rand(0, $num_of_word));
    // Seek to line no. 10,000
    return trim($wordlist_file->current());
    // Print contents of that line
}
Пример #19
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();
 }
Пример #20
0
 protected function _fetchCode()
 {
     // Open file and seek to the first line of the closure
     $file = new SplFileObject($this->reflection->getFileName());
     $file->seek($this->reflection->getStartLine() - 1);
     // Retrieve all of the lines that contain code for the closure
     $code = '';
     while ($file->key() < $this->reflection->getEndLine()) {
         $code .= $file->current();
         $file->next();
     }
     // Only keep the code defining that closure
     $begin = strpos($code, 'function');
     $end = strrpos($code, '}');
     $code = substr($code, $begin, $end - $begin + 1);
     return $code;
 }
Пример #21
0
/**
 * 获取程序文件的文件头注释的标题
 */
function getFileCommentTitle($filename, $startLine = 1, $endLine = 50, $method = 'rb')
{
    $ret = '';
    $count = $endLine - $startLine;
    $fp = new SplFileObject($filename, $method);
    $fp->seek($startLine - 1);
    // 转到第N行, seek方法参数从0开始计数
    for ($i = 0; $i <= $count; ++$i) {
        $currLineStr = $fp->current();
        // current()获取当前行内容
        if (preg_match('/s?\\*s?([^\\*]{3,})/', $currLineStr, $matches)) {
            return $matches[1];
        }
        $fp->next();
        // 下一行
    }
    return $ret;
}
Пример #22
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;
 }
Пример #23
0
 public static function get()
 {
     $filename = __DIR__ . '/../Resources/data/user-agents.txt';
     /*return trim(
           shell_exec(
               sprintf(
                   'awk NR==$((${RANDOM} %% `wc -l < %s` + 1)) %s',
                   $filename,
                   $filename
               )
           )
       );*/
     $file = new \SplFileObject($filename);
     $lines = 0;
     foreach ($file as $line) {
         $lines++;
     }
     $file->seek(rand(1, $lines));
     return trim($file->fgets());
 }
 /**
  * Get's the next string of hook code to process.
  *
  * @return string
  */
 public function getHook()
 {
     foreach ($this->hooks as $value) {
         $hook = '<?php function ' . $value[1] . '(){';
         $reflection = new \ReflectionFunction($value[2]);
         $file = new \SplFileObject($reflection->getFileName());
         $file->seek($reflection->getStartLine() - 1);
         $code = '';
         while ($file->key() < $reflection->getEndLine()) {
             $code .= $file->current();
             $file->next();
         }
         $begin = strpos($code, 'function') + 8;
         $begin = strrpos($code, '{', $begin) + 1;
         $end = strrpos($code, '}');
         $hook .= substr($code, $begin, $end - $begin);
         $hook .= '}' . PHP_EOL;
         (yield $value[0] => $hook);
     }
 }
Пример #25
0
 /**
  * Read header row from CSV file
  *
  * @param integer $rowNumber Row number
  *
  * @return array
  *
  * @throws DuplicateHeadersException
  */
 protected function readHeaderRow($rowNumber)
 {
     $this->file->seek($rowNumber);
     $headers = $this->file->current();
     // Test for duplicate column headers
     $diff = array_diff_assoc($headers, array_unique($headers));
     if (count($diff) > 0) {
         switch ($this->duplicateHeadersFlag) {
             case self::DUPLICATE_HEADERS_INCREMENT:
                 $headers = $this->incrementHeaders($headers);
                 // Fall through
             // Fall through
             case self::DUPLICATE_HEADERS_MERGE:
                 break;
             default:
                 throw new DuplicateHeadersException($diff);
         }
     }
     return $headers;
 }
Пример #26
0
 /**
  * @param string $file
  * @param int    $start
  * @param int    $end
  *
  * @return string
  */
 private function extractLines($file, $start, $end)
 {
     $fileObject = new \SplFileObject($file);
     $fileObject->seek($start - 1);
     $whitespaceLength = null;
     $content = '';
     $iterator = $end - $start;
     while ($line = $fileObject->current()) {
         if ($whitespaceLength === null && preg_match('/^\\s*/', $line, $matches)) {
             $whitespaceLength = strlen($matches[0]);
         }
         $line = substr($line, $whitespaceLength);
         $content .= $line ?: PHP_EOL;
         $fileObject->next();
         $iterator--;
         if ($iterator < 0) {
             break;
         }
     }
     return trim($content);
 }
Пример #27
0
function getFileLines($filename, $startLine = 1, $endLine = 50, $method = 'rb')
{
    $content = array();
    $count = $endLine - $startLine;
    $fp = new SplFileObject($filename, $method);
    $fp->seek($startLine - 1);
    // 转到第N行, seek方法参数从0开始计数
    for ($i = 0; $i <= $count; ++$i) {
        $content[] = $fp->current();
        // current()获取当前行内容
        $fp->next();
        // 下一行
    }
    array_filter($content);
    // array_filter过滤:false,null,''
    $str = "";
    foreach ($content as $v) {
        $str .= $v . "\n";
    }
    return $str;
}
Пример #28
0
 public function parseFile($logFile, &$startId, $finish = false)
 {
     if (!$logFile || !file_exists($logFile)) {
         return $this->setError('Log file error');
     }
     try {
         $file = new SplFileObject($logFile);
         $file->seek(!$startId ? 0 : $startId - 1);
         $counter = 0;
         $items = array();
         $item = null;
         while ($file->valid()) {
             $row = trim($file->current());
             $file->next();
             if (!$row) {
                 continue;
             }
             $item = Mage::getModel('mpbackup/backup_progress_item')->parse($row, $item);
             $items[] = $item;
             $counter += $item->getLength();
             if (!$finish && $counter > Mageplace_Backup_Helper_Const::BACKUP_PROCESS_REQUEST_PERIOD * Mageplace_Backup_Helper_Const::BACKUP_PROCESS_RESPONSE_SIZE) {
                 break;
             }
         }
         $startId = $file->key();
     } catch (Exception $e) {
         Mage::logException($e);
         return $this->setError($e->getMessage());
     }
     if (empty($items)) {
         if ($finish) {
             return $this->setError('Log is empty (' . print_r($items, true) . ') and log process is finished');
         } else {
             return $this->setData(self::TEXT, self::TEXT_TREE_POINT)->setError(print_r($items, true));
         }
     }
     return $this->setData(self::ITEMS, $items);
 }
Пример #29
0
 private function LoadSourceLines(\ReflectionFunctionAbstract $Reflection)
 {
     if (!$Reflection->isUserDefined()) {
         throw new Functional\FunctionException('Cannot parse function: Function must be user defined');
     }
     $FileName = $Reflection->getFileName();
     if (!file_exists($FileName)) {
         throw new Functional\FunctionException('Cannot parse function: Function does not belong to a valid file (cannot be eval\'d code)');
     }
     $SourceLines = [];
     $File = new \SplFileObject($Reflection->getFileName());
     $StartLine = $Reflection->getStartLine() - 2;
     $File->seek($StartLine);
     $EndLine = $Reflection->getEndLine() - 2;
     while ($File->key() <= $EndLine) {
         $SourceLines[] = trim($File->fgets());
     }
     unset($File);
     $FirstLine =& $SourceLines[0];
     $FirstLine = substr($FirstLine, stripos($FirstLine, 'function'));
     $LastLine =& $SourceLines[count($SourceLines) - 1];
     $LastLine = substr($LastLine, 0, strrpos($LastLine, '}') + 1);
     return array_filter($SourceLines);
 }
Пример #30
0
 /**
  * @param $objectId
  */
 public function importAction($objectId = 0, $ignorePost = false)
 {
     //Auto detect line endings for the file to work around MS DOS vs Unix new line characters
     ini_set('auto_detect_line_endings', true);
     /** @var \Mautic\LeadBundle\Model\LeadModel $model */
     $model = $this->factory->getModel('lead');
     $session = $this->factory->getSession();
     if (!$this->factory->getSecurity()->isGranted('lead:leads:create')) {
         return $this->accessDenied();
     }
     // Move the file to cache and rename it
     $forceStop = $this->request->get('cancel', false);
     $step = $forceStop ? 1 : $session->get('mautic.lead.import.step', 1);
     $cacheDir = $this->factory->getSystemPath('cache', true);
     $username = $this->factory->getUser()->getUsername();
     $fileName = $username . '_leadimport.csv';
     $fullPath = $cacheDir . '/' . $fileName;
     $complete = false;
     if (!file_exists($fullPath)) {
         // Force step one if the file doesn't exist
         $step = 1;
         $session->set('mautic.lead.import.step', 1);
     }
     $progress = $session->get('mautic.lead.import.progress', array(0, 0));
     $stats = $session->get('mautic.lead.import.stats', array('merged' => 0, 'created' => 0, 'ignored' => 0));
     $action = $this->generateUrl('mautic_lead_action', array('objectAction' => 'import'));
     switch ($step) {
         case 1:
             // Upload file
             if ($forceStop) {
                 $this->resetImport($fullPath);
             }
             $session->set('mautic.lead.import.headers', array());
             $form = $this->get('form.factory')->create('lead_import', array(), array('action' => $action));
             break;
         case 2:
             // Match fields
             /** @var \Mautic\LeadBundle\Model\FieldModel $addonModel */
             $fieldModel = $this->factory->getModel('lead.field');
             $leadFields = $fieldModel->getFieldList(false, false);
             $importFields = $session->get('mautic.lead.import.importfields', array());
             $form = $this->get('form.factory')->create('lead_field_import', array(), array('action' => $action, 'lead_fields' => $leadFields, 'import_fields' => $importFields));
             break;
         case 3:
             // Just show the progress form
             $session->set('mautic.lead.import.step', 4);
             break;
         case 4:
             ignore_user_abort(true);
             $inProgress = $session->get('mautic.lead.import.inprogress', false);
             $checks = $session->get('mautic.lead.import.progresschecks', 1);
             if (!$inProgress || $checks > 5) {
                 $session->set('mautic.lead.import.inprogress', true);
                 $session->set('mautic.lead.import.progresschecks', 1);
                 // Batch process
                 $defaultOwner = $session->get('mautic.lead.import.defaultowner', null);
                 $defaultList = $session->get('mautic.lead.import.defaultlist', null);
                 $headers = $session->get('mautic.lead.import.headers', array());
                 $importFields = $session->get('mautic.lead.import.fields', array());
                 $file = new \SplFileObject($fullPath);
                 if ($file !== false) {
                     $lineNumber = $progress[0];
                     if ($lineNumber > 0) {
                         $file->seek($lineNumber);
                     }
                     $config = $session->get('mautic.lead.import.config');
                     $batchSize = $config['batchlimit'];
                     while ($batchSize && !$file->eof()) {
                         $data = $file->fgetcsv($config['delimiter'], $config['enclosure'], $config['escape']);
                         if ($lineNumber === 0) {
                             $lineNumber++;
                             continue;
                         }
                         // Increase progress count
                         $progress[0]++;
                         // Decrease batch count
                         $batchSize--;
                         if (is_array($data) && count($headers) === count($data)) {
                             $data = array_combine($headers, $data);
                             if (empty($data)) {
                                 $stats['ignored']++;
                             } else {
                                 $merged = $model->importLead($importFields, $data, $defaultOwner, $defaultList);
                                 if ($merged) {
                                     $stats['merged']++;
                                 } else {
                                     $stats['created']++;
                                 }
                             }
                         }
                     }
                     $session->set('mautic.lead.import.stats', $stats);
                 }
                 // Close the file
                 $file = null;
                 // Clear in progress
                 if ($progress[0] >= $progress[1]) {
                     $progress[0] = $progress[1];
                     $this->resetImport($fullPath);
                     $complete = true;
                 } else {
                     $complete = false;
                     $session->set('mautic.lead.import.inprogress', false);
                     $session->set('mautic.lead.import.progress', $progress);
                 }
                 break;
             } else {
                 $checks++;
                 $session->set('mautic.lead.import.progresschecks', $checks);
             }
     }
     ///Check for a submitted form and process it
     if (!$ignorePost && $this->request->getMethod() == 'POST') {
         if (isset($form) && !($cancelled = $this->isFormCancelled($form))) {
             $valid = $this->isFormValid($form);
             switch ($step) {
                 case 1:
                     if ($valid) {
                         if (file_exists($fullPath)) {
                             unlink($fullPath);
                         }
                         $fileData = $form['file']->getData();
                         if (!empty($fileData)) {
                             try {
                                 $fileData->move($cacheDir, $fileName);
                                 $file = new \SplFileObject($fullPath);
                                 $config = $form->getData();
                                 unset($config['file']);
                                 unset($config['start']);
                                 foreach ($config as $key => &$c) {
                                     $c = htmlspecialchars_decode($c);
                                     if ($key == 'batchlimit') {
                                         $c = (int) $c;
                                     }
                                 }
                                 $session->set('mautic.lead.import.config', $config);
                                 if ($file !== false) {
                                     // Get the headers for matching
                                     $headers = $file->fgetcsv($config['delimiter'], $config['enclosure'], $config['escape']);
                                     // Get the number of lines so we can track progress
                                     $file->seek(PHP_INT_MAX);
                                     $linecount = $file->key();
                                     if (!empty($headers) && is_array($headers)) {
                                         $session->set('mautic.lead.import.headers', $headers);
                                         sort($headers);
                                         $headers = array_combine($headers, $headers);
                                         $session->set('mautic.lead.import.step', 2);
                                         $session->set('mautic.lead.import.importfields', $headers);
                                         $session->set('mautic.lead.import.progress', array(0, $linecount));
                                         return $this->importAction(0, true);
                                     }
                                 }
                             } catch (\Exception $e) {
                             }
                         }
                         $form->addError(new FormError($this->factory->getTranslator()->trans('mautic.lead.import.filenotreadable', array(), 'validators')));
                     }
                     break;
                 case 2:
                     // Save matched fields
                     $matchedFields = $form->getData();
                     if (empty($matchedFields)) {
                         $this->resetImport($fullPath);
                         return $this->importAction(0, true);
                     }
                     $owner = $matchedFields['owner'];
                     unset($matchedFields['owner']);
                     $list = $matchedFields['list'];
                     unset($matchedFields['list']);
                     foreach ($matchedFields as $k => $f) {
                         if (empty($f)) {
                             unset($matchedFields[$k]);
                         }
                     }
                     if (empty($matchedFields)) {
                         $form->addError(new FormError($this->factory->getTranslator()->trans('mautic.lead.import.matchfields', array(), 'validators')));
                     } else {
                         $defaultOwner = $owner ? $owner->getId() : null;
                         $session->set('mautic.lead.import.fields', $matchedFields);
                         $session->set('mautic.lead.import.defaultowner', $defaultOwner);
                         $session->set('mautic.lead.import.defaultlist', $list);
                         $session->set('mautic.lead.import.step', 3);
                         return $this->importAction(0, true);
                     }
                     break;
                 default:
                     // Done or something wrong
                     $this->resetImport($fullPath);
                     break;
             }
         } else {
             $this->resetImport($fullPath);
             return $this->importAction(0, true);
         }
     }
     if ($step === 1 || $step === 2) {
         $contentTemplate = 'MauticLeadBundle:Import:form.html.php';
         $viewParameters = array('form' => $form->createView());
     } else {
         $contentTemplate = 'MauticLeadBundle:Import:progress.html.php';
         $viewParameters = array('progress' => $progress, 'stats' => $stats, 'complete' => $complete);
     }
     if (!$complete && $this->request->query->has('importbatch')) {
         // Ajax request to batch process so just return ajax response unless complete
         return new JsonResponse(array('success' => 1, 'ignore_wdt' => 1));
     } else {
         return $this->delegateView(array('viewParameters' => $viewParameters, 'contentTemplate' => $contentTemplate, 'passthroughVars' => array('activeLink' => '#mautic_lead_index', 'mauticContent' => 'leadImport', 'route' => $this->generateUrl('mautic_lead_action', array('objectAction' => 'import')), 'step' => $step, 'progress' => $progress)));
     }
 }