laracasts / TestDummy

Easy factories for PHP integration testing.
https://laracasts.com/lessons/whats-new-in-testdummy
MIT License
456 stars 80 forks source link

[Proposal] Add attributes method to BuildableRepositoryInterface #47

Closed jonsa closed 9 years ago

jonsa commented 9 years ago

With the current state of the Builder class. Assumptions are made that BuildableRepositoryInterface::build should return an instance of Illuminate\Database\Eloquent\Model and not mixed as is defined. The reason for this is that Builder::persist calls a method getAttributes on the returned entity.

I propose this should be abstracted away into the BuildableRepositoryInterface by means of an attributes method or something similar. This should allow for something else than Eloquent to be used.

saturday commented 9 years ago

Here's an example of an implementation of the BuildableRepositoryInterface that works well - I've removed the create functionality for project specific reasons - with fluent and data returned from a postgresql table.


<?php namespace Middleware\Factories;

use Laracasts\TestDummy\BuildableRepositoryInterface;
use Laracasts\TestDummy\TestDummyException;
use stdClass;

/**
 * Class MyDatabaseProvider
 * @package Middleware\Factories
 */
class MyDatabaseProvider implements BuildableRepositoryInterface {

    /**
     * Build the entity with attributes.
     *
     * @param string $type
     * @param array $attributes
     * @throws TestDummyException
     * @return mixed
     */
    public function build($type, array $attributes)
    {
        return $this->fill($attributes);
    }

    /**
     * Persist the entity.
     *
     * @param Model $entity
     * @return void
     */
    public function save($entity)
    {
//        $entity->save();
    }

    /**
     * Get all attributes for the model.
     *
     * @param  object $entity
     * @return array
     */
    public function getAttributes($entity)
    {
        return array_keys(get_object_vars($entity));
    }

    /**
     * Force fill an object with attributes.
     *
     * @param  array $attributes
     * @return stdClass
     */
    private function fill($attributes)
    {
        $object = new stdClass();

        foreach ($attributes as $key => $value) {
            $object->$key = $value;
        }

        return $object;
    }

}