@param $period

@return array
@throws Exception
544859
protected function parsePeriodFromName($period)
    {
        $min = null;
        $max = null;

        $date = new DateTime('today', $this->getTimezoneFrom());

        switch ($period) {
            case 'today' :
                $max = clone $date;
                $min = clone $date;
                break;

            case 'yesterday' :
                $max = clone $date->modify('-1 day');
                $min = clone $date;
                break;

            case 'tomorrow' :
                $max = clone $date->modify('+1 day');
                $min = clone $date;
                break;

            case 'thisMonth' :
                $max = clone $date->modify('last day of this month');
                $min = clone $date->modify('first day of this month');
                break;

            case 'thisMonthToDate' :
                $max = clone $date;
                $min = clone $date->modify('first day of this month');
                break;

            case 'thisWeek' :
                $max = clone $date->modify('sunday this week');
                $min = clone $date->modify("monday this week");
                break;

            case 'thisWeekToDate' :
                $max = clone $date;
                $min = clone $date->modify("monday this week");
                break;

            case 'thisYear' :
                $max = clone $date->modify('last day of december this year');
                $min = clone $date->modify('first day of january this year');
                break;

            case 'thisYearToDate' :
                $max = clone $date;
                $min = clone $date->modify('first day of january this year');
                break;

            case 'lastMonth' :
                $max = clone $date->modify('last day of last month');
                $min = clone $date->modify('first day of this month');
                break;

            case 'lastWeek' :
                $max = clone $date->modify('sunday last week');
                $min = clone $date->modify("monday this week");
                break;

            case 'lastYear' :
                $max = clone $date->modify('last day of december last year');
                $min = clone $date->modify('first day of january this year');
                break;

            case 'total' :
                break;

            case 'untilToday' :
                $max = clone $date;
                break;

            default :
                if (preg_match('/^last(\d+)(?:Days)?$/u', $period, $found)) {
                    $days = $found[1];
                    $max  = clone $date;
                    $min  = clone $date->modify("-{$days} day");
                } elseif (preg_match('/^(?:before|-)(\d+)(?:Days)?$/u', $period, $found)) {
                    $days = $found[1];
                    $min  = clone $date->modify("-{$days} day");
                    $max  = clone $date;
                } else {
                    throw new Exception("Period {$period} not supported");
                }
        }

        $result = [
            'min' => $min,
            'max' => $max,
        ];

        return $result;
    }
309418
public function getExceptionArray($exception)
    {
        $_message = 'Uknonwn exception object, not instance of \Exception.';
        $_file = 'unknown';
        $_line = 0;
        $_trace = [];
        $_previousException = [];
        
        if (is_object($exception)) {
            $prev = $exception->getPrevious();
            
            if (!empty($prev)) {
                $_previousException = [
                    'message' => $prev->getMessage(),
                    'file' => $prev->getFile(),
                    'line' => $prev->getLine(),
                    'trace' => $this->buildTrace($prev),
                ];
            }
            
            $_trace = $this->buildTrace($exception);
            $_message = $exception->getMessage();
            $_file = $exception->getFile();
            $_line = $exception->getLine();
        } elseif (is_string($exception)) {
            $_message = 'exception string: ' . $exception;
        } elseif (is_array($exception)) {
            $_message = isset($exception['message']) ? $exception['message'] : 'exception array dump: ' . print_r($exception, true);
            $_file = isset($exception['file']) ? $exception['file'] : __FILE__;
            $_line = isset($exception['line']) ? $exception['line'] : __LINE__;
        }

        return [
            'message' => $_message,
            'file' => $_file,
            'line' => $_line,
            'requestUri' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : null,
            'serverName' => isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null,
            'date' => date('d.m.Y H:i'),
            'trace' => $_trace,
            'previousException' => $_previousException,
            'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null,
            'get' => isset($_GET) ? ArrayHelper::coverSensitiveValues($_GET, $this->sensitiveKeys) : [],
            'post' => isset($_POST) ? ArrayHelper::coverSensitiveValues($_POST, $this->sensitiveKeys) : [],
            'bodyParams' => Yii::$app instanceof Application ? ArrayHelper::coverSensitiveValues(Yii::$app->request->bodyParams) : [],
            'session' => isset($_SESSION) ? ArrayHelper::coverSensitiveValues($_SESSION, $this->sensitiveKeys) : [],
            'server' => isset($_SERVER) ? ArrayHelper::coverSensitiveValues($_SERVER, $this->sensitiveKeys) : [],
            'profiling' => Yii::getLogger()->profiling,
            'logger' => Yii::getLogger()->messages,
        ];
    }
