/** * Constructor * * @param \SplFileObject $post Post source file */ public function __construct(\SplFileObject $post) { $this->source = $post; if (!preg_match('/[\\d]{4}\\/[\\d]{2}\\/(.+)$/', $post->getPathname())) { throw new \Exception(sprintf('%s is not a valid post', $post->getPathname())); } $paths = explode(DIRECTORY_SEPARATOR, $post->getPath()); $this->month = $paths[count($paths) - 1]; $this->year = $paths[count($paths) - 2]; $this->slug = $post->getBasename('.' . $post->getExtension()); }
/** * Clears a directory of cached files with the correct header. * * @return void */ protected function _clearDirectory($path) { $dir = new DirectoryIterator($path); foreach ($dir as $file) { $fileInfo = new SplFileObject($file->getPathname()); $line = $fileInfo->fgets(); if (preg_match('#^/\\* asset_compress \\d+ \\*/$#', $line)) { $this->out('Deleting ' . $fileInfo->getPathname()); unlink($fileInfo->getPathname()); } } }
/** * @inheritdoc */ public function start() { if (!$this->file) { throw new \LogicException('Set a file first'); } if ($this->writer) { throw new \LogicException('Writer already started'); } $this->writer = new BaseXmlWriter(); $this->writer->openUri($this->file->getPathname()); $this->writer->setIndent($this->indent); $this->writer->startDocument('1.0', 'UTF-8'); $this->write(sprintf('<%s>', $this->rootNode)); }
/** * 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 bool $createKey Whether the key should be created if it doesn't exists, or not * @return bool 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->_config['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->_config['mask'])) { trigger_error(sprintf('Could not apply permission mask "%s" on cache file "%s"', $this->_File->getPathname(), $this->_config['mask']), E_USER_WARNING); } } return true; }
protected function _openFile($key, $createKey = false) { $dir = $this->settings['path']; //create dir if needed if (!is_dir($dir)) { mkdir($dir, 0777, 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) { if (!$this->settings['suppress_errors']) { trigger_error($e->getMessage(), E_USER_WARNING); } return false; } unset($path); if (!$exists && !chmod($this->file->getPathname(), (int) $this->settings['mask'])) { if (!$this->settings['suppress_errors']) { trigger_error('Could not apply permission mask on cache file ' . $this->file->getPathname(), E_USER_WARNING); } } } return true; }
/** * @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; }
public function __construct(\SplFileObject $file, $xpath = null) { $this->filename = $file->getPathname(); if (!is_null($xpath) && !is_string($xpath)) { throw new \InvalidArgumentException('xpath must be null or a string'); } $this->xpath = $xpath; }
/** * @return void */ public function testInit() { $filePath = __DIR__ . '/example_read.txt'; $fileObject = new FileReader($filePath, 'r', true); $this->assertEquals($filePath, $fileObject->getPathname()); $this->assertTrue($fileObject->isReadable()); $fileObject = new \SplFileObject($filePath, 'r'); $this->assertEquals($filePath, $fileObject->getPathname()); $this->assertTrue($fileObject->isReadable()); }
/** * @return void */ public function testInit() { $filePath = __DIR__ . '/example_write1.txt'; $fileObject = new FileWriter($filePath); $this->assertEquals($filePath, $fileObject->getPathname()); $this->assertTrue($fileObject->isWritable()); $filePath = __DIR__ . '/example_write2.txt'; $fileObject = new \SplFileObject($filePath, 'r+'); $this->assertEquals($filePath, $fileObject->getPathname()); $this->assertTrue($fileObject->isWritable()); }
public function __construct($message, $parser, \SplFileObject $file = NULL) { $this->code = xml_get_error_code($parser); if (false === $this->code) { throw new \BadMethodCallException('This is not a valid xml_parser resource.'); } parent::__construct($message ?: xml_error_string($this->code), $this->code); $this->file = $file ? $file->getPathname() : '(data stream)'; $this->line = xml_get_current_line_number($parser); $this->err['srcColumn'] = xml_get_current_column_number($parser); $this->err['srcIndex'] = xml_get_current_byte_index($parser); }
/** * Add input argument * * @param string $filePath * Input file path * * @return Identify * @throws \InvalidArgumentException */ public function in($filePath) { if (!file_exists($filePath)) { $message = 'The input file path (' . $filePath . ') is invalid or the file could not be located.'; throw new \InvalidArgumentException($message); } $file = new \SplFileObject($filePath); if ($file->isReadable()) { $this->inputFile = '"' . $file->getPathname() . '"'; } $this->getQuery()->dirty(); return $this; }
/** * Construct CSV reader * * @param \SplFileObject $file Excel file * @param int $headerRowNumber Optional number of header row * @param int $activeSheet Index of active sheet to read from */ public function __construct(\SplFileObject $file, $headerRowNumber = null, $activeSheet = null) { $reader = \PHPExcel_IOFactory::createReaderForFile($file->getPathName()); $reader->setReadDataOnly(true); $excel = $reader->load($file->getPathname()); if (null !== $activeSheet) { $excel->setActiveSheetIndex($activeSheet); } $this->worksheet = $excel->getActiveSheet()->toArray(); if (null !== $headerRowNumber) { $this->setHeaderRowNumber($headerRowNumber); } }
/** * Default route test */ public function testRoutePath() { $file = new \SplFileObject(__DIR__ . '/../../../../../files/cestlafete.jpg'); self::$DI['client']->request("GET", "/admin/tests/pathurl/path/", ['path' => $file->getPathname()]); $response = self::$DI['client']->getResponse(); $this->assertTrue($response->isOk()); $this->assertEquals("application/json", self::$DI['client']->getResponse()->headers->get("content-type")); $content = json_decode(self::$DI['client']->getResponse()->getContent()); $this->assertTrue(is_object($content)); $this->assertObjectHasAttribute('exists', $content); $this->assertObjectHasAttribute('file', $content); $this->assertObjectHasAttribute('dir', $content); $this->assertObjectHasAttribute('readable', $content); $this->assertObjectHasAttribute('executable', $content); }
/** * @covers \Phansible\Controller\DefaultController::docsAction */ public function testShouldRenderDocsActionWhenFileExists() { $container = new \Pimple(); $this->twig->expects($this->once())->method('render')->with($this->equalTo('docs.html.twig'), $this->callback(function ($param) { return array_key_exists('content', $param) && strpos($param['content'], 'ansible'); })); $docFile = new \SplFileObject('/tmp/vagrant.md', 'w+'); $docFile->fwrite('Phansible'); $doc = 'vagrant'; $container['twig'] = $this->twig; $container['docs.path'] = '/tmp'; $this->controller->setPimple($container); $this->controller->docsAction($doc); unlink($docFile->getPathname()); }
/** * @param \SplFileObject $file Excel file * @param integer $headerRowNumber Optional number of header row * @param integer $activeSheet Index of active sheet to read from * @param boolean $readOnly If set to false, the reader take care of the excel formatting (slow) */ public function __construct(\SplFileObject $file, $headerRowNumber = null, $activeSheet = null, $readOnly = true) { $reader = \PHPExcel_IOFactory::createReaderForFile($file->getPathName()); $reader->setReadDataOnly($readOnly); /** @var \PHPExcel $excel */ $excel = $reader->load($file->getPathname()); if (null !== $activeSheet) { $excel->setActiveSheetIndex($activeSheet); } $this->worksheet = $excel->getActiveSheet(); $this->maxColumn = $this->worksheet->getHighestColumn(); $this->maxRow = $this->worksheet->getHighestRow(); if (null !== $headerRowNumber) { $this->setHeaderRowNumber($headerRowNumber); } }
/** * Clears a directory of cached files with the correct header. * * @return void */ protected function _clearDirectory($path) { $dir = new DirectoryIterator($path); foreach ($dir as $file) { if (in_array($file->getFilename(), array('.', '..'))) { continue; } $fileInfo = new SplFileObject($file->getPathname()); $line = $fileInfo->fgets(); if (preg_match('#^/\\* asset_compress \\d+ \\*/$#', $line)) { $pathName = $fileInfo->getPathname(); unset($fileInfo); $this->out('Deleting ' . $pathName); unlink($pathName); } } }
protected function execute(InputInterface $input, OutputInterface $output) { $diffComputer = $this->getContainer()->get('diff.computer'); $collection = $this->getContainer()->get('utility')->getCollection($input->getArgument('institutionCode'), $input->getArgument('collectionCode')); if (!is_null($collection)) { $savePath = $input->getArgument('savePath'); $entityName = $input->getArgument('entityName'); $fileCatalogNumbers = new \SplFileObject($savePath . '/catalogNumbers_' . $entityName . '.json'); $catalogNumbers[$entityName] = json_decode(file_get_contents($fileCatalogNumbers->getPathname()), true); $diffComputer->setCollection($collection); $diffComputer->setCatalogNumbers($catalogNumbers); $diffComputer->computeClassname($entityName); $datas = $diffComputer->getAllDatas(); $fs = new Filesystem(); $fs->dumpFile($savePath . '/' . $entityName . '.json', \json_encode($datas, JSON_PRETTY_PRINT)); $fs->dumpFile($savePath . '/taxons_' . $entityName . '.json', \json_encode($diffComputer->getTaxons())); } }
public function finalizeFile(\SplFileObject $fileObject) { if ($this->headers !== null) { // Create tmp file with header $fd = fopen('php://temp', 'w+b'); fputcsv($fd, $this->headers); // Copy file content into tmp file $fileObject->rewind(); fwrite($fd, $fileObject->fread($fileObject->getSize())); // Overwrite file content with tmp content rewind($fd); $fileObject->rewind(); $fileObject->fwrite(stream_get_contents($fd)); clearstatcache(true, $fileObject->getPathname()); fclose($fd); } // Remove last line feed $fileObject->ftruncate($fileObject->getSize() - 1); }
/** * {@inheritdoc} */ public function updateMetadata(MediaInterface $media, $force = true) { try { // this is now optimized at all!!! $path = tempnam(sys_get_temp_dir(), 'sonata_update_metadata'); $fileObject = new \SplFileObject($path, 'w'); $fileObject->fwrite($this->getReferenceFile($media)->getContent()); $image = $this->imagineAdapter->open($fileObject->getPathname()); $size = $image->getSize(); $media->setSize($fileObject->getSize()); $media->setWidth($size->getWidth()); $media->setHeight($size->getHeight()); } catch (\LogicException $e) { $media->setProviderStatus(MediaInterface::STATUS_ERROR); $media->setSize(0); $media->setWidth(0); $media->setHeight(0); } }
public function report_mail($options) { $this->log(__('Reporting via e-mail', 'my-wp-backup')); if ('default' === $options['method']) { $this->log(__('Sending email via default method', 'my-wp-backup'), 'debug'); $attachments = array(); if ('1' === $options['attach']) { array_push($attachments, $this->logfile->getPathname()); } add_filter('wp_mail_from', function () use($options) { return $options['from']; }); add_filter('wp_mail_from_name', function () use($options) { return $options['name']; }); wp_mail($options['address'], $this->format_message($options['title']), $this->format_message($options['message']), array(), $attachments); } elseif ('smtp' === $options['method']) { $this->log(__('Sending email via SMTP', 'my-wp-backup'), 'debug'); $security = 'none' === $options['smtp_protocol'] ? null : $options['smtp_protocol']; $transport = new \Swift_SmtpTransport($options['smtp_server'], $options['smtp_port'], $security); $mailer = new \Swift_Mailer($transport); $message = new \Swift_Message(); $transport->setUsername($options['smtp_username'])->setPassword($options['smtp_password']); $message->setSubject($this->format_message($options['title']))->setFrom(array($options['from'] => $options['name']))->setTo(array($options['address']))->setBody($this->format_message($options['message'])); if ('1' === $options['attach']) { $logfile = fopen($this->basedir . 'log.txt', 'r'); $log = ''; while (!feof($logfile) && ($line = fgets($logfile))) { $line = json_decode($line, true); $log .= $line['text'] . "\n"; } fclose($logfile); $attachment = new \Swift_Attachment($log, 'log.txt', 'text/plain'); $message->attach($attachment); } $mailer->send($message); } else { $this->log(sprintf(__('Unknown e-mail sending method: %s', 'my-wp-backup'), $options['method']), 'error'); } $this->log(__('Done e-mail report', 'my-wp-backup')); }
/** * Parse les pleins et remplit le tableau $pleins. * * @param \SplFileObject $file Fichier XML fourni par MyCars. */ public function parse(\SplFileObject $file) { // Repository $vehiculeRepository = $this->em->getRepository('ComptesBundle:Vehicule'); // Configuration du handler $configuration = $this->configuration['mycars.xml']; // Tableau de correspondance entre le nom du véhicule dans MyCars et l'objet Vehicule $vehicules = array(); foreach ($configuration['vehicules'] as $vehiculeLabel => $vehiculeID) { $vehicules[$vehiculeLabel] = $vehiculeRepository->find($vehiculeID); } $filename = $file->getPathname(); $xml = simplexml_load_file($filename); foreach ($xml->refuel as $refuel) { $plein = new Plein(); // Véhicule $vehiculeName = (string) $refuel->car_name; $vehicule = $vehicules[$vehiculeName]; $plein->setVehicule($vehicule); // Date $date = \DateTime::createFromFormat('Y-m-d G:i', (string) $refuel->refuelDate); $plein->setDate($date); // Distance parcourue $distanceParcourue = (string) $refuel->distance; $plein->setDistanceParcourue($distanceParcourue); // Montant $montant = (string) $refuel->price * (string) $refuel->quantity; $plein->setMontant($montant); // Prix au litre $prixLitre = (string) $refuel->price; $plein->setPrixLitre($prixLitre); // Quantité $quantite = (string) $refuel->quantity; $plein->setQuantite($quantite); // Classification $classification = $this->getClassification($plein); $this->classify($plein, $classification); } }
public function __construct(\SplFileObject $file, $headerRowNumber = null, $activeSheet = null, $readOnly = true, $maxRows = null, $maxCol = null) { $this->file = $file; $this->activeSheet = $activeSheet; $this->reader = \PHPExcel_IOFactory::createReaderForFile($file->getPathName()); $this->reader->setReadDataOnly($readOnly); if (!is_null($headerRowNumber)) { $this->headerRowNumber = $headerRowNumber; $headerReader = clone $this->reader; $headerReader->setReadFilter(new ReadFilter($headerRowNumber + 1)); /** @var \PHPExcel $excel */ $excel = $headerReader->load($file->getPathname()); if (null !== $activeSheet) { $excel->setActiveSheetIndex($activeSheet); } $rows = $excel->getActiveSheet()->toArray(); $this->columnHeaders = $rows[$headerRowNumber]; //set max col from header length if not already given if (is_null($maxCol)) { $maxCol = \PHPExcel_Cell::stringFromColumnIndex(count($this->columnHeaders) - 1); } } $this->setBoundaries($maxRows, $maxCol); }
public function validate($file, Constraint $constraint) { if ($file) { $file = new \SplFileObject($file->getPathname()); $reader = new CsvReader($file); $reader->setHeaderRowNumber(0); foreach ($reader as $lineNb => $row) { $lineNb = $lineNb + 1; if (count($row) !== 7) { $this->context->addViolation('invalid_number_of_column', ['%lineNb%' => $lineNb]); return; } $columnHeaders = ['resource_type', 'name', 'max_time_reservation', 'description', 'localisation', 'quantity', 'color']; foreach ($columnHeaders as $name) { if (!array_key_exists($name, $row)) { $this->context->addViolation('invalid_column_headers', ['%columnName%' => $name]); return; } } if (strlen($row['resource_type']) < 2 || strlen($row['resource_type']) > 50) { $this->context->addViolation('invalid_number_characters_resource_type', ['%lineNb%' => $lineNb]); return; } if (strlen($row['name']) < 2 || strlen($row['name']) > 50) { $this->context->addViolation('invalid_number_characters_name', ['%lineNb%' => $lineNb]); return; } $file2 = new \SplFileObject($file->getPathname()); $reader2 = new CsvReader($file2); $reader2->setHeaderRowNumber(0); foreach ($reader2 as $lineNb2 => $row2) { $lineNb2 = $lineNb2 + 1; if ($lineNb !== $lineNb2 && strtolower($row['resource_type']) === strtolower($row2['resource_type']) && strtolower($row['name']) === strtolower($row2['name'])) { $this->context->addViolation('double_resource_for_one_resource_type', ['%lineNb1%' => $lineNb, '%lineNb2%' => $lineNb2]); return; } } if (!empty($row['max_time_reservation']) && !preg_match('#^[0-9]+:[0-9]{2}(:[0-9]{2})?$#', $row['max_time_reservation'])) { $this->context->addViolation('invalid_type_for_max_time_reservation', ['%lineNb%' => $lineNb]); return; } if (strlen($row['localisation']) > 255) { $this->context->addViolation('invalid_number_characters_localisation', ['%lineNb%' => $lineNb]); return; } if (intval($row['quantity']) < 1) { $this->context->addViolation('invalid_number_quantity', ['%lineNb%' => $lineNb]); return; } if (!preg_match('/#[a-zA-Z0-9]{6}/', $row['color']) && !empty($row['color'])) { $this->context->addViolation('invalid_color_format', ['%lineNb%' => $lineNb]); return; } $resourceType = $this->em->getRepository('FormaLibreReservationBundle:ResourceType')->findOneBy(['name' => $row['resource_type']]); if ($resourceType) { $resource = $this->em->getRepository('FormaLibreReservationBundle:Resource')->findBy(['resourceType' => $resourceType->getId(), 'name' => $row['name']]); if ($resource) { $this->context->addViolation('resource_already_exists_for_resource_type', ['%lineNb%' => $lineNb]); return; } } } } }
public function unserialize(\SplFileObject $fileObject) { $unserializedXml = $this->xmlEncoder->decode(file_get_contents($fileObject->getPathname()), 'null'); return reset($unserializedXml); }
/** * Get file relative pPath * * @return string */ protected function getFileRelativePath() { $dir = \Includes\Utils\FileManager::getRealPath(LC_DIR_VAR . $this->importer->getOptions()->dir); return substr($this->file->getPathname(), strlen($dir) + 1); }
public function importResourcesAction($file) { $file = new \SplFileObject($file->getPathname()); $reader = new CsvReader($file); $reader->setHeaderRowNumber(0); $data = ['resourcesTypes' => [], 'resources' => []]; foreach ($reader as $row) { $resourceTypeName = ucfirst($row['resource_type']); $resourceName = ucfirst($row['name']); $maxTimeReservation = $row['max_time_reservation']; $description = ucfirst($row['description']); $localisation = ucfirst($row['localisation']); $quantity = $row['quantity']; $color = empty($row['color']) ? '#3a87ad' : $row['color']; $resourceType = $this->resourceTypeRepo->findOneBy(['name' => $resourceTypeName]); if (!$resourceType) { $resourceType = new ResourceType(); $resourceType->setName($resourceTypeName); $this->em->persist($resourceType); $this->em->flush(); $data['resourcesTypes'][] = ['id' => $resourceType->getId(), 'name' => $resourceType->getName()]; } $resource = new Resource(); $resource->setResourceType($resourceType)->setName($resourceName)->setMaxTimeReservation($maxTimeReservation)->setDescription($description)->setLocalisation($localisation)->setQuantity($quantity)->setColor($color); $this->em->persist($resource); $this->em->flush(); $data['resources'][] = ['resourceTypeId' => $resourceType->getId(), 'resource' => ['id' => $resource->getId(), 'name' => $resourceName]]; } return $data; }
/** * @param \SplFileObject $partFile * @param string $destinationUri */ private function moveFile(\SplFileObject $partFile, $destinationUri) { rename($partFile->getPathname(), $destinationUri); }
/** * Constructor * * @param \SplFileObject $file File * @param string $sheet Sheet title (optional) * @param string $type Excel file type (optional, defaults to * Excel2007) */ public function __construct(\SplFileObject $file, $sheet = null, $type = 'Excel2007') { $this->filename = $file->getPathname(); $this->sheet = $sheet; $this->type = $type; }
public function unserialize(\SplFileObject $fileObject) { return json_decode(file_get_contents($fileObject->getPathname()), true); }
/** * {@inheritdoc} */ public function getFilePath() { return $this->file ? $this->file->getPathname() : null; }