Example #1
0
 /**
  * @param string[] $items
  * @return bool
  */
 public function writeArray(array $items)
 {
     $content = $this->generateFileContentForArray($items);
     $file = $this->fileInfo->openFile('w');
     $file->fwrite($content);
     return $file->fflush();
 }
Example #2
0
 /**
  * Create a file if is not already exists.
  * @return self
  */
 protected function _createFeedLockFile()
 {
     if (!$this->_isFeedLockFileExist()) {
         $this->_stream->openFile(static::FILE_OPEN_MODE);
     }
     return $this;
 }
 /**
  * @return \SplFileObject
  */
 protected function getFile()
 {
     if (!$this->file instanceof \SplFileObject) {
         $this->file = $this->fileInfo->openFile();
         $this->file->setFlags(\SplFileObject::READ_CSV | \SplFileObject::READ_AHEAD | \SplFileObject::DROP_NEW_LINE);
         $this->file->setCsvControl($this->delimiter, $this->enclosure, $this->escape);
         if ($this->firstLineIsHeader && !$this->header) {
             $this->header = $this->file->fgetcsv();
         }
     }
     return $this->file;
 }
Example #4
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $fileInfo = new \SplFileInfo($this->getContainer()->getParameter('kernel.root_dir') . '/../web/sitemap.xml');
     if ($fileInfo->isFile() && $fileInfo->isReadable()) {
         $output->write('Reading sitemap.xml...');
         $file = $fileInfo->openFile();
         $xml = '';
         while (!$file->eof()) {
             $xml .= $file->fgets();
         }
         $output->writeln(' done.');
         $output->write('Updating sitemap.xml...');
         $sitemap = new \SimpleXMLIterator($xml);
         $sitemap->rewind();
         $lastmodDate = new \DateTime();
         $lastmodDate->sub(new \DateInterval('P1D'));
         $lastmodDateFormatted = $lastmodDate->format('Y-m-d');
         while ($sitemap->valid()) {
             $sitemap->current()->lastmod = $lastmodDateFormatted;
             $sitemap->next();
         }
         $file = $file->openFile('w');
         $file->fwrite($sitemap->asXML());
         $output->writeln(' done.');
     } else {
         $output->writeln('Error: Cannot open file web/sitemap.xml');
     }
 }
Example #5
0
 public function importSingleMovie(\SplFileInfo $source)
 {
     if (!$source->isReadable()) {
         return $this->output->writelnError(sprintf("File %s not readable", $source->getFilename()));
     }
     $this->output->writelnInfo(sprintf("Importing %s ...", $source->getRealPath()));
     $file = $source->openFile();
     /** @var Movies $movie */
     $movie = $this->getMovie($file->fread($file->getSize()), $file->getBasename('.html'));
     if (!$movie) {
         return $this->output->writelnError(sprintf("Not found dmm id", $source->getFilename()));
     }
     $this->currentDmmId = $movie->banngo;
     if (Movies::findFirstById($movie->id)) {
         return $this->output->writelnWarning(sprintf("Movie %s already exists, insert skipped", $movie->banngo));
     }
     /** @var Mysql $db */
     $db = $this->getDI()->get('dbMaster');
     $db->begin();
     if (false === $movie->save()) {
         $db->rollback();
         return $this->output->writelnError(sprintf("Movie saving failed by %s", implode(',', $movie->getMessages())));
     }
     $db->commit();
     $this->output->writelnSuccess(sprintf("Movie %s saving success as %s, detail: %s", $movie->banngo, $movie->id, ''));
 }
 protected function getInput()
 {
     $input = new \SplFileInfo(FILESYSTEM1 . self::KEY);
     $fileObj = $input->openFile('a');
     $fileObj->fwrite(self::CONTENT);
     return $input;
 }
 /**
  * Main check method
  *
  * @param string $pathToFile
  * @throws \RuntimeException if file not found
  * @return bool
  */
 public function validate($pathToFile)
 {
     $this->clearErrors();
     $path = new \SplFileInfo($pathToFile);
     if (!$path->isFile() || !$path->isReadable()) {
         throw new \RuntimeException(sprintf('File "%s" not found', $pathToFile));
     }
     $file = $path->openFile('r');
     $currentLineNumber = 1;
     while (!$file->eof()) {
         $line = $file->fgets();
         if ($line == '' && $file->eof()) {
             break;
         }
         // Validate line structure
         $this->validateEOL($currentLineNumber, $line);
         $nodes = array_filter(preg_split('/\\s+/', $line));
         // Validate label
         $label = array_shift($nodes);
         $this->validateLabel($currentLineNumber, $label);
         // Validate features format
         $this->validateFeatures($currentLineNumber, $nodes);
         // Increate the line number
         $currentLineNumber++;
     }
     return $this->isValid();
 }