390157
public function getAll($idSite, $period, $date, $segment = false)
    {
        Piwik::checkUserHasViewAccess($idSite);

        $this->checkSingleSite($idSite, 'getAll');
        $dataTable = $this->getReferrerType($idSite, $period, $date, $segment, $typeReferrer = false, $idSubtable = false, $expanded = true);

        if ($dataTable instanceof DataTable\Map) {
            throw new Exception("Referrers.getAll with multiple sites or dates is not supported (yet).");
        }

        $dataTable = $dataTable->mergeSubtables($labelColumn = 'referer_type', $useMetadataColumn = true);
        $dataTable->queueFilter('ReplaceColumnNames');
        $dataTable->queueFilter('ReplaceSummaryRowLabel');

        return $dataTable;
    }
245945
public function period(string $period)
    {
        if (!in_array($period, Constants::PERIODS)) {
            throw new InvalidPeriodException('Request period is not valid. Valid values are defined in \Barryvanveen\Lastfm\Constants::PERIODS.');
        }

        $this->query = array_merge($this->query ?? [], ['period' => $period]);

        return $this;
    }
1361344
public function getException($exception)
    {
        return array(
          'type' => 'exception',
          'tid' => $this->tid,
          'action' => $this->action,
          'method' => $this->method,
          'message' => $exception->getMessage(),
          'where' => $exception->getTraceAsString()
        );
    }
665963
private function getResumenPeriodo()
    {
        $resumen = [];
        foreach ($this->detalles as &$d) {
            // si el tipo de boleta no está en el resumen se crea
            if (!isset($resumen[$d['TpoDoc']])) {
                $resumen[$d['TpoDoc']] = [
                    'TpoDoc' => $d['TpoDoc'],
                    'TotAnulado' => false,
                    'TotalesServicio' => [],
                ];
            }
            // si no existe el tipo de servicio se agrega
            if (!isset($resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']])) {
                $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']] = [
                    'TpoServ' => $d['TpoServ'],
                    'PeriodoDevengado' => false,
                    'TotDoc' => false,
                    'TotMntExe' => false,
                    'TotMntNeto' => 0,
                    'TasaIVA' => 0,
                    'TotMntIVA' => 0,
                    'TotMntTotal' => false,
                    'TotMntNoFact' => false,
                    'TotMntPeriodo' => false,
                    'TotSaldoAnt' => false,
                    'TotVlrPagar' => false,
                    'TotTicket' => false,
                ];
            }
            // agregar detalle al resumen
            if (empty($d['Anulado'])) {
                // contabilizar documento
                $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotDoc'] += 1;
                // ir sumando valores
                $vals = ['MntExe'=>'TotMntExe', 'MntTotal'=>'TotMntTotal', 'MntNoFact'=>'TotMntNoFact', 'MntPeriodo'=>'TotMntPeriodo', 'SaldoAnt'=>'TotSaldoAnt', 'VlrPagar'=>'TotVlrPagar', 'TotTicketBoleta'=>'TotTicket'];
                foreach ($vals as $ori => $des) {
                    if ($d[$ori]) {
                        $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']][$des] += $d[$ori];
                    }
                }
                // determinar neto e iva
                $tasa = \sasco\LibreDTE\Sii::getIVA();
                $neto = round(($d['MntTotal'] - $d['MntExe']) / (1 + $tasa/100));
                if ($neto) {
                    $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntNeto'] += $neto;
                    $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TasaIVA'] = $tasa;
                    // WARNING: problema por aproximaciones al calcular el NETO e IVA a partir del BRUTO
                    //$resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntIVA'] = round($resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntNeto'] * ($tasa/100));
                    $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntIVA'] = $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntTotal'] - $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntExe'] - $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntNeto'];
                }
            }
            // documento anulado
            else if ($d['Anulado']=='A') {
                $resumen[$d['TpoDoc']]['TotAnulado'] += 1;
            }
        }
        // armar resumen verdadero
        $ResumenPeriodo = ['TotalesPeriodo'=>[]];
        foreach ($resumen as $r) {
            $ResumenPeriodo['TotalesPeriodo'][] = $r;
        }
        // entregar resumen
        return $ResumenPeriodo;
    }
