Skip to content

Instantly share code, notes, and snippets.

@janpecha
Last active July 24, 2020 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janpecha/00647d93efdda08076b105e6ee21a64e to your computer and use it in GitHub Desktop.
Save janpecha/00647d93efdda08076b105e6ee21a64e to your computer and use it in GitHub Desktop.
Lean Mapper entity testing
<?php
// LeanMapper 3.4.2
require __DIR__ . '/vendor/autoload.php';
class AppMapper extends \LeanMapper\DefaultMapper
{
protected $defaultEntityNamespace = '';
}
/**
* @property int $id
* @property string $name
* @property Book[] $books m:belongsToMany
*/
class Author extends \LeanMapper\Entity
{
}
/**
* @property int $id
* @property Author $author m:hasOne
* @property string $name
*/
class Book extends \LeanMapper\Entity
{
}
$connection = new LeanMapper\Connection([
'driver' => 'sqlite3',
'database' => ':memory:',
'lazy' => TRUE,
]);
$mapper = new AppMapper;
$entityFactory = new LeanMapper\DefaultEntityFactory;
// WRONG WAY
// $author = new Author;
// $author->name = 'John Doe';
// $author->makeAlive($entityFactory, $connection, $mapper);
// $author->attach(1);
// $author->books = []; // error => Cannot write to read-only property 'books' in entity Author
// RIGHT WAY
$authors = LeanMapper\Result::createInstance([
[
'id' => 1,
'name' => 'John Doe',
],
], 'author', $connection, $mapper);
$books = LeanMapper\Result::createInstance([
[
'id' => 1,
'author_id' => 1,
'name' => 'Book A',
],
[
'id' => 2,
'author_id' => 2,
'name' => 'Book B',
],
[
'id' => 3,
'author_id' => 1,
'name' => 'Book C',
],
], 'book', $connection, $mapper);
$authors->setReferencingResult($books, 'book', 'author_id');
$books->setReferencedResult($authors, 'author', 'author_id');
$author = new Author($authors->getRow(1));
$author->makeAlive($entityFactory);
// prints: 'Book A', 'Book C'
foreach ($author->books as $book) {
var_dump($book->name);
var_dump($book->author->name);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment