PHPackages                             c0destep/holy\_bible - 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. c0destep/holy\_bible

ActiveLibrary

c0destep/holy\_bible
====================

Holy Bible

v2.1.0(1mo ago)495MITPHPPHP ^8.1CI passing

Since Mar 26Pushed 1mo agoCompare

[ Source](https://github.com/c0destep/holy_bible)[ Packagist](https://packagist.org/packages/c0destep/holy_bible)[ RSS](/packages/c0destep-holy-bible/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (8)Dependencies (9)Versions (10)Used By (0)

Holy Bible API - PHP Library
============================

[](#holy-bible-api---php-library)

> 🌐 [English Version](docs/README-EN.md)

[![PHP Version](https://camo.githubusercontent.com/7663c9d53dc13cedaf0660a8745a7e77d2dd711257f36aa86ebce12a0600ef42/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e312d626c75652e737667)](https://php.net)[![License](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667)](LICENSE)[![PHPStan Level](https://camo.githubusercontent.com/d117944b58da8146f96b4ef7403807610a20eeb3fbcaaaf95157bbcdad1686eb/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c253230382d627269676874677265656e2e737667)](https://phpstan.org/)

Uma biblioteca PHP moderna e robusta para acessar a API da Bíblia Digital com suporte a cache, retry logic, logging e DTOs tipados.

✨ Características
-----------------

[](#-características)

- 🚀 **Cache Inteligente** - Até 400x mais rápido com cache automático
- 🔄 **Retry Automático** - Exponential backoff para falhas temporárias
- 📝 **PSR-3 Logging** - Logging completo para debugging
- 🎯 **Type-Safe** - DTOs com propriedades readonly (PHP 8.1+)
- 🏗️ **Arquitetura em Camadas** - Client/Service/Facade
- ⚙️ **Configuração Flexível** - Arrays, variáveis de ambiente, ou objetos
- ✅ **100% Testado** - 27 testes automatizados
- 🔒 **PHPStan Level 8** - Análise estática rigorosa
- 🔙 **Backward Compatible** - Funciona com código existente
- 📴 **Offline Support** - Suporte a SQLite local

📦 Instalação
------------

[](#-instalação)

```
composer require c0destep/holy_bible
```

🚀 Uso Rápido
------------

[](#-uso-rápido)

### Básico (Backward Compatible)

[](#básico-backward-compatible)

```
use HolyBible\Bible;
use HolyBible\Books;

$bible = new Bible();

// Obter capítulo
$chapter = $bible->getChapter(Books::JOHN, 3);
foreach ($chapter['verses'] as $verse) {
    echo "{$verse['number']}. {$verse['text']}\n";
}

// Obter versículo específico
$verse = $bible->getVerse(Books::JOHN, 3, 16);
echo $verse['text'];

// Listar todos os livros
$books = $bible->getBooks();

// Listar versões disponíveis
$versions = $bible->getAvailableVersions();
```

### Com Configuração Avançada

[](#com-configuração-avançada)

```
use HolyBible\Bible;
use HolyBible\Config\BibleConfig;
use HolyBible\Retry\RetryPolicy;
use Monolog\Logger;
use Monolog\Level;
use Monolog\Handler\StreamHandler;

// Criar logger
$logger = new Logger('bible');
$logger->pushHandler(new StreamHandler('bible.log', Level::Debug));

// Configurar
$config = new BibleConfig([
    'version' => 'nvi',
    'timeout' => 10.0,
    'cache_enabled' => true,
    'cache_ttl' => 7200,  // 2 horas
    'retry_policy' => RetryPolicy::aggressive(),
    'logger' => $logger
]);

$bible = Bible::withConfig($config);
```

### Usando DTOs (Type-Safe)

[](#usando-dtos-type-safe)

```
$service = $bible->getService();

// Retorna ChapterDTO
$chapter = $service->getChapter(Books::PSALMS, 23);

echo "Livro: {$chapter->book->name}\n";
echo "Capítulo: {$chapter->number}\n";
echo "Versículos: {$chapter->getVerseCount()}\n";

foreach ($chapter->verses as $verse) {
    echo "{$verse->number}. {$verse->text}\n";
}

// Buscar versículo específico
$verse1 = $chapter->getVerse(1);
if ($verse1) {
    echo $verse1->text;
}
```

### Tratamento de Erros

[](#tratamento-de-erros)

```
use HolyBible\Exception\{
    InvalidChapterException,
    InvalidVerseException,
    NetworkException,
    ApiResponseException
};

try {
    $chapter = $bible->getChapter(Books::GENESIS, 1);

} catch (InvalidChapterException $e) {
    // Entrada inválida (capítulo < 1)
    echo "Capítulo inválido: " . $e->getMessage();

} catch (InvalidVerseException $e) {
    // Entrada inválida (versículo < 1)
    echo "Versículo inválido: " . $e->getMessage();

} catch (NetworkException $e) {
    // Erro de rede/timeout
    echo "Erro de conexão: " . $e->getMessage();
    // Retry já foi tentado automaticamente

} catch (ApiResponseException $e) {
    // Erro da API (JSON inválido, etc)
    echo "Erro da API: " . $e->getMessage();
}
```

⚙️ Configuração
---------------

[](#️-configuração)

### Via Array

[](#via-array)

```
$config = new BibleConfig([
    'version' => 'acf',              // Versão da Bíblia
    'user_token' => 'seu-token',     // Token de autenticação (opcional)
    'timeout' => 15.0,               // Timeout em segundos
    'cache_enabled' => true,         // Habilitar cache
    'cache_ttl' => 3600,             // TTL do cache em segundos
    'cache_dir' => '/custom/path',   // Diretório do cache (opcional)
    'retry_enabled' => true,         // Habilitar retry
    'retry_policy' => RetryPolicy::default(),  // Política de retry
    'logger' => $myLogger            // PSR-3 logger (opcional)
]);
```

### Via Variáveis de Ambiente

[](#via-variáveis-de-ambiente)

```
export BIBLE_VERSION=nvi
export BIBLE_USER_TOKEN=abc123
export BIBLE_TIMEOUT=10.0
export BIBLE_CACHE_ENABLED=true
export BIBLE_CACHE_TTL=7200
export BIBLE_RETRY_ENABLED=true
export BIBLE_SQLITE_PATH=/caminho/para/bible.sqlite
```

```
// Lê automaticamente das variáveis de ambiente
$config = new BibleConfig();
$bible = Bible::withConfig($config);
```

### Interface Fluente

[](#interface-fluente)

```
$config = new BibleConfig();
$config->setVersion('acf')
       ->setTimeout(20.0)
       ->setCacheTtl(1800)
       ->setRetryPolicy(RetryPolicy::aggressive());
```

🔄 Retry Logic
-------------

[](#-retry-logic)

A biblioteca implementa retry automático com exponential backoff:

### Políticas Pré-Configuradas

[](#políticas-pré-configuradas)

```
use HolyBible\Retry\RetryPolicy;

// Padrão: 3 tentativas, backoff 2x
$policy = RetryPolicy::default();

// Agressivo: 5 tentativas, backoff 1.5x
$policy = RetryPolicy::aggressive();

// Desabilitado
$policy = RetryPolicy::disabled();

// Customizado
$policy = new RetryPolicy(
    maxAttempts: 4,
    initialDelayMs: 200,
    multiplier: 2.5,
    maxDelayMs: 10000
);
```

### Quando Retry é Aplicado

[](#quando-retry-é-aplicado)

- ✅ Erros de conexão (timeout, DNS, etc)
- ✅ Erros 5xx do servidor
- ✅ Erro 429 (rate limiting)
- ❌ Erros 4xx (exceto 429)
- ❌ Erros de validação local

📝 Logging
---------

[](#-logging)

Suporte completo a PSR-3 logging:

```
use Monolog\Logger;
use Monolog\Level;
use Monolog\Handler\StreamHandler;

$logger = new Logger('bible');
$logger->pushHandler(new StreamHandler('bible.log', Level::Debug));

$config = new BibleConfig(['logger' => $logger]);
$bible = Bible::withConfig($config);

// Logs automáticos:
// - DEBUG: Cada requisição HTTP
// - INFO: Requisições bem-sucedidas
// - WARNING: Retries, erros temporários
// - ERROR: Falhas definitivas
```

💾 Cache
-------

[](#-cache)

### Cache de Arquivos (Padrão)

[](#cache-de-arquivos-padrão)

```
use HolyBible\Cache\FileCache;

$cache = new FileCache('/var/cache/bible');
$config = new BibleConfig([
    'cache' => $cache,
    'cache_ttl' => 86400  // 24 horas
]);
```

### Cache Customizado

[](#cache-customizado)

Implemente `CacheInterface`:

```
use HolyBible\Cache\CacheInterface;

class RedisCache implements CacheInterface
{
    public function get(string $key): mixed { /* ... */ }
    public function set(string $key, mixed $value, int $ttl = 3600): bool { /* ... */ }
    public function has(string $key): bool { /* ... */ }
    public function delete(string $key): bool { /* ... */ }
    public function clear(): bool { /* ... */ }
}

$config = new BibleConfig(['cache' => new RedisCache()]);
```

### Desabilitar Cache

[](#desabilitar-cache)

```
$config = new BibleConfig(['cache_enabled' => false]);
```

💾 Suporte Offline (SQLite)
--------------------------

[](#-suporte-offline-sqlite)

Agora você pode usar a biblioteca sem conexão com a internet através de um banco de dados SQLite local.

### ⚙️ Configuração SQLite

[](#️-configuração-sqlite)

```
use HolyBible\Bible;
use HolyBible\Config\BibleConfig;

// 1. Configure o caminho para o arquivo .sqlite
$config = new BibleConfig([
    'sqlite_path' => 'bible.sqlite',
    'version'     => 'nvi'
]);

// 2. A fachada Bible trocará automaticamente para o modo offline
$bible = Bible::withConfig($config);

// 3. O uso permanece idêntico ao modo online (URIs mapeadas para SQL)
$chapter = $bible->getChapter(HolyBible\Books::PSALMS, 23);
```

### 🌍 Variável de Ambiente

[](#-variável-de-ambiente)

Você também pode configurar o caminho globalmente via `.env` ou export:

```
export BIBLE_SQLITE_PATH=/caminho/para/bible.sqlite
```

A biblioteca inclui o arquivo `bible.sqlite` na raiz, gerado a partir do `data.sql` fornecido, permitindo o funcionamento offline imediato.

📚 DTOs Disponíveis
------------------

[](#-dtos-disponíveis)

### BookDTO

[](#bookdto)

```
$book->name;       // "Gênesis"
$book->abbrev;     // "gn"
$book->chapters;   // 50
$book->testament;  // "VT"
```

### ChapterDTO

[](#chapterdto)

```
$chapter->book;           // BookDTO
$chapter->number;         // 3
$chapter->verses;         // VerseDTO[]
$chapter->getVerse(16);   // VerseDTO|null
$chapter->getVerseCount(); // int
```

### VerseDTO

[](#versedto)

```
$verse->number;  // 16
$verse->text;    // "Porque Deus amou o mundo..."
```

### VersionDTO

[](#versiondto)

```
$version->version;  // "nvi"
$version->name;     // "Nova Versão Internacional"
```

🧪 Testes
--------

[](#-testes)

```
# Rodar todos os testes
./vendor/bin/phpunit

# Com coverage
./vendor/bin/phpunit --coverage-html coverage

# PHPStan
./vendor/bin/phpstan analyse src tests
```

📊 Estatísticas
--------------

[](#-estatísticas)

- **27 testes automatizados** (100% passando)
- **71 assertions**
- **PHPStan level 8** (0 erros)
- **~2,200 linhas de código**
- **19 classes**
- **2 interfaces**
- **5 exceções customizadas**

🏗️ Arquitetura
--------------

[](#️-arquitetura)

```
src/
├── Cache/          # Sistema de cache
├── Client/         # HTTP client layer
├── Config/         # Configuração
├── DTO/            # Data Transfer Objects
├── Exception/      # Exceções customizadas
├── Retry/          # Retry logic
├── Service/        # Business logic
├── Bible.php       # Facade (API pública)
└── Books.php       # Enum de livros

```

🤝 Contribuindo
--------------

[](#-contribuindo)

Contribuições são bem-vindas! Por favor:

1. Fork o projeto
2. Crie uma branch (`git checkout -b feature/nova-feature`)
3. Commit suas mudanças (`git commit -am 'Adiciona nova feature'`)
4. Push para a branch (`git push origin feature/nova-feature`)
5. Abra um Pull Request

📄 Licença
---------

[](#-licença)

Este projeto está licenciado sob a Licença MIT - veja o arquivo [LICENSE](LICENSE) para detalhes.

🙏 Créditos
----------

[](#-créditos)

- API fornecida por [A Bíblia Digital](https://www.abibliadigital.com.br/)
- Desenvolvido por [c0destep](https://github.com/c0destep)

📞 Suporte
---------

[](#-suporte)

- 🐛 [Reportar Bug](https://github.com/c0destep/holy_bible/issues)
- 💡 [Solicitar Feature](https://github.com/c0destep/holy_bible/issues)
- 📖 [Documentação](https://github.com/c0destep/holy_bible/wiki)

---

**Feito com ❤️ em PHP**

###  Health Score

45

—

FairBetter than 92% of packages

Maintenance88

Actively maintained with recent releases

Popularity11

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 91.7% 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 ~155 days

Recently: every ~1 days

Total

8

Last Release

58d ago

Major Versions

v1.0.0 → v2.0.02026-02-02

### Community

Maintainers

![](https://www.gravatar.com/avatar/0b4c849fbc960889dbcd54c776fc9916dbbca0814f3088868873d97b57936280?d=identicon)[Codestep](/maintainers/Codestep)

---

Top Contributors

[![c0destep](https://avatars.githubusercontent.com/u/65411044?v=4)](https://github.com/c0destep "c0destep (33 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (3 commits)")

---

Tags

biblehacktoberfestphp

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/c0destep-holy-bible/health.svg)

```
[![Health](https://phpackages.com/badges/c0destep-holy-bible/health.svg)](https://phpackages.com/packages/c0destep-holy-bible)
```

###  Alternatives

[craftcms/cms

Craft CMS

3.6k3.6M2.6k](/packages/craftcms-cms)[google/cloud

Google Cloud Client Library

1.2k16.2M53](/packages/google-cloud)[google/cloud-core

Google Cloud PHP shared dependency, providing functionality useful to all components.

343121.4M79](/packages/google-cloud-core)[googleads/googleads-php-lib

Google Ad Manager SOAP API Client Library for PHP

67410.3M25](/packages/googleads-googleads-php-lib)[tempest/framework

The PHP framework that gets out of your way.

2.1k23.1k9](/packages/tempest-framework)[akamai-open/edgegrid-client

Implements the Akamai {OPEN} EdgeGrid Authentication specified by https://developer.akamai.com/introduction/Client\_Auth.html

482.5M6](/packages/akamai-open-edgegrid-client)

PHPackages © 2026

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