Skip to content

Commit

Permalink
Refs matomo-org#5037 Refactor the factory out of the Period class in …
Browse files Browse the repository at this point in the history
…its own Period\Factory class
  • Loading branch information
mattab committed May 2, 2014
1 parent ff3bb73 commit 02e030e
Show file tree
Hide file tree
Showing 17 changed files with 176 additions and 127 deletions.
3 changes: 2 additions & 1 deletion core/Archive.php
Expand Up @@ -13,6 +13,7 @@
use Piwik\ArchiveProcessor\Rules;
use Piwik\DataAccess\ArchiveSelector;
use Piwik\Period\Range;
use Piwik\Period\Factory;

/**
* The **Archive** class is used to query cached analytics statistics
Expand Down Expand Up @@ -204,7 +205,7 @@ public static function build($idSites, $period, $strDate, $segment = false, $_re
$allPeriods = $oPeriod->getSubperiods();
} else {
$timezone = count($websiteIds) == 1 ? Site::getTimezoneFor($websiteIds[0]) : false;
$oPeriod = Period::makePeriodFromQueryParams($timezone, $period, $strDate);
$oPeriod = Factory::makePeriodFromQueryParams($timezone, $period, $strDate);
$allPeriods = array($oPeriod);
}
$segment = new Segment($segment, $websiteIds);
Expand Down
2 changes: 1 addition & 1 deletion core/DataTable.php
Expand Up @@ -139,7 +139,7 @@
*
* $dataTable = \Piwik\Plugins\Referrers\API::getInstance()->getSearchEngines($idSite = 1, $period = 'day', $date = '2007-07-24');
* $oldPeriod = $dataTable->metadata['period'];
* $dataTable->metadata['period'] = Period::factory('week', Date::factory('2013-10-18'));
* $dataTable->metadata['period'] = Period\Factory::build('week', Date::factory('2013-10-18'));
*
* **Serializing & unserializing**
*
Expand Down
2 changes: 1 addition & 1 deletion core/DataTable/Renderer/Csv.php
Expand Up @@ -341,7 +341,7 @@ protected function renderHeader()
} else if (strpos($date, ',') !== false) {
$period = new Range('range', $date);
} else {
$period = Period::factory($period, Date::factory($date));
$period = Period\Factory::build($period, Date::factory($date));
}

$prettyDate = $period->getLocalizedLongString();
Expand Down
94 changes: 5 additions & 89 deletions core/Period.php
Expand Up @@ -11,9 +11,9 @@
use Exception;
use Piwik\Period\Day;
use Piwik\Period\Month;
use Piwik\Period\Range;
use Piwik\Period\Week;
use Piwik\Period\Year;
use Piwik\Period\Range;

/**
* Date range representation.
Expand All @@ -26,16 +26,8 @@
* There are five types of periods in Piwik: day, week, month, year and range,
* where **range** is any date range. The reason the other periods exist instead
* of just **range** is that Piwik will pre-archive reports for days, weeks, months
* and years, while every other date range is archived on-demand.
*
* ### Examples
*
* **Building a period from 'date' and 'period' query parameters**
*
* $date = Common::getRequestVar('date', null, 'string');
* $period = Common::getRequestVar('period', null, 'string');
* $periodObject = Period::advancedFactory($period, $date);
*
* and years, while every custom date range is archived on-demand.
*
* @api
*/
abstract class Period
Expand Down Expand Up @@ -68,51 +60,6 @@ public function __construct(Date $date)
$this->date = clone $date;
}

/**
* Creates a new Period instance with a period ID and {@link Date} instance.
*
* _Note: This method cannot create {@link Period\Range} periods._
*
* @param string $strPeriod `"day"`, `"week"`, `"month"`, `"year"`, `"range"`.
* @param Date|string $date A date within the period or the range of dates.
* @throws Exception If `$strPeriod` is invalid.
* @return \Piwik\Period
*/
static public function factory($strPeriod, $date)
{
if (is_string($date)) {
if (Period::isMultiplePeriod($date, $strPeriod) || $strPeriod == 'range') {
return new Range($strPeriod, $date);
}

$date = Date::factory($date);
}

switch ($strPeriod) {
case 'day':
return new Day($date);
break;

case 'week':
return new Week($date);
break;

case 'month':
return new Month($date);
break;

case 'year':
return new Year($date);
break;

default:
$message = Piwik::translate(
'General_ExceptionInvalidPeriod', array($strPeriod, 'day, week, month, year, range'));
throw new Exception($message);
break;
}
}

/**
* Returns true if `$dateString` and `$period` represent multiple periods.
*
Expand All @@ -126,8 +73,8 @@ static public function factory($strPeriod, $date)
* etc.
*
* @static
* @param $dateString The **date** query parameter value.
* @param $period The **period** query parameter value.
* @param $dateString string The **date** query parameter value.
* @param $period string The **period** query parameter value.
* @return boolean
*/
public static function isMultiplePeriod($dateString, $period)
Expand All @@ -138,37 +85,6 @@ public static function isMultiplePeriod($dateString, $period)
&& $period != 'range';
}