931142
public function getResults($query)
    {
        $searchResults = [];

        if ($query == '') {
            return $searchResults;
        }

        if ($this->searchEngineId == '') {
            throw new \Exception('You must specify a searchEngineId');
        }

        $client = new Client();
        $result = $client->get('http://www.google.com/cse', ['query' => ['cx' => $this->searchEngineId,
                'client' => 'google-csbe',
                'num' => 20,
                'output' => 'xml_no_dtd',
                'q' => $query,
            ],
        ]);

        if ($result->getStatusCode() != 200) {
            throw new Exception('Resultcode was not ok: '.$result->getStatusCode());
        }

        $xml = simplexml_load_string($result->getBody());

        if ($xml->ERROR) {
            throw new Exception('XML indicated service error: '.$xml->ERROR);
        }

        if ($xml->RES->R) {
            $i = 0;
            foreach ($xml->RES->R as $item) {
                $searchResults[$i]['name'] = (string) $item->T;
                $searchResults[$i]['url'] = (string) $item->U;
                $searchResults[$i]['snippet'] = (string) $item->S;
                $searchResults[$i]['image'] = $this->getPageMapProperty($item, 'cse_image', 'src');

                $searchResults[$i]['product']['name'] = $this->getPageMapProperty($item, 'product', 'name');
                $searchResults[$i]['product']['brand'] = $this->getPageMapProperty($item, 'product', 'brand');
                $searchResults[$i]['product']['price'] = $this->getPageMapProperty($item, 'product', 'price');
                $searchResults[$i]['product']['image'] = $this->getPageMapProperty($item, 'product', 'image');
                $searchResults[$i]['product']['identifier'] = $this->getPageMapProperty($item, 'product', 'identifier');

                $searchResults[$i]['offer']['price'] = $this->getPageMapProperty($item, 'offer', 'price');
                $searchResults[$i]['offer']['pricecurrency'] = $this->getPageMapProperty($item, 'offer', 'pricecurrency');

                ++$i;
            }
        }

        return $searchResults;
    }
1193353
private function getExceptionData($exception)
    {
        $data = [];

        $data['enviroment'] = env('APP_ENV');
        $data['host'] = Request::server('SERVER_NAME');
        $data['method'] = Request::method();
        $data['fullUrl'] = Request::fullUrl();
        $data['exception'] = $exception->getMessage();
        $data['error'] = $exception->getTraceAsString();
        $data['line'] = $exception->getLine();
        $data['file'] = $exception->getFile();
        $data['class'] = get_class($exception);
        $data['storage'] = [
            'SERVER' => Request::server(),
            'GET' => Request::query(),
            'POST' => $_POST,
            'FILE' => Request::file(),
            'OLD' => Request::hasSession() ? Request::old() : [],
            'COOKIE' => Request::cookie(),
            'SESSION' => Request::hasSession() ? Session::all() : [],
            'HEADERS' => Request::header(),
        ];

        $data['storage'] = array_filter($data['storage']);

        $count = $this->config['count'];
        $lines = file($data['file']);
        $data['exegutor'] = [];

        for ($i = -1 * abs($count); $i <= abs($count); $i++) {
            $data['exegutor'][] = $this->getLineInfo($lines, $data['line'], $i);
        }
        $data['exegutor'] = array_filter($data['exegutor']);

        // to make symfony exception more readable
        if ($data['class'] == 'Symfony\Component\Debug\Exception\FatalErrorException') {
            preg_match("~^(.+)' in ~", $data['exception'], $matches);
            if (isset($matches[1])) {
                $data['exception'] = $matches[1];
            }
        }

        return $data;
    }
1110313
private function processPeriod($period)
    {
        $sub = null;

        if ($period == 'week' || $period == 'W') {
            $sub = \Zend_Date::WEEK;
        } elseif ($period == 'month' || $period == 'M') {
            $sub = \Zend_Date::MONTH;
        } elseif ($period == 'year') {
            $sub = \Zend_Date::YEAR;
        } elseif ($period == 'D') {
            $sub = \Zend_Date::DAY;
        }
        return $sub;
    }
