Skip to content

Instantly share code, notes, and snippets.

@jimbojsb
Created March 15, 2013 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimbojsb/5172390 to your computer and use it in GitHub Desktop.
Save jimbojsb/5172390 to your computer and use it in GitHub Desktop.
splfileobject
<?php
namespace Genoa\Data\Transport;
use Genoa\Model\Provider;
use Psr\Log\LoggerInterface;
class Cjftp extends \SplFileObject
{
const TEMP_DIR = "/tmp/genoa";
private $provider;
private $columns;
private $logger;
private $shouldDelete = true;
private $mapping = [
'manufacturer' => 'MANUFACTURER',
'sale_price' => 'SALEPRICE',
'price' => 'PRICE',
'name' => 'NAME',
'description' => 'DESCRIPTION',
'image_url' => 'IMAGEURL',
'buy_url' => 'BUYURL' ,
'uid' => 'SKU',
'in_stock' => 'INSTOCK',
'category' => 'ADVERTISERCATEGORY'
];
public function __construct(Provider $provider, LoggerInterface $logger)
{
$this->provider = $provider;
if ($provider->mapping) {
foreach ($provider->mapping as $key => $val) {
$this->mapping[$key] = $val;
}
}
$this->logger = $logger;
if (file_exists($this->provider->source)) {
// mainly for testing, normally this would never exist
parent::__construct($this->provider->source, 'r');
$this->shouldDelete = false;
} else {
$localGzipPath = self::TEMP_DIR . "/" . $this->provider->source;
$localFilePath = str_replace('.gz', '', $localGzipPath);
@mkdir(self::TEMP_DIR);
$ftp = ftp_connect('ftp.vertive.com');
//redacted
ftp_pasv($ftp, true);
@ftp_get($ftp, $localGzipPath, $this->provider->source, FTP_BINARY);
if (!file_exists($localGzipPath)) {
throw new \RuntimeException("Couldn't transfer " . $this->provider->source);
}
exec('gunzip -f ' . $localGzipPath, $output, $retval);
if ($retval != 0) {
$this->logger->warning("gunzip exited with code $retval");
}
if (!file_exists($localFilePath)) {
throw new \RuntimeException("after attempted gunzip, $localFilePath did not exist");
}
parent::__construct($localFilePath, 'r');
}
$this->setCsvControl(',');
$this->setFlags(self::READ_CSV);
$this->columns = parent::current();
$this->next();
}
public function __destruct()
{
if ($this->shouldDelete) {
@unlink($this->getPathname());
}
}
public function current()
{
$raw = parent::current();
if (count($this->columns) == count($raw)) {
$data = array_combine($this->columns, $raw);
$realData = [];
foreach ($this->mapping as $destination => $source) {
$realData[$destination] = $data[$source];
}
if ($realData['in_stock'] != 'NO') {
return $realData;
}
}
}
public function rewind()
{
parent::rewind();
parent::current();
parent::next();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment