<?php
namespace com\foo;
use \Exception;
/**
* A class for handling tabular data
*
* @package com.foo
* @author Tomas Sandven
**/
class Tabular_Data
{
// Constants
const SUPPORTED_FILE_TYPES = 'csv,xls,xlsx';
// Fields
private $data = false;
private $initiated = false;
/**
* Constructor for Tabular_Data class. Use factory functions.
*
* @author Tomas Sandven
**/
public function __construct() {}
/**
* Creates a new Tabular_Data object and attempts to load data from the
* input file. Throws exceptions upon errors. Error codes:
* - 1001: Input file does not exist
* - 1002: No read access of input file
* - 1003: Input file type is not supported
* - 1004: Error reading file content, could be corrupt file or a code bug
*
* Supported file types:
* - *.csv
* - *.xls
* - *.xlsx
*
* @param $filepath: The path of the tabular data file
* @param $columns: An array of the column names to include. This can be
* omitted to load all columns.
*
* @return Tabular_Data
* @author Tomas Sandven
**/
public function loadFromFile($filepath)
{
// Prepare locals necessary for validation
$filename = @end(explode('/', $filepath));
$extension = @end(explode('.', $filename));
$exts = explode(',', self::SUPPORTED_FILE_TYPES);
// Don't let this class be initiated twice
if($this->initiated) throw new Exception(
'Already initiated! Only use factory functions!', 1);
// Check if the file exists
if(!is_file($filepath)) throw new Exception(
'Input file does not exist', 1001);
// File must be readable
if(!is_readable($filepath)) throw new Exception(
'Lacking permission to read the input file', 1002);
// File type must be supported
if(!in_array($extension, $exts))
throw new Exception('File type not supported', 1003);
// TODO
}
/**
* Loads tabular data using the PHPExcel library.
*
* @param $filepath: The path of the tabular data file
* @param $columns: An array of the column names to include. This can be
* omitted to load all columns.
*
* @return array
* @author Tomas Sandven
**/
public function _loadExcelData($filepath, $columns = false)
{
}
// #############################
// ##### FACTORY FUNCTIONS #####
// #############################
/**
* Shortcut for running creating a Tabular_Data instance from a file
*
* @author Tomas Sandven
**/
public static function fromFile($filepath, $columns = false)
{
$td = new Tabular_Data;
$td->loadFromFile($filepath, $columns);
return $td;
}
}
// Debug
if(!defined('BITO'))
{
$td = Tabular_Data::fromFile('/home/codemonkey/foo/bison.xlsx');
}