cms/app/Console/Commands/GeneratePosts.php

89 lines
2.3 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Post;
use App\User;
use App\Repositories\PostRepository;
use Illuminate\Console\Command;
class GeneratePosts extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'post:generate {postType} {amount?} {--user_id=}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate posts';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
* @throws \Exception
*/
public function handle()
{
$user_id = $this->option('user_id');
if($user_id) {
$user = User::find($user_id);
if(!$user) {
throw new \Exception("User $user_id doesn't exist");
}
} else {
$user = User::inRandomOrder()->first();
if(!$user) {
throw new \Exception("User $user_id doesn't exist");
}
}
$amount = $this->argument('amount');
if(!$amount) {
$amount = 1;
}
$postType = $this->argument('postType');
$postTypes = config('postTypes');
if(array_key_exists($postType, $postTypes)) {
/** @var Post $model */
$postRepo = new PostRepository($postTypes[$postType]['model']);
$faker = \Faker\Factory::create();
for($i = 0; $i < $amount; $i++) {
$post = $postRepo->createModel();
$post->fill([
'title' => $this->randomTextLength($faker, 10, 25),
'excerpt' => $this->randomTextLength($faker, 10, 30),
'introduction' => $faker->realText($faker->numberBetween(20, 400)),
'user_id' => $user->id
]);
$post->save();
}
}
}
private function randomTextLength($faker, $min, $max)
{
return mb_substr($this->rtrim($faker->realText($max)), 0, $faker->numberBetween($min, $max - 1));
}
private function rtrim($text)
{
return mb_substr($text, 0, -1);
}
}