242923
public function find($index)
    {
        $result = array();
        foreach ($this->events as $event) {
            if ($index instanceof PeriodInterface && $index->containsEvent($event)) {
                $result[] = $event;
            } elseif ($index instanceof \DateTime && $event->contains($index)) {
                $result[] = $event;
            }
        }

        return $result;
    }
442550
private function getParams($filter)
    {
        $params = [];
        if ($filter) {
            $filter = (string) $filter;
            $filter = strtolower($filter);
            if ($filter !== 'all') {
                $validate = ['completed', 'incomplete', 'late', 'upcoming'];
                if (!in_array($filter, $validate)) {
                    throw new Exception('Invalid value for param filter');
                }
                $params['find'] = $filter;
            }
        }
        return $params;
    }
865700
public function getMonth(): Period
    {
        $startDate = $this
            ->setTime(0, 0)
            ->setDate((int) $this->format('Y'), (int) $this->format('n'), 1);

        return new Period($startDate, $startDate->add(new DateInterval('P1M')));
    }
711608
private function getExceptionMessage(\Exception $exception, Response $response): array
    {
        if ($exception instanceof ValidationExceptionInterface) {
            return ['errors' => $exception->getViolationList()];
        }

        $message = $exception->getMessage();

        if (Response::HTTP_NOT_FOUND === $response->getStatusCode()) {
            $message = preg_replace('#.+\\\|\s+object$#', '', $message);
        }

        if ($this->isDebug) {
            return ['message' => $message, 'trace' => $exception->getTrace()];
        }

        return ['message' => $message];
    }
1047596
protected function getResults($query)
    {
         $searchFields = ($this->getSearchFields() ?: singleton($this->sourceObject)->stat('searchable_fields'));

        if(!$searchFields) {
            throw new Exception(
                sprintf('HasOneAutocompleteField: No searchable fields could be found for class "%s"',
                $this->sourceObject));
        }

        $params = [];
        $sort = [];
        
        foreach($searchFields as $searchField) {
            $name = (strpos($searchField, ':') !== FALSE) ? $searchField : "$searchField:PartialMatch:nocase";
            $params[$name] = $query;
            $sort[$searchField] = "ASC";
        }

        $results = DataList::create($this->sourceObject)
            ->filterAny($params)
            ->sort($sort)
            ->limit($this->getResultsLimit());

        return $results;
    }
207791
public function scopeWithinPeriod(Builder $query, Period $period)
    {
        $startDateTime = $period->getStartDateTime();
        $endDateTime = $period->getEndDateTime();

        if ($startDateTime && ! $endDateTime) {
            $query->where('viewed_at', '>=', $startDateTime);
        } elseif (! $startDateTime && $endDateTime) {
            $query->where('viewed_at', '<=', $endDateTime);
        } elseif ($startDateTime && $endDateTime) {
            $query->whereBetween('viewed_at', [$startDateTime, $endDateTime]);
        }

        return $query;
    }
292136
function getPeriodoSala (periodo) {
  assert.ok(typeof periodo === 'number' || periodo instanceof Date, '[senadores-asistencia]: El periodo ingresado debe ser un número o una fecha.')

  let _period = {}
  if (typeof periodo === 'number') {
    _period = periods.filter(period => period.legislatura === periodo)
    // search directly by period id
    if (_period.length > 0) return _period[0]
    // search only by year
    _period = periods.filter(period => {
      return period.desde.getFullYear() <= periodo && periodo <= period.hasta.getFullYear()
    })[0]
    assert.ok(_period, '[senadores-asistencia]: Periodo de busqueda no encontrado')
    console.warn('[senadores-asistencia]: Solo se puede consultar por periodo legislativo. Si para un mismo año existe más de un periodo legislativo, solo se obtendran los resultados del primer periodo encontrado, por lo que jamas se obtendran los periodos posteriores en caso de existir. Prefiera busquedas por fecha o id de legislatura.')
    return _period
  }
  if (periodo instanceof Date) {
    // search by date
    _period = periods.filter(period => {
      return period.desde.getTime() <= periodo.getTime() && periodo.getTime() <= period.hasta.getTime()
    })[0]
    assert.ok(_period, '[senadores-asistencia]: Periodo de busqueda no encontrado')
    return _period
  }
}
154400
public function &get($idSite, $period)
    {
        if (!isset($this->data[$idSite][$period])) {
            $this->data[$idSite][$period] = $this->defaultRow;
        }
        return $this->data[$idSite][$period];
    }