コード例 #1
1
 public static function getPlanning($year, $group, $week, $h = false)
 {
     $groupModel = new GroupsModel();
     $ids = $groupModel->getIDs($year, $group);
     $ids = $ids[0];
     $identFile = new ConfigFileParser('app/config/ident.json');
     $ident = $identFile->getEntry('ident');
     $fileName = 'public/img/img_planning/' . $ids['ID'] . '_' . $week . ($h ? '_h' : '') . '.png';
     try {
         $file = new \SplFileObject($fileName, 'rw');
         if ($file->getMTime() < time() - 900) {
             throw new \RuntimeException();
         }
     } catch (\RuntimeException $e) {
         $fp = fopen($fileName, 'w+');
         $url = 'http://planning.univ-amu.fr/ade/imageEt?identifier=' . $ident . '&projectId=8&idPianoWeek=' . $week . '&idPianoDay=0,1,2,3,4,5&idTree=' . $ids['IDTREE'] . '&width=1000&height=700&lunchName=REPAS&displayMode=1057855&showLoad=false&ttl=1405063872880000&displayConfId=' . ($h ? '60' : '59');
         $ch = curl_init(str_replace(" ", "%20", $url));
         curl_setopt($ch, CURLOPT_TIMEOUT, 50);
         curl_setopt($ch, CURLOPT_FILE, $fp);
         curl_setopt($ch, CURLOPT_FILE, $fp);
         curl_exec($ch);
         curl_close($ch);
     }
     return '/' . $fileName;
 }
コード例 #2
0
ファイル: PHPDocCommand.php プロジェクト: beyondit/ocok
 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);
     }
 }
コード例 #3
0
ファイル: CsvFileLoader.php プロジェクト: Dren-x/mobit
 /**
  * {@inheritdoc}
  */
 public function load($resource, $locale, $domain = 'messages')
 {
     if (!stream_is_local($resource)) {
         throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
     }
     if (!file_exists($resource)) {
         throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
     }
     $messages = array();
     try {
         $file = new \SplFileObject($resource, 'rb');
     } catch (\RuntimeException $e) {
         throw new NotFoundResourceException(sprintf('Error opening file "%s".', $resource), 0, $e);
     }
     $file->setFlags(\SplFileObject::READ_CSV | \SplFileObject::SKIP_EMPTY);
     $file->setCsvControl($this->delimiter, $this->enclosure, $this->escape);
     foreach ($file as $data) {
         if ('#' !== substr($data[0], 0, 1) && isset($data[1]) && 2 === count($data)) {
             $messages[$data[0]] = $data[1];
         }
     }
     $catalogue = parent::load($messages, $locale, $domain);
     if (class_exists('Symfony\\Component\\Config\\Resource\\FileResource')) {
         $catalogue->addResource(new FileResource($resource));
     }
     return $catalogue;
 }
コード例 #4
0
 /**
  * {@inheritdoc}
  */
 protected function loadResource($resource)
 {
     $messages = array();
     try {
         $file = new \SplFileObject($resource, 'rb');
     } catch (\RuntimeException $e) {
         throw new NotFoundResourceException(sprintf('Error opening file "%s".', $resource), 0, $e);
     }
     $file->setFlags(\SplFileObject::READ_CSV | \SplFileObject::SKIP_EMPTY);
     $file->setCsvControl($this->delimiter, $this->enclosure, $this->escape);
     foreach ($file as $data) {
         if (substr($data[0], 0, 1) === '#') {
             continue;
         }
         if (!isset($data[1])) {
             continue;
         }
         if (count($data) == 2) {
             $messages[$data[0]] = $data[1];
         } else {
             continue;
         }
     }
     return $messages;
 }
コード例 #5
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']);
 }
