PHPackages                             macpaw/schema-context-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. macpaw/schema-context-bundle

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

macpaw/schema-context-bundle
============================

A Symfony bundle to provide schema context

v2.0.2(6mo ago)136.1k↓29.4%2PHPPHP &gt;=8.3CI passing

Since Jul 10Pushed 6mo agoCompare

[ Source](https://github.com/MacPaw/schema-context-bundle)[ Packagist](https://packagist.org/packages/macpaw/schema-context-bundle)[ RSS](/packages/macpaw-schema-context-bundle/feed)WikiDiscussions develop Synced 1mo ago

READMEChangelog (10)Dependencies (8)Versions (20)Used By (2)

Schema Context Bundle
=====================

[](#schema-context-bundle)

The **SchemaContextBundle** provides a robust way to manage dynamic schema context across your Symfony application, especially useful for multi-tenant setups. It extracts schema information from W3C standard baggage headers (or Symfony Messenger Stamps), validates schema changes based on environment configuration, and propagates schema context throughout your application, including HTTP clients and Symfony Messenger queues.

---

Features
--------

[](#features)

- Extracts tenant schema param from W3C standard `baggage` request header.
- Stores schema and baggage context in a global `BaggageSchemaResolver`.
- Validates schema changes based on environment configuration to prevent accidental schema mismatches.
- Injects schema and baggage info into Messenger messages via a middleware.
- Rehydrates schema and baggage on message consumption via a middleware.
- Provide decorator for Http clients to propagate baggage header.
- Optional: Adds baggage context to Monolog log records via a processor.

---

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

[](#installation)

```
composer require macpaw/schema-context-bundle
```

If you are not using Symfony Flex, register the bundle manually:

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

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

[](#configuration)

### 1. Bundle Configuration

[](#1-bundle-configuration)

Add this config to `config/packages/schema_context.yaml`:

```
schema_context:
    environment_name: '%env(APP_ENV)%' # Current environment name (example: 'develop')
    header_name: 'X-Tenant' # Key name in baggage header to extract schema name
    environment_schema: '%env(ENVIRONMENT_SCHEMA)%' # The schema for this environment (example: 'public')
    overridable_environments: ['develop', 'staging', 'test'] # Environments where schema can be overridden via baggage header or Symfony Messenger stamp
```

**Configuration parameters:**

- `environment_name`: The name of the current environment. Best practice is to use `'%env(APP_ENV)%'` to match Symfony's environment.
- `environment_schema`: The schema for this environment.
- `header_name`: The key name in the baggage header used to extract the schema value.
- `overridable_environments`: List of environment names where schema can be overridden via baggage header or Symfony Messenger stamp.

```
APP_ENV=develop
ENVIRONMENT_SCHEMA=public
```

### 3. Schema Override Protection

[](#3-schema-override-protection)

The bundle includes protection against accidental schema changes in production environments:

- In **non-overridable environments** (e.g., `production`): The schema is always fixed to `environment_schema`. Any attempt to override it via baggage header will throw `EnvironmentSchemaMismatchException`.
- In **overridable environments** (e.g., `develop`, `staging`): The schema can be dynamically changed via baggage header for testing and development purposes.

Usage
-----

[](#usage)

```
use Macpaw\SchemaContextBundle\Service\BaggageSchemaResolver;

public function index(BaggageSchemaResolver $schemaResolver)
{
    $schema = $schemaResolver->getSchema();
    $baggage = $schemaResolver->getBaggage();
    // Use schema in logic
}
```

### Baggage Header Format

[](#baggage-header-format)

The bundle uses W3C standard `baggage` header format. Example request:

```
GET /api/endpoint HTTP/1.1
Host: example.com
baggage: X-Tenant=tenant_a,user-id=12345,trace-id=abc123
```

The bundle will extract the schema value from the baggage header using the key specified in `header_name` configuration.

Exception Handling
------------------

[](#exception-handling)

### EnvironmentSchemaMismatchException

[](#environmentschemamismatchexception)

The bundle throws `EnvironmentSchemaMismatchException` when:

- The environment is **not** in the `overridable_environments` list
- A request tries to set a schema via baggage header that differs from `environment_schema`

This exception prevents accidental schema changes in production/staging/etc. environments. Example error message:

```
Schema mismatch in "production" environment: expected "public", got "tenant_a". Allowed override environments: [develop, staging, test].

```

**How to handle:**

- In production/staging/etc.: ensure clients don't send schema baggage headers, or send the correct environment schema
- In development: add your environment to `overridable_environments` list if you need to test different schemas

Baggage-Aware HTTP Client
-------------------------

[](#baggage-aware-http-client)

Decorate your http client in your service configuration:

```
services:
    baggage_aware_payment_http_client:
        class: Macpaw\SchemaContextBundle\HttpClient\BaggageAwareHttpClient
        decorates: payment_http_client #http client to decorate
        arguments:
            - '@baggage_aware_payment_http_client.inner'
```

### A Note on Testing

[](#a-note-on-testing)

If you are replacing or mocking HTTP clients in your test environment, for example, using a library like [`macpaw/extended-mock-http-client`](https://github.com/MacPaw/extended_mock_http_client), you need to disable the `BaggageAwareHttpClient` decoration.

```
when@test:
    services:
        baggage_aware_payment_http_client:
            class: Macpaw\SchemaContextBundle\HttpClient\BaggageAwareHttpClient
```

Messenger Integration
---------------------

[](#messenger-integration)

The bundle provides a middleware that automatically:

- Adds a BaggageSchemaStamp to dispatched messages
- Restores the schema and baggage context on message handling

Enable the middleware in your `messenger.yaml`:

```
framework:
    messenger:
        buses:
            messenger.bus.default:
                middleware:
                    - Macpaw\SchemaContextBundle\Messenger\Middleware\BaggageSchemaMiddleware
```

Optional: Monolog Integration
-----------------------------

[](#optional-monolog-integration)

The bundle provides an optional processor that automatically adds baggage context to your log records:

- Adds baggage information to the `extra` field of log records

To enable the processor, add it to your service configuration:

```
services:
    Macpaw\SchemaContextBundle\Monolog\BaggageProcessor:
        tags:
            - { name: monolog.processor }
```

Testing
-------

[](#testing)

To run tests:

```
vendor/bin/phpunit
```

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

[](#contributing)

Feel free to open issues and submit pull requests.

License
-------

[](#license)

This bundle is released under the MIT license.

###  Health Score

46

—

FairBetter than 93% of packages

Maintenance66

Regular maintenance activity

Popularity30

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~6 days

Recently: every ~1 days

Total

17

Last Release

208d ago

Major Versions

v1.3.2 → v2.0.02025-10-20

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1935412?v=4)[MacPaw Inc.](/maintainers/macpaw)[@MacPaw](https://github.com/MacPaw)

---

Top Contributors

[![alekseytupichenkov](https://avatars.githubusercontent.com/u/8191991?v=4)](https://github.com/alekseytupichenkov "alekseytupichenkov (30 commits)")[![cod-a-holic](https://avatars.githubusercontent.com/u/15779118?v=4)](https://github.com/cod-a-holic "cod-a-holic (16 commits)")[![serhiidonii](https://avatars.githubusercontent.com/u/158484424?v=4)](https://github.com/serhiidonii "serhiidonii (14 commits)")[![crossplanegithub[bot]](https://avatars.githubusercontent.com/u/1935412?v=4)](https://github.com/crossplanegithub[bot] "crossplanegithub[bot] (1 commits)")

---

Tags

backendmacpawsymfony

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/macpaw-schema-context-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/macpaw-schema-context-bundle/health.svg)](https://phpackages.com/packages/macpaw-schema-context-bundle)
```

###  Alternatives

[sylius/sylius

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

8.4k5.6M651](/packages/sylius-sylius)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[pentatrion/vite-bundle

Vite integration for your Symfony app

2755.3M13](/packages/pentatrion-vite-bundle)[sulu/sulu

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

1.3k1.3M152](/packages/sulu-sulu)[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)[contao/core-bundle

Contao Open Source CMS

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

PHPackages © 2026

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