<NME> Repository.php
<BEF> <?php

namespace Bolt\Storage;

use ArrayObject;
use Bolt\Events\HydrationEvent;
use Bolt\Events\StorageEvent;
use Bolt\Events\StorageEvents;
use Bolt\Storage\Entity\Builder;
use Bolt\Storage\Entity\Entity;
use Bolt\Storage\Field\Type\FieldTypeInterface;
use Bolt\Storage\Mapping\ClassMetadata;
use Bolt\Storage\Query\QueryInterface;
use Doctrine\Common\Persistence\ObjectRepository;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Query\QueryBuilder;

/**
 * A default repository class that other repositories can inherit to provide more specific features.
 */
class Repository implements ObjectRepository
{
    /** @var EntityManager */
    public $em;
    /** @var ClassMetadata */
    public $_class;
    /** @var string */
    public $entityName;
    /** @var Builder */
    public $builder;

    /**
     * Initializes a new Repository.
     *
     * @param EntityManager $em            the EntityManager to use
     * @param ClassMetadata $classMetadata the class descriptor
     */
    public function __construct($em, ClassMetadata $classMetadata)
    {
        $this->em = $em;
        $this->_class = $classMetadata;
        $this->entityName = $classMetadata->getName();
    }

    /**
     * Creates a new empty entity and passes the supplied data to the constructor.
     *
     * @param array         $params
     * @param ClassMetadata $metadata
     *
     * @return Entity
     */
    public function create($params = [], ClassMetadata $metadata = null)
    {
        $params = new ArrayObject($params);
        $builder = $this->getEntityBuilder();
        /** @var Entity $entity */
        $entity = $builder->getEntity();
        $preEventArgs = new HydrationEvent($params, ['entity' => $entity, 'repository' => $this]);
        $this->event()->dispatch(StorageEvents::PRE_HYDRATE, $preEventArgs);
        $builder->create($params, $entity);
        $postEventArgs = new HydrationEvent($params, ['entity' => $entity, 'repository' => $this]);
        $this->event()->dispatch(StorageEvents::POST_HYDRATE, $postEventArgs);

        return $entity;
    }

    /**
     * Creates a new QueryBuilder instance that is prepopulated for this entity name.
     *
     * @param string $alias
        if (empty($alias)) {
            $select = '*';
        } else {
            $select = $alias.'.*';
        }

        return $this->em->createQueryBuilder()
        }

        if (empty($alias)) {
            $select = '*';
        } else {
            $select = $alias . '.*';
        }
    public function find($id)
    {
        $qb = $this->getLoadQuery();
        $result = $qb->where($this->getAlias().'.id = :id')
            ->setParameter('id', $id)
            ->execute()
            ->fetch();
     * Return the number of rows used in this repository table.
     *
     * @return int
     */
    public function count()
    {
        $qb = $this->getLoadQuery()
            ->select('COUNT(' . $this->getAlias() . '.id) as count')
            ->resetQueryParts(['groupBy', 'join'])
        ;
        $result = $qb->execute()->fetchColumn(0);

        return (int) $result;
    }

    /**
     * {@inheritdoc}
     */
    public function find($id)
    {
        $qb = $this->getLoadQuery();
        $result = $qb->where($this->getAlias() . '.id = :id')
            ->setParameter('id', $id)
            ->execute()
            ->fetch();

        if ($result) {
            return $this->hydrate($result, $qb);
        }

        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function findAll()
    {
        return $this->findBy([]);
    }

    /**
     * {@inheritdoc}
     */
    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
    {
        $qb = $this->findWithCriteria($criteria, $orderBy, $limit, $offset);

        $result = $qb->execute()->fetchAll();

        if ($result) {
            return $this->hydrateAll($result, $qb);
        }

        return false;
    }

    /**
     * Finds a single object by a set of criteria.
     *
     * @param array $criteria the criteria
     * @param array $orderBy
     *
     * @return object|false the object
     */
    public function findOneBy(array $criteria, array $orderBy = null)
    {
        $qb = $this->findWithCriteria($criteria, $orderBy);
        $result = $qb->execute()->fetch();

        if ($result) {
            return $this->hydrate($result, $qb);
        }

        return false;
    }

    /**
     * Internal method to build a basic select, returns QB object.
     *
     * @param array $criteria
     * @param array $orderBy
     * @param int   $limit
     * @param int   $offset
     *
     * @return QueryBuilder
     */
    protected function findWithCriteria(array $criteria, array $orderBy = null, $limit = null, $offset = null)
    {
        $qb = $this->getLoadQuery();
        foreach ($criteria as $col => $val) {
            if (is_array($val)) {
                $qb->andWhere($this->getAlias() . ".$col IN(:$col)");
                $qb->setParameter(":$col", $val, Connection::PARAM_INT_ARRAY);
            } else {
                $qb->andWhere($this->getAlias() . ".$col = :$col");
                $qb->setParameter(":$col", $val);
            }
        }
        if ($orderBy) {
            $qb->orderBy($orderBy[0], $orderBy[1]);
        }
        if ($limit) {
            $qb->setMaxResults($limit);
        }
        if ($offset) {
            $qb->setFirstResult($offset);
        }

        return $qb;
    }

    /**
     * Method to hydrate and return a QueryBuilder query.
     *
     * @param QueryBuilder $query
     *
     * @return array Entity
     */
    public function findWith(QueryBuilder $query)
    {
        $this->load($query);

        $result = $query->execute()->fetchAll();
        if ($result) {
            return $this->hydrateAll($result, $query);
        }

        return [];
    }

    /**
     * Method to hydrate and return a single QueryBuilder result.
     *
     * @param QueryBuilder $query
     *
     * @return Entity|false
     */
    public function findOneWith(QueryBuilder $query)
    {
        $this->load($query);
        $result = $query->execute()->fetch();
        if ($result) {
            return $this->hydrate($result, $query);
        }

        return false;
    }

    /**
     * Method to execute query from a Bolt QueryInterface object
     * The query is passed to the pre-load handlers then built into a
     * QueryBuilder instance that can be executed.
     *
     * @param QueryInterface $query [description]
     *
     * @return array Entity | false
     */
    public function queryWith(QueryInterface $query)
    {
        $this->query($query);
        $queryBuilder = $query->build();

        return $this->findWith($queryBuilder);
    }

    /**
     * Internal method to initialise and return a QueryBuilder instance.
     * Note that the metadata fields will be passed the instance to modify where appropriate.
     *
     * @return QueryBuilder
     */
    protected function getLoadQuery()
    {
        $qb = $this->createQueryBuilder();
        $this->load($qb);

        return $qb;
    }

    /**
     * Internal method to run load method on each field for the managed entity.
     *
     * Takes a QueryBuilder instance as input
     *
     * @param QueryBuilder $query
     */
    protected function load(QueryBuilder $query)
    {
        $metadata = $this->getClassMetadata();
        foreach ($metadata->getFieldMappings() as $field) {
            $fieldtype = $this->getFieldManager()->get($field['fieldtype'], $field);
            if ($fieldtype instanceof FieldTypeInterface) {
                $fieldtype->load($query, $metadata);
            }
        }
    }

    /**
     * Internal method to run query method on each field for the managed entity.
     *
     * Takes a QueryInterface instance as input
     *
     * @param QueryInterface $query
     */
    protected function query(QueryInterface $query)
    {
        $metadata = $this->getClassMetadata();

        foreach ($metadata->getFieldMappings() as $field) {
            $fieldtype = $this->getFieldManager()->get($field['fieldtype'], $field);
            if ($fieldtype instanceof FieldTypeInterface) {
                $fieldtype->query($query, $metadata);
            }
        }
    }

    /**
     * Internal method to run persist method on each field for the managed entity.
     *
     * Takes a QuerySet instance as input
     *
     * @param QuerySet $queries
     * @param Entity   $entity
     * @param array    $exclusions
     */
    protected function persist(QuerySet $queries, $entity, $exclusions = [])
    {
        $metadata = $this->getClassMetadata();

        foreach ($metadata->getFieldMappings() as $field) {
            $fieldName = $field['fieldname'];
            if (in_array($fieldName, $exclusions)) {
                continue;
            }
            // Don't add field to the persistence query if it is not an entity
            // property, and on UPDATE only
            if (!isset($entity->$fieldName) && $entity->getId() !== null) {
                continue;
            }

            $field = $this->getFieldManager()->get($field['fieldtype'], $field);
            if ($field instanceof FieldTypeInterface) {
                $field->persist($queries, $entity);
            }
        }
    }

    /**
     * Deletes a single object.
     *
     * @param object $entity the entity to delete
     *
     * @return bool
     */
    public function delete($entity)
    {
        $event = new StorageEvent($entity);
        $this->event()->dispatch(StorageEvents::PRE_DELETE, $event);
        $qb = $this->em->createQueryBuilder()
            ->delete($this->getTableName())
            ->where('id = :id')
            ->setParameter('id', $entity->getId());

        $response = $qb->execute();
        $event = new StorageEvent($entity);
        $this->event()->dispatch(StorageEvents::POST_DELETE, $event);

        return $response;
    }

    /**
     * Saves a single object.
     *
     * @param object $entity the entity to save
     * @param bool   $silent Suppress events
     *
     * @return bool
     */
    public function save($entity, $silent = null)
    {
        try {
            if ($existing = $entity->getId()) {
                $creating = false;
            } else {
                $creating = true;
            }
        } catch (\Exception $e) {
            $creating = $existing = false;
        }

        if ($silent === null) {
            $event = new StorageEvent($entity, ['create' => $creating]);
            $this->event()->dispatch(StorageEvents::PRE_SAVE, $event);
        }

        if ($existing) {
            $response = $this->update($entity);
        } else {
            $response = $this->insert($entity);
        }

        if ($silent === null) {
            $this->event()->dispatch(StorageEvents::POST_SAVE, $event);
        }

        return $response;
    }

    /**
     * Saves a new object into the database.
     *
     * @param object $entity the entity to insert
     *
     * @return bool
     */
    public function insert($entity)
    {
        $querySet = new QuerySet();
        $qb = $this->em->createQueryBuilder();
        $qb->insert($this->getTableName());
        $querySet->append($qb);
        $this->persist($querySet, $entity, ['id']);

        $result = $querySet->execute();

        // Try and set the entity id using the response from the insert
        try {
            $entity->setId($querySet->getInsertId());
        } catch (\Exception $e) {
        }

        return $result;
    }

    /**
     * Updates an object into the database.
     *
     * @param object   $entity     the entity to update
     * @param string[] $exclusions Ignore updates to these fields
     *
     * @return bool
     */
    public function update($entity, $exclusions = [])
    {
        $querySet = new QuerySet();
        $querySet->setParentId($entity->getId());
        $qb = $this->em->createQueryBuilder();
        $qb->update($this->getTableName())
            ->where('id = :id')
            ->setParameter('id', $entity->getId());
        $querySet->append($qb);
        $this->persist($querySet, $entity, $exclusions);

        return $querySet->execute();
    }

    /**
     * Internal method to hydrate an Entity Object from fetched data.
     *
     * @param array        $data
     * @param QueryBuilder $qb
     *
     * @return mixed
     */
    protected function hydrate(array $data, QueryBuilder $qb)
    {
        $entity = $this->getEntityBuilder()->getEntity();

        $data = new ArrayObject($data);
        $preEventArgs = new HydrationEvent($data, ['entity' => $entity, 'repository' => $this]);
        $this->event()->dispatch(StorageEvents::PRE_HYDRATE, $preEventArgs);

        $this->getEntityBuilder()->createFromDatabaseValues($data, $entity);

        $postEventArgs = new HydrationEvent($entity, ['entity' => $entity, 'data' => $data, 'repository' => $this]);
        $this->event()->dispatch(StorageEvents::POST_HYDRATE, $postEventArgs);

        return $entity;
    }

    /**
     * Internal method to hydrate an array of Entity Objects from fetched data.
     *
     * @param array        $data
     * @param QueryBuilder $qb
     *
     * @return mixed
     */
    protected function hydrateAll(array $data, QueryBuilder $qb)
    {
        $rows = [];
        foreach ($data as $row) {
            $rows[] = $this->hydrate($row, $qb);
        }

        return $rows;
    }

    /**
     * Internal method to refresh (re-hydrate an entity) using
     * the field setters.
     *
     * @param  $entity
     */
    protected function refresh($entity)
    {
        $this->getEntityBuilder()->refresh($entity);
    }

    /**
     * Fetches FieldManager instance from the EntityManager.
     *
     * @return FieldManager
     */
    public function getFieldManager()
    {
        return $this->em->getFieldManager();
    }

    /**
     * @return Builder $builder
     */
    public function getEntityBuilder()
    {
        $builder = $this->em->getEntityBuilder();
        $builder->setClass($this->getEntityName());
        $builder->setClassMetadata($this->getClassMetadata());

        return $builder;
    }

    /**
     * @return string
     */
    public function getEntityName()
    {
        return $this->entityName;
    }

    /**
     * @return string
     */
    public function getClassName()
    {
        return $this->getEntityName();
    }

    /**
     * @return string
     */
    public function getTableName()
    {
        return $this->getClassMetadata()->getTableName();
    }

    /**
     * @return string
     */
    public function getAlias()
    {
        return $this->getClassMetadata()->getAliasName();
    }

    /**
     * @return EntityManager
     */
    public function getEntityManager()
    {
        return $this->em;
    }

    /**
     * Getter for class metadata.
     *
     * @return ClassMetadata
     */
    public function getClassMetadata()
    {
        return $this->_class;
    }

    /**
     * Shortcut method to fetch the Event Dispatcher.
     *
     * @return \Symfony\Component\EventDispatcher\EventDispatcherInterface
     */
    public function event()
    {
        return $this->getEntityManager()->getEventManager();
    }
}

<MSG> Spaces around string concat operator
<DFF> @@ -72,7 +72,7 @@ class Repository implements ObjectRepository
         if (empty($alias)) {
             $select = '*';
         } else {
-            $select = $alias.'.*';
+            $select = $alias . '.*';
         }
 