Example #8
0
 public function it_throws_if_the_data_read_back_from_the_file_system_is_not_an_array()
 {
     $fs = new FileSystem();
     $fileInfo = new \SplFileInfo($fs->path('/r.php'));
     $file = $fileInfo->openFile('w');
     $file->fwrite("<?php\nreturn 'foo';");
     $this->beConstructedWith($fileInfo);
     $this->shouldThrow(UnexpectedValueException::class)->duringReadArray();
 }
Example #9
0
 public function importXmlFile(\SplFileInfo $source)
 {
     if (!$source->isReadable()) {
         return $this->output->writelnError(sprintf("File %s not readable", $source->getFilename()));
     }
     $this->output->writelnInfo(sprintf("Importing %s ...", $source->getRealPath()));
     $file = $source->openFile();
     $xml = simplexml_load_string($file->fread($file->getSize()));
     return $this->saveDmmList($xml);
 }
 /**
  * @see EbayEnterprise_Catalog_Model_Error_IConfirmations::append()
  */
 public function append($content = '')
 {
     if (is_null($this->fileStream)) {
         throw new EbayEnterprise_Catalog_Model_Error_Exception(sprintf('[ %s ] Error Confirmations file stream is not instantiated', __CLASS__));
     }
     $oldMask = umask(self::ERROR_FILE_PERMISSIONS_MASK);
     $this->fileStream->openFile('a')->fwrite("{$content}\n");
     umask($oldMask);
     return $this;
 }
 /**
  * Builds a UnitOfWork instance from the given \SplFileInfo
  *
  * @param \SplFileInfo $fileInfo The fileInfo to build from
  *
  * @throws \InvalidArgumentException
  *
  * @return UnitOfWork The instantiated migration
  */
 public static function buildFromSplFileInfo(\SplFileInfo $fileInfo)
 {
     $uniqueId = $fileInfo->getBasename();
     $file = $fileInfo->openFile();
     $query = '';
     while (!$file->eof()) {
         $query .= $file->fgets();
     }
     return new UnitOfWork(new Uid($uniqueId), new Workload($query), new \DateTime());
 }
Example #12
0
 public static function write_file($path, $data, $mode = 'w')
 {
     try {
         $file = new SplFileInfo($path);
         $data_obj = $file->openFile($mode);
         $data_obj->fwrite($data, strlen($data));
         $data_obj->fflush();
     } catch (Exception $e) {
         throw new keke_exception($e->getMessage());
     }
     unset($file, $data_obj, $data);
     return TRUE;
 }
Example #13
0
 /**
  * Abre um arquivo especificado pelo parâmetro $filePath para leitura.
  * Retorna o objeto que representa o arquivo em caso de sucesso, ou o 
  * boolean false caso contrário.
  * 
  * @param string $filePath caminho do arquivo
  * @return mixed SplFileObject em caso de sucesso | bool false caso contrário
  */
 static function openFile($filePath)
 {
     if (is_string($filePath)) {
         try {
             $fileInfo = new SplFileInfo($filePath);
             if ($fileInfo->isFile()) {
                 $file = $fileInfo->openFile();
                 return $file;
             } else {
                 return false;
             }
         } catch (Exception $e) {
             trigger_error("Arquivo não pode ser importado\n" . $e->getMessage(), E_USER_WARNING);
             return false;
         }
     }
 }
 /**
  * Fetch a file from remote host and write to local filesystem.
  *
  * Set overwrite to true to force overwrite of existing files.
  *
  * @param string $remotePathName - e.g. replicant/files
  * @param string $localPathName - e.g. assets/replicant/files
  * @param bool $overwrite
  * @param string $contentType
  * @return int|bool number of bytes written or false if failed
  * @throws Exception
  */
 public function fetchFile($remotePathName, $localPathName, $overwrite = false, $contentType = '')
 {
     // most paths lead to null or error return
     $written = null;
     $fileInfo = new SplFileInfo($localPathName);
     $exists = $fileInfo->isFile();
     if ($exists && !$overwrite) {
         return false;
     }
     $url = $this->buildURL($remotePathName);
     $fileObject = $fileInfo->openFile("w");
     if ($fileObject) {
         // readFile will throw an exception on error so we'll not try and write a bad file
         $written = $fileObject->fwrite($this->readFile($url, $contentType));
     }
     return $written > 0 ? $written : false;
 }
