Explorar o código

Make app:publish-scheduled-articles work

axkuhta hai 1 ano
pai
achega
0c3ff2816a
Modificáronse 2 ficheiros con 33 adicións e 1 borrados
  1. 17 1
      app/Console/Commands/PublishScheduledArticles.php
  2. 16 0
      app/Models/Article.php

+ 17 - 1
app/Console/Commands/PublishScheduledArticles.php

@@ -3,6 +3,7 @@
 namespace App\Console\Commands;
 
 use Illuminate\Console\Command;
+use App\Models\Article;
 
 class PublishScheduledArticles extends Command
 {
@@ -25,6 +26,21 @@ class PublishScheduledArticles extends Command
      */
     public function handle()
     {
-        //
+        $pending_up = Article::pending()->get();
+        $pending_down = Article::published()->whereNotNull("unpublish_at")->get();
+
+        foreach ($pending_up as $article) {
+			if ($article->publish_at->isPast()) {
+				$this->info("Publishing [$article->title] at " . now());
+				$article->publish();
+			}
+        }
+
+        foreach ($pending_down as $article) {
+			if ($article->unpublish_at->isPast()) {
+				$this->info("Taking down [$article->title] at " . now());
+				$article->unpublish();
+			}
+        }
     }
 }

+ 16 - 0
app/Models/Article.php

@@ -9,6 +9,12 @@ class Article extends Model
 {
 	use SoftDeletes;
 
+	// Приведение к datetime нужно для использования метода isPast
+	protected $casts = [
+		"publish_at" => "datetime",
+		"unpublish_at" => "datetime"
+	];
+
 	const STATUS_DRAFT		= 0;
 	const STATUS_PENDING	= 1;
 	const STATUS_PUBLISHED	= 2;
@@ -25,4 +31,14 @@ class Article extends Model
 	function comments() {
 		return $this->morphMany(Comment::class, "commentable");
 	}
+
+	function publish() {
+		$this->status = static::STATUS_PUBLISHED;
+		$this->save();
+	}
+
+	function unpublish() {
+		$this->status = static::STATUS_ARCHIVED;
+		$this->save();
+	}
 }