         return $this->em->createQueryBuilder()
@@ -86,7 +86,7 @@ class Repository implements ObjectRepository
     public function find($id)
     {
         $qb = $this->getLoadQuery();
-        $result = $qb->where($this->getAlias().'.id = :id')
+        $result = $qb->where($this->getAlias() . '.id = :id')
             ->setParameter('id', $id)
             ->execute()
             ->fetch();

{'commit': 'diff --git a/src/AccessControl/Token/Generator.php b/src/AccessControl/Token/Generator.php\nindex 19846cdeb..ac6db6f03 100644\n--- a/src/AccessControl/Token/Generator.php\n+++ b/src/AccessControl/Token/Generator.php\n@@ -27,7 +27,7 @@ class Generator\n         $hostName = $cookieOptions[\'browseragent\'] ? $userAgent : \'\';\n         $userAgent = $cookieOptions[\'httphost\'] ? $hostName : \'\';\n \n-        $this->token = md5($username.$salt.$remoteIP.$hostName.$userAgent);\n+        $this->token = md5($username . $salt . $remoteIP . $hostName . $userAgent);\n     }\n \n     public function __toString()\ndiff --git a/src/Asset/Injector.php b/src/Asset/Injector.php\nindex 1e06807c3..2ffe72a32 100644\n--- a/src/Asset/Injector.php\n+++ b/src/Asset/Injector.php\n@@ -318,6 +318,6 @@ class Injector\n      */\n     private function tagSoup(AssetInterface $asset, $rawHtml)\n     {\n-        return $rawHtml. (string) $asset . "\\n";\n+        return $rawHtml . (string) $asset . "\\n";\n     }\n }\ndiff --git a/src/Cache.php b/src/Cache.php\nindex 05056e3e5..9725fc064 100644\n--- a/src/Cache.php\n+++ b/src/Cache.php\n@@ -170,7 +170,7 @@ class Cache extends FilesystemCache\n      */\n     private function updateCacheVersion()\n     {\n-        $version = md5($this->app[\'bolt_version\'].$this->app[\'bolt_name\']);\n+        $version = md5($this->app[\'bolt_version\'] . $this->app[\'bolt_name\']);\n         file_put_contents($this->getDirectory() . \'/.version\', $version);\n     }\n }\ndiff --git a/src/Configuration/Check/DirectoryAccess.php b/src/Configuration/Check/DirectoryAccess.php\nindex b26622da7..e08436cfa 100644\n--- a/src/Configuration/Check/DirectoryAccess.php\n+++ b/src/Configuration/Check/DirectoryAccess.php\n@@ -41,7 +41,7 @@ class DirectoryAccess extends BaseCheck implements ConfigurationCheckInterface\n             $directory = $this->app[\'resources\']->getPath($directory);\n \n             try {\n-                $tmpfile = $directory .\'/.check\';\n+                $tmpfile = $directory . \'/.check\';\n \n                 if ($fs->exists($directory) && $fs->touch($tmpfile) === null && $fs->remove($tmpfile) === null) {\n                     $this->createResult()->pass()->setMessage("Directory $directory is writable.");\ndiff --git a/src/Configuration/YamlUpdater.php b/src/Configuration/YamlUpdater.php\nindex cb1ddea34..256252ff5 100644\n--- a/src/Configuration/YamlUpdater.php\n+++ b/src/Configuration/YamlUpdater.php\n@@ -83,7 +83,7 @@ class YamlUpdater\n     public function change($key, $value, $makebackup = true)\n     {\n         $pattern = str_replace("/", ":.*", $key);\n-        preg_match_all(\'/^\'.$pattern.\'(:\\s*)/mis\', $this->file->read(), $matches,  PREG_OFFSET_CAPTURE);\n+        preg_match_all(\'/^\' . $pattern . \'(:\\s*)/mis\', $this->file->read(), $matches,  PREG_OFFSET_CAPTURE);\n \n         if (count($matches[0]) > 0 && count($matches[1])) {\n             $index = $matches[1][0][1] + strlen($matches[1][0][0]);\n@@ -92,7 +92,7 @@ class YamlUpdater\n         }\n \n         $line = substr_count($this->file->read(), "\\n", 0, $index);\n-        $this->yaml[$line] = preg_replace(\'/^(.*):(.*)/\', "$1: ".$this->prepareValue($value), $this->yaml[$line]);\n+        $this->yaml[$line] = preg_replace(\'/^(.*):(.*)/\', "$1: " . $this->prepareValue($value), $this->yaml[$line]);\n \n         return $this->save($makebackup);\n     }\ndiff --git a/src/Helpers/Str.php b/src/Helpers/Str.php\nindex d8b22c30b..0aa443cbc 100644\n--- a/src/Helpers/Str.php\n+++ b/src/Helpers/Str.php\n@@ -25,12 +25,12 @@ class Str\n             $extrachars = preg_quote($extrachars, $delim);\n         }\n         if ($strict) {\n-            $slugify = Slugify::create(\'/[^a-z0-9_\'.$extrachars.\' -]+/\');\n+            $slugify = Slugify::create(\'/[^a-z0-9_\' . $extrachars . \' -]+/\');\n             $str = $slugify->slugify($str, \'\');\n             $str = str_replace(\' \', \'-\', $str);\n         } else {\n             // Allow Uppercase and don\'t convert spaces to dashes\n-            $slugify = Slugify::create(\'/[^a-zA-Z0-9_.,\'.$extrachars.\' -]+/\', [\'lowercase\' => false]);\n+            $slugify = Slugify::create(\'/[^a-zA-Z0-9_.,\' . $extrachars . \' -]+/\', [\'lowercase\' => false]);\n             $str = $slugify->slugify($str, \'\');\n         }\n \ndiff --git a/src/Legacy/Storage.php b/src/Legacy/Storage.php\nindex 84644459a..14c98ab0e 100644\n--- a/src/Legacy/Storage.php\n+++ b/src/Legacy/Storage.php\n@@ -1126,7 +1126,7 @@ class Storage\n \n         try {\n             foreach ($recordIds as $recordId) {\n-                $content = $this->getContent("$contenttypeSlug/".$recordId[\'id\'], [\'hydrate\' => false, \'returnsingle\' => true]);\n+                $content = $this->getContent($contenttypeSlug . \'/\' . $recordId[\'id\'], [\'hydrate\' => false, \'returnsingle\' => true]);\n \n                 $event = new StorageEvent($content, [\'contenttype\' => $contenttypeSlug, \'create\' => false]);\n                 $this->app[\'dispatcher\']->dispatch("timed.$type", $event);\ndiff --git a/src/Storage/ContentRequest/Edit.php b/src/Storage/ContentRequest/Edit.php\nindex 98c738146..e910d7d7f 100644\n--- a/src/Storage/ContentRequest/Edit.php\n+++ b/src/Storage/ContentRequest/Edit.php\n@@ -166,7 +166,7 @@ class Edit\n \n         foreach ($contentType[\'relations\'] as $relationName => $relationValues) {\n             $repo = $this->em->getRepository($relationName);\n-            $relationConfig = $this->config->get(\'contenttypes/\'.$relationName, []);\n+            $relationConfig = $this->config->get(\'contenttypes/\' . $relationName, []);\n \n             $list[$relationName] = $repo->getSelectList($relationConfig, $relationValues[\'order\']);\n         }\ndiff --git a/src/Storage/Entity/Builder.php b/src/Storage/Entity/Builder.php\nindex 301478157..ea2a80973 100644\n--- a/src/Storage/Entity/Builder.php\n+++ b/src/Storage/Entity/Builder.php\n@@ -178,7 +178,7 @@ class Builder\n \n         foreach ((array) $fields as $key => $mapping) {\n             $fieldType = $this->fieldManager->get($mapping[\'fieldtype\'], $mapping);\n-            $getter = \'get\'.ucfirst($key);\n+            $getter = \'get\' . ucfirst($key);\n             $value = $entity->$getter();\n             if ($value) {\n                 call_user_func_array([$fieldType, \'set\'], [$entity, $value]);\ndiff --git a/src/Storage/Entity/Entity.php b/src/Storage/Entity/Entity.php\nindex 36b70ed3e..6094d1749 100644\n--- a/src/Storage/Entity/Entity.php\n+++ b/src/Storage/Entity/Entity.php\n@@ -17,7 +17,7 @@ abstract class Entity implements ArrayAccess, JsonSerializable\n     public function __construct($data = [])\n     {\n         foreach ($data as $key => $value) {\n-            $method = \'set\'.ucfirst($key);\n+            $method = \'set\' . ucfirst($key);\n             $this->$method($value);\n         }\n     }\ndiff --git a/src/Storage/Entity/EntityArrayAccessTrait.php b/src/Storage/Entity/EntityArrayAccessTrait.php\nindex 46e95608d..e22addbb9 100644\n--- a/src/Storage/Entity/EntityArrayAccessTrait.php\n+++ b/src/Storage/Entity/EntityArrayAccessTrait.php\n@@ -18,7 +18,7 @@ trait EntityArrayAccessTrait\n      */\n     public function offsetSet($offset, $value)\n     {\n-        $accessor = \'set\'.ucfirst($offset);\n+        $accessor = \'set\' . ucfirst($offset);\n         $this->$accessor($value);\n     }\n \n@@ -29,7 +29,7 @@ trait EntityArrayAccessTrait\n      */\n     public function offsetExists($offset)\n     {\n-        $accessor = \'get\'.ucfirst($offset);\n+        $accessor = \'get\' . ucfirst($offset);\n         $result = $this->$accessor();\n \n         return !empty($result);\n@@ -42,7 +42,7 @@ trait EntityArrayAccessTrait\n      */\n     public function offsetUnset($offset)\n     {\n-        $accessor = \'set\'.ucfirst($offset);\n+        $accessor = \'set\' . ucfirst($offset);\n         $this->$accessor(null);\n     }\n \n@@ -53,7 +53,7 @@ trait EntityArrayAccessTrait\n      */\n     public function offsetGet($offset)\n     {\n-        $accessor = \'get\'.ucfirst($offset);\n+        $accessor = \'get\' . ucfirst($offset);\n \n         return $this->$accessor();\n     }\ndiff --git a/src/Storage/Entity/EntitySerializeTrait.php b/src/Storage/Entity/EntitySerializeTrait.php\nindex a563d4c8a..2ab118990 100644\n--- a/src/Storage/Entity/EntitySerializeTrait.php\n+++ b/src/Storage/Entity/EntitySerializeTrait.php\n@@ -20,12 +20,12 @@ trait EntitySerializeTrait\n             if (in_array($k, $this->_internal)) {\n                 continue;\n             }\n-            $method = \'serialize\'.$k;\n+            $method = \'serialize\' . $k;\n             $data[$k] = $this->$method();\n         }\n \n         foreach ($this->_fields as $k => $v) {\n-            $method = \'serialize\'.$k;\n+            $method = \'serialize\' . $k;\n             $data[$k] = $this->$method();\n         }\n \ndiff --git a/src/Storage/Entity/MagicAttributeTrait.php b/src/Storage/Entity/MagicAttributeTrait.php\nindex 1fb397bf2..aab16c623 100644\n--- a/src/Storage/Entity/MagicAttributeTrait.php\n+++ b/src/Storage/Entity/MagicAttributeTrait.php\n@@ -13,7 +13,7 @@ trait MagicAttributeTrait\n \n     public function __get($key)\n     {\n-        $method = \'get\'.ucfirst($key);\n+        $method = \'get\' . ucfirst($key);\n         if (in_array($key, $this->getFields())) {\n             return $this->$method();\n         }\n@@ -21,7 +21,7 @@ trait MagicAttributeTrait\n \n     public function __set($key, $value)\n     {\n-        $method = \'set\'.ucfirst($key);\n+        $method = \'set\' . ucfirst($key);\n         $this->$method($value);\n     }\n \n@@ -58,7 +58,7 @@ trait MagicAttributeTrait\n         }\n \n         if (strncasecmp($method, \'serialize\', 9) == 0) {\n-            $method = \'get\'.substr($method, 9);\n+            $method = \'get\' . substr($method, 9);\n \n             return $this->$method();\n         }\ndiff --git a/src/Storage/Entity/TemplateFields.php b/src/Storage/Entity/TemplateFields.php\nindex b591d3e4d..b117e4c35 100644\n--- a/src/Storage/Entity/TemplateFields.php\n+++ b/src/Storage/Entity/TemplateFields.php\n@@ -15,7 +15,7 @@ class TemplateFields extends Entity\n      */\n     public function get($key)\n     {\n-        $accessor = \'get\'.ucfirst($key);\n+        $accessor = \'get\' . ucfirst($key);\n \n         return $this->$accessor();\n     }\ndiff --git a/src/Storage/Field/Collection/FieldCollection.php b/src/Storage/Field/Collection/FieldCollection.php\nindex ee7edcb64..d08f935b9 100644\n--- a/src/Storage/Field/Collection/FieldCollection.php\n+++ b/src/Storage/Field/Collection/FieldCollection.php\n@@ -95,7 +95,7 @@ class FieldCollection extends AbstractLazyCollection\n                 $fieldtype = $val->getFieldtype();\n                 $field = $this->em->getFieldManager()->getFieldFor($fieldtype);\n                 $type = $field->getStorageType();\n-                $typeCol = \'value_\'.$type->getName();\n+                $typeCol = \'value_\' . $type->getName();\n                 $val->setValue($val->$typeCol);\n                 $objects[$val->getName()] = $val;\n             }\ndiff --git a/src/Storage/Field/Type/FieldTypeBase.php b/src/Storage/Field/Type/FieldTypeBase.php\nindex f3387e23d..344982118 100644\n--- a/src/Storage/Field/Type/FieldTypeBase.php\n+++ b/src/Storage/Field/Type/FieldTypeBase.php\n@@ -72,7 +72,7 @@ abstract class FieldTypeBase implements FieldTypeInterface\n     {\n         $key = $this->mapping[\'fieldname\'];\n         $qb = &$queries[0];\n-        $valueMethod = \'serialize\'.ucfirst($key);\n+        $valueMethod = \'serialize\' . ucfirst($key);\n         $value = $entity->$valueMethod();\n \n         $type = $this->getStorageType();\n@@ -82,8 +82,8 @@ abstract class FieldTypeBase implements FieldTypeInterface\n         } else {\n             $value = $this->mapping[\'default\'];\n         }\n-        $qb->setValue($key, \':\'.$key);\n-        $qb->set($key, \':\'.$key);\n+        $qb->setValue($key, \':\' . $key);\n+        $qb->set($key, \':\' . $key);\n         $qb->setParameter($key, $value);\n     }\n \ndiff --git a/src/Storage/Field/Type/RelationType.php b/src/Storage/Field/Type/RelationType.php\nindex 5b9b8fd67..cd4e33787 100644\n--- a/src/Storage/Field/Type/RelationType.php\n+++ b/src/Storage/Field/Type/RelationType.php\n@@ -42,7 +42,7 @@ class RelationType extends FieldTypeBase\n             if ($filter->getKey() == $field) {\n \n                 // This gets the method name, one of andX() / orX() depending on type of expression\n-                $method = strtolower($filter->getExpressionObject()->getType()).\'X\';\n+                $method = strtolower($filter->getExpressionObject()->getType()) . \'X\';\n \n                 $newExpr = $query->getQueryBuilder()->expr()->$method();\n                 foreach ($filter->getParameters() as $k => $v) {\ndiff --git a/src/Storage/Field/Type/RepeaterType.php b/src/Storage/Field/Type/RepeaterType.php\nindex f560b7f3f..12dd67e67 100644\n--- a/src/Storage/Field/Type/RepeaterType.php\n+++ b/src/Storage/Field/Type/RepeaterType.php\n@@ -48,7 +48,7 @@ class RepeaterType extends FieldTypeBase\n     {\n         $this->normalize($entity);\n         $key = $this->mapping[\'fieldname\'];\n-        $accessor = \'get\'.ucfirst($key);\n+        $accessor = \'get\' . ucfirst($key);\n \n         $collection = $entity->$accessor();\n \n@@ -87,7 +87,7 @@ class RepeaterType extends FieldTypeBase\n     public function normalize($entity)\n     {\n         $key = $this->mapping[\'fieldname\'];\n-        $accessor = \'get\'.ucfirst($key);\n+        $accessor = \'get\' . ucfirst($key);\n \n         $outerCollection = $entity->$accessor();\n         $newVal = [];\n@@ -103,7 +103,7 @@ class RepeaterType extends FieldTypeBase\n                 }\n             }\n \n-            $setter = \'set\'.ucfirst($key);\n+            $setter = \'set\' . ucfirst($key);\n             $entity->$setter($collection);\n         }\n     }\n@@ -187,7 +187,7 @@ class RepeaterType extends FieldTypeBase\n             $repo = $this->em->getRepository(get_class($fieldValue));\n             $field = $this->getFieldType($fieldValue->getFieldname());\n             $type = $field->getStorageType();\n-            $typeCol = \'value_\'.$type->getName();\n+            $typeCol = \'value_\' . $type->getName();\n \n             $fieldValue->$typeCol = $fieldValue->getValue();\n             $fieldValue->setFieldtype($this->getFieldTypeName($fieldValue->getFieldname()));\n@@ -229,7 +229,7 @@ class RepeaterType extends FieldTypeBase\n             $repo = $this->em->getRepository(get_class($fieldValue));\n             $field = $this->getFieldType($fieldValue->getFieldname());\n             $type = $field->getStorageType();\n-            $typeCol = \'value_\'.$type->getName();\n+            $typeCol = \'value_\' . $type->getName();\n             $fieldValue->$typeCol = $fieldValue->getValue();\n \n             // This takes care of instances where an entity might be inserted, and thus not\n@@ -254,7 +254,7 @@ class RepeaterType extends FieldTypeBase\n     protected function getFieldType($field)\n     {\n         if (!isset($this->mapping[\'data\'][\'fields\'][$field][\'fieldtype\'])) {\n-            throw new FieldConfigurationException(\'Invalid repeating field configuration for \'.$field);\n+            throw new FieldConfigurationException(\'Invalid repeating field configuration for \' . $field);\n         }\n         $mapping = $this->mapping[\'data\'][\'fields\'][$field];\n         $setting = $mapping[\'fieldtype\'];\n@@ -272,7 +272,7 @@ class RepeaterType extends FieldTypeBase\n     protected function getFieldTypeName($field)\n     {\n         if (!isset($this->mapping[\'data\'][\'fields\'][$field][\'type\'])) {\n-            throw new FieldConfigurationException(\'Invalid repeating field configuration for \'.$field);\n+            throw new FieldConfigurationException(\'Invalid repeating field configuration for \' . $field);\n         }\n         $mapping = $this->mapping[\'data\'][\'fields\'][$field];\n \ndiff --git a/src/Storage/Field/Type/TaxonomyType.php b/src/Storage/Field/Type/TaxonomyType.php\nindex c060e7fe3..840f45997 100644\n--- a/src/Storage/Field/Type/TaxonomyType.php\n+++ b/src/Storage/Field/Type/TaxonomyType.php\n@@ -38,7 +38,7 @@ class TaxonomyType extends FieldTypeBase\n             if ($filter->getKey() == $field) {\n \n                 // This gets the method name, one of andX() / orX() depending on type of expression\n-                $method = strtolower($filter->getExpressionObject()->getType()).\'X\';\n+                $method = strtolower($filter->getExpressionObject()->getType()) . \'X\';\n \n                 $newExpr = $query->getQueryBuilder()->expr()->$method();\n                 foreach ($filter->getParameters() as $k => $v) {\n@@ -82,7 +82,7 @@ class TaxonomyType extends FieldTypeBase\n         }\n \n         $query\n-            ->addSelect($this->getPlatformGroupConcat("$field.slug", $order, $field.\'_slugs\', $query))\n+            ->addSelect($this->getPlatformGroupConcat("$field.slug", $order, $field . \'_slugs\', $query))\n             ->addSelect($this->getPlatformGroupConcat("$field.name", $order, $field, $query))\n             ->leftJoin($alias, $target, $field, "$alias.id = $field.content_id AND $field.contenttype=\'$boltname\' AND $field.taxonomytype=\'$field\'")\n             ->addGroupBy("$alias.id");\n@@ -106,7 +106,7 @@ class TaxonomyType extends FieldTypeBase\n             if (empty($taxValueSlug)) {\n                 continue;\n             }\n-            \n+\n             $keyName = $taxName . \'/\' . $taxValueSlug;\n             $taxValueProxy[$keyName] = new TaxonomyValue($taxName, $taxValueName, $taxData);\n \n@@ -127,10 +127,10 @@ class TaxonomyType extends FieldTypeBase\n         $values[$taxName] = !empty($taxValueProxy) ? $taxValueProxy : null;\n \n         foreach ($values as $tname => $tval) {\n-            $setter = \'set\'.ucfirst($tname);\n+            $setter = \'set\' . ucfirst($tname);\n             $entity->$setter($tval);\n         }\n-        \n+\n         $entity->setTaxonomy($values);\n         $entity->setGroup($group);\n         $entity->setSortorder($sortorder);\ndiff --git a/src/Storage/Field/Type/TemplateFieldsType.php b/src/Storage/Field/Type/TemplateFieldsType.php\nindex 66b33df78..ab2991010 100644\n--- a/src/Storage/Field/Type/TemplateFieldsType.php\n+++ b/src/Storage/Field/Type/TemplateFieldsType.php\n@@ -61,7 +61,7 @@ class TemplateFieldsType extends FieldTypeBase\n     {\n         $key = $this->mapping[\'fieldname\'];\n         $qb = &$queries[0];\n-        $valueMethod = \'serialize\'.ucfirst($key);\n+        $valueMethod = \'serialize\' . ucfirst($key);\n         $value = $entity->$valueMethod();\n \n         $type = $this->getStorageType();\n@@ -74,8 +74,8 @@ class TemplateFieldsType extends FieldTypeBase\n             $value = isset($this->mapping[\'default\']) ? $this->mapping[\'default\'] : null;\n         }\n \n-        $qb->setValue($key, ":".$key);\n-        $qb->set($key, ":".$key);\n+        $qb->setValue($key, \':\' . $key);\n+        $qb->set($key, \':\' . $key);\n         $qb->setParameter($key, $value);\n     }\n \ndiff --git a/src/Storage/NamingStrategy.php b/src/Storage/NamingStrategy.php\nindex 39420bc27..66ca725df 100644\n--- a/src/Storage/NamingStrategy.php\n+++ b/src/Storage/NamingStrategy.php\n@@ -28,7 +28,7 @@ class NamingStrategy implements NamingStrategyInterface\n         $className = $this->getRelativeClass($className);\n         $className = ltrim(strtolower(preg_replace(\'/[A-Z]/\', \'_$0\', $className)), \'_\');\n \n-        return $this->prefix.$className;\n+        return $this->prefix . $className;\n     }\n \n     /**\ndiff --git a/src/Storage/Query/Adapter/PostgresSearch.php b/src/Storage/Query/Adapter/PostgresSearch.php\nindex f9e08b7e1..981f83e5a 100644\n--- a/src/Storage/Query/Adapter/PostgresSearch.php\n+++ b/src/Storage/Query/Adapter/PostgresSearch.php\n@@ -31,7 +31,7 @@ class PostgresSearch\n     {\n         $words = implode(\'&\', $this->searchWords);\n         $sub = clone $this->qb;\n-        $this->qb->addSelect("ts_rank(bsearch.document, to_tsquery(\'".$words."\')) as score");\n+        $this->qb->addSelect("ts_rank(bsearch.document, to_tsquery(\'" . $words . "\')) as score");\n         $sub->select(\'*\');\n         $select = [];\n \n@@ -49,12 +49,12 @@ class PostgresSearch\n             $weight = $this->getWeight($config[\'weight\']);\n             $select[] = "setweight(to_tsvector($alias.$fieldName), \'$weight\')";\n         }\n-        $sub->select(\'*, \'.implode(\' || \', $select). \' AS document\');\n+        $sub->select(\'*, \' . implode(\' || \', $select) . \' AS document\');\n         $sub->groupBy("$alias.id");\n \n-        $this->qb->from(\'(\'.$sub->getSQL().\')\', \'bsearch\');\n+        $this->qb->from(\'(\' . $sub->getSQL() . \')\', \'bsearch\');\n \n-        $this->qb->where("bsearch.document @@ to_tsquery(\'".$words."\')");\n+        $this->qb->where("bsearch.document @@ to_tsquery(\'" . $words . "\')");\n         $this->qb->orderBy(\'score\', \'DESC\');\n \n         return $this->qb;\ndiff --git a/src/Storage/Query/QueryParameterParser.php b/src/Storage/Query/QueryParameterParser.php\nindex 6d9b9a52b..8ddbd6881 100644\n--- a/src/Storage/Query/QueryParameterParser.php\n+++ b/src/Storage/Query/QueryParameterParser.php\n@@ -58,7 +58,7 @@ class QueryParameterParser\n      */\n     public function setAlias($alias)\n     {\n-        $this->alias = $alias.\'.\';\n+        $this->alias = $alias . \'.\';\n     }\n \n     /**\n@@ -124,10 +124,10 @@ class QueryParameterParser\n \n             while (($key = array_shift($keys)) && ($val = array_shift($values))) {\n                 $val = $this->parseValue($val);\n-                $placeholder = $key.\'_\'.$count;\n+                $placeholder = $key . \'_\' . $count;\n                 $filterParams[$placeholder] = $val[\'value\'];\n                 $exprMethod = $val[\'operator\'];\n-                $parts[] = $this->expr->$exprMethod($this->alias.$key, ":$placeholder");\n+                $parts[] = $this->expr->$exprMethod($this->alias . $key, \':\' . $placeholder);\n                 $count++;\n             }\n \n@@ -174,10 +174,10 @@ class QueryParameterParser\n \n             while ($val = array_shift($values)) {\n                 $val = $this->parseValue($val);\n-                $placeholder = $key.\'_\'.$count;\n+                $placeholder = $key . \'_\' . $count;\n                 $filterParams[$placeholder] = $val[\'value\'];\n                 $exprMethod = $val[\'operator\'];\n-                $parts[] = $this->expr->$exprMethod($this->alias.$key, ":$placeholder");\n+                $parts[] = $this->expr->$exprMethod($this->alias . $key, \':\' . $placeholder);\n                 $count++;\n             }\n \n@@ -202,12 +202,12 @@ class QueryParameterParser\n     public function defaultFilterHandler($key, $value, $expr)\n     {\n         $val = $this->parseValue($value);\n-        $placeholder = $key.\'_1\';\n+        $placeholder = $key . \'_1\';\n         $exprMethod = $val[\'operator\'];\n \n         $filter = new Filter();\n         $filter->setKey($key);\n-        $filter->setExpression($expr->andX($expr->$exprMethod($this->alias.$key, ":$placeholder")));\n+        $filter->setExpression($expr->andX($expr->$exprMethod($this->alias . $key, \':\' . $placeholder)));\n         $filter->setParameters([$placeholder => $val[\'value\']]);\n \n         return $filter;\ndiff --git a/src/Storage/Query/SearchConfig.php b/src/Storage/Query/SearchConfig.php\nindex 9f58315a7..d90ab046e 100644\n--- a/src/Storage/Query/SearchConfig.php\n+++ b/src/Storage/Query/SearchConfig.php\n@@ -88,7 +88,7 @@ class SearchConfig\n     protected function parseTaxonomies($contenttype, $taxonomies)\n     {\n         foreach ((array) $taxonomies as $taxonomy) {\n-            $taxonomyConfig = $this->config->get(\'taxonomy/\'.$taxonomy);\n+            $taxonomyConfig = $this->config->get(\'taxonomy/\' . $taxonomy);\n             if (isset($taxonomyConfig[\'searchweight\'])) {\n                 $weight = $taxonomyConfig[\'searchweight\'];\n             } elseif (isset($taxonomyConfig[\'behaves_like\']) && $taxonomyConfig[\'behaves_like\'] === \'tags\') {\n@@ -123,7 +123,7 @@ class SearchConfig\n      */\n     protected function getSearchableColumns($type)\n     {\n-        $fields = $this->config->get(\'contenttypes/\'.$type.\'/fields\');\n+        $fields = $this->config->get(\'contenttypes/\' . $type . \'/fields\');\n \n         foreach ($fields as $field => $options) {\n             if (in_array($options[\'type\'], [\'text\', \'textarea\', \'html\', \'markdown\']) || $options[\'searchable\'] == true) {\n@@ -150,7 +150,7 @@ class SearchConfig\n      */\n     protected function isInvisible($contenttype)\n     {\n-        $info = $this->config->get(\'contenttypes/\'.$contenttype);\n+        $info = $this->config->get(\'contenttypes/\' . $contenttype);\n         if ($info) {\n             if (array_key_exists(\'viewless\', $info) && $info[\'viewless\'] == true) {\n                 return true;\ndiff --git a/src/Storage/Query/SearchQuery.php b/src/Storage/Query/SearchQuery.php\nindex db37f4c51..f87778397 100644\n--- a/src/Storage/Query/SearchQuery.php\n+++ b/src/Storage/Query/SearchQuery.php\n@@ -73,11 +73,11 @@ class SearchQuery extends SelectQuery\n         if (strpos($this->search, \'+\')) {\n             $words = preg_split(\'/[\\s\\+]+/\', $this->search);\n \n-            return \'%\'.implode(\'% && %\', $words).\'%\';\n+            return \'%\' . implode(\'% && %\', $words) . \'%\';\n         } else {\n             $words = explode(\' \', $this->search);\n \n-            return \'%\'.implode(\'% || %\', $words).\'%\';\n+            return \'%\' . implode(\'% || %\', $words) . \'%\';\n         }\n     }\n \ndiff --git a/src/Storage/Query/SelectQuery.php b/src/Storage/Query/SelectQuery.php\nindex f48863aad..3a466d5bb 100644\n--- a/src/Storage/Query/SelectQuery.php\n+++ b/src/Storage/Query/SelectQuery.php\n@@ -101,7 +101,7 @@ class SelectQuery implements QueryInterface\n     {\n         return array_intersect_key(\n             $this->getWhereParameters(),\n-            array_flip(preg_grep(\'/^\'.$fieldname.\'_/\', array_keys($this->getWhereParameters())))\n+            array_flip(preg_grep(\'/^\' . $fieldname . \'_/\', array_keys($this->getWhereParameters())))\n         );\n     }\n \ndiff --git a/src/Storage/Repository.php b/src/Storage/Repository.php\nindex dbff0ffa4..77cab7e67 100644\n--- a/src/Storage/Repository.php\n+++ b/src/Storage/Repository.php\n@@ -72,7 +72,7 @@ class Repository implements ObjectRepository\n         if (empty($alias)) {\n             $select = \'*\';\n         } else {\n-            $select = $alias.\'.*\';\n+            $select = $alias . \'.*\';\n         }\n \n         return $this->em->createQueryBuilder()\n@@ -86,7 +86,7 @@ class Repository implements ObjectRepository\n     public function find($id)\n     {\n         $qb = $this->getLoadQuery();\n-        $result = $qb->where($this->getAlias().\'.id = :id\')\n+        $result = $qb->where($this->getAlias() . \'.id = :id\')\n             ->setParameter(\'id\', $id)\n             ->execute()\n             ->fetch();\ndiff --git a/src/Twig/Handler/AdminHandler.php b/src/Twig/Handler/AdminHandler.php\nindex cbddd81da..83c85aaf6 100644\n--- a/src/Twig/Handler/AdminHandler.php\n+++ b/src/Twig/Handler/AdminHandler.php\n@@ -221,7 +221,7 @@ class AdminHandler\n         $return = \'\';\n \n         $add = function ($name, $value = null) use (&$return) {\n-            $return .= \' \' .$name . ($value === null ? \'\' : \'="\' . htmlspecialchars($value) . \'"\');\n+            $return .= \' \' . $name . ($value === null ? \'\' : \'="\' . htmlspecialchars($value) . \'"\');\n         };\n \n         foreach ($attributes as $name => $value) {\n', 'commit_subject': 'Spaces around string concat operator', 'repo_name': 'bolt/bolt', 'committer': {'name': 'rarila', 'email': 'b257af45fbc9f52d0e728490f2c2da9e4f66647e@gmx.net', 'time_sec': '1446566255', 'tz_offset': '60', 'date': {'seconds': '1446566255'}}, 'commit_tree': '6732e6f3fb4ffa0ffd3d31c47d0ccd3d547814d3', 'commit_message': 'Spaces around string concat operator', 'language_name': 'Shell', 'license': 'mit', 'hunks': "@@ -72,7 +72,7 @@ class Repository implements ObjectRepository\n         if (empty($alias)) {\n             $select = '*';\n         } else {\n-            $select = $alias.'.*';\n+            $select = $alias . '.*';\n         }\n \n         return $this->em->createQueryBuilder()\n@@ -86,7 +86,7 @@ class Repository implements ObjectRepository\n     public function find($id)\n     {\n         $qb = $this->getLoadQuery();\n-        $result = $qb->where($this->getAlias().'.id = :id')\n+        $result = $qb->where($this->getAlias() . '.id = :id')\n             ->setParameter('id', $id)\n             ->execute()\n             ->fetch();\n", 'addition_count': 2, 'deletion_count': 2, 'src_file': 'a/src/Storage/Repository.php', 'tgt_file': 'b/src/Storage/Repository.php', 'file_extension': '.php', 'before_file': '<?php\n\nnamespace Bolt\\Storage;\n\nuse ArrayObject;\nuse Bolt\\Events\\HydrationEvent;\nuse Bolt\\Events\\StorageEvent;\nuse Bolt\\Events\\StorageEvents;\nuse Bolt\\Storage\\Entity\\Builder;\nuse Bolt\\Storage\\Entity\\Entity;\nuse Bolt\\Storage\\Field\\Type\\FieldTypeInterface;\nuse Bolt\\Storage\\Mapping\\ClassMetadata;\nuse Bolt\\Storage\\Query\\QueryInterface;\nuse Doctrine\\Common\\Persistence\\ObjectRepository;\nuse Doctrine\\DBAL\\Connection;\nuse Doctrine\\DBAL\\Query\\QueryBuilder;\n\n/**\n * A default repository class that other repositories can inherit to provide more specific features.\n */\nclass Repository implements ObjectRepository\n{\n    /** @var EntityManager */\n    public $em;\n    /** @var ClassMetadata */\n    public $_class;\n    /** @var string */\n    public $entityName;\n    /** @var Builder */\n    public $builder;\n\n    /**\n     * Initializes a new Repository.\n     *\n     * @param EntityManager $em            the EntityManager to use\n     * @param ClassMetadata $classMetadata the class descriptor\n     */\n    public function __construct($em, ClassMetadata $classMetadata)\n    {\n        $this->em = $em;\n        $this->_class = $classMetadata;\n        $this->entityName = $classMetadata->getName();\n    }\n\n    /**\n     * Creates a new empty entity and passes the supplied data to the constructor.\n     *\n     * @param array         $params\n     * @param ClassMetadata $metadata\n     *\n     * @return Entity\n     */\n    public function create($params = [], ClassMetadata $metadata = null)\n    {\n        $params = new ArrayObject($params);\n        $builder = $this->getEntityBuilder();\n        /** @var Entity $entity */\n        $entity = $builder->getEntity();\n        $preEventArgs = new HydrationEvent($params, [\'entity\' => $entity, \'repository\' => $this]);\n        $this->event()->dispatch(StorageEvents::PRE_HYDRATE, $preEventArgs);\n        $builder->create($params, $entity);\n        $postEventArgs = new HydrationEvent($params, [\'entity\' => $entity, \'repository\' => $this]);\n        $this->event()->dispatch(StorageEvents::POST_HYDRATE, $postEventArgs);\n\n        return $entity;\n    }\n\n    /**\n     * Creates a new QueryBuilder instance that is prepopulated for this entity name.\n     *\n     * @param string $alias\n        if (empty($alias)) {\n            $select = \'*\';\n        } else {\n            $select = $alias.\'.*\';\n        }\n\n        return $this->em->createQueryBuilder()\n        }\n\n        if (empty($alias)) {\n            $select = \'*\';\n        } else {\n            $select = $alias . \'.*\';\n        }\n    public function find($id)\n    {\n        $qb = $this->getLoadQuery();\n        $result = $qb->where($this->getAlias().\'.id = :id\')\n            ->setParameter(\'id\', $id)\n            ->execute()\n            ->fetch();\n     * Return the number of rows used in this repository table.\n     *\n     * @return int\n     */\n    public function count()\n    {\n        $qb = $this->getLoadQuery()\n            ->select(\'COUNT(\' . $this->getAlias() . \'.id) as count\')\n            ->resetQueryParts([\'groupBy\', \'join\'])\n        ;\n        $result = $qb->execute()->fetchColumn(0);\n\n        return (int) $result;\n    }\n\n    /**\n     * {@inheritdoc}\n     */\n    public function find($id)\n    {\n        $qb = $this->getLoadQuery();\n        $result = $qb->where($this->getAlias() . \'.id = :id\')\n            ->setParameter(\'id\', $id)\n            ->execute()\n            ->fetch();\n\n        if ($result) {\n            return $this->hydrate($result, $qb);\n        }\n\n        return false;\n    }\n\n    /**\n     * {@inheritdoc}\n     */\n    public function findAll()\n    {\n        return $this->findBy([]);\n    }\n\n    /**\n     * {@inheritdoc}\n     */\n    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)\n    {\n        $qb = $this->findWithCriteria($criteria, $orderBy, $limit, $offset);\n\n        $result = $qb->execute()->fetchAll();\n\n        if ($result) {\n            return $this->hydrateAll($result, $qb);\n        }\n\n        return false;\n    }\n\n    /**\n     * Finds a single object by a set of criteria.\n     *\n     * @param array $criteria the criteria\n     * @param array $orderBy\n     *\n     * @return object|false the object\n     */\n    public function findOneBy(array $criteria, array $orderBy = null)\n    {\n        $qb = $this->findWithCriteria($criteria, $orderBy);\n        $result = $qb->execute()->fetch();\n\n        if ($result) {\n            return $this->hydrate($result, $qb);\n        }\n\n        return false;\n    }\n\n    /**\n     * Internal method to build a basic select, returns QB object.\n     *\n     * @param array $criteria\n     * @param array $orderBy\n     * @param int   $limit\n     * @param int   $offset\n     *\n     * @return QueryBuilder\n     */\n    protected function findWithCriteria(array $criteria, array $orderBy = null, $limit = null, $offset = null)\n    {\n        $qb = $this->getLoadQuery();\n        foreach ($criteria as $col => $val) {\n            if (is_array($val)) {\n                $qb->andWhere($this->getAlias() . ".$col IN(:$col)");\n                $qb->setParameter(":$col", $val, Connection::PARAM_INT_ARRAY);\n            } else {\n                $qb->andWhere($this->getAlias() . ".$col = :$col");\n                $qb->setParameter(":$col", $val);\n            }\n        }\n        if ($orderBy) {\n            $qb->orderBy($orderBy[0], $orderBy[1]);\n        }\n        if ($limit) {\n            $qb->setMaxResults($limit);\n        }\n        if ($offset) {\n            $qb->setFirstResult($offset);\n        }\n\n        return $qb;\n    }\n\n    /**\n     * Method to hydrate and return a QueryBuilder query.\n     *\n     * @param QueryBuilder $query\n     *\n     * @return array Entity\n     */\n    public function findWith(QueryBuilder $query)\n    {\n        $this->load($query);\n\n        $result = $query->execute()->fetchAll();\n        if ($result) {\n            return $this->hydrateAll($result, $query);\n        }\n\n        return [];\n    }\n\n    /**\n     * Method to hydrate and return a single QueryBuilder result.\n     *\n     * @param QueryBuilder $query\n     *\n     * @return Entity|false\n     */\n    public function findOneWith(QueryBuilder $query)\n    {\n        $this->load($query);\n        $result = $query->execute()->fetch();\n        if ($result) {\n            return $this->hydrate($result, $query);\n        }\n\n        return false;\n    }\n\n    /**\n     * Method to execute query from a Bolt QueryInterface object\n     * The query is passed to the pre-load handlers then built into a\n     * QueryBuilder instance that can be executed.\n     *\n     * @param QueryInterface $query [description]\n     *\n     * @return array Entity | false\n     */\n    public function queryWith(QueryInterface $query)\n    {\n        $this->query($query);\n        $queryBuilder = $query->build();\n\n        return $this->findWith($queryBuilder);\n    }\n\n    /**\n     * Internal method to initialise and return a QueryBuilder instance.\n     * Note that the metadata fields will be passed the instance to modify where appropriate.\n     *\n     * @return QueryBuilder\n     */\n    protected function getLoadQuery()\n    {\n        $qb = $this->createQueryBuilder();\n        $this->load($qb);\n\n        return $qb;\n    }\n\n    /**\n     * Internal method to run load method on each field for the managed entity.\n     *\n     * Takes a QueryBuilder instance as input\n     *\n     * @param QueryBuilder $query\n     */\n    protected function load(QueryBuilder $query)\n    {\n        $metadata = $this->getClassMetadata();\n        foreach ($metadata->getFieldMappings() as $field) {\n            $fieldtype = $this->getFieldManager()->get($field[\'fieldtype\'], $field);\n            if ($fieldtype instanceof FieldTypeInterface) {\n                $fieldtype->load($query, $metadata);\n            }\n        }\n    }\n\n    /**\n     * Internal method to run query method on each field for the managed entity.\n     *\n     * Takes a QueryInterface instance as input\n     *\n     * @param QueryInterface $query\n     */\n    protected function query(QueryInterface $query)\n    {\n        $metadata = $this->getClassMetadata();\n\n        foreach ($metadata->getFieldMappings() as $field) {\n            $fieldtype = $this->getFieldManager()->get($field[\'fieldtype\'], $field);\n            if ($fieldtype instanceof FieldTypeInterface) {\n                $fieldtype->query($query, $metadata);\n            }\n        }\n    }\n\n    /**\n     * Internal method to run persist method on each field for the managed entity.\n     *\n     * Takes a QuerySet instance as input\n     *\n     * @param QuerySet $queries\n     * @param Entity   $entity\n     * @param array    $exclusions\n     */\n    protected function persist(QuerySet $queries, $entity, $exclusions = [])\n    {\n        $metadata = $this->getClassMetadata();\n\n        foreach ($metadata->getFieldMappings() as $field) {\n            $fieldName = $field[\'fieldname\'];\n            if (in_array($fieldName, $exclusions)) {\n                continue;\n            }\n            // Don\'t add field to the persistence query if it is not an entity\n            // property, and on UPDATE only\n            if (!isset($entity->$fieldName) && $entity->getId() !== null) {\n                continue;\n            }\n\n            $field = $this->getFieldManager()->get($field[\'fieldtype\'], $field);\n            if ($field instanceof FieldTypeInterface) {\n                $field->persist($queries, $entity);\n            }\n        }\n    }\n\n    /**\n     * Deletes a single object.\n     *\n     * @param object $entity the entity to delete\n     *\n     * @return bool\n     */\n    public function delete($entity)\n    {\n        $event = new StorageEvent($entity);\n        $this->event()->dispatch(StorageEvents::PRE_DELETE, $event);\n        $qb = $this->em->createQueryBuilder()\n            ->delete($this->getTableName())\n            ->where(\'id = :id\')\n            ->setParameter(\'id\', $entity->getId());\n\n        $response = $qb->execute();\n        $event = new StorageEvent($entity);\n        $this->event()->dispatch(StorageEvents::POST_DELETE, $event);\n\n        return $response;\n    }\n\n    /**\n     * Saves a single object.\n     *\n     * @param object $entity the entity to save\n     * @param bool   $silent Suppress events\n     *\n     * @return bool\n     */\n    public function save($entity, $silent = null)\n    {\n        try {\n            if ($existing = $entity->getId()) {\n                $creating = false;\n            } else {\n                $creating = true;\n            }\n        } catch (\\Exception $e) {\n            $creating = $existing = false;\n        }\n\n        if ($silent === null) {\n            $event = new StorageEvent($entity, [\'create\' => $creating]);\n            $this->event()->dispatch(StorageEvents::PRE_SAVE, $event);\n        }\n\n        if ($existing) {\n            $response = $this->update($entity);\n        } else {\n            $response = $this->insert($entity);\n        }\n\n        if ($silent === null) {\n            $this->event()->dispatch(StorageEvents::POST_SAVE, $event);\n        }\n\n        return $response;\n    }\n\n    /**\n     * Saves a new object into the database.\n     *\n     * @param object $entity the entity to insert\n     *\n     * @return bool\n     */\n    public function insert($entity)\n    {\n        $querySet = new QuerySet();\n        $qb = $this->em->createQueryBuilder();\n        $qb->insert($this->getTableName());\n        $querySet->append($qb);\n        $this->persist($querySet, $entity, [\'id\']);\n\n        $result = $querySet->execute();\n\n        // Try and set the entity id using the response from the insert\n        try {\n            $entity->setId($querySet->getInsertId());\n        } catch (\\Exception $e) {\n        }\n\n        return $result;\n    }\n\n    /**\n     * Updates an object into the database.\n     *\n     * @param object   $entity     the entity to update\n     * @param string[] $exclusions Ignore updates to these fields\n     *\n     * @return bool\n     */\n    public function update($entity, $exclusions = [])\n    {\n        $querySet = new QuerySet();\n        $querySet->setParentId($entity->getId());\n        $qb = $this->em->createQueryBuilder();\n        $qb->update($this->getTableName())\n            ->where(\'id = :id\')\n            ->setParameter(\'id\', $entity->getId());\n        $querySet->append($qb);\n        $this->persist($querySet, $entity, $exclusions);\n\n        return $querySet->execute();\n    }\n\n    /**\n     * Internal method to hydrate an Entity Object from fetched data.\n     *\n     * @param array        $data\n     * @param QueryBuilder $qb\n     *\n     * @return mixed\n     */\n    protected function hydrate(array $data, QueryBuilder $qb)\n    {\n        $entity = $this->getEntityBuilder()->getEntity();\n\n        $data = new ArrayObject($data);\n        $preEventArgs = new HydrationEvent($data, [\'entity\' => $entity, \'repository\' => $this]);\n        $this->event()->dispatch(StorageEvents::PRE_HYDRATE, $preEventArgs);\n\n        $this->getEntityBuilder()->createFromDatabaseValues($data, $entity);\n\n        $postEventArgs = new HydrationEvent($entity, [\'entity\' => $entity, \'data\' => $data, \'repository\' => $this]);\n        $this->event()->dispatch(StorageEvents::POST_HYDRATE, $postEventArgs);\n\n        return $entity;\n    }\n\n    /**\n     * Internal method to hydrate an array of Entity Objects from fetched data.\n     *\n     * @param array        $data\n     * @param QueryBuilder $qb\n     *\n     * @return mixed\n     */\n    protected function hydrateAll(array $data, QueryBuilder $qb)\n    {\n        $rows = [];\n        foreach ($data as $row) {\n            $rows[] = $this->hydrate($row, $qb);\n        }\n\n        return $rows;\n    }\n\n    /**\n     * Internal method to refresh (re-hydrate an entity) using\n     * the field setters.\n     *\n     * @param  $entity\n     */\n    protected function refresh($entity)\n    {\n        $this->getEntityBuilder()->refresh($entity);\n    }\n\n    /**\n     * Fetches FieldManager instance from the EntityManager.\n     *\n     * @return FieldManager\n     */\n    public function getFieldManager()\n    {\n        return $this->em->getFieldManager();\n    }\n\n    /**\n     * @return Builder $builder\n     */\n    public function getEntityBuilder()\n    {\n        $builder = $this->em->getEntityBuilder();\n        $builder->setClass($this->getEntityName());\n        $builder->setClassMetadata($this->getClassMetadata());\n\n        return $builder;\n    }\n\n    /**\n     * @return string\n     */\n    public function getEntityName()\n    {\n        return $this->entityName;\n    }\n\n    /**\n     * @return string\n     */\n    public function getClassName()\n    {\n        return $this->getEntityName();\n    }\n\n    /**\n     * @return string\n     */\n    public function getTableName()\n    {\n        return $this->getClassMetadata()->getTableName();\n    }\n\n    /**\n     * @return string\n     */\n    public function getAlias()\n    {\n        return $this->getClassMetadata()->getAliasName();\n    }\n\n    /**\n     * @return EntityManager\n     */\n    public function getEntityManager()\n    {\n        return $this->em;\n    }\n\n    /**\n     * Getter for class metadata.\n     *\n     * @return ClassMetadata\n     */\n    public function getClassMetadata()\n    {\n        return $this->_class;\n    }\n\n    /**\n     * Shortcut method to fetch the Event Dispatcher.\n     *\n     * @return \\Symfony\\Component\\EventDispatcher\\EventDispatcherInterface\n     */\n    public function event()\n    {\n        return $this->getEntityManager()->getEventManager();\n    }\n}\n', 'message': 'Spaces around string concat operator', 'author_name': 'rarila', 'lang': 'php'}