コード例 #6
0
ファイル: lib.php プロジェクト: subsevenx2001/HathHelper
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;
}
コード例 #7
0
 /**
  * @param ExportEventInterface $event
  * @throws CloseArchiveException
  * @throws OpenArchiveException
  * @throws UnavailableArchiveException
  */
 public function onCreateArchive(ExportEventInterface $event)
 {
     $archiveName = (string) Uuid::uuid1();
     $projectRootDir = realpath($this->projectRootDir);
     $archivePath = realpath($this->archiveDir) . '/' . $archiveName . '.zip';
     $archive = $this->openArchive($archivePath);
     foreach ($this->exportedCollection as $exportable) {
         if ($exportable instanceof ExportableInterface) {
             $exportPath = $projectRootDir . '/' . $exportable->getExportDestination();
             if (file_exists($exportPath)) {
                 $exportFile = new \SplFileObject($exportPath);
                 $archive->addFile($exportPath, $exportFile->getFilename());
             } else {
                 $this->logger->error(sprintf('Could not find export at "%s"', $exportPath));
                 // TODO Emit ErrorEvent to be handled later on for more robustness
                 continue;
             }
         }
     }
     $this->closeArchive($archive, $archivePath);
     if ($event instanceof JobAwareEventInterface) {
         if (!file_exists($archivePath)) {
             throw new UnavailableArchiveException(sprintf('Could not find archive at "%s"', $archivePath), UnavailableArchiveException::DEFAULT_CODE);
         }
         /** @var \WeavingTheWeb\Bundle\ApiBundle\Entity\Job $job */
         $job = $event->getJob();
         $archiveFile = new \SplFileObject($archivePath);
         $filename = str_replace('.zip', '', $archiveFile->getFilename());
         $router = $this->router;
         $getArchiveUrl = $this->router->generate('weaving_the_web_api_get_archive', ['filename' => $filename], $router::ABSOLUTE_PATH);
         $job->setOutput($getArchiveUrl);
     }
     $this->exportedCollection = [];
 }
コード例 #8
0
ファイル: Less.php プロジェクト: rickkuipers/justless
 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;
 }
コード例 #9
0
 /**
  * Returns the source filename for where the comment block was located
  *
  * @return string
  */
 public function getFilename()
 {
     if ($this->file === null) {
         return '';
     }
     return $this->file->getFilename();
 }
コード例 #10
0
 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();
     }
 }
コード例 #11
0
ファイル: csv.php プロジェクト: pombredanne/vulnDB
 public function insert($file, array $callback, $scan_info)
 {
     $class = $callback[0];
     $method = $callback[1];
     $class = Model::factory($class);
     $this->_handle = fopen($file, 'r');
     $headers = fgetcsv($this->_handle, $file);
     $scan_data = array();
     $file = new SplFileObject($file);
     $file->setFlags(SplFileObject::SKIP_EMPTY);
     $file->setFlags(SplFileObject::READ_AHEAD);
     $file->setFlags(SplFileObject::READ_CSV);
     $file->setCsvControl(",", '"', "\"");
     $c = 0;
     foreach ($file as $row) {
         $c++;
         if (count($row) === count($headers)) {
             $scan_data[] = array_combine($headers, $row);
             $row = array();
         }
         if ($c % $this->insert_threshold == 0) {
             Logger::msg('info', array('message' => 'flushing ' . $this->insert_threshold . ' rows', "class" => $callback[0], "method" => $callback[1], 'rows_inserted' => $c));
             Logger::msg('info', array('memory_usage' => $this->file_size(memory_get_usage())));
             $flush = $class->{$method}($scan_data, $scan_info);
             $scan_data = array();
         }
     }
     $flush = $class->{$method}($scan_data, $scan_info);
     $scan_data = array();
     Logger::msg('info', array('memory_usage' => $this->file_size(memory_get_usage())));
     return $c;
 }
コード例 #12
0
ファイル: ImageCommand.php プロジェクト: Eraac/TP-Blog
 /**
  * @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();
 }
コード例 #13
0
 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;
 }
コード例 #14
0
ファイル: Stream.php プロジェクト: codenamephp/platform.core
 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;
 }
コード例 #15
0
ファイル: SplFileInfo.php プロジェクト: JPunto/Symfony
 /**
  * Returns the contents of the file
  *
  * @return string the contents of the file
  */
 public function getContents()
 {
     $file = new \SplFileObject($this->getRealpath(), 'rb');
     ob_start();
     $file->fpassthru();
     return ob_get_clean();
 }
コード例 #16
0
ファイル: readFile.php プロジェクト: panchao1/my_php_code
/**
 * 返回文件从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);
}
コード例 #17
0
ファイル: Bot.php プロジェクト: mpyw/hardbotter
 /**
  * コンストラクタ
  * 副作用が大量にあるので注意
  */
 public function __construct(ClientInterface $client, $filename = 'stamp.json', $span = 0, $mark_limit = 10000, $back_limit = 3600)
 {
     // ヘッダの送出
     if (!headers_sent()) {
         header('Content-Type: text/html; charset=UTF-8');
     }
     // エラー表示の設定
     error_reporting(-1);
     ini_set('log_errors', PHP_SAPI === 'cli');
     ini_set('display_errors', PHP_SAPI !== 'cli');
     // 重複起動防止
     $file = new \SplFileObject($filename, 'a+b');
     if (!$file->flock(LOCK_EX | LOCK_NB)) {
         throw new \RuntimeException('Failed to lock file.');
     }
     // JSONとして保存してあるデータを取得
     clearstatcache();
     $json = $file->getSize() > 0 ? json_decode($file->fread($file->getSize()), true) : [];
     // JSONに前回実行時刻が保存されていた時
     if (isset($json['prev'])) {
         // 十分に時間が空いたかどうかをチェック
         if (!static::expired($json['prev'], $span)) {
             throw new \RuntimeException('Execution span is not enough.');
         }
     }
     // JSONにマーク済みステータス一覧が記録されていたとき復元する
     if (isset($json['marked'])) {
         $this->marked = array_map('filter_var', (array) $json['marked']);
     }
     $this->client = $client;
     $this->file = $file;
     $this->prev = (new \DateTimeImmutable('now', new \DateTimeZone('UTC')))->format('r');
     $this->mark_limit = $mark_limit;
     $this->back_limit = $back_limit;
 }