Example #15
0
 /**
  * Overwritten I do not want to throw an exception...just ignore it! return default and delete.
  * Retrieve a cached value entry by id. 
  *
  *     // Retrieve cache entry from file group
  *     $data = Cache::instance('file')->get('foo');
  *
  *     // Retrieve cache entry from file group and return 'bar' if miss
  *     $data = Cache::instance('file')->get('foo', 'bar');
  *
  * @param   string   $id       id of cache to entry
  * @param   string   $default  default value to return if cache miss
  * @return  mixed
  * @throws  Cache_Exception
  */
 public function get($id, $default = NULL)
 {
     $filename = Cache_File::filename($this->_sanitize_id($id));
     $directory = $this->_resolve_directory($filename);
     // Wrap operations in try/catch to return default
     try {
         // Open file
         $file = new SplFileInfo($directory . $filename);
         // If file does not exist
         if (!$file->isFile()) {
             // Return default value
             return $default;
         } else {
             // Open the file and parse data
             $created = $file->getMTime();
             $data = $file->openFile();
             $lifetime = $data->fgets();
             // If we're at the EOF at this point, corrupted!
             if ($data->eof()) {
                 $this->_delete_file($file, NULL, TRUE);
                 return $default;
             }
             $cache = '';
             while ($data->eof() === FALSE) {
                 $cache .= $data->fgets();
             }
             // Test the expiry
             if ($created + (int) $lifetime < time()) {
                 // Delete the file
                 $this->_delete_file($file, NULL, TRUE);
                 return $default;
             } else {
                 return unserialize($cache);
             }
         }
     } catch (ErrorException $e) {
         $this->_delete_file($file, NULL, TRUE);
         return $default;
     }
 }
Example #16
0
    public static function install()
    {
        $dirs = array('resources/cache', 'resources/log', 'tmp');
        foreach ($dirs as $dir) {
            if (!file_exists($dir)) {
                mkdir($dir, 0755, true);
            } else {
                chmod($dir, 0755);
            }
        }
        $console = 'console';
        $code = <<<HEREDOC
#!/usr/bin/env php
<?php

require_once __DIR__.'/vendor/autoload.php';

\$app = new Silex\\Application();

\$app['environment'] = 'dev';
require __DIR__.'/src/app.php';
\$app->boot();

\$console = require __DIR__.'/src/console.php';
\$console->run();
HEREDOC;
        if (!file_exists($console)) {
            $fileinfo = new \SplFileInfo($console);
            $f = $fileinfo->openFile('w');
            $f->fwrite($code);
            $fileinfo = null;
            $f = null;
        }
        if (file_exists($console)) {
            chmod($console, 0500);
        }
    }
