f828dd12 by prami

Campaign : upload user

1 parent 2ace4d0d
Showing 551 changed files with 4785 additions and 8 deletions
......@@ -8,6 +8,8 @@ use App\Services\FormBuilder;
use Illuminate\Http\Request;
use Response;
use App\Models\User;
use Excel;
use File;
class CampaignController extends Controller {
......@@ -80,6 +82,63 @@ class CampaignController extends Controller {
// {
// return view("layout.module.campaign.campaignTabData");
// }
if($action == 'upload'){
try{
if($request->hasFile('file')){
$extension = File::extension($request->file->getClientOriginalName());
if ($extension == "xlsx" || $extension == "xls" || $extension == "csv") {
$path = $request->file->getRealPath();
$data = Excel::load($path, function($reader) {
})->get();
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
if(!empty($value->name)){
$campaign = Input::get("selectCampaignField");
if($campaign=="all"){
$campaign="";
$allcampaign=Campaign::where('mtype',"=","company")->orderBy('mkey')->get();
foreach ($allcampaign as $mkeycampaign)
{
$campaign .= $mkeycampaign->mkey.",";
}
$campaign=substr($campaign, 0, -1);
}
$usercampaign=User::where('username','=',trim($value->name))->first();
$campaignList =$usercampaign->clients.",".$campaign;
$data=json_decode($usercampaign->data,true);
if(isset($data['hrmsdata']))
{
$hrmsdata=unserialize($data['hrmsdata']);
$hrmsdata['clientsownerlist'] = $campaignList;
$data['hrmsdata']=serialize($hrmsdata);
}else
{
$hrmsdata['clientsownerlist'] = $campaignList;
$data['hrmsdata']=serialize($hrmsdata);
}
$data=json_encode($data);
$usercampaign->updated_at=date("Y-m-d H:i:s");
$usercampaign->clients=$campaignList;
$usercampaign->data=$data;
$usercampaign->save();
}
}
}
}
}
}catch(Exception $e) {
Log::error($e->getMessage());
}
}
}
public function show($id)
......
......@@ -9,7 +9,8 @@
"laravel/framework": "5.2.*",
"league/flysystem-aws-s3-v3": "~1.0",
"marcelog/pami": "dev-master",
"marcelog/pagi": "2.*"
"marcelog/pagi": "2.*",
"maatwebsite/excel": "~2.1.0"
},
"require-dev": {
"fzaninotto/faker": "~1.4",
......
......@@ -45,6 +45,8 @@ return [
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
Maatwebsite\Excel\ExcelServiceProvider::class,
],
'aliases' => [
......@@ -80,6 +82,7 @@ return [
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
'Input' => 'Illuminate\Support\Facades\Input',
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
],
......
......@@ -43,6 +43,11 @@ $dashboarduser=Auth::user();
//$data['client'] = $client;
// if(isset($username))$data->username = $username;
if(isset($_POST['uploadSet'])){
print_r($_FILES);
exit('test');
}
?>
<div class="row">
<div class="col-md-12">
......@@ -66,16 +71,19 @@ $dashboarduser=Auth::user();
<div class="panel panel-info">
<div class="panel-body">
<form method="post" id="upload_form" enctype="multipart/form-data">
<input type=hidden name=uploadSet value='1'>
{{ csrf_field() }}
<div class="col-md-2">
<label>Upload Users:</label>
</div>
<div class="col-md-6">
<input type="file" name="user">
<input type="file" name="file" id="file" required />
</div>
<div class="col-md-2">
<button id="upload" class="btn btn-xs btn-info">Upload
</button>
<input type="submit" name="upload" id="upload" class="btn btn-primary" value="Upload">
</div>
</form>
</div>
</div>
......@@ -113,6 +121,31 @@ $dashboarduser=Auth::user();
</div>
<script>
$(document).ready(function(){
$('#upload_form').on('submit', function(event){
var selectCampaignField = $('#selectCampaignField').val();
var formData = new FormData(this);
formData.append('selectCampaignField', selectCampaignField);
event.preventDefault();
$.ajax({
url:"campaign?action=upload",
method:"POST",
data:formData,
dataType:'JSON',
contentType: false,
cache: false,
processData: false,
success:function(data)
{
doAjax("campaign/show","campaign="+selectCampaignField,"campaignDetailsArea","","","GET");
simpleNotification('Success','topRight',"Campaign assign suceesfully!");
}
});
});
});
</script>
<script>
function addInQueue(){
var data = 'radioValue='+$("input[name='query']:checked").val();
......
This diff could not be displayed because it is too large.
......@@ -8,16 +8,16 @@ $baseDir = dirname($vendorDir);
return array(
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
'1d1b89d124cc9cb8219922c9d5569199' => $vendorDir . '/hamcrest/hamcrest-php/hamcrest/Hamcrest.php',
'a0edc8309cc5e1d60e3047b5df6b7052' => $vendorDir . '/guzzlehttp/psr7/src/functions_include.php',
'c964ee0ededf28c96ebd9db5099ef910' => $vendorDir . '/guzzlehttp/promises/src/functions_include.php',
'b067bc7112e384b61c701452d53a14a8' => $vendorDir . '/mtdowling/jmespath.php/src/JmesPath.php',
'a0edc8309cc5e1d60e3047b5df6b7052' => $vendorDir . '/guzzlehttp/psr7/src/functions_include.php',
'37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php',
'b067bc7112e384b61c701452d53a14a8' => $vendorDir . '/mtdowling/jmespath.php/src/JmesPath.php',
'667aeda72477189d0494fecd327c3641' => $vendorDir . '/symfony/var-dumper/Resources/functions/dump.php',
'8a9dc1de0ca7e01f3e08231539562f61' => $vendorDir . '/aws/aws-sdk-php/src/functions.php',
'2c102faa651ef8ea5874edb585946bce' => $vendorDir . '/swiftmailer/swiftmailer/lib/swift_required.php',
'bd9634f2d41831496de0d3dfe4c94881' => $vendorDir . '/symfony/polyfill-php56/bootstrap.php',
'e7223560d890eab89cda23685e711e2c' => $vendorDir . '/psy/psysh/src/Psy/functions.php',
'5255c38a0faeba867671b61dfda6d864' => $vendorDir . '/paragonie/random_compat/lib/random.php',
'e7223560d890eab89cda23685e711e2c' => $vendorDir . '/psy/psysh/src/Psy/functions.php',
'f0906e6318348a765ffb6eb24e0d0938' => $vendorDir . '/laravel/framework/src/Illuminate/Foundation/helpers.php',
'58571171fd5812e6e447dce228f52f4d' => $vendorDir . '/laravel/framework/src/Illuminate/Support/helpers.php',
);
......
......@@ -9,7 +9,9 @@ return array(
'Psr\\Log\\' => array($vendorDir . '/psr/log'),
'Prophecy\\' => array($vendorDir . '/phpspec/prophecy/src'),
'PhpSpec' => array($vendorDir . '/phpspec/phpspec/src'),
'PHPExcel' => array($vendorDir . '/phpoffice/phpexcel/Classes'),
'Mockery' => array($vendorDir . '/mockery/mockery/library'),
'Maatwebsite\\Excel\\' => array($vendorDir . '/maatwebsite/excel/src'),
'JakubOnderka\\PhpConsoleHighlighter' => array($vendorDir . '/jakub-onderka/php-console-highlighter/src'),
'JakubOnderka\\PhpConsoleColor' => array($vendorDir . '/jakub-onderka/php-console-color/src'),
'Doctrine\\Common\\Inflector\\' => array($vendorDir . '/doctrine/inflector/lib'),
......
......@@ -6,9 +6,10 @@ $vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'phpDocumentor\\Reflection\\' => array($vendorDir . '/phpdocumentor/reflection-common/src', $vendorDir . '/phpdocumentor/type-resolver/src', $vendorDir . '/phpdocumentor/reflection-docblock/src'),
'phpDocumentor\\Reflection\\' => array($vendorDir . '/phpdocumentor/reflection-common/src', $vendorDir . '/phpdocumentor/reflection-docblock/src', $vendorDir . '/phpdocumentor/type-resolver/src'),
'XdgBaseDir\\' => array($vendorDir . '/dnoegel/php-xdg-base-dir/src'),
'Webmozart\\Assert\\' => array($vendorDir . '/webmozart/assert/src'),
'TijsVerkoyen\\CssToInlineStyles\\' => array($vendorDir . '/tijsverkoyen/css-to-inline-styles/src'),
'Symfony\\Polyfill\\Util\\' => array($vendorDir . '/symfony/polyfill-util'),
'Symfony\\Polyfill\\Php56\\' => array($vendorDir . '/symfony/polyfill-php56'),
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
......
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
## Laravel Excel v2.1.* for Laravel 5
Looking for Laravel Excel for Laravel 4? Visit the [`1.3` branch](https://github.com/Maatwebsite/Laravel-Excel/tree/1.3)
[<img src="http://www.maatwebsite.nl/img/excel_banner.jpg"/>](http://www.maatwebsite.nl/laravel-excel/docs)
[<img src="https://cloud.githubusercontent.com/assets/7728097/6332170/1b495af2-bb84-11e4-9a93-34a9abc01840.jpg"/>](http://www.maatwebsite.nl/vacature-php-programmeur-maastricht)
Laravel Excel brings the power of PHPOffice's PHPExcel to Laravel 5 with a touch of the Laravel Magic. It includes features like: importing Excel and CSV to collections, exporting models, array's and views to Excel, importing batches of files and importing a file by a config file.
- Import into Laravel **Collections**
- Export **Blade views** to Excel and CSV with optional CSS styling
- **Batch** imports
- A lot of optional **config settings**
- Easy **cell caching**
- Chunked and queued importer
- ExcelFile method injections
- Editing existing Excel files
- **Advanced import** by config files
- and many more...
---
```php
Excel::create('Laravel Excel', function($excel) {
$excel->sheet('Excel sheet', function($sheet) {
$sheet->setOrientation('landscape');
});
})->export('xls');
```
---
[![Build Status](https://travis-ci.org/Maatwebsite/Laravel-Excel.svg?branch=master)](https://travis-ci.org/Maatwebsite/Laravel-Excel)
[![Latest Stable Version](https://poser.pugx.org/maatwebsite/excel/v/stable.png)](https://packagist.org/packages/maatwebsite/excel) [![Total Downloads](https://poser.pugx.org/maatwebsite/excel/downloads.png)](https://packagist.org/packages/maatwebsite/excel) [![License](https://poser.pugx.org/maatwebsite/excel/license.png)](https://packagist.org/packages/maatwebsite/excel)
[![Monthly Downloads](https://poser.pugx.org/maatwebsite/excel/d/monthly.png)](https://packagist.org/packages/maatwebsite/excel)
[![Daily Downloads](https://poser.pugx.org/maatwebsite/excel/d/daily.png)](https://packagist.org/packages/maatwebsite/excel)
[![Help the project](http://www.pledgie.com/campaigns/30385.png?skin_name=chrome)](http://pledgie.com/campaigns/30385)
#Installation
Require this package in your `composer.json` and update composer. This will download the package and PHPExcel of PHPOffice.
```php
"maatwebsite/excel": "~2.1.0"
```
After updating composer, add the ServiceProvider to the providers array in `config/app.php`
```php
Maatwebsite\Excel\ExcelServiceProvider::class,
```
You can use the facade for shorter code. Add this to your aliases:
```php
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
```
The class is bound to the ioC as `excel`
```php
$excel = App::make('excel');
```
To publish the config settings in Laravel 5 use:
```php
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
```
This will add an `excel.php` config file to your config folder.
# Documentation
The complete documentation can be found at: [http://www.maatwebsite.nl/laravel-excel/docs](http://www.maatwebsite.nl/laravel-excel/docs)
# Support
Support only through Github. Please don't mail us about issues, make a Github issue instead.
# Contributing
**ALL** bug fixes should be made to appropriate branch (e.g. `2.0` for 2.0.* bug fixes). Bug fixes should never be sent to the `master` branch.
More about contributing can be found at: [http://www.maatwebsite.nl/laravel-excel/docs/getting-started#contributing](http://www.maatwebsite.nl/laravel-excel/docs/getting-started#contributing)
# License
This package is licensed under LGPL. You are free to use it in personal and commercial projects. The code can be forked and modified, but the original copyright author should always be included!
{
"name": "maatwebsite/excel",
"description": "An eloquent way of importing and exporting Excel and CSV in Laravel 4 with the power of PHPExcel",
"license": "LGPL",
"keywords": [
"laravel",
"phpexcel",
"excel",
"csv",
"export",
"import",
"batch"
],
"authors": [
{
"name": "Maatwebsite.nl",
"email": "[email protected]"
}
],
"require": {
"php": ">=5.5",
"phpoffice/phpexcel": "1.8.*",
"illuminate/cache": "5.0.*|5.1.*|5.2.*|5.3.*|5.4.*",
"illuminate/config": "5.0.*|5.1.*|5.2.*|5.3.*|5.4.*",
"illuminate/filesystem": "5.0.*|5.1.*|5.2.*|5.3.*|5.4.*",
"illuminate/support": "5.0.*|5.1.*|5.2.*|5.3.*|5.4.*",
"nesbot/carbon": "~1.0",
"tijsverkoyen/css-to-inline-styles": "~2.0"
},
"require-dev": {
"phpseclib/phpseclib": "~1.0",
"phpunit/phpunit": "~4.0",
"mockery/mockery": "~0.9",
"orchestra/testbench": "3.1.*"
},
"suggest": {
"illuminate/http": "5.0.*|5.1.*|5.2.*|5.3.*|5.4.*",
"illuminate/routing": "5.0.*|5.1.*|5.2.*|5.3.*|5.4.*",
"illuminate/view": "5.0.*|5.1.*|5.2.*|5.3.*|5.4.*",
"illuminate/queue": "5.0.*|5.1.*|5.2.*|5.3.*|5.4.*"
},
"autoload": {
"classmap": [
"src/Maatwebsite/Excel"
],
"psr-0": {
"Maatwebsite\\Excel\\": "src/"
}
},
"autoload-dev": {
"classmap": [
"tests/TestCase.php"
]
}
}
REDIS0006ܳCZV
\ No newline at end of file
{
"providers": [
"Maatwebsite\\Excel\\ExcelServiceProvider"
],
"aliases": [
{
"alias": "Excel",
"facade": "Maatwebsite\\Excel\\Facades\\Excel"
}
]
}
<?php namespace Maatwebsite\Excel\Classes;
use PHPExcel_Settings;
use PHPExcel_CachedObjectStorageFactory;
class Cache {
/**
* PHPExcel cache class
* @var string
*/
protected $class = 'PHPExcel_CachedObjectStorageFactory';
/**
* Available caching drivers
* @var array
*/
protected $available = [
'memory' => 'cache_in_memory',
'gzip' => 'cache_in_memory_gzip',
'serialized' => 'cache_in_memory_serialized',
'igbinary' => 'cache_igbinary',
'discISAM' => 'cache_to_discISAM',
'apc' => 'cache_to_apc',
'memcache' => 'cache_to_memcache',
'temp' => 'cache_to_phpTemp',
'wincache' => 'cache_to_wincache',
'sqlite' => 'cache_to_sqlite',
'sqlite3' => 'cache_to_sqlite3'
];
/**
* The name of the config file
* @var string
*/
private $configName = 'excel.cache';
/**
* Cache constructor
*/
public function __construct()
{
// Get driver and settings from the config
$this->driver = config($this->configName . '.driver', 'memory');
$this->settings = config($this->configName . '.settings', []);
// Init if caching is enabled
if ($this->isEnabled())
$this->init();
}
/**
* Init the cache
* @return void
*/
public function init()
{
// Find the cache driver
$this->findDriver();
// Set the storage driver
PHPExcel_Settings::setCacheStorageMethod($this->method, $this->settings);
}
/**
* Set the right driver
* @return void
*/
public function findDriver()
{
$property = $this->detect();
$this->method = constant($this->class . '::' . $property);
}
/**
* Detect the caching driver
* @return string $driver
*/
protected function detect()
{
// Add additional settings
$this->addAdditionalSettings();
// return the driver
return isset($this->available[$this->driver]) ? $this->available[$this->driver] : reset($this->available);
}
/**
* Add additional settings for the current driver
* @return void
*/
protected function addAdditionalSettings()
{
switch ($this->driver)
{
case 'memcache':
// Add extra memcache settings
$this->settings = array_merge($this->settings, [
'memcacheServer' => config($this->configName . '.memcache.host', 'localhost'),
'memcachePort' => config($this->configName . '.memcache.port', 11211)
]);
break;
case 'discISAM':
// Add dir
$this->settings = array_merge($this->settings, [
'dir' => config($this->configName . '.dir', storage_path('cache')),
]);
break;
}
}
/**
* Check if caching is enabled
* @return boolean
*/
public function isEnabled()
{
return config($this->configName . '.enable', true) ? true : false;
}
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Classes;
use PHPExcel_IOFactory;
use Illuminate\Filesystem\Filesystem;
use Maatwebsite\Excel\Exceptions\LaravelExcelException;
class FormatIdentifier {
/**
* Available formats
*
* @var array
* @access protected
*/
protected $formats = [
'Excel2007',
'Excel5',
'Excel2003XML',
'OOCalc',
'SYLK',
'Gnumeric',
'CSV',
'HTML',
'PDF'
];
/**
* Construct new format identifier
* @param Filesystem $filesystem
*/
public function __construct(Filesystem $filesystem)
{
$this->filesystem = $filesystem;
}
/**
* Get the file format by file
* @param $file
* @throws LaravelExcelException
* @return string $format
*/
public function getFormatByFile($file)
{
// get the file extension
$ext = $this->getExtension($file);
// get the file format
$format = $this->getFormatByExtension($ext);
// Check if the file can be read
if ($this->canRead($format, $file))
return $format;
// Do a last try to init the file with all available readers
return $this->lastResort($file, $format, $ext);
}
/**
* Identify file format
* @param $ext
* @return string $format
*/
public function getFormatByExtension($ext)
{
switch ($ext)
{
/*
|--------------------------------------------------------------------------
| Excel 2007
|--------------------------------------------------------------------------
*/
case 'xlsx':
case 'xlsm':
case 'xltx':
case 'xltm':
return 'Excel2007';
break;
/*
|--------------------------------------------------------------------------
| Excel5
|--------------------------------------------------------------------------
*/
case 'xls':
case 'xlt':
return 'Excel5';
break;
/*
|--------------------------------------------------------------------------
| OOCalc
|--------------------------------------------------------------------------
*/
case 'ods':
case 'ots':
return 'OOCalc';
break;
/*
|--------------------------------------------------------------------------
| SYLK
|--------------------------------------------------------------------------
*/
case 'slk':
return 'SYLK';
break;
/*
|--------------------------------------------------------------------------
| Excel2003XML
|--------------------------------------------------------------------------
*/
case 'xml':
return 'Excel2003XML';
break;
/*
|--------------------------------------------------------------------------
| Gnumeric
|--------------------------------------------------------------------------
*/
case 'gnumeric':
return 'Gnumeric';
break;
/*
|--------------------------------------------------------------------------
| HTML
|--------------------------------------------------------------------------
*/
case 'htm':
case 'html':
return 'HTML';
break;
/*
|--------------------------------------------------------------------------
| CSV
|--------------------------------------------------------------------------
*/
case 'csv':
case 'txt':
return 'CSV';
break;
/*
|--------------------------------------------------------------------------
| PDF
|--------------------------------------------------------------------------
*/
case 'pdf':
return 'PDF';
break;
}
}
/**
* Get the content type by file format
* @param string $format
* @return string $contentType
*/
public function getContentTypeByFormat($format)
{
switch ($format)
{
/*
|--------------------------------------------------------------------------
| Excel 2007
|--------------------------------------------------------------------------
*/
case 'Excel2007':
return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8';
break;
/*
|--------------------------------------------------------------------------
| Excel5
|--------------------------------------------------------------------------
*/
case 'Excel5':
return 'application/vnd.ms-excel; charset=UTF-8';
break;
/*
|--------------------------------------------------------------------------
| HTML
|--------------------------------------------------------------------------
*/
case 'HTML':
return 'HTML';
break;
/*
|--------------------------------------------------------------------------
| CSV
|--------------------------------------------------------------------------
*/
case 'CSV':
return 'application/csv; charset=UTF-8';
break;
/*
|--------------------------------------------------------------------------
| PDF
|--------------------------------------------------------------------------
*/
case 'PDF':
return'application/pdf; charset=UTF-8';
break;
}
}
/**
* Try every reader we have
* @param $file
* @param bool $wrongFormat
* @param string $ext
* @throws LaravelExcelException
* @return string $format
*/
protected function lastResort($file, $wrongFormat = false, $ext = 'xls')
{
// Loop through all available formats
foreach ($this->formats as $format)
{
// Check if the file could be read
if ($wrongFormat != $format && $this->canRead($format, $file))
return $format;
}
// Give up searching and throw an exception
throw new LaravelExcelException('[ERROR] Reader could not identify file format for file [' . $file . '] with extension [' . $ext . ']');
}
/**
* Check if we can read the file
* @param $format
* @param $file
* @return boolean
*/
protected function canRead($format, $file)
{
if ($format)
{
$reader = $this->initReader($format);
return $reader && $reader->canRead($file);
}
return false;
}
/**
* Init the reader based on the format
* @param string $format
* @return \PHPExcel_Reader_IReader
*/
protected function initReader($format)
{
return PHPExcel_IOFactory::createReader($format);
}
/**
* Get the file extension
* @param string $file
* @return string
*/
protected function getExtension($file)
{
return strtolower($this->filesystem->extension($file));
}
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Classes;
use PHPExcel as PHPOffice_PHPExcel;
/**
*
* Laravel wrapper for PHPExcel
*
* @category Laravel Excel
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @copyright Original Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
* @author Maatwebsite <[email protected]>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class PHPExcel extends PHPOffice_PHPExcel {
/**
* Allowed autofill properties
* @var array
*/
public $allowedProperties = [
'creator',
'lastModifiedBy',
'description',
'subject',
'keywords',
'category',
'manager',
'company'
];
/**
* Create sheet and add it to this workbook
*
* @param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last)
* @param bool|string $title
* @throws \PHPExcel_Exception
* @return LaravelExcelWorksheet
*/
public function createSheet($iSheetIndex = null, $title = false)
{
// Init new Laravel Excel worksheet
$newSheet = new LaravelExcelWorksheet($this, $title);
// Add the sheet
$this->addSheet($newSheet, $iSheetIndex);
// Return the sheet
return $newSheet;
}
/**
* Check if the user change change the workbook property
* @param string $method
* @return boolean
*/
public function isChangeableProperty($method)
{
$name = lcfirst(str_replace('set', '', $method));
return in_array($name, $this->getAllowedProperties()) ? true : false;
}
/**
* Set default properties
* @param array $custom
* @return void
*/
public function setDefaultProperties($custom = [])
{
// Get the properties
$properties = $this->getProperties();
// Get fillable properties
foreach ($this->getAllowedProperties() as $prop)
{
// Get the method
$method = 'set' . ucfirst($prop);
// get the value
$value = in_array($prop, array_keys($custom)) ? $custom[$prop] : config('excel.properties.' . $prop, null);
// set the property
call_user_func_array([$properties, $method], [$value]);
}
}
/**
* load info from parent obj
* @param \PHPExcel $object
* @return $this
*/
function cloneParent(\PHPExcel $object)
{
// Init new reflection object
$class = new \ReflectionClass(get_class($object));
// Loop through all properties
foreach($class->getProperties() as $property)
{
// Make the property public
$property->setAccessible(true);
// Set the found value to this sheet
$property->setValue(
$this,
$property->getValue($object)
);
}
return $this;
}
/**
* Return all allowed properties
* @return array
*/
public function getAllowedProperties()
{
return $this->allowedProperties;
}
}
<?php namespace Maatwebsite\Excel\Collections;
/**
*
* LaravelExcel CellCollection
*
* @category Laravel Excel
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <[email protected]>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class CellCollection extends ExcelCollection {
/**
* Create a new collection.
* @param array $items
* @return \Maatwebsite\Excel\Collections\CellCollection
*/
public function __construct(array $items = [])
{
$this->setItems($items);
}
/**
* Set the items
* @param array $items
* @return void
*/
public function setItems($items)
{
foreach ($items as $name => $value)
{
$value = !empty($value) || is_numeric($value) ? $value : null;
$this->put($name, $value);
}
}
/**
* Dynamically get values
* @param string $key
* @return string
*/
public function __get($key)
{
if ($this->has($key))
return $this->get($key);
}
/**
* Determine if an attribute exists on the model.
*
* @param string $key
* @return bool
*/
public function __isset($key)
{
return $this->has($key);
}
}
<?php namespace Maatwebsite\Excel\Collections;
use Illuminate\Support\Collection;
/**
*
* LaravelExcel ExcelCollection
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <[email protected]>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class ExcelCollection extends Collection {
/**
* Sheet title
* @var [type]
*/
protected $title;
/**
* Get the title
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set the title
* @param $title
*/
public function setTitle($title)
{
$this->title = $title;
}
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Collections;
/**
*
* LaravelExcel RowCollection
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <[email protected]>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class RowCollection extends ExcelCollection {
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Collections;
/**
*
* LaravelExcel SheetCollection
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <[email protected]>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class SheetCollection extends ExcelCollection {
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel;
use Closure;
use Maatwebsite\Excel\Readers\Batch;
use Maatwebsite\Excel\Classes\PHPExcel;
use Maatwebsite\Excel\Readers\LaravelExcelReader;
use Maatwebsite\Excel\Writers\LaravelExcelWriter;
use Maatwebsite\Excel\Exceptions\LaravelExcelException;
/**
*
* Laravel wrapper for PHPExcel
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <[email protected]>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class Excel {
/**
* Filter
* @var array
*/
protected $filters = [
'registered' => [],
'enabled' => []
];
/**
* Excel object
* @var PHPExcel
*/
protected $excel;
/**
* Reader object
* @var LaravelExcelReader
*/
protected $reader;
/**
* Writer object
* @var LaravelExcelWriter
*/
protected $writer;
/**
* Construct Excel
* @param PHPExcel $excel
* @param LaravelExcelReader $reader
* @param LaravelExcelWriter $writer
*/
public function __construct(PHPExcel $excel, LaravelExcelReader $reader, LaravelExcelWriter $writer)
{
// Set Excel dependencies
$this->excel = $excel;
$this->reader = $reader;
$this->writer = $writer;
}
/**
* Create a new file
* @param $filename
* @param callable|null $callback
* @return LaravelExcelWriter
*/
public function create($filename, $callback = null)
{
// Writer instance
$writer = clone $this->writer;
// Disconnect worksheets to prevent unnecessary ones
$this->excel->disconnectWorksheets();
// Inject our excel object
$writer->injectExcel($this->excel);
// Set the filename and title
$writer->setFileName($filename);
$writer->setTitle($filename);
// Do the callback
if ($callback instanceof Closure)
call_user_func($callback, $writer);
// Return the writer object
return $writer;
}
/**
*
* Load an existing file
*
* @param string $file The file we want to load
* @param callback|null $callback
* @param string|null $encoding
* @param bool $noBasePath
* @param callback|null $callbackConfigReader
* @return LaravelExcelReader
*/
public function load($file, $callback = null, $encoding = null, $noBasePath = false, $callbackConfigReader = null)
{
// Reader instance
$reader = clone $this->reader;
// Inject excel object
$reader->injectExcel($this->excel);
// Enable filters
$reader->setFilters($this->filters);
// Set the encoding
$encoding = is_string($callback) ? $callback : $encoding;
// Start loading
$reader->load($file, $encoding, $noBasePath, $callbackConfigReader);
// Do the callback
if ($callback instanceof Closure)
call_user_func($callback, $reader);
// Return the reader object
return $reader;
}
/**
* Set select sheets
* @param $sheets
* @return LaravelExcelReader
*/
public function selectSheets($sheets = [])
{
$sheets = is_array($sheets) ? $sheets : func_get_args();
$this->reader->setSelectedSheets($sheets);
return $this;
}
/**
* Select sheets by index
* @param array $sheets
* @return $this
*/
public function selectSheetsByIndex($sheets = [])
{
$sheets = is_array($sheets) ? $sheets : func_get_args();
$this->reader->setSelectedSheetIndices($sheets);
return $this;
}
/**
* Batch import
* @param $files
* @param callback $callback
* @return PHPExcel
*/
public function batch($files, Closure $callback)
{
$batch = new Batch;
return $batch->start($this, $files, $callback);
}
/**
* Create a new file and share a view
* @param string $view
* @param array $data
* @param array $mergeData
* @return LaravelExcelWriter
*/
public function shareView($view, $data = [], $mergeData = [])
{
return $this->create($view)->shareView($view, $data, $mergeData);
}
/**
* Create a new file and load a view
* @param string $view
* @param array $data
* @param array $mergeData
* @return LaravelExcelWriter
*/
public function loadView($view, $data = [], $mergeData = [])
{
return $this->shareView($view, $data, $mergeData);
}
/**
* Set filters
* @param array $filters
* @return Excel
*/
public function registerFilters($filters = [])
{
// If enabled array key exists
if(array_key_exists('enabled', $filters))
{
// Set registered array
$registered = $filters['registered'];
// Filter on enabled
$this->filter($filters['enabled']);
}
else
{
$registered = $filters;
}
// Register the filters
$this->filters['registered'] = !empty($this->filters['registered']) ? array_merge($this->filters['registered'], $registered) : $registered;
return $this;
}
/**
* Enable certain filters
* @param string|array $filter
* @param bool|false|string $class
* @return Excel
*/
public function filter($filter, $class = false)
{
// Add multiple filters
if(is_array($filter))
{
$this->filters['enabled'] = !empty($this->filters['enabled']) ? array_merge($this->filters['enabled'], $filter) : $filter;
}
else
{
// Add single filter
$this->filters['enabled'][] = $filter;
// Overrule filter class for this request
if($class)
$this->filters['registered'][$filter] = $class;
}
// Remove duplicates
$this->filters['enabled'] = array_unique($this->filters['enabled']);
return $this;
}
/**
* Get register, enabled (or both) filters
* @param string|boolean $key [description]
* @return array
*/
public function getFilters($key = false)
{
return $key ? $this->filters[$key] : $this->filters;
}
/**
* Dynamically call methods
* @throws LaravelExcelException
*/
public function __call($method, $params)
{
// If the dynamic call starts with "with", add the var to the data array
if (method_exists($this->excel, $method))
{
// Call the method from the excel object with the given params
return call_user_func_array([$this->excel, $method], $params);
}
// If reader method exists, call that one
if (method_exists($this->reader, $method))
{
// Call the method from the reader object with the given params
return call_user_func_array([$this->reader, $method], $params);
}
throw new LaravelExcelException('Laravel Excel method [' . $method . '] does not exist');
}
}
<?php namespace Maatwebsite\Excel;
use PHPExcel_Settings;
use PHPExcel_Shared_Font;
use Maatwebsite\Excel\Readers\Html;
use Maatwebsite\Excel\Classes\Cache;
use Maatwebsite\Excel\Classes\PHPExcel;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Response;
use Maatwebsite\Excel\Parsers\CssParser;
use Maatwebsite\Excel\Parsers\ViewParser;
use Maatwebsite\Excel\Classes\FormatIdentifier;
use Maatwebsite\Excel\Readers\LaravelExcelReader;
use Maatwebsite\Excel\Writers\LaravelExcelWriter;
use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles;
use Laravel\Lumen\Application as LumenApplication;
/**
*
* LaravelExcel Excel ServiceProvider
*
* @category Laravel Excel
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <[email protected]>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class ExcelServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
if ($this->app instanceof LumenApplication) {
$this->app->configure('excel');
} else {
$this->publishes([
__DIR__ . '/../../config/excel.php' => config_path('excel.php'),
]);
}
$this->mergeConfigFrom(
__DIR__ . '/../../config/excel.php', 'excel'
);
//Set the autosizing settings
$this->setAutoSizingSettings();
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->bindClasses();
$this->bindCssParser();
$this->bindReaders();
$this->bindParsers();
$this->bindPHPExcelClass();
$this->bindWriters();
$this->bindExcel();
}
/**
* Bind PHPExcel classes
* @return void
*/
protected function bindPHPExcelClass()
{
// Set object
$me = $this;
// Bind the PHPExcel class
$this->app->singleton('phpexcel', function () use ($me)
{
// Set locale
$me->setLocale();
// Set the caching settings
$me->setCacheSettings();
// Init phpExcel
$excel = new PHPExcel();
$excel->setDefaultProperties();
return $excel;
});
}
/**
* Bind the css parser
*/
protected function bindCssParser()
{
// Bind css parser
$this->app->singleton('excel.parsers.css', function ()
{
return new CssParser(
new CssToInlineStyles()
);
});
}
/**
* Bind writers
* @return void
*/
protected function bindReaders()
{
// Bind the laravel excel reader
$this->app->singleton('excel.reader', function ($app)
{
return new LaravelExcelReader(
$app['files'],
$app['excel.identifier'],
$app['Illuminate\Contracts\Bus\Dispatcher']
);
});
// Bind the html reader class
$this->app->singleton('excel.readers.html', function ($app)
{
return new Html(
$app['excel.parsers.css']
);
});
}
/**
* Bind writers
* @return void
*/
protected function bindParsers()
{
// Bind the view parser
$this->app->singleton('excel.parsers.view', function ($app)
{
return new ViewParser(
$app['excel.readers.html']
);
});
}
/**
* Bind writers
* @return void
*/
protected function bindWriters()
{
// Bind the excel writer
$this->app->singleton('excel.writer', function ($app)
{
return new LaravelExcelWriter(
$app->make(Response::class),
$app['files'],
$app['excel.identifier']
);
});
}
/**
* Bind Excel class
* @return void
*/
protected function bindExcel()
{
// Bind the Excel class and inject its dependencies
$this->app->singleton('excel', function ($app)
{
$excel = new Excel(
$app['phpexcel'],
$app['excel.reader'],
$app['excel.writer'],
$app['excel.parsers.view']
);
$excel->registerFilters($app['config']->get('excel.filters', array()));
return $excel;
});
$this->app->alias('phpexcel', PHPExcel::class);
}
/**
* Bind other classes
* @return void
*/
protected function bindClasses()
{
// Bind the format identifier
$this->app->singleton('excel.identifier', function ($app)
{
return new FormatIdentifier($app['files']);
});
}
/**
* Set cache settings
* @return Cache
*/
public function setCacheSettings()
{
return new Cache();
}
/**
* Set locale
*/
public function setLocale()
{
$locale = config('app.locale', 'en_us');
PHPExcel_Settings::setLocale($locale);
}
/**
* Set the autosizing settings
*/
public function setAutoSizingSettings()
{
$method = config('excel.export.autosize-method', PHPExcel_Shared_Font::AUTOSIZE_METHOD_APPROX);
PHPExcel_Shared_Font::setAutoSizeMethod($method);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [
'excel',
'phpexcel',
'excel.reader',
'excel.readers.html',
'excel.parsers.view',
'excel.writer'
];
}
}
<?php namespace Maatwebsite\Excel\Exceptions;
use PHPExcel_Exception;
/**
*
* LaravelExcel Exception
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <[email protected]>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class LaravelExcelException extends PHPExcel_Exception {
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Facades;
use Illuminate\Support\Facades\Facade;
/**
*
* LaravelExcel Facade
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <[email protected]>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class Excel extends Facade {
/**
* Return facade accessor
* @return string
*/
protected static function getFacadeAccessor()
{
return 'excel';
}
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Files;
use Illuminate\Foundation\Application;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Exceptions\LaravelExcelException;
abstract class ExcelFile extends File {
/**
* @var bool|string
*/
protected $delimiter;
/**
* @var bool|string
*/
protected $enclosure;
/**
* @var null
*/
protected $encoding = null;
/**
* @param Application $app
* @param Excel $excel
*/
public function __construct(Application $app, Excel $excel)
{
parent::__construct($app, $excel);
$this->file = $this->loadFile();
}
/**
* Get file
* @return string
*/
abstract public function getFile();
/**
* Get delimiter
* @return string
*/
protected function getDelimiter()
{
return $this->delimiter;
}
/**
* Get enclosure
* @return string
*/
protected function getEnclosure()
{
return $this->enclosure;
}
/**
* Get filters
* @return array
*/
public function getFilters()
{
return [];
}
/**
* Start importing
*/
public function handleImport()
{
return $this->handle(
get_class($this)
);
}
/**
* Load the file
* @return \Maatwebsite\Excel\Readers\LaravelExcelReader
*/
public function loadFile()
{
// Load filters
$this->loadFilters();
// Load base settings
$this->loadBaseSettings();
// Load the file
$file = $this->excel->load(
$this->getFile(),
null,
$this->encoding
);
return $file;
}
/**
* Load the filter
* @return void
*/
protected function loadFilters()
{
// Register the filters
$this->excel->registerFilters(
$this->getFilters()
);
// Loop through the filters
foreach($this->getFilters() as $filter)
{
// Enable the filter
$this->excel->filter($filter);
}
}
/**
* Load base settings
*/
protected function loadBaseSettings()
{
$this->loadCSVSettings();
}
/**
* Load CSV Settings
*/
protected function loadCSVSettings()
{
// Get user provided delimiter
$delimiter = $this->getDelimiter();
// Set it when given
if($delimiter)
$this->excel->setDelimiter($delimiter);
// Get user provided enclosure
$enclosure = $this->getEnclosure();
// Set it when given
if($enclosure)
$this->excel->setEnclosure($enclosure);
}
/**
* Dynamically call methods
* @param string $method
* @param array $params
* @return mixed
*/
public function __call($method, $params)
{
return call_user_func_array([$this->file, $method], $params);
}
}
<?php namespace Maatwebsite\Excel\Files;
interface ExportHandler {
/**
* Handle the export
* @param $file
* @return mixed
*/
public function handle($file);
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Files;
use Illuminate\Foundation\Application;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Exceptions\LaravelExcelException;
abstract class File {
/**
* @var Application
*/
protected $app;
/**
* Excel instance
* @var Excel
*/
protected $excel;
/**
* Loaded file
* @var \Maatwebsite\Excel\Readers\LaravelExcelReader
*/
protected $file;
/**
* @param Application $app
* @param Excel $excel
*/
public function __construct(Application $app, Excel $excel)
{
$this->app = $app;
$this->excel = $excel;
}
/**
* Handle the import/export of the file
* @param $type
* @throws LaravelExcelException
* @return mixed
*/
public function handle($type)
{
// Get the handler
$handler = $this->getHandler($type);
// Call the handle method and inject the file
return $handler->handle($this);
}
/**
* Get handler
* @param $type
* @throws LaravelExcelException
* @return mixed
*/
protected function getHandler($type)
{
return $this->app->make(
$this->getHandlerClassName($type)
);
}
/**
* Get the file instance
* @return mixed
*/
public function getFileInstance()
{
return $this->file;
}
/**
* Get the handler class name
* @throws LaravelExcelException
* @return string
*/
protected function getHandlerClassName($type)
{
// Translate the file into a FileHandler
$class = get_class($this);
$handler = substr_replace($class, $type . 'Handler', strrpos($class, $type));
// Check if the handler exists
if (!class_exists($handler))
throw new LaravelExcelException("$type handler [$handler] does not exist.");
return $handler;
}
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Files;
interface ImportHandler {
/**
* Handle the import
* @param $file
* @return mixed
*/
public function handle($file);
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Files;
use Illuminate\Foundation\Application;
use Maatwebsite\Excel\Excel;
abstract class NewExcelFile extends File {
/**
* @param Application $app
* @param Excel $excel
*/
public function __construct(Application $app, Excel $excel)
{
parent::__construct($app, $excel);
$this->file = $this->createNewFile();
}
/**
* Get file
* @return string
*/
abstract public function getFilename();
/**
* Start importing
*/
public function handleExport()
{
return $this->handle(
get_class($this)
);
}
/**
* Load the file
* @return \Maatwebsite\Excel\Readers\LaravelExcelReader
*/
public function createNewFile()
{
// Load the file
$file = $this->excel->create(
$this->getFilename()
);
return $file;
}
/**
* Dynamically call methods
* @param string $method
* @param array $params
* @return mixed
*/
public function __call($method, $params)
{
return call_user_func_array([$this->file, $method], $params);
}
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Filters;
use PHPExcel_Reader_IReadFilter;
class ChunkReadFilter implements PHPExcel_Reader_IReadFilter
{
/**
* Start row
* @var integer
*/
private $_startRow = 0;
/**
* End row
* @var integer
*/
private $_endRow = 0;
/**
* Set the list of rows that we want to read
* @param integer $startRow
* @param integer $chunkSize
* @return void
*/
public function setRows($startRow, $chunkSize)
{
$this->_startRow = $startRow;
$this->_endRow = $startRow + $chunkSize;
}
/**
* Read the cell
* @param string $column
* @param integer $row
* @param string $worksheetName
* @return booleaan
*/
public function readCell($column, $row, $worksheetName = '')
{
// Only read the heading row, and the rows that are configured in $this->_startRow and $this->_endRow
if (($row == config('excel.import.startRow')) || ($row >= $this->_startRow && $row <= $this->_endRow)) {
return true;
}
return false;
}
}
<?php namespace Maatwebsite\Excel\Parsers;
use DOMDocument;
use Illuminate\Support\Facades\URL;
use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles;
/**
*
* LaravelExcel CSS Parser
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <[email protected]>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class CssParser {
/**
* @var CssToInlineStyles
*/
protected $cssInliner;
/**
* DOM xml
* @var \SimpleXMLElement
*/
protected $xml;
/**
* Style sheet links
* @var array
*/
protected $links = [];
/**
* Construct the css parser
* @param CssToInlineStyles $cssInliner
*/
public function __construct(CssToInlineStyles $cssInliner)
{
$this->cssInliner = $cssInliner;
}
/**
* Transform the found css to inline styles
*/
public function transformCssToInlineStyles($html)
{
$css = '';
// Loop through all stylesheets
foreach($this->links as $link)
{
$css .= file_get_contents($link);
}
return $this->cssInliner->convert($html, $css);
}
/**
* Find the stylesheets inside the view
* @param DOMDocument $dom
* @return CssParser
*/
public function findStyleSheets(DOMDocument $dom)
{
// Import the dom
$this->importDom($dom);
// Get all stylesheet tags
$tags = $this->getStyleSheetTags();
foreach ($tags as $node)
{
$this->links[] = $this->getCleanStyleSheetLink($node);
}
// We don't need duplicate css files
$this->links = array_unique($this->links);
return $this;
}
/**
* Import the dom
* @return SimpleXMLElement
*/
protected function importDom(DOMDocument $dom)
{
return $this->xml = simplexml_import_dom($dom);
}
/**
* Get all stylesheet tags
* @return array
*/
protected function getStyleSheetTags()
{
return $this->xml->xpath('//link[@rel="stylesheet"]');
}
/**
* Get the clean link to the stylesheet
* @param string $node
* @return string
*/
protected function getCleanStyleSheetLink($node)
{
// Get the link
$link = $node->attributes()->href;
return $link;
}
/**
* Get css from link
* @param string $link
* @return string|boolean
*/
protected function getCssFromLink($link)
{
return file_get_contents($link);
}
}
<?php namespace Maatwebsite\Excel\Parsers;
use Maatwebsite\Excel\Readers\Html;
use Illuminate\Support\Facades\View;
/**
*
* LaravelExcel ViewParser
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <[email protected]>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class ViewParser {
/**
* View file
* @var string
*/
public $view;
/**
* Data array
* @var array
*/
public $data = [];
/**
* View merge data
* @var array
*/
public $mergeData = [];
/**
* Construct the view parser
* @param Html $reader
* @return \Maatwebsite\Excel\Parsers\ViewParser
*/
public function __construct(Html $reader)
{
$this->reader = $reader;
}
/**
* Parse the view
* @param \Maatwebsite\Excel\Classes\LaravelExcelWorksheet $sheet
* @return \Maatwebsite\Excel\Classes\LaravelExcelWorksheet
*/
public function parse($sheet)
{
$html = View::make($this->getView(), $this->getData(), $this->getMergeData())->render();
return $this->_loadHTML($sheet, $html);
}
/**
* Load the HTML
* @param \Maatwebsite\Excel\Classes\LaravelExcelWorksheet $sheet
* @param string $html
* @return \Maatwebsite\Excel\Classes\LaravelExcelWorksheet
*/
protected function _loadHTML($sheet, $html)
{
return $this->reader->load($html, true, $sheet);
}
/**
* Get the view
* @return string
*/
public function getView()
{
return $this->view;
}
/**
* Get data
* @return array
*/
public function getData()
{
return $this->data;
}
/**
* Get merge data
* @return array
*/
public function getMergeData()
{
return $this->mergeData;
}
/**
* Set the view
* @param bool|string $view
*/
public function setView($view = false)
{
if ($view)
$this->view = $view;
}
/**
* Set the data
* @param array $data
*/
public function setData($data = [])
{
if (!empty($data))
$this->data = array_merge($this->data, $data);
}
/**
* Set the merge data
* @param array $mergeData
*/
public function setMergeData($mergeData = [])
{
if (!empty($mergeData))
$this->mergeData = array_merge($this->mergeData, $mergeData);
}
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Readers;
use Closure;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Exceptions\LaravelExcelException;
/**
*
* LaravelExcel Batch Importer
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <[email protected]>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class Batch {
/**
* Excel object
* @var Excel
*/
protected $excel;
/**
* Batch files
* @var array
*/
public $files = [];
/**
* Set allowed file extensions
* @var array
*/
protected $allowedFileExtensions = [
'xls',
'xlsx',
'csv'
];
/**
* Start the Batach
* @param Excel $excel
* @param array $files
* @param Closure $callback
* @return Excel
*/
public function start(Excel $excel, $files, Closure $callback)
{
// Set excel object
$this->excel = $excel;
// Set files
$this->_setFiles($files);
// Do the callback
if ($callback instanceof Closure)
{
foreach ($this->getFiles() as $file)
{
// Load the file
$excel = $this->excel->load($file);
// Do a callback with the loaded file
call_user_func($callback, $excel, $file);
}
}
// Return our excel object
return $this->excel;
}
/**
* Get the files
* @return array
*/
public function getFiles()
{
return $this->files;
}
/**
* Set the batch files
* @param array|string $files
* @throws LaravelExcelException
* @return void
*/
protected function _setFiles($files)
{
// If the param is an array, these will be the files for the batch import
if (is_array($files))
{
$this->files = $this->_getFilesByArray($files);
}
// Get all the files inside a folder
elseif (is_string($files))
{
$this->files = $this->_getFilesByFolder($files);
}
// Check if files were found
if (empty($this->files))
throw new LaravelExcelException('[ERROR]: No files were found. Batch terminated.');
}
/**
* Set files by array
* @param array $array
* @return array
*/
protected function _getFilesByArray($array)
{
$files = [];
// Make sure we have real paths
foreach ($array as $i => $file)
{
$files[$i] = realpath($file) ? $file : base_path($file);
}
return $files;
}
/**
* Get all files inside a folder
* @param string $folder
* @return array
*/
protected function _getFilesByFolder($folder)
{
// Check if it's a real path
if (!realpath($folder))
$folder = base_path($folder);
// Find path names matching our pattern of excel extensions
$glob = glob($folder . '/*.{' . implode(',', $this->allowedFileExtensions) . '}', GLOB_BRACE);
// If no matches, return empty array
if ($glob === false) return [];
// Return files
return array_filter($glob, function ($file)
{
return filetype($file) == 'file';
});
}
}
\ No newline at end of file
<?php
namespace Maatwebsite\Excel\Readers;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Maatwebsite\Excel\Filters\ChunkReadFilter;
use SuperClosure\Serializer;
class ChunkedReadJob implements ShouldQueue
{
use Queueable;
/**
* @var int
*/
private $startRow;
/**
* @var callable
*/
private $callback;
/**
* @var
*/
private $chunkSize;
/**
* @var
*/
private $startIndex;
/**
* @var
*/
private $file;
/**
* @var null
*/
private $sheets;
/**
* @var bool
*/
private $shouldQueue;
/**
* ChunkedReadJob constructor.
*
* @param $file
* @param null $sheets
* @param int $startRow
* @param $startIndex
* @param $chunkSize
* @param callable $callback
* @param bool $shouldQueue
*/
public function __construct(
$file,
$sheets = null,
$startRow,
$startIndex,
$chunkSize,
callable $callback,
$shouldQueue = true
) {
$this->startRow = $startRow;
$this->chunkSize = $chunkSize;
$this->startIndex = $startIndex;
$this->file = $file;
$this->callback = $shouldQueue ? (new Serializer)->serialize($callback) : $callback;
$this->sheets = $sheets;
$this->shouldQueue = $shouldQueue;
}
/***
* Handle the read job
*/
public function handle()
{
$reader = app('excel.reader');
$reader->injectExcel(app('phpexcel'));
$reader->_init($this->file);
$filter = new ChunkReadFilter();
$reader->reader->setLoadSheetsOnly($this->sheets);
$reader->reader->setReadFilter($filter);
$reader->reader->setReadDataOnly(true);
// Set the rows for the chunking
$filter->setRows($this->startRow, $this->chunkSize);
// Load file with chunk filter enabled
$reader->excel = $reader->reader->load($this->file);
// Slice the results
$results = $reader->get()->slice($this->startIndex, $this->chunkSize);
$callback = $this->shouldQueue ? (new Serializer)->unserialize($this->callback) : $this->callback;
// Do a callback
if (is_callable($callback)) {
$break = call_user_func($callback, $results);
}
$reader->_reset();
unset($reader, $results);
if ($break) {
return true;
}
}
}
<?php namespace Maatwebsite\Excel\Readers;
use Closure;
use PHPExcel;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Collections\SheetCollection;
use Maatwebsite\Excel\Exceptions\LaravelExcelException;
/**
*
* LaravelExcel ConfigReader
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <[email protected]>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class ConfigReader {
/**
* Excel object
* @var PHPExcel
*/
public $excel;
/**
* The sheet
* @var LaravelExcelWorksheet
*/
public $sheet;
/**
* The sheetname
* @var string
*/
public $sheetName;
/**
* Collection of sheets (through the config reader)
* @var SheetCollection
*/
public $sheetCollection;
/**
* Constructor
* @param PHPExcel $excel
* @param string $config
* @param callback $callback
*/
public function __construct(PHPExcel $excel, $config = 'excel.import', $callback = null)
{
// Set excel object
$this->excel = $excel;
// config name
$this->configName = $config;
// start
$this->start($callback);
}
/**
* Start the import
* @param bool|callable $callback $callback
* @throws \PHPExcel_Exception
* @return void
*/
public function start($callback = false)
{
// Init a new sheet collection
$this->sheetCollection = new SheetCollection();
// Get the sheet names
if ($sheets = $this->excel->getSheetNames())
{
// Loop through the sheets
foreach ($sheets as $index => $name)
{
// Set sheet name
$this->sheetName = $name;
// Set sheet
$this->sheet = $this->excel->setActiveSheetIndex($index);
// Do the callback
if ($callback instanceof Closure)
{
call_user_func($callback, $this);
}
// If no callback, put it inside the sheet collection
else
{
$this->sheetCollection->push(clone $this);
}
}
}
}
/**
* Get the sheet collection
* @return SheetCollection
*/
public function getSheetCollection()
{
return $this->sheetCollection;
}
/**
* Get value by index
* @param string $field
* @return string|null
*/
protected function valueByIndex($field)
{
// Convert field name
$field = snake_case($field);
// Get coordinate
if ($coordinate = $this->getCoordinateByKey($field))
{
// return cell value by coordinate
return $this->getCellValueByCoordinate($coordinate);
}
return null;
}
/**
* Return cell value
* @param string $coordinate
* @return string|null
*/
protected function getCellValueByCoordinate($coordinate)
{
if ($this->sheet)
{
if (str_contains($coordinate, ':'))
{
// We want to get a range of cells
$values = $this->sheet->rangeToArray($coordinate);
return $values;
}
else
{
// We want 1 specific cell
return $this->sheet->getCell($coordinate)->getValue();
}
}
return null;
}
/**
* Get the coordinates from the config file
* @param string $field
* @return string|boolean
*/
protected function getCoordinateByKey($field)
{
return config($this->configName . '.' . $this->sheetName . '.' . $field, false);
}
/**
* Dynamically get a value by config
* @param string $field
* @return string
*/
public function __get($field)
{
return $this->valueByIndex($field);
}
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Writers;
use Maatwebsite\Excel\Classes\LaravelExcelWorksheet;
/**
*
* LaravelExcel Excel writer
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <[email protected]>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class CellWriter {
/**
* Current $sheet
* @var LaravelExcelWorksheet
*/
public $sheet;
/**
* Selected cells
* @var array
*/
public $cells;
/**
* Constructor
* @param array $cells
* @param LaravelExcelWorksheet $sheet
*/
public function __construct($cells, LaravelExcelWorksheet $sheet)
{
$this->cells = $cells;
$this->sheet = $sheet;
}
/**
* Set cell value
* @param [type] $value
* @return CellWriter
*/
public function setValue($value)
{
// Only set cell value for single cells
if (!str_contains($this->cells, ':'))
{
$this->sheet->setCellValue($this->cells, $value);
}
return $this;
}
/**
* Set the background
* @param string $color
* @param string $type
* @param string $colorType
* @return CellWriter
*/
public function setBackground($color, $type = 'solid', $colorType = 'rgb')
{
return $this->setColorStyle('fill', $color, $type, $colorType);
}
/**
* Set the font color
* @param string $color
* @param string $colorType
* @return CellWriter
*/
public function setFontColor($color, $colorType = 'rgb')
{
return $this->setColorStyle('font', $color, false, $colorType);
}
/**
* Set the font
* @param $styles
* @return CellWriter
*/
public function setFont($styles)
{
return $this->setStyle('font', $styles);
}
/**
* Set font family
* @param string $family
* @return CellWriter
*/
public function setFontFamily($family)
{
return $this->setStyle('font', [
'name' => $family
]);
}
/**
* Set font size
* @param string $size
* @return CellWriter
*/
public function setFontSize($size)
{
return $this->setStyle('font', [
'size' => $size
]);
}
/**
* Set font weight
* @param boolean|string $bold
* @return CellWriter
*/
public function setFontWeight($bold = true)
{
return $this->setStyle('font', [
'bold' => ($bold === 'bold' || $bold === true)
]);
}
/**
* Set border
* @param string $top
* @param bool|string $right
* @param bool|string $bottom
* @param bool|string $left
* @return CellWriter
*/
public function setBorder($top = 'none', $right = 'none', $bottom = 'none', $left = 'none')
{
// Set the border styles
$styles = is_array($top) ? $top : [
'top' => [
'style' => $top
],
'left' => [
'style' => $left,
],
'right' => [
'style' => $right,
],
'bottom' => [
'style' => $bottom,
]
];
return $this->setStyle('borders', $styles);
}
/**
* Set the text rotation
* @param integer $alignment
* @return CellWriter
*/
public function setTextRotation($degrees)
{
$style = $this->getCellStyle()->getAlignment()->setTextRotation($degrees);
return $this;
}
/**
* Set the alignment
* @param string $alignment
* @return CellWriter
*/
public function setAlignment($alignment)
{
return $this->setStyle('alignment', [
'horizontal' => $alignment
]);
}
/**
* Set vertical alignment
* @param string $alignment
* @return CellWriter
*/
public function setValignment($alignment)
{
return $this->setStyle('alignment', [
'vertical' => $alignment
]);
}
/**
* Set the text indent
* @param integer $indent
* @return CellWriter
*/
public function setTextIndent($indent)
{
$style = $this->getCellStyle()->getAlignment()->setIndent((int)$indent);
return $this;
}
/**
* Set the color style
* @param $styleType
* @param string $color
* @param boolean $type
* @param string $colorType
* @return CellWriter
*/
protected function setColorStyle($styleType, $color, $type = false, $colorType = 'rgb')
{
// Set the styles
$styles = is_array($color) ? $color : [
'type' => $type,
'color' => [$colorType => str_replace('#', '', $color)]
];
return $this->setStyle($styleType, $styles);
}
/**
* Set style
* @param $styleType
* @param string $styles
* @return CellWriter
*/
protected function setStyle($styleType, $styles)
{
// Get the cell style
$style = $this->getCellStyle();
// Apply style from array
$style->applyFromArray([
$styleType => $styles
]);
return $this;
}
/**
* Get the cell style
* @return \PHPExcel_Style
*/
protected function getCellStyle()
{
return $this->sheet->getStyle($this->cells);
}
}
/Build export-ignore
/unitTests export-ignore
README.md export-ignore
build/PHPExcel.phar
unitTests/codeCoverage
analysis
## IDE support
*.buildpath
*.project
/.settings
/.idea
language: php
php:
- 5.4
- 5.5
- 5.6
- 7.0
- hhvm
matrix:
allow_failures:
- php: hhvm
before_script:
## Packages
- sudo apt-get -qq update > /dev/null
## Composer
- composer self-update
- composer install --prefer-source --dev
- phpenv global "$TRAVIS_PHP_VERSION"
script:
## PHP_CodeSniffer
- ./vendor/bin/phpcs --report-width=200 --report-summary --report-full Classes/ unitTests/ --standard=PSR2 -n
## PHPUnit
- phpunit -c ./unitTests/
notifications:
email: false
<?php
PHPExcel_Autoloader::register();
// As we always try to run the autoloader before anything else, we can use it to do a few
// simple checks and initialisations
//PHPExcel_Shared_ZipStreamWrapper::register();
// check mbstring.func_overload
if (ini_get('mbstring.func_overload') & 2) {
throw new PHPExcel_Exception('Multibyte function overloading in PHP must be disabled for string functions (2).');
}
PHPExcel_Shared_String::buildCharacterSets();
/**
* PHPExcel
*
* Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel
* @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
class PHPExcel_Autoloader
{
/**
* Register the Autoloader with SPL
*
*/
public static function register()
{
if (function_exists('__autoload')) {
// Register any existing autoloader function with SPL, so we don't get any clashes
spl_autoload_register('__autoload');
}
// Register ourselves with SPL
if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
return spl_autoload_register(array('PHPExcel_Autoloader', 'load'), true, true);
} else {
return spl_autoload_register(array('PHPExcel_Autoloader', 'load'));
}
}
/**
* Autoload a class identified by name
*
* @param string $pClassName Name of the object to load
*/
public static function load($pClassName)
{
if ((class_exists($pClassName, false)) || (strpos($pClassName, 'PHPExcel') !== 0)) {
// Either already loaded, or not a PHPExcel class request
return false;
}
$pClassFilePath = PHPEXCEL_ROOT .
str_replace('_', DIRECTORY_SEPARATOR, $pClassName) .
'.php';
if ((file_exists($pClassFilePath) === false) || (is_readable($pClassFilePath) === false)) {
// Can't load
return false;
}
require($pClassFilePath);
}
}
<?php
/**
* PHPExcel_CachedObjectStorage_APC
*
* Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel_CachedObjectStorage
* @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
class PHPExcel_CachedObjectStorage_APC extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache
{
/**
* Prefix used to uniquely identify cache data for this worksheet
*
* @access private
* @var string
*/
private $cachePrefix = null;
/**
* Cache timeout
*
* @access private
* @var integer
*/
private $cacheTime = 600;
/**
* Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object
*
* @access private
* @return void
* @throws PHPExcel_Exception
*/
protected function storeData()
{
if ($this->currentCellIsDirty && !empty($this->currentObjectID)) {
$this->currentObject->detach();
if (!apc_store(
$this->cachePrefix . $this->currentObjectID . '.cache',
serialize($this->currentObject),
$this->cacheTime
)) {
$this->__destruct();
throw new PHPExcel_Exception('Failed to store cell ' . $this->currentObjectID . ' in APC');
}
$this->currentCellIsDirty = false;
}
$this->currentObjectID = $this->currentObject = null;
}
/**
* Add or Update a cell in cache identified by coordinate address
*
* @access public
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel_Cell $cell Cell to update
* @return PHPExcel_Cell
* @throws PHPExcel_Exception
*/
public function addCacheData($pCoord, PHPExcel_Cell $cell)
{
if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) {
$this->storeData();
}
$this->cellCache[$pCoord] = true;
$this->currentObjectID = $pCoord;
$this->currentObject = $cell;
$this->currentCellIsDirty = true;
return $cell;
}
/**
* Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell?
*
* @access public
* @param string $pCoord Coordinate address of the cell to check
* @throws PHPExcel_Exception
* @return boolean
*/
public function isDataSet($pCoord)
{
// Check if the requested entry is the current object, or exists in the cache
if (parent::isDataSet($pCoord)) {
if ($this->currentObjectID == $pCoord) {
return true;
}
// Check if the requested entry still exists in apc
$success = apc_fetch($this->cachePrefix.$pCoord.'.cache');
if ($success === false) {
// Entry no longer exists in APC, so clear it from the cache array
parent::deleteCacheData($pCoord);
throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in APC cache');
}
return true;
}
return false;
}
/**
* Get cell at a specific coordinate
*
* @access public
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel_Exception
* @return PHPExcel_Cell Cell that was found, or null if not found
*/
public function getCacheData($pCoord)
{
if ($pCoord === $this->currentObjectID) {
return $this->currentObject;
}
$this->storeData();
// Check if the entry that has been requested actually exists
if (parent::isDataSet($pCoord)) {
$obj = apc_fetch($this->cachePrefix . $pCoord . '.cache');
if ($obj === false) {
// Entry no longer exists in APC, so clear it from the cache array
parent::deleteCacheData($pCoord);
throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in APC cache');
}
} else {
// Return null if requested entry doesn't exist in cache
return null;
}
// Set current entry to the requested entry
$this->currentObjectID = $pCoord;
$this->currentObject = unserialize($obj);
// Re-attach this as the cell's parent
$this->currentObject->attach($this);
// Return requested entry
return $this->currentObject;
}
/**
* Get a list of all cell addresses currently held in cache
*
* @return string[]
*/
public function getCellList()
{
if ($this->currentObjectID !== null) {
$this->storeData();
}
return parent::getCellList();
}
/**
* Delete a cell in cache identified by coordinate address
*
* @access public
* @param string $pCoord Coordinate address of the cell to delete
* @throws PHPExcel_Exception
*/
public function deleteCacheData($pCoord)
{
// Delete the entry from APC
apc_delete($this->cachePrefix.$pCoord.'.cache');
// Delete the entry from our cell address array
parent::deleteCacheData($pCoord);
}
/**
* Clone the cell collection
*
* @access public
* @param PHPExcel_Worksheet $parent The new worksheet
* @throws PHPExcel_Exception
* @return void
*/
public function copyCellCollection(PHPExcel_Worksheet $parent)
{
parent::copyCellCollection($parent);
// Get a new id for the new file name
$baseUnique = $this->getUniqueID();
$newCachePrefix = substr(md5($baseUnique), 0, 8) . '.';
$cacheList = $this->getCellList();
foreach ($cacheList as $cellID) {
if ($cellID != $this->currentObjectID) {
$obj = apc_fetch($this->cachePrefix . $cellID . '.cache');
if ($obj === false) {
// Entry no longer exists in APC, so clear it from the cache array
parent::deleteCacheData($cellID);
throw new PHPExcel_Exception('Cell entry ' . $cellID . ' no longer exists in APC');
}
if (!apc_store($newCachePrefix . $cellID . '.cache', $obj, $this->cacheTime)) {
$this->__destruct();
throw new PHPExcel_Exception('Failed to store cell ' . $cellID . ' in APC');
}
}
}
$this->cachePrefix = $newCachePrefix;
}
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells()
{
if ($this->currentObject !== null) {
$this->currentObject->detach();
$this->currentObject = $this->currentObjectID = null;
}
// Flush the APC cache
$this->__destruct();
$this->cellCache = array();
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->parent = null;
}
/**
* Initialise this new cell collection
*
* @param PHPExcel_Worksheet $parent The worksheet for this cell collection
* @param array of mixed $arguments Additional initialisation arguments
*/
public function __construct(PHPExcel_Worksheet $parent, $arguments)
{
$cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600;
if ($this->cachePrefix === null) {
$baseUnique = $this->getUniqueID();
$this->cachePrefix = substr(md5($baseUnique), 0, 8) . '.';
$this->cacheTime = $cacheTime;
parent::__construct($parent);
}
}
/**
* Destroy this cell collection
*/
public function __destruct()
{
$cacheList = $this->getCellList();
foreach ($cacheList as $cellID) {
apc_delete($this->cachePrefix . $cellID . '.cache');
}
}
/**
* Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build
*
* @return boolean
*/
public static function cacheMethodIsAvailable()
{
if (!function_exists('apc_store')) {
return false;
}
if (apc_sma_info() === false) {
return false;
}
return true;
}
}
<?php
/**
* PHPExcel_CachedObjectStorage_DiscISAM
*
* Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel_CachedObjectStorage
* @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
class PHPExcel_CachedObjectStorage_DiscISAM extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache
{
/**
* Name of the file for this cache
*
* @var string
*/
private $fileName = null;
/**
* File handle for this cache file
*
* @var resource
*/
private $fileHandle = null;
/**
* Directory/Folder where the cache file is located
*
* @var string
*/
private $cacheDirectory = null;
/**
* Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object
*
* @return void
* @throws PHPExcel_Exception
*/
protected function storeData()
{
if ($this->currentCellIsDirty && !empty($this->currentObjectID)) {
$this->currentObject->detach();
fseek($this->fileHandle, 0, SEEK_END);
$this->cellCache[$this->currentObjectID] = array(
'ptr' => ftell($this->fileHandle),
'sz' => fwrite($this->fileHandle, serialize($this->currentObject))
);
$this->currentCellIsDirty = false;
}
$this->currentObjectID = $this->currentObject = null;
}
/**
* Add or Update a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel_Cell $cell Cell to update
* @return PHPExcel_Cell
* @throws PHPExcel_Exception
*/
public function addCacheData($pCoord, PHPExcel_Cell $cell)
{
if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) {
$this->storeData();
}
$this->currentObjectID = $pCoord;
$this->currentObject = $cell;
$this->currentCellIsDirty = true;
return $cell;
}
/**
* Get cell at a specific coordinate
*
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel_Exception
* @return PHPExcel_Cell Cell that was found, or null if not found
*/
public function getCacheData($pCoord)
{
if ($pCoord === $this->currentObjectID) {
return $this->currentObject;
}
$this->storeData();
// Check if the entry that has been requested actually exists
if (!isset($this->cellCache[$pCoord])) {
// Return null if requested entry doesn't exist in cache
return null;
}
// Set current entry to the requested entry
$this->currentObjectID = $pCoord;
fseek($this->fileHandle, $this->cellCache[$pCoord]['ptr']);
$this->currentObject = unserialize(fread($this->fileHandle, $this->cellCache[$pCoord]['sz']));
// Re-attach this as the cell's parent
$this->currentObject->attach($this);
// Return requested entry
return $this->currentObject;
}
/**
* Get a list of all cell addresses currently held in cache
*
* @return string[]
*/
public function getCellList()
{
if ($this->currentObjectID !== null) {
$this->storeData();
}
return parent::getCellList();
}
/**
* Clone the cell collection
*
* @param PHPExcel_Worksheet $parent The new worksheet
*/
public function copyCellCollection(PHPExcel_Worksheet $parent)
{
parent::copyCellCollection($parent);
// Get a new id for the new file name
$baseUnique = $this->getUniqueID();
$newFileName = $this->cacheDirectory.'/PHPExcel.'.$baseUnique.'.cache';
// Copy the existing cell cache file
copy($this->fileName, $newFileName);
$this->fileName = $newFileName;
// Open the copied cell cache file
$this->fileHandle = fopen($this->fileName, 'a+');
}
/**
* Clear the cell collection and disconnect from our parent
*
*/
public function unsetWorksheetCells()
{
if (!is_null($this->currentObject)) {
$this->currentObject->detach();
$this->currentObject = $this->currentObjectID = null;
}
$this->cellCache = array();
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->parent = null;
// Close down the temporary cache file
$this->__destruct();
}
/**
* Initialise this new cell collection
*
* @param PHPExcel_Worksheet $parent The worksheet for this cell collection
* @param array of mixed $arguments Additional initialisation arguments
*/
public function __construct(PHPExcel_Worksheet $parent, $arguments)
{
$this->cacheDirectory = ((isset($arguments['dir'])) && ($arguments['dir'] !== null))
? $arguments['dir']
: PHPExcel_Shared_File::sys_get_temp_dir();
parent::__construct($parent);
if (is_null($this->fileHandle)) {
$baseUnique = $this->getUniqueID();
$this->fileName = $this->cacheDirectory.'/PHPExcel.'.$baseUnique.'.cache';
$this->fileHandle = fopen($this->fileName, 'a+');
}
}
/**
* Destroy this cell collection
*/
public function __destruct()
{
if (!is_null($this->fileHandle)) {
fclose($this->fileHandle);
unlink($this->fileName);
}
$this->fileHandle = null;
}
}
<?php
/**
* PHPExcel_CachedObjectStorage_ICache
*
* Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel_CachedObjectStorage
* @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
interface PHPExcel_CachedObjectStorage_ICache
{
/**
* Add or Update a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel_Cell $cell Cell to update
* @return PHPExcel_Cell
* @throws PHPExcel_Exception
*/
public function addCacheData($pCoord, PHPExcel_Cell $cell);
/**
* Add or Update a cell in cache
*
* @param PHPExcel_Cell $cell Cell to update
* @return PHPExcel_Cell
* @throws PHPExcel_Exception
*/
public function updateCacheData(PHPExcel_Cell $cell);
/**
* Fetch a cell from cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to retrieve
* @return PHPExcel_Cell Cell that was found, or null if not found
* @throws PHPExcel_Exception
*/
public function getCacheData($pCoord);
/**
* Delete a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to delete
* @throws PHPExcel_Exception
*/
public function deleteCacheData($pCoord);
/**
* Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell?
*
* @param string $pCoord Coordinate address of the cell to check
* @return boolean
*/
public function isDataSet($pCoord);
/**
* Get a list of all cell addresses currently held in cache
*
* @return string[]
*/
public function getCellList();
/**
* Get the list of all cell addresses currently held in cache sorted by column and row
*
* @return string[]
*/
public function getSortedCellList();
/**
* Clone the cell collection
*
* @param PHPExcel_Worksheet $parent The new worksheet
* @return void
*/
public function copyCellCollection(PHPExcel_Worksheet $parent);
/**
* Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build
*
* @return boolean
*/
public static function cacheMethodIsAvailable();
}
<?php
/**
* PHPExcel_CachedObjectStorage_Igbinary
*
* Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel_CachedObjectStorage
* @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
class PHPExcel_CachedObjectStorage_Igbinary extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache
{
/**
* Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object
*
* @return void
* @throws PHPExcel_Exception
*/
protected function storeData()
{
if ($this->currentCellIsDirty && !empty($this->currentObjectID)) {
$this->currentObject->detach();
$this->cellCache[$this->currentObjectID] = igbinary_serialize($this->currentObject);
$this->currentCellIsDirty = false;
}
$this->currentObjectID = $this->currentObject = null;
} // function _storeData()
/**
* Add or Update a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel_Cell $cell Cell to update
* @return PHPExcel_Cell
* @throws PHPExcel_Exception
*/
public function addCacheData($pCoord, PHPExcel_Cell $cell)
{
if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) {
$this->storeData();
}
$this->currentObjectID = $pCoord;
$this->currentObject = $cell;
$this->currentCellIsDirty = true;
return $cell;
} // function addCacheData()
/**
* Get cell at a specific coordinate
*
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel_Exception
* @return PHPExcel_Cell Cell that was found, or null if not found
*/
public function getCacheData($pCoord)
{
if ($pCoord === $this->currentObjectID) {
return $this->currentObject;
}
$this->storeData();
// Check if the entry that has been requested actually exists
if (!isset($this->cellCache[$pCoord])) {
// Return null if requested entry doesn't exist in cache
return null;
}
// Set current entry to the requested entry
$this->currentObjectID = $pCoord;
$this->currentObject = igbinary_unserialize($this->cellCache[$pCoord]);
// Re-attach this as the cell's parent
$this->currentObject->attach($this);
// Return requested entry
return $this->currentObject;
} // function getCacheData()
/**
* Get a list of all cell addresses currently held in cache
*
* @return string[]
*/
public function getCellList()
{
if ($this->currentObjectID !== null) {
$this->storeData();
}
return parent::getCellList();
}
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells()
{
if (!is_null($this->currentObject)) {
$this->currentObject->detach();
$this->currentObject = $this->currentObjectID = null;
}
$this->cellCache = array();
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->parent = null;
} // function unsetWorksheetCells()
/**
* Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build
*
* @return boolean
*/
public static function cacheMethodIsAvailable()
{
if (!function_exists('igbinary_serialize')) {
return false;
}
return true;
}
}
<?php
/**
* PHPExcel_CachedObjectStorage_Memory
*
* Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel_CachedObjectStorage
* @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
class PHPExcel_CachedObjectStorage_Memory extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache
{
/**
* Dummy method callable from CacheBase, but unused by Memory cache
*
* @return void
*/
protected function storeData()
{
}
/**
* Add or Update a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel_Cell $cell Cell to update
* @return PHPExcel_Cell
* @throws PHPExcel_Exception
*/
public function addCacheData($pCoord, PHPExcel_Cell $cell)
{
$this->cellCache[$pCoord] = $cell;
// Set current entry to the new/updated entry
$this->currentObjectID = $pCoord;
return $cell;
}
/**
* Get cell at a specific coordinate
*
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel_Exception
* @return PHPExcel_Cell Cell that was found, or null if not found
*/
public function getCacheData($pCoord)
{
// Check if the entry that has been requested actually exists
if (!isset($this->cellCache[$pCoord])) {
$this->currentObjectID = null;
// Return null if requested entry doesn't exist in cache
return null;
}
// Set current entry to the requested entry
$this->currentObjectID = $pCoord;
// Return requested entry
return $this->cellCache[$pCoord];
}
/**
* Clone the cell collection
*
* @param PHPExcel_Worksheet $parent The new worksheet
*/
public function copyCellCollection(PHPExcel_Worksheet $parent)
{
parent::copyCellCollection($parent);
$newCollection = array();
foreach ($this->cellCache as $k => &$cell) {
$newCollection[$k] = clone $cell;
$newCollection[$k]->attach($this);
}
$this->cellCache = $newCollection;
}
/**
* Clear the cell collection and disconnect from our parent
*
*/
public function unsetWorksheetCells()
{
// Because cells are all stored as intact objects in memory, we need to detach each one from the parent
foreach ($this->cellCache as $k => &$cell) {
$cell->detach();
$this->cellCache[$k] = null;
}
unset($cell);
$this->cellCache = array();
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->parent = null;
}
}
<?php
/**
* PHPExcel_CachedObjectStorage_MemoryGZip
*
* Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel_CachedObjectStorage
* @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
class PHPExcel_CachedObjectStorage_MemoryGZip extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache
{
/**
* Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object
*
* @return void
* @throws PHPExcel_Exception
*/
protected function storeData()
{
if ($this->currentCellIsDirty && !empty($this->currentObjectID)) {
$this->currentObject->detach();
$this->cellCache[$this->currentObjectID] = gzdeflate(serialize($this->currentObject));
$this->currentCellIsDirty = false;
}
$this->currentObjectID = $this->currentObject = null;
}
/**
* Add or Update a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel_Cell $cell Cell to update
* @return PHPExcel_Cell
* @throws PHPExcel_Exception
*/
public function addCacheData($pCoord, PHPExcel_Cell $cell)
{
if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) {
$this->storeData();
}
$this->currentObjectID = $pCoord;
$this->currentObject = $cell;
$this->currentCellIsDirty = true;
return $cell;
}
/**
* Get cell at a specific coordinate
*
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel_Exception
* @return PHPExcel_Cell Cell that was found, or null if not found
*/
public function getCacheData($pCoord)
{
if ($pCoord === $this->currentObjectID) {
return $this->currentObject;
}
$this->storeData();
// Check if the entry that has been requested actually exists
if (!isset($this->cellCache[$pCoord])) {
// Return null if requested entry doesn't exist in cache
return null;
}
// Set current entry to the requested entry
$this->currentObjectID = $pCoord;
$this->currentObject = unserialize(gzinflate($this->cellCache[$pCoord]));
// Re-attach this as the cell's parent
$this->currentObject->attach($this);
// Return requested entry
return $this->currentObject;
}
/**
* Get a list of all cell addresses currently held in cache
*
* @return string[]
*/
public function getCellList()
{
if ($this->currentObjectID !== null) {
$this->storeData();
}
return parent::getCellList();
}
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells()
{
if (!is_null($this->currentObject)) {
$this->currentObject->detach();
$this->currentObject = $this->currentObjectID = null;
}
$this->cellCache = array();
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->parent = null;
}
}
<?php
/**
* PHPExcel_CachedObjectStorage_MemorySerialized
*
* Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel_CachedObjectStorage
* @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
class PHPExcel_CachedObjectStorage_MemorySerialized extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache
{
/**
* Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object
*
* @return void
* @throws PHPExcel_Exception
*/
protected function storeData()
{
if ($this->currentCellIsDirty && !empty($this->currentObjectID)) {
$this->currentObject->detach();
$this->cellCache[$this->currentObjectID] = serialize($this->currentObject);
$this->currentCellIsDirty = false;
}
$this->currentObjectID = $this->currentObject = null;
}
/**
* Add or Update a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel_Cell $cell Cell to update
* @return PHPExcel_Cell
* @throws PHPExcel_Exception
*/
public function addCacheData($pCoord, PHPExcel_Cell $cell)
{
if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) {
$this->storeData();
}
$this->currentObjectID = $pCoord;
$this->currentObject = $cell;
$this->currentCellIsDirty = true;
return $cell;
}
/**
* Get cell at a specific coordinate
*
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel_Exception
* @return PHPExcel_Cell Cell that was found, or null if not found
*/
public function getCacheData($pCoord)
{
if ($pCoord === $this->currentObjectID) {
return $this->currentObject;
}
$this->storeData();
// Check if the entry that has been requested actually exists
if (!isset($this->cellCache[$pCoord])) {
// Return null if requested entry doesn't exist in cache
return null;
}
// Set current entry to the requested entry
$this->currentObjectID = $pCoord;
$this->currentObject = unserialize($this->cellCache[$pCoord]);
// Re-attach this as the cell's parent
$this->currentObject->attach($this);
// Return requested entry
return $this->currentObject;
}
/**
* Get a list of all cell addresses currently held in cache
*
* @return string[]
*/
public function getCellList()
{
if ($this->currentObjectID !== null) {
$this->storeData();
}
return parent::getCellList();
}
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells()
{
if (!is_null($this->currentObject)) {
$this->currentObject->detach();
$this->currentObject = $this->currentObjectID = null;
}
$this->cellCache = array();
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->parent = null;
}
}
<?php
/**
* PHPExcel_CachedObjectStorage_PHPTemp
*
* Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel_CachedObjectStorage
* @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
class PHPExcel_CachedObjectStorage_PHPTemp extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache
{
/**
* Name of the file for this cache
*
* @var string
*/
private $fileHandle = null;
/**
* Memory limit to use before reverting to file cache
*
* @var integer
*/
private $memoryCacheSize = null;
/**
* Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object
*
* @return void
* @throws PHPExcel_Exception
*/
protected function storeData()
{
if ($this->currentCellIsDirty && !empty($this->currentObjectID)) {
$this->currentObject->detach();
fseek($this->fileHandle, 0, SEEK_END);
$this->cellCache[$this->currentObjectID] = array(
'ptr' => ftell($this->fileHandle),
'sz' => fwrite($this->fileHandle, serialize($this->currentObject))
);
$this->currentCellIsDirty = false;
}
$this->currentObjectID = $this->currentObject = null;
}
/**
* Add or Update a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel_Cell $cell Cell to update
* @return PHPExcel_Cell
* @throws PHPExcel_Exception
*/
public function addCacheData($pCoord, PHPExcel_Cell $cell)
{
if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) {
$this->storeData();
}
$this->currentObjectID = $pCoord;
$this->currentObject = $cell;
$this->currentCellIsDirty = true;
return $cell;
}
/**
* Get cell at a specific coordinate
*
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel_Exception
* @return PHPExcel_Cell Cell that was found, or null if not found
*/
public function getCacheData($pCoord)
{
if ($pCoord === $this->currentObjectID) {
return $this->currentObject;
}
$this->storeData();
// Check if the entry that has been requested actually exists
if (!isset($this->cellCache[$pCoord])) {
// Return null if requested entry doesn't exist in cache
return null;
}
// Set current entry to the requested entry
$this->currentObjectID = $pCoord;
fseek($this->fileHandle, $this->cellCache[$pCoord]['ptr']);
$this->currentObject = unserialize(fread($this->fileHandle, $this->cellCache[$pCoord]['sz']));
// Re-attach this as the cell's parent
$this->currentObject->attach($this);
// Return requested entry
return $this->currentObject;
}
/**
* Get a list of all cell addresses currently held in cache
*
* @return string[]
*/
public function getCellList()
{
if ($this->currentObjectID !== null) {
$this->storeData();
}
return parent::getCellList();
}
/**
* Clone the cell collection
*
* @param PHPExcel_Worksheet $parent The new worksheet
* @return void
*/
public function copyCellCollection(PHPExcel_Worksheet $parent)
{
parent::copyCellCollection($parent);
// Open a new stream for the cell cache data
$newFileHandle = fopen('php://temp/maxmemory:' . $this->memoryCacheSize, 'a+');
// Copy the existing cell cache data to the new stream
fseek($this->fileHandle, 0);
while (!feof($this->fileHandle)) {
fwrite($newFileHandle, fread($this->fileHandle, 1024));
}
$this->fileHandle = $newFileHandle;
}
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells()
{
if (!is_null($this->currentObject)) {
$this->currentObject->detach();
$this->currentObject = $this->currentObjectID = null;
}
$this->cellCache = array();
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->parent = null;
// Close down the php://temp file
$this->__destruct();
}
/**
* Initialise this new cell collection
*
* @param PHPExcel_Worksheet $parent The worksheet for this cell collection
* @param array of mixed $arguments Additional initialisation arguments
*/
public function __construct(PHPExcel_Worksheet $parent, $arguments)
{
$this->memoryCacheSize = (isset($arguments['memoryCacheSize'])) ? $arguments['memoryCacheSize'] : '1MB';
parent::__construct($parent);
if (is_null($this->fileHandle)) {
$this->fileHandle = fopen('php://temp/maxmemory:' . $this->memoryCacheSize, 'a+');
}
}
/**
* Destroy this cell collection
*/
public function __destruct()
{
if (!is_null($this->fileHandle)) {
fclose($this->fileHandle);
}
$this->fileHandle = null;
}
}
<?php
/**
* PHPExcel_CachedObjectStorage_Wincache
*
* Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel_CachedObjectStorage
* @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
class PHPExcel_CachedObjectStorage_Wincache extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache
{
/**
* Prefix used to uniquely identify cache data for this worksheet
*
* @var string
*/
private $cachePrefix = null;
/**
* Cache timeout
*
* @var integer
*/
private $cacheTime = 600;
/**
* Store cell data in cache for the current cell object if it's "dirty",
* and the 'nullify' the current cell object
*
* @return void
* @throws PHPExcel_Exception
*/
protected function storeData()
{
if ($this->currentCellIsDirty && !empty($this->currentObjectID)) {
$this->currentObject->detach();
$obj = serialize($this->currentObject);
if (wincache_ucache_exists($this->cachePrefix.$this->currentObjectID.'.cache')) {
if (!wincache_ucache_set($this->cachePrefix.$this->currentObjectID.'.cache', $obj, $this->cacheTime)) {
$this->__destruct();
throw new PHPExcel_Exception('Failed to store cell '.$this->currentObjectID.' in WinCache');
}
} else {
if (!wincache_ucache_add($this->cachePrefix.$this->currentObjectID.'.cache', $obj, $this->cacheTime)) {
$this->__destruct();
throw new PHPExcel_Exception('Failed to store cell '.$this->currentObjectID.' in WinCache');
}
}
$this->currentCellIsDirty = false;
}
$this->currentObjectID = $this->currentObject = null;
}
/**
* Add or Update a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to update
* @param PHPExcel_Cell $cell Cell to update
* @return PHPExcel_Cell
* @throws PHPExcel_Exception
*/
public function addCacheData($pCoord, PHPExcel_Cell $cell)
{
if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) {
$this->storeData();
}
$this->cellCache[$pCoord] = true;
$this->currentObjectID = $pCoord;
$this->currentObject = $cell;
$this->currentCellIsDirty = true;
return $cell;
}
/**
* Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell?
*
* @param string $pCoord Coordinate address of the cell to check
* @return boolean
*/
public function isDataSet($pCoord)
{
// Check if the requested entry is the current object, or exists in the cache
if (parent::isDataSet($pCoord)) {
if ($this->currentObjectID == $pCoord) {
return true;
}
// Check if the requested entry still exists in cache
$success = wincache_ucache_exists($this->cachePrefix.$pCoord.'.cache');
if ($success === false) {
// Entry no longer exists in Wincache, so clear it from the cache array
parent::deleteCacheData($pCoord);
throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in WinCache');
}
return true;
}
return false;
}
/**
* Get cell at a specific coordinate
*
* @param string $pCoord Coordinate of the cell
* @throws PHPExcel_Exception
* @return PHPExcel_Cell Cell that was found, or null if not found
*/
public function getCacheData($pCoord)
{
if ($pCoord === $this->currentObjectID) {
return $this->currentObject;
}
$this->storeData();
// Check if the entry that has been requested actually exists
$obj = null;
if (parent::isDataSet($pCoord)) {
$success = false;
$obj = wincache_ucache_get($this->cachePrefix.$pCoord.'.cache', $success);
if ($success === false) {
// Entry no longer exists in WinCache, so clear it from the cache array
parent::deleteCacheData($pCoord);
throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in WinCache');
}
} else {
// Return null if requested entry doesn't exist in cache
return null;
}
// Set current entry to the requested entry
$this->currentObjectID = $pCoord;
$this->currentObject = unserialize($obj);
// Re-attach this as the cell's parent
$this->currentObject->attach($this);
// Return requested entry
return $this->currentObject;
}
/**
* Get a list of all cell addresses currently held in cache
*
* @return string[]
*/
public function getCellList()
{
if ($this->currentObjectID !== null) {
$this->storeData();
}
return parent::getCellList();
}
/**
* Delete a cell in cache identified by coordinate address
*
* @param string $pCoord Coordinate address of the cell to delete
* @throws PHPExcel_Exception
*/
public function deleteCacheData($pCoord)
{
// Delete the entry from Wincache
wincache_ucache_delete($this->cachePrefix.$pCoord.'.cache');
// Delete the entry from our cell address array
parent::deleteCacheData($pCoord);
}
/**
* Clone the cell collection
*
* @param PHPExcel_Worksheet $parent The new worksheet
* @return void
*/
public function copyCellCollection(PHPExcel_Worksheet $parent)
{
parent::copyCellCollection($parent);
// Get a new id for the new file name
$baseUnique = $this->getUniqueID();
$newCachePrefix = substr(md5($baseUnique), 0, 8) . '.';
$cacheList = $this->getCellList();
foreach ($cacheList as $cellID) {
if ($cellID != $this->currentObjectID) {
$success = false;
$obj = wincache_ucache_get($this->cachePrefix.$cellID.'.cache', $success);
if ($success === false) {
// Entry no longer exists in WinCache, so clear it from the cache array
parent::deleteCacheData($cellID);
throw new PHPExcel_Exception('Cell entry '.$cellID.' no longer exists in Wincache');
}
if (!wincache_ucache_add($newCachePrefix.$cellID.'.cache', $obj, $this->cacheTime)) {
$this->__destruct();
throw new PHPExcel_Exception('Failed to store cell '.$cellID.' in Wincache');
}
}
}
$this->cachePrefix = $newCachePrefix;
}
/**
* Clear the cell collection and disconnect from our parent
*
* @return void
*/
public function unsetWorksheetCells()
{
if (!is_null($this->currentObject)) {
$this->currentObject->detach();
$this->currentObject = $this->currentObjectID = null;
}
// Flush the WinCache cache
$this->__destruct();
$this->cellCache = array();
// detach ourself from the worksheet, so that it can then delete this object successfully
$this->parent = null;
}
/**
* Initialise this new cell collection
*
* @param PHPExcel_Worksheet $parent The worksheet for this cell collection
* @param array of mixed $arguments Additional initialisation arguments
*/
public function __construct(PHPExcel_Worksheet $parent, $arguments)
{
$cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600;
if (is_null($this->cachePrefix)) {
$baseUnique = $this->getUniqueID();
$this->cachePrefix = substr(md5($baseUnique), 0, 8).'.';
$this->cacheTime = $cacheTime;
parent::__construct($parent);
}
}
/**
* Destroy this cell collection
*/
public function __destruct()
{
$cacheList = $this->getCellList();
foreach ($cacheList as $cellID) {
wincache_ucache_delete($this->cachePrefix.$cellID.'.cache');
}
}
/**
* Identify whether the caching method is currently available
* Some methods are dependent on the availability of certain extensions being enabled in the PHP build
*
* @return boolean
*/
public static function cacheMethodIsAvailable()
{
if (!function_exists('wincache_ucache_add')) {
return false;
}
return true;
}
}
<?php
/**
* PHPExcel_CachedObjectStorageFactory
*
* Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel_CachedObjectStorage
* @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
class PHPExcel_CachedObjectStorageFactory
{
const cache_in_memory = 'Memory';
const cache_in_memory_gzip = 'MemoryGZip';
const cache_in_memory_serialized = 'MemorySerialized';
const cache_igbinary = 'Igbinary';
const cache_to_discISAM = 'DiscISAM';
const cache_to_apc = 'APC';
const cache_to_memcache = 'Memcache';
const cache_to_phpTemp = 'PHPTemp';
const cache_to_wincache = 'Wincache';
const cache_to_sqlite = 'SQLite';
const cache_to_sqlite3 = 'SQLite3';
/**
* Name of the method used for cell cacheing
*
* @var string
*/
private static $cacheStorageMethod = null;
/**
* Name of the class used for cell cacheing
*
* @var string
*/
private static $cacheStorageClass = null;
/**
* List of all possible cache storage methods
*
* @var string[]
*/
private static $storageMethods = array(
self::cache_in_memory,
self::cache_in_memory_gzip,
self::cache_in_memory_serialized,
self::cache_igbinary,
self::cache_to_phpTemp,
self::cache_to_discISAM,
self::cache_to_apc,
self::cache_to_memcache,
self::cache_to_wincache,
self::cache_to_sqlite,
self::cache_to_sqlite3,
);
/**
* Default arguments for each cache storage method
*
* @var array of mixed array
*/
private static $storageMethodDefaultParameters = array(
self::cache_in_memory => array(
),
self::cache_in_memory_gzip => array(
),
self::cache_in_memory_serialized => array(
),
self::cache_igbinary => array(
),
self::cache_to_phpTemp => array( 'memoryCacheSize' => '1MB'
),
self::cache_to_discISAM => array( 'dir' => null
),
self::cache_to_apc => array( 'cacheTime' => 600
),
self::cache_to_memcache => array( 'memcacheServer' => 'localhost',
'memcachePort' => 11211,
'cacheTime' => 600
),
self::cache_to_wincache => array( 'cacheTime' => 600
),
self::cache_to_sqlite => array(
),
self::cache_to_sqlite3 => array(
),
);
/**
* Arguments for the active cache storage method
*
* @var array of mixed array
*/
private static $storageMethodParameters = array();
/**
* Return the current cache storage method
*
* @return string|null
**/
public static function getCacheStorageMethod()
{
return self::$cacheStorageMethod;
}
/**
* Return the current cache storage class
*
* @return PHPExcel_CachedObjectStorage_ICache|null
**/
public static function getCacheStorageClass()
{
return self::$cacheStorageClass;
}
/**
* Return the list of all possible cache storage methods
*
* @return string[]
**/
public static function getAllCacheStorageMethods()
{
return self::$storageMethods;
}
/**
* Return the list of all available cache storage methods
*
* @return string[]
**/
public static function getCacheStorageMethods()
{
$activeMethods = array();
foreach (self::$storageMethods as $storageMethod) {
$cacheStorageClass = 'PHPExcel_CachedObjectStorage_' . $storageMethod;
if (call_user_func(array($cacheStorageClass, 'cacheMethodIsAvailable'))) {
$activeMethods[] = $storageMethod;
}
}
return $activeMethods;
}
/**
* Identify the cache storage method to use
*
* @param string $method Name of the method to use for cell cacheing
* @param array of mixed $arguments Additional arguments to pass to the cell caching class
* when instantiating
* @return boolean
**/
public static function initialize($method = self::cache_in_memory, $arguments = array())
{
if (!in_array($method, self::$storageMethods)) {
return false;
}
$cacheStorageClass = 'PHPExcel_CachedObjectStorage_'.$method;
if (!call_user_func(array( $cacheStorageClass,
'cacheMethodIsAvailable'))) {
return false;
}
self::$storageMethodParameters[$method] = self::$storageMethodDefaultParameters[$method];
foreach ($arguments as $k => $v) {
if (array_key_exists($k, self::$storageMethodParameters[$method])) {
self::$storageMethodParameters[$method][$k] = $v;
}
}
if (self::$cacheStorageMethod === null) {
self::$cacheStorageClass = 'PHPExcel_CachedObjectStorage_' . $method;
self::$cacheStorageMethod = $method;
}
return true;
}
/**
* Initialise the cache storage
*
* @param PHPExcel_Worksheet $parent Enable cell caching for this worksheet
* @return PHPExcel_CachedObjectStorage_ICache
**/
public static function getInstance(PHPExcel_Worksheet $parent)
{
$cacheMethodIsAvailable = true;
if (self::$cacheStorageMethod === null) {
$cacheMethodIsAvailable = self::initialize();
}
if ($cacheMethodIsAvailable) {
$instance = new self::$cacheStorageClass(
$parent,
self::$storageMethodParameters[self::$cacheStorageMethod]
);
if ($instance !== null) {
return $instance;
}
}
return false;
}
/**
* Clear the cache storage
*
**/
public static function finalize()
{
self::$cacheStorageMethod = null;
self::$cacheStorageClass = null;
self::$storageMethodParameters = array();
}
}
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!