コード例 #18
0
ファイル: SimpleWriter.php プロジェクト: AgencyPMG/CsvSugar
 /**
  * {@inheritdoc}
  * @param array|Traversable $row The row to write
  */
 public function writeRow($row)
 {
     if ($row instanceof \Traversable) {
         $row = iterator_to_array($row);
     }
     $this->fileObject->fputcsv(is_array($row) ? $row : [$row]);
 }
コード例 #19
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>");
 }
コード例 #20
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";
         }
     }
 }
コード例 #21
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);
 }
コード例 #22
0
 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);
 }
コード例 #23
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');
     }
 }
コード例 #24
0
ファイル: data_store.php プロジェクト: ryanknu/zule-framework
 public function writeFile()
 {
     $file = new \SplFileObject($this->filename, 'w');
     $bytes = $file->fwrite($this->data);
     echo $this->data;
     //$this->writeLine("Wrote $bytes to {$this->fileName}");
 }
コード例 #25
0
ファイル: crouter.php プロジェクト: schigh/router
 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;
 }
コード例 #26
0
ファイル: citySearch.php プロジェクト: markbaker/quadtrees
function buildQuadTree($filename)
{
    //  Set the centrepoint of our QuadTree at 0.0 Longitude, 0.0 Latitude
    $centrePoint = new \QuadTrees\QuadTreeXYPoint(0.0, 0.0);
    //  Set the bounding box to the entire globe
    $quadTreeBoundingBox = new \QuadTrees\QuadTreeBoundingBox($centrePoint, 360, 180);
    //  Create our QuadTree
    $quadTree = new \QuadTrees\QuadTree($quadTreeBoundingBox);
    echo "Loading cities: ";
    $cityFile = new \SplFileObject($filename);
    $cityFile->setFlags(\SplFileObject::READ_CSV | \SplFileObject::DROP_NEW_LINE | \SplFileObject::SKIP_EMPTY);
    //  Populate our new QuadTree with cities from around the world
    $cityCount = 0;
    foreach ($cityFile as $cityData) {
        if (!empty($cityData[0])) {
            if ($cityCount % 1000 == 0) {
                echo '.';
            }
            $city = new cityPoint($cityData[0], $cityData[1], $cityData[3], $cityData[2]);
            $quadTree->insert($city);
            ++$cityCount;
        }
    }
    echo PHP_EOL, "Added {$cityCount} cities to QuadTree", PHP_EOL;
    return $quadTree;
}
コード例 #27
0
 /**
  * @param \SplFileObject $file             File
  * @param string         $sheet            Sheet title (optional)
  * @param string         $type             Excel file type (defaults to Excel2007)
  * @param bool           $prependHeaderRow
  */
 public function __construct(\SplFileObject $file, $sheet = null, $type = 'Excel2007', $prependHeaderRow = false)
 {
     $this->filename = $file->getPathname();
     $this->sheet = $sheet;
     $this->type = $type;
     $this->prependHeaderRow = $prependHeaderRow;
 }
コード例 #28
0
 /**
  * {@inheritdoc}
  *
  * @api
  */
 public function load($resource, $locale, $domain = 'messages')
 {
     $messages = array();
     try {
         $file = new \SplFileObject($resource, 'rb');
     } catch (\RuntimeException $e) {
         throw new \InvalidArgumentException(sprintf('Error opening file "%s".', $resource));
     }
     $file->setFlags(\SplFileObject::READ_CSV | \SplFileObject::SKIP_EMPTY);
     $file->setCsvControl($this->delimiter, $this->enclosure, $this->escape);
     foreach ($file as $data) {
         if (substr($data[0], 0, 1) === '#') {
             continue;
         }
         if (!isset($data[1])) {
             continue;
         }
         if (count($data) == 2) {
             $messages[$data[0]] = $data[1];
         } else {
             continue;
         }
     }
     $catalogue = parent::load($messages, $locale, $domain);
     $catalogue->addResource(new FileResource($resource));
     return $catalogue;
 }
