Return count of users by $types and $sexe between $startDate and $endDate

@param array $types List of types
@param number|unknown $startDate
@param number|unknown $endDate
343764
public function getListUserCountByRangeDate($types, $startDate = '', $endDate = '')
    {
        if (empty($types)) {
            return array();
        }
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');

        $now = new \DateTime("now");
        // $now->format('Y-m-d') . ' 23:59:59';
        $startDateTime = \DateTime::createFromFormat('d/m/Y', $startDate);
        $endDateTime = \DateTime::createFromFormat('d/m/Y', $endDate);

        $rsm = new \Doctrine\ORM\Query\ResultSetMapping;

        $select = array();
        $i = 0;

        foreach ($types as $type) {
            switch ($type) {
                case 'validatedMembers':
                    $filter = "u.state IS NOT NULL";
                    break;
                case 'activeMembers':
                    $filter = "u.state=1";
                    break;
                case 'optin':
                    $filter = "u.optin=1";
                    break;
                case 'optinPartners':
                    $filter = "u.optin_partner=1";
                    break;
                case 'unregistered':
                    $filter = "u.state IS NULL";
                    break;
                case 'suspended':
                    $filter = "u.state=2";
                    break;
                default:
                case 'members':
                    $filter = "u.user_id";
                    break;
            }

            $rsm->addScalarResult('c'.$i, 'c'.$i);
            $select[] = 'SUM(CASE WHEN '.$filter.' THEN 1 ELSE 0 END) AS c'.$i;
            $rsm->addScalarResult('c'.$i.'_male', 'c'.$i.'_male');
            $select[] = 'SUM(CASE WHEN '.$filter.' AND (u.title=\'M\' OR u.title IS NULL) THEN 1 ELSE 0 END) AS c'.$i.'_male';
            $rsm->addScalarResult('c'.$i.'_female', 'c'.$i.'_female');
            $select[] = 'SUM(CASE WHEN '.$filter.' AND u.title=\'Me\' THEN 1 ELSE 0 END) AS c'.$i++.'_female';
        }

        if ($startDate != '' && $endDate != '') {
            $dateRange = "(u.created_at >='" . $startDateTime->format('Y-m-d') . " 0:0:0' AND u.created_at <= '" . $endDateTime->format('Y-m-d') . " 0:0:0')";
        } elseif ($startDate == '' && $endDate != '') {
            $dateRange = "u.created_at <= '" . $endDateTime->format('Y-m-d') . " 0:0:0'";
        } elseif ($startDate != '' && $endDate == '') {
            $dateRange = "u.created_at >='" . $startDateTime->format('Y-m-d') . " 0:0:0'";
        } else {
            $dateRange = "u.created_at IS NOT NULL";
        }
        $query = $em->createNativeQuery('
			SELECT '.implode(',', $select).' FROM user AS u
			WHERE ' . $dateRange, $rsm);
        return array_values($query->getSingleResult());
    }
301352
public function getEmailStats($date, $endDate = null, $aggregatedBy = null)
    {
        $url = $this->getApiEndpoint() . '/v2/email/stats/since-date/' . $date;
        if ($endDate && $aggregatedBy) {
            $url .= '?endDate=' . $endDate . '&aggregatedBy=' . $aggregatedBy;
        }

        $response = $this->setUrl($url)
            ->setVerb('GET')
            ->execute();

        if (isset($response->message)) {
            $this->helper->log('GET EMAIL STATS : ' . $response->message);
        }

        return $response;
    }
67199
public function countInstancesOfType($typeId)
    {
        try {
            return $this->innerGateway->countInstancesOfType($typeId);
        } catch (DBALException $e) {
            throw new RuntimeException('Database error', 0, $e);
        } catch (PDOException $e) {
            throw new RuntimeException('Database error', 0, $e);
        }
    }
244057
public static function getRowCount( $table, $type = 'row' ) {

		$stat = self::find()->where( '`table`=:table AND type=:type', [ ':table' => $table, ':type' => $type ] )->one();

		if( isset( $stat ) ) {

			return $stat->count;
		}

		return 0;
	}
712094
public function getEntityPayments($startDate, $endDate)
    {
        $requestInterval = new Structure\RequestInterval($startDate, $endDate);

        $this->response = parent::getEntityPayments($this->entity, $requestInterval);

        /**
         * Checks the state of the platform integration.
         */
        if (Exception\IntegrationState::check($this->response->integrationState)) {
            throw new Exception\IntegrationState($this->response->integrationState);
        }

        return $this->response;
    }
451353
public function getTopBrowsersForPeriod($startDate, $endDate, $maxResults)
    {
        $browserData = [];
        $answer = $this->performQuery($startDate, $endDate, 'ga:sessions', ['dimensions' => 'ga:browser', 'sort' => '-ga:sessions']);

        if (is_null($answer->rows)) {
            return new Collection([]);
        }

        foreach ($answer->rows as $browserRow) {
            $browserData[] = ['browser' => $browserRow[0], 'sessions' => $browserRow[1]];
        }

        $browserCollection = new Collection(array_slice($browserData, 0, $maxResults - 1));

        if (count($browserData) > $maxResults) {
            $otherBrowsers = new Collection(array_slice($browserData, $maxResults - 1));
            $otherBrowsersCount = array_sum($otherBrowsers->lists('sessions'));

            $browserCollection->put(null, ['browser' => 'other', 'sessions' => $otherBrowsersCount]);
        }

        return $browserCollection;
    }
681660
public function getTopReferrersForPeriod($startDate, $endDate, $maxResults)
    {
        $referrerData = [];

        $answer = $this->performQuery($startDate, $endDate, 'ga:pageviews', ['dimensions' => 'ga:fullReferrer', 'sort' => '-ga:pageviews', 'max-results' => $maxResults]);

        if (is_null($answer->rows)) {
            return new Collection([]);
        }

        foreach ($answer->rows as $pageRow) {
            $referrerData[] = ['url' => $pageRow[0], 'pageViews' => $pageRow[1]];
        }

        return new Collection($referrerData);
    }
649203
public function stats_send($template = null, $start_date = null, $end_date = null, array $data = [ ]) {
        $data['stat'] = 'send';

        if (!is_null($template)) {
            $data['template'] = $template;
        }
        if (!is_null($start_date)) {
            $data['start_date'] = $start_date;
        }
        if (!is_null($end_date)) {
            $data['end_date'] = $end_date;
        }

        return $this->stats($data);
    }
1033008
protected function getVisitsViewsUsersForPeriod(
        DateTime $startDate,
        DateTime $endDate
    ) {
        $cacheName = md5(serialize('visits-views-users'
            .$startDate->format('Y-m-d').$endDate->format('Y-m-d')));

        $urlParams = [
            'ids'        => $this->counter_id,
            'date1'      => $startDate->format('Y-m-d'),
            'date2'      => $endDate->format('Y-m-d'),
            'metrics'    => 'ym:s:visits,ym:s:pageviews,ym:s:users',
            'dimensions' => 'ym:s:date',
            'sort'       => 'ym:s:date',
        ];

        $this->data = $this->request($urlParams, $cacheName);
    }
533434
protected function doIndexCleanup(array $types, DateTime $date = null)
    {
        $query = [];

        if ($types) {
            $query[] = 'type_name:("' . implode('" OR "', $types) . '")';
        } else {
            $query[] = '*:*';
        }

        if ($date) {
            $date = clone $date;
            $date->setTimezone(new DateTimeZone('UTC'));

            $query[] = '-_time_:[' . $date->format('Y-m-d\TG:i:s\Z') . ' TO *]';
        }

        // Delete everything else that did not got a update or does not exist anymore in the
        // database.

        $job = new Job('DELETE');
        $job->setOption('query', implode(' ', $query));

        $this->getQueue()->push($job, 1);
    }
206996
public function getStats($contactClientId, $type, $fromDate = null, $toDate = null)
    {
        $q = $this->createQueryBuilder('s');

        $expr = $q->expr()->andX(
            $q->expr()->eq('IDENTITY(s.contactclient)', (int) $contactClientId),
            $q->expr()->eq('s.type', ':type')
        );

        if ($fromDate) {
            $expr->add(
                $q->expr()->gte('s.dateAdded', ':fromDate')
            );
            $q->setParameter('fromDate', $fromDate);
        }
        if ($toDate) {
            $expr->add(
                $q->expr()->lte('s.dateAdded', ':toDate')
            );
            $q->setParameter('toDate', $toDate);
        }

        $q->where($expr)
            ->setParameter('type', $type);

        return $q->getQuery()->getArrayResult();
    }
710506
public function visitsByPeriod($startDate, $endDate, GetVisitByPeriod $getVisitByPeriod)
    {
        $startDate = Carbon::createFromFormat('Y-m-d', $startDate);
        $endDate = Carbon::createFromFormat('Y-m-d', $endDate);

        return $getVisitByPeriod->fire($startDate, $endDate);
    }
390273
public function count($type,$addSQL='',$params=array()) {
		try {
			return (int) $this->writer->count($type,$addSQL,$params);
		}catch(RedBean_Exception_SQL $e) {
			if (!$this->writer->sqlStateIn($e->getSQLState(),
			array(RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_TABLE)
			)) throw $e;
		}
		return 0;
	}
175675
private function applyDateFilter($objectsIterator, $startDate, $endDate)
    {
        // If either a start or end date was provided, filter out dates that
        // don't match the date range.
        if ($startDate || $endDate) {
            $fn = function ($object) use ($startDate, $endDate) {
                if (!preg_match('/[0-9]{8}T[0-9]{4}Z/', $object['Key'], $m)) {
                    return false;
                }
                $date = strtotime($m[0]);

                return (!$startDate || $date >= $startDate)
                    && (!$endDate || $date <= $endDate);
            };
            $objectsIterator = new \CallbackFilterIterator($objectsIterator, $fn);
        }

        return $objectsIterator;
    }
1175985
public function getCountByDate(
        \DateTime $date = null,
        $contactClientId,
        $statuses = [File::STATUS_READY, File::STATUS_SENT, File::STATUS_ERROR],
        $test = false
    ) {
        $start = clone $date;
        $end   = clone $date;
        $q     = $this->getEntityManager()->getConnection()->createQueryBuilder();
        $q->select('COUNT(*)')
            ->from(MAUTIC_TABLE_PREFIX.$this->getTableName());

        $start->setTime(0, 0, 0);
        $end->setTime(0, 0, 0)->modify('+1 day');
        $timezone = new \DateTimeZone(date_default_timezone_get());
        $start->setTimezone($timezone);
        $end->setTimezone($timezone);

        $q->where(
            $q->expr()->eq('contactclient_id', (int) $contactClientId),
            $q->expr()->gte('date_added', ':start'),
            $q->expr()->lt('date_added', ':end'),
            $q->expr()->eq('test', $test ? 1 : 0)
        );
        $q->setParameter('start', $start->format('Y-m-d H:i:s'));
        $q->setParameter('end', $end->format('Y-m-d H:i:s'));
        $q->andWhere('status IN (\''.implode('\',\'', $statuses).'\')');

        return (int) $q->execute()->fetchColumn();
    }
724054
public static function initDatesInRange($start_date, $end_date, $daysDifference = 1){
        $dates_in_range = [];
        $begin = new DateTime($start_date);
        $end = new DateTime($end_date);
        $endModify = $end->modify( '+'.$daysDifference.' day' ); 

        $interval = new DateInterval('P'.$daysDifference.'D');
        $daterange = new DatePeriod($begin, $interval ,$endModify);

        foreach($daterange as $date){
            $dates_in_range[$date->getTimestamp()] = $date->format("Y-m-d");
        }
        return $dates_in_range;
    }
203828
public function countActiveUsers(array $finderParams = [], $defaultPeriod = false)
    {
        if ($defaultPeriod) {
            $finderParams = $this->formatQueryParams($finderParams);
        }
        $queryParams = FinderProvider::parseQueryParams($finderParams);
        $resultData = $this->logRepository->countActiveUsers($queryParams['allFilters']);

        return floatval($resultData);
    }