Airship\Cabin\Bridge\Blueprint\Blog::createPost PHP Method

createPost() public method

Create (and, optionally, publish) a new blog post.
public createPost ( array $post, boolean $publish = false ) : boolean
$post array
$publish boolean
return boolean
    public function createPost(array $post, bool $publish = false) : bool
    {
        $this->db->beginTransaction();
        $newPostArgs = ['author' => $post['author'], 'category' => $post['category'] > 0 ? $post['category'] : null, 'description' => $post['description'], 'format' => !empty($post['format']) ? $post['format'] : 'Rich Text', 'shorturl' => \Airship\uniqueId(), 'status' => $publish, 'slug' => $this->makeBlogPostSlug(!empty($post['slug']) ? $post['slug'] : $post['title'] ?? 'Untitled'), 'title' => $post['title'] ?? 'Untitled'];
        // If we are publishing, let's set the publishing time.
        if ($publish) {
            if (!empty($post['published'])) {
                try {
                    $pub = new \DateTime($post['published']);
                } catch (\Throwable $ex) {
                    // Invalid DateTime format
                    $pub = new \DateTime();
                }
            } else {
                $pub = new \DateTime();
            }
            $newPostArgs['published'] = $pub->format(\AIRSHIP_DATE_FORMAT);
        }
        // Create the post entry
        $newPostId = $this->db->insertGet('hull_blog_posts', $newPostArgs, 'postid');
        // Did something break?
        if ($newPostId === false) {
            return false;
        }
        if ($publish) {
            \Airship\clear_cache();
        }
        // Insert the initial blog post version
        $this->db->insert('hull_blog_post_versions', ['post' => $newPostId, 'body' => $post['blog_post_body'], 'format' => $post['format'], 'metadata' => \json_encode($post['metadata'] ?? []), 'live' => $publish, 'published_by' => $publish ? $this->getActiveUserId() : null]);
        // Populate tags (only allow this if the tag actually exists)
        $allTags = $this->db->column('SELECT tagid FROM hull_blog_tags');
        foreach ($post['tags'] as $tag) {
            if (!\in_array($tag, $allTags)) {
                continue;
            }
            $this->db->insert('hull_blog_post_tags', ['postid' => $newPostId, 'tagid' => $tag]);
        }
        return $this->db->commit();
    }

Usage Example

Esempio n. 1
0
 /**
  * Create a new blog post
  *
  * @param array $post
  * @param array $authorsAllowed
  * @return bool
  */
 protected function processNewPost(array $post, array $authorsAllowed = []) : bool
 {
     $required = ['author', 'blog_post_body', 'format', 'save_btn', 'title'];
     if (!\Airship\all_keys_exist($required, $post)) {
         return false;
     }
     if (!\in_array($post['author'], $authorsAllowed)) {
         return false;
     }
     $publish = $this->can('publish') ? $post['save_btn'] === 'publish' : false;
     return $this->blog->createPost($post, $publish);
 }