/** * Display a listing of the resource. * * @return Res2ponse */ public function index() { $s = Setting::first(); $word = WordCard::find($s->word_id); $settings = array('answer_time' => $s->answer_time, 'daily_bonus' => $s->daily_bonus, 'general_cost' => $s->general_cost, 'top_bonus' => $s->top_bonus, 'word_cost' => $s->word_cost, 'life_cost' => $s->life_cost, 'words_for_the_next_bonus' => $s->words_for_the_next_bonus, 'word' => array('id' => $s->word_id, 'word' => $word->word, 'answer' => $word->answer, 'category_id' => $word->category_id), 'quiz' => ['url' => $s->quiz, 'added_on' => $s->added_on]); return $this->respond($settings); }
private function parseCsv($data) { $row = explode(';', $data); $category = $this->checkCategory($row[2]); $this->info('Creating ' . $row[0] . ' with category: ' . $category->id); WordCard::create(['word' => $row[0], 'answer' => $row[1], 'category_id' => $category->id]); }
public static function getRandomCards($sentCards, $take = 20, $category = null) { $result = []; if ($category) { $cards = $category->wordcards->toArray(); $count = $category->wordcards()->count(); } else { $cards = WordCard::all()->toArray(); $count = WordCard::count(); } $countdown = $count; $countdown = 500; while (count($result) < $take) { // if ($countdown != 0) $countdown--; else { // return $result; // } if (empty($cards)) { return $result; } if (count($cards) < 1) { $card = array_shift($cards); } else { $index = rand(0, $count); } if (array_key_exists($index, $cards)) { $card = $cards[$index]; unset($cards[$index]); } else { $card = array_shift($cards); } if (isset($card)) { $sentCardsExists = array_filter($sentCards, function ($sentCard) use($card) { return $sentCard['word_id'] == $card['id']; }); $resultCardsExists = array_filter($result, function ($oldCard) use($card) { return $oldCard['id'] == $card['id']; }); if (count($sentCardsExists) == 0 && count($resultCardsExists) == 0) { array_push($result, $card); } // var_dump(count($cards)); // var_dump('============='); } } return $result; }
public function fire() { $pushWords = new Collection(); $dayWord = WordCard::find(Setting::first()->word_id); $pushWords->push(['word_id' => $dayWord->id, 'category_id' => $dayWord->category_id]); Category::all()->each(function ($category) use($pushWords) { $this->info("looking at category {$category->id}"); $word = $this->getSentWord($category); if ($word) { $pushWords->push(['word_id' => $word->id, 'category_id' => $category->id]); } else { $this->error('Empty category'); } }); $this->check(); $this->pushWords2($pushWords); }
public function run() { $faker = Faker::create(); WordCard::create(['word' => 'Такела́ж', 'answer' => 'общее название всех снастей на судне или вооружение отдельной мачты или рангоутного дерева, употребляемое для крепления рангоута и управления им и парусами.', 'category_id' => '1']); WordCard::create(['word' => 'Фили́стер', 'answer' => 'человек без духовных потребностей, тот, кто не ценит искусство, не разделяет связанных с ним эстетических или духовных ценностей.', 'category_id' => '1']); WordCard::create(['word' => 'Ло́феры', 'answer' => 'модель туфель без шнурков, по форме напоминающих мокасины, только с подошвой и на низком широком каблуке,могут быть снабжены декоративными кисточками.', 'category_id' => '1']); WordCard::create(['word' => 'Инса́йт', 'answer' => 'интеллектуальное явление, суть которого в неожиданном понимании стоящей проблемы и нахождении её решения.', 'category_id' => '1']); WordCard::create(['word' => 'Акрофобия', 'answer' => 'неконтролируемый иррациональный страх высоты.', 'category_id' => '1']); WordCard::create(['word' => 'Эфебифобия', 'answer' => 'психологическая и социальная боязнь молодежи.', 'category_id' => '1']); WordCard::create(['word' => 'Ксенофобия', 'answer' => 'страх или неуважение по отношению к иностранцам или незнакомым людям.', 'category_id' => '1']); WordCard::create(['word' => 'Акрибофо́бия', 'answer' => 'навязчивый страх не понять смысл прочитанного.', 'category_id' => '1']); WordCard::create(['word' => 'Персо́на нон гра́та', 'answer' => 'дипломатический термин, который используют для обозначения лица, чье назначение в качестве дипломатического представителя в какую-либо страну не одобрено этой страной.', 'category_id' => '1']); WordCard::create(['word' => 'Ке́йтеринг', 'answer' => 'оорганизация ресторанного обслуживания на выезде; доставка блюд на мероприятие, в офис, в загородный дом и т.д', 'category_id' => '1']); WordCard::create(['word' => 'Каптча', 'answer' => 'каптча или капча – это специальный механизм, с помощью которого сайт отличает людей от компьютеров (спам-роботов, ботов и т.д.).', 'category_id' => '1']); WordCard::create(['word' => 'Марципа́н', 'answer' => 'это приготовленная из тертого миндаля и сахарной пудры/сахарного сиропа густая смесь, похожая на тесто.', 'category_id' => '1']); WordCard::create(['word' => 'ЮНЕСКО', 'answer' => 'крупная международная организация, которая занимается вопросами образования, науки и культуры во всем мире, призвана поддерживать всеобщее уважение прав и свобод человека, согласно Уставу ООН.', 'category_id' => '1']); WordCard::create(['word' => 'Пра́ймериз', 'answer' => 'предварительные выборы, предвыборы кандидата от одной партии.', 'category_id' => '1']); WordCard::create(['word' => 'Ли́зинг', 'answer' => 'комплекс имущественных и экономических отношений, возникающих в связи с приобретением в собственность имущества и последующей сдачей его во временное пользование за определенную плату.', 'category_id' => '1']); }
public function create_word($word, $category_id) { $validator = Validator::make(array('category_id' => Input::get('category_id')), array('word' => 'alpha_spaces', 'answer' => 'alpha_spaces', 'category_id' => 'numeric')); if ($validator->fails()) { return $this->respondInsufficientPrivileges($validator->messages()->all()); } $newWord = WordCard::create(array('word' => $word->word, 'answer' => $word->answer, 'category_id' => $category_id)); $category = Category::find($category_id); $category->update_amount(); $category->save(); if ($newWord) { return true; } return false; }
public function start($user_id) { $offset = Input::has('page') ? Input::get('page') : 0; $user = User::find($user_id); if (!$user) { return $this->respondNotFound('User not found'); } $balance = $user->balance; if (Input::get('category') == 0) { $s = Setting::first(); if ($balance < $s->general_cost) { return $this->respondInsufficientPrivileges('Not enough money'); } if ($offset == 0) { $user->balance = $user->balance - $s->general_cost; } // $words = WordCard::take(20)->skip($offset * 20)->get()->toArray(); $testWords = DB::table('test_word_cards')->where('category_id', 0)->where('user_id', $user->id)->get(); $transformedTestWords = array_map(function ($testWord) { return ['id' => $testWord->id, 'user_id' => $testWord->user_id, 'word_id' => $testWord->word_id, 'category_id' => $testWord->category_id]; }, $testWords); $words = WordCard::getRandomCards($transformedTestWords, 20); if (count($words) == 0) { DB::table('test_word_cards')->where('category_id', 0)->where('user_id', $user->id)->delete(); } foreach ($words as $word) { $wordsToModel[$word['id']] = ['category_id' => 0]; } } else { $category = Category::find(Input::get('category')); if (!$category) { return $this->respondNotFound('Category not found'); } if ($category->wordcards->count() <= 20) { return $this->respond(['status' => 'started', 'balance' => $user->balance, 'words' => []]); } if ($balance < $category->test_price) { return $this->respondInsufficientPrivileges('Not enough money'); } // Begin compiling cards $testWords = DB::table('test_word_cards')->where('category_id', $category->id)->where('user_id', $user->id)->get(); $transformedTestWords = array_map(function ($testWord) { return ['id' => $testWord->id, 'user_id' => $testWord->user_id, 'word_id' => $testWord->word_id, 'category_id' => $testWord->category_id]; }, $testWords); $words = WordCard::getRandomCards($transformedTestWords, 20, $category); // We got less than 5 if (count($words) <= 5 && $offset == 0) { // remove from history DB::table('test_word_cards')->where('category_id', $category->id)->where('user_id', $user->id)->delete(); $secondIterationWords = WordCard::getRandomCards([], 20 - count($words), $category); $words = array_merge($words, $secondIterationWords); $words = array_values($words); } elseif (count($words) == 0 && $offset != 0) { DB::table('test_word_cards')->where('category_id', $category->id)->where('user_id', $user->id)->delete(); } foreach ($words as $word) { $wordsToModel[$word['id']] = ['category_id' => $category->id]; } if ($offset == 0 && count($words) > 5) { $user->balance = $user->balance - $category->test_price; } } if (isset($wordsToModel)) { $user->testWords()->attach($wordsToModel); } $user->save(); shuffle($words); $response['status'] = 'started'; $response['count'] = count($words); $response['balance'] = $user->balance; $response['words'] = $this->transformWordsCollection($words); return $this->respond($response); }
public function pushWord($word) { $word = WordCard::find($word['word_id']); DB::table('users')->where('word_id', 0)->update(['word_id' => Setting::first()->word_id]); User::where('device', '<>', '')->groupBy('device')->chunk(200, function ($users) use($word) { $devices = PushNotification::DeviceCollection($users->map(function ($user) { $this->line($user->device); return PushNotification::Device($user->device, ['badge' => 1]); })->toArray()); // foreach ($users as $user) { // $rawdevices[] = PushNotification::Device($user->device, ['badge' => 1]); // } // $devices = PushNotification::DeviceCollection($rawdevices); $this->line('Sending chunk of 200...'); try { PushNotification::app('IOS')->to($devices)->send($word->word . " - новое слово для изучения", ["custom" => ["cdata" => [["word_id" => $word->id, "cat_id" => $word->category_id]], "type" => 0]]); } catch (Exception $e) { $this->error($e); } }); $this->info('Dayword ' . $word->word . '(' . $word->id . ') category ' . $word->category_id . ' pushed.'); }
/** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { $wordCard = WordCard::find($id); $category = Category::find($wordCard->category_id); if ($wordCard->delete()) { $category->update_amount(); $category->save(); return $this->respondNoContent(); } return $this->respondServerError(); }