/**
* Creates a Period instance using a period, date and timezone.
*
* @param string $timezone The timezone of the date. Only used if `$date` is `'now'`, `'today'`,
* `'yesterday'` or `'yesterdaySameTime'`.
* @param string $period The period string: `"day"`, `"week"`, `"month"`, `"year"`, `"range"`.
* @param string $date The date or date range string. Can be a special value including
* `'now'`, `'today'`, `'yesterday'`, `'yesterdaySameTime'`.
* @return \Piwik\Period
*/
public static function makePeriodFromQueryParams($timezone, $period, $date)
{
if (empty($timezone)) {
$timezone = 'UTC';
}

if ($period == 'range') {
$oPeriod = new Period\Range('range', $date, $timezone, Date::factory('today', $timezone));
} else {
if (!($date instanceof Date)) {
if ($date == 'now' || $date == 'today') {
$date = date('Y-m-d', Date::factory('now', $timezone)->getTimestamp());
} elseif ($date == 'yesterday' || $date == 'yesterdaySameTime') {
$date = date('Y-m-d', Date::factory('now', $timezone)->subDay(1)->getTimestamp());
}
$date = Date::factory($date);
}
$oPeriod = Period::factory($period, $date);
}
return $oPeriod;
}

/**
* Returns the first day of the period.
Expand Down
110 changes: 110 additions & 0 deletions core/Period/Factory.php
@@ -0,0 +1,110 @@
<?php
/**
* Piwik - Open source web analytics
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Period;

use Exception;
use Piwik\Date;
use Piwik\Period;
use Piwik\Piwik;

class Factory
{
/**
* Creates a new Period instance with a period ID and {@link Date} instance.
*
* _Note: This method cannot create {@link Period\Range} periods._
*
* @param string $period `"day"`, `"week"`, `"month"`, `"year"`, `"range"`.
* @param Date|string $date A date within the period or the range of dates.
* @throws Exception If `$strPeriod` is invalid.
* @return \Piwik\Period
*/
static public function build($period, $date)
{
if (is_string($date)) {
if (Period::isMultiplePeriod($date, $period) || $period == 'range') {
self::checkPeriodIsEnabled('range');
return new Range($period, $date);
}
$date = Date::factory($date);
}

self::checkPeriodIsEnabled($period);
switch ($period) {
case 'day':
return new Day($date);
break;

case 'week':
return new Week($date);
break;

case 'month':
return new Month($date);
break;

case 'year':
return new Year($date);
break;
}

self::throwExceptionInvalidPeriod($period);
}

private static function checkPeriodIsEnabled($period)
{
$enabledPeriodsInAPI = array();
if(!in_array($period, $enabledPeriodsInAPI)) {
self::throwExceptionInvalidPeriod($period);
}
}

/**
* @param $strPeriod
* @throws \Exception
*/
private static function throwExceptionInvalidPeriod($strPeriod)
{
$message = Piwik::translate('General_ExceptionInvalidPeriod', array($strPeriod, 'day, week, month, year, range'));
throw new Exception($message);
}


/**
* Creates a Period instance using a period, date and timezone.
*
* @param string $timezone The timezone of the date. Only used if `$date` is `'now'`, `'today'`,
* `'yesterday'` or `'yesterdaySameTime'`.
* @param string $period The period string: `"day"`, `"week"`, `"month"`, `"year"`, `"range"`.
* @param string $date The date or date range string. Can be a special value including
* `'now'`, `'today'`, `'yesterday'`, `'yesterdaySameTime'`.
* @return \Piwik\Period
*/
public static function makePeriodFromQueryParams($timezone, $period, $date)
{
if (empty($timezone)) {
$timezone = 'UTC';
}

if ($period == 'range') {
$oPeriod = new Period\Range('range', $date, $timezone, Date::factory('today', $timezone));
} else {
if (!($date instanceof Date)) {
if ($date == 'now' || $date == 'today') {
$date = date('Y-m-d', Date::factory('now', $timezone)->getTimestamp());
} elseif ($date == 'yesterday' || $date == 'yesterdaySameTime') {
$date = date('Y-m-d', Date::factory('now', $timezone)->subDay(1)->getTimestamp());
}
$date = Date::factory($date);
}
$oPeriod = Factory::build($period, $date);
}
return $oPeriod;
}
}
4 changes: 2 additions & 2 deletions core/Period/Range.php
Expand Up @@ -338,14 +338,14 @@ protected function processOptimalSubperiods($startDate, $endDate)
protected function fillArraySubPeriods($startDate, $endDate, $period)
{
$arrayPeriods = array();
$endSubperiod = Period::factory($period, $endDate);
$endSubperiod = Period\Factory::build($period, $endDate);
$arrayPeriods[] = $endSubperiod;

// set end date to start of end period since we're comparing against start date.
$endDate = $endSubperiod->getDateStart();
while ($endDate->isLater($startDate)) {
$endDate = $endDate->addPeriod(-1, $period);
$subPeriod = Period::factory($period, $endDate);
$subPeriod = Period\Factory::build($period, $endDate);
$arrayPeriods[] = $subPeriod;
}
$arrayPeriods = array_reverse($arrayPeriods);
Expand Down
58 changes: 40 additions & 18 deletions core/Plugin/Controller.php
Expand Up @@ -189,6 +189,40 @@ protected static function getEnabledPeriodsInUI()
return $periods;
}