Example #17
0
 /**
  * Sets the current cache key this class is managing, and creates a writable SplFileObject
  * for the cache file the key is referring to.
  *
  * @param string $key The key
  * @param boolean $createKey Whether the key should be created if it doesn't exists, or not
  * @return boolean true if the cache key could be set, false otherwise
  */
 protected function _setKey($key, $createKey = false)
 {
     $groups = null;
     if (!empty($this->_groupPrefix)) {
         $groups = vsprintf($this->_groupPrefix, $this->groups());
     }
     $dir = $this->settings['path'] . $groups;
     if (!is_dir($dir)) {
         mkdir($dir, 0775, true);
     }
     $path = new SplFileInfo($dir . $key);
     if (!$createKey && !$path->isFile()) {
         return false;
     }
     if (empty($this->_File) || $this->_File->getBaseName() !== $key) {
         $exists = file_exists($path->getPathname());
         try {
             $this->_File = $path->openFile('c+');
         } catch (Exception $e) {
             trigger_error($e->getMessage(), E_USER_WARNING);
             return false;
         }
         unset($path);
         if (!$exists && !chmod($this->_File->getPathname(), (int) $this->settings['mask'])) {
             trigger_error(__d('cake_dev', 'Could not apply permission mask "%s" on cache file "%s"', array($this->_File->getPathname(), $this->settings['mask'])), E_USER_WARNING);
         }
     }
     return true;
 }
 protected function getDataFromFile(\SplFileInfo $fileinfo)
 {
     $file = $fileinfo->openFile('r');
     $file->setFlags(\SplFileObject::SKIP_EMPTY | \SplFileObject::DROP_NEW_LINE);
     $lines = [];
     foreach ($file as $line) {
         if ($line !== false) {
             $lines[] = $line;
         }
     }
     $content = implode('', $lines);
     $data = json_decode($content, true);
     if ($data === null) {
         throw new \Exception("File [" . $fileinfo->getPathname() . "] contains incorrect JSON (error code " . json_last_error() . ")");
     }
     return $data;
 }
Example #19
0
 /**
  * Deletes files recursively and returns FALSE on any errors
  * 
  *     // Delete a file or folder whilst retaining parent directory and ignore all errors
  *     $this->_delete_file($folder, TRUE, TRUE);
  *
  * @param   SplFileInfo  file
  * @param   boolean  retain the parent directory
  * @param   boolean  ignore_errors to prevent all exceptions interrupting exec
  * @param   boolean  only expired files
  * @return  boolean
  * @throws  Kohana_Cache_Exception
  */
 protected function _delete_file(SplFileInfo $file, $retain_parent_directory = FALSE, $ignore_errors = FALSE, $only_expired = FALSE)
 {
     // Allow graceful error handling
     try {
         // If is file
         if ($file->isFile()) {
             try {
                 // If only expired is not set
                 if ($only_expired === FALSE) {
                     // We want to delete the file
                     $delete = TRUE;
                 } else {
                     // Assess the file expiry to flag it for deletion
                     $json = $file->openFile('r')->current();
                     $data = json_decode($json);
                     $delete = $data->expiry < time();
                 }
                 // If the delete flag is set
                 if ($delete === TRUE) {
                     // Try to delete
                     unlink($file->getRealPath());
                 }
             } catch (ErrorException $e) {
                 // Catch any delete file warnings
                 if ($e->getCode() === E_WARNING) {
                     throw new Kohana_Cache_Exception(__METHOD__ . ' failed to delete file : :file', array(':file' => $file->getRealPath()));
                 }
             }
         } else {
             if ($file->isDir()) {
                 // Create new DirectoryIterator
                 $files = new DirectoryIterator($file->getPathname());
                 // Iterate over each entry
                 while ($files->valid()) {
                     // Extract the entry name
                     $name = $files->getFilename();
                     // If the name is not a dot
                     if ($name != '.' and $name != '..') {
                         // Create new file resource
                         $fp = new SplFileInfo($files->getRealPath());
                         // Delete the file
                         $this->_delete_file($fp);
                     }
                     // Move the file pointer on
                     $files->next();
                 }
                 // If set to retain parent directory, return now
                 if ($retain_parent_directory) {
                     return TRUE;
                 }
                 try {
                     // Remove the files iterator
                     // (fixes Windows PHP which has permission issues with open iterators)
                     unset($files);
                     // Try to remove the parent directory
                     return rmdir($file->getRealPath());
                 } catch (ErrorException $e) {
                     // Catch any delete directory warnings
                     if ($e->getCode() === E_WARNING) {
                         throw new Kohana_Cache_Exception(__METHOD__ . ' failed to delete directory : :directory', array(':directory' => $file->getRealPath()));
                     }
                 }
             }
         }
     } catch (Exception $e) {
         // If ignore_errors is on
         if ($ignore_errors === TRUE) {
             // Return
             return FALSE;
         }
         // Throw exception
         throw $e;
     }
 }
