some code cleanup & refactoring

closed some TODOs
This commit is contained in:
Steffen Vogel 2010-07-20 22:43:08 +02:00
parent d167436ca7
commit 7c4288f92a
26 changed files with 125 additions and 94 deletions

View file

@ -2,6 +2,7 @@
// TODO replace by state class
const BACKEND_DIR = '/home/steffen/workspace/volkszaehler.org/backend';
const DEV_ENV = TRUE;
// class autoloading
require BACKEND_DIR . '/lib/Util/ClassLoader.php';
@ -28,7 +29,7 @@ $em = Volkszaehler\Dispatcher::createEntityManager();
$helperSet = new \Symfony\Components\Console\Helper\HelperSet(array('em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em)));
$cli = new \Symfony\Components\Console\Application('Doctrine Command Line Interface', Doctrine\ORM\Version::VERSION);
$cli->setCatchExceptions(true);
$cli->setCatchExceptions(TRUE);
$cli->setHelperSet($helperSet);
$cli->addCommands(array(
// DBAL Commands

View file

@ -27,7 +27,7 @@ use Volkszaehler\Controller;
// TODO replace by state class
const VERSION = 1.1;
const BACKEND_DIR = '/home/steffen/workspace/volkszaehler.org/backend'; // TODO realpath(__DIR__)
const DEV_ENV = true;
const DEV_ENV = TRUE;
// class autoloading
require BACKEND_DIR . '/lib/Util/ClassLoader.php';

View file

@ -74,7 +74,7 @@ class Channel extends Controller {
$this->em->flush();
}
// TODO implement ChannelController::edit();
// TODO implement Controller\Channel::edit();
// TODO authentification/indentification
public function edit() {

View file

@ -21,12 +21,14 @@
namespace Volkszaehler\Controller;
// TODO call as subcontroller from Controller\Channel::get()?
// TODO call via redirect from Controller\Channel
use Volkszaehler\Util;
class Data extends Controller {
// TODO authentification/indentification
public function get() {
// TODO why not ucids?
// TODO use uuids for groups or channels
$ids = explode(',', trim($this->view->request->getParameter('ids')));
$q = $this->em->createQuery('SELECT c FROM Volkszaehler\Model\Channel c WHERE c.id IN (' . implode(', ', $ids) . ')');
@ -49,7 +51,7 @@ class Data extends Controller {
$value = (float) $this->view->request->getParameter('value');
$ts = (int) $this->view->request->getParameter('timestamp');
if ($ts == 0) {
$ts = microtime(true) * 1000;
$ts = microtime(TRUE) * 1000;
}
$data = new \Volkszaehler\Model\Data($channel, $value, $ts);
@ -61,9 +63,10 @@ class Data extends Controller {
}
/*
* prune all data from database
* prune data from database
*/
public function delete() { // TODO add user authentification
// TODO authentification/indentification
public function delete() {
$dql = 'DELETE FROM \Volkszaehler\Model\Data WHERE channel_id = ' . $this->id;
if ($this->view->request->getParameter('from')) {

View file

@ -43,7 +43,7 @@ class Group extends Controller {
$this->view->add($group);
}
// TODO check for valid user identity
// TODO authentification/indentification
public function delete() {
$group = Group::getByUuid($this->view->request->getParameter('ugid'));
@ -52,7 +52,7 @@ class Group extends Controller {
}
public function edit() {
// TODO implement GroupController::edit();
// TODO implement Controller\Group::edit();
}
}

View file

@ -28,7 +28,7 @@ use Volkszaehler\Util;
/*
* frontcontroller / dispatcher
*/
final class Dispatcher {
class Dispatcher {
// MVC
protected $em; // Model (Doctrine EntityManager)
protected $view; // View
@ -115,7 +115,7 @@ final class Dispatcher {
$config->setProxyDir(BACKEND_DIR . '/lib/Model/Proxies');
$config->setProxyNamespace('Volkszaehler\Model\Proxies');
$config->setAutoGenerateProxyClasses(DEV_ENV == true);
$config->setAutoGenerateProxyClasses(DEV_ENV == TRUE);
return \Doctrine\ORM\EntityManager::create(Util\Configuration::read('db'), $config);
}

View file

@ -74,7 +74,7 @@ abstract class Interpreter implements InterpreterInterface {
default:
if (is_numeric($groupBy)) { // lets agrregate it with php
$groupBy = (int) $groupBy;
$sqlGroupBy = false;
$sqlGroupBy = FALSE;
}
else {
throw new \InvalidArgumentException('\'' . $groupBy . '\' is not an unknown grouping mode');
@ -82,18 +82,18 @@ abstract class Interpreter implements InterpreterInterface {
}
$sql = 'SELECT';
$sql .= ($sqlGroupBy === false) ? ' timestamp, value' : ' MAX(timestamp) AS timestamp, SUM(value) AS value, COUNT(timestamp) AS count';
$sql .= ($sqlGroupBy === FALSE) ? ' timestamp, value' : ' MAX(timestamp) AS timestamp, SUM(value) AS value, COUNT(timestamp) AS count';
$sql .= ' FROM data WHERE channel_id = ' . (int) $this->channel->getId();
if (!is_null($from)) {
if (isset($from)) {
$sql .= ' && timestamp > ' . $from;
}
if (!is_null($to)) {
if (isset($to)) {
$sql .= ' && timestamp < ' . $to;
}
if ($sqlGroupBy !== false) {
if ($sqlGroupBy !== FALSE) {
$sql .= ' GROUP BY ' . $sqlGroupBy;
}
@ -125,7 +125,7 @@ abstract class Interpreter implements InterpreterInterface {
for ($i = 1; $i <= $packageCount; $i++) {
$package = array('timestamp' => (int) $reading['timestamp'], // last timestamp in package
'value' => (float) $reading['value'], // sum of values
'count' => ($sqlGroupBy === false) ? 1 : $reading['count']); // total count of values or pulses in the package
'count' => ($sqlGroupBy === FALSE) ? 1 : $reading['count']); // total count of values or pulses in the package
while ($package['count'] < $packageSize) {
$reading = next($result);

View file

@ -60,7 +60,8 @@ class Meter extends Interpreter {
return $min;
}
public function getAverage($from = NULL, $to = NULL) { // TODO calculate timeinterval if no params were given
// TODO calculate timeinterval if no params were given
public function getAverage($from = NULL, $to = NULL) {
return $this->getConsumption($from, $to) / ($to - $from) / 1000; // return W
}

View file

@ -42,13 +42,13 @@ class Channel extends Entity {
/**
* @OneToMany(targetEntity="Data", mappedBy="channel"), cascade={"remove"}
*/
private $data = NULL;
protected $data = NULL;
/** @Column(type="integer") */
private $resolution;
protected $resolution;
/** @Column(type="decimal", precision="5", scale="2") */
private $cost;
protected $cost;
/*
* indicator => interpreter, unit mapping
@ -78,7 +78,7 @@ class Channel extends Entity {
/*
* add a new data to the database
* @todo move to logger?
* @todo move to Logger\Logger?
*/
public function addData(\Volkszaehler\Model\Data $data) {
$this->data->add($data);

View file

@ -34,20 +34,20 @@ class Data {
* @Id
* @Column(type="bigint")
*/
private $timestamp;
protected $timestamp;
/**
* @Column(type="decimal", precision="10", scale="5")
* @todo change to float after DCC-67 has been closed
*/
private $value;
protected $value;
/**
* @Id
* @ManyToOne(targetEntity="Channel", inversedBy="data")
* @JoinColumn(name="channel_id", referencedColumnName="id")
*/
private $channel;
protected $channel;
public function __construct(Channel\Channel $channel, $value, $timestamp) {
$this->channel = $channel;

View file

@ -31,10 +31,10 @@ use Doctrine\Common\Collections\ArrayCollection;
*/
class Group extends Entity {
/** @Column(type="string") */
private $name;
protected $name;
/** @Column(type="string") */
private $description;
protected $description;
/**
* @ManyToMany(targetEntity="Channel")
@ -43,7 +43,7 @@ class Group extends Entity {
* inverseJoinColumns={@JoinColumn(name="channel_id", referencedColumnName="id")}
* )
*/
private $channels = NULL;
protected $channels = NULL;
/**
* @ManyToMany(targetEntity="Group")
@ -52,7 +52,7 @@ class Group extends Entity {
* inverseJoinColumns={@JoinColumn(name="child_id", referencedColumnName="id")}
* )
*/
private $children = NULL;
protected $children = NULL;
/*
* construct

View file

@ -24,10 +24,10 @@
namespace Volkszaehler\Util;
class ClassLoader {
private $fileExtension = '.php';
private $namespace;
private $includePath;
private $namespaceSeparator = '\\';
protected $fileExtension = '.php';
protected $namespace;
protected $includePath;
protected $namespaceSeparator = '\\';
/**
* Creates a new <tt>ClassLoader</tt> that loads classes of the
@ -40,7 +40,7 @@ class ClassLoader {
* @param string $ns The namespace of the classes to load.
* @param string $includePath The base include path to use.
*/
public function __construct($ns = null, $includePath = null) {
public function __construct($ns = NULL, $includePath = NULL) {
$this->namespace = $ns;
$this->includePath = $includePath;
}
@ -102,16 +102,16 @@ class ClassLoader {
* @return boolean TRUE if the class has been successfully loaded, FALSE otherwise.
*/
public function loadClass($className) {
if ($this->namespace !== null && strpos($className, $this->namespace . $this->namespaceSeparator) !== 0) {
return false;
if ($this->namespace !== NULL && strpos($className, $this->namespace . $this->namespaceSeparator) !== 0) {
return FALSE;
}
$subNamespace = substr($className, strlen($this->namespace));
$parts = explode($this->namespaceSeparator, $subNamespace);
$path = implode(DIRECTORY_SEPARATOR, $parts);
require_once ($this->includePath !== null ? $this->includePath : '') . $path . $this->fileExtension;
return true;
require_once ($this->includePath !== NULL ? $this->includePath : '') . $path . $this->fileExtension;
return TRUE;
}
/**
@ -122,15 +122,15 @@ class ClassLoader {
* @return boolean TRUE if this ClassLoader can load the class, FALSE otherwise.
*/
public function canLoadClass($className) {
if ($this->namespace !== null && strpos($className, $this->namespace . $this->namespaceSeparator) !== 0) {
return false; // TODO handle with exceptions
if ($this->namespace !== NULL && strpos($className, $this->namespace . $this->namespaceSeparator) !== 0) {
return FALSE; // TODO handle with exceptions
}
$subNamespace = substr($className, strlen($this->namespace));
$parts = explode($this->namespaceSeparator, $subNamespace);
$path = implode(DIRECTORY_SEPARATOR, $parts);
return file_exists(($this->includePath !== null ? $this->includePath . DIRECTORY_SEPARATOR : '') . $path . $this->fileExtension);
return file_exists(($this->includePath !== NULL ? $this->includePath . DIRECTORY_SEPARATOR : '') . $path . $this->fileExtension);
}
/**
@ -155,8 +155,8 @@ class ClassLoader {
* @return boolean TRUE if the class exists as per the definition given above, FALSE otherwise.
*/
public static function classExists($className) {
if (class_exists($className, false)) {
return true;
if (class_exists($className, FALSE)) {
return TRUE;
}
foreach (spl_autoload_functions() as $loader) {
@ -164,24 +164,24 @@ class ClassLoader {
if (is_object($loader[0])) {
if ($loader[0] instanceof ClassLoader) { // array($obj, 'methodName')
if ($loader[0]->canLoadClass($className)) {
return true;
return TRUE;
}
} else if ($loader[0]->{$loader[1]}($className)) {
return true;
return TRUE;
}
} else if ($loader[0]::$loader[1]($className)) { // array('ClassName', 'methodName')
return true;
return TRUE;
}
} else if ($loader instanceof \Closure) { // function($className) {..}
if ($loader($className)) {
return true;
return TRUE;
}
} else if (is_string($loader) && $loader($className)) { // "MyClass::loadClass"
return true;
return TRUE;
}
}
return false;
return FALSE;
}
/**
@ -199,6 +199,6 @@ class ClassLoader {
}
}
return null;
return NULL;
}
}

View file

@ -32,7 +32,7 @@ class Configuration {
$values =& self::$values;
$tree = explode('.', $var);
foreach ($tree as $part) {
$values =& $values[$part]; // TODO array_merge_recursive()
$values =& $values[$part]; // TODO use array_merge_recursive()
}
$values = $value;
@ -81,7 +81,7 @@ class Configuration {
$delcaration = '';
foreach (self::$values as $key => $value) {
$export = var_export($value, true);
$export = var_export($value, TRUE);
$export = preg_replace('/=>\s+array/', '=> array', $export);
$export = str_replace(" ", "\t", $export);

View file

@ -37,19 +37,19 @@ class Debug implements Logging\SQLLogger {
*/
public function __construct($level) {
// taking timestamp to stop execution time
$this->created = microtime(true);
$this->created = microtime(TRUE);
$this->level = $level;
if (!is_null(self::$instance)) {
if (isset(self::$instance)) {
throw new \Exception('debugging has already been started. please use the static functions!');
}
self::$instance = $this;
// assert options
assert_options(ASSERT_ACTIVE, true);
assert_options(ASSERT_BAIL, false);
assert_options(ASSERT_WARNING, false);
assert_options(ASSERT_ACTIVE, TRUE);
assert_options(ASSERT_BAIL, FALSE);
assert_options(ASSERT_WARNING, FALSE);
assert_options(ASSERT_CALLBACK, array($this, 'assertHandler'));
@ -58,12 +58,18 @@ class Debug implements Logging\SQLLogger {
/*
* interface for doctrine's dbal sql logger
*/
function logSQL($sql, array $params = null) {
$this->queries[] = array('sql' => $sql, 'parameter' => $params);
function logSQL($sql, array $parameter = NULL) {
$query['sql'] = $sql;
if (isset($parameter) && !empty($parameter)) {
$query['parameters'] = $parameter;
}
$this->queries[] = $query;
}
static public function log($message) {
if (!is_null(self::$instance)) {
if (isset(self::$instance)) {
$trace = debug_backtrace();
self::$instance->messages[] = array(
@ -99,9 +105,9 @@ class Debug implements Logging\SQLLogger {
);
}
public static function isActivated() { return !is_null(self::$instance); }
public static function isActivated() { return isset(self::$instance); }
public function getExecutionTime() { return round((microtime(true) - $this->created), 5); }
public function getExecutionTime() { return round((microtime(TRUE) - $this->created), 5); }
public function getQueries() { return $this->queries; }
public function getMessages() { return $this->messages; }
}

View file

@ -92,7 +92,7 @@ class Uuid {
public static function compare($a, $b) {
/* Compares the binary representations of two UUIDs.
The comparison will return true if they are bit-exact,
The comparison will return TRUE if they are bit-exact,
or if neither is valid. */
if (self::makeBin($a, 16)==self::makeBin($b, 16))
return TRUE;
@ -239,7 +239,7 @@ class Uuid {
protected static function makeBin($str, $len) {
/* Insure that an input string is either binary or hexadecimal.
Returns binary representation, or false on failure. */
Returns binary representation, or FALSE on failure. */
if ($str instanceof self)
return $str->bytes;
if (strlen($str)==$len)

View file

@ -27,6 +27,9 @@ abstract class Csv extends \Volkszaehler\View\View {
protected $csv = array();
protected $header = array();
protected $footer = array();
protected $delimiter = ';';
protected $enclosure = '"';
/*
* constructor
@ -37,8 +40,8 @@ abstract class Csv extends \Volkszaehler\View\View {
$this->header[] = 'source: volkszaehler.org';
$this->header[] = 'version: ' . \Volkszaehler\VERSION;
$this->response->setHeader('Content-type', 'text/plain');
//$this->response->setHeader('Content-Disposition', 'attachment; filename="data.csv"');
$this->response->setHeader('Content-type', 'text/csv');
$this->response->setHeader('Content-Disposition', 'attachment; filename="data.csv"');
}
public function render() {
@ -49,7 +52,9 @@ abstract class Csv extends \Volkszaehler\View\View {
echo PHP_EOL;
foreach ($this->csv as $array) {
echo implode(";", $array) . PHP_EOL;
$array = array_map(array($this, 'escape'), $array);
echo implode($this->delimiter, $array) . PHP_EOL;
}
echo PHP_EOL;
@ -61,11 +66,27 @@ abstract class Csv extends \Volkszaehler\View\View {
parent::render();
}
public function addDebug() {
$this->footer[] = 'time: ' . $this->getTime();
protected function escape($value) {
if (is_string($value)) {
return $this->enclosure . $value . $this->enclosure;
}
elseif (is_numeric($value)) {
return $value;
}
else {
return (string) $value;
}
}
public function addDebug(Util\Debug $debug) {
$this->footer[] = 'time: ' . $debug->getExecutionTime();
$this->footer[] = 'database: ' . Util\Configuration::read('db.driver');
foreach (\Volkszaehler\Util\Debug::getSQLLogger()->queries as $query) {
foreach ($debug->getMessages() as $message) {
$this->footer[] = 'message: ' . $message['message']; // TODO add more information
}
foreach ($debug->getQueries() as $query) {
$this->footer[] = 'query: ' . $query['sql'];
$this->footer[] = ' parameters: ' . implode(', ', $query['parameters']);
}

View file

@ -103,7 +103,7 @@ class Response {
public function getCode() { return $this->code; }
public function setCode($code) { $this->code = $code; }
static public function getCodeDescription($code) {
return (isset(self::$codes[$code])) ? self::$codes[$code] : false;
return (isset(self::$codes[$code])) ? self::$codes[$code] : FALSE;
}
}

View file

@ -29,7 +29,6 @@ require_once \Volkszaehler\BACKEND_DIR . '/lib/vendor/JpGraph/jpgraph_date.php';
* JpGraph plotting
*
* @todo add caching
* @todo unifiy axes of same unit
*/
class JpGraph extends View {
/*
@ -60,7 +59,7 @@ class JpGraph extends View {
$this->graph->SetScale('datlin');
$this->graph->legend->SetPos(0.1,0.02, 'left', 'top');
$this->graph->legend->SetShadow(false);
$this->graph->legend->SetShadow(FALSE);
$this->graph->SetMarginColor('white');
$this->graph->SetYDeltaDist(65);
@ -75,7 +74,7 @@ class JpGraph extends View {
//$this->graph->img->SetAntiAliasing();
}
public function add(\Volkszaehler\Model\Channel $obj, $data = NULL) {
public function add(\Volkszaehler\Model\Channel $obj, array $data) {
$count = count($this->channels);
$xData = $yData = array();
foreach ($data as $reading) {
@ -87,7 +86,7 @@ class JpGraph extends View {
$plot = new \ScatterPlot($yData, $xData);
$plot->setLegend($obj->getName() . ': ' . $obj->getDescription() . ' [' . $obj->getUnit() . ']');
$plot->SetLinkPoints(true, self::$colors[$count]);
$plot->SetLinkPoints(TRUE, self::$colors[$count]);
$plot->mark->SetColor(self::$colors[$count]);
$plot->mark->SetFillColor(self::$colors[$count]);

View file

@ -23,8 +23,7 @@ namespace Volkszaehler\View\Json;
class Channel extends Json {
public function add(\Volkszaehler\Model\Channel $obj, $data = NULL) {
$channel['id'] = (int) $obj->getId();
public function add(\Volkszaehler\Model\Channel $obj, array $data = NULL) {
$channel['uuid'] = (string) $obj->getUuid();
$channel['indicator'] = $obj->getIndicator();
$channel['unit'] = $obj->getUnit();
@ -37,7 +36,7 @@ class Channel extends Json {
$channel['cost'] = (float) $obj->getCost();
}
if (!is_null($data) && is_array($data)) {
if (isset($data)) {
$channel['data'] = array();
foreach ($data as $reading) {
$channel['data'][] = array($reading['timestamp'], $reading['value'], $reading['count']);

View file

@ -23,13 +23,12 @@ namespace Volkszaehler\View\Json;
class Group extends Json {
public function add(\Volkszaehler\Model\Group $obj, $recursive = false) {
$group['id'] = (int) $obj->getId();
public function add(\Volkszaehler\Model\Group $obj, $recursive = FALSE) {
$group['uuid'] = (string) $obj->getUuid();
$group['name'] = $obj->getName();
$group['description'] = $obj->getDescription();
if ($recursive) { // TODO add really nested sub groups
if ($recursive) { // TODO add nested groups in json view
$children = $obj->getChildren();
foreach ($children as $child) {

View file

@ -53,7 +53,7 @@ abstract class Json extends \Volkszaehler\View\View {
protected static function format($json) {
$formatted = '';
$indentLevel = 0;
$inString = false;
$inString = FALSE;
$len = strlen($json);
for($c = 0; $c < $len; $c++) {

View file

@ -29,7 +29,7 @@ class Channel extends Xml {
$this->xml = $this->xmlDoc->createElement('channels');
}
public function add(\Volkszaehler\Model\Channel $obj, $data = NULL) {
public function add(\Volkszaehler\Model\Channel $obj, array $data = NULL) {
$xmlChannel = $this->xmlDoc->createElement('channel');
$xmlChannel->setAttribute('uuid', $obj->getUuid());
@ -40,7 +40,7 @@ class Channel extends Xml {
$xmlChannel->appendChild($this->xmlDoc->createElement('resolution', (int) $obj->getResolution()));
$xmlChannel->appendChild($this->xmlDoc->createElement('cost', (float) $obj->getCost()));
if (!is_null($data) && is_array($data)) {
if (isset($data)) {
$xmlData = $this->xmlDoc->createElement('data');
foreach ($data as $reading) {

View file

@ -32,9 +32,9 @@ class Group extends Xml {
public function add(\Volkszaehler\Model\Group $obj) {
$xmlGroup = $this->xmlDoc->createElement('group');
$xmlGroup->setAttribute('id', (int) $obj->id);
$xmlGroup->appendChild($this->xmlDoc->createElement('uuid', $obj->uuid));
$xmlGroup->appendChild($this->xmlDoc->createElement('description', $obj->description));
$xmlGroup->setAttribute('uuid', $obj->getUuid());
$xmlGroup->appendChild($this->xmlDoc->createElement('name', $obj->getName()));
$xmlGroup->appendChild($this->xmlDoc->createElement('description', $obj->getDescription()));
// TODO include sub groups?

View file

@ -21,7 +21,6 @@
namespace Volkszaehler\View\Xml;
// TODO outdated
use Volkszaehler\Util;
abstract class Xml extends \Volkszaehler\View\View {
@ -58,13 +57,14 @@ abstract class Xml extends \Volkszaehler\View\View {
$this->xmlRoot->appendChild($xmlException);
}
public function addDebug() {
public function addDebug(Util\Debug $debug) {
$xmlDebug = $this->xmlDoc->createElement('debug');
$xmlDebug->appendChild($this->xmlDoc->createElement('time', $this->getTime()));
$xmlDebug->appendChild($this->xmlDoc->createElement('time', $debug->getExecutionTime()));
$xmlDebug->appendChild($this->xmlDoc->createElement('database', Util\Configuration::read('db.driver')));
// TODO add queries
// TODO add queries to xml debug
// TODO add messages to xml output
$this->xmlRoot->appendChild($xmlDebug);
}
@ -83,7 +83,7 @@ abstract class Xml extends \Volkszaehler\View\View {
$xmlArgs = $this->xmlDoc->createElement($key);
$xmlTrace->appendChild($xmlArgs);
foreach ($value as $arg) {
$xmlArgs->appendChild($this->xmlDoc->createElement('arg', print_r($value, true))); // TODO check $value content
$xmlArgs->appendChild($this->xmlDoc->createElement('arg', (is_scalar($value)) ? $value : print_r($value, TRUE)));
}
break;

View file

@ -25,6 +25,6 @@ $config['db']['user'] = 'volkszaehler';
$config['db']['password'] = '';
$config['db']['dbname'] = 'volkszaehler';
$config['debug'] = false;
$config['debug'] = FALSE;
?>

View file

@ -31,6 +31,8 @@
<?php
// TODO complete installer
switch (@$_GET['step']) {
case '1':
echo 'bla';