PHPackages                             cosmologist/symfony-common-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. [Database &amp; ORM](/categories/database)
4. /
5. cosmologist/symfony-common-bundle

AbandonedArchivedSymfony-bundle[Database &amp; ORM](/categories/database)

cosmologist/symfony-common-bundle
=================================

Useful features for Symfony, Doctrine, Twig etc.

2.0.0(6y ago)2269MITPHPPHP &gt;=5.4

Since Sep 13Pushed 1y ago1 watchersCompare

[ Source](https://github.com/Cosmologist/SymfonyCommonBundle)[ Packagist](https://packagist.org/packages/cosmologist/symfony-common-bundle)[ RSS](/packages/cosmologist-symfony-common-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (1)Versions (18)Used By (0)

SymfonyCommonBundle
===================

[](#symfonycommonbundle)

Useful features for Symfony, Doctrine, Twig etc.

Debug
-----

[](#debug)

### Easy way to start debug with RunnerCommand

[](#easy-way-to-start-debug-with-runnercommand)

If you are using *PhpStorm*, then an easy way to use this feature is to create an external tool (*File-&gt; Settings-&gt; Tools-&gt; External Tools*) with parameters:

- Name: Runner
- Program: */usr/bin/php*
- Arguments: *-d xdebug.remote\_autostart=1 -d xdebug.remote\_enable=1 bin/console symfony-common:runner $FilePath$ $LineNumber$*
- Working Directory: *$ProjectFileDir$*

After that, select *Tools -&gt; External Tools -&gt; Runner* - the command will try to execute a function or method from where the cursor is currently located.
At this point, execution will not automatically stop at the specified location - you must manually set a breakpoint.

Doctrine
--------

[](#doctrine)

### Extra DBAL events

[](#extra-dbal-events)

*Cosmologist\\Bundle\\SymfonyCommonBundle\\Doctrine\\ExtraConnection* is Doctrine DBAL-connection wrapper that add useful features and methods to DBAL.

#### Activation

[](#activation)

Add the wrapper\_class parameter to the Doctrine DBAL connection configuration in config.yml to use:

```
default:
    driver: pdo_mysql
    dbname: ~
    user: ~
    password: ~
    host: ~
    wrapper_class: \Cosmologist\Bundle\SymfonyCommonBundle\Doctrine\ExtraConnection
```

#### Additional DBAL-events

[](#additional-dbal-events)

postBeginTransaction, postCommit, postRollback

#### Helper methods

[](#helper-methods)

*Connection::fetchAllIndexed* prepares and executes an SQL query and returns the result as an associative array, each row in the result set array is indexed by the value of the first column.

```
$connection->fetchAllIndexed('SELECT id, name FROM users');
// 1  => [id: 1, name: Ivan]
// 7  => [id: 7, name: Vasiliy]
// ...
```

### Doctrine Utils

[](#doctrine-utils)

Get Doctrine utils

```
$utils = $container->get(Cosmologist\Bundle\SymfonyCommonBundle\Doctrine\DoctrineUtils::class);
// or
$utils = $container->get('symfony_common.doctrine.utils');
```

Get real class of Doctrine entity (resolve entity proxy class)
Supports Doctrine &lt; 3.x and Doctrine &gt; 3.x

```
$entity = $entityManager->find(App\Entity\Foo::class, $identifier);
DoctrineUtils::getRealClass($entity); \\ "App\Entity\Foo"
DoctrineUtils::getRealClass(App\Entity\Foo::class); \\ "App\Entity\Foo"
```

Simple way to get doctrine entity metadata

```
$utils->getClassMetadata($entity);
$utils->getClassMetadata(Entity::class);
```

Get the target class name of the given association path (ie "contact.user") recursively

```
$doctrineUtils->getAssociationTargetClassRecursive('AppBundle/Entity/Company', 'contact.user'); // 'AppBundle/Entity/User'
```

Get entity identifier field name (does not support multiple identifiers - throws DoctrineUtilsException)

```
$utils->getEntitySingleIdentifierField($entity);
$utils->getEntitySingleIdentifierField(Entity::class);
```

Get entity identifier value (does not support multiple identifiers - throws DoctrineUtilsException)

```
$utils->getEntitySingleIdentifierValue($entity);
```

Determine if the object or FQCN is a Doctrine entity (under Doctrine control) or not

```
$utils->isEntity($entity);
```

Get the readable alias for the doctrine entity

```
$this->getEntityAlias(FooBundle\Entity\Bar\Baz::class); // 'foo.bar.baz'
$this->decodeEntityAlias('foo.bar.baz'); // 'FooBundle\Entity\Bar\Baz'
```

Perform recursively join operation of the given association path (ie "contact.user.type")

```
$qb = $entityManager->getRepository(Company::class)->createQueryBuilder('company');

# Recursive joins
DoctrineUtils::joinRecursive($qb, 'contact.user.type');
// equivalent to
$qb
  ->join('company.contact', 'contact')
  ->join('contact.user', 'user')
  ->join('user.type', 'type');
```

> **Attention**: method doesn't care about alias uniqueness

Add a join to the query once

```
// Adds join and returns an alias of added join
DoctrineUtils::joinOnce($qb, 'contact.user', 'u1'); // "u1"

// If a join with specified parameters exists then only returns an alias of existed join
DoctrineUtils::joinOnce($qb, 'contact.user', 'u2'); // "u1"
```

Merge multiple `Doctrine\Common\Collections\Criteria` into a one `Doctrine\Common\Collections\Criteria`

```
$resultCriteria = DoctrineUtils::mergeCriteria($firstCriteria, $secondCriteria);
```

Routing
-------

[](#routing)

Forwards to another URI.
Like *Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller::forward*, but using URI.

```
$utils = $container->get('symfony_common.routing.utils');

$utils->forwardToUri('/products/programmers-t-shirts');
// or
$utils->forwardToUri('https://myshop.com/products/programmers-t-shirts');
```

Security
--------

[](#security)

### Command for interactive setup ACLs and ACEs

[](#command-for-interactive-setup-acls-and-aces)

```
bin/console symfony-common:acl:set
```

### ROLE\_SUPER\_USER

[](#role_super_user)

*Cosmologist\\Bundle\\SymfonyCommonBundle\\Security\\Voter\\SuperUserRoleVoter* adds a special role "ROLE\_SUPER\_USER" which effectively bypasses any, and all security checks.

### The service Crypto

[](#the-service-crypto)

The service `Crypto` provides functions for the *simple symmetric encryption*.
The *framework.secret* used as a key to encryption.

```
$crypto = $container->get(Cosmologist\Bundle\SymfonyCommonBundle\Security\Crypto::class);
$crypto->decrypt($crypto->encrypt('The sensitive string')); // 'The sensitive string'
```

Dependency Injection
--------------------

[](#dependency-injection)

### Convenient way to get a Reference to a Doctrine DBAL connection

[](#convenient-way-to-get-a-reference-to-a-doctrine-dbal-connection)

```
DependencyInjectionUtils::getDoctrineDbalConnectionReference('default'); // doctrine.dbal.default_connection
```

### Convenient way to get a Reference to a Doctrine EntityManager

[](#convenient-way-to-get-a-reference-to-a-doctrine-entitymanager)

```
DependencyInjectionUtils::getDoctrineOrmEntityManagerReference('default'); // doctrine.orm.default_entity_manager
```

### Store key as attribute in configuration

[](#store-key-as-attribute-in-configuration)

Useful for:

- to simplify your configuration
- to avoid problem of losing the key when you merge config across files ([Symfony Issue #29817](https://github.com/symfony/symfony/issues/29817))

Usage:

```
# AppBundle\DependencyInjection\Configuration.php
...
use Cosmologist\Bundle\SymfonyCommonBundle\DependencyInjection\DependencyInjectionUtils;
...
->arrayNode('events')
    ->beforeNormalization()
        ->always(ConfigurationUtils::useKeyAsAttribute('server'))
    ->end()
    ->prototype('array')
...
```

Config like this:

```
something:
  servers:
     serverA:
       username: userA
       password: passwordA
     serverB:
       username: userB
       password: passwordB

```

comes out like:

```
servers [
   serverA => [username: userA, password: passwordA, server: serverA],
   serverB => [username: userB, password: passwordB, server: serverB],
 ]

```

#### ServiceBridge

[](#servicebridge)

A convenient way to dynamically access symfony services.

#### Call Symfony services over HTTP

[](#call-symfony-services-over-http)

##### Include routing.yml

[](#include-routingyml)

```
# app/config/routing.yml
admin.service:
  resource: "@SymfonyCommonBundle/Resources/config/routing.yml"
  prefix:   /admin

```

##### Send POST-request

[](#send-post-request)

URL example:
`yourdomain.com/bridge/mybundle.foo/bar`
or
`yourdomain.com/bridge/MyBundle\Foo/bar`

- **/bridge** is a ServiceBridge route suffix
- **mybundle.foo** (or **MyBundle\\Foo**) is a service name
- **process** is service method name

Method arguments must be passed as POST parameters. ServiceBridge automatically fetches a Doctrine entity if the method expects an argument of the entity (the hint type of the argument).

The method arguments should be passed as POST-parameters.
ServiceBridge fetch entity from Doctrine automatically, by the identifier from request, if method expects entity argument (argument type-hint).

**Caution**: Use security [access\_control](https://symfony.com/doc/current/security/access_control.html) option to restrict access to the service controller.

##### Return types to response types map

[](#return-types-to-response-types-map)

- array|object -&gt; json
- binary string -&gt; response with content-disposition=attachment and binary content-type
- another scalar -&gt; simple response

### Static access to the service container from anywhere

[](#static-access-to-the-service-container-from-anywhere)

```
use Cosmologist\Bundle\SymfonyCommonBundle\DependencyInjection\ContainerStatic;

ContainerStatic::getContainer();
ContainerStatic::get('serivice_id');
ContainerStatic::getParameter('parameter_id');
```

Twig
----

[](#twig)

### Pagination template (Bootstrap friendly)

[](#pagination-template-bootstrap-friendly)

```
{% include '@SymfonyCommon/pagination.html.twig' with { page: current_page, count: items_total, limit: items_per_page } %}

{# Parameters:
   * page (int) : The current page you are in
   * limit (int): Number of records to display per page
   * count (int): Total count of records
   * currentFilters (array)(optional) : associative array that contains route-arguments #}
```

### Inject any callable to the Twig

[](#inject-any-callable-to-the-twig)

```
# app/config/config.yml

symfony_common:
  twig:
    php_extension:
      filters:
          - strip_tags # register php "strip_tags" function as twig "strip_tags" filter
          -
            foo_bar: # register static method MyApp\Foo::bar as twig filter "foo_bar"
                  - MyApp\Foo
                  - bar
      functions:
          - time # register php "time" function as twig "time" function
```

See also: [umpirsky/twig-php-function](https://github.com/umpirsky/twig-php-function)

Monolog
-------

[](#monolog)

### Monolog activation strategy for Symfony 3.x to skip the 404 HttpException records.

[](#monolog-activation-strategy-for-symfony-3x-to-skip-the-404-httpexception-records)

Monolog NotFoundActivationStrategy (activation\_strategy, excluded\_404s and excluded\_http\_codes options) does not work in Symfony 3.0 as currently monolog-bundle injects a reference to request from the service container into the NotFoundActivationStrategy.

- [Issue #166](https://github.com/symfony/monolog-bundle/issues/166#issuecomment-221725696)

#### TODO

[](#todo)

- Other HTTP-codes support
- Configure default actionLevel value via Configuration

#### Usage

[](#usage)

```
    main:
      type:                fingers_crossed
      handler:             grouped
       activation_strategy: symfony_common.monolog.fingers_crossed.ignore_http_not_found_activation_strategy
```

BrowserKit
----------

[](#browserkit)

Add the specified HTTP-header to the prepared BrowserKit request

```
use Cosmologist\Bundle\SymfonyCommonBundle\BrowserKit\BrowserKitUtils;

/** @var \Symfony\Component\BrowserKit\Client $cient */

BrowserKitUtils::addHeader($client, 'header-name', 'header-value');
```

Dump configuration files for external related applications
----------------------------------------------------------

[](#dump-configuration-files-for-external-related-applications)

Useful when you want to deduplicate application parameters (like db-connections, paths etc) and store related external applications configurations (backup-systems, crontab etc) inside the project.

### Example

[](#example)

Configuration for abstract backup-system

Configuration file template:

```
# app/config/external/dist/backup.yml.twig
backup:
    mysql:
        {{ name }}
        {{ user }}
        {{ password }}
    compress: yes
    sync-to: amazon-s3
```

Define parameters for dist:

```
# app/config/config.yml
symfony_common:
    external_config:
        superbackup:
            name: '%doctrine.connection.default.database_name%'
            user: '%doctrine.connection.default.database_user%'
            password: '%doctrine.connection.default.database_password%'
```

Run dumper:

```
php app/console symfony-common:external-config:dump superbackup backup.yml.twig --env=prod --no-debug

```

And config should be dumped to *app/cache/prod/external\_config/backup.yml* (without *.twig* extension)

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance34

Infrequent updates — may be unmaintained

Popularity14

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 57.9% 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 ~19 days

Total

17

Last Release

2488d ago

Major Versions

1.8.0 → 2.0.02019-07-17

### Community

Maintainers

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

---

Top Contributors

[![Cosmologist](https://avatars.githubusercontent.com/u/966525?v=4)](https://github.com/Cosmologist "Cosmologist (11 commits)")[![4562448](https://avatars.githubusercontent.com/u/70571767?v=4)](https://github.com/4562448 "4562448 (8 commits)")

---

Tags

doctrinedoctrine-dbaldoctrine-extensiondoctrine-ormphpsymfonysymfony-bundletwigtwig-extensiontwig-filterphpsymfonybundletwigdoctrine

### Embed Badge

![Health badge](/badges/cosmologist-symfony-common-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/cosmologist-symfony-common-bundle/health.svg)](https://phpackages.com/packages/cosmologist-symfony-common-bundle)
```

###  Alternatives

[omines/datatables-bundle

Symfony DataTables Bundle with native Doctrine ORM, Elastica and MongoDB support

2851.4M6](/packages/omines-datatables-bundle)[kucharovic/money-bundle

This bundle provides integration for Money library in your Symfony project.

2253.7k](/packages/kucharovic-money-bundle)[prezent/doctrine-translatable-bundle

Integrate the doctrine-translatable extension in Symfony

14698.4k5](/packages/prezent-doctrine-translatable-bundle)[farmatholin/segment-io-bundle

Segment.io php lib

11257.4k](/packages/farmatholin-segment-io-bundle)[vasek-purchart/doctrine-date-time-immutable-types-bundle

Bundle integration of Doctrine DateTimeImmutable types for Symfony

1085.6k](/packages/vasek-purchart-doctrine-date-time-immutable-types-bundle)[andanteproject/soft-deletable-bundle

A Symfony Bundle to handle soft deletable with Doctrine Entities

1028.3k](/packages/andanteproject-soft-deletable-bundle)

PHPackages © 2026

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