/**
* @return array
*/
private static function getEnabledPeriodsNames()
{
$availablePeriods = self::getEnabledPeriodsInUI();
$periodNames = array(
'day' => array(
'singular' => Piwik::translate('CoreHome_PeriodDay'),
'plural' => Piwik::translate('CoreHome_PeriodDays')
),
'week' => array(
'singular' => Piwik::translate('CoreHome_PeriodWeek'),
'plural' => Piwik::translate('CoreHome_PeriodWeeks')
),
'month' => array(
'singular' => Piwik::translate('CoreHome_PeriodMonth'),
'plural' => Piwik::translate('CoreHome_PeriodMonths')
),
'year' => array(
'singular' => Piwik::translate('CoreHome_PeriodYear'),
'plural' => Piwik::translate('CoreHome_PeriodYears')
),
// Note: plural is not used for date range
'range' => array(
'singular' => Piwik::translate('General_DateRangeInPeriodList'),
'plural' => Piwik::translate('General_DateRangeInPeriodList')
),
);

$periodNames = array_intersect_key($periodNames, array_fill_keys($availablePeriods, true));
return $periodNames;
}

/**
* Returns the name of the default method that will be called
* when visiting: index.php?module=PluginName without the action parameter.
Expand Down Expand Up @@ -491,7 +525,7 @@ protected function setGeneralVariablesView($view)
$periodStr = Common::getRequestVar('period');
if ($periodStr != 'range') {
$date = Date::factory($this->strDate);
$period = Period::factory($periodStr, $date);
$period = Period\Factory::build($periodStr, $date);
} else {
$period = new Range($periodStr, $rawDate, $this->site->getTimezone());
}
Expand Down Expand Up @@ -693,26 +727,14 @@ public static function setPeriodVariablesView($view)
$view->displayUniqueVisitors = SettingsPiwik::isUniqueVisitorsEnabled($currentPeriod);
$availablePeriods = self::getEnabledPeriodsInUI();
if (!in_array($currentPeriod, $availablePeriods)) {
throw new Exception("Period must be one of: " . implode(",", $availablePeriods));
throw new Exception("Period must be one of: " . implode(", ", $availablePeriods));
}
$periodNames = array(
'day' => array('singular' => Piwik::translate('CoreHome_PeriodDay'), 'plural' => Piwik::translate('CoreHome_PeriodDays')),
'week' => array('singular' => Piwik::translate('CoreHome_PeriodWeek'), 'plural' => Piwik::translate('CoreHome_PeriodWeeks')),
'month' => array('singular' => Piwik::translate('CoreHome_PeriodMonth'), 'plural' => Piwik::translate('CoreHome_PeriodMonths')),
'year' => array('singular' => Piwik::translate('CoreHome_PeriodYear'), 'plural' => Piwik::translate('CoreHome_PeriodYears')),
// Note: plural is not used for date range
'range' => array('singular' => Piwik::translate('General_DateRangeInPeriodList'), 'plural' => Piwik::translate('General_DateRangeInPeriodList')),
);

$periodNames = array_intersect_key($periodNames, array_fill_keys($availablePeriods, true));

$found = array_search($currentPeriod, $availablePeriods);
if ($found !== false) {
unset($availablePeriods[$found]);
}
unset($availablePeriods[$found]);

$view->period = $currentPeriod;
$view->otherPeriods = $availablePeriods;
$view->periodsNames = $periodNames;
$view->periodsNames = self::getEnabledPeriodsNames();
}

/**
Expand Down Expand Up @@ -895,7 +917,7 @@ public static function getCalendarPrettyDate($period)
*/
public static function getPrettyDate($date, $period)
{
return self::getCalendarPrettyDate(Period::factory($period, Date::factory($date)));
return self::getCalendarPrettyDate(Period\Factory::build($period, Date::factory($date)));
}

/**
Expand Down
2 changes: 1 addition & 1 deletion plugins/API/ProcessedReport.php
Expand Up @@ -423,7 +423,7 @@ public function getProcessedReport($idSite, $period, $date, $apiModule, $apiActi
}
$website = new Site($idSite);

$period = Period::factory($period, $date);
$period = Period\Factory::build($period, $date);
$period = $period->getLocalizedLongString();

$return = array(
Expand Down

0 comments on commit 02e030e

Please sign in to comment.