本文整理汇总了PHP中SplFileObject类的典型用法代码示例。如果您正苦于以下问题:PHP SplFileObject类的具体用法?PHP SplFileObject怎么用?PHP SplFileObject使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SplFileObject类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。
示例1: execute
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);
}
}
开发者ID:beyondit,项目名称:ocok,代码行数:32,代码来源:PHPDocCommand.php
示例2: loadResource
/**
* {@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;
}
开发者ID:niyomja,项目名称:laravel_redis,代码行数:28,代码来源:CsvFileLoader.php
示例3: load
/**
* {@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;
}
开发者ID:Dren-x,项目名称:mobit,代码行数:30,代码来源:CsvFileLoader.php
示例4: getPlanning
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;
}
开发者ID:thomasmunoz13,项目名称:planning_iut,代码行数:25,代码来源:Planning.php
示例5: _getCSVLine
/**
* 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']);
}
开发者ID:neterslandreau,项目名称:goinggreen,代码行数:14,代码来源:csv_import.php
示例6: upload_hathdl
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;
}
开发者ID:subsevenx2001,项目名称:HathHelper,代码行数:34,代码来源:lib.php
示例7: onCreateArchive
/**
* @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 = [];
}
开发者ID:WeavingTheWeb,项目名称:devobs,代码行数:40,代码来源:ExportSubscriber.php
示例8: __invoke
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;
}
开发者ID:rickkuipers,项目名称:justless,代码行数:25,代码来源:Less.php
示例9: upload
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();
}
}
开发者ID:vincent4vx,项目名称:image-secure,代码行数:32,代码来源:HomeController.php
示例10: insert
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;
}
开发者ID:pombredanne,项目名称:vulnDB,代码行数:32,代码来源:csv.php
示例11: getImage
/**
* @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();
}
开发者ID:Eraac,项目名称:TP-Blog,代码行数:12,代码来源:ImageCommand.php
示例12: fileNameToSplFile
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;
}
开发者ID:stevenbuehner,项目名称:import-jot-form,代码行数:7,代码来源:JotFormDownloadHelper.php
示例13: write
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;
}
开发者ID:codenamephp,项目名称:platform.core,代码行数:7,代码来源:Stream.php
示例14: getContents
/**
* 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();
}
开发者ID:JPunto,项目名称:Symfony,代码行数:12,代码来源:SplFileInfo.php
示例15: readFileByLines
/**
* 返回文件从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);
}
开发者ID:panchao1,项目名称:my_php_code,代码行数:42,代码来源:readFile.php
示例16: __construct
/**
* コンストラクタ
* 副作用が大量にあるので注意
*/
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;
}
开发者ID:mpyw,项目名称:hardbotter,代码行数:39,代码来源:Bot.php
示例17: execute
/**
* {@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>");
}
开发者ID:NCapiaumont,项目名称:comptes,代码行数:37,代码来源:KeywordsImportCommand.php
示例18: actionIndex
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";
}
}
}
开发者ID:super-d2,项目名称:codeigniter_demo,代码行数:29,代码来源:CheckBomCommand.php
示例19: setBodyFromReflection
/**
* @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);
}
开发者ID:tomaszdurka,项目名称:codegenerator,代码行数:29,代码来源:FunctionBlock.php
示例20: persist
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);
}
开发者ID:aigouzz,项目名称:php-spider,代码行数:7,代码来源:FileRawResponsePersistenceHandler.php
注:本文中的SplFileObject类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论