Skip to content

Use real object managers #49

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Feb 12, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,31 @@ This extension provides following features:
* Provides correct return type for `Doctrine\ORM\EntityManager::find`, `getReference` and `getPartialReference` when `Foo::class` entity class name is provided as the first argument
* Adds missing `matching` method on `Doctrine\Common\Collections\Collection`. This can be turned off by setting `parameters.doctrine.allCollectionsSelectable` to `false`.

This extension does not yet support custom `repositoryClass` specified for each entity class. However, if your repositories have a common base class, you can configure it in your `phpstan.neon` and PHPStan will see additional methods you define in it:
If your repositories have a common base class, you can configure it in your `phpstan.neon` and PHPStan will see additional methods you define in it:

```
```neon
parameters:
doctrine:
repositoryClass: MyApp\Doctrine\BetterEntityRepository
```

Alternatively, you can provide your object manager and all custom repositories will be loaded

```neon
parameters:
doctrine:
objectManagerLoader: tests/object-manager.php
```

For example, in a Symfony project, `object-manager.php` would look something like this:

```php
require dirname(__DIR__).'/../config/bootstrap.php';
$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$kernel->boot();
return $kernel->getContainer()->get('doctrine')->getManager();
```

## Usage

To use this extension, require it in [Composer](https://getcomposer.org/):
Expand Down
12 changes: 7 additions & 5 deletions extension.neon
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
parameters:
doctrine:
repositoryClass: Doctrine\ORM\EntityRepository
repositoryClass: null
allCollectionsSelectable: true
objectManagerLoader: null

conditionalTags:
PHPStan\Reflection\Doctrine\DoctrineSelectableClassReflectionExtension:
Expand All @@ -20,8 +21,6 @@ services:
- phpstan.broker.dynamicMethodReturnTypeExtension
-
class: PHPStan\Type\Doctrine\ObjectManagerGetRepositoryDynamicReturnTypeExtension
arguments:
repositoryClass: %doctrine.repositoryClass%
tags:
- phpstan.broker.dynamicMethodReturnTypeExtension
-
Expand All @@ -34,7 +33,10 @@ services:
- phpstan.broker.dynamicMethodReturnTypeExtension
-
class: PHPStan\Type\Doctrine\ManagerRegistryGetRepositoryDynamicReturnTypeExtension
arguments:
repositoryClass: %doctrine.repositoryClass%
tags:
- phpstan.broker.dynamicMethodReturnTypeExtension
-
class: PHPStan\Type\Doctrine\ObjectMetadataResolver
arguments:
objectManagerLoader: %doctrine.objectManagerLoader%
repositoryClass: %doctrine.repositoryClass%
13 changes: 8 additions & 5 deletions src/Type/Doctrine/GetRepositoryDynamicReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@
abstract class GetRepositoryDynamicReturnTypeExtension implements \PHPStan\Type\DynamicMethodReturnTypeExtension
{

/** @var string */
private $repositoryClass;
/** @var ObjectMetadataResolver */
private $metadataResolver;

public function __construct(string $repositoryClass)
public function __construct(ObjectMetadataResolver $metadataResolver)
{
$this->repositoryClass = $repositoryClass;
$this->metadataResolver = $metadataResolver;
}

public function isMethodSupported(MethodReflection $methodReflection): bool
Expand All @@ -42,7 +42,10 @@ public function getTypeFromMethodCall(
return new MixedType();
}

return new ObjectRepositoryType($argType->getValue(), $this->repositoryClass);
$objectName = $argType->getValue();
$repositoryClass = $this->metadataResolver->getRepositoryClass($objectName);

return new ObjectRepositoryType($objectName, $repositoryClass);
}

}
72 changes: 72 additions & 0 deletions src/Type/Doctrine/ObjectMetadataResolver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\Doctrine;

use Doctrine\Common\Persistence\ObjectManager;
use RuntimeException;
use function file_exists;
use function is_readable;

final class ObjectMetadataResolver
{

/** @var ?ObjectManager */
private $objectManager;

/** @var string */
private $repositoryClass;

public function __construct(?string $objectManagerLoader, ?string $repositoryClass)
{
if ($objectManagerLoader !== null) {
$this->objectManager = $this->getObjectManager($objectManagerLoader);
}
if ($repositoryClass !== null) {
$this->repositoryClass = $repositoryClass;
} elseif ($this->objectManager !== null && get_class($this->objectManager) === 'Doctrine\ODM\MongoDB\DocumentManager') {
$this->repositoryClass = 'Doctrine\ODM\MongoDB\DocumentRepository';
} else {
$this->repositoryClass = 'Doctrine\ORM\EntityRepository';
}
}

/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingReturnTypeHint
* @param string $objectManagerLoader
* @return ObjectManager
*/
private function getObjectManager(string $objectManagerLoader)
{
if (! file_exists($objectManagerLoader) && ! is_readable($objectManagerLoader)) {
throw new RuntimeException('Object manager could not be loaded');
}

return require $objectManagerLoader;
}

public function getRepositoryClass(string $className): string
{
if ($this->objectManager === null) {
return $this->repositoryClass;
}

$metadata = $this->objectManager->getClassMetadata($className);

$ormMetadataClass = 'Doctrine\ORM\Mapping\ClassMetadata';
if ($metadata instanceof $ormMetadataClass) {
/** @var \Doctrine\ORM\Mapping\ClassMetadata $ormMetadata */
$ormMetadata = $metadata;
return $ormMetadata->customRepositoryClassName ?? $this->repositoryClass;
}

$odmMetadataClass = 'Doctrine\ODM\MongoDB\Mapping\ClassMetadata';
if ($metadata instanceof $odmMetadataClass) {
/** @var \Doctrine\ODM\MongoDB\Mapping\ClassMetadata $odmMetadata */
$odmMetadata = $metadata;
return $odmMetadata->customRepositoryClassName ?? $this->repositoryClass;
}

return $this->repositoryClass;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public function dataTopics(): array
['documentManagerDynamicReturn'],
['documentRepositoryDynamicReturn'],
['documentManagerMergeReturn'],
['customRepositoryUsage'],
];
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[
{
"message": "Call to an undefined method PHPStan\\DoctrineIntegration\\ODM\\CustomRepositoryUsage\\MyRepository::nonexistant().",
"line": 31,
"ignorable": true
}
]
64 changes: 64 additions & 0 deletions tests/DoctrineIntegration/ODM/data/customRepositoryUsage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php declare(strict_types = 1);

namespace PHPStan\DoctrineIntegration\ODM\CustomRepositoryUsage;

use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\DocumentRepository;
use Doctrine\ODM\MongoDB\Mapping\Annotations\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations\Id;
use RuntimeException;

class Example
{
/**
* @var MyRepository
*/
private $repository;

public function __construct(DocumentManager $documentManager)
{
$this->repository = $documentManager->getRepository(MyDocument::class);
}

public function get(): void
{
$test = $this->repository->get('testing');
$test->doSomethingElse();
}

public function nonexistant(): void
{
$this->repository->nonexistant();
}
}

/**
* @Document(repositoryClass=MyRepository::class)
*/
class MyDocument
{
/**
* @Id(strategy="NONE", type="string")
*
* @var string
*/
private $id;

public function doSomethingElse(): void
{
}
}

class MyRepository extends DocumentRepository
{
public function get(string $id): MyDocument
{
$document = $this->find($id);

if ($document === null) {
throw new RuntimeException('Not found...');
}

return $document;
}
}
29 changes: 29 additions & 0 deletions tests/DoctrineIntegration/ODM/document-manager.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php declare(strict_types = 1);

use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\Common\Cache\ArrayCache;
use Doctrine\ODM\MongoDB\Configuration;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver;

AnnotationRegistry::registerUniqueLoader('class_exists');

$config = new Configuration();
$config->setProxyDir(__DIR__);
$config->setProxyNamespace('PHPstan\Doctrine\OdmProxies');
$config->setMetadataCacheImpl(new ArrayCache());
$config->setHydratorDir(__DIR__);
$config->setHydratorNamespace('PHPstan\Doctrine\OdmHydrators');

$config->setMetadataDriverImpl(
new AnnotationDriver(
new AnnotationReader(),
[__DIR__ . '/data']
)
);

return DocumentManager::create(
null,
$config
);
2 changes: 1 addition & 1 deletion tests/DoctrineIntegration/ODM/phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ includes:

parameters:
doctrine:
repositoryClass: Doctrine\ODM\MongoDB\DocumentRepository
objectManagerLoader: tests/DoctrineIntegration/ODM/document-manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public function dataTopics(): array
['entityManagerDynamicReturn'],
['entityRepositoryDynamicReturn'],
['entityManagerMergeReturn'],
['customRepositoryUsage'],
];
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[
{
"message": "Call to an undefined method PHPStan\\DoctrineIntegration\\ORM\\CustomRepositoryUsage\\MyRepository::nonexistant().",
"line": 30,
"ignorable": true
}
]
65 changes: 65 additions & 0 deletions tests/DoctrineIntegration/ORM/data/customRepositoryUsage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php declare(strict_types = 1);

namespace PHPStan\DoctrineIntegration\ORM\CustomRepositoryUsage;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Mapping as ORM;
use RuntimeException;

class Example
{
/**
* @var MyRepository
*/
private $repository;

public function __construct(EntityManagerInterface $entityManager)
{
$this->repository = $entityManager->getRepository(MyEntity::class);
}

public function get(): void
{
$test = $this->repository->get(1);
$test->doSomethingElse();
}

public function nonexistant(): void
{
$this->repository->nonexistant();
}
}

/**
* @ORM\Entity(repositoryClass=MyRepository::class)
*/
class MyEntity
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*
* @var int
*/
private $id;

public function doSomethingElse(): void
{
}
}

class MyRepository extends EntityRepository
{
public function get(int $id): MyEntity
{
$entity = $this->find($id);

if ($entity === null) {
throw new RuntimeException('Not found...');
}

return $entity;
}
}
30 changes: 30 additions & 0 deletions tests/DoctrineIntegration/ORM/entity-manager.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php declare(strict_types = 1);

use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\Common\Cache\ArrayCache;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;

AnnotationRegistry::registerUniqueLoader('class_exists');

$config = new Configuration();
$config->setProxyDir(__DIR__);
$config->setProxyNamespace('PHPstan\Doctrine\OrmProxies');
$config->setMetadataCacheImpl(new ArrayCache());

$config->setMetadataDriverImpl(
new AnnotationDriver(
new AnnotationReader(),
[__DIR__ . '/data']
)
);

return EntityManager::create(
[
'driver' => 'pdo_sqlite',
'memory' => true,
],
$config
);
Loading