PHPackages                             tourze/statistics-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. tourze/statistics-bundle

ActiveSymfony-bundle[Utility &amp; Helpers](/categories/utility)

tourze/statistics-bundle
========================

Symfony 统计数据模块，提供日报生成、指标收集、统计表创建等功能

1.1.0(5mo ago)02501MITPHPCI passing

Since Apr 7Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/tourze/statistics-bundle)[ Packagist](https://packagist.org/packages/tourze/statistics-bundle)[ RSS](/packages/tourze-statistics-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (46)Versions (12)Used By (1)

statistics-bundle
=================

[](#statistics-bundle)

[English](README.md) | [中文](README.zh-CN.md)

[![Latest Version](https://camo.githubusercontent.com/ddcf18a15c2bde24ea783b30c91aa63eaf212b17d3ea1eec1d8180683165cad7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f75727a652f737461746973746963732d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/statistics-bundle)[![PHP Version](https://camo.githubusercontent.com/d9e7e0acfc255a520d086f0f0a1919afc2ce5d75ae4b73d9b0bd318d630a5a1a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f746f75727a652f737461746973746963732d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/statistics-bundle)[![License](https://camo.githubusercontent.com/95526f0de4213af73dd31713243e3d0f844dd2b51ebe67f2eb4af3f3fa997f79/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f746f75727a652f737461746973746963732d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/statistics-bundle)![Coverage](https://camo.githubusercontent.com/994d68acb2aadf1c3c7711ddcb3b30429246a6c05da9e601f62c3f932ac795a8/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f7665726167652d3130302532352d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)

A comprehensive Symfony bundle for statistics data collection, providing daily report generation, metrics collection, and automatic statistics table creation functionality.

This bundle offers a complete solution for statistics management in Symfony applications, featuring a flexible plugin-based architecture that supports custom metrics providers and automatic table schema management.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Dependencies](#dependencies)
- [Installation](#installation)
- [Configuration](#configuration)
- [Quick Start](#quick-start)
- [Advanced Usage](#advanced-usage)
    - [Creating Custom Metric Providers](#creating-custom-metric-providers)
    - [Stats Table Management](#stats-table-management)
- [API Reference](#api-reference)
- [Contributing](#contributing)
- [License](#license)
- [Changelog](#changelog)

Features
--------

[](#features)

- **Daily Report Generation**: Automatically generate and manage daily statistics reports
- **Flexible Metrics System**: Plugin-based architecture with custom metric providers
- **Multi-dimensional Analysis**: Support for categorized metrics with various data types
- **CLI Tools**: Console commands for report generation and stats table management
- **Doctrine Integration**: Full ORM support with proper entity relationships
- **Async Processing**: Support for background processing via Symfony Messenger
- **Extensible Architecture**: Easy to extend with custom providers and processors

Dependencies
------------

[](#dependencies)

- PHP &gt;= 8.1
- Symfony &gt;= 7.3
- Doctrine ORM &gt;= 3.0
- nesbot/carbon &gt;= 2.72
- tourze ecosystem packages (doctrine-helper, doctrine-timestamp-bundle, etc.)

Installation
------------

[](#installation)

Install via Composer:

```
composer require tourze/statistics-bundle
```

Configuration
-------------

[](#configuration)

Register the bundle in your Symfony application:

```
// config/bundles.php
return [
    // ... other bundles
    StatisticsBundle\StatisticsBundle::class => ['all' => true],
];
```

The bundle works out of the box with minimal configuration. Services are automatically registered and tagged for dependency injection.

Quick Start
-----------

[](#quick-start)

1. **Register the bundle** in Symfony (if not auto-registered):

    ```
    // config/bundles.php
    return [
        // ... other bundles
        StatisticsBundle\StatisticsBundle::class => ['all' => true],
    ];
    ```
2. **Run database migrations** to create required tables:

    ```
    php bin/console doctrine:migrations:migrate
    ```
3. **Generate daily reports** using the CLI command:

    ```
    # Generate report for yesterday (default)
    php bin/console app:statistics:generate-daily-report

    # Generate report for a specific date
    php bin/console app:statistics:generate-daily-report --date=2024-04-27

    # Force regenerate existing report
    php bin/console app:statistics:generate-daily-report --date=2024-04-27 --force
    ```
4. **Manage stats tables** with auto-generation:

    ```
    php bin/console app:stats-table
    ```

Advanced Usage
--------------

[](#advanced-usage)

### Creating Custom Metric Providers

[](#creating-custom-metric-providers)

Implement the `MetricProviderInterface` to create custom metrics:

```
use Carbon\CarbonImmutable;
use StatisticsBundle\Metric\MetricProviderInterface;
use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;

#[AutoconfigureTag(MetricProviderInterface::SERVICE_TAG)]
class CustomMetricProvider implements MetricProviderInterface
{
    public function getMetricId(): string
    {
        return 'user_registrations';
    }

    public function getMetricName(): string
    {
        return 'Daily User Registrations';
    }

    public function getMetricDescription(): string
    {
        return 'Number of users registered on this day';
    }

    public function getMetricUnit(): string
    {
        return 'users';
    }

    public function getCategory(): string
    {
        return 'user_activity';
    }

    public function getCategoryOrder(): int
    {
        return 10;
    }

    public function getMetricValue(CarbonImmutable $date): mixed
    {
        // Your custom logic here - query database, call APIs, etc.
        return $this->userRepository->countRegistrationsForDate($date);
    }
}
```

The metrics provider will be automatically registered when you tag it with `MetricProviderInterface::SERVICE_TAG`.

### Stats Table Management

[](#stats-table-management)

The bundle provides automatic statistics table creation and management through the `AsStatsColumn` attribute:

```
use StatisticsBundle\Attribute\AsStatsColumn;
use StatisticsBundle\Enum\StatTimeDimension;
use StatisticsBundle\Enum\StatType;

class MyEntity
{
    #[AsStatsColumn(timeDimension: StatTimeDimension::DAILY_NEW, statsType: StatType::COUNT)]
    private int $dailyCount;

    #[AsStatsColumn(timeDimension: StatTimeDimension::MONTHLY_TOTAL, statsType: StatType::SUM, name: 'monthly_revenue')]
    private float $revenue;
}
```

Then run the stats table command to create/update tables:

```
php bin/console app:stats-table
```

### Working with Daily Reports

[](#working-with-daily-reports)

The bundle provides a service for programmatic access to daily reports:

```
use StatisticsBundle\Service\DailyReportService;

class MyController
{
    public function __construct(
        private DailyReportService $dailyReportService
    ) {}

    public function getReports()
    {
        // Get a specific date report
        $report = $this->dailyReportService->getDailyReport('2024-04-27');

        // Get reports for a date range
        $reports = $this->dailyReportService->getDailyReportsByDateRange(
            '2024-04-01',
            '2024-04-30'
        );

        // Get recent reports (last 7 days by default)
        $recentReports = $this->dailyReportService->getRecentDailyReports(30);

        // Create or update a report programmatically
        $metricsData = [
            'user_count' => ['name' => 'User Count', 'value' => 150, 'unit' => 'users'],
            'revenue' => ['name' => 'Daily Revenue', 'value' => 1250.50, 'unit' => 'USD']
        ];
        $report = $this->dailyReportService->createOrUpdateDailyReport(
            '2024-04-27',
            $metricsData,
            ['extra' => 'metadata']
        );
    }
}
```

### Entities and Data Structure

[](#entities-and-data-structure)

The bundle provides the following main entities:

- **DailyReport**: Represents a daily statistics report with date and metrics
- **DailyMetric**: Individual metrics within a daily report with name, value, unit, and category
- **StatTimeDimension**: Enum for time dimensions (DAILY\_NEW, DAILY\_TOTAL, WEEKLY\_NEW, etc.)
- **StatType**: Enum for statistic types (COUNT, SUM, AVG, etc.)
- **AsStatsColumn**: Attribute for marking entity properties for automatic stats table generation

API Reference
-------------

[](#api-reference)

### Console Commands

[](#console-commands)

- `app:statistics:generate-daily-report`: Generate daily statistics reports with options for date and force refresh
- `app:stats-table`: Automatically create and maintain statistics tables based on entity annotations

### Services

[](#services)

- `DailyReportService`: Main service for daily report CRUD operations and metric provider management
- `CreateTableStatsHandler`: Async message handler for statistics table data population

### Interfaces and Attributes

[](#interfaces-and-attributes)

- `MetricProviderInterface`: Interface for implementing custom metric providers
- `DailyReportRepositoryInterface`: Repository interface for daily reports
- `AsStatsColumn`: Attribute for marking entity properties for automatic statistics tracking

Contributing
------------

[](#contributing)

We welcome contributions! Please follow these guidelines:

- Follow PSR-12 coding standards
- Write comprehensive tests for new features
- Update documentation for API changes
- Use semantic versioning for releases

License
-------

[](#license)

This package is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.

Changelog
---------

[](#changelog)

For a detailed list of changes, please refer to the [CHANGELOG.md](CHANGELOG.md) file or the Git commit history.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance73

Regular maintenance activity

Popularity11

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~25 days

Recently: every ~50 days

Total

11

Last Release

151d ago

Major Versions

0.1.3 → 1.0.02025-11-04

### Community

Maintainers

![](https://www.gravatar.com/avatar/e354fdb316da535dfa8ba2e9193a473c403b6bc6fb9170778d1dc50e304c6e9d?d=identicon)[tourze](/maintainers/tourze)

---

Top Contributors

[![tourze](https://avatars.githubusercontent.com/u/13899502?v=4)](https://github.com/tourze "tourze (5 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-statistics-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-statistics-bundle/health.svg)](https://phpackages.com/packages/tourze-statistics-bundle)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[open-dxp/opendxp

Content &amp; Product Management Framework (CMS/PIM)

7310.3k29](/packages/open-dxp-opendxp)[contao/core-bundle

Contao Open Source CMS

1231.6M2.4k](/packages/contao-core-bundle)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
