public function computeDelta()
 {
     // get metric from yesterday
     $yesterdaysDate = date('Y-m-d', strtotime('yesterday'));
     $stat = Statistic::findOne(['where' => ['metric' => $this->key(), 'day' => $yesterdaysDate]]);
     $previous = $stat ? $stat->val : 0;
     return $this->computeValue() - $previous;
 }
 /**
  * Saves the Nth previous period. Creates the statistic entry
  * if it does not exist, otherwise overwrites the previous value.
  *
  * @param int $n nth previous period to save
  *
  * @return bool
  */
 public function savePeriod($n = 1)
 {
     if (!$this->shouldBeCaptured() || $n < 1) {
         return false;
     }
     // compute the period in question
     $period = $this->nthPreviousPeriod($n);
     // compute the value for that time period
     $value = $this->computeValue($period);
     // generate the start date for the period
     $d = date('Y-m-d', $period['start']);
     // save the value
     $stat = new Statistic([$this->key(), $d]);
     if (!$stat->exists()) {
         $stat = new Statistic();
         return $stat->create(['metric' => $this->key(), 'day' => $d, 'val' => $value]);
     } else {
         return $stat->set('val', $value);
     }
 }