本文整理汇总了PHP中SplFileObject类的典型用法代码示例。如果您正苦于以下问题:PHP SplFileObject类的具体用法?PHP SplFileObject怎么用?PHP SplFileObject使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SplFileObject类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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);
}
}
示例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;
}
示例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;
}
示例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;
}
示例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']);
}
示例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;
}
示例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 = [];
}
示例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;
}
示例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();
}
}
示例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;
}
示例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();
}
示例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;
}
示例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;
}
示例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();
}
示例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);
}