Example #20
0
 public function testDecoratedMethods()
 {
     $decorated = $this->getMockBuilder('hanneskod\\classtools\\Tests\\MockSplFileInfo')->setConstructorArgs([''])->getMock();
     $decorated->expects($this->once())->method('getRelativePath');
     $decorated->expects($this->once())->method('getRelativePathname');
     $decorated->expects($this->once())->method('getContents');
     $decorated->expects($this->once())->method('getATime');
     $decorated->expects($this->once())->method('getBasename');
     $decorated->expects($this->once())->method('getCTime');
     $decorated->expects($this->once())->method('getExtension');
     $decorated->expects($this->once())->method('getFileInfo');
     $decorated->expects($this->once())->method('getFilename');
     $decorated->expects($this->once())->method('getGroup');
     $decorated->expects($this->once())->method('getInode');
     $decorated->expects($this->once())->method('getLinkTarget');
     $decorated->expects($this->once())->method('getMTime');
     $decorated->expects($this->once())->method('getOwner');
     $decorated->expects($this->once())->method('getPath');
     $decorated->expects($this->once())->method('getPathInfo');
     $decorated->expects($this->once())->method('getPathname');
     $decorated->expects($this->once())->method('getPerms');
     $decorated->expects($this->once())->method('getRealPath');
     $decorated->expects($this->once())->method('getSize');
     $decorated->expects($this->once())->method('getType');
     $decorated->expects($this->once())->method('isDir');
     $decorated->expects($this->once())->method('isExecutable');
     $decorated->expects($this->once())->method('isFile');
     $decorated->expects($this->once())->method('isLink');
     $decorated->expects($this->once())->method('isReadable');
     $decorated->expects($this->once())->method('isWritable');
     $decorated->expects($this->once())->method('openFile');
     $decorated->expects($this->once())->method('setFileClass');
     $decorated->expects($this->once())->method('setInfoClass');
     $decorated->expects($this->once())->method('__toString')->will($this->returnValue(''));
     $fileInfo = new SplFileInfo($decorated);
     $fileInfo->getRelativePath();
     $fileInfo->getRelativePathname();
     $fileInfo->getContents();
     $fileInfo->getATime();
     $fileInfo->getBasename();
     $fileInfo->getCTime();
     $fileInfo->getExtension();
     $fileInfo->getFileInfo();
     $fileInfo->getFilename();
     $fileInfo->getGroup();
     $fileInfo->getInode();
     $fileInfo->getLinkTarget();
     $fileInfo->getMTime();
     $fileInfo->getOwner();
     $fileInfo->getPath();
     $fileInfo->getPathInfo();
     $fileInfo->getPathname();
     $fileInfo->getPerms();
     $fileInfo->getRealPath();
     $fileInfo->getSize();
     $fileInfo->getType();
     $fileInfo->isDir();
     $fileInfo->isExecutable();
     $fileInfo->isFile();
     $fileInfo->isLink();
     $fileInfo->isReadable();
     $fileInfo->isWritable();
     $fileInfo->openFile();
     $fileInfo->setFileClass();
     $fileInfo->setInfoClass();
     (string) $fileInfo;
 }
Example #21
0
 /**
  * Test if the `remove` return true if the resource was removed.
  */
 public function testRemoveReturnTrueIfTheResourceWasRemoved()
 {
     $this->fileInfo->openFile('w+');
     $resource = new XMLResource($this->fileInfo);
     $this->assertTrue($resource->remove());
 }
Example #22
0
 /**
  * Parse the CREDITS file to populate the package developers, roles and email.
  *
  */
 function parseCREDITS()
 {
     if (file_exists($this->path . DIRECTORY_SEPARATOR . 'CREDITS')) {
         $a = new \SplFileInfo($this->path . DIRECTORY_SEPARATOR . 'CREDITS');
         foreach ($a->openFile('r') as $line) {
             if ($line && $line[0] === ';') {
                 continue;
             }
             if (preg_match('/^(.+) \\[(.+)\\] \\<(.+)\\> \\((.+?)(\\/inactive)?\\)/', $line, $match)) {
                 $this->pxml->maintainer[$match[2]]->role($match[4])->name($match[1])->email($match[3])->active(isset($match[5]) ? 'no' : 'yes');
                 if ($this->doCompatible) {
                     $this->pxml_compatible->maintainer[$match[2]]->role($match[4])->name($match[1])->email($match[3])->active(isset($match[5]) ? 'no' : 'yes');
                 }
             }
         }
     }
 }
