Corcel\Post::newFromBuilder PHP Method

newFromBuilder() public method

By default, this method will always return an instance of the calling class. However if post types have been registered with the Post class using the registerPostType() static method, this will now return an instance of that class instead. If the post type string from $attributes->post_type does not appear in the static $postTypes array, then the class instantiated will be the called class (the default behaviour of this method).
public newFromBuilder ( array $attributes = [], null $connection = null ) : mixed
$attributes array
$connection null
return mixed
    public function newFromBuilder($attributes = [], $connection = null)
    {
        if (is_object($attributes) && array_key_exists($attributes->post_type, static::$postTypes)) {
            $class = static::$postTypes[$attributes->post_type];
        } elseif (is_array($attributes) && array_key_exists($attributes['post_type'], static::$postTypes)) {
            $class = static::$postTypes[$attributes['post_type']];
        } else {
            $class = get_called_class();
        }
        $model = new $class([]);
        $model->exists = true;
        $model->setRawAttributes((array) $attributes, true);
        $model->setConnection($connection ?: $this->connection);
        return $model;
    }

Usage Example

Beispiel #1
0
 public function testPostTypeConstructor()
 {
     Post::registerPostType('video', 'Video');
     $post = new Post();
     $model = $post->newFromBuilder(['post_type' => 'video']);
     $this->assertInstanceOf("Video", $model);
 }