PHPackages                             kokiddp/election-scraper-vda - 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. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. kokiddp/election-scraper-vda

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

kokiddp/election-scraper-vda
============================

Libreria per estrarre i dati delle elezioni dal sito della Regione Valle d'Aosta

v1.1.1(9mo ago)010MITPHPPHP &gt;=7.4

Since Sep 26Pushed 9mo agoCompare

[ Source](https://github.com/kokiddp/election-scraper-vda)[ Packagist](https://packagist.org/packages/kokiddp/election-scraper-vda)[ RSS](/packages/kokiddp-election-scraper-vda/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (4)Versions (11)Used By (0)

Election Scraper Valle d'Aosta
==============================

[](#election-scraper-valle-daosta)

[![Status](https://camo.githubusercontent.com/f3027ad9568842bf73b1fcc63be58537b4b204e86196a56c5c9625aec9e6b9d6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7374617475732d6578706572696d656e74616c2d626c7565)](https://camo.githubusercontent.com/f3027ad9568842bf73b1fcc63be58537b4b204e86196a56c5c9625aec9e6b9d6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7374617475732d6578706572696d656e74616c2d626c7565) [![PHP](https://camo.githubusercontent.com/59521a508b7b958748482fd2095d8e892b61381e2e9d103cb547a72bb60e9557/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d2533453d372e342d373737626234)](https://camo.githubusercontent.com/59521a508b7b958748482fd2095d8e892b61381e2e9d103cb547a72bb60e9557/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d2533453d372e342d373737626234) [![License](https://camo.githubusercontent.com/88e1dabf4d223df0950e0985948e231325fefca9fa7fe9e446cf8b1c5e9d9e47/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e)](https://camo.githubusercontent.com/88e1dabf4d223df0950e0985948e231325fefca9fa7fe9e446cf8b1c5e9d9e47/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e)

Libreria PHP per scaricare, normalizzare e riutilizzare i risultati elettorali pubblicati sul portale della Regione Autonoma Valle d'Aosta. Tutti gli scraper condividono un'API coerente e modelli di dominio tipizzati, così da integrare facilmente i dati in dashboard, report o applicazioni custom.

Table of contents
-----------------

[](#table-of-contents)

- [Overview](#overview)
- [Quick start](#quick-start)
- [Key features](#key-features)
- [Installation](#installation)
    - [Requirements](#requirements)
    - [From source](#from-source)
- [Usage](#usage)
    - [Unified fetch/parse API](#unified-fetchparse-api)
    - [Caching and logging](#caching-and-logging)
    - [Command-line helper](#command-line-helper)
- [Available scrapers](#available-scrapers)
- [Domain models &amp; value objects](#domain-models--value-objects)
- [Architecture](#architecture)
- [Testing](#testing)
- [Extending the library](#extending-the-library)
- [Roadmap](#roadmap)
- [Contributing](#contributing)
- [License](#license)
- [Disclaimer](#disclaimer)

Overview
--------

[](#overview)

Election Scraper espone una famiglia di scraper HTML basati su `DOMDocument` e `DOMXPath` per trasformare le tabelle elettorali regionali in oggetti PHP. L'astrazione comune (`AbstractHtmlScraper`) gestisce download, cache opzionale, logging PSR-3, normalizzazione dell'encoding e sanificazione dei dati. Ogni scraper restituisce modelli ricchi (`ComunalResult`, `RegionalResult`, `ReferendumResult`, ecc.) corredati da metodi helper e value object (`VoteCount`, `Percentage`).

Quick start
-----------

[](#quick-start)

```
composer install
php scripts/parse_pages.php
```

```
use ElectionScraperVdA\ReferendumScraper;

$scraper = new ReferendumScraper();
$results = $scraper->fetch('https://example.test/referendum.html');

foreach ($results as $result) {
    echo $result->getResultSummary(), PHP_EOL;
}
```

- Usa `parseHtml()` se hai già il markup localmente.
- Gli esempi HTML sono nella cartella `examples/` per esperimenti rapidi.

Key features
------------

[](#key-features)

- ✅ Supporto a cinque tipologie di consultazioni (referendum, regionali, comunali, coalizioni comunali, ballottaggi).
- ✅ API coerente `fetch()` / `parseHtml()` con docblock generics per l'inferenza dei tipi.
- ✅ Modelli che estendono `AbstractElectionResult` con metodi di riepilogo (`getSummary()`).
- ✅ Value object immutabili per voti e percentuali (`VoteCount`, `Percentage`).
- ✅ Caching personalizzabile via callback o PSR-16 plug-and-play.
- ✅ Logging opzionale attraverso qualunque `Psr\Log\LoggerInterface`.
- ✅ Gestione errori dedicata con `ScraperException::network()` e `ScraperException::parsing()`.
- ✅ Suite PHPUnit che copre edge case HTML e aggregazioni numeriche.

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

[](#installation)

### Requirements

[](#requirements)

- PHP &gt;= 7.4
- Estensioni: `ext-dom`, `ext-libxml` (opzionale ma consigliata: `ext-curl` per download più affidabili)
- Composer

### From source

[](#from-source)

```
git clone https://github.com/kokiddp/election-scraper-vda.git
cd election-scraper-vda
composer install
```

> Quando il pacchetto sarà disponibile su Packagist potrai installarlo con `composer require kokiddp/election-scraper-vda` all'interno di un altro progetto.

Usage
-----

[](#usage)

### Unified fetch/parse API

[](#unified-fetchparse-api)

Ogni scraper implementa la stessa interfaccia:

```
$resultOrCollection = $scraper->fetch(string $url);      // scarica e fa parsing
$resultOrCollection = $scraper->parseHtml(string $html); // usa HTML già disponibile
```

Il metodo protetto `doParse()` racchiude la logica specifica sfruttando `DOMXPath`.

### Caching and logging

[](#caching-and-logging)

```
use ElectionScraperVdA\ComunalScraper;
use Psr\Log\NullLogger;

$cache = function (string $key, string $url, callable $download) {
    $tmp = sys_get_temp_dir() . '/es_' . $key;
    if (is_file($tmp)) {
        return file_get_contents($tmp);
    }
    $html = $download($url);
    file_put_contents($tmp, $html);
    return $html;
};

$scraper = new ComunalScraper(cacheCallback: $cache, logger: new NullLogger());
$result = $scraper->fetch('https://example.test/comunali.html');
```

È possibile anche fornire una cache PSR-16:

```
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Psr16Cache;
use ElectionScraperVdA\ReferendumScraper;

$pool = new FilesystemAdapter(namespace: 'election', defaultLifetime: 300);
$psr16 = new Psr16Cache($pool);
$scraper = new ReferendumScraper(psr16Cache: $psr16, psr16Ttl: 600);
```

La priorità è: **PSR-16** &gt; **callback custom** &gt; nessuna cache. Puoi inoltre passare un logger PSR-3 (Monolog, `NullLogger`, ecc.) per ricevere messaggi su fetch, fallimenti e parsing.

### Command-line helper

[](#command-line-helper)

`php scripts/parse_pages.php` processa gli HTML in `examples/` e produce `examples/parsed_output.json`, utile come regression test manuale o per esplorare la struttura dei dati.

Available scrapers
------------------

[](#available-scrapers)

ScraperOutputDescrizione`ReferendumScraper``array`Risultati SÌ/NO per entità (comune, Aosta, regionale)`RegionalScraper``array`Liste con voti, percentuali, seggi e voti contestati`ComunalScraper``ComunalResult`Liste e candidati del singolo comune`ComunalCoalitionScraper``ComunalCoalitionResult`Coalizioni sindaco/vice e liste di supporto`BallottaggioScraper``BallottaggioResult`Confronto a due con margine e affluenzaDomain models &amp; value objects
---------------------------------

[](#domain-models--value-objects)

- `AbstractElectionResult`: campi condivisi (elettori, votanti, schede bianche/nulle) e helper (`ensureAffluenza()`, `votiValidiCount()`).
- `ComunalResult`, `ComunalCoalitionResult`, `BallottaggioResult`: specializzazioni con liste, coalizioni e candidati.
- `ReferendumResult`, `RegionalResult`: modelli standalone con metodi di parsing (`fromArray()`), formatter e sintesi (`getResultSummary()`).
- `VoteCount`, `Percentage`: value object immutabili con validazioni e formattazione consistente.

Ogni modello espone `getSummary()` per generare descrizioni pronte da loggare o mostrare a video. In fase di parsing vengono sanitizzati numeri, percentuali e stringhe.

Architecture
------------

[](#architecture)

```
src/
    Scraper/
        AbstractHtmlScraper