Example #23
0
    /**
     * @param $indexFileName
     */
    public function addHtaccessRule($indexFileName)
    {

        $file = $this->getHtaccessFile();

        if ($file instanceof SplFileInfo) {

            $fileObj = $file->openFile('a+');

        } else {

            $filePath = $this->getRootDir() . DIRECTORY_SEPARATOR . '.htaccess';
            $file = new SplFileInfo($filePath);

            $fileObj = $file->openFile('w+');

        }

        $content = '

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ ' . $indexFileName . ' [NC,L]
DirectoryIndex ' . $indexFileName . '
        ';

        $fileObj->fwrite($content);

    }
Example #24
0
 /**
  * Set a value to cache with id and lifetime
  * 
  *     $data = 'bar';
  * 
  *     // Set 'bar' to 'foo' in file group, using default expiry
  *     Cache::instance('file')->set('foo', $data);
  * 
  *     // Set 'bar' to 'foo' in file group for 30 seconds
  *     Cache::instance('file')->set('foo', $data, 30);
  *
  * @param   string   id of cache entry
  * @param   string   data to set to cache
  * @param   integer  lifetime in seconds
  * @return  boolean
  */
 public function set($id, $data, $lifetime = NULL)
 {
     $filename = Cache_File::filename($this->_sanitize_id($id));
     $directory = $this->_resolve_directory($filename);
     // If lifetime is NULL
     if ($lifetime === NULL) {
         // Set to the default expiry
         $lifetime = Arr::get($this->_config, 'default_expire', Cache::DEFAULT_EXPIRE);
     }
     // Open directory
     $dir = new SplFileInfo($directory);
     // If the directory path is not a directory
     if (!$dir->isDir()) {
         // Create the directory
         if (!mkdir($directory, 0777, TRUE)) {
             throw new Kohana_Cache_Exception(__METHOD__ . ' unable to create directory : :directory', array(':directory' => $directory));
         }
         // chmod to solve potential umask issues
         chmod($directory, 0777);
     }
     // Open file to inspect
     $resouce = new SplFileInfo($directory . $filename);
     $file = $resouce->openFile('w');
     try {
         $type = gettype($data);
         // Serialize the data
         $data = json_encode((object) array('payload' => $type === 'string' ? $data : serialize($data), 'expiry' => time() + $lifetime, 'type' => $type));
         $size = strlen($data);
     } catch (ErrorException $e) {
         // If serialize through an error exception
         if ($e->getCode() === E_NOTICE) {
             // Throw a caching error
             throw new Kohana_Cache_Exception(__METHOD__ . ' failed to serialize data for caching with message : ' . $e->getMessage());
         }
         // Else rethrow the error exception
         throw $e;
     }
     try {
         $file->fwrite($data, $size);
         return (bool) $file->fflush();
     } catch (Exception $e) {
         throw $e;
     }
 }
 /**
  * Creates the SSL file passed as parameter or nothing if the file already exists.
  *
  * @param \SplFileInfo $certificate The file info about the SSL file to generate
  *
  * @return void
  */
 public function createSslCertificate(\SplFileInfo $certificate)
 {
     // first we've to check if OpenSSL is available
     if (!extension_loaded('openssl')) {
         return;
     }
     // do nothing if the file is already available
     if ($certificate->isFile()) {
         return;
     }
     // prepare the certificate data from our configuration
     $dn = array("countryName" => "DE", "stateOrProvinceName" => "Bavaria", "localityName" => "Kolbermoor", "organizationName" => "appserver.io", "organizationalUnitName" => "Development", "commonName" => gethostname(), "emailAddress" => "*****@*****.**");
     // check the operating system
     switch (strtoupper(PHP_OS)) {
         case 'DARWIN':
             // on Mac OS X use the system default configuration
             $configargs = array('config' => '/System/Library/OpenSSL/openssl.cnf');
             break;
         case 'WINNT':
             // on Windows use the system configuration we deliver
             $configargs = array('config' => $this->getBaseDirectory('/php/extras/ssl/openssl.cnf'));
             break;
         default:
             // on all other use a standard configuration
             $configargs = array('digest_alg' => 'md5', 'x509_extensions' => 'v3_ca', 'req_extensions' => 'v3_req', 'private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA, 'encrypt_key' => false);
     }
     // generate a new private (and public) key pair
     $privkey = openssl_pkey_new($configargs);
     // Generate a certificate signing request
     $csr = openssl_csr_new($dn, $privkey, $configargs);
     // create a self-signed cert that is valid for 365 days
     $sscert = openssl_csr_sign($csr, null, $privkey, 365, $configargs);
     // export the cert + pk files
     $certout = '';
     $pkeyout = '';
     openssl_x509_export($sscert, $certout);
     openssl_pkey_export($privkey, $pkeyout, null, $configargs);
     // write the SSL certificate data to the target
     $file = $certificate->openFile('w');
     if (($written = $file->fwrite($certout . $pkeyout)) === false) {
         throw new \Exception(sprintf('Can\'t create SSL certificate %s', $certificate->getPathname()));
     }
     // log a message that the file has been written successfully
     $this->getInitialContext()->getSystemLogger()->info(sprintf('Successfully created %s with %d bytes', $certificate->getPathname(), $written));
     // log any errors that occurred here
     while (($e = openssl_error_string()) !== false) {
         $this->getInitialContext()->getSystemLogger()->debug($e);
     }
 }
Example #26
0
<?php

$info = new SplFileInfo('SplFileInfo.php');
printf("Extension: %s\n", $info->getExtension());
printf("Filename: %s\n", $info->getFilename());
printf("Path: %s\n", $info->getPathname());
printf("RealPath: %s\n", $info->getRealPath());
printf("Type: %s\n", $info->getType());
printf("Size: %s\n", $info->getSize());
printf("Dir: %b, Exec: %b, File: %b, Link: %b, R: %b, W: %b\n", $info->isDir(), $info->isExecutable(), $info->isFile(), $info->isLink(), $info->isReadable(), $info->isWritable());
$file = $info->openFile('r');
foreach ($file as $line) {
    printf("%s", $line);
}
Example #27
0
<?php

class test extends SplFileObject
{
    public function example()
    {
        return "From class test";
    }
}
$info = new SplFileInfo(__FILE__);
$info->setFileClass('test');
var_dump($info->openFile()->example());
try {
    $info->setFileClass('stdclass');
} catch (UnexpectedValueException $e) {
    echo $e->getMessage(), PHP_EOL;
}
Example #28
0
 final function parseFile(\SplFileInfo $file)
 {
     $this->file = $file->openFile('rb');
     if (version_compare(PHP_VERSION, '5.5.11', '<')) {
         $this->file->setMaxLineLen(4096);
     }
     $this->init();
     while ($data = version_compare(PHP_VERSION, '5.5.11', '<') ? $this->file->fgets() : $this->file->fread(4096)) {
         $this->parse($data, false);
     }
     $this->parse(NULL, true);
     $this->destroy();
     return true;
 }
Example #29
0
<?php

class Foo extends SplFileObject
{
    public $bam = array();
}
$fileInfo = new SplFileInfo('php://temp');
$fileInfo->setFileClass('Foo');
$file = $fileInfo->openFile('r');
print var_dump($file->bam);
// is null or UNKNOWN:0
?>
===DONE===
Example #30
0
<?php

class CustomFO extends SplFileObject
{
    private $i = 1;
    public function current()
    {
        return $this->i++ . ": " . htmlspecialchars($this->getCurrentLine()) . "";
    }
}
$SFI = new SplFileInfo("splFileInfo.php");
$SFI->setFileClass("CustomFO");
$file = $SFI->openFile();
echo "<pre>";
foreach ($file as $line) {
    echo $line;
}
echo "</pre>";
?>

<?php 
/*
foreach( get_class_methods(SplFileInfo) as $methodName){
	echo $methodName.'<br />';
}
*/