コード例 #29
0
 /**
  * @param string       $code
  * @param PyStringNode $csv
  *
  * @Then /^exported file of "([^"]*)" should contain:$/
  *
  * @throws ExpectationException
  * @throws \Exception
  */
 public function exportedFileOfShouldContain($code, PyStringNode $csv)
 {
     $config = $this->getFixturesContext()->getJobInstance($code)->getRawConfiguration();
     $path = $this->getMainContext()->getSubcontext('job')->getJobInstancePath($code);
     if (!is_file($path)) {
         throw $this->getMainContext()->createExpectationException(sprintf('File "%s" doesn\'t exist', $path));
     }
     $delimiter = isset($config['delimiter']) ? $config['delimiter'] : ';';
     $enclosure = isset($config['enclosure']) ? $config['enclosure'] : '"';
     $escape = isset($config['escape']) ? $config['escape'] : '\\';
     $csvFile = new \SplFileObject($path);
     $csvFile->setFlags(\SplFileObject::READ_CSV | \SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY | \SplFileObject::DROP_NEW_LINE);
     $csvFile->setCsvControl($delimiter, $enclosure, $escape);
     $expectedLines = [];
     foreach ($csv->getLines() as $line) {
         if (!empty($line)) {
             $expectedLines[] = explode($delimiter, str_replace($enclosure, '', $line));
         }
     }
     $actualLines = [];
     while ($data = $csvFile->fgetcsv()) {
         if (!empty($data)) {
             $actualLines[] = array_map(function ($item) use($enclosure) {
                 return str_replace($enclosure, '', $item);
             }, $data);
         }
     }
     $expectedCount = count($expectedLines);
     $actualCount = count($actualLines);
     assertSame($expectedCount, $actualCount, sprintf('Expecting to see %d rows, found %d', $expectedCount, $actualCount));
     if (md5(json_encode($actualLines[0])) !== md5(json_encode($expectedLines[0]))) {
         throw new \Exception(sprintf('Header in the file %s does not match expected one: %s', $path, implode(' | ', $actualLines[0])));
     }
     unset($actualLines[0]);
     unset($expectedLines[0]);
     foreach ($expectedLines as $expectedLine) {
         $originalExpectedLine = $expectedLine;
         $found = false;
         foreach ($actualLines as $index => $actualLine) {
             // Order of columns is not ensured
             // Sorting the line values allows to have two identical lines
             // with values in different orders
             sort($expectedLine);
             sort($actualLine);
             // Same thing for the rows
             // Order of the rows is not reliable
             // So we generate a hash for the current line and ensured that
             // the generated file contains a line with the same hash
             if (md5(json_encode($actualLine)) === md5(json_encode($expectedLine))) {
                 $found = true;
                 // Unset line to prevent comparing it twice
                 unset($actualLines[$index]);
                 break;
             }
         }
         if (!$found) {
             throw new \Exception(sprintf('Could not find a line containing "%s" in %s', implode(' | ', $originalExpectedLine), $path));
         }
     }
 }
コード例 #30
0
function buildQuadTree($filename)
{
    //  Set the centrepoint of our QuadTree at 0.0 Longitude, 0.0 Latitude
    $centrePoint = new \QuadTrees\QuadTreeXYPoint(0.0, 0.0);
    //  Set the bounding box to the entire globe
    $quadTreeBoundingBox = new \QuadTrees\QuadTreeBoundingBox($centrePoint, 360, 180);
    //  Create our QuadTree
    $quadTree = new \QuadTrees\QuadTree($quadTreeBoundingBox);
    echo "Loading lunarLandings: ";
    $landingFile = new \SplFileObject($filename);
    $landingFile->setFlags(\SplFileObject::READ_CSV | \SplFileObject::DROP_NEW_LINE | \SplFileObject::SKIP_EMPTY);
    //  Populate our new QuadTree with lunarLandings from around the world
    $lunarLandingCount = 0;
    foreach ($landingFile as $lunarLandingData) {
        if (!empty($lunarLandingData[0])) {
            if ($lunarLandingCount % 10 == 0) {
                echo '.';
            }
            $lunarLanding = new lunarLandingPoint(trim($lunarLandingData[0]), trim($lunarLandingData[1]), trim($lunarLandingData[2]), trim($lunarLandingData[4]), trim($lunarLandingData[3]));
            $quadTree->insert($lunarLanding);
            ++$lunarLandingCount;
        }
    }
    echo PHP_EOL, "Added {$lunarLandingCount} lunar landing details to QuadTree", PHP_EOL;
    return